labs-claude 0.1.7 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,6 +10,14 @@ labs setup
10
10
  labs
11
11
  ```
12
12
 
13
+ ## Update
14
+
15
+ ```bash
16
+ npm install -g labs-claude@latest --prefer-online
17
+ ```
18
+
19
+ Then **close every open `labs` window and open `labs` again**. A new `labs` replaces the old background proxy by itself, and old windows keep running old code until they are restarted. `labs --version` shows what you have.
20
+
13
21
  Works on **Windows, macOS and Linux**. You need:
14
22
 
15
23
  - **Node.js 18+**
@@ -27,7 +35,7 @@ Works on **Windows, macOS and Linux**. You need:
27
35
  | `labs --model 5` | Pick by its number in `labs models` |
28
36
  | `labs --model gpt-5.4` | Any ElevenLabs LLM id |
29
37
  | `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) |
38
+ | `labs --effort max` | Reasoning effort (default: `high`). labs keeps the effort you chose: a slow first word is retried up to 3 times at the same effort, never lowered |
31
39
  | `labs models` / `labs models --all` | List models with context and reply sizes |
32
40
  | `labs usage` | Credits left, and what recent sessions cost per model (tokens and USD) |
33
41
  | `labs stop` | Stop the background proxy |
@@ -44,16 +52,70 @@ Claude Code ──HTTP (Anthropic API)──> labs proxy on 127.0.0.1:8081 ─
44
52
  - When the model calls a tool, Claude Code runs it on your machine, with its usual permission prompts.
45
53
  - Every conversation runs in text-only mode, so no audio is generated.
46
54
 
55
+ ## Control your real Chrome
56
+
57
+ Claude in Chrome needs a claude.ai login, which labs replaces with its own key, so `labs --chrome` cannot work. labs drives **your real Chrome** (your logins and tabs) through Microsoft's official **Playwright Extension** instead:
58
+
59
+ 1. Install the [Playwright Extension](https://chromewebstore.google.com/detail/playwright-extension/mmlmfjhmonkocbjadbfplnigmagldckm) (publisher: Microsoft; linked from [microsoft/playwright](https://github.com/microsoft/playwright/tree/main/packages/extension)).
60
+ 2. Click its icon and copy `PLAYWRIGHT_MCP_EXTENSION_TOKEN` (optional: without it Chrome asks "Allow?" on each connection).
61
+ 3. Run `labs setup` and answer **y** to "Let labs control your real Chrome?". It adds the `labs-browser` server to Claude Code.
62
+ 4. Close and reopen `labs`, then ask for any browser task: *"open gmail.com and read the subject of my top email"*.
63
+
64
+ The model works in its own tab group, so your other tabs stay out of reach. It can use every site you are signed in to, so give it the same care as any browser agent.
65
+
66
+ ## GLM 5.3 on Amazon Bedrock (your own AWS account)
67
+
68
+ `glm` runs Z.AI's full GLM 5.3 (744B, 1M context, 128k replies) through Amazon Bedrock instead of ElevenLabs. It is a direct API, so none of the ElevenLabs limits below apply (no 50-second cut, no tool cap, no 4k replies).
69
+
70
+ 1. In the AWS console (region us-east-1): Amazon Bedrock → API keys → generate a key.
71
+ 2. `labs bedrock` and paste it (hidden; saved to `~/.labs/bedrock-key`, never printed).
72
+ 3. `labs --model glm`, or `/model glm` inside Claude Code. The older ElevenLabs GLM 5.2 is still there as `glm52`.
73
+
74
+ Every request of that session (side calls too) stays on Bedrock and is billed to your AWS account (credits first). `~/.labs/bedrock-usage.jsonl` logs tokens per call. Claude Code compacts at `"bedrockContextLimit"` (default `200000`) because Bedrock bills all input tokens on every turn.
75
+
76
+ ## Chat page
77
+
78
+ `labs chat` opens a private chat page at `http://127.0.0.1:8081/chat`, already logged in: it opens a one-time link (single use, 60 seconds), so you never paste the key. If that fails, the key goes to the clipboard for a one-time login instead.
79
+
80
+ - **Chat**: talk to GLM 5.3 (or any labs model); drop text files and images in; chats are saved in `~/.labs/chat/`; each reply shows tokens and an estimated cost.
81
+ - **Agent**: pick a folder and give a task; the real Claude Code works there on the chosen model and the page shows each step. "Can read and edit files" allows edits only; "Full access" also runs commands.
82
+
83
+ The page works only on this machine (`127.0.0.1`) and only with your labs key (an HttpOnly, same-site cookie).
84
+
85
+ The page lives inside the proxy, so it is down until `labs` or `labs chat` starts the proxy. To keep it up from login, run `labs autostart on` (Windows): a hidden task checks the proxy at login and every 2 minutes, also on battery. `labs autostart off` removes the task.
86
+
87
+ ## Phone (Remote Control)
88
+
89
+ `/remote-control` does not work in labs: Anthropic disables it whenever `ANTHROPIC_BASE_URL` points at a proxy. Use real `claude` for Remote Control, or run `labs` in `tmux` on a server and open it from your phone over SSH.
90
+
91
+ ## Saving tokens
92
+
93
+ ElevenLabs caches only the system prompt, so every token of history is paid in full on every turn. labs keeps that down:
94
+
95
+ - **Side calls on a cheap model.** Titles, summaries and compaction (requests without tools) run on `gemini-3.8-flash`. Set `"sideModel": false` in `~/.labs/config.json` to keep them on your chosen model.
96
+ - **Compaction at 300k.** Claude Code compacts at `"contextLimit"` (default `300000`), even on 1M models; raise it in `~/.labs/config.json` if you want longer memory at a higher cost.
97
+ - **Big file reads.** A whole-file Read over 350 lines is summarised by `gemini-3.8-flash` with line ranges; the model reads exact lines with offset/limit before editing. Turn off with `"shunt": false`.
98
+ - `labs usage` shows fresh vs cached input per model, so you can see where credits go.
99
+
47
100
  ## Limits to know
48
101
 
49
102
  - **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.
103
+ - **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.
104
+ - **15 seconds to the first word:** ElevenLabs' maximum. labs retries a slow start up to 3 times before Claude Code sees an error.
105
+ - **120-second tool limit:** ElevenLabs gives up on a tool after 120 s; labs sends the late result as a message when the command finishes.
106
+ - **About 190 tools at once:** an ElevenLabs agent holds at most 200 tool documents; beyond that, labs offers the most recently used ones.
107
+ - **Usage is billed to your ElevenLabs account.** Check it at elevenlabs.io → Usage or with `labs usage`.
108
+
109
+ ## Reliability
110
+
111
+ - **One memory per task.** Each Claude Code thread stays in one ElevenLabs conversation; a restart replays your instructions (CLAUDE.md, memory) plus the newest turns.
112
+ - **Live streaming.** Text appears as the model writes it.
113
+ - **Self-healing proxy.** A `labs` window restarts the background proxy within ~10 s if it dies.
114
+ - **Local only.** The proxy accepts only `labs` (a private key in `~/.labs/proxy-key`) on `127.0.0.1`.
53
115
 
54
116
  ## Files
55
117
 
56
- `~/.labs/`: `config.json`, `proxy.log`, `llm-list.json`, `tool-registry-<agent>.json`, `conversations/`
118
+ `~/.labs/`: `config.json`, `proxy-key`, `proxy.log`, `llm-list.json`, `tool-registry-<agent>.json`, `conversations/`, `bedrock-key`, `bedrock-usage.jsonl`, `chat/`
57
119
 
58
120
  ## License
59
121
 
package/bin/labs.js CHANGED
@@ -1,114 +1,178 @@
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 axios = require('axios');
3
+ const { spawn } = require('child_process');
4
+ const { randomUUID } = require('crypto');
5
+ const { CONFIG_PATH, LABS_DIR, loadConfig, loadLlmList } = require('../src/config');
6
+ const { loadProxyKey } = require('../src/local-auth');
7
+ const { ensureProxy, keepProxyAlive, stopProxy } = require('../src/proxy-manager');
8
+ const { parseLaunchArgs, withLabsHeaders, chromeCompatibilityWarning } = require('../src/launch-args');
9
+ const { runSetup, setupBedrock } = require('../src/setup');
10
+ const { bedrockModelId, readBedrockKey } = require('../src/bedrock');
11
+ const { printUsage } = require('../src/usage');
12
+ const { setAutostart } = require('../src/autostart');
13
+ const { version } = require('../package.json');
14
+
15
+ const HELP = `labs ${version} — Claude Code running on ElevenLabs models
16
+
17
+ labs open Claude Code on the default model (astra)
18
+ labs --model opus pick a model by name, number (labs --model 5) or raw ElevenLabs id
19
+ labs -p "question" any Claude Code flag works, e.g. -p, --resume, --permission-mode
20
+ labs models [--all] list models
21
+ labs usage credits left and what recent sessions cost per model
22
+ labs setup set your ElevenLabs key, the bridge agent and real-Chrome control
23
+ labs bedrock save your Amazon Bedrock key, then: labs --model glm (GLM 5.3)
24
+ labs chat open the private chat page (http://127.0.0.1:8081/chat)
25
+ labs serve start the background proxy if it is not running, then exit
26
+ labs autostart on|off keep the proxy (and the chat page) running from login (Windows)
27
+ labs stop stop the background proxy
28
+
29
+ Inside Claude Code: /model <name> switches model, e.g. /model gpt-5.6-terra
30
+ Browser: "open gmail.com and read my top email" uses your real Chrome (set up with labs setup)
31
+ Update: npm install -g labs-claude@latest --prefer-online, then close and reopen every labs window`;
32
+
33
+ function printModels(config, showAll) {
34
+ const llms = loadLlmList();
35
+ const byId = Object.fromEntries(llms.map(item => [item.llm, item]));
36
+ const size = (n) => n >= 1000000 ? `${Math.round(n / 100000) / 10}M` : `${Math.round(n / 1000)}k`;
37
+ console.log('\n🚀 Labs models (labs --model <name or number>)\n');
38
+ Object.entries(config.models).forEach(([name, llm], index) => {
39
+ const info = byId[llm];
40
+ const detail = bedrockModelId(llm)
41
+ ? `Amazon Bedrock, ${size(config.bedrockContextLimit).padStart(5)} context 128k reply`
42
+ : info ? `${size(info.max_context_limit).padStart(5)} context ${size(info.max_tokens_limit).padStart(5)} reply` : 'not offered on your account';
43
+ const marker = name === config.defaultModel ? ' ← default' : '';
44
+ console.log(`${String(index + 1).padStart(3)}. ${name.padEnd(11)} ${llm.padEnd(24)} ${detail}${marker}`);
45
+ });
46
+ const current = llms.filter(item => !item.deprecation_info && !item.is_checkpoint);
47
+ if (showAll) {
48
+ console.log(`\nAll ${current.length} current ElevenLabs LLMs (use the id with --model):\n`);
49
+ 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`));
50
+ } else {
51
+ console.log(`\n${current.length} current ElevenLabs LLMs in total: labs models --all`);
52
+ }
53
+ console.log('Inside Claude Code: /model <name> switches model.\n');
54
+ }
55
+
56
+ // The browser opens a one-time link (single use, 60 s), so the key is never pasted or shown. If that fails, the key
57
+ // goes to the clipboard, never to the screen, so it does not end up in terminal logs or screenshots.
58
+ async function openChat(config) {
59
+ if (!(await ensureProxy(config.port))) {
60
+ console.error('❌ The labs proxy did not start. See ~/.labs/proxy.log');
61
+ process.exit(1);
62
+ }
63
+ const base = `http://127.0.0.1:${config.port}`;
64
+ let url = `${base}/chat`;
65
+ try {
66
+ const { data } = await axios.post(`${base}/chat/api/login-link`, null, { headers: { 'x-api-key': loadProxyKey(LABS_DIR) }, timeout: 3000 });
67
+ url = base + data.path;
68
+ console.log('🔓 Opening the chat page, already logged in.');
69
+ } catch {
70
+ const clipboard = { win32: ['clip', []], darwin: ['pbcopy', []] }[process.platform];
71
+ if (clipboard) {
72
+ const copy = spawn(clipboard[0], clipboard[1]);
73
+ copy.stdin.end(loadProxyKey(LABS_DIR));
74
+ console.log('🔑 Your labs key is on the clipboard: paste it once on the page.');
75
+ }
76
+ }
77
+ console.log(`💬 ${base}/chat`);
78
+ const opener = process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] : [process.platform === 'darwin' ? 'open' : 'xdg-open', [url]];
79
+ spawn(opener[0], opener[1], { stdio: 'ignore', detached: true }).unref();
80
+ }
81
+
82
+ function launchClaude(claudeArgs, env) {
83
+ // The native installer ships claude.exe; an npm-installed Claude Code on Windows is a .cmd shim that needs a shell.
84
+ const command = process.platform === 'win32' ? 'claude.exe' : 'claude';
85
+ const child = spawn(command, claudeArgs, { stdio: 'inherit', env });
86
+ child.on('error', error => {
87
+ if (error.code !== 'ENOENT' || process.platform !== 'win32') {
88
+ console.error(`❌ Could not start Claude Code: ${error.message}`);
89
+ process.exit(1);
90
+ }
91
+ const quoted = claudeArgs.map(arg => `"${arg.replace(/"/g, '\\"')}"`).join(' ');
92
+ spawn(`claude ${quoted}`, { stdio: 'inherit', env, shell: true }).on('exit', code => process.exit(code ?? 1));
93
+ });
94
+ child.on('exit', code => process.exit(code ?? 0));
95
+ }
96
+
97
+ async function main() {
98
+ const args = process.argv.slice(2);
99
+ if (args[0] === 'setup') return runSetup();
100
+ if (args[0] === 'bedrock') return setupBedrock();
101
+ if (args[0] === '--help' || args[0] === 'help') return console.log(HELP);
102
+ if (args[0] === '--version') return console.log(version);
103
+ if (args[0] === 'autostart') {
104
+ if (!['on', 'off'].includes(args[1])) return console.log('Use: labs autostart on | labs autostart off');
105
+ const { ok, message } = setAutostart(args[1] === 'on');
106
+ console[ok ? 'log' : 'error'](message);
107
+ return process.exit(ok ? 0 : 1);
108
+ }
109
+ // The autostart task runs this with no window, so it must never fall into the interactive setup.
110
+ if (args[0] === 'serve') {
111
+ const ready = loadConfig()?.apiKey && await ensureProxy(loadConfig().port);
112
+ console.log(ready ? '✅ labs proxy running' : '❌ labs proxy not started (run labs setup, see ~/.labs/proxy.log)');
113
+ return process.exit(ready ? 0 : 1);
114
+ }
115
+
116
+ let config = loadConfig();
117
+ if (!config?.apiKey || !config.bridgeAgent) {
118
+ console.log(`No setup found at ${CONFIG_PATH}, running setup first.\n`);
119
+ await runSetup();
120
+ config = loadConfig();
121
+ }
122
+
123
+ if (args[0] === 'models') return printModels(config, args.includes('--all'));
124
+ if (args[0] === 'usage') return printUsage(config);
125
+ if (args[0] === 'chat') return openChat(config);
126
+ if (args[0] === 'stop') return console.log(await stopProxy(config.port) ? '🛑 Proxy stopped' : 'Proxy was not running');
127
+
128
+ const { modelName, claudeArgs } = parseLaunchArgs(args, {
129
+ aliases: config.models,
130
+ llmIds: new Set(loadLlmList().map(item => item.llm)),
131
+ defaultModel: config.defaultModel
132
+ });
133
+
134
+ const chromeWarning = chromeCompatibilityWarning(claudeArgs);
135
+ if (chromeWarning) console.error(`⚠️ ${chromeWarning}`);
136
+
137
+ if (!(await ensureProxy(config.port))) {
138
+ console.error('❌ The labs proxy did not start. See ~/.labs/proxy.log');
139
+ process.exit(1);
140
+ }
141
+
142
+ const llm = config.models[modelName] || modelName;
143
+ const onBedrock = Boolean(bedrockModelId(llm));
144
+ // Without a key every call gets 401, and Claude Code retries those silently: the window would look frozen.
145
+ if (onBedrock && !readBedrockKey(LABS_DIR)) {
146
+ console.error(`❌ ${modelName} runs on Amazon Bedrock and no Bedrock key is saved. Run: labs bedrock`);
147
+ process.exit(1);
148
+ }
149
+ const llmInfo = onBedrock
150
+ ? { max_context_limit: config.bedrockContextLimit }
151
+ : loadLlmList().find(item => item.llm === llm);
152
+ if (!claudeArgs.some(arg => arg === '--effort' || arg.startsWith('--effort='))) {
153
+ claudeArgs.push('--effort', config.defaultEffort || 'high');
154
+ }
155
+
156
+ const env = {
157
+ ...process.env,
158
+ // Claude Code only knows Anthropic windows; without this it assumes 200k and compacts at the wrong point.
159
+ ...(llmInfo ? { CLAUDE_CODE_MAX_CONTEXT_TOKENS: String(Math.min(llmInfo.max_context_limit, config.contextLimit)) } : {}),
160
+ ANTHROPIC_BASE_URL: `http://127.0.0.1:${config.port}`,
161
+ ANTHROPIC_AUTH_TOKEN: loadProxyKey(LABS_DIR),
162
+ ANTHROPIC_CUSTOM_HEADERS: withLabsHeaders(process.env.ANTHROPIC_CUSTOM_HEADERS, randomUUID(), modelName),
163
+ // Subagents run on the chosen model too; the proxy answers overload with 529 so Claude Code retries, never switches.
164
+ CLAUDE_CODE_SUBAGENT_MODEL: modelName
165
+ };
166
+ // A leftover key (e.g. from an Ollama setup) would take precedence over the proxy's auth token.
167
+ delete env.ANTHROPIC_API_KEY;
168
+
169
+ const window = llmInfo ? `, ${Math.round(llmInfo.max_context_limit / 1000)}k context` : '';
170
+ console.log(`🚀 Claude Code on ${onBedrock ? 'Amazon Bedrock' : 'ElevenLabs'} ${modelName} (${llm}${window})`);
171
+ keepProxyAlive(config.port);
172
+ launchClaude(claudeArgs, env);
173
+ }
174
+
175
+ main().catch(error => {
176
+ console.error(`❌ ${error.message}`);
177
+ process.exit(1);
178
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "labs-claude",
3
- "version": "0.1.7",
3
+ "version": "0.2.6",
4
4
  "description": "Run the real Claude Code CLI on ElevenLabs models (GPT-6 Astra, Opus 5.5, Gemini, GLM...) with your own ElevenLabs key — like Ollama, but for ElevenLabs.",
5
5
  "bin": {
6
6
  "labs": "bin/labs.js"
@@ -25,6 +25,7 @@
25
25
  ],
26
26
  "license": "MIT",
27
27
  "dependencies": {
28
+ "@aws-sdk/client-bedrock-runtime": "^3.1156.0",
28
29
  "axios": "^1.20.0",
29
30
  "body-parser": "^2.3.0",
30
31
  "express": "^5.2.1",
@@ -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) {
@@ -197,32 +235,83 @@ function createAnthropicEvents(message) {
197
235
  emit('message_delta', {
198
236
  type: 'message_delta',
199
237
  delta: { stop_reason: message.stop_reason, stop_sequence: null },
200
- usage: { output_tokens: usage.output_tokens }
238
+ // message_start can only carry an estimate; the final count (exact on Bedrock) arrives here, as in the Anthropic API.
239
+ usage: { input_tokens: usage.input_tokens, output_tokens: usage.output_tokens }
201
240
  });
202
241
  emit('message_stop', { type: 'message_stop' });
203
242
  return events;
204
243
  }
205
244
 
206
- function writeAnthropicEvents(response, events) {
245
+ function startEventStream(response) {
207
246
  response.status(200);
208
247
  response.set({
209
248
  'Content-Type': 'text/event-stream; charset=utf-8',
210
249
  'Cache-Control': 'no-cache',
211
250
  Connection: 'keep-alive'
212
251
  });
213
- for (const { event, data } of events) {
214
- response.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
215
- }
252
+ }
253
+
254
+ function writeEvent(response, { event, data }) {
255
+ response.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
256
+ }
257
+
258
+ function writeAnthropicEvents(response, events) {
259
+ startEventStream(response);
260
+ for (const event of events) writeEvent(response, event);
216
261
  response.end();
217
262
  }
218
263
 
264
+ const STREAM_PING_MS = 10000;
265
+
266
+ // Text reaches Claude Code as ElevenLabs writes it; tool calls and the stop reason follow when the turn settles.
267
+ // Nothing is sent before the first word, so an early failure can still be answered with an HTTP error and retried.
268
+ function createLiveStream(response, { model, inputTokens }) {
269
+ let pingTimer = null;
270
+ const live = {
271
+ started: false,
272
+ streamedText: '',
273
+ text(delta) {
274
+ if (!live.started) {
275
+ live.started = true;
276
+ startEventStream(response);
277
+ const { content, usage, ...start } = createAnthropicMessage({ model, inputTokens });
278
+ writeEvent(response, { event: 'message_start', data: { type: 'message_start', message: { ...start, content: [], stop_reason: null, usage: { input_tokens: inputTokens, output_tokens: 0 } } } });
279
+ writeEvent(response, { event: 'content_block_start', data: { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } } });
280
+ pingTimer = setInterval(() => writeEvent(response, { event: 'ping', data: { type: 'ping' } }), STREAM_PING_MS);
281
+ }
282
+ live.streamedText += delta;
283
+ writeEvent(response, { event: 'content_block_delta', data: { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: delta } } });
284
+ },
285
+ // The message must carry streamedText as its text, so the reply Claude Code stores matches what it was shown.
286
+ finish(message) {
287
+ live.stopPings();
288
+ if (!live.started) return writeAnthropicEvents(response, createAnthropicEvents(message));
289
+ writeEvent(response, { event: 'content_block_stop', data: { type: 'content_block_stop', index: 0 } });
290
+ const rest = createAnthropicEvents(message).filter(({ event, data }) => event !== 'message_start' && data.index !== 0);
291
+ for (const event of rest) writeEvent(response, event);
292
+ response.end();
293
+ },
294
+ fail(error) {
295
+ live.stopPings();
296
+ writeEvent(response, { event: 'error', data: { type: 'error', error: { type: 'api_error', message: error.message } } });
297
+ response.end();
298
+ },
299
+ stopPings() {
300
+ clearInterval(pingTimer);
301
+ }
302
+ };
303
+ return live;
304
+ }
305
+
219
306
  module.exports = {
220
307
  createAnthropicEvents,
221
308
  createAnthropicMessage,
309
+ createLiveStream,
222
310
  createModelCatalog,
223
311
  createSessionKey,
224
312
  createThreadId,
225
313
  extractLatestUserContent,
314
+ lastAssistantContent,
226
315
  replySignature,
227
316
  formatConversationHistory,
228
317
  isValidSessionId,
@@ -0,0 +1,43 @@
1
+ const { spawnSync } = require('child_process');
2
+ const path = require('path');
3
+
4
+ const TASK_NAME = 'labs proxy';
5
+ const LABS_BIN = path.join(__dirname, '..', 'bin', 'labs.js');
6
+
7
+ const quote = text => `'${String(text).replace(/'/g, "''")}'`;
8
+
9
+ // A logon trigger alone misses a proxy that crashes later, so the task also runs every 2 minutes; `labs serve` exits at
10
+ // once when the proxy is healthy. Task Scheduler's defaults skip tasks on battery, which would leave a laptop without the
11
+ // proxy, so both battery settings are switched off. conhost --headless keeps a console window from flashing.
12
+ function registerScript() {
13
+ return [
14
+ `$action = New-ScheduledTaskAction -Execute 'conhost.exe' -Argument ${quote(`--headless "${process.execPath}" "${LABS_BIN}" serve`)}`,
15
+ '$logon = New-ScheduledTaskTrigger -AtLogOn -User $env:USERNAME',
16
+ '$every = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 2)',
17
+ '$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable '
18
+ + '-MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Minutes 1)',
19
+ `Register-ScheduledTask -TaskName ${quote(TASK_NAME)} -Action $action -Trigger $logon,$every -Settings $settings `
20
+ + "-Description 'Keeps the labs proxy (Claude Code + chat page on 127.0.0.1:8081) running.' -Force | Out-Null"
21
+ ].join('; ');
22
+ }
23
+
24
+ function runPowerShell(script) {
25
+ return spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { encoding: 'utf8', windowsHide: true });
26
+ }
27
+
28
+ function setAutostart(on) {
29
+ if (process.platform !== 'win32') return { ok: false, message: 'labs autostart is Windows only for now.' };
30
+ const script = on
31
+ ? registerScript()
32
+ : `Unregister-ScheduledTask -TaskName ${quote(TASK_NAME)} -Confirm:$false -ErrorAction SilentlyContinue`;
33
+ const result = runPowerShell(script);
34
+ if (result.status !== 0) return { ok: false, message: (result.stderr || result.stdout || 'PowerShell failed').trim() };
35
+ return {
36
+ ok: true,
37
+ message: on
38
+ ? `✅ Task "${TASK_NAME}" checks the proxy at login and every 2 minutes. Undo: labs autostart off`
39
+ : `🛑 Task "${TASK_NAME}" removed. The proxy now starts only with labs or labs chat.`
40
+ };
41
+ }
42
+
43
+ module.exports = { setAutostart, registerScript, TASK_NAME };