labs-claude 0.1.0 → 0.1.2
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 +60 -60
- package/bin/labs.js +1 -1
- package/package.json +1 -1
- package/src/elevenlabs-tools.js +1 -1
- package/src/proxy.js +474 -438
- package/src/setup.js +1 -1
package/README.md
CHANGED
|
@@ -1,60 +1,60 @@
|
|
|
1
|
-
# labs-claude
|
|
2
|
-
|
|
3
|
-
Run the **real Claude Code CLI** on **ElevenLabs models**: GPT-6 Astra, GPT-6.1 Sol, GPT-5.6 Terra, Claude Opus 5.5, Gemini 3.8 Flash, GLM-52 and more, using your own ElevenLabs credits. It works the way Ollama does: Claude Code stays original (tools, skills, subagents, `/model`, `/resume`, permissions) and only the model behind it changes.
|
|
4
|
-
|
|
5
|
-
## Install
|
|
6
|
-
|
|
7
|
-
```bash
|
|
8
|
-
npm install -g labs-claude
|
|
9
|
-
labs setup
|
|
10
|
-
labs
|
|
11
|
-
```
|
|
12
|
-
|
|
13
|
-
Works on **Windows, macOS and Linux**. You need:
|
|
14
|
-
|
|
15
|
-
- **Node.js 18+**
|
|
16
|
-
- **Claude Code** installed (`claude --version` should work)
|
|
17
|
-
- An **ElevenLabs API key** with ElevenAgents access (elevenlabs.io → Developers → API Keys)
|
|
18
|
-
|
|
19
|
-
`labs setup` checks your key and creates one agent in **your** ElevenLabs account named *Labs Claude Code Bridge*. The key is saved in `~/.labs/config.json`, readable only by you. If `ELEVENLABS_API_KEY` is set in your environment instead, the key is used from there and never written to disk.
|
|
20
|
-
|
|
21
|
-
## Use
|
|
22
|
-
|
|
23
|
-
| Command | What it does |
|
|
24
|
-
|---|---|
|
|
25
|
-
| `labs` | Claude Code on the default model (astra) |
|
|
26
|
-
| `labs --model opus` | Pick a model by short name |
|
|
27
|
-
| `labs --model 5` | Pick by its number in `labs models` |
|
|
28
|
-
| `labs --model gpt-5.4` | Any ElevenLabs LLM id |
|
|
29
|
-
| `labs -p "fix the failing test"` | Any Claude Code flag passes through |
|
|
30
|
-
| `labs --effort
|
|
31
|
-
| `labs models` / `labs models --all` | List models with context and reply sizes |
|
|
32
|
-
| `labs usage` | Credits left, and what recent sessions cost per model (tokens and USD) |
|
|
33
|
-
| `labs stop` | Stop the background proxy |
|
|
34
|
-
|
|
35
|
-
Inside Claude Code, `/model terra` or `/model gpt-6-luna` switches model, and `/effort` changes effort. Claude's own names map to the same models on ElevenLabs (`opus` → `claude-opus-5-5`).
|
|
36
|
-
|
|
37
|
-
## How it works
|
|
38
|
-
|
|
39
|
-
```
|
|
40
|
-
Claude Code ──HTTP (Anthropic API)──> labs proxy on 127.0.0.1:8081 ──WebSocket──> ElevenLabs agent ──> chosen LLM
|
|
41
|
-
```
|
|
42
|
-
|
|
43
|
-
- The proxy forwards Claude Code's real system prompt and its real tools. Each tool is mirrored once into your ElevenLabs account as a client tool.
|
|
44
|
-
- When the model calls a tool, Claude Code runs it on your machine, with its usual permission prompts.
|
|
45
|
-
- Every conversation runs in text-only mode, so no audio is generated.
|
|
46
|
-
|
|
47
|
-
## Limits to know
|
|
48
|
-
|
|
49
|
-
- **Context windows are ElevenLabs' limits:** Astra, Sol and Terra have 272k; Opus 5.5, Sonnet 5.5 and Gemini 3.8 Flash have 1M; GLM, Qwen and DeepSeek have 64k context with 4k replies.
|
|
50
|
-
- **
|
|
51
|
-
- **120-second tool limit:** ElevenLabs waits at most 120 s for a tool result. A command that runs longer can fail that turn.
|
|
52
|
-
- **Usage is billed to your ElevenLabs account.** Check it at elevenlabs.io → Usage.
|
|
53
|
-
|
|
54
|
-
## Files
|
|
55
|
-
|
|
56
|
-
`~/.labs/`: `config.json`, `proxy.log`, `llm-list.json`, `tool-registry-<agent>.json`, `conversations/`
|
|
57
|
-
|
|
58
|
-
## License
|
|
59
|
-
|
|
60
|
-
MIT
|
|
1
|
+
# labs-claude
|
|
2
|
+
|
|
3
|
+
Run the **real Claude Code CLI** on **ElevenLabs models**: GPT-6 Astra, GPT-6.1 Sol, GPT-5.6 Terra, Claude Opus 5.5, Gemini 3.8 Flash, GLM-52 and more, using your own ElevenLabs credits. It works the way Ollama does: Claude Code stays original (tools, skills, subagents, `/model`, `/resume`, permissions) and only the model behind it changes.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install -g labs-claude
|
|
9
|
+
labs setup
|
|
10
|
+
labs
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Works on **Windows, macOS and Linux**. You need:
|
|
14
|
+
|
|
15
|
+
- **Node.js 18+**
|
|
16
|
+
- **Claude Code** installed (`claude --version` should work)
|
|
17
|
+
- An **ElevenLabs API key** with ElevenAgents access (elevenlabs.io → Developers → API Keys)
|
|
18
|
+
|
|
19
|
+
`labs setup` checks your key and creates one agent in **your** ElevenLabs account named *Labs Claude Code Bridge*. The key is saved in `~/.labs/config.json`, readable only by you. If `ELEVENLABS_API_KEY` is set in your environment instead, the key is used from there and never written to disk.
|
|
20
|
+
|
|
21
|
+
## Use
|
|
22
|
+
|
|
23
|
+
| Command | What it does |
|
|
24
|
+
|---|---|
|
|
25
|
+
| `labs` | Claude Code on the default model (astra) |
|
|
26
|
+
| `labs --model opus` | Pick a model by short name |
|
|
27
|
+
| `labs --model 5` | Pick by its number in `labs models` |
|
|
28
|
+
| `labs --model gpt-5.4` | Any ElevenLabs LLM id |
|
|
29
|
+
| `labs -p "fix the failing test"` | Any Claude Code flag passes through |
|
|
30
|
+
| `labs --effort max` | Reasoning effort (default: `high`; lowered automatically if a reply would exceed ElevenLabs time limits) |
|
|
31
|
+
| `labs models` / `labs models --all` | List models with context and reply sizes |
|
|
32
|
+
| `labs usage` | Credits left, and what recent sessions cost per model (tokens and USD) |
|
|
33
|
+
| `labs stop` | Stop the background proxy |
|
|
34
|
+
|
|
35
|
+
Inside Claude Code, `/model terra` or `/model gpt-6-luna` switches model, and `/effort` changes effort. Claude's own names map to the same models on ElevenLabs (`opus` → `claude-opus-5-5`).
|
|
36
|
+
|
|
37
|
+
## How it works
|
|
38
|
+
|
|
39
|
+
```
|
|
40
|
+
Claude Code ──HTTP (Anthropic API)──> labs proxy on 127.0.0.1:8081 ──WebSocket──> ElevenLabs agent ──> chosen LLM
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
- The proxy forwards Claude Code's real system prompt and its real tools. Each tool is mirrored once into your ElevenLabs account as a client tool.
|
|
44
|
+
- When the model calls a tool, Claude Code runs it on your machine, with its usual permission prompts.
|
|
45
|
+
- Every conversation runs in text-only mode, so no audio is generated.
|
|
46
|
+
|
|
47
|
+
## Limits to know
|
|
48
|
+
|
|
49
|
+
- **Context windows are ElevenLabs' limits:** Astra, Sol and Terra have 272k; Opus 5.5, Sonnet 5.5 and Gemini 3.8 Flash have 1M; GLM, Qwen and DeepSeek have 64k context with 4k replies.
|
|
50
|
+
- **About 50 seconds per reply:** ElevenLabs cuts any single reply (thinking plus writing) after roughly 50 s. labs asks the model to write big files in parts of about 80 lines, and lowers effort automatically if a reply still runs over.
|
|
51
|
+
- **120-second tool limit:** ElevenLabs waits at most 120 s for a tool result. A command that runs longer can fail that turn.
|
|
52
|
+
- **Usage is billed to your ElevenLabs account.** Check it at elevenlabs.io → Usage.
|
|
53
|
+
|
|
54
|
+
## Files
|
|
55
|
+
|
|
56
|
+
`~/.labs/`: `config.json`, `proxy.log`, `llm-list.json`, `tool-registry-<agent>.json`, `conversations/`
|
|
57
|
+
|
|
58
|
+
## License
|
|
59
|
+
|
|
60
|
+
MIT
|
package/bin/labs.js
CHANGED
|
@@ -87,7 +87,7 @@ async function main() {
|
|
|
87
87
|
const llm = config.models[modelName] || modelName;
|
|
88
88
|
const llmInfo = loadLlmList().find(item => item.llm === llm);
|
|
89
89
|
if (!claudeArgs.some(arg => arg === '--effort' || arg.startsWith('--effort='))) {
|
|
90
|
-
claudeArgs.push('--effort', config.defaultEffort || '
|
|
90
|
+
claudeArgs.push('--effort', config.defaultEffort || 'high');
|
|
91
91
|
}
|
|
92
92
|
|
|
93
93
|
const env = {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "labs-claude",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
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": { "labs": "bin/labs.js" },
|
|
6
6
|
"files": ["bin", "src", "README.md"],
|
package/src/elevenlabs-tools.js
CHANGED
package/src/proxy.js
CHANGED
|
@@ -1,438 +1,474 @@
|
|
|
1
|
-
const express = require('express');
|
|
2
|
-
const axios = require('axios');
|
|
3
|
-
const bodyParser = require('body-parser');
|
|
4
|
-
const fs = require('fs');
|
|
5
|
-
const path = require('path');
|
|
6
|
-
const { createHash } = require('crypto');
|
|
7
|
-
const { execFileSync } = require('child_process');
|
|
8
|
-
const WebSocket = require('ws');
|
|
9
|
-
const {
|
|
10
|
-
createAnthropicEvents,
|
|
11
|
-
createAnthropicMessage,
|
|
12
|
-
createThreadId,
|
|
13
|
-
extractLatestUserContent,
|
|
14
|
-
formatConversationHistory,
|
|
15
|
-
isValidSessionId,
|
|
16
|
-
resolveLlm,
|
|
17
|
-
writeAnthropicEvents
|
|
18
|
-
} = require('./anthropic-protocol');
|
|
19
|
-
const { ToolRegistry } = require('./elevenlabs-tools');
|
|
20
|
-
const { API_BASE, LABS_DIR, loadConfig, loadLlmList, saveLlmList } = require('./config');
|
|
21
|
-
const { version: VERSION } = require('../package.json');
|
|
22
|
-
|
|
23
|
-
console.log(`=== labs-claude proxy ${VERSION} ===`);
|
|
24
|
-
|
|
25
|
-
const SETTLE_MS = 800;
|
|
26
|
-
const REQUEST_TIMEOUT_MS = 600000;
|
|
27
|
-
const MAX_REPLAY_CHARS = 120000;
|
|
28
|
-
const CONVERSATIONS_DIR = path.join(LABS_DIR, 'conversations');
|
|
29
|
-
|
|
30
|
-
const config = loadConfig();
|
|
31
|
-
if (!config?.apiKey || !config.bridgeAgent) {
|
|
32
|
-
console.error('❌ Not set up. Run: labs setup');
|
|
33
|
-
process.exit(1);
|
|
34
|
-
}
|
|
35
|
-
const PORT = config.port;
|
|
36
|
-
const HEADERS = { 'xi-api-key': config.apiKey };
|
|
37
|
-
const aliases = config.models;
|
|
38
|
-
let llmList = loadLlmList();
|
|
39
|
-
let llmIds = new Set(llmList.map(item => item.llm));
|
|
40
|
-
const EFFORT_ORDER = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
|
41
|
-
|
|
42
|
-
|
|
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
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
//
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
console.
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
function
|
|
266
|
-
|
|
267
|
-
if (!
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
conn.
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
})
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
const
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
1
|
+
const express = require('express');
|
|
2
|
+
const axios = require('axios');
|
|
3
|
+
const bodyParser = require('body-parser');
|
|
4
|
+
const fs = require('fs');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const { createHash } = require('crypto');
|
|
7
|
+
const { execFileSync } = require('child_process');
|
|
8
|
+
const WebSocket = require('ws');
|
|
9
|
+
const {
|
|
10
|
+
createAnthropicEvents,
|
|
11
|
+
createAnthropicMessage,
|
|
12
|
+
createThreadId,
|
|
13
|
+
extractLatestUserContent,
|
|
14
|
+
formatConversationHistory,
|
|
15
|
+
isValidSessionId,
|
|
16
|
+
resolveLlm,
|
|
17
|
+
writeAnthropicEvents
|
|
18
|
+
} = require('./anthropic-protocol');
|
|
19
|
+
const { ToolRegistry } = require('./elevenlabs-tools');
|
|
20
|
+
const { API_BASE, LABS_DIR, loadConfig, loadLlmList, saveLlmList } = require('./config');
|
|
21
|
+
const { version: VERSION } = require('../package.json');
|
|
22
|
+
|
|
23
|
+
console.log(`=== labs-claude proxy ${VERSION} ===`);
|
|
24
|
+
|
|
25
|
+
const SETTLE_MS = 800;
|
|
26
|
+
const REQUEST_TIMEOUT_MS = 600000;
|
|
27
|
+
const MAX_REPLAY_CHARS = 120000;
|
|
28
|
+
const CONVERSATIONS_DIR = path.join(LABS_DIR, 'conversations');
|
|
29
|
+
|
|
30
|
+
const config = loadConfig();
|
|
31
|
+
if (!config?.apiKey || !config.bridgeAgent) {
|
|
32
|
+
console.error('❌ Not set up. Run: labs setup');
|
|
33
|
+
process.exit(1);
|
|
34
|
+
}
|
|
35
|
+
const PORT = config.port;
|
|
36
|
+
const HEADERS = { 'xi-api-key': config.apiKey };
|
|
37
|
+
const aliases = config.models;
|
|
38
|
+
let llmList = loadLlmList();
|
|
39
|
+
let llmIds = new Set(llmList.map(item => item.llm));
|
|
40
|
+
const EFFORT_ORDER = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
|
41
|
+
|
|
42
|
+
// Every tool definition is re-read at the start of each ElevenLabs conversation, and ElevenLabs drops a reply whose
|
|
43
|
+
// first token takes over 15 s, so only Claude Code's coding tools and MCP tools are forwarded.
|
|
44
|
+
const FORWARDED_BUILTINS = new Set([
|
|
45
|
+
'Agent', 'Task', 'Bash', 'PowerShell', 'Read', 'Write', 'Edit', 'MultiEdit', 'Glob', 'Grep',
|
|
46
|
+
'WebFetch', 'WebSearch', 'Skill', 'ToolSearch', 'TodoWrite', 'NotebookEdit'
|
|
47
|
+
]);
|
|
48
|
+
|
|
49
|
+
function isForwardedTool(tool) {
|
|
50
|
+
return FORWARDED_BUILTINS.has(tool.name) || tool.name.startsWith('mcp__');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// ElevenLabs cuts any single reply after about 50 s (thinking plus writing, measured), so one Write of a whole file
|
|
54
|
+
// fails; the model is asked to build files in small steps instead.
|
|
55
|
+
const BRIDGE_NOTE = [
|
|
56
|
+
'',
|
|
57
|
+
'',
|
|
58
|
+
'# Output limits of this connection',
|
|
59
|
+
'Every reply (your thinking plus your output) must finish within about 40 seconds or it is cut off.',
|
|
60
|
+
'Never put more than about 80 lines of code in one Write or Edit call.',
|
|
61
|
+
'Build longer files in steps: Write the first part, then add the rest with further Edit calls, one part per reply.'
|
|
62
|
+
].join('\n');
|
|
63
|
+
|
|
64
|
+
const toolRegistry = new ToolRegistry({
|
|
65
|
+
http: axios,
|
|
66
|
+
apiBase: API_BASE,
|
|
67
|
+
headers: HEADERS,
|
|
68
|
+
file: path.join(LABS_DIR, `tool-registry-${config.bridgeAgent}.json`),
|
|
69
|
+
agentId: config.bridgeAgent
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
async function refreshLlmList() {
|
|
73
|
+
try {
|
|
74
|
+
const response = await axios.get(`${API_BASE}/llm/list`, { headers: HEADERS });
|
|
75
|
+
saveLlmList(response.data.llms);
|
|
76
|
+
llmList = response.data.llms;
|
|
77
|
+
llmIds = new Set(llmList.map(item => item.llm));
|
|
78
|
+
console.log(`📋 ${llmIds.size} ElevenLabs LLMs available`);
|
|
79
|
+
} catch (error) {
|
|
80
|
+
console.error(`⚠️ Could not refresh LLM list, using cached copy: ${error.message}`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Effort and reply length are agent-level settings on ElevenLabs (not per-conversation overrides), so the bridge
|
|
85
|
+
// agent is re-pointed before each new conversation; the queue keeps concurrent opens from racing each other.
|
|
86
|
+
// ElevenLabs drops a turn whose first token takes longer than 15 s (cascade_timeout_seconds), which very high
|
|
87
|
+
// effort can exceed; the highest effort that answered in time is remembered per LLM for the proxy's lifetime.
|
|
88
|
+
const effortCaps = new Map();
|
|
89
|
+
|
|
90
|
+
function lowerEffortCap(llm, failedEffort) {
|
|
91
|
+
const efforts = (llmList.find(item => item.llm === llm)?.available_reasoning_efforts || [])
|
|
92
|
+
.filter(option => EFFORT_ORDER.indexOf(option) < EFFORT_ORDER.indexOf(failedEffort));
|
|
93
|
+
if (!efforts.length) return false;
|
|
94
|
+
effortCaps.set(llm, efforts.reduce((best, option) => EFFORT_ORDER.indexOf(option) > EFFORT_ORDER.indexOf(best) ? option : best));
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function agentSettingsFor(llm, requestedEffort, requestedMaxTokens) {
|
|
99
|
+
const info = llmList.find(item => item.llm === llm) || {};
|
|
100
|
+
const efforts = info.available_reasoning_efforts || [];
|
|
101
|
+
const cap = effortCaps.get(llm);
|
|
102
|
+
const capped = cap && EFFORT_ORDER.indexOf(requestedEffort) > EFFORT_ORDER.indexOf(cap) ? cap : requestedEffort;
|
|
103
|
+
const wanted = EFFORT_ORDER.indexOf(capped);
|
|
104
|
+
const effort = efforts.length
|
|
105
|
+
? efforts.reduce((best, option) => Math.abs(EFFORT_ORDER.indexOf(option) - wanted) < Math.abs(EFFORT_ORDER.indexOf(best) - wanted) ? option : best)
|
|
106
|
+
: null;
|
|
107
|
+
// Always the model's full reply length: Claude Code's own max_tokens is sized for Anthropic models.
|
|
108
|
+
return { llm, reasoning_effort: effort, max_tokens: info.max_tokens_limit || requestedMaxTokens || 4096 };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
let settingsQueue = Promise.resolve();
|
|
112
|
+
let appliedSettings = '';
|
|
113
|
+
|
|
114
|
+
function withAgentSettings(settings, openFn) {
|
|
115
|
+
const run = async () => {
|
|
116
|
+
const key = JSON.stringify(settings);
|
|
117
|
+
if (key !== appliedSettings) {
|
|
118
|
+
// An explicit null is required: an effort left over from the previous LLM makes ElevenLabs reject the switch.
|
|
119
|
+
const prompt = {
|
|
120
|
+
llm: settings.llm,
|
|
121
|
+
max_tokens: settings.max_tokens,
|
|
122
|
+
reasoning_effort: settings.reasoning_effort,
|
|
123
|
+
// Voice defaults: 4 s to first token, then silently fall back to another LLM. 15 s is ElevenLabs' maximum.
|
|
124
|
+
cascade_timeout_seconds: 15,
|
|
125
|
+
// Streaming a reasoning summary counts as the first output, so long thinking no longer trips the 15 s
|
|
126
|
+
// first-token cancel (measured: Opus at max effort answered at 27.8 s with it, was cancelled without).
|
|
127
|
+
enable_reasoning_summary: Boolean(settings.reasoning_effort),
|
|
128
|
+
backup_llm_config: { preference: 'disabled' }
|
|
129
|
+
};
|
|
130
|
+
// Conversations default to 600 s on new agents; 7200 s is the API maximum.
|
|
131
|
+
await axios.patch(`${API_BASE}/agents/${config.bridgeAgent}`,
|
|
132
|
+
{ conversation_config: { agent: { prompt }, conversation: { max_duration_seconds: 7200 } } }, { headers: HEADERS });
|
|
133
|
+
appliedSettings = key;
|
|
134
|
+
console.log(`🎚️ Bridge set to ${settings.llm} effort=${settings.reasoning_effort || 'n/a'} max_tokens=${settings.max_tokens}`);
|
|
135
|
+
}
|
|
136
|
+
const conn = openFn();
|
|
137
|
+
await conn.ready;
|
|
138
|
+
return conn;
|
|
139
|
+
};
|
|
140
|
+
const next = settingsQueue.then(run, run);
|
|
141
|
+
settingsQueue = next.catch(() => {});
|
|
142
|
+
return next;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// ============================================
|
|
146
|
+
// WEBSOCKET CONVERSATIONS: one per (LLM, Claude Code thread, tool set)
|
|
147
|
+
// ============================================
|
|
148
|
+
|
|
149
|
+
const connections = new Map();
|
|
150
|
+
|
|
151
|
+
function systemText(system) {
|
|
152
|
+
if (typeof system === 'string') return system;
|
|
153
|
+
return Array.isArray(system) ? system.map(block => block.text || '').join('\n\n') : '';
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function openConversation(key, { llm, prompt, toolIds }) {
|
|
157
|
+
const existing = connections.get(key);
|
|
158
|
+
// A socket still CONNECTING must be awaited, not replaced: replacing it routed the old socket's events into the new one.
|
|
159
|
+
if (existing && [WebSocket.OPEN, WebSocket.CONNECTING].includes(existing.ws.readyState)) return existing;
|
|
160
|
+
|
|
161
|
+
console.log(`🔌 Opening ${llm} conversation (${toolIds.length} tools) for ${key}`);
|
|
162
|
+
const ws = new WebSocket(`wss://api.elevenlabs.io/v1/convai/conversation?agent_id=${config.bridgeAgent}`, { headers: HEADERS });
|
|
163
|
+
const conn = {
|
|
164
|
+
ws,
|
|
165
|
+
llm,
|
|
166
|
+
pending: null,
|
|
167
|
+
messageId: 0,
|
|
168
|
+
conversationId: null,
|
|
169
|
+
contextTokens: 0,
|
|
170
|
+
openToolCallIds: new Set(),
|
|
171
|
+
closeReason: ''
|
|
172
|
+
};
|
|
173
|
+
connections.set(key, conn);
|
|
174
|
+
|
|
175
|
+
conn.ready = new Promise((resolve, reject) => {
|
|
176
|
+
ws.on('open', () => {
|
|
177
|
+
ws.send(JSON.stringify({
|
|
178
|
+
type: 'conversation_initiation_client_data',
|
|
179
|
+
conversation_config_override: {
|
|
180
|
+
conversation: { text_only: true },
|
|
181
|
+
agent: { first_message: '', prompt: { prompt, llm, tool_ids: toolIds } }
|
|
182
|
+
}
|
|
183
|
+
}));
|
|
184
|
+
conn.markReady = resolve;
|
|
185
|
+
});
|
|
186
|
+
ws.on('error', error => {
|
|
187
|
+
console.error(`🚨 WS error for ${key}: ${error.message}`);
|
|
188
|
+
reject(error);
|
|
189
|
+
});
|
|
190
|
+
ws.on('close', (code, reason) => {
|
|
191
|
+
conn.closeReason = `code ${code}${reason?.length ? `: ${reason}` : ''}`;
|
|
192
|
+
console.log(`🔌 Conversation closed for ${key} (${conn.closeReason})`);
|
|
193
|
+
reject(new Error(`ElevenLabs closed the conversation (${conn.closeReason})`));
|
|
194
|
+
if (conn.pending) settle(conn, { error: new Error(`ElevenLabs closed the conversation (${conn.closeReason})`) });
|
|
195
|
+
connections.delete(key);
|
|
196
|
+
});
|
|
197
|
+
});
|
|
198
|
+
conn.ready.catch(() => {});
|
|
199
|
+
|
|
200
|
+
ws.on('message', data => {
|
|
201
|
+
try {
|
|
202
|
+
handleEvent(conn, JSON.parse(data.toString()));
|
|
203
|
+
} catch (error) {
|
|
204
|
+
console.error(`⚠️ WS event error: ${error.message}`);
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
return conn;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function handleEvent(conn, msg) {
|
|
211
|
+
switch (msg.type) {
|
|
212
|
+
case 'conversation_initiation_metadata':
|
|
213
|
+
conn.conversationId = msg.conversation_initiation_metadata_event?.conversation_id;
|
|
214
|
+
console.log(`📋 Conversation ${conn.conversationId} on ${conn.llm}`);
|
|
215
|
+
conn.markReady?.(conn);
|
|
216
|
+
break;
|
|
217
|
+
case 'ping':
|
|
218
|
+
// The server expects the ping's event_id echoed back; a bare pong lets the connection die.
|
|
219
|
+
conn.ws.send(JSON.stringify({ type: 'pong', event_id: msg.ping_event?.event_id }));
|
|
220
|
+
break;
|
|
221
|
+
case 'agent_response': {
|
|
222
|
+
if (!conn.pending) break;
|
|
223
|
+
const text = msg.agent_response_event?.agent_response || '';
|
|
224
|
+
conn.pending.text = conn.pending.text ? `${conn.pending.text}\n\n${text}` : text;
|
|
225
|
+
settleSoon(conn);
|
|
226
|
+
break;
|
|
227
|
+
}
|
|
228
|
+
case 'client_tool_call':
|
|
229
|
+
handleToolCall(conn, msg.client_tool_call);
|
|
230
|
+
break;
|
|
231
|
+
case 'context_usage':
|
|
232
|
+
conn.contextTokens = msg.context_usage_event?.context_tokens || conn.contextTokens;
|
|
233
|
+
break;
|
|
234
|
+
case 'client_error':
|
|
235
|
+
console.error(`🚨 ElevenLabs client_error: ${JSON.stringify(msg.error_event)}`);
|
|
236
|
+
break;
|
|
237
|
+
default:
|
|
238
|
+
break;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function handleToolCall(conn, call) {
|
|
243
|
+
if (!call?.tool_name || !call.tool_call_id) return;
|
|
244
|
+
if (!conn.pending) {
|
|
245
|
+
// Arrived after the turn was already returned; answering keeps the agent from waiting forever.
|
|
246
|
+
conn.ws.send(JSON.stringify({
|
|
247
|
+
type: 'client_tool_result', tool_call_id: call.tool_call_id, is_error: true,
|
|
248
|
+
result: 'This tool call arrived after the turn ended. Request it again in your next turn.'
|
|
249
|
+
}));
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
const name = toolRegistry.claudeNameFor(call.tool_name);
|
|
253
|
+
if (call.parameters) call.parameters = withWindowsPaths(call.parameters);
|
|
254
|
+
console.log(`🔧 ${name} ${JSON.stringify(call.parameters || {}).slice(0, 160)}`);
|
|
255
|
+
conn.pending.toolCalls.push({ id: call.tool_call_id, name, input: call.parameters || {} });
|
|
256
|
+
conn.openToolCallIds.add(call.tool_call_id);
|
|
257
|
+
settleSoon(conn);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// On Windows, models copy Git Bash paths (/tmp/..., /c/Users/...) from `pwd` into file tools; Claude Code reads those
|
|
261
|
+
// as outside the project and asks for permission. Git's own cygpath gives the exact Windows equivalent.
|
|
262
|
+
const PATH_KEYS = ['file_path', 'path', 'notebook_path'];
|
|
263
|
+
const windowsPathCache = new Map();
|
|
264
|
+
|
|
265
|
+
function toWindowsPath(value) {
|
|
266
|
+
if (process.platform !== 'win32' || typeof value !== 'string' || !value.startsWith('/')) return value;
|
|
267
|
+
if (!windowsPathCache.has(value)) {
|
|
268
|
+
let converted = value.replace(/^\/([a-zA-Z])(\/|$)/, (match, drive) => `${drive.toUpperCase()}:\\`).replace(/\//g, '\\');
|
|
269
|
+
try {
|
|
270
|
+
converted = execFileSync('cygpath', ['-w', value], { encoding: 'utf8', windowsHide: true }).trim() || converted;
|
|
271
|
+
} catch {
|
|
272
|
+
// cygpath missing: the drive-letter rewrite above is the best available guess.
|
|
273
|
+
}
|
|
274
|
+
windowsPathCache.set(value, converted);
|
|
275
|
+
}
|
|
276
|
+
return windowsPathCache.get(value);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function withWindowsPaths(input) {
|
|
280
|
+
const output = { ...input };
|
|
281
|
+
for (const key of PATH_KEYS) output[key] = toWindowsPath(output[key]);
|
|
282
|
+
for (const key of PATH_KEYS) if (output[key] === undefined) delete output[key];
|
|
283
|
+
return output;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// The agent can emit text and several tool calls for one turn as separate events, so settle after a short quiet gap.
|
|
287
|
+
function settleSoon(conn) {
|
|
288
|
+
clearTimeout(conn.pending.settleTimer);
|
|
289
|
+
conn.pending.settleTimer = setTimeout(() => settle(conn, null), SETTLE_MS);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function settle(conn, failure) {
|
|
293
|
+
const pending = conn.pending;
|
|
294
|
+
if (!pending) return;
|
|
295
|
+
conn.pending = null;
|
|
296
|
+
clearTimeout(pending.settleTimer);
|
|
297
|
+
clearTimeout(pending.timeout);
|
|
298
|
+
if (failure?.error) pending.reject(failure.error);
|
|
299
|
+
else pending.resolve({ text: pending.text, toolCalls: pending.toolCalls });
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function sendTurn(conn, { text, toolResults, history }) {
|
|
303
|
+
if (conn.pending) throw new Error('A request is already active for this conversation');
|
|
304
|
+
const requestId = String(++conn.messageId);
|
|
305
|
+
|
|
306
|
+
return new Promise((resolve, reject) => {
|
|
307
|
+
conn.pending = { resolve, reject, text: '', toolCalls: [], settleTimer: null };
|
|
308
|
+
conn.pending.timeout = setTimeout(
|
|
309
|
+
() => settle(conn, { error: new Error(`No reply from ${conn.llm} within ${REQUEST_TIMEOUT_MS / 1000}s`) }),
|
|
310
|
+
REQUEST_TIMEOUT_MS
|
|
311
|
+
);
|
|
312
|
+
|
|
313
|
+
// Claude Code resends the whole thread every turn, so a fresh conversation (reconnect, /model switch,
|
|
314
|
+
// --resume, compaction) is seeded from what Claude Code sent.
|
|
315
|
+
if (conn.messageId === 1 && history.length) {
|
|
316
|
+
conn.ws.send(JSON.stringify({
|
|
317
|
+
type: 'contextual_update',
|
|
318
|
+
text: `Conversation so far:\n${formatConversationHistory(history).slice(-MAX_REPLAY_CHARS)}`
|
|
319
|
+
}));
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
const known = toolResults.filter(result => conn.openToolCallIds.has(result.toolUseId));
|
|
323
|
+
if (toolResults.length && known.length === toolResults.length) {
|
|
324
|
+
for (const result of toolResults) {
|
|
325
|
+
conn.openToolCallIds.delete(result.toolUseId);
|
|
326
|
+
conn.ws.send(JSON.stringify({
|
|
327
|
+
type: 'client_tool_result',
|
|
328
|
+
tool_call_id: result.toolUseId,
|
|
329
|
+
result: result.content,
|
|
330
|
+
is_error: result.isError
|
|
331
|
+
}));
|
|
332
|
+
}
|
|
333
|
+
if (text) conn.ws.send(JSON.stringify({ type: 'contextual_update', text }));
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// Results for calls this conversation never made (it was reopened) go in as text, otherwise the agent
|
|
338
|
+
// waits on tool_call_ids it does not know and never answers.
|
|
339
|
+
const resultText = toolResults
|
|
340
|
+
.map(result => `${result.isError ? 'Tool error' : 'Tool result'} (${result.toolUseId}):\n${result.content}`)
|
|
341
|
+
.join('\n\n');
|
|
342
|
+
conn.ws.send(JSON.stringify({
|
|
343
|
+
type: 'user_message',
|
|
344
|
+
id: requestId,
|
|
345
|
+
text: [resultText, text, resultText ? 'Continue the task from here.' : ''].filter(Boolean).join('\n\n')
|
|
346
|
+
}));
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function saveConversation(threadId, llm, conversationId, messages) {
|
|
351
|
+
if (!fs.existsSync(CONVERSATIONS_DIR)) fs.mkdirSync(CONVERSATIONS_DIR, { recursive: true });
|
|
352
|
+
fs.writeFileSync(path.join(CONVERSATIONS_DIR, `${threadId}.json`),
|
|
353
|
+
JSON.stringify({ llm, conversationId, history: messages, updatedAt: Date.now() }, null, 1));
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
function anthropicError(res, status, type, message) {
|
|
357
|
+
return res.status(status).json({ type: 'error', error: { type, message } });
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// ============================================
|
|
361
|
+
// HTTP: Anthropic Messages API
|
|
362
|
+
// ============================================
|
|
363
|
+
|
|
364
|
+
const app = express();
|
|
365
|
+
app.use(bodyParser.json({ limit: '50mb' }));
|
|
366
|
+
|
|
367
|
+
app.post('/v1/messages', async (req, res) => {
|
|
368
|
+
const { model, messages = [], system, stream, metadata, tools = [], max_tokens: maxTokens, output_config: outputConfig } = req.body;
|
|
369
|
+
const launchModel = req.get('x-labs-model');
|
|
370
|
+
// Claude Code answers repeated errors by falling back opus -> sonnet -> haiku on its own; on the main thread
|
|
371
|
+
// (tools present) a Claude id therefore means "fallback", so stay on the model the user launched with.
|
|
372
|
+
const isClaudeFallback = /^claude-/.test(model || '') && (req.body.tools || []).length > 0 && Boolean(launchModel);
|
|
373
|
+
const llm = resolveLlm(isClaudeFallback ? launchModel : model, launchModel, aliases, llmIds);
|
|
374
|
+
console.log(`\n🤖 ${model} -> ${llm || 'UNKNOWN'} | ${messages.length} messages | ${tools.length} tools`);
|
|
375
|
+
if (!llm) return anthropicError(res, 400, 'invalid_request_error', `Unknown model "${model}". Run "labs models" to list models.`);
|
|
376
|
+
|
|
377
|
+
try {
|
|
378
|
+
const latest = extractLatestUserContent(messages);
|
|
379
|
+
if (!latest.text && latest.toolResults.length === 0) {
|
|
380
|
+
return anthropicError(res, 400, 'invalid_request_error', 'No text or tool result in the latest user message');
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// Claude Code's side calls (titles, summaries) carry no tools; keep them out of the coding conversation.
|
|
384
|
+
const isSideRequest = tools.length === 0;
|
|
385
|
+
const sessionId = req.get('x-labs-session-id') || metadata?.session_id || `side_${Date.now()}`;
|
|
386
|
+
const threadId = isValidSessionId(sessionId) ? createThreadId(sessionId, messages) : createThreadId('anon', messages);
|
|
387
|
+
const toolIds = isSideRequest ? [] : await toolRegistry.ensure(tools.filter(isForwardedTool));
|
|
388
|
+
const toolSetHash = createHash('sha1').update(toolIds.join(',')).digest('hex').slice(0, 8);
|
|
389
|
+
let conn;
|
|
390
|
+
let result;
|
|
391
|
+
for (;;) {
|
|
392
|
+
const settings = agentSettingsFor(llm, outputConfig?.effort || 'high', maxTokens);
|
|
393
|
+
const key = isSideRequest
|
|
394
|
+
? `side_${Date.now()}_${Math.random().toString(36).slice(2)}`
|
|
395
|
+
: `${llm}:${settings.reasoning_effort}:${threadId}:${toolSetHash}`;
|
|
396
|
+
const existing = connections.get(key);
|
|
397
|
+
conn = existing && existing.ws.readyState === WebSocket.OPEN
|
|
398
|
+
? existing
|
|
399
|
+
: await withAgentSettings(settings, () => openConversation(key, { llm, prompt: `${systemText(system) || 'You are a helpful assistant.'}${BRIDGE_NOTE}`, toolIds }));
|
|
400
|
+
try {
|
|
401
|
+
result = await sendTurn(conn, { text: latest.text, toolResults: latest.toolResults, history: messages.slice(0, -1) });
|
|
402
|
+
break;
|
|
403
|
+
} catch (error) {
|
|
404
|
+
if (!/Cascade Error: TimeoutError|took too long/.test(error.message) || !lowerEffortCap(llm, settings.reasoning_effort)) throw error;
|
|
405
|
+
console.log(`🎚️ ${llm} too slow at effort=${settings.reasoning_effort}; retrying at ${effortCaps.get(llm)}`);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// Claude Code decides when to auto-compact from input_tokens, so report the whole request, not just the last turn.
|
|
410
|
+
// Base64 images and documents are thousands of characters but roughly 1.5k tokens each to a model; counting
|
|
411
|
+
// their raw length made Claude Code believe the window was full and compact after every prompt.
|
|
412
|
+
const IMAGE_TOKENS_AS_CHARS = 6000;
|
|
413
|
+
const withoutBinary = JSON.stringify(messages, (field, value) =>
|
|
414
|
+
field === 'data' && typeof value === 'string' && value.length > IMAGE_TOKENS_AS_CHARS ? 'x'.repeat(IMAGE_TOKENS_AS_CHARS) : value);
|
|
415
|
+
const requestChars = JSON.stringify(system || '').length + withoutBinary.length + JSON.stringify(tools.filter(isForwardedTool)).length;
|
|
416
|
+
const message = createAnthropicMessage({
|
|
417
|
+
model,
|
|
418
|
+
text: result.text || '',
|
|
419
|
+
toolCalls: result.toolCalls || [],
|
|
420
|
+
inputTokens: conn.contextTokens || Math.ceil(requestChars / 4)
|
|
421
|
+
});
|
|
422
|
+
|
|
423
|
+
if (isSideRequest) conn.ws.close();
|
|
424
|
+
else saveConversation(threadId, llm, conn.conversationId, [...messages, { role: 'assistant', content: message.content }]);
|
|
425
|
+
|
|
426
|
+
return stream ? writeAnthropicEvents(res, createAnthropicEvents(message)) : res.json(message);
|
|
427
|
+
} catch (error) {
|
|
428
|
+
console.error(`🚨 ${llm}: ${error.message}`);
|
|
429
|
+
// 500, not 529: Claude Code retries a 500 on the same model, but answers repeated 529s by switching models.
|
|
430
|
+
if (!res.headersSent) return anthropicError(res, 500, 'api_error', `ElevenLabs ${llm}: ${error.message}`);
|
|
431
|
+
}
|
|
432
|
+
});
|
|
433
|
+
|
|
434
|
+
app.get('/health', (req, res) => res.json({ name: 'labs-claude', version: VERSION }));
|
|
435
|
+
|
|
436
|
+
app.post('/shutdown', (req, res) => {
|
|
437
|
+
res.json({ ok: true });
|
|
438
|
+
setTimeout(() => process.exit(0), 100);
|
|
439
|
+
});
|
|
440
|
+
|
|
441
|
+
app.get('/v1/models', (req, res) => {
|
|
442
|
+
res.json({ data: Object.entries(aliases).map(([id, llm]) => ({ id, type: 'model', display_name: `${id} (${llm})` })) });
|
|
443
|
+
});
|
|
444
|
+
|
|
445
|
+
app.get('/v1/sessions', (req, res) => {
|
|
446
|
+
if (!fs.existsSync(CONVERSATIONS_DIR)) return res.json({ sessions: [] });
|
|
447
|
+
const sessions = fs.readdirSync(CONVERSATIONS_DIR).filter(file => file.endsWith('.json')).map(file => {
|
|
448
|
+
const data = JSON.parse(fs.readFileSync(path.join(CONVERSATIONS_DIR, file), 'utf8'));
|
|
449
|
+
return { id: file.replace('.json', ''), llm: data.llm || data.agentId, messageCount: (data.history || []).length, updatedAt: data.updatedAt };
|
|
450
|
+
});
|
|
451
|
+
res.json({ sessions: sessions.sort((a, b) => b.updatedAt - a.updatedAt) });
|
|
452
|
+
});
|
|
453
|
+
|
|
454
|
+
app.delete('/v1/sessions/:sessionId', (req, res) => {
|
|
455
|
+
const { sessionId } = req.params;
|
|
456
|
+
if (!isValidSessionId(sessionId)) return res.status(400).json({ error: 'Invalid session ID' });
|
|
457
|
+
const filePath = path.join(CONVERSATIONS_DIR, `${sessionId}.json`);
|
|
458
|
+
if (!fs.existsSync(filePath)) return res.status(404).json({ error: 'Session not found' });
|
|
459
|
+
fs.unlinkSync(filePath);
|
|
460
|
+
res.json({ success: true });
|
|
461
|
+
});
|
|
462
|
+
|
|
463
|
+
process.on('uncaughtException', error => console.error(`💥 Uncaught: ${error.stack}`));
|
|
464
|
+
process.on('unhandledRejection', error => console.error(`💥 Unhandled rejection: ${error?.stack || error}`));
|
|
465
|
+
|
|
466
|
+
process.on('SIGINT', () => {
|
|
467
|
+
connections.forEach(conn => conn.ws.close());
|
|
468
|
+
process.exit(0);
|
|
469
|
+
});
|
|
470
|
+
|
|
471
|
+
app.listen(PORT, '127.0.0.1', () => {
|
|
472
|
+
console.log(`✅ Proxy LIVE at http://localhost:${PORT} | bridge agent ${config.bridgeAgent}`);
|
|
473
|
+
refreshLlmList();
|
|
474
|
+
});
|
package/src/setup.js
CHANGED
|
@@ -46,7 +46,7 @@ async function createBridgeAgent(headers) {
|
|
|
46
46
|
backup_llm_config: { preference: 'disabled' }
|
|
47
47
|
}
|
|
48
48
|
},
|
|
49
|
-
conversation: { text_only: true }
|
|
49
|
+
conversation: { text_only: true, max_duration_seconds: 7200 }
|
|
50
50
|
},
|
|
51
51
|
platform_settings: {
|
|
52
52
|
// Post-conversation analysis adds nothing for a coding bridge.
|