labs-claude 0.1.16 → 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 +122 -68
- package/bin/labs.js +65 -6
- package/package.json +2 -1
- package/src/anthropic-protocol.js +2 -1
- package/src/autostart.js +43 -0
- package/src/bedrock.js +162 -0
- package/src/chat/index.html +534 -0
- package/src/chat-routes.js +149 -0
- package/src/config.js +6 -1
- package/src/local-auth.js +2 -1
- package/src/proxy-manager.js +14 -2
- package/src/proxy.js +110 -19
- package/src/setup.js +23 -4
package/README.md
CHANGED
|
@@ -1,68 +1,122 @@
|
|
|
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
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
`labs
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
|
32
|
-
|
|
33
|
-
| `labs
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
##
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
##
|
|
67
|
-
|
|
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
|
+
## 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
|
+
|
|
21
|
+
Works on **Windows, macOS and Linux**. You need:
|
|
22
|
+
|
|
23
|
+
- **Node.js 18+**
|
|
24
|
+
- **Claude Code** installed (`claude --version` should work)
|
|
25
|
+
- An **ElevenLabs API key** with ElevenAgents access (elevenlabs.io → Developers → API Keys)
|
|
26
|
+
|
|
27
|
+
`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.
|
|
28
|
+
|
|
29
|
+
## Use
|
|
30
|
+
|
|
31
|
+
| Command | What it does |
|
|
32
|
+
|---|---|
|
|
33
|
+
| `labs` | Claude Code on the default model (astra) |
|
|
34
|
+
| `labs --model opus` | Pick a model by short name |
|
|
35
|
+
| `labs --model 5` | Pick by its number in `labs models` |
|
|
36
|
+
| `labs --model gpt-5.4` | Any ElevenLabs LLM id |
|
|
37
|
+
| `labs -p "fix the failing test"` | Any Claude Code flag passes through |
|
|
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 |
|
|
39
|
+
| `labs models` / `labs models --all` | List models with context and reply sizes |
|
|
40
|
+
| `labs usage` | Credits left, and what recent sessions cost per model (tokens and USD) |
|
|
41
|
+
| `labs stop` | Stop the background proxy |
|
|
42
|
+
|
|
43
|
+
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`).
|
|
44
|
+
|
|
45
|
+
## How it works
|
|
46
|
+
|
|
47
|
+
```
|
|
48
|
+
Claude Code ──HTTP (Anthropic API)──> labs proxy on 127.0.0.1:8081 ──WebSocket──> ElevenLabs agent ──> chosen LLM
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
- 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.
|
|
52
|
+
- When the model calls a tool, Claude Code runs it on your machine, with its usual permission prompts.
|
|
53
|
+
- Every conversation runs in text-only mode, so no audio is generated.
|
|
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
|
+
|
|
100
|
+
## Limits to know
|
|
101
|
+
|
|
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.
|
|
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`.
|
|
115
|
+
|
|
116
|
+
## Files
|
|
117
|
+
|
|
118
|
+
`~/.labs/`: `config.json`, `proxy-key`, `proxy.log`, `llm-list.json`, `tool-registry-<agent>.json`, `conversations/`, `bedrock-key`, `bedrock-usage.jsonl`, `chat/`
|
|
119
|
+
|
|
120
|
+
## License
|
|
121
|
+
|
|
122
|
+
MIT
|
package/bin/labs.js
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
const axios = require('axios');
|
|
2
3
|
const { spawn } = require('child_process');
|
|
3
4
|
const { randomUUID } = require('crypto');
|
|
4
5
|
const { CONFIG_PATH, LABS_DIR, loadConfig, loadLlmList } = require('../src/config');
|
|
5
6
|
const { loadProxyKey } = require('../src/local-auth');
|
|
6
7
|
const { ensureProxy, keepProxyAlive, stopProxy } = require('../src/proxy-manager');
|
|
7
8
|
const { parseLaunchArgs, withLabsHeaders, chromeCompatibilityWarning } = require('../src/launch-args');
|
|
8
|
-
const { runSetup } = require('../src/setup');
|
|
9
|
+
const { runSetup, setupBedrock } = require('../src/setup');
|
|
10
|
+
const { bedrockModelId, readBedrockKey } = require('../src/bedrock');
|
|
9
11
|
const { printUsage } = require('../src/usage');
|
|
12
|
+
const { setAutostart } = require('../src/autostart');
|
|
10
13
|
const { version } = require('../package.json');
|
|
11
14
|
|
|
12
15
|
const HELP = `labs ${version} — Claude Code running on ElevenLabs models
|
|
@@ -16,10 +19,16 @@ const HELP = `labs ${version} — Claude Code running on ElevenLabs models
|
|
|
16
19
|
labs -p "question" any Claude Code flag works, e.g. -p, --resume, --permission-mode
|
|
17
20
|
labs models [--all] list models
|
|
18
21
|
labs usage credits left and what recent sessions cost per model
|
|
19
|
-
labs setup set your ElevenLabs
|
|
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)
|
|
20
27
|
labs stop stop the background proxy
|
|
21
28
|
|
|
22
|
-
Inside Claude Code: /model <name> switches model, e.g. /model gpt-5.6-terra
|
|
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`;
|
|
23
32
|
|
|
24
33
|
function printModels(config, showAll) {
|
|
25
34
|
const llms = loadLlmList();
|
|
@@ -28,7 +37,9 @@ function printModels(config, showAll) {
|
|
|
28
37
|
console.log('\n🚀 Labs models (labs --model <name or number>)\n');
|
|
29
38
|
Object.entries(config.models).forEach(([name, llm], index) => {
|
|
30
39
|
const info = byId[llm];
|
|
31
|
-
const detail =
|
|
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';
|
|
32
43
|
const marker = name === config.defaultModel ? ' ← default' : '';
|
|
33
44
|
console.log(`${String(index + 1).padStart(3)}. ${name.padEnd(11)} ${llm.padEnd(24)} ${detail}${marker}`);
|
|
34
45
|
});
|
|
@@ -42,6 +53,32 @@ function printModels(config, showAll) {
|
|
|
42
53
|
console.log('Inside Claude Code: /model <name> switches model.\n');
|
|
43
54
|
}
|
|
44
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
|
+
|
|
45
82
|
function launchClaude(claudeArgs, env) {
|
|
46
83
|
// The native installer ships claude.exe; an npm-installed Claude Code on Windows is a .cmd shim that needs a shell.
|
|
47
84
|
const command = process.platform === 'win32' ? 'claude.exe' : 'claude';
|
|
@@ -60,8 +97,21 @@ function launchClaude(claudeArgs, env) {
|
|
|
60
97
|
async function main() {
|
|
61
98
|
const args = process.argv.slice(2);
|
|
62
99
|
if (args[0] === 'setup') return runSetup();
|
|
100
|
+
if (args[0] === 'bedrock') return setupBedrock();
|
|
63
101
|
if (args[0] === '--help' || args[0] === 'help') return console.log(HELP);
|
|
64
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
|
+
}
|
|
65
115
|
|
|
66
116
|
let config = loadConfig();
|
|
67
117
|
if (!config?.apiKey || !config.bridgeAgent) {
|
|
@@ -72,6 +122,7 @@ async function main() {
|
|
|
72
122
|
|
|
73
123
|
if (args[0] === 'models') return printModels(config, args.includes('--all'));
|
|
74
124
|
if (args[0] === 'usage') return printUsage(config);
|
|
125
|
+
if (args[0] === 'chat') return openChat(config);
|
|
75
126
|
if (args[0] === 'stop') return console.log(await stopProxy(config.port) ? '🛑 Proxy stopped' : 'Proxy was not running');
|
|
76
127
|
|
|
77
128
|
const { modelName, claudeArgs } = parseLaunchArgs(args, {
|
|
@@ -89,7 +140,15 @@ async function main() {
|
|
|
89
140
|
}
|
|
90
141
|
|
|
91
142
|
const llm = config.models[modelName] || modelName;
|
|
92
|
-
const
|
|
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);
|
|
93
152
|
if (!claudeArgs.some(arg => arg === '--effort' || arg.startsWith('--effort='))) {
|
|
94
153
|
claudeArgs.push('--effort', config.defaultEffort || 'high');
|
|
95
154
|
}
|
|
@@ -108,7 +167,7 @@ async function main() {
|
|
|
108
167
|
delete env.ANTHROPIC_API_KEY;
|
|
109
168
|
|
|
110
169
|
const window = llmInfo ? `, ${Math.round(llmInfo.max_context_limit / 1000)}k context` : '';
|
|
111
|
-
console.log(`🚀 Claude Code on ElevenLabs ${modelName} (${llm}${window})`);
|
|
170
|
+
console.log(`🚀 Claude Code on ${onBedrock ? 'Amazon Bedrock' : 'ElevenLabs'} ${modelName} (${llm}${window})`);
|
|
112
171
|
keepProxyAlive(config.port);
|
|
113
172
|
launchClaude(claudeArgs, env);
|
|
114
173
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "labs-claude",
|
|
3
|
-
"version": "0.
|
|
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",
|
|
@@ -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
|
-
|
|
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;
|
package/src/autostart.js
ADDED
|
@@ -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 };
|
package/src/bedrock.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
const { createHash } = require('crypto');
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
const { BedrockRuntimeClient, ConverseStreamCommand } = require('@aws-sdk/client-bedrock-runtime');
|
|
5
|
+
|
|
6
|
+
// Aliases whose value starts with this prefix run on Amazon Bedrock instead of ElevenLabs.
|
|
7
|
+
const BEDROCK_PREFIX = 'bedrock:';
|
|
8
|
+
const MAX_OUTPUT_TOKENS = 128000;
|
|
9
|
+
const IMAGE_FORMATS = { 'image/png': 'png', 'image/jpeg': 'jpeg', 'image/jpg': 'jpeg', 'image/gif': 'gif', 'image/webp': 'webp' };
|
|
10
|
+
|
|
11
|
+
function bedrockModelId(llm) {
|
|
12
|
+
return typeof llm === 'string' && llm.startsWith(BEDROCK_PREFIX) ? llm.slice(BEDROCK_PREFIX.length) : null;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Bedrock tool names must match ^[a-zA-Z0-9_-]{1,64}$; long MCP names get a short, stable stand-in.
|
|
16
|
+
function bedrockToolName(name) {
|
|
17
|
+
if (/^[a-zA-Z0-9_-]{1,64}$/.test(name)) return name;
|
|
18
|
+
const hash = createHash('sha1').update(name).digest('hex').slice(0, 8);
|
|
19
|
+
return `${name.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 55)}_${hash}`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function imageBlock(source) {
|
|
23
|
+
const format = IMAGE_FORMATS[source?.media_type];
|
|
24
|
+
if (source?.type !== 'base64' || !format) return { text: '[image in an unsupported format was left out]' };
|
|
25
|
+
return { image: { format, source: { bytes: Buffer.from(source.data, 'base64') } } };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function textOf(content) {
|
|
29
|
+
if (typeof content === 'string') return content;
|
|
30
|
+
return (content || []).map(block => block.type === 'text' ? block.text : `[${block.type}]`).join('\n');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function toolResultContent(content) {
|
|
34
|
+
const blocks = typeof content === 'string' || content == null
|
|
35
|
+
? [{ text: String(content ?? '') }]
|
|
36
|
+
: content.map(block => block.type === 'image' ? imageBlock(block.source) : { text: block.text ?? textOf([block]) });
|
|
37
|
+
const kept = blocks.filter(block => block.image || block.text.trim());
|
|
38
|
+
return kept.length ? kept : [{ text: '(no output)' }];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Claude Code's history can hold tool blocks on a request without tools (titles, compaction); Bedrock refuses tool
|
|
42
|
+
// blocks without a toolConfig, so there they become plain text.
|
|
43
|
+
function convertBlock(block, withTools) {
|
|
44
|
+
switch (block.type) {
|
|
45
|
+
case 'text':
|
|
46
|
+
return block.text.trim() ? { text: block.text } : null;
|
|
47
|
+
case 'image':
|
|
48
|
+
return imageBlock(block.source);
|
|
49
|
+
case 'tool_use':
|
|
50
|
+
return withTools
|
|
51
|
+
? { toolUse: { toolUseId: block.id, name: bedrockToolName(block.name), input: block.input || {} } }
|
|
52
|
+
: { text: `[called tool ${block.name} with ${JSON.stringify(block.input || {})}]` };
|
|
53
|
+
case 'tool_result':
|
|
54
|
+
return withTools
|
|
55
|
+
? { toolResult: { toolUseId: block.tool_use_id, content: toolResultContent(block.content), status: block.is_error ? 'error' : 'success' } }
|
|
56
|
+
: { text: `[tool result]\n${textOf(block.content)}` };
|
|
57
|
+
case 'document':
|
|
58
|
+
return block.source?.type === 'text' ? { text: block.source.data } : { text: '[a document was left out]' };
|
|
59
|
+
default:
|
|
60
|
+
// thinking / redacted_thinking come from other models and carry signatures Bedrock cannot check.
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function toConverse(body, modelId) {
|
|
66
|
+
const tools = (body.tools || []).filter(tool => tool.name && tool.input_schema);
|
|
67
|
+
const withTools = tools.length > 0;
|
|
68
|
+
const merged = [];
|
|
69
|
+
for (const message of body.messages || []) {
|
|
70
|
+
if (message.role !== 'user' && message.role !== 'assistant') continue;
|
|
71
|
+
const blocks = typeof message.content === 'string' ? [{ type: 'text', text: message.content }] : message.content || [];
|
|
72
|
+
const content = blocks.map(block => convertBlock(block, withTools)).filter(Boolean);
|
|
73
|
+
if (!content.length) continue;
|
|
74
|
+
const last = merged.at(-1);
|
|
75
|
+
// Bedrock needs strictly alternating roles; Claude Code sometimes sends two user turns in a row.
|
|
76
|
+
if (last?.role === message.role) last.content.push(...content);
|
|
77
|
+
else merged.push({ role: message.role, content });
|
|
78
|
+
}
|
|
79
|
+
if (merged[0]?.role === 'assistant') merged.unshift({ role: 'user', content: [{ text: '(continue)' }] });
|
|
80
|
+
|
|
81
|
+
const systemText = typeof body.system === 'string' ? body.system : textOf(body.system);
|
|
82
|
+
const request = {
|
|
83
|
+
modelId,
|
|
84
|
+
messages: merged,
|
|
85
|
+
inferenceConfig: { maxTokens: Math.min(body.max_tokens || 32000, MAX_OUTPUT_TOKENS) }
|
|
86
|
+
};
|
|
87
|
+
if (systemText.trim()) request.system = [{ text: systemText }];
|
|
88
|
+
if (typeof body.temperature === 'number') request.inferenceConfig.temperature = body.temperature;
|
|
89
|
+
if (withTools) {
|
|
90
|
+
request.toolConfig = {
|
|
91
|
+
tools: tools.map(tool => {
|
|
92
|
+
const { $schema, ...schema } = tool.input_schema;
|
|
93
|
+
return { toolSpec: { name: bedrockToolName(tool.name), description: tool.description || tool.name, inputSchema: { json: schema } } };
|
|
94
|
+
})
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
const toolNames = new Map(tools.map(tool => [bedrockToolName(tool.name), tool.name]));
|
|
98
|
+
return { request, toolNames };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function readBedrockKey(labsDir) {
|
|
102
|
+
const file = path.join(labsDir, 'bedrock-key');
|
|
103
|
+
return fs.existsSync(file) ? fs.readFileSync(file, 'utf8').trim() : process.env.AWS_BEARER_TOKEN_BEDROCK || null;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function saveBedrockKey(labsDir, key) {
|
|
107
|
+
fs.mkdirSync(labsDir, { recursive: true });
|
|
108
|
+
fs.writeFileSync(path.join(labsDir, 'bedrock-key'), key.trim(), { mode: 0o600 });
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function createBedrockClient({ region, apiKey, requestHandler }) {
|
|
112
|
+
return new BedrockRuntimeClient({
|
|
113
|
+
region,
|
|
114
|
+
token: async () => ({ token: apiKey }),
|
|
115
|
+
authSchemePreference: ['httpBearerAuth'],
|
|
116
|
+
...(requestHandler ? { requestHandler } : {})
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function streamConverse({ client, body, modelId, onText, signal }) {
|
|
121
|
+
const { request, toolNames } = toConverse(body, modelId);
|
|
122
|
+
const response = await client.send(new ConverseStreamCommand(request), { abortSignal: signal });
|
|
123
|
+
let text = '';
|
|
124
|
+
let stopReason = null;
|
|
125
|
+
const usage = { inputTokens: 0, outputTokens: 0 };
|
|
126
|
+
const tools = new Map();
|
|
127
|
+
for await (const event of response.stream) {
|
|
128
|
+
if (event.contentBlockStart?.start?.toolUse) {
|
|
129
|
+
const { toolUseId, name } = event.contentBlockStart.start.toolUse;
|
|
130
|
+
tools.set(event.contentBlockStart.contentBlockIndex, { id: toolUseId, name: toolNames.get(name) || name, json: '' });
|
|
131
|
+
} else if (event.contentBlockDelta) {
|
|
132
|
+
const { delta, contentBlockIndex } = event.contentBlockDelta;
|
|
133
|
+
if (delta.text) {
|
|
134
|
+
text += delta.text;
|
|
135
|
+
if (onText) onText(delta.text);
|
|
136
|
+
} else if (delta.toolUse) {
|
|
137
|
+
tools.get(contentBlockIndex).json += delta.toolUse.input || '';
|
|
138
|
+
}
|
|
139
|
+
} else if (event.messageStop) {
|
|
140
|
+
stopReason = event.messageStop.stopReason;
|
|
141
|
+
} else if (event.metadata?.usage) {
|
|
142
|
+
usage.inputTokens = event.metadata.usage.inputTokens || 0;
|
|
143
|
+
usage.outputTokens = event.metadata.usage.outputTokens || 0;
|
|
144
|
+
} else {
|
|
145
|
+
const failure = Object.entries(event).find(([key]) => key.endsWith('Exception'));
|
|
146
|
+
if (failure) throw new Error(`${failure[0]}: ${failure[1]?.message || 'stream failed'}`);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const toolCalls = [...tools.values()].map(tool => ({ id: tool.id, name: tool.name, input: tool.json ? JSON.parse(tool.json) : {} }));
|
|
150
|
+
return { text, toolCalls, usage, stopReason };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
module.exports = {
|
|
154
|
+
BEDROCK_PREFIX,
|
|
155
|
+
bedrockModelId,
|
|
156
|
+
bedrockToolName,
|
|
157
|
+
createBedrockClient,
|
|
158
|
+
readBedrockKey,
|
|
159
|
+
saveBedrockKey,
|
|
160
|
+
streamConverse,
|
|
161
|
+
toConverse
|
|
162
|
+
};
|