labs-claude 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,60 @@
1
+ # labs-claude
2
+
3
+ Run the **real Claude Code CLI** on **ElevenLabs models**: GPT-6 Astra, GPT-6.1 Sol, GPT-5.6 Terra, Claude Opus 5.5, Gemini 3.8 Flash, GLM-52 and more, using your own ElevenLabs credits. It works the way Ollama does: Claude Code stays original (tools, skills, subagents, `/model`, `/resume`, permissions) and only the model behind it changes.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install -g labs-claude
9
+ labs setup
10
+ labs
11
+ ```
12
+
13
+ Works on **Windows, macOS and Linux**. You need:
14
+
15
+ - **Node.js 18+**
16
+ - **Claude Code** installed (`claude --version` should work)
17
+ - An **ElevenLabs API key** with ElevenAgents access (elevenlabs.io → Developers → API Keys)
18
+
19
+ `labs setup` checks your key and creates one agent in **your** ElevenLabs account named *Labs Claude Code Bridge*. The key is saved in `~/.labs/config.json`, readable only by you. If `ELEVENLABS_API_KEY` is set in your environment instead, the key is used from there and never written to disk.
20
+
21
+ ## Use
22
+
23
+ | Command | What it does |
24
+ |---|---|
25
+ | `labs` | Claude Code on the default model (astra) |
26
+ | `labs --model opus` | Pick a model by short name |
27
+ | `labs --model 5` | Pick by its number in `labs models` |
28
+ | `labs --model gpt-5.4` | Any ElevenLabs LLM id |
29
+ | `labs -p "fix the failing test"` | Any Claude Code flag passes through |
30
+ | `labs --effort high` | Reasoning effort (default: `max`, lowered automatically if a model is too slow) |
31
+ | `labs models` / `labs models --all` | List models with context and reply sizes |
32
+ | `labs usage` | Credits left, and what recent sessions cost per model (tokens and USD) |
33
+ | `labs stop` | Stop the background proxy |
34
+
35
+ Inside Claude Code, `/model terra` or `/model gpt-6-luna` switches model, and `/effort` changes effort. Claude's own names map to the same models on ElevenLabs (`opus` → `claude-opus-5-5`).
36
+
37
+ ## How it works
38
+
39
+ ```
40
+ Claude Code ──HTTP (Anthropic API)──> labs proxy on 127.0.0.1:8081 ──WebSocket──> ElevenLabs agent ──> chosen LLM
41
+ ```
42
+
43
+ - The proxy forwards Claude Code's real system prompt and its real tools. Each tool is mirrored once into your ElevenLabs account as a client tool.
44
+ - When the model calls a tool, Claude Code runs it on your machine, with its usual permission prompts.
45
+ - Every conversation runs in text-only mode, so no audio is generated.
46
+
47
+ ## Limits to know
48
+
49
+ - **Context windows are ElevenLabs' limits:** Astra, Sol and Terra have 272k; Opus 5.5, Sonnet 5.5 and Gemini 3.8 Flash have 1M; GLM, Qwen and DeepSeek have 64k context with 4k replies.
50
+ - **15-second first-token limit:** ElevenLabs drops a reply whose first token takes longer than 15 s. At very high effort, labs steps the effort down automatically.
51
+ - **120-second tool limit:** ElevenLabs waits at most 120 s for a tool result. A command that runs longer can fail that turn.
52
+ - **Usage is billed to your ElevenLabs account.** Check it at elevenlabs.io → Usage.
53
+
54
+ ## Files
55
+
56
+ `~/.labs/`: `config.json`, `proxy.log`, `llm-list.json`, `tool-registry-<agent>.json`, `conversations/`
57
+
58
+ ## License
59
+
60
+ MIT
package/bin/labs.js ADDED
@@ -0,0 +1,114 @@
1
+ #!/usr/bin/env node
2
+ const { spawn } = require('child_process');
3
+ const { randomUUID } = require('crypto');
4
+ const { CONFIG_PATH, loadConfig, loadLlmList } = require('../src/config');
5
+ const { ensureProxy, stopProxy } = require('../src/proxy-manager');
6
+ const { parseLaunchArgs, withLabsHeaders } = require('../src/launch-args');
7
+ const { runSetup } = require('../src/setup');
8
+ const { printUsage } = require('../src/usage');
9
+ const { version } = require('../package.json');
10
+
11
+ const HELP = `labs ${version} — Claude Code running on ElevenLabs models
12
+
13
+ labs open Claude Code on the default model (astra)
14
+ labs --model opus pick a model by name, number (labs --model 5) or raw ElevenLabs id
15
+ labs -p "question" any Claude Code flag works, e.g. -p, --resume, --permission-mode
16
+ labs models [--all] list models
17
+ labs usage credits left and what recent sessions cost per model
18
+ labs setup set your ElevenLabs API key and create the bridge agent
19
+ labs stop stop the background proxy
20
+
21
+ Inside Claude Code: /model <name> switches model, e.g. /model gpt-5.6-terra`;
22
+
23
+ function printModels(config, showAll) {
24
+ const llms = loadLlmList();
25
+ const byId = Object.fromEntries(llms.map(item => [item.llm, item]));
26
+ const size = (n) => n >= 1000000 ? `${Math.round(n / 100000) / 10}M` : `${Math.round(n / 1000)}k`;
27
+ console.log('\n🚀 Labs models (labs --model <name or number>)\n');
28
+ Object.entries(config.models).forEach(([name, llm], index) => {
29
+ const info = byId[llm];
30
+ const detail = info ? `${size(info.max_context_limit).padStart(5)} context ${size(info.max_tokens_limit).padStart(5)} reply` : 'not offered on your account';
31
+ const marker = name === config.defaultModel ? ' ← default' : '';
32
+ console.log(`${String(index + 1).padStart(3)}. ${name.padEnd(11)} ${llm.padEnd(24)} ${detail}${marker}`);
33
+ });
34
+ const current = llms.filter(item => !item.deprecation_info && !item.is_checkpoint);
35
+ if (showAll) {
36
+ console.log(`\nAll ${current.length} current ElevenLabs LLMs (use the id with --model):\n`);
37
+ current.forEach(item => console.log(` ${item.llm.padEnd(32)} ${size(item.max_context_limit).padStart(5)} context ${size(item.max_tokens_limit).padStart(5)} reply`));
38
+ } else {
39
+ console.log(`\n${current.length} current ElevenLabs LLMs in total: labs models --all`);
40
+ }
41
+ console.log('Inside Claude Code: /model <name> switches model.\n');
42
+ }
43
+
44
+ function launchClaude(claudeArgs, env) {
45
+ // The native installer ships claude.exe; an npm-installed Claude Code on Windows is a .cmd shim that needs a shell.
46
+ const command = process.platform === 'win32' ? 'claude.exe' : 'claude';
47
+ const child = spawn(command, claudeArgs, { stdio: 'inherit', env });
48
+ child.on('error', error => {
49
+ if (error.code !== 'ENOENT' || process.platform !== 'win32') {
50
+ console.error(`❌ Could not start Claude Code: ${error.message}`);
51
+ process.exit(1);
52
+ }
53
+ const quoted = claudeArgs.map(arg => `"${arg.replace(/"/g, '\\"')}"`).join(' ');
54
+ spawn(`claude ${quoted}`, { stdio: 'inherit', env, shell: true }).on('exit', code => process.exit(code ?? 1));
55
+ });
56
+ child.on('exit', code => process.exit(code ?? 0));
57
+ }
58
+
59
+ async function main() {
60
+ const args = process.argv.slice(2);
61
+ if (args[0] === 'setup') return runSetup();
62
+ if (args[0] === '--help' || args[0] === 'help') return console.log(HELP);
63
+ if (args[0] === '--version') return console.log(version);
64
+
65
+ let config = loadConfig();
66
+ if (!config?.apiKey || !config.bridgeAgent) {
67
+ console.log(`No setup found at ${CONFIG_PATH}, running setup first.\n`);
68
+ await runSetup();
69
+ config = loadConfig();
70
+ }
71
+
72
+ if (args[0] === 'models') return printModels(config, args.includes('--all'));
73
+ if (args[0] === 'usage') return printUsage(config);
74
+ if (args[0] === 'stop') return console.log(await stopProxy(config.port) ? '🛑 Proxy stopped' : 'Proxy was not running');
75
+
76
+ const { modelName, claudeArgs } = parseLaunchArgs(args, {
77
+ aliases: config.models,
78
+ llmIds: new Set(loadLlmList().map(item => item.llm)),
79
+ defaultModel: config.defaultModel
80
+ });
81
+
82
+ if (!(await ensureProxy(config.port))) {
83
+ console.error('❌ The labs proxy did not start. See ~/.labs/proxy.log');
84
+ process.exit(1);
85
+ }
86
+
87
+ const llm = config.models[modelName] || modelName;
88
+ const llmInfo = loadLlmList().find(item => item.llm === llm);
89
+ if (!claudeArgs.some(arg => arg === '--effort' || arg.startsWith('--effort='))) {
90
+ claudeArgs.push('--effort', config.defaultEffort || 'max');
91
+ }
92
+
93
+ const env = {
94
+ ...process.env,
95
+ // Claude Code only knows Anthropic windows; without this it assumes 200k and compacts at the wrong point.
96
+ ...(llmInfo ? { CLAUDE_CODE_MAX_CONTEXT_TOKENS: String(llmInfo.max_context_limit) } : {}),
97
+ ANTHROPIC_BASE_URL: `http://127.0.0.1:${config.port}`,
98
+ ANTHROPIC_AUTH_TOKEN: 'labs-local',
99
+ ANTHROPIC_CUSTOM_HEADERS: withLabsHeaders(process.env.ANTHROPIC_CUSTOM_HEADERS, randomUUID(), modelName),
100
+ // Subagents run on the chosen model too; the proxy answers overload with 529 so Claude Code retries, never switches.
101
+ CLAUDE_CODE_SUBAGENT_MODEL: modelName
102
+ };
103
+ // A leftover key (e.g. from an Ollama setup) would take precedence over the proxy's auth token.
104
+ delete env.ANTHROPIC_API_KEY;
105
+
106
+ const window = llmInfo ? `, ${Math.round(llmInfo.max_context_limit / 1000)}k context` : '';
107
+ console.log(`🚀 Claude Code on ElevenLabs ${modelName} (${llm}${window})`);
108
+ launchClaude(claudeArgs, env);
109
+ }
110
+
111
+ main().catch(error => {
112
+ console.error(`❌ ${error.message}`);
113
+ process.exit(1);
114
+ });
package/package.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "labs-claude",
3
+ "version": "0.1.0",
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"],
10
+ "license": "MIT",
11
+ "dependencies": {
12
+ "axios": "^1.20.0",
13
+ "body-parser": "^2.3.0",
14
+ "express": "^5.2.1",
15
+ "ws": "^8.22.0"
16
+ }
17
+ }
@@ -0,0 +1,207 @@
1
+ const { createHash, randomUUID } = require('crypto');
2
+
3
+ const modelDisplayNames = {
4
+ astra: 'GPT-6 Astra',
5
+ opus: 'Opus 5.5',
6
+ glm: 'GLM-52',
7
+ sol: 'GPT-6 Sol',
8
+ qwen: 'Qwen3-6 35B',
9
+ oss: 'GPT-OSS-120B',
10
+ gemini: 'Gemini 3.8 Flash'
11
+ };
12
+
13
+ function contentToText(content) {
14
+ if (typeof content === 'string') return content;
15
+ if (!Array.isArray(content)) return '';
16
+
17
+ return content.map(block => {
18
+ if (block.type === 'text' || block.type === 'input_text') return block.text || '';
19
+ if (block.type === 'tool_use') return `Tool call ${block.name}: ${JSON.stringify(block.input || {})}`;
20
+ if (block.type === 'tool_result') {
21
+ const resultText = contentToText(block.content);
22
+ const errorPrefix = block.is_error ? 'Tool error' : 'Tool result';
23
+ return `${errorPrefix} (${block.tool_use_id || 'unknown'}):\n${resultText}`;
24
+ }
25
+ return '';
26
+ }).filter(Boolean).join('\n\n');
27
+ }
28
+
29
+ function extractLatestUserContent(messages) {
30
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
31
+ const message = messages[index];
32
+ if (message.role !== 'user') continue;
33
+
34
+ const blocks = Array.isArray(message.content) ? message.content : [];
35
+ const toolResults = blocks
36
+ .filter(block => block.type === 'tool_result')
37
+ .map(block => ({
38
+ toolUseId: block.tool_use_id,
39
+ content: contentToText(block.content),
40
+ isError: Boolean(block.is_error)
41
+ }));
42
+ const text = Array.isArray(message.content)
43
+ ? blocks
44
+ .filter(block => block.type === 'text' || block.type === 'input_text')
45
+ .map(block => block.text || '')
46
+ .join('\n\n')
47
+ : contentToText(message.content);
48
+
49
+ return {
50
+ text: text.trim(),
51
+ toolResults
52
+ };
53
+ }
54
+
55
+ return { text: '', toolResults: [] };
56
+ }
57
+
58
+ function createAnthropicMessage({ model, text = '', toolCalls = [], inputTokens = 0 }) {
59
+ const toolBlocks = toolCalls.map(tool => ({
60
+ type: 'tool_use',
61
+ id: tool.id,
62
+ name: tool.name,
63
+ input: tool.input || {}
64
+ }));
65
+ const content = [
66
+ ...(text || toolBlocks.length === 0 ? [{ type: 'text', text }] : []),
67
+ ...toolBlocks
68
+ ];
69
+ const outputText = text + (toolBlocks.length ? JSON.stringify(toolBlocks) : '');
70
+
71
+ return {
72
+ id: `msg_${randomUUID()}`,
73
+ type: 'message',
74
+ role: 'assistant',
75
+ content,
76
+ model,
77
+ stop_reason: toolCalls.length > 0 ? 'tool_use' : 'end_turn',
78
+ stop_sequence: null,
79
+ usage: {
80
+ input_tokens: inputTokens,
81
+ output_tokens: Math.ceil(outputText.length / 4)
82
+ }
83
+ };
84
+ }
85
+
86
+ function isValidSessionId(sessionId) {
87
+ return typeof sessionId === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(sessionId);
88
+ }
89
+
90
+ function createSessionKey(agentId, sessionId) {
91
+ return `${encodeURIComponent(agentId)}:${sessionId}`;
92
+ }
93
+
94
+ // The main thread and each subagent share one Claude Code session id but start from different first messages.
95
+ function createThreadId(sessionId, messages) {
96
+ const opening = contentToText(messages[0]?.content).slice(0, 4000);
97
+ return `${sessionId}_${createHash('sha1').update(opening).digest('hex').slice(0, 10)}`;
98
+ }
99
+
100
+ // Like Ollama: Claude Code's own model ids, Labs aliases and raw ElevenLabs LLM ids all resolve to an ElevenLabs LLM.
101
+ function resolveLlm(requestedModel, launchModel, aliases, llmIds) {
102
+ const direct = name => {
103
+ if (!name) return null;
104
+ const clean = name.replace(/\[1m\]$/i, '');
105
+ if (aliases[clean]) return aliases[clean];
106
+ if (llmIds.has(clean)) return clean;
107
+ const undated = clean.replace(/-\d{8}$/, '');
108
+ if (llmIds.has(undated)) return undated;
109
+ return null;
110
+ };
111
+ const claudeFamily = name => {
112
+ const family = /^claude-(opus|sonnet|haiku)/.exec(name || '')?.[1];
113
+ return family ? aliases[family] || null : null;
114
+ };
115
+ return direct(requestedModel) || claudeFamily(requestedModel) || direct(launchModel) || null;
116
+ }
117
+
118
+ function createModelCatalog(models) {
119
+ return Object.keys(models).map(id => ({
120
+ id,
121
+ name: modelDisplayNames[id] || id
122
+ }));
123
+ }
124
+
125
+ function formatConversationHistory(history) {
126
+ return history
127
+ .filter(message => message.role === 'user' || message.role === 'assistant')
128
+ .map(message => `${message.role === 'user' ? 'User' : 'Assistant'}: ${contentToText(message.content)}`)
129
+ .filter(message => !message.endsWith(': '))
130
+ .join('\n');
131
+ }
132
+
133
+ function createAnthropicEvents(message) {
134
+ const events = [];
135
+ const emit = (event, data) => events.push({ event, data });
136
+ const { content, usage, ...messageStart } = message;
137
+
138
+ emit('message_start', {
139
+ type: 'message_start',
140
+ message: {
141
+ ...messageStart,
142
+ content: [],
143
+ stop_reason: null,
144
+ stop_sequence: null,
145
+ usage: { input_tokens: usage.input_tokens, output_tokens: 0 }
146
+ }
147
+ });
148
+
149
+ content.forEach((block, index) => {
150
+ if (block.type === 'text') {
151
+ emit('content_block_start', {
152
+ type: 'content_block_start', index,
153
+ content_block: { type: 'text', text: '' }
154
+ });
155
+ if (block.text) {
156
+ emit('content_block_delta', {
157
+ type: 'content_block_delta', index,
158
+ delta: { type: 'text_delta', text: block.text }
159
+ });
160
+ }
161
+ } else if (block.type === 'tool_use') {
162
+ emit('content_block_start', {
163
+ type: 'content_block_start', index,
164
+ content_block: { type: 'tool_use', id: block.id, name: block.name, input: {} }
165
+ });
166
+ emit('content_block_delta', {
167
+ type: 'content_block_delta', index,
168
+ delta: { type: 'input_json_delta', partial_json: JSON.stringify(block.input) }
169
+ });
170
+ }
171
+ emit('content_block_stop', { type: 'content_block_stop', index });
172
+ });
173
+
174
+ emit('message_delta', {
175
+ type: 'message_delta',
176
+ delta: { stop_reason: message.stop_reason, stop_sequence: null },
177
+ usage: { output_tokens: usage.output_tokens }
178
+ });
179
+ emit('message_stop', { type: 'message_stop' });
180
+ return events;
181
+ }
182
+
183
+ function writeAnthropicEvents(response, events) {
184
+ response.status(200);
185
+ response.set({
186
+ 'Content-Type': 'text/event-stream; charset=utf-8',
187
+ 'Cache-Control': 'no-cache',
188
+ Connection: 'keep-alive'
189
+ });
190
+ for (const { event, data } of events) {
191
+ response.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
192
+ }
193
+ response.end();
194
+ }
195
+
196
+ module.exports = {
197
+ createAnthropicEvents,
198
+ createAnthropicMessage,
199
+ createModelCatalog,
200
+ createSessionKey,
201
+ createThreadId,
202
+ extractLatestUserContent,
203
+ formatConversationHistory,
204
+ isValidSessionId,
205
+ resolveLlm,
206
+ writeAnthropicEvents
207
+ };
package/src/config.js ADDED
@@ -0,0 +1,53 @@
1
+ const fs = require('fs');
2
+ const os = require('os');
3
+ const path = require('path');
4
+
5
+ const LABS_DIR = process.env.LABS_HOME || path.join(os.homedir(), '.labs');
6
+ const CONFIG_PATH = path.join(LABS_DIR, 'config.json');
7
+ const LLM_LIST_PATH = path.join(LABS_DIR, 'llm-list.json');
8
+ const DEFAULT_PORT = 8081;
9
+ const API_BASE = 'https://api.elevenlabs.io/v1/convai';
10
+
11
+ // Short names for the strongest current ElevenLabs LLMs; any raw ElevenLabs LLM id also works.
12
+ const DEFAULT_MODELS = {
13
+ astra: 'gpt-6-astra',
14
+ sol: 'gpt-6.1-sol',
15
+ terra: 'gpt-5.6-terra',
16
+ luna: 'gpt-6-luna',
17
+ opus: 'claude-opus-5-5',
18
+ sonnet: 'claude-sonnet-5-5',
19
+ haiku: 'claude-haiku-4-5',
20
+ gemini: 'gemini-3.8-flash',
21
+ 'gemini-pro': 'gemini-3.1-pro-preview',
22
+ glm: 'glm-52',
23
+ qwen: 'qwen35-397b-a17b',
24
+ deepseek: 'deepseek-v41-flash'
25
+ };
26
+
27
+ function loadConfig() {
28
+ if (!fs.existsSync(CONFIG_PATH)) return null;
29
+ const stored = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
30
+ return {
31
+ port: DEFAULT_PORT,
32
+ defaultModel: 'astra',
33
+ ...stored,
34
+ models: { ...DEFAULT_MODELS, ...(stored.models || {}) },
35
+ apiKey: process.env.ELEVENLABS_API_KEY || stored.apiKey
36
+ };
37
+ }
38
+
39
+ function saveConfig(config) {
40
+ fs.mkdirSync(LABS_DIR, { recursive: true });
41
+ fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), { mode: 0o600 });
42
+ }
43
+
44
+ function loadLlmList() {
45
+ return fs.existsSync(LLM_LIST_PATH) ? JSON.parse(fs.readFileSync(LLM_LIST_PATH, 'utf8')) : [];
46
+ }
47
+
48
+ function saveLlmList(llms) {
49
+ fs.mkdirSync(LABS_DIR, { recursive: true });
50
+ fs.writeFileSync(LLM_LIST_PATH, JSON.stringify(llms, null, 1));
51
+ }
52
+
53
+ module.exports = { API_BASE, CONFIG_PATH, DEFAULT_MODELS, LABS_DIR, loadConfig, loadLlmList, saveConfig, saveLlmList };
@@ -0,0 +1,132 @@
1
+ const { createHash } = require('crypto');
2
+ const fs = require('fs');
3
+
4
+ const MAX_DESCRIPTION = 3000;
5
+ const MAX_NAME = 64;
6
+ const MAX_TIMEOUT_SECS = 120;
7
+
8
+ // ElevenLabs client-tool parameters accept a plain JSON-Schema subset; Claude Code tools use the full dialect.
9
+ function toElevenLabsSchema(schema, fallbackDescription) {
10
+ const node = pickBranch(schema || {});
11
+ const type = normaliseType(node);
12
+ const out = { type, description: (node.description || fallbackDescription || 'value').slice(0, MAX_DESCRIPTION) };
13
+
14
+ if (node.const !== undefined) out.enum = [node.const];
15
+ else if (Array.isArray(node.enum)) out.enum = node.enum;
16
+
17
+ if (type === 'object') {
18
+ out.properties = {};
19
+ for (const [key, child] of Object.entries(node.properties || {})) {
20
+ out.properties[key] = toElevenLabsSchema(child, key);
21
+ }
22
+ const required = (node.required || []).filter(key => key in out.properties);
23
+ if (required.length) out.required = required;
24
+ }
25
+ if (type === 'array') out.items = toElevenLabsSchema(node.items || { type: 'string' }, 'item');
26
+ return out;
27
+ }
28
+
29
+ function pickBranch(node) {
30
+ const branches = node.anyOf || node.oneOf || node.allOf;
31
+ if (!branches) return node;
32
+ const usable = branches.find(branch => branch.type && branch.type !== 'null') || branches[0] || {};
33
+ return pickBranch({ description: node.description, ...usable });
34
+ }
35
+
36
+ function normaliseType(node) {
37
+ const type = Array.isArray(node.type) ? node.type.find(t => t !== 'null') : node.type;
38
+ if (['string', 'number', 'integer', 'boolean', 'array', 'object'].includes(type)) return type;
39
+ if (node.properties) return 'object';
40
+ if (node.items) return 'array';
41
+ return 'string';
42
+ }
43
+
44
+ // ElevenLabs tool names must match ^[a-zA-Z0-9_-]{1,64}$; long MCP names get a stable hashed alias.
45
+ function toElevenLabsName(name) {
46
+ const safe = name.replace(/[^a-zA-Z0-9_-]/g, '_');
47
+ if (safe.length <= MAX_NAME) return safe;
48
+ return `${safe.slice(0, MAX_NAME - 11)}_${createHash('sha1').update(name).digest('hex').slice(0, 10)}`;
49
+ }
50
+
51
+ function toToolConfig(tool) {
52
+ return {
53
+ type: 'client',
54
+ name: toElevenLabsName(tool.name),
55
+ description: (tool.description || tool.name).slice(0, MAX_DESCRIPTION),
56
+ expects_response: true,
57
+ response_timeout_secs: MAX_TIMEOUT_SECS,
58
+ parameters: toElevenLabsSchema(tool.input_schema || { type: 'object' }, tool.name)
59
+ };
60
+ }
61
+
62
+ function toolFingerprint(tool) {
63
+ return createHash('sha1').update(JSON.stringify([tool.name, tool.description, tool.input_schema])).digest('hex');
64
+ }
65
+
66
+ // Mirrors Claude Code's tools onto ElevenLabs: one client tool per name, updated in place when Claude Code changes
67
+ // a description or schema (they vary between sessions), so the account never fills up with copies.
68
+ class ToolRegistry {
69
+ constructor({ http, apiBase, headers, file, agentId }) {
70
+ this.http = http;
71
+ this.apiBase = apiBase;
72
+ this.headers = headers;
73
+ this.file = file;
74
+ this.agentId = agentId;
75
+ const stored = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
76
+ // Older registries were keyed by fingerprint; keep the newest id per tool name.
77
+ this.entries = {};
78
+ for (const entry of Object.values(stored)) {
79
+ if (entry?.id) this.entries[entry.name] = { fingerprint: null, ...entry };
80
+ }
81
+ this.queue = Promise.resolve();
82
+ }
83
+
84
+ ensure(tools) {
85
+ const run = () => this.ensureNow(tools);
86
+ this.queue = this.queue.then(run, run);
87
+ return this.queue;
88
+ }
89
+
90
+ async ensureNow(tools) {
91
+ const usable = tools.filter(tool => tool.name && tool.input_schema);
92
+ let changed = false;
93
+ for (const tool of usable) {
94
+ const fingerprint = toolFingerprint(tool);
95
+ const entry = this.entries[tool.name];
96
+ if (entry?.fingerprint === fingerprint) continue;
97
+ try {
98
+ if (entry) {
99
+ await this.http.patch(`${this.apiBase}/tools/${entry.id}`, { tool_config: toToolConfig(tool) }, { headers: this.headers });
100
+ entry.fingerprint = fingerprint;
101
+ } else {
102
+ const response = await this.http.post(`${this.apiBase}/tools`, { tool_config: toToolConfig(tool) }, { headers: this.headers });
103
+ this.entries[tool.name] = { name: tool.name, alias: toElevenLabsName(tool.name), id: response.data.id, fingerprint };
104
+ console.log(`🧩 Mirrored tool ${tool.name} -> ${response.data.id}`);
105
+ }
106
+ changed = true;
107
+ } catch (error) {
108
+ console.error(`⚠️ Could not mirror tool ${tool.name}: ${JSON.stringify(error.response?.data || error.message).slice(0, 300)}`);
109
+ }
110
+ }
111
+ if (changed) {
112
+ await this.attachAll();
113
+ fs.writeFileSync(this.file, JSON.stringify(this.entries, null, 1));
114
+ }
115
+ return usable.map(tool => this.entries[tool.name]?.id).filter(Boolean);
116
+ }
117
+
118
+ claudeNameFor(alias) {
119
+ const entry = Object.values(this.entries).find(item => item.alias === alias);
120
+ return entry ? entry.name : alias;
121
+ }
122
+
123
+ // Per-conversation tool_ids overrides may only name tools already attached to the agent.
124
+ async attachAll() {
125
+ const ids = [...new Set(Object.values(this.entries).map(entry => entry.id).filter(Boolean))];
126
+ await this.http.patch(`${this.apiBase}/agents/${this.agentId}`,
127
+ { conversation_config: { agent: { prompt: { tool_ids: ids } } } },
128
+ { headers: this.headers });
129
+ }
130
+ }
131
+
132
+ module.exports = { ToolRegistry, toElevenLabsName, toElevenLabsSchema, toToolConfig };
@@ -0,0 +1,35 @@
1
+ // Splits `labs` arguments into the Labs model choice and everything that goes to Claude Code untouched.
2
+ function parseLaunchArgs(args, { aliases, llmIds, defaultModel }) {
3
+ const aliasNames = Object.keys(aliases);
4
+ let modelName = defaultModel;
5
+ const claudeArgs = [];
6
+
7
+ for (let index = 0; index < args.length; index += 1) {
8
+ const arg = args[index];
9
+ const inline = arg.startsWith('--model=') ? arg.slice('--model='.length) : null;
10
+ if (arg !== '--model' && inline === null) {
11
+ claudeArgs.push(arg);
12
+ continue;
13
+ }
14
+ const value = inline ?? args[++index];
15
+ if (!value) throw new Error('--model requires a value');
16
+ modelName = /^\d+$/.test(value) && aliasNames[Number(value) - 1] ? aliasNames[Number(value) - 1] : value;
17
+ }
18
+
19
+ if (!aliases[modelName] && !llmIds.has(modelName)) {
20
+ throw new Error(`Unknown model "${modelName}". Run "labs models --all" to list models.`);
21
+ }
22
+ return { modelName, claudeArgs: [...claudeArgs, '--model', modelName] };
23
+ }
24
+
25
+ function withLabsHeaders(headers, sessionId, modelName) {
26
+ const lines = String(headers || '')
27
+ .split(/\r?\n/)
28
+ .filter(line => line.trim()
29
+ && !/^\s*x-labs-session-id\s*:/i.test(line)
30
+ && !/^\s*x-labs-model\s*:/i.test(line));
31
+ lines.push(`X-Labs-Session-Id: ${sessionId}`, `X-Labs-Model: ${modelName}`);
32
+ return lines.join('\n');
33
+ }
34
+
35
+ module.exports = { parseLaunchArgs, withLabsHeaders };
@@ -0,0 +1,45 @@
1
+ const axios = require('axios');
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const { spawn } = require('child_process');
5
+ const { LABS_DIR } = require('./config');
6
+ const { version: VERSION } = require('../package.json');
7
+
8
+ async function health(port) {
9
+ try {
10
+ return (await axios.get(`http://127.0.0.1:${port}/health`, { timeout: 1000 })).data;
11
+ } catch {
12
+ return null;
13
+ }
14
+ }
15
+
16
+ // Reuses a running proxy of the same version; an older version (after `npm update -g`) is stopped and replaced.
17
+ async function ensureProxy(port) {
18
+ const running = await health(port);
19
+ if (running?.name === 'labs-claude' && running.version === VERSION) return true;
20
+ if (running?.name === 'labs-claude') {
21
+ await axios.post(`http://127.0.0.1:${port}/shutdown`).catch(() => {});
22
+ await new Promise(resolve => setTimeout(resolve, 500));
23
+ }
24
+
25
+ fs.mkdirSync(LABS_DIR, { recursive: true });
26
+ const log = fs.openSync(path.join(LABS_DIR, 'proxy.log'), 'a');
27
+ const child = spawn(process.execPath, [path.join(__dirname, 'proxy.js')], {
28
+ detached: true,
29
+ stdio: ['ignore', log, log],
30
+ windowsHide: true
31
+ });
32
+ child.unref();
33
+
34
+ for (let attempt = 0; attempt < 120; attempt += 1) {
35
+ if ((await health(port))?.version === VERSION) return true;
36
+ await new Promise(resolve => setTimeout(resolve, 250));
37
+ }
38
+ return false;
39
+ }
40
+
41
+ async function stopProxy(port) {
42
+ return axios.post(`http://127.0.0.1:${port}/shutdown`).then(() => true, () => false);
43
+ }
44
+
45
+ module.exports = { ensureProxy, stopProxy };
package/src/proxy.js ADDED
@@ -0,0 +1,438 @@
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
+ const toolRegistry = new ToolRegistry({
43
+ http: axios,
44
+ apiBase: API_BASE,
45
+ headers: HEADERS,
46
+ file: path.join(LABS_DIR, `tool-registry-${config.bridgeAgent}.json`),
47
+ agentId: config.bridgeAgent
48
+ });
49
+
50
+ async function refreshLlmList() {
51
+ try {
52
+ const response = await axios.get(`${API_BASE}/llm/list`, { headers: HEADERS });
53
+ saveLlmList(response.data.llms);
54
+ llmList = response.data.llms;
55
+ llmIds = new Set(llmList.map(item => item.llm));
56
+ console.log(`📋 ${llmIds.size} ElevenLabs LLMs available`);
57
+ } catch (error) {
58
+ console.error(`⚠️ Could not refresh LLM list, using cached copy: ${error.message}`);
59
+ }
60
+ }
61
+
62
+ // Effort and reply length are agent-level settings on ElevenLabs (not per-conversation overrides), so the bridge
63
+ // agent is re-pointed before each new conversation; the queue keeps concurrent opens from racing each other.
64
+ // ElevenLabs drops a turn whose first token takes longer than 15 s (cascade_timeout_seconds), which very high
65
+ // effort can exceed; the highest effort that answered in time is remembered per LLM for the proxy's lifetime.
66
+ const effortCaps = new Map();
67
+
68
+ function lowerEffortCap(llm, failedEffort) {
69
+ const efforts = (llmList.find(item => item.llm === llm)?.available_reasoning_efforts || [])
70
+ .filter(option => EFFORT_ORDER.indexOf(option) < EFFORT_ORDER.indexOf(failedEffort) && EFFORT_ORDER.indexOf(option) >= EFFORT_ORDER.indexOf('medium'));
71
+ if (!efforts.length) return false;
72
+ effortCaps.set(llm, efforts.reduce((best, option) => EFFORT_ORDER.indexOf(option) > EFFORT_ORDER.indexOf(best) ? option : best));
73
+ return true;
74
+ }
75
+
76
+ function agentSettingsFor(llm, requestedEffort, requestedMaxTokens) {
77
+ const info = llmList.find(item => item.llm === llm) || {};
78
+ const efforts = info.available_reasoning_efforts || [];
79
+ const cap = effortCaps.get(llm);
80
+ const capped = cap && EFFORT_ORDER.indexOf(requestedEffort) > EFFORT_ORDER.indexOf(cap) ? cap : requestedEffort;
81
+ const wanted = EFFORT_ORDER.indexOf(capped);
82
+ const effort = efforts.length
83
+ ? efforts.reduce((best, option) => Math.abs(EFFORT_ORDER.indexOf(option) - wanted) < Math.abs(EFFORT_ORDER.indexOf(best) - wanted) ? option : best)
84
+ : null;
85
+ // Always the model's full reply length: Claude Code's own max_tokens is sized for Anthropic models.
86
+ return { llm, reasoning_effort: effort, max_tokens: info.max_tokens_limit || requestedMaxTokens || 4096 };
87
+ }
88
+
89
+ let settingsQueue = Promise.resolve();
90
+ let appliedSettings = '';
91
+
92
+ function withAgentSettings(settings, openFn) {
93
+ const run = async () => {
94
+ const key = JSON.stringify(settings);
95
+ if (key !== appliedSettings) {
96
+ // An explicit null is required: an effort left over from the previous LLM makes ElevenLabs reject the switch.
97
+ const prompt = {
98
+ llm: settings.llm,
99
+ max_tokens: settings.max_tokens,
100
+ reasoning_effort: settings.reasoning_effort,
101
+ // Voice defaults: 4 s to first token, then silently fall back to another LLM. 15 s is ElevenLabs' maximum.
102
+ cascade_timeout_seconds: 15,
103
+ backup_llm_config: { preference: 'disabled' }
104
+ };
105
+ await axios.patch(`${API_BASE}/agents/${config.bridgeAgent}`, { conversation_config: { agent: { prompt } } }, { headers: HEADERS });
106
+ appliedSettings = key;
107
+ console.log(`🎚️ Bridge set to ${settings.llm} effort=${settings.reasoning_effort || 'n/a'} max_tokens=${settings.max_tokens}`);
108
+ }
109
+ const conn = openFn();
110
+ await conn.ready;
111
+ return conn;
112
+ };
113
+ const next = settingsQueue.then(run, run);
114
+ settingsQueue = next.catch(() => {});
115
+ return next;
116
+ }
117
+
118
+ // ============================================
119
+ // WEBSOCKET CONVERSATIONS: one per (LLM, Claude Code thread, tool set)
120
+ // ============================================
121
+
122
+ const connections = new Map();
123
+
124
+ function systemText(system) {
125
+ if (typeof system === 'string') return system;
126
+ return Array.isArray(system) ? system.map(block => block.text || '').join('\n\n') : '';
127
+ }
128
+
129
+ function openConversation(key, { llm, prompt, toolIds }) {
130
+ const existing = connections.get(key);
131
+ // A socket still CONNECTING must be awaited, not replaced: replacing it routed the old socket's events into the new one.
132
+ if (existing && [WebSocket.OPEN, WebSocket.CONNECTING].includes(existing.ws.readyState)) return existing;
133
+
134
+ console.log(`🔌 Opening ${llm} conversation (${toolIds.length} tools) for ${key}`);
135
+ const ws = new WebSocket(`wss://api.elevenlabs.io/v1/convai/conversation?agent_id=${config.bridgeAgent}`, { headers: HEADERS });
136
+ const conn = {
137
+ ws,
138
+ llm,
139
+ pending: null,
140
+ messageId: 0,
141
+ conversationId: null,
142
+ contextTokens: 0,
143
+ openToolCallIds: new Set(),
144
+ closeReason: ''
145
+ };
146
+ connections.set(key, conn);
147
+
148
+ conn.ready = new Promise((resolve, reject) => {
149
+ ws.on('open', () => {
150
+ ws.send(JSON.stringify({
151
+ type: 'conversation_initiation_client_data',
152
+ conversation_config_override: {
153
+ conversation: { text_only: true },
154
+ agent: { first_message: '', prompt: { prompt, llm, tool_ids: toolIds } }
155
+ }
156
+ }));
157
+ conn.markReady = resolve;
158
+ });
159
+ ws.on('error', error => {
160
+ console.error(`🚨 WS error for ${key}: ${error.message}`);
161
+ reject(error);
162
+ });
163
+ ws.on('close', (code, reason) => {
164
+ conn.closeReason = `code ${code}${reason?.length ? `: ${reason}` : ''}`;
165
+ console.log(`🔌 Conversation closed for ${key} (${conn.closeReason})`);
166
+ reject(new Error(`ElevenLabs closed the conversation (${conn.closeReason})`));
167
+ if (conn.pending) settle(conn, { error: new Error(`ElevenLabs closed the conversation (${conn.closeReason})`) });
168
+ connections.delete(key);
169
+ });
170
+ });
171
+ conn.ready.catch(() => {});
172
+
173
+ ws.on('message', data => {
174
+ try {
175
+ handleEvent(conn, JSON.parse(data.toString()));
176
+ } catch (error) {
177
+ console.error(`⚠️ WS event error: ${error.message}`);
178
+ }
179
+ });
180
+ return conn;
181
+ }
182
+
183
+ function handleEvent(conn, msg) {
184
+ switch (msg.type) {
185
+ case 'conversation_initiation_metadata':
186
+ conn.conversationId = msg.conversation_initiation_metadata_event?.conversation_id;
187
+ console.log(`📋 Conversation ${conn.conversationId} on ${conn.llm}`);
188
+ conn.markReady?.(conn);
189
+ break;
190
+ case 'ping':
191
+ // The server expects the ping's event_id echoed back; a bare pong lets the connection die.
192
+ conn.ws.send(JSON.stringify({ type: 'pong', event_id: msg.ping_event?.event_id }));
193
+ break;
194
+ case 'agent_response': {
195
+ if (!conn.pending) break;
196
+ const text = msg.agent_response_event?.agent_response || '';
197
+ conn.pending.text = conn.pending.text ? `${conn.pending.text}\n\n${text}` : text;
198
+ settleSoon(conn);
199
+ break;
200
+ }
201
+ case 'client_tool_call':
202
+ handleToolCall(conn, msg.client_tool_call);
203
+ break;
204
+ case 'context_usage':
205
+ conn.contextTokens = msg.context_usage_event?.context_tokens || conn.contextTokens;
206
+ break;
207
+ case 'client_error':
208
+ console.error(`🚨 ElevenLabs client_error: ${JSON.stringify(msg.error_event)}`);
209
+ break;
210
+ default:
211
+ break;
212
+ }
213
+ }
214
+
215
+ function handleToolCall(conn, call) {
216
+ if (!call?.tool_name || !call.tool_call_id) return;
217
+ if (!conn.pending) {
218
+ // Arrived after the turn was already returned; answering keeps the agent from waiting forever.
219
+ conn.ws.send(JSON.stringify({
220
+ type: 'client_tool_result', tool_call_id: call.tool_call_id, is_error: true,
221
+ result: 'This tool call arrived after the turn ended. Request it again in your next turn.'
222
+ }));
223
+ return;
224
+ }
225
+ const name = toolRegistry.claudeNameFor(call.tool_name);
226
+ if (call.parameters) call.parameters = withWindowsPaths(call.parameters);
227
+ console.log(`🔧 ${name} ${JSON.stringify(call.parameters || {}).slice(0, 160)}`);
228
+ conn.pending.toolCalls.push({ id: call.tool_call_id, name, input: call.parameters || {} });
229
+ conn.openToolCallIds.add(call.tool_call_id);
230
+ settleSoon(conn);
231
+ }
232
+
233
+ // On Windows, models copy Git Bash paths (/tmp/..., /c/Users/...) from `pwd` into file tools; Claude Code reads those
234
+ // as outside the project and asks for permission. Git's own cygpath gives the exact Windows equivalent.
235
+ const PATH_KEYS = ['file_path', 'path', 'notebook_path'];
236
+ const windowsPathCache = new Map();
237
+
238
+ function toWindowsPath(value) {
239
+ if (process.platform !== 'win32' || typeof value !== 'string' || !value.startsWith('/')) return value;
240
+ if (!windowsPathCache.has(value)) {
241
+ let converted = value.replace(/^\/([a-zA-Z])(\/|$)/, (match, drive) => `${drive.toUpperCase()}:\\`).replace(/\//g, '\\');
242
+ try {
243
+ converted = execFileSync('cygpath', ['-w', value], { encoding: 'utf8', windowsHide: true }).trim() || converted;
244
+ } catch {
245
+ // cygpath missing: the drive-letter rewrite above is the best available guess.
246
+ }
247
+ windowsPathCache.set(value, converted);
248
+ }
249
+ return windowsPathCache.get(value);
250
+ }
251
+
252
+ function withWindowsPaths(input) {
253
+ const output = { ...input };
254
+ for (const key of PATH_KEYS) output[key] = toWindowsPath(output[key]);
255
+ for (const key of PATH_KEYS) if (output[key] === undefined) delete output[key];
256
+ return output;
257
+ }
258
+
259
+ // The agent can emit text and several tool calls for one turn as separate events, so settle after a short quiet gap.
260
+ function settleSoon(conn) {
261
+ clearTimeout(conn.pending.settleTimer);
262
+ conn.pending.settleTimer = setTimeout(() => settle(conn, null), SETTLE_MS);
263
+ }
264
+
265
+ function settle(conn, failure) {
266
+ const pending = conn.pending;
267
+ if (!pending) return;
268
+ conn.pending = null;
269
+ clearTimeout(pending.settleTimer);
270
+ clearTimeout(pending.timeout);
271
+ if (failure?.error) pending.reject(failure.error);
272
+ else pending.resolve({ text: pending.text, toolCalls: pending.toolCalls });
273
+ }
274
+
275
+ function sendTurn(conn, { text, toolResults, history }) {
276
+ if (conn.pending) throw new Error('A request is already active for this conversation');
277
+ const requestId = String(++conn.messageId);
278
+
279
+ return new Promise((resolve, reject) => {
280
+ conn.pending = { resolve, reject, text: '', toolCalls: [], settleTimer: null };
281
+ conn.pending.timeout = setTimeout(
282
+ () => settle(conn, { error: new Error(`No reply from ${conn.llm} within ${REQUEST_TIMEOUT_MS / 1000}s`) }),
283
+ REQUEST_TIMEOUT_MS
284
+ );
285
+
286
+ // Claude Code resends the whole thread every turn, so a fresh conversation (reconnect, /model switch,
287
+ // --resume, compaction) is seeded from what Claude Code sent.
288
+ if (conn.messageId === 1 && history.length) {
289
+ conn.ws.send(JSON.stringify({
290
+ type: 'contextual_update',
291
+ text: `Conversation so far:\n${formatConversationHistory(history).slice(-MAX_REPLAY_CHARS)}`
292
+ }));
293
+ }
294
+
295
+ const known = toolResults.filter(result => conn.openToolCallIds.has(result.toolUseId));
296
+ if (toolResults.length && known.length === toolResults.length) {
297
+ for (const result of toolResults) {
298
+ conn.openToolCallIds.delete(result.toolUseId);
299
+ conn.ws.send(JSON.stringify({
300
+ type: 'client_tool_result',
301
+ tool_call_id: result.toolUseId,
302
+ result: result.content,
303
+ is_error: result.isError
304
+ }));
305
+ }
306
+ if (text) conn.ws.send(JSON.stringify({ type: 'contextual_update', text }));
307
+ return;
308
+ }
309
+
310
+ // Results for calls this conversation never made (it was reopened) go in as text, otherwise the agent
311
+ // waits on tool_call_ids it does not know and never answers.
312
+ const resultText = toolResults
313
+ .map(result => `${result.isError ? 'Tool error' : 'Tool result'} (${result.toolUseId}):\n${result.content}`)
314
+ .join('\n\n');
315
+ conn.ws.send(JSON.stringify({
316
+ type: 'user_message',
317
+ id: requestId,
318
+ text: [resultText, text, resultText ? 'Continue the task from here.' : ''].filter(Boolean).join('\n\n')
319
+ }));
320
+ });
321
+ }
322
+
323
+ function saveConversation(threadId, llm, conversationId, messages) {
324
+ if (!fs.existsSync(CONVERSATIONS_DIR)) fs.mkdirSync(CONVERSATIONS_DIR, { recursive: true });
325
+ fs.writeFileSync(path.join(CONVERSATIONS_DIR, `${threadId}.json`),
326
+ JSON.stringify({ llm, conversationId, history: messages, updatedAt: Date.now() }, null, 1));
327
+ }
328
+
329
+ function anthropicError(res, status, type, message) {
330
+ return res.status(status).json({ type: 'error', error: { type, message } });
331
+ }
332
+
333
+ // ============================================
334
+ // HTTP: Anthropic Messages API
335
+ // ============================================
336
+
337
+ const app = express();
338
+ app.use(bodyParser.json({ limit: '50mb' }));
339
+
340
+ app.post('/v1/messages', async (req, res) => {
341
+ const { model, messages = [], system, stream, metadata, tools = [], max_tokens: maxTokens, output_config: outputConfig } = req.body;
342
+ const llm = resolveLlm(model, req.get('x-labs-model'), aliases, llmIds);
343
+ console.log(`\n🤖 ${model} -> ${llm || 'UNKNOWN'} | ${messages.length} messages | ${tools.length} tools`);
344
+ if (!llm) return anthropicError(res, 400, 'invalid_request_error', `Unknown model "${model}". Run "labs models" to list models.`);
345
+
346
+ try {
347
+ const latest = extractLatestUserContent(messages);
348
+ if (!latest.text && latest.toolResults.length === 0) {
349
+ return anthropicError(res, 400, 'invalid_request_error', 'No text or tool result in the latest user message');
350
+ }
351
+
352
+ // Claude Code's side calls (titles, summaries) carry no tools; keep them out of the coding conversation.
353
+ const isSideRequest = tools.length === 0;
354
+ const sessionId = req.get('x-labs-session-id') || metadata?.session_id || `side_${Date.now()}`;
355
+ const threadId = isValidSessionId(sessionId) ? createThreadId(sessionId, messages) : createThreadId('anon', messages);
356
+ const toolIds = isSideRequest ? [] : await toolRegistry.ensure(tools);
357
+ const toolSetHash = createHash('sha1').update(toolIds.join(',')).digest('hex').slice(0, 8);
358
+ let conn;
359
+ let result;
360
+ for (;;) {
361
+ const settings = agentSettingsFor(llm, outputConfig?.effort || 'max', maxTokens);
362
+ const key = isSideRequest
363
+ ? `side_${Date.now()}_${Math.random().toString(36).slice(2)}`
364
+ : `${llm}:${settings.reasoning_effort}:${threadId}:${toolSetHash}`;
365
+ const existing = connections.get(key);
366
+ conn = existing && existing.ws.readyState === WebSocket.OPEN
367
+ ? existing
368
+ : await withAgentSettings(settings, () => openConversation(key, { llm, prompt: systemText(system) || 'You are a helpful assistant.', toolIds }));
369
+ try {
370
+ result = await sendTurn(conn, { text: latest.text, toolResults: latest.toolResults, history: messages.slice(0, -1) });
371
+ break;
372
+ } catch (error) {
373
+ if (!/Cascade Error: TimeoutError/.test(error.message) || !lowerEffortCap(llm, settings.reasoning_effort)) throw error;
374
+ console.log(`🎚️ ${llm} too slow at effort=${settings.reasoning_effort}; retrying at ${effortCaps.get(llm)}`);
375
+ }
376
+ }
377
+
378
+ // Claude Code decides when to auto-compact from input_tokens, so report the whole request, not just the last turn.
379
+ const requestChars = JSON.stringify(system || '').length + JSON.stringify(messages).length + JSON.stringify(tools).length;
380
+ const message = createAnthropicMessage({
381
+ model,
382
+ text: result.text || '',
383
+ toolCalls: result.toolCalls || [],
384
+ inputTokens: conn.contextTokens || Math.ceil(requestChars / 4)
385
+ });
386
+
387
+ if (isSideRequest) conn.ws.close();
388
+ else saveConversation(threadId, llm, conn.conversationId, [...messages, { role: 'assistant', content: message.content }]);
389
+
390
+ return stream ? writeAnthropicEvents(res, createAnthropicEvents(message)) : res.json(message);
391
+ } catch (error) {
392
+ console.error(`🚨 ${llm}: ${error.message}`);
393
+ // 500, not 529: Claude Code retries a 500 on the same model, but answers repeated 529s by switching models.
394
+ if (!res.headersSent) return anthropicError(res, 500, 'api_error', `ElevenLabs ${llm}: ${error.message}`);
395
+ }
396
+ });
397
+
398
+ app.get('/health', (req, res) => res.json({ name: 'labs-claude', version: VERSION }));
399
+
400
+ app.post('/shutdown', (req, res) => {
401
+ res.json({ ok: true });
402
+ setTimeout(() => process.exit(0), 100);
403
+ });
404
+
405
+ app.get('/v1/models', (req, res) => {
406
+ res.json({ data: Object.entries(aliases).map(([id, llm]) => ({ id, type: 'model', display_name: `${id} (${llm})` })) });
407
+ });
408
+
409
+ app.get('/v1/sessions', (req, res) => {
410
+ if (!fs.existsSync(CONVERSATIONS_DIR)) return res.json({ sessions: [] });
411
+ const sessions = fs.readdirSync(CONVERSATIONS_DIR).filter(file => file.endsWith('.json')).map(file => {
412
+ const data = JSON.parse(fs.readFileSync(path.join(CONVERSATIONS_DIR, file), 'utf8'));
413
+ return { id: file.replace('.json', ''), llm: data.llm || data.agentId, messageCount: (data.history || []).length, updatedAt: data.updatedAt };
414
+ });
415
+ res.json({ sessions: sessions.sort((a, b) => b.updatedAt - a.updatedAt) });
416
+ });
417
+
418
+ app.delete('/v1/sessions/:sessionId', (req, res) => {
419
+ const { sessionId } = req.params;
420
+ if (!isValidSessionId(sessionId)) return res.status(400).json({ error: 'Invalid session ID' });
421
+ const filePath = path.join(CONVERSATIONS_DIR, `${sessionId}.json`);
422
+ if (!fs.existsSync(filePath)) return res.status(404).json({ error: 'Session not found' });
423
+ fs.unlinkSync(filePath);
424
+ res.json({ success: true });
425
+ });
426
+
427
+ process.on('uncaughtException', error => console.error(`💥 Uncaught: ${error.stack}`));
428
+ process.on('unhandledRejection', error => console.error(`💥 Unhandled rejection: ${error?.stack || error}`));
429
+
430
+ process.on('SIGINT', () => {
431
+ connections.forEach(conn => conn.ws.close());
432
+ process.exit(0);
433
+ });
434
+
435
+ app.listen(PORT, '127.0.0.1', () => {
436
+ console.log(`✅ Proxy LIVE at http://localhost:${PORT} | bridge agent ${config.bridgeAgent}`);
437
+ refreshLlmList();
438
+ });
package/src/setup.js ADDED
@@ -0,0 +1,121 @@
1
+ const axios = require('axios');
2
+ const readline = require('readline');
3
+ const { execFileSync } = require('child_process');
4
+ const { API_BASE, CONFIG_PATH, loadConfig, saveConfig, saveLlmList } = require('./config');
5
+
6
+ const BRIDGE_AGENT_NAME = 'Labs Claude Code Bridge';
7
+
8
+ function askHidden(question) {
9
+ return new Promise(resolve => {
10
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true });
11
+ rl._writeToOutput = text => { if (text.includes(question)) process.stdout.write(text); };
12
+ rl.question(question, answer => {
13
+ rl.close();
14
+ process.stdout.write('\n');
15
+ resolve(answer.trim());
16
+ });
17
+ });
18
+ }
19
+
20
+ function hasClaudeCode() {
21
+ try {
22
+ execFileSync(process.platform === 'win32' ? 'claude.exe' : 'claude', ['--version'], { stdio: 'ignore' });
23
+ return true;
24
+ } catch {
25
+ try {
26
+ execFileSync('claude --version', { stdio: 'ignore', shell: true });
27
+ return true;
28
+ } catch {
29
+ return false;
30
+ }
31
+ }
32
+ }
33
+
34
+ // Per-conversation overrides (prompt, llm, tool_ids) are what let one agent run Claude Code's own prompt and tools on any LLM.
35
+ async function createBridgeAgent(headers) {
36
+ const response = await axios.post(`${API_BASE}/agents/create`, {
37
+ name: BRIDGE_AGENT_NAME,
38
+ conversation_config: {
39
+ agent: {
40
+ first_message: '',
41
+ language: 'en',
42
+ prompt: {
43
+ prompt: 'Claude Code supplies the real system prompt per conversation.',
44
+ llm: 'gemini-3.8-flash',
45
+ cascade_timeout_seconds: 15,
46
+ backup_llm_config: { preference: 'disabled' }
47
+ }
48
+ },
49
+ conversation: { text_only: true }
50
+ },
51
+ platform_settings: {
52
+ // Post-conversation analysis adds nothing for a coding bridge.
53
+ topic_discovery: { enabled: false },
54
+ sentiment_analysis: { enabled: false },
55
+ overrides: {
56
+ conversation_config_override: {
57
+ agent: { first_message: true, prompt: { prompt: true, llm: true, tool_ids: true } },
58
+ conversation: { text_only: true }
59
+ }
60
+ }
61
+ }
62
+ }, { headers });
63
+ return response.data.agent_id;
64
+ }
65
+
66
+ async function agentExists(agentId, headers) {
67
+ try {
68
+ await axios.get(`${API_BASE}/agents/${agentId}`, { headers });
69
+ return true;
70
+ } catch {
71
+ return false;
72
+ }
73
+ }
74
+
75
+ async function runSetup() {
76
+ console.log('⚙️ labs setup — Claude Code on ElevenLabs models\n');
77
+ if (!hasClaudeCode()) {
78
+ console.log('❌ Claude Code is not installed. Install it first: https://docs.claude.com/en/docs/claude-code/setup');
79
+ process.exit(1);
80
+ }
81
+ console.log('✅ Claude Code found');
82
+
83
+ const existing = loadConfig() || {};
84
+ let apiKey = process.env.ELEVENLABS_API_KEY || existing.apiKey;
85
+ if (apiKey) {
86
+ console.log('✅ Using the ElevenLabs API key already configured');
87
+ } else {
88
+ console.log('🔑 Paste your ElevenLabs API key (elevenlabs.io → Developers → API Keys; it needs ElevenAgents access).');
89
+ apiKey = await askHidden(' API key: ');
90
+ }
91
+ const headers = { 'xi-api-key': apiKey };
92
+
93
+ let llms;
94
+ try {
95
+ llms = (await axios.get(`${API_BASE}/llm/list`, { headers })).data.llms;
96
+ } catch (error) {
97
+ console.log(`❌ ElevenLabs rejected the key (${error.response?.status || error.message}). Check it has ElevenAgents permission.`);
98
+ process.exit(1);
99
+ }
100
+ saveLlmList(llms);
101
+ console.log(`✅ Key works — ${llms.filter(item => !item.deprecation_info).length} models available`);
102
+
103
+ let bridgeAgent = existing.bridgeAgent;
104
+ if (!bridgeAgent || !(await agentExists(bridgeAgent, headers))) {
105
+ bridgeAgent = await createBridgeAgent(headers);
106
+ console.log(`✅ Created "${BRIDGE_AGENT_NAME}" agent in your ElevenLabs account (${bridgeAgent})`);
107
+ } else {
108
+ console.log(`✅ Bridge agent ready (${bridgeAgent})`);
109
+ }
110
+
111
+ const { apiKey: _storedKey, models: _models, ...rest } = existing;
112
+ saveConfig({
113
+ ...rest,
114
+ // A key supplied through the environment stays there instead of being copied to disk.
115
+ ...(process.env.ELEVENLABS_API_KEY ? {} : { apiKey }),
116
+ bridgeAgent
117
+ });
118
+ console.log(`💾 Saved ${CONFIG_PATH}\n\n🚀 Done. Run: labs (Astra)\n labs --model opus\n labs models (list all)`);
119
+ }
120
+
121
+ module.exports = { runSetup };
package/src/usage.js ADDED
@@ -0,0 +1,44 @@
1
+ const axios = require('axios');
2
+ const { API_BASE } = require('./config');
3
+
4
+ // Totals what the bridge agent's recent conversations cost, per LLM, from ElevenLabs' own billing metadata.
5
+ async function printUsage(config, limit = 50) {
6
+ const headers = { 'xi-api-key': config.apiKey };
7
+ const subscription = (await axios.get('https://api.elevenlabs.io/v1/user/subscription', { headers })).data;
8
+ const list = (await axios.get(`${API_BASE}/conversations`, { headers, params: { agent_id: config.bridgeAgent, page_size: limit } })).data.conversations;
9
+
10
+ const perModel = {};
11
+ let credits = 0;
12
+ for (const item of list) {
13
+ const metadata = (await axios.get(`${API_BASE}/conversations/${item.conversation_id}`, { headers })).data.metadata || {};
14
+ credits += metadata.cost || 0;
15
+ const llmUsage = metadata.charging?.llm_usage || {};
16
+ for (const phase of ['irreversible_generation', 'initiated_generation']) {
17
+ for (const [model, usage] of Object.entries(llmUsage[phase]?.model_usage || {})) {
18
+ const row = perModel[model] ||= { conversations: 0, input: 0, cached: 0, output: 0, usd: 0 };
19
+ row.conversations += 1;
20
+ row.input += (usage.input?.tokens || 0) + (usage.input_cache_write?.tokens || 0);
21
+ row.cached += usage.input_cache_read?.tokens || 0;
22
+ row.output += usage.output_total?.tokens || 0;
23
+ row.usd += Object.values(usage).reduce((sum, part) => sum + (part.price || 0), 0);
24
+ }
25
+ }
26
+ }
27
+
28
+ const used = subscription.character_count;
29
+ const total = subscription.character_limit;
30
+ const reset = subscription.next_character_count_reset_unix
31
+ ? new Date(subscription.next_character_count_reset_unix * 1000).toISOString().slice(0, 10)
32
+ : 'unknown';
33
+ console.log(`\n💰 ElevenLabs credits: ${used.toLocaleString()} used of ${total.toLocaleString()} (${(used / total * 100).toFixed(1)}%), resets ${reset}`);
34
+ console.log(`📊 Last ${list.length} labs conversations: ${credits.toLocaleString()} credits\n`);
35
+ const pad = (value, width) => String(value).padStart(width);
36
+ console.log(`${'model'.padEnd(26)}${pad('convs', 6)}${pad('fresh in', 12)}${pad('cached in', 12)}${pad('output', 10)}${pad('USD', 9)}`);
37
+ for (const [model, row] of Object.entries(perModel).sort((a, b) => b[1].usd - a[1].usd)) {
38
+ console.log(`${model.padEnd(26)}${pad(row.conversations, 6)}${pad(row.input.toLocaleString(), 12)}${pad(row.cached.toLocaleString(), 12)}${pad(row.output.toLocaleString(), 10)}${pad(`$${row.usd.toFixed(2)}`, 9)}`);
39
+ }
40
+ console.log('\nFresh input is full price, cached input is about 10x cheaper, output is the most expensive per token.');
41
+ console.log('Billing can lag a few minutes behind a conversation.\n');
42
+ }
43
+
44
+ module.exports = { printUsage };