labs-claude 0.1.0 → 0.1.4
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/anthropic-protocol.js +15 -2
- package/src/elevenlabs-tools.js +1 -1
- package/src/proxy.js +99 -20
- 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.4",
|
|
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"],
|
|
@@ -26,6 +26,18 @@ function contentToText(content) {
|
|
|
26
26
|
}).filter(Boolean).join('\n\n');
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
+
// Base64 images and PDFs in the user turn, including those nested in tool results (screenshots, Read of a .png).
|
|
30
|
+
function collectImages(blocks) {
|
|
31
|
+
const found = [];
|
|
32
|
+
for (const block of blocks || []) {
|
|
33
|
+
if ((block.type === 'image' || block.type === 'document') && block.source?.type === 'base64') {
|
|
34
|
+
found.push({ mediaType: block.source.media_type, data: block.source.data });
|
|
35
|
+
}
|
|
36
|
+
if (block.type === 'tool_result' && Array.isArray(block.content)) found.push(...collectImages(block.content));
|
|
37
|
+
}
|
|
38
|
+
return found;
|
|
39
|
+
}
|
|
40
|
+
|
|
29
41
|
function extractLatestUserContent(messages) {
|
|
30
42
|
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
31
43
|
const message = messages[index];
|
|
@@ -48,11 +60,12 @@ function extractLatestUserContent(messages) {
|
|
|
48
60
|
|
|
49
61
|
return {
|
|
50
62
|
text: text.trim(),
|
|
51
|
-
toolResults
|
|
63
|
+
toolResults,
|
|
64
|
+
images: collectImages(blocks)
|
|
52
65
|
};
|
|
53
66
|
}
|
|
54
67
|
|
|
55
|
-
return { text: '', toolResults: [] };
|
|
68
|
+
return { text: '', toolResults: [], images: [] };
|
|
56
69
|
}
|
|
57
70
|
|
|
58
71
|
function createAnthropicMessage({ model, text = '', toolCalls = [], inputTokens = 0 }) {
|
package/src/elevenlabs-tools.js
CHANGED
package/src/proxy.js
CHANGED
|
@@ -39,6 +39,28 @@ let llmList = loadLlmList();
|
|
|
39
39
|
let llmIds = new Set(llmList.map(item => item.llm));
|
|
40
40
|
const EFFORT_ORDER = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
|
41
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
|
+
|
|
42
64
|
const toolRegistry = new ToolRegistry({
|
|
43
65
|
http: axios,
|
|
44
66
|
apiBase: API_BASE,
|
|
@@ -67,7 +89,7 @@ const effortCaps = new Map();
|
|
|
67
89
|
|
|
68
90
|
function lowerEffortCap(llm, failedEffort) {
|
|
69
91
|
const efforts = (llmList.find(item => item.llm === llm)?.available_reasoning_efforts || [])
|
|
70
|
-
.filter(option => EFFORT_ORDER.indexOf(option) < EFFORT_ORDER.indexOf(failedEffort)
|
|
92
|
+
.filter(option => EFFORT_ORDER.indexOf(option) < EFFORT_ORDER.indexOf(failedEffort));
|
|
71
93
|
if (!efforts.length) return false;
|
|
72
94
|
effortCaps.set(llm, efforts.reduce((best, option) => EFFORT_ORDER.indexOf(option) > EFFORT_ORDER.indexOf(best) ? option : best));
|
|
73
95
|
return true;
|
|
@@ -100,9 +122,14 @@ function withAgentSettings(settings, openFn) {
|
|
|
100
122
|
reasoning_effort: settings.reasoning_effort,
|
|
101
123
|
// Voice defaults: 4 s to first token, then silently fall back to another LLM. 15 s is ElevenLabs' maximum.
|
|
102
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),
|
|
103
128
|
backup_llm_config: { preference: 'disabled' }
|
|
104
129
|
};
|
|
105
|
-
|
|
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, file_input: { enabled: true } } } }, { headers: HEADERS });
|
|
106
133
|
appliedSettings = key;
|
|
107
134
|
console.log(`🎚️ Bridge set to ${settings.llm} effort=${settings.reasoning_effort || 'n/a'} max_tokens=${settings.max_tokens}`);
|
|
108
135
|
}
|
|
@@ -257,9 +284,20 @@ function withWindowsPaths(input) {
|
|
|
257
284
|
}
|
|
258
285
|
|
|
259
286
|
// The agent can emit text and several tool calls for one turn as separate events, so settle after a short quiet gap.
|
|
287
|
+
// ElevenLabs sends no end-of-turn event, and a model may send its "Now adding X" sentence long before the tool call
|
|
288
|
+
// that writes X. Settling 0.8 s after text alone ended turns early and the late tool call was thrown away.
|
|
289
|
+
const TEXT_SETTLE_MS = 6000;
|
|
290
|
+
const ANNOUNCEMENT_SETTLE_MS = 40000;
|
|
291
|
+
const ANNOUNCES_WORK = /(\bnow\b|\bnext\b|\bnext:|i'll|i will|let me|adding|writing|building|creating|updating|starting|:\s*$|…\s*$|\.\.\.\s*$)/i;
|
|
292
|
+
|
|
260
293
|
function settleSoon(conn) {
|
|
261
|
-
|
|
262
|
-
|
|
294
|
+
const pending = conn.pending;
|
|
295
|
+
clearTimeout(pending.settleTimer);
|
|
296
|
+
const lastLine = (pending.text || '').trim().split('\n').pop() || '';
|
|
297
|
+
// Announcements are short; a long text reply that merely mentions "next steps" is a finished answer.
|
|
298
|
+
const announces = (pending.text || '').length < 400 && ANNOUNCES_WORK.test(lastLine);
|
|
299
|
+
const wait = pending.toolCalls.length ? SETTLE_MS : announces ? ANNOUNCEMENT_SETTLE_MS : TEXT_SETTLE_MS;
|
|
300
|
+
pending.settleTimer = setTimeout(() => settle(conn, null), wait);
|
|
263
301
|
}
|
|
264
302
|
|
|
265
303
|
function settle(conn, failure) {
|
|
@@ -272,12 +310,45 @@ function settle(conn, failure) {
|
|
|
272
310
|
else pending.resolve({ text: pending.text, toolCalls: pending.toolCalls });
|
|
273
311
|
}
|
|
274
312
|
|
|
275
|
-
|
|
313
|
+
// Images reach ElevenLabs only as files uploaded to the conversation and referenced from a multimodal_message.
|
|
314
|
+
const MAX_FILES_PER_MESSAGE = 5;
|
|
315
|
+
|
|
316
|
+
async function uploadImages(conn, images) {
|
|
317
|
+
const fileIds = [];
|
|
318
|
+
for (const [index, image] of images.entries()) {
|
|
319
|
+
const extension = (image.mediaType.split('/')[1] || 'png').replace('jpeg', 'jpg');
|
|
320
|
+
const form = new FormData();
|
|
321
|
+
form.append('file', new Blob([Buffer.from(image.data, 'base64')], { type: image.mediaType }), `image-${index + 1}.${extension}`);
|
|
322
|
+
const response = await fetch(`${API_BASE}/conversations/${conn.conversationId}/files`, { method: 'POST', headers: HEADERS, body: form });
|
|
323
|
+
if (!response.ok) throw new Error(`Image upload failed (${response.status}): ${(await response.text()).slice(0, 200)}`);
|
|
324
|
+
fileIds.push((await response.json()).file_id);
|
|
325
|
+
}
|
|
326
|
+
return fileIds;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function sendMultimodal(conn, text, fileIds) {
|
|
330
|
+
for (let start = 0; start < fileIds.length; start += MAX_FILES_PER_MESSAGE) {
|
|
331
|
+
conn.ws.send(JSON.stringify({
|
|
332
|
+
type: 'multimodal_message',
|
|
333
|
+
text: { type: 'user_message', text: start === 0 ? text : 'More images:', source_medium: 'image' },
|
|
334
|
+
files: fileIds.slice(start, start + MAX_FILES_PER_MESSAGE).map(fileId => ({ type: 'file_input', file_id: fileId }))
|
|
335
|
+
}));
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function sendTurn(conn, { text, toolResults, history, images = [] }) {
|
|
276
340
|
if (conn.pending) throw new Error('A request is already active for this conversation');
|
|
277
341
|
const requestId = String(++conn.messageId);
|
|
278
342
|
|
|
279
|
-
return new Promise((resolve, reject) => {
|
|
343
|
+
return new Promise(async (resolve, reject) => {
|
|
280
344
|
conn.pending = { resolve, reject, text: '', toolCalls: [], settleTimer: null };
|
|
345
|
+
let fileIds = [];
|
|
346
|
+
try {
|
|
347
|
+
fileIds = images.length ? await uploadImages(conn, images) : [];
|
|
348
|
+
} catch (error) {
|
|
349
|
+
settle(conn, { error });
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
281
352
|
conn.pending.timeout = setTimeout(
|
|
282
353
|
() => settle(conn, { error: new Error(`No reply from ${conn.llm} within ${REQUEST_TIMEOUT_MS / 1000}s`) }),
|
|
283
354
|
REQUEST_TIMEOUT_MS
|
|
@@ -299,11 +370,12 @@ function sendTurn(conn, { text, toolResults, history }) {
|
|
|
299
370
|
conn.ws.send(JSON.stringify({
|
|
300
371
|
type: 'client_tool_result',
|
|
301
372
|
tool_call_id: result.toolUseId,
|
|
302
|
-
result: result.content,
|
|
373
|
+
result: fileIds.length ? `${result.content}\n[The image output of this tool follows in the next message.]` : result.content,
|
|
303
374
|
is_error: result.isError
|
|
304
375
|
}));
|
|
305
376
|
}
|
|
306
377
|
if (text) conn.ws.send(JSON.stringify({ type: 'contextual_update', text }));
|
|
378
|
+
if (fileIds.length) sendMultimodal(conn, 'Image output of the tool call above.', fileIds);
|
|
307
379
|
return;
|
|
308
380
|
}
|
|
309
381
|
|
|
@@ -312,11 +384,9 @@ function sendTurn(conn, { text, toolResults, history }) {
|
|
|
312
384
|
const resultText = toolResults
|
|
313
385
|
.map(result => `${result.isError ? 'Tool error' : 'Tool result'} (${result.toolUseId}):\n${result.content}`)
|
|
314
386
|
.join('\n\n');
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
text: [resultText, text, resultText ? 'Continue the task from here.' : ''].filter(Boolean).join('\n\n')
|
|
319
|
-
}));
|
|
387
|
+
const turnText = [resultText, text, resultText ? 'Continue the task from here.' : ''].filter(Boolean).join('\n\n');
|
|
388
|
+
if (fileIds.length) sendMultimodal(conn, turnText || 'See the attached image.', fileIds);
|
|
389
|
+
else conn.ws.send(JSON.stringify({ type: 'user_message', id: requestId, text: turnText }));
|
|
320
390
|
});
|
|
321
391
|
}
|
|
322
392
|
|
|
@@ -339,13 +409,17 @@ app.use(bodyParser.json({ limit: '50mb' }));
|
|
|
339
409
|
|
|
340
410
|
app.post('/v1/messages', async (req, res) => {
|
|
341
411
|
const { model, messages = [], system, stream, metadata, tools = [], max_tokens: maxTokens, output_config: outputConfig } = req.body;
|
|
342
|
-
const
|
|
412
|
+
const launchModel = req.get('x-labs-model');
|
|
413
|
+
// Claude Code answers repeated errors by falling back opus -> sonnet -> haiku on its own; on the main thread
|
|
414
|
+
// (tools present) a Claude id therefore means "fallback", so stay on the model the user launched with.
|
|
415
|
+
const isClaudeFallback = /^claude-/.test(model || '') && (req.body.tools || []).length > 0 && Boolean(launchModel);
|
|
416
|
+
const llm = resolveLlm(isClaudeFallback ? launchModel : model, launchModel, aliases, llmIds);
|
|
343
417
|
console.log(`\n🤖 ${model} -> ${llm || 'UNKNOWN'} | ${messages.length} messages | ${tools.length} tools`);
|
|
344
418
|
if (!llm) return anthropicError(res, 400, 'invalid_request_error', `Unknown model "${model}". Run "labs models" to list models.`);
|
|
345
419
|
|
|
346
420
|
try {
|
|
347
421
|
const latest = extractLatestUserContent(messages);
|
|
348
|
-
if (!latest.text && latest.toolResults.length === 0) {
|
|
422
|
+
if (!latest.text && latest.toolResults.length === 0 && latest.images.length === 0) {
|
|
349
423
|
return anthropicError(res, 400, 'invalid_request_error', 'No text or tool result in the latest user message');
|
|
350
424
|
}
|
|
351
425
|
|
|
@@ -353,30 +427,35 @@ app.post('/v1/messages', async (req, res) => {
|
|
|
353
427
|
const isSideRequest = tools.length === 0;
|
|
354
428
|
const sessionId = req.get('x-labs-session-id') || metadata?.session_id || `side_${Date.now()}`;
|
|
355
429
|
const threadId = isValidSessionId(sessionId) ? createThreadId(sessionId, messages) : createThreadId('anon', messages);
|
|
356
|
-
const toolIds = isSideRequest ? [] : await toolRegistry.ensure(tools);
|
|
430
|
+
const toolIds = isSideRequest ? [] : await toolRegistry.ensure(tools.filter(isForwardedTool));
|
|
357
431
|
const toolSetHash = createHash('sha1').update(toolIds.join(',')).digest('hex').slice(0, 8);
|
|
358
432
|
let conn;
|
|
359
433
|
let result;
|
|
360
434
|
for (;;) {
|
|
361
|
-
const settings = agentSettingsFor(llm, outputConfig?.effort || '
|
|
435
|
+
const settings = agentSettingsFor(llm, outputConfig?.effort || 'high', maxTokens);
|
|
362
436
|
const key = isSideRequest
|
|
363
437
|
? `side_${Date.now()}_${Math.random().toString(36).slice(2)}`
|
|
364
438
|
: `${llm}:${settings.reasoning_effort}:${threadId}:${toolSetHash}`;
|
|
365
439
|
const existing = connections.get(key);
|
|
366
440
|
conn = existing && existing.ws.readyState === WebSocket.OPEN
|
|
367
441
|
? existing
|
|
368
|
-
: await withAgentSettings(settings, () => openConversation(key, { llm, prompt: systemText(system) || 'You are a helpful assistant.'
|
|
442
|
+
: await withAgentSettings(settings, () => openConversation(key, { llm, prompt: `${systemText(system) || 'You are a helpful assistant.'}${BRIDGE_NOTE}`, toolIds }));
|
|
369
443
|
try {
|
|
370
|
-
result = await sendTurn(conn, { text: latest.text, toolResults: latest.toolResults, history: messages.slice(0, -1) });
|
|
444
|
+
result = await sendTurn(conn, { text: latest.text, toolResults: latest.toolResults, images: latest.images, history: messages.slice(0, -1) });
|
|
371
445
|
break;
|
|
372
446
|
} catch (error) {
|
|
373
|
-
if (!/Cascade Error: TimeoutError/.test(error.message) || !lowerEffortCap(llm, settings.reasoning_effort)) throw error;
|
|
447
|
+
if (!/Cascade Error: TimeoutError|took too long/.test(error.message) || !lowerEffortCap(llm, settings.reasoning_effort)) throw error;
|
|
374
448
|
console.log(`🎚️ ${llm} too slow at effort=${settings.reasoning_effort}; retrying at ${effortCaps.get(llm)}`);
|
|
375
449
|
}
|
|
376
450
|
}
|
|
377
451
|
|
|
378
452
|
// Claude Code decides when to auto-compact from input_tokens, so report the whole request, not just the last turn.
|
|
379
|
-
|
|
453
|
+
// Base64 images and documents are thousands of characters but roughly 1.5k tokens each to a model; counting
|
|
454
|
+
// their raw length made Claude Code believe the window was full and compact after every prompt.
|
|
455
|
+
const IMAGE_TOKENS_AS_CHARS = 6000;
|
|
456
|
+
const withoutBinary = JSON.stringify(messages, (field, value) =>
|
|
457
|
+
field === 'data' && typeof value === 'string' && value.length > IMAGE_TOKENS_AS_CHARS ? 'x'.repeat(IMAGE_TOKENS_AS_CHARS) : value);
|
|
458
|
+
const requestChars = JSON.stringify(system || '').length + withoutBinary.length + JSON.stringify(tools.filter(isForwardedTool)).length;
|
|
380
459
|
const message = createAnthropicMessage({
|
|
381
460
|
model,
|
|
382
461
|
text: result.text || '',
|
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, file_input: { enabled: true } }
|
|
50
50
|
},
|
|
51
51
|
platform_settings: {
|
|
52
52
|
// Post-conversation analysis adds nothing for a coding bridge.
|