labs-claude 0.1.7 → 0.1.16

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 CHANGED
@@ -1,60 +1,68 @@
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 max` | Reasoning effort (default: `high`; lowered automatically if a reply would exceed ElevenLabs time limits) |
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
- - **About 50 seconds per reply:** ElevenLabs cuts any single reply (thinking plus writing) after roughly 50 s. labs asks the model to write big files in parts of about 80 lines, and lowers effort automatically if a reply still runs over.
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
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 max` | Reasoning effort (default: `high`; lowered automatically if a reply would exceed ElevenLabs time limits) |
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
+ ## Browser integration
48
+
49
+ Claude Code's built-in Claude in Chrome integration is not supported by Labs' custom API authentication. Current Claude Code requires a supported direct Claude account signed in with `/login`; passing `labs --chrome` does not satisfy that requirement. Labs forwards the flag but prints a compatibility warning when it is explicitly enabled.
50
+
51
+ To use the official extension, launch `claude --chrome` outside Labs with supported authentication. See the [Chrome integration requirements](https://code.claude.com/docs/en/chrome).
52
+
53
+ A separately configured browser MCP server is an alternative for browser automation through Labs, not the same extension. Labs passes `--mcp-config` and `--strict-mcp-config` through to Claude Code. Browser MCP operation has not been verified end-to-end by the offline test suite.
54
+
55
+ ## Limits to know
56
+
57
+ - **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.
58
+ - **About 50 seconds per reply:** ElevenLabs cuts any single reply (thinking plus writing) after roughly 50 s. labs asks the model to write big files in parts of about 80 lines, and lowers effort automatically if a reply still runs over.
59
+ - **120-second tool limit:** ElevenLabs waits at most 120 s for a tool result. A command that runs longer can fail that turn.
60
+ - **Usage is billed to your ElevenLabs account.** Check it at elevenlabs.io → Usage.
61
+
62
+ ## Files
63
+
64
+ `~/.labs/`: `config.json`, `proxy.log`, `llm-list.json`, `tool-registry-<agent>.json`, `conversations/`
65
+
66
+ ## License
67
+
68
+ MIT
package/bin/labs.js CHANGED
@@ -1,114 +1,119 @@
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 || 'high');
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
- });
1
+ #!/usr/bin/env node
2
+ const { spawn } = require('child_process');
3
+ const { randomUUID } = require('crypto');
4
+ const { CONFIG_PATH, LABS_DIR, loadConfig, loadLlmList } = require('../src/config');
5
+ const { loadProxyKey } = require('../src/local-auth');
6
+ const { ensureProxy, keepProxyAlive, stopProxy } = require('../src/proxy-manager');
7
+ const { parseLaunchArgs, withLabsHeaders, chromeCompatibilityWarning } = require('../src/launch-args');
8
+ const { runSetup } = require('../src/setup');
9
+ const { printUsage } = require('../src/usage');
10
+ const { version } = require('../package.json');
11
+
12
+ const HELP = `labs ${version} — Claude Code running on ElevenLabs models
13
+
14
+ labs open Claude Code on the default model (astra)
15
+ labs --model opus pick a model by name, number (labs --model 5) or raw ElevenLabs id
16
+ labs -p "question" any Claude Code flag works, e.g. -p, --resume, --permission-mode
17
+ labs models [--all] list models
18
+ labs usage credits left and what recent sessions cost per model
19
+ labs setup set your ElevenLabs API key and create the bridge agent
20
+ labs stop stop the background proxy
21
+
22
+ Inside Claude Code: /model <name> switches model, e.g. /model gpt-5.6-terra`;
23
+
24
+ function printModels(config, showAll) {
25
+ const llms = loadLlmList();
26
+ const byId = Object.fromEntries(llms.map(item => [item.llm, item]));
27
+ const size = (n) => n >= 1000000 ? `${Math.round(n / 100000) / 10}M` : `${Math.round(n / 1000)}k`;
28
+ console.log('\n🚀 Labs models (labs --model <name or number>)\n');
29
+ Object.entries(config.models).forEach(([name, llm], index) => {
30
+ const info = byId[llm];
31
+ const detail = info ? `${size(info.max_context_limit).padStart(5)} context ${size(info.max_tokens_limit).padStart(5)} reply` : 'not offered on your account';
32
+ const marker = name === config.defaultModel ? ' ← default' : '';
33
+ console.log(`${String(index + 1).padStart(3)}. ${name.padEnd(11)} ${llm.padEnd(24)} ${detail}${marker}`);
34
+ });
35
+ const current = llms.filter(item => !item.deprecation_info && !item.is_checkpoint);
36
+ if (showAll) {
37
+ console.log(`\nAll ${current.length} current ElevenLabs LLMs (use the id with --model):\n`);
38
+ 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`));
39
+ } else {
40
+ console.log(`\n${current.length} current ElevenLabs LLMs in total: labs models --all`);
41
+ }
42
+ console.log('Inside Claude Code: /model <name> switches model.\n');
43
+ }
44
+
45
+ function launchClaude(claudeArgs, env) {
46
+ // The native installer ships claude.exe; an npm-installed Claude Code on Windows is a .cmd shim that needs a shell.
47
+ const command = process.platform === 'win32' ? 'claude.exe' : 'claude';
48
+ const child = spawn(command, claudeArgs, { stdio: 'inherit', env });
49
+ child.on('error', error => {
50
+ if (error.code !== 'ENOENT' || process.platform !== 'win32') {
51
+ console.error(`❌ Could not start Claude Code: ${error.message}`);
52
+ process.exit(1);
53
+ }
54
+ const quoted = claudeArgs.map(arg => `"${arg.replace(/"/g, '\\"')}"`).join(' ');
55
+ spawn(`claude ${quoted}`, { stdio: 'inherit', env, shell: true }).on('exit', code => process.exit(code ?? 1));
56
+ });
57
+ child.on('exit', code => process.exit(code ?? 0));
58
+ }
59
+
60
+ async function main() {
61
+ const args = process.argv.slice(2);
62
+ if (args[0] === 'setup') return runSetup();
63
+ if (args[0] === '--help' || args[0] === 'help') return console.log(HELP);
64
+ if (args[0] === '--version') return console.log(version);
65
+
66
+ let config = loadConfig();
67
+ if (!config?.apiKey || !config.bridgeAgent) {
68
+ console.log(`No setup found at ${CONFIG_PATH}, running setup first.\n`);
69
+ await runSetup();
70
+ config = loadConfig();
71
+ }
72
+
73
+ if (args[0] === 'models') return printModels(config, args.includes('--all'));
74
+ if (args[0] === 'usage') return printUsage(config);
75
+ if (args[0] === 'stop') return console.log(await stopProxy(config.port) ? '🛑 Proxy stopped' : 'Proxy was not running');
76
+
77
+ const { modelName, claudeArgs } = parseLaunchArgs(args, {
78
+ aliases: config.models,
79
+ llmIds: new Set(loadLlmList().map(item => item.llm)),
80
+ defaultModel: config.defaultModel
81
+ });
82
+
83
+ const chromeWarning = chromeCompatibilityWarning(claudeArgs);
84
+ if (chromeWarning) console.error(`⚠️ ${chromeWarning}`);
85
+
86
+ if (!(await ensureProxy(config.port))) {
87
+ console.error('❌ The labs proxy did not start. See ~/.labs/proxy.log');
88
+ process.exit(1);
89
+ }
90
+
91
+ const llm = config.models[modelName] || modelName;
92
+ const llmInfo = loadLlmList().find(item => item.llm === llm);
93
+ if (!claudeArgs.some(arg => arg === '--effort' || arg.startsWith('--effort='))) {
94
+ claudeArgs.push('--effort', config.defaultEffort || 'high');
95
+ }
96
+
97
+ const env = {
98
+ ...process.env,
99
+ // Claude Code only knows Anthropic windows; without this it assumes 200k and compacts at the wrong point.
100
+ ...(llmInfo ? { CLAUDE_CODE_MAX_CONTEXT_TOKENS: String(Math.min(llmInfo.max_context_limit, config.contextLimit)) } : {}),
101
+ ANTHROPIC_BASE_URL: `http://127.0.0.1:${config.port}`,
102
+ ANTHROPIC_AUTH_TOKEN: loadProxyKey(LABS_DIR),
103
+ ANTHROPIC_CUSTOM_HEADERS: withLabsHeaders(process.env.ANTHROPIC_CUSTOM_HEADERS, randomUUID(), modelName),
104
+ // Subagents run on the chosen model too; the proxy answers overload with 529 so Claude Code retries, never switches.
105
+ CLAUDE_CODE_SUBAGENT_MODEL: modelName
106
+ };
107
+ // A leftover key (e.g. from an Ollama setup) would take precedence over the proxy's auth token.
108
+ delete env.ANTHROPIC_API_KEY;
109
+
110
+ const window = llmInfo ? `, ${Math.round(llmInfo.max_context_limit / 1000)}k context` : '';
111
+ console.log(`🚀 Claude Code on ElevenLabs ${modelName} (${llm}${window})`);
112
+ keepProxyAlive(config.port);
113
+ launchClaude(claudeArgs, env);
114
+ }
115
+
116
+ main().catch(error => {
117
+ console.error(`❌ ${error.message}`);
118
+ process.exit(1);
119
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "labs-claude",
3
- "version": "0.1.7",
3
+ "version": "0.1.16",
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": {
6
6
  "labs": "bin/labs.js"
@@ -38,7 +38,30 @@ function collectImages(blocks) {
38
38
  return found;
39
39
  }
40
40
 
41
+ function lastAssistantIndex(messages) {
42
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
43
+ if (messages[index].role === 'assistant') return index;
44
+ }
45
+ return -1;
46
+ }
47
+
48
+ // Claude Code ends each request with a role "system" message (reminders, hook output), so the reply this request
49
+ // continues from is the last assistant message, not messages[length - 2].
50
+ function lastAssistantContent(messages) {
51
+ const index = lastAssistantIndex(messages);
52
+ return index >= 0 ? messages[index].content : null;
53
+ }
54
+
41
55
  function extractLatestUserContent(messages) {
56
+ const systemText = messages.slice(lastAssistantIndex(messages) + 1)
57
+ .filter(message => message.role === 'system')
58
+ .map(message => contentToText(message.content).trim())
59
+ .filter(Boolean);
60
+ const latest = extractLatestUserTurn(messages);
61
+ return { ...latest, text: [...systemText, latest.text].filter(Boolean).join('\n\n') };
62
+ }
63
+
64
+ function extractLatestUserTurn(messages) {
42
65
  for (let index = messages.length - 1; index >= 0; index -= 1) {
43
66
  const message = messages[index];
44
67
  if (message.role !== 'user') continue;
@@ -145,12 +168,27 @@ function createModelCatalog(models) {
145
168
  }));
146
169
  }
147
170
 
148
- function formatConversationHistory(history) {
149
- return history
150
- .filter(message => message.role === 'user' || message.role === 'assistant')
151
- .map(message => `${message.role === 'user' ? 'User' : 'Assistant'}: ${contentToText(message.content)}`)
152
- .filter(message => !message.endsWith(': '))
153
- .join('\n');
171
+ const ROLE_LABELS = { user: 'User', assistant: 'Assistant', system: 'System' };
172
+
173
+ // Over budget, the first message stays: Claude Code puts CLAUDE.md, memory and SessionStart hook output there, and a
174
+ // plain tail cut dropped exactly those. It may take up to 40% of the budget; the newest turns fill the rest.
175
+ function formatConversationHistory(history, maxChars = Infinity) {
176
+ const lines = history
177
+ .filter(message => ROLE_LABELS[message.role])
178
+ .map(message => `${ROLE_LABELS[message.role]}: ${contentToText(message.content)}`)
179
+ .filter(message => !message.endsWith(': '));
180
+ const full = lines.join('\n');
181
+ if (full.length <= maxChars || lines.length === 0) return full;
182
+
183
+ const first = lines[0].slice(0, Math.floor(maxChars * 0.4));
184
+ let room = maxChars - first.length - 60;
185
+ const tail = [];
186
+ for (let index = lines.length - 1; index > 0 && lines[index].length + 1 <= room; index -= 1) {
187
+ tail.unshift(lines[index]);
188
+ room -= lines[index].length + 1;
189
+ }
190
+ const omitted = lines.length - 1 - tail.length;
191
+ return [first, `[... ${omitted} earlier messages omitted ...]`, ...tail].join('\n');
154
192
  }
155
193
 
156
194
  function createAnthropicEvents(message) {
@@ -203,26 +241,76 @@ function createAnthropicEvents(message) {
203
241
  return events;
204
242
  }
205
243
 
206
- function writeAnthropicEvents(response, events) {
244
+ function startEventStream(response) {
207
245
  response.status(200);
208
246
  response.set({
209
247
  'Content-Type': 'text/event-stream; charset=utf-8',
210
248
  'Cache-Control': 'no-cache',
211
249
  Connection: 'keep-alive'
212
250
  });
213
- for (const { event, data } of events) {
214
- response.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
215
- }
251
+ }
252
+
253
+ function writeEvent(response, { event, data }) {
254
+ response.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
255
+ }
256
+
257
+ function writeAnthropicEvents(response, events) {
258
+ startEventStream(response);
259
+ for (const event of events) writeEvent(response, event);
216
260
  response.end();
217
261
  }
218
262
 
263
+ const STREAM_PING_MS = 10000;
264
+
265
+ // Text reaches Claude Code as ElevenLabs writes it; tool calls and the stop reason follow when the turn settles.
266
+ // Nothing is sent before the first word, so an early failure can still be answered with an HTTP error and retried.
267
+ function createLiveStream(response, { model, inputTokens }) {
268
+ let pingTimer = null;
269
+ const live = {
270
+ started: false,
271
+ streamedText: '',
272
+ text(delta) {
273
+ if (!live.started) {
274
+ live.started = true;
275
+ startEventStream(response);
276
+ const { content, usage, ...start } = createAnthropicMessage({ model, inputTokens });
277
+ writeEvent(response, { event: 'message_start', data: { type: 'message_start', message: { ...start, content: [], stop_reason: null, usage: { input_tokens: inputTokens, output_tokens: 0 } } } });
278
+ writeEvent(response, { event: 'content_block_start', data: { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } } });
279
+ pingTimer = setInterval(() => writeEvent(response, { event: 'ping', data: { type: 'ping' } }), STREAM_PING_MS);
280
+ }
281
+ live.streamedText += delta;
282
+ writeEvent(response, { event: 'content_block_delta', data: { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: delta } } });
283
+ },
284
+ // The message must carry streamedText as its text, so the reply Claude Code stores matches what it was shown.
285
+ finish(message) {
286
+ live.stopPings();
287
+ if (!live.started) return writeAnthropicEvents(response, createAnthropicEvents(message));
288
+ writeEvent(response, { event: 'content_block_stop', data: { type: 'content_block_stop', index: 0 } });
289
+ const rest = createAnthropicEvents(message).filter(({ event, data }) => event !== 'message_start' && data.index !== 0);
290
+ for (const event of rest) writeEvent(response, event);
291
+ response.end();
292
+ },
293
+ fail(error) {
294
+ live.stopPings();
295
+ writeEvent(response, { event: 'error', data: { type: 'error', error: { type: 'api_error', message: error.message } } });
296
+ response.end();
297
+ },
298
+ stopPings() {
299
+ clearInterval(pingTimer);
300
+ }
301
+ };
302
+ return live;
303
+ }
304
+
219
305
  module.exports = {
220
306
  createAnthropicEvents,
221
307
  createAnthropicMessage,
308
+ createLiveStream,
222
309
  createModelCatalog,
223
310
  createSessionKey,
224
311
  createThreadId,
225
312
  extractLatestUserContent,
313
+ lastAssistantContent,
226
314
  replySignature,
227
315
  formatConversationHistory,
228
316
  isValidSessionId,
@@ -0,0 +1,38 @@
1
+ const { execFileSync } = require('child_process');
2
+
3
+ // Claude in Chrome needs a claude.ai login, which labs replaces with its proxy key, so labs drives the user's real
4
+ // Chrome through Microsoft's official Playwright Extension instead (verified 2026-10-08: publisher Microsoft,
5
+ // linked from github.com/microsoft/playwright packages/extension).
6
+ const EXTENSION_URL = 'https://chromewebstore.google.com/detail/playwright-extension/mmlmfjhmonkocbjadbfplnigmagldckm';
7
+ const SERVER_NAME = 'labs-browser';
8
+
9
+ function browserServerArgs(token, platform = process.platform) {
10
+ // On Windows npx is a .cmd file, which Claude Code can only start through cmd.
11
+ const command = platform === 'win32' ? ['cmd', '/c', 'npx'] : ['npx'];
12
+ return [
13
+ 'mcp', 'add', SERVER_NAME, '--scope', 'user',
14
+ ...(token ? ['-e', `PLAYWRIGHT_MCP_EXTENSION_TOKEN=${token}`] : []),
15
+ '--', ...command, '--yes', '@playwright/mcp@latest', '--extension'
16
+ ];
17
+ }
18
+
19
+ function runClaude(args) {
20
+ const options = { stdio: 'ignore' };
21
+ try {
22
+ execFileSync(process.platform === 'win32' ? 'claude.exe' : 'claude', args, options);
23
+ } catch (error) {
24
+ if (process.platform !== 'win32' || error.code !== 'ENOENT') throw error;
25
+ execFileSync('claude', args, { ...options, shell: true });
26
+ }
27
+ }
28
+
29
+ function installBrowserServer(token) {
30
+ try {
31
+ runClaude(['mcp', 'remove', SERVER_NAME, '--scope', 'user']);
32
+ } catch {
33
+ // Not configured yet.
34
+ }
35
+ runClaude(browserServerArgs(token));
36
+ }
37
+
38
+ module.exports = { EXTENSION_URL, browserServerArgs, installBrowserServer };
package/src/config.js CHANGED
@@ -30,6 +30,11 @@ function loadConfig() {
30
30
  return {
31
31
  port: DEFAULT_PORT,
32
32
  defaultModel: 'astra',
33
+ // ElevenLabs caches only the system prompt, so every token of history is paid at full price on every turn
34
+ // (measured 2026-10-08: 8 Opus turns at ~324k context cost $11.98). Claude Code compacts at this size.
35
+ contextLimit: 300000,
36
+ // Titles, summaries and compaction (requests without tools) ran on Opus/Sonnet; a cheap 1M model does them.
37
+ sideModel: 'gemini-3.8-flash',
33
38
  ...stored,
34
39
  models: { ...DEFAULT_MODELS, ...(stored.models || {}) },
35
40
  apiKey: process.env.ELEVENLABS_API_KEY || stored.apiKey