labs-claude 0.1.16 → 0.3.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 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,24 +52,89 @@ 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
 
47
- ## Browser integration
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
+ ## Qwen on our GPU box (a labs key, no ElevenLabs account needed)
67
+
68
+ The box runs Qwen 3.8 27B (normal and uncensored, 262k context) on one RTX PRO 6000. It is on for booked hours, not all day.
69
+
70
+ 1. Get a labs key (`lk_...`) from whoever runs the gateway.
71
+ 2. `labs key`, press Enter for the address (`https://labs.instant.uz`), paste the key (hidden).
72
+ 3. `labs --model qwen` or `labs --model qwen-uncensored`.
73
+
74
+ When the box is off, `labs` says so before Claude Code opens. Box tokens are free per token; each key can have a daily $ cap for paid models. The gateway (keys, metering, console) lives in `gateway/` and is not part of the npm package.
75
+
76
+ ## GLM 5.3 on Amazon Bedrock (your own AWS account)
77
+
78
+ `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).
48
79
 
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.
80
+ 1. In the AWS console (region us-east-1): Amazon Bedrock → API keys → generate a key.
81
+ 2. `labs bedrock` and paste it (hidden; saved to `~/.labs/bedrock-key`, never printed).
82
+ 3. `labs --model glm`, or `/model glm` inside Claude Code. The older ElevenLabs GLM 5.2 is still there as `glm52`.
50
83
 
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).
84
+ 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.
52
85
 
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.
86
+ ## Auto fallback: real Opus first, labs Opus 5.5 when the subscription ends
87
+
88
+ `labs auto` (any Claude Code flags work) starts the real Claude Code on your subscription. When the subscription fails for good in that session, the same session is resumed on labs Opus 5.5 with one line: `Subscription limit hit, continuing on labs Opus 5.5`. The next `labs auto` tries the subscription again.
89
+
90
+ - Signal: labs tails the session transcript (`~/.claude/projects/.../<session>.jsonl`). It switches on an API-error record of type `authentication_failed`, `oauth_org_not_allowed`, `account_on_hold`, `billing_error`, or a `rate_limit` carrying `quotaLimits.status: rejected` that resets more than 5 minutes away (session, weekly, Opus limits). Plain 429s and overloads are retried by Claude Code and never switch.
91
+ - The title and first line show the brain: `Opus · subscription` or `Opus 5.5 · labs`.
92
+ - Test it: `LABS_AUTO_FORCE_FALLBACK=1 labs auto -p "say ok"` runs one real subscription turn, then forces the switch.
93
+ - Interactive limitation: after the switch, retype or say "continue" (the failed message is in the session; labs does not resend it).
94
+
95
+ ## Chat page
96
+
97
+ `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.
98
+
99
+ - **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.
100
+ - **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.
101
+
102
+ The page works only on this machine (`127.0.0.1`) and only with your labs key (an HttpOnly, same-site cookie).
103
+
104
+ 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.
105
+
106
+ ## Phone (Remote Control)
107
+
108
+ `/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.
109
+
110
+ ## Saving tokens
111
+
112
+ ElevenLabs caches only the system prompt, so every token of history is paid in full on every turn. labs keeps that down:
113
+
114
+ - **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.
115
+ - **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.
116
+ - **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`.
117
+ - `labs usage` shows fresh vs cached input per model, so you can see where credits go.
54
118
 
55
119
  ## Limits to know
56
120
 
57
121
  - **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.
122
+ - **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.
123
+ - **15 seconds to the first word:** ElevenLabs' maximum. labs retries a slow start up to 3 times before Claude Code sees an error.
124
+ - **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.
125
+ - **About 190 tools at once:** an ElevenLabs agent holds at most 200 tool documents; beyond that, labs offers the most recently used ones.
126
+ - **Usage is billed to your ElevenLabs account.** Check it at elevenlabs.io → Usage or with `labs usage`.
127
+
128
+ ## Reliability
129
+
130
+ - **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.
131
+ - **Live streaming.** Text appears as the model writes it.
132
+ - **Self-healing proxy.** A `labs` window restarts the background proxy within ~10 s if it dies.
133
+ - **Local only.** The proxy accepts only `labs` (a private key in `~/.labs/proxy-key`) on `127.0.0.1`.
61
134
 
62
135
  ## Files
63
136
 
64
- `~/.labs/`: `config.json`, `proxy.log`, `llm-list.json`, `tool-registry-<agent>.json`, `conversations/`
137
+ `~/.labs/`: `config.json`, `proxy-key`, `proxy.log`, `llm-list.json`, `tool-registry-<agent>.json`, `conversations/`, `bedrock-key`, `bedrock-usage.jsonl`, `chat/`
65
138
 
66
139
  ## License
67
140
 
package/bin/labs.js CHANGED
@@ -1,119 +1,245 @@
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
- });
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, ask, askHidden } = require('../src/setup');
10
+ const { gatewayModelFrom, prepareGatewayLaunch, saveGatewayKey, makeAdminToken, openConsole, storedConfig } = require('../src/gateway-client');
11
+ const { bedrockModelId, readBedrockKey } = require('../src/bedrock');
12
+ const { printUsage } = require('../src/usage');
13
+ const { setAutostart } = require('../src/autostart');
14
+ const { planSubscriptionLeg, planLabsLegArgs, createWatcher } = require('../src/auto-fallback');
15
+ const { version } = require('../package.json');
16
+
17
+ const HELP = `labs ${version} — Claude Code running on ElevenLabs models
18
+
19
+ labs open Claude Code on the default model (astra)
20
+ labs --model opus pick a model by name, number (labs --model 5) or raw ElevenLabs id
21
+ labs -p "question" any Claude Code flag works, e.g. -p, --resume, --permission-mode
22
+ labs auto [claude args] real Claude Code on your subscription; on a limit or expired login, same session continues on labs Opus 5.5
23
+ labs models [--all] list models
24
+ labs usage credits left and what recent sessions cost per model
25
+ labs setup set your ElevenLabs key, the bridge agent and real-Chrome control
26
+ labs bedrock save your Amazon Bedrock key, then: labs --model glm (GLM 5.3)
27
+ labs --model qwen Claude Code on our GPU box (qwen | qwen-uncensored), through the labs gateway
28
+ labs key save the labs key you were given for the box
29
+ labs console open the gateway console (keys, usage, $); admin only
30
+ labs admin-token <ssh> make a new console admin token on the gateway server
31
+ labs chat open the private chat page (http://127.0.0.1:8081/chat)
32
+ labs serve start the background proxy if it is not running, then exit
33
+ labs autostart on|off keep the proxy (and the chat page) running from login (Windows)
34
+ labs stop stop the background proxy
35
+
36
+ Inside Claude Code: /model <name> switches model, e.g. /model gpt-5.6-terra
37
+ Browser: "open gmail.com and read my top email" uses your real Chrome (set up with labs setup)
38
+ Update: npm install -g labs-claude@latest --prefer-online, then close and reopen every labs window`;
39
+
40
+ function printModels(config, showAll) {
41
+ const llms = loadLlmList();
42
+ const byId = Object.fromEntries(llms.map(item => [item.llm, item]));
43
+ const size = (n) => n >= 1000000 ? `${Math.round(n / 100000) / 10}M` : `${Math.round(n / 1000)}k`;
44
+ console.log('\n🚀 Labs models (labs --model <name or number>)\n');
45
+ Object.entries(config.models).forEach(([name, llm], index) => {
46
+ const info = byId[llm];
47
+ const detail = bedrockModelId(llm)
48
+ ? `Amazon Bedrock, ${size(config.bedrockContextLimit).padStart(5)} context 128k reply`
49
+ : info ? `${size(info.max_context_limit).padStart(5)} context ${size(info.max_tokens_limit).padStart(5)} reply` : 'not offered on your account';
50
+ const marker = name === config.defaultModel ? ' ← default' : '';
51
+ console.log(`${String(index + 1).padStart(3)}. ${name.padEnd(11)} ${llm.padEnd(24)} ${detail}${marker}`);
52
+ });
53
+ const current = llms.filter(item => !item.deprecation_info && !item.is_checkpoint);
54
+ if (showAll) {
55
+ console.log(`\nAll ${current.length} current ElevenLabs LLMs (use the id with --model):\n`);
56
+ 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`));
57
+ } else {
58
+ console.log(`\n${current.length} current ElevenLabs LLMs in total: labs models --all`);
59
+ }
60
+ console.log('Inside Claude Code: /model <name> switches model.\n');
61
+ }
62
+
63
+ // The browser opens a one-time link (single use, 60 s), so the key is never pasted or shown. If that fails, the key
64
+ // goes to the clipboard, never to the screen, so it does not end up in terminal logs or screenshots.
65
+ async function openChat(config) {
66
+ if (!(await ensureProxy(config.port))) {
67
+ console.error('❌ The labs proxy did not start. See ~/.labs/proxy.log');
68
+ process.exit(1);
69
+ }
70
+ const base = `http://127.0.0.1:${config.port}`;
71
+ let url = `${base}/chat`;
72
+ try {
73
+ const { data } = await axios.post(`${base}/chat/api/login-link`, null, { headers: { 'x-api-key': loadProxyKey(LABS_DIR) }, timeout: 3000 });
74
+ url = base + data.path;
75
+ console.log('🔓 Opening the chat page, already logged in.');
76
+ } catch {
77
+ const clipboard = { win32: ['clip', []], darwin: ['pbcopy', []] }[process.platform];
78
+ if (clipboard) {
79
+ const copy = spawn(clipboard[0], clipboard[1]);
80
+ copy.stdin.end(loadProxyKey(LABS_DIR));
81
+ console.log('🔑 Your labs key is on the clipboard: paste it once on the page.');
82
+ }
83
+ }
84
+ console.log(`💬 ${base}/chat`);
85
+ const opener = process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] : [process.platform === 'darwin' ? 'open' : 'xdg-open', [url]];
86
+ spawn(opener[0], opener[1], { stdio: 'ignore', detached: true }).unref();
87
+ }
88
+
89
+ function launchClaude(claudeArgs, env, onExit = code => process.exit(code ?? 0)) {
90
+ // The native installer ships claude.exe; an npm-installed Claude Code on Windows is a .cmd shim that needs a shell.
91
+ const command = process.platform === 'win32' ? 'claude.exe' : 'claude';
92
+ const child = spawn(command, claudeArgs, { stdio: 'inherit', env });
93
+ const handle = { child, kill: () => handle.child.kill() };
94
+ child.on('error', error => {
95
+ if (error.code !== 'ENOENT' || process.platform !== 'win32') {
96
+ console.error(`❌ Could not start Claude Code: ${error.message}`);
97
+ process.exit(1);
98
+ }
99
+ const quoted = claudeArgs.map(arg => `"${arg.replace(/"/g, '\\"')}"`).join(' ');
100
+ handle.child = spawn(`claude ${quoted}`, { stdio: 'inherit', env, shell: true });
101
+ handle.child.on('exit', code => onExit(code));
102
+ });
103
+ child.on('exit', code => onExit(code));
104
+ return handle;
105
+ }
106
+
107
+ // Everything needed to start Claude Code against the labs proxy; shared by `labs` and the labs leg of `labs auto`.
108
+ async function prepareLabsLaunch(config, args) {
109
+ const { modelName, claudeArgs } = parseLaunchArgs(args, {
110
+ aliases: config.models,
111
+ llmIds: new Set(loadLlmList().map(item => item.llm)),
112
+ defaultModel: config.defaultModel
113
+ });
114
+
115
+ const chromeWarning = chromeCompatibilityWarning(claudeArgs);
116
+ if (chromeWarning) console.error(`⚠️ ${chromeWarning}`);
117
+
118
+ if (!(await ensureProxy(config.port))) {
119
+ console.error('❌ The labs proxy did not start. See ~/.labs/proxy.log');
120
+ process.exit(1);
121
+ }
122
+
123
+ const llm = config.models[modelName] || modelName;
124
+ const onBedrock = Boolean(bedrockModelId(llm));
125
+ // Without a key every call gets 401, and Claude Code retries those silently: the window would look frozen.
126
+ if (onBedrock && !readBedrockKey(LABS_DIR)) {
127
+ console.error(`❌ ${modelName} runs on Amazon Bedrock and no Bedrock key is saved. Run: labs bedrock`);
128
+ process.exit(1);
129
+ }
130
+ const llmInfo = onBedrock
131
+ ? { max_context_limit: config.bedrockContextLimit }
132
+ : loadLlmList().find(item => item.llm === llm);
133
+ if (!claudeArgs.some(arg => arg === '--effort' || arg.startsWith('--effort='))) {
134
+ claudeArgs.push('--effort', config.defaultEffort || 'high');
135
+ }
136
+
137
+ const env = {
138
+ ...process.env,
139
+ // Claude Code only knows Anthropic windows; without this it assumes 200k and compacts at the wrong point.
140
+ ...(llmInfo ? { CLAUDE_CODE_MAX_CONTEXT_TOKENS: String(Math.min(llmInfo.max_context_limit, config.contextLimit)) } : {}),
141
+ ANTHROPIC_BASE_URL: `http://127.0.0.1:${config.port}`,
142
+ ANTHROPIC_AUTH_TOKEN: loadProxyKey(LABS_DIR),
143
+ ANTHROPIC_CUSTOM_HEADERS: withLabsHeaders(process.env.ANTHROPIC_CUSTOM_HEADERS, randomUUID(), modelName),
144
+ // Subagents run on the chosen model too; the proxy answers overload with 529 so Claude Code retries, never switches.
145
+ CLAUDE_CODE_SUBAGENT_MODEL: modelName
146
+ };
147
+ // A leftover key (e.g. from an Ollama setup) would take precedence over the proxy's auth token.
148
+ delete env.ANTHROPIC_API_KEY;
149
+
150
+ const window = llmInfo ? `, ${Math.round(llmInfo.max_context_limit / 1000)}k context` : '';
151
+ const banner = `🚀 Claude Code on ${onBedrock ? 'Amazon Bedrock' : 'ElevenLabs'} ${modelName} (${llm}${window})`;
152
+ return { modelName, claudeArgs, env, banner };
153
+ }
154
+
155
+ // `labs auto`: real Claude Code on the subscription first; when the subscription fails for good in this session
156
+ // (see src/subscription-failure.js), the same session is resumed on labs Opus 5.5. The next start tries the subscription again.
157
+ async function runAuto(args) {
158
+ const force = process.env.LABS_AUTO_FORCE_FALLBACK === '1';
159
+ const leg = planSubscriptionLeg(args);
160
+ const env = { ...process.env };
161
+ // The subscription leg must talk to Anthropic directly, even when this shell was started with labs variables.
162
+ for (const name of ['ANTHROPIC_BASE_URL', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_CUSTOM_HEADERS', 'CLAUDE_CODE_MAX_CONTEXT_TOKENS', 'CLAUDE_CODE_SUBAGENT_MODEL']) delete env[name];
163
+ console.log('🟢 Opus · subscription');
164
+ process.stdout.write(']0;Opus · subscription');
165
+
166
+ let switched = false;
167
+ const toLabs = async failure => {
168
+ if (switched) return;
169
+ switched = true;
170
+ watcher.stop();
171
+ const sessionId = leg.sessionId || failure.sessionId;
172
+ handle.kill();
173
+ let config = loadConfig();
174
+ if (!config?.apiKey || !config.bridgeAgent) { await runSetup(); config = loadConfig(); }
175
+ const launch = await prepareLabsLaunch(config, planLabsLegArgs(args, sessionId));
176
+ console.log(`
177
+ 🔁 Subscription limit hit (${failure.kind}), continuing on labs Opus 5.5`);
178
+ process.stdout.write(']0;Opus 5.5 · labs');
179
+ keepProxyAlive(config.port);
180
+ launchClaude(launch.claudeArgs, launch.env);
181
+ };
182
+ const watcher = createWatcher({ sessionId: leg.sessionId, fromStart: leg.fromStart, startedAt: Date.now(), forceFallback: force, onFailure: toLabs });
183
+ const handle = launchClaude(leg.args, env, async code => {
184
+ if (switched) return;
185
+ // A -p run ends right after the error, before the next poll: read what is left before deciding to exit.
186
+ const found = watcher.pollNow();
187
+ if (found) return toLabs(found);
188
+ watcher.stop();
189
+ process.exit(code ?? 0);
190
+ });
191
+ }
192
+
193
+ async function main() {
194
+ const args = process.argv.slice(2);
195
+ if (args[0] === 'setup') return runSetup();
196
+ if (args[0] === 'bedrock') return setupBedrock();
197
+ if (args[0] === 'auto') return runAuto(args.slice(1));
198
+ if (args[0] === '--help' || args[0] === 'help') return console.log(HELP);
199
+ if (args[0] === '--version') return console.log(version);
200
+ if (args[0] === 'autostart') {
201
+ if (!['on', 'off'].includes(args[1])) return console.log('Use: labs autostart on | labs autostart off');
202
+ const { ok, message } = setAutostart(args[1] === 'on');
203
+ console[ok ? 'log' : 'error'](message);
204
+ return process.exit(ok ? 0 : 1);
205
+ }
206
+ // The autostart task runs this with no window, so it must never fall into the interactive setup.
207
+ if (args[0] === 'serve') {
208
+ const ready = loadConfig()?.apiKey && await ensureProxy(loadConfig().port);
209
+ console.log(ready ? '✅ labs proxy running' : '❌ labs proxy not started (run labs setup, see ~/.labs/proxy.log)');
210
+ return process.exit(ready ? 0 : 1);
211
+ }
212
+
213
+ // Box users (friends) may have no ElevenLabs account at all, so these never fall into the ElevenLabs setup.
214
+ if (args[0] === 'key') return saveGatewayKey(askHidden, ask);
215
+ if (args[0] === 'admin-token') return makeAdminToken(args[1]);
216
+ if (args[0] === 'console') return openConsole(storedConfig());
217
+ const boxModel = gatewayModelFrom(args);
218
+ if (boxModel) {
219
+ const launch = await prepareGatewayLaunch(storedConfig(), args, boxModel);
220
+ console.log(launch.banner);
221
+ return launchClaude(launch.claudeArgs, launch.env);
222
+ }
223
+
224
+ let config = loadConfig();
225
+ if (!config?.apiKey || !config.bridgeAgent) {
226
+ console.log(`No setup found at ${CONFIG_PATH}, running setup first.\n`);
227
+ await runSetup();
228
+ config = loadConfig();
229
+ }
230
+
231
+ if (args[0] === 'models') return printModels(config, args.includes('--all'));
232
+ if (args[0] === 'usage') return printUsage(config);
233
+ if (args[0] === 'chat') return openChat(config);
234
+ if (args[0] === 'stop') return console.log(await stopProxy(config.port) ? '🛑 Proxy stopped' : 'Proxy was not running');
235
+
236
+ const launch = await prepareLabsLaunch(config, args);
237
+ console.log(launch.banner);
238
+ keepProxyAlive(config.port);
239
+ launchClaude(launch.claudeArgs, launch.env);
240
+ }
241
+
242
+ main().catch(error => {
243
+ console.error(`❌ ${error.message}`);
244
+ process.exit(1);
245
+ });
package/package.json CHANGED
@@ -1,33 +1,34 @@
1
- {
2
- "name": "labs-claude",
3
- "version": "0.1.16",
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": {
6
- "labs": "bin/labs.js"
7
- },
8
- "files": [
9
- "bin",
10
- "src",
11
- "README.md"
12
- ],
13
- "scripts": {
14
- "test": "node --test"
15
- },
16
- "engines": {
17
- "node": ">=18"
18
- },
19
- "keywords": [
20
- "claude-code",
21
- "elevenlabs",
22
- "proxy",
23
- "anthropic",
24
- "cli"
25
- ],
26
- "license": "MIT",
27
- "dependencies": {
28
- "axios": "^1.20.0",
29
- "body-parser": "^2.3.0",
30
- "express": "^5.2.1",
31
- "ws": "^8.22.0"
32
- }
33
- }
1
+ {
2
+ "name": "labs-claude",
3
+ "version": "0.3.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": {
6
+ "labs": "bin/labs.js"
7
+ },
8
+ "files": [
9
+ "bin",
10
+ "src",
11
+ "README.md"
12
+ ],
13
+ "scripts": {
14
+ "test": "node --test"
15
+ },
16
+ "engines": {
17
+ "node": ">=18"
18
+ },
19
+ "keywords": [
20
+ "claude-code",
21
+ "elevenlabs",
22
+ "proxy",
23
+ "anthropic",
24
+ "cli"
25
+ ],
26
+ "license": "MIT",
27
+ "dependencies": {
28
+ "@aws-sdk/client-bedrock-runtime": "^3.1156.0",
29
+ "axios": "^1.20.0",
30
+ "body-parser": "^2.3.0",
31
+ "express": "^5.2.1",
32
+ "ws": "^8.22.0"
33
+ }
34
+ }
@@ -235,7 +235,8 @@ function createAnthropicEvents(message) {
235
235
  emit('message_delta', {
236
236
  type: 'message_delta',
237
237
  delta: { stop_reason: message.stop_reason, stop_sequence: null },
238
- 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 }
239
240
  });
240
241
  emit('message_stop', { type: 'message_stop' });
241
242
  return events;