labs-claude 0.3.0 → 0.3.3
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 +20 -4
- package/bin/labs.js +187 -40
- package/package.json +4 -3
- package/src/agy.js +1016 -0
- package/src/anthropic-protocol.js +84 -17
- package/src/chat/index.html +10 -1
- package/src/config.js +101 -71
- package/src/gateway-client.js +173 -124
- package/src/gemini.js +474 -0
- package/src/image-mcp.js +174 -0
- package/src/launch-args.js +15 -4
- package/src/proxy-manager.js +6 -4
- package/src/proxy.js +976 -801
- package/src/setup.js +43 -1
- package/src/ui.js +181 -0
- package/src/usage.js +42 -2
- package/src/web-mcp.js +253 -0
package/src/proxy.js
CHANGED
|
@@ -1,801 +1,976 @@
|
|
|
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 { execFile } = require('child_process');
|
|
7
|
-
const WebSocket = require('ws');
|
|
8
|
-
const {
|
|
9
|
-
createAnthropicMessage,
|
|
10
|
-
createLiveStream,
|
|
11
|
-
createThreadId,
|
|
12
|
-
extractLatestUserContent,
|
|
13
|
-
lastAssistantContent,
|
|
14
|
-
replySignature,
|
|
15
|
-
formatConversationHistory,
|
|
16
|
-
isValidSessionId,
|
|
17
|
-
resolveLlm
|
|
18
|
-
} = require('./anthropic-protocol');
|
|
19
|
-
const { ToolRegistry } = require('./elevenlabs-tools');
|
|
20
|
-
const { oversizedWholeFileReads, shuntNote, WORKER_PROMPT } = require('./read-shunt');
|
|
21
|
-
const { loadProxyKey, rejectLocalRequest } = require('./local-auth');
|
|
22
|
-
const { bedrockModelId, createBedrockClient, readBedrockKey, streamConverse } = require('./bedrock');
|
|
23
|
-
const {
|
|
24
|
-
const {
|
|
25
|
-
const {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
const PORT = config.port;
|
|
39
|
-
const HEADERS = { 'xi-api-key': config.apiKey };
|
|
40
|
-
const aliases = config.models;
|
|
41
|
-
let llmList = loadLlmList();
|
|
42
|
-
let llmIds = new Set(llmList.map(item => item.llm));
|
|
43
|
-
const EFFORT_ORDER = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
|
44
|
-
|
|
45
|
-
// Every tool definition is re-read at the start of each ElevenLabs conversation, and ElevenLabs drops a reply whose
|
|
46
|
-
// first token takes over 15 s, so only Claude Code's coding tools and MCP tools are forwarded.
|
|
47
|
-
const FORWARDED_BUILTINS = new Set([
|
|
48
|
-
'Agent', 'Task', 'Bash', 'PowerShell', 'Read', 'Write', 'Edit', 'MultiEdit', 'Glob', 'Grep',
|
|
49
|
-
'WebFetch', 'WebSearch', 'Skill', 'ToolSearch', 'WaitForMcpServers', 'TodoWrite', 'NotebookEdit',
|
|
50
|
-
'AskUserQuestion', 'EnterPlanMode', 'ExitPlanMode', 'Monitor', 'TaskStop'
|
|
51
|
-
]);
|
|
52
|
-
|
|
53
|
-
// Claude Code's first request comes before its MCP servers connect, so the second request carried ~25 new tools and
|
|
54
|
-
// forced a fresh conversation. Tools used in the last few days are offered from the start; calling one that has not
|
|
55
|
-
// connected yet just returns Claude Code's "no such tool" error.
|
|
56
|
-
const PRELOAD_WINDOW_MS = 3 * 24 * 60 * 60 * 1000;
|
|
57
|
-
const PRELOAD_MAX_TOOLS = 100;
|
|
58
|
-
|
|
59
|
-
function isForwardedTool(tool) {
|
|
60
|
-
return FORWARDED_BUILTINS.has(tool.name) || tool.name.startsWith('mcp__');
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
// ElevenLabs cuts any single reply after about 50 s (thinking plus writing, measured), so one Write of a whole file
|
|
64
|
-
// fails; the model is asked to build files in small steps instead.
|
|
65
|
-
const BRIDGE_NOTE = [
|
|
66
|
-
'',
|
|
67
|
-
'',
|
|
68
|
-
'# Output limits of this connection',
|
|
69
|
-
'Every reply (your thinking plus your output) must finish within about 40 seconds or it is cut off.',
|
|
70
|
-
'Never put more than about 80 lines of code in one Write or Edit call.',
|
|
71
|
-
'Build longer files in steps: Write the first part, then add the rest with further Edit calls, one part per reply.',
|
|
72
|
-
'',
|
|
73
|
-
'# Browser',
|
|
74
|
-
'Claude in Chrome is not available on this connection. For any browser task (open, read, click, fill, screenshot)',
|
|
75
|
-
'use the mcp__labs-browser__* tools: they drive the user\'s real Chrome with its logins and tabs.',
|
|
76
|
-
'Read the page with browser_snapshot before clicking, and use the element refs it returns.'
|
|
77
|
-
].join('\n');
|
|
78
|
-
|
|
79
|
-
const toolRegistry = new ToolRegistry({
|
|
80
|
-
http: axios,
|
|
81
|
-
apiBase: API_BASE,
|
|
82
|
-
headers: HEADERS,
|
|
83
|
-
file: path.join(LABS_DIR, `tool-registry-${config.bridgeAgent}.json`),
|
|
84
|
-
agentId: config.bridgeAgent
|
|
85
|
-
});
|
|
86
|
-
|
|
87
|
-
async function refreshLlmList() {
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
//
|
|
101
|
-
//
|
|
102
|
-
//
|
|
103
|
-
|
|
104
|
-
const
|
|
105
|
-
const
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
const
|
|
118
|
-
const
|
|
119
|
-
const
|
|
120
|
-
const
|
|
121
|
-
const
|
|
122
|
-
|
|
123
|
-
:
|
|
124
|
-
|
|
125
|
-
//
|
|
126
|
-
//
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
//
|
|
137
|
-
//
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
const
|
|
141
|
-
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
let
|
|
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
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
const
|
|
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
|
-
if (
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
if (
|
|
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
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
//
|
|
281
|
-
//
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
const
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
pending.streamedResponseId
|
|
296
|
-
pending.
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
//
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
if (!
|
|
315
|
-
|
|
316
|
-
//
|
|
317
|
-
|
|
318
|
-
conn.
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
conn.
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
//
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
//
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
if (
|
|
346
|
-
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
for (const key of PATH_KEYS)
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
//
|
|
366
|
-
//
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
clearTimeout(pending.
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
const
|
|
392
|
-
|
|
393
|
-
+ '
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
const
|
|
400
|
-
const
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
const
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
const
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
}
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
const
|
|
441
|
-
form
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
//
|
|
462
|
-
//
|
|
463
|
-
//
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
pending
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
conn.
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
if (conn.
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
//
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
conn.
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
if (
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
//
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
.
|
|
518
|
-
|
|
519
|
-
const
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
//
|
|
535
|
-
//
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
//
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
&&
|
|
548
|
-
candidate.
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
fs.
|
|
558
|
-
|
|
559
|
-
}
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
}
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
//
|
|
567
|
-
//
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
let
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
if (apiKey
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
const
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
const
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
const
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
if (result.
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
const
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
if (
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
}
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
//
|
|
630
|
-
//
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
const
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
const
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
const
|
|
651
|
-
const
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
const
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
});
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
}
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
app.
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
});
|
|
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 { execFile } = require('child_process');
|
|
7
|
+
const WebSocket = require('ws');
|
|
8
|
+
const {
|
|
9
|
+
createAnthropicMessage,
|
|
10
|
+
createLiveStream,
|
|
11
|
+
createThreadId,
|
|
12
|
+
extractLatestUserContent,
|
|
13
|
+
lastAssistantContent,
|
|
14
|
+
replySignature,
|
|
15
|
+
formatConversationHistory,
|
|
16
|
+
isValidSessionId,
|
|
17
|
+
resolveLlm
|
|
18
|
+
} = require('./anthropic-protocol');
|
|
19
|
+
const { ToolRegistry } = require('./elevenlabs-tools');
|
|
20
|
+
const { oversizedWholeFileReads, shuntNote, WORKER_PROMPT } = require('./read-shunt');
|
|
21
|
+
const { loadProxyKey, rejectLocalRequest } = require('./local-auth');
|
|
22
|
+
const { bedrockModelId, createBedrockClient, readBedrockKey, streamConverse } = require('./bedrock');
|
|
23
|
+
const { ThoughtSignatureStore, geminiModelId, resolveGeminiAuth, streamGemini } = require('./gemini');
|
|
24
|
+
const { AGY_MODELS, agyModelId, createAgyBridge, hasAgyCli, isAgyFallbackModel } = require('./agy');
|
|
25
|
+
const { hasChatSession, mountChat } = require('./chat-routes');
|
|
26
|
+
const { API_BASE, LABS_DIR, codeFingerprint, credentialFingerprint, loadEffectiveConfig, loadLlmList, saveLlmList } = require('./config');
|
|
27
|
+
const CODE = codeFingerprint();
|
|
28
|
+
const { version: VERSION } = require('../package.json');
|
|
29
|
+
|
|
30
|
+
console.log(`=== labs-claude proxy ${VERSION} ===`);
|
|
31
|
+
|
|
32
|
+
const SETTLE_MS = 800;
|
|
33
|
+
const REQUEST_TIMEOUT_MS = 600000;
|
|
34
|
+
const CONVERSATIONS_DIR = path.join(LABS_DIR, 'conversations');
|
|
35
|
+
|
|
36
|
+
const config = loadEffectiveConfig();
|
|
37
|
+
const hasElevenLabs = Boolean(config.apiKey && config.bridgeAgent);
|
|
38
|
+
const PORT = config.port;
|
|
39
|
+
const HEADERS = hasElevenLabs ? { 'xi-api-key': config.apiKey } : {};
|
|
40
|
+
const aliases = config.models;
|
|
41
|
+
let llmList = loadLlmList();
|
|
42
|
+
let llmIds = new Set(llmList.map(item => item.llm));
|
|
43
|
+
const EFFORT_ORDER = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
|
44
|
+
|
|
45
|
+
// Every tool definition is re-read at the start of each ElevenLabs conversation, and ElevenLabs drops a reply whose
|
|
46
|
+
// first token takes over 15 s, so only Claude Code's coding tools and MCP tools are forwarded.
|
|
47
|
+
const FORWARDED_BUILTINS = new Set([
|
|
48
|
+
'Agent', 'Task', 'Bash', 'PowerShell', 'Read', 'Write', 'Edit', 'MultiEdit', 'Glob', 'Grep',
|
|
49
|
+
'WebFetch', 'WebSearch', 'Skill', 'ToolSearch', 'WaitForMcpServers', 'TodoWrite', 'NotebookEdit',
|
|
50
|
+
'AskUserQuestion', 'EnterPlanMode', 'ExitPlanMode', 'Monitor', 'TaskStop'
|
|
51
|
+
]);
|
|
52
|
+
|
|
53
|
+
// Claude Code's first request comes before its MCP servers connect, so the second request carried ~25 new tools and
|
|
54
|
+
// forced a fresh conversation. Tools used in the last few days are offered from the start; calling one that has not
|
|
55
|
+
// connected yet just returns Claude Code's "no such tool" error.
|
|
56
|
+
const PRELOAD_WINDOW_MS = 3 * 24 * 60 * 60 * 1000;
|
|
57
|
+
const PRELOAD_MAX_TOOLS = 100;
|
|
58
|
+
|
|
59
|
+
function isForwardedTool(tool) {
|
|
60
|
+
return FORWARDED_BUILTINS.has(tool.name) || tool.name.startsWith('mcp__');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// ElevenLabs cuts any single reply after about 50 s (thinking plus writing, measured), so one Write of a whole file
|
|
64
|
+
// fails; the model is asked to build files in small steps instead.
|
|
65
|
+
const BRIDGE_NOTE = [
|
|
66
|
+
'',
|
|
67
|
+
'',
|
|
68
|
+
'# Output limits of this connection',
|
|
69
|
+
'Every reply (your thinking plus your output) must finish within about 40 seconds or it is cut off.',
|
|
70
|
+
'Never put more than about 80 lines of code in one Write or Edit call.',
|
|
71
|
+
'Build longer files in steps: Write the first part, then add the rest with further Edit calls, one part per reply.',
|
|
72
|
+
'',
|
|
73
|
+
'# Browser',
|
|
74
|
+
'Claude in Chrome is not available on this connection. For any browser task (open, read, click, fill, screenshot)',
|
|
75
|
+
'use the mcp__labs-browser__* tools: they drive the user\'s real Chrome with its logins and tabs.',
|
|
76
|
+
'Read the page with browser_snapshot before clicking, and use the element refs it returns.'
|
|
77
|
+
].join('\n');
|
|
78
|
+
|
|
79
|
+
const toolRegistry = hasElevenLabs ? new ToolRegistry({
|
|
80
|
+
http: axios,
|
|
81
|
+
apiBase: API_BASE,
|
|
82
|
+
headers: HEADERS,
|
|
83
|
+
file: path.join(LABS_DIR, `tool-registry-${config.bridgeAgent}.json`),
|
|
84
|
+
agentId: config.bridgeAgent
|
|
85
|
+
}) : null;
|
|
86
|
+
|
|
87
|
+
async function refreshLlmList() {
|
|
88
|
+
if (!hasElevenLabs) return;
|
|
89
|
+
try {
|
|
90
|
+
const response = await axios.get(`${API_BASE}/llm/list`, { headers: HEADERS });
|
|
91
|
+
saveLlmList(response.data.llms);
|
|
92
|
+
llmList = response.data.llms;
|
|
93
|
+
llmIds = new Set(llmList.map(item => item.llm));
|
|
94
|
+
console.log(`📋 ${llmIds.size} ElevenLabs LLMs available`);
|
|
95
|
+
} catch (error) {
|
|
96
|
+
console.error(`⚠️ Could not refresh LLM list, using cached copy: ${error.message}`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Effort and reply length are agent-level settings on ElevenLabs (not per-conversation overrides), so the bridge
|
|
101
|
+
// agent is re-pointed before each new conversation; the queue keeps concurrent opens from racing each other.
|
|
102
|
+
// ElevenLabs drops a turn whose first token takes longer than 15 s (cascade_timeout_seconds), which very high
|
|
103
|
+
// effort can exceed; the highest effort that answered in time is remembered per LLM for the proxy's lifetime.
|
|
104
|
+
const effortCaps = new Map();
|
|
105
|
+
const MAX_SLOW_RETRIES = 3;
|
|
106
|
+
const SHARED_MAX_TOKENS = 65536;
|
|
107
|
+
|
|
108
|
+
function lowerEffortCap(llm, failedEffort) {
|
|
109
|
+
const efforts = (llmList.find(item => item.llm === llm)?.available_reasoning_efforts || [])
|
|
110
|
+
.filter(option => EFFORT_ORDER.indexOf(option) < EFFORT_ORDER.indexOf(failedEffort));
|
|
111
|
+
if (!efforts.length) return false;
|
|
112
|
+
effortCaps.set(llm, efforts.reduce((best, option) => EFFORT_ORDER.indexOf(option) > EFFORT_ORDER.indexOf(best) ? option : best));
|
|
113
|
+
return true;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function agentSettingsFor(llm, requestedEffort, requestedMaxTokens) {
|
|
117
|
+
const info = llmList.find(item => item.llm === llm) || {};
|
|
118
|
+
const efforts = info.available_reasoning_efforts || [];
|
|
119
|
+
const cap = effortCaps.get(llm);
|
|
120
|
+
const capped = cap && EFFORT_ORDER.indexOf(requestedEffort) > EFFORT_ORDER.indexOf(cap) ? cap : requestedEffort;
|
|
121
|
+
const wanted = EFFORT_ORDER.indexOf(capped);
|
|
122
|
+
const effort = efforts.length
|
|
123
|
+
? efforts.reduce((best, option) => Math.abs(EFFORT_ORDER.indexOf(option) - wanted) < Math.abs(EFFORT_ORDER.indexOf(best) - wanted) ? option : best)
|
|
124
|
+
: null;
|
|
125
|
+
// The model's full reply length (Claude Code's own max_tokens is sized for Anthropic models), but never above the
|
|
126
|
+
// largest every Gemini 3.x accepts: reply length is agent-wide, so an Opus window opening mid side call handed
|
|
127
|
+
// gemini-3.8-flash Opus's 128000 and Google refused it (15 failed side calls, 2026-10-30).
|
|
128
|
+
const limit = info.max_tokens_limit || requestedMaxTokens || 4096;
|
|
129
|
+
return { llm, reasoning_effort: effort, max_tokens: Math.min(limit, SHARED_MAX_TOKENS) };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// New agents do not send context_usage or agent_response_complete unless asked; both are verified on gpt-6-astra.
|
|
133
|
+
const CLIENT_EVENTS = ['agent_response', 'agent_response_correction', 'agent_tool_response', 'client_tool_call',
|
|
134
|
+
'context_usage', 'agent_response_complete', 'agent_chat_response_part', 'interruption'];
|
|
135
|
+
|
|
136
|
+
// Claude Code compacts on its own at config.contextLimit (from the context_usage tokens reported as input_tokens).
|
|
137
|
+
// ElevenLabs' server-side compaction is the safety net just above that limit (0.95 is the API maximum); it keeps the
|
|
138
|
+
// newest 40 messages word for word.
|
|
139
|
+
function compactionFor(llm) {
|
|
140
|
+
const window = llmList.find(item => item.llm === llm)?.max_context_limit || config.contextLimit;
|
|
141
|
+
const fraction = Math.min(0.95, Math.round((config.contextLimit * 1.1 / window) * 100) / 100);
|
|
142
|
+
return { enabled: true, soft_trigger_fraction: fraction, tail_size: 40 };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
let settingsQueue = Promise.resolve();
|
|
146
|
+
let appliedSettings = '';
|
|
147
|
+
|
|
148
|
+
function withAgentSettings(settings, openFn) {
|
|
149
|
+
const run = async () => {
|
|
150
|
+
const key = JSON.stringify(settings);
|
|
151
|
+
if (key !== appliedSettings) {
|
|
152
|
+
// An explicit null is required: an effort left over from the previous LLM makes ElevenLabs reject the switch.
|
|
153
|
+
const prompt = {
|
|
154
|
+
llm: settings.llm,
|
|
155
|
+
max_tokens: settings.max_tokens,
|
|
156
|
+
reasoning_effort: settings.reasoning_effort,
|
|
157
|
+
// Voice defaults: 4 s to first token, then silently fall back to another LLM. 15 s is ElevenLabs' maximum.
|
|
158
|
+
cascade_timeout_seconds: 15,
|
|
159
|
+
// Streaming a reasoning summary counts as the first output, so long thinking no longer trips the 15 s
|
|
160
|
+
// first-token cancel (measured: Opus at max effort answered at 27.8 s with it, was cancelled without).
|
|
161
|
+
enable_reasoning_summary: Boolean(settings.reasoning_effort),
|
|
162
|
+
backup_llm_config: { preference: 'disabled' }
|
|
163
|
+
};
|
|
164
|
+
// Conversations default to 600 s on new agents; 7200 s is the API maximum. Unset, the idle limit closed every
|
|
165
|
+
// chat 15 min after the last reply (145 of 300, measured 2026-10-30), and the cold reopen of a ~190k-token
|
|
166
|
+
// history missed the 15 s first-token limit: all 7 "All LLMs have failed". 7200 s is its maximum too.
|
|
167
|
+
await axios.patch(`${API_BASE}/agents/${config.bridgeAgent}`,
|
|
168
|
+
{ conversation_config: { agent: { prompt }, conversation: { max_duration_seconds: 7200, max_duration_seconds_after_last_agent_message: 7200, file_input: { enabled: true }, client_events: CLIENT_EVENTS, compaction: compactionFor(settings.llm) } } }, { headers: HEADERS });
|
|
169
|
+
appliedSettings = key;
|
|
170
|
+
console.log(`🎚️ Bridge set to ${settings.llm} effort=${settings.reasoning_effort || 'n/a'} max_tokens=${settings.max_tokens}`);
|
|
171
|
+
}
|
|
172
|
+
const conn = openFn();
|
|
173
|
+
await conn.ready;
|
|
174
|
+
return conn;
|
|
175
|
+
};
|
|
176
|
+
const next = settingsQueue.then(run, run);
|
|
177
|
+
settingsQueue = next.catch(() => {});
|
|
178
|
+
return next;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// ============================================
|
|
182
|
+
// WEBSOCKET CONVERSATIONS: one per (LLM, Claude Code thread, tool set)
|
|
183
|
+
// ============================================
|
|
184
|
+
|
|
185
|
+
const connections = new Map();
|
|
186
|
+
|
|
187
|
+
function systemText(system) {
|
|
188
|
+
if (typeof system === 'string') return system;
|
|
189
|
+
return Array.isArray(system) ? system.map(block => block.text || '').join('\n\n') : '';
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function openConversation(key, { llm, prompt, toolIds }) {
|
|
193
|
+
const existing = connections.get(key);
|
|
194
|
+
// A socket still CONNECTING must be awaited, not replaced: replacing it routed the old socket's events into the new one.
|
|
195
|
+
if (existing && [WebSocket.OPEN, WebSocket.CONNECTING].includes(existing.ws.readyState)) return existing;
|
|
196
|
+
|
|
197
|
+
console.log(`🔌 Opening ${llm} conversation (${toolIds.length} tools) for ${key}`);
|
|
198
|
+
const ws = new WebSocket(`wss://api.elevenlabs.io/v1/convai/conversation?agent_id=${config.bridgeAgent}`, { headers: HEADERS });
|
|
199
|
+
const conn = {
|
|
200
|
+
ws,
|
|
201
|
+
llm,
|
|
202
|
+
pending: null,
|
|
203
|
+
messageId: 0,
|
|
204
|
+
conversationId: null,
|
|
205
|
+
contextTokens: 0,
|
|
206
|
+
openToolCallIds: new Set(),
|
|
207
|
+
timedOutToolCalls: new Set(),
|
|
208
|
+
toolIds: new Set(toolIds),
|
|
209
|
+
filesUploaded: 0,
|
|
210
|
+
promptChars: prompt.length,
|
|
211
|
+
replayChars: 0,
|
|
212
|
+
closeReason: ''
|
|
213
|
+
};
|
|
214
|
+
connections.set(key, conn);
|
|
215
|
+
|
|
216
|
+
conn.ready = new Promise((resolve, reject) => {
|
|
217
|
+
ws.on('open', () => {
|
|
218
|
+
ws.send(JSON.stringify({
|
|
219
|
+
type: 'conversation_initiation_client_data',
|
|
220
|
+
conversation_config_override: {
|
|
221
|
+
conversation: { text_only: true },
|
|
222
|
+
agent: { first_message: '', prompt: { prompt, llm, tool_ids: toolIds } }
|
|
223
|
+
}
|
|
224
|
+
}));
|
|
225
|
+
conn.markReady = resolve;
|
|
226
|
+
});
|
|
227
|
+
ws.on('error', error => {
|
|
228
|
+
console.error(`🚨 WS error for ${key}: ${error.message}`);
|
|
229
|
+
reject(error);
|
|
230
|
+
if (conn.pending) settle(conn, { error });
|
|
231
|
+
if (connections.get(key) === conn) connections.delete(key);
|
|
232
|
+
ws.terminate();
|
|
233
|
+
});
|
|
234
|
+
ws.on('close', (code, reason) => {
|
|
235
|
+
conn.closeReason = `code ${code}${reason?.length ? `: ${reason}` : ''}`;
|
|
236
|
+
console.log(`🔌 Conversation closed for ${key} (${conn.closeReason})`);
|
|
237
|
+
reject(new Error(`ElevenLabs closed the conversation (${conn.closeReason})`));
|
|
238
|
+
if (conn.pending) settle(conn, { error: new Error(`ElevenLabs closed the conversation (${conn.closeReason})`) });
|
|
239
|
+
if (connections.get(key) === conn) connections.delete(key);
|
|
240
|
+
});
|
|
241
|
+
});
|
|
242
|
+
conn.ready.catch(() => {});
|
|
243
|
+
|
|
244
|
+
ws.on('message', data => {
|
|
245
|
+
try {
|
|
246
|
+
handleEvent(conn, JSON.parse(data.toString()));
|
|
247
|
+
} catch (error) {
|
|
248
|
+
console.error(`⚠️ WS event error: ${error.message}`);
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
return conn;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function handleEvent(conn, msg) {
|
|
255
|
+
switch (msg.type) {
|
|
256
|
+
case 'conversation_initiation_metadata':
|
|
257
|
+
conn.conversationId = msg.conversation_initiation_metadata_event?.conversation_id;
|
|
258
|
+
console.log(`📋 Conversation ${conn.conversationId} on ${conn.llm}`);
|
|
259
|
+
conn.markReady?.(conn);
|
|
260
|
+
break;
|
|
261
|
+
case 'ping':
|
|
262
|
+
// The server expects the ping's event_id echoed back; a bare pong lets the connection die.
|
|
263
|
+
conn.ws.send(JSON.stringify({ type: 'pong', event_id: msg.ping_event?.event_id }));
|
|
264
|
+
break;
|
|
265
|
+
case 'agent_response': {
|
|
266
|
+
if (!conn.pending) break;
|
|
267
|
+
const text = msg.agent_response_event?.agent_response || '';
|
|
268
|
+
conn.pending.text = conn.pending.text ? `${conn.pending.text}\n\n${text}` : text;
|
|
269
|
+
settleSoon(conn);
|
|
270
|
+
break;
|
|
271
|
+
}
|
|
272
|
+
case 'client_tool_call':
|
|
273
|
+
handleToolCall(conn, msg.client_tool_call);
|
|
274
|
+
break;
|
|
275
|
+
case 'context_usage':
|
|
276
|
+
conn.contextTokens = msg.context_usage_event?.context_tokens || conn.contextTokens;
|
|
277
|
+
console.log(`📊 ${conn.llm} context ${conn.contextTokens} tokens (${conn.conversationId})`);
|
|
278
|
+
break;
|
|
279
|
+
case 'agent_tool_response': {
|
|
280
|
+
// ElevenLabs gives a client tool at most 120 s (measured 2026-10-08), then records an error and lets the
|
|
281
|
+
// agent move on. Claude Code may still be running it (long builds, a permission prompt), so its result
|
|
282
|
+
// must later go in as a message: a client_tool_result for a closed call is ignored and the turn hangs.
|
|
283
|
+
const response = msg.agent_tool_response;
|
|
284
|
+
if (!conn.pending && response?.is_error && conn.openToolCallIds.delete(response.tool_call_id)) {
|
|
285
|
+
conn.timedOutToolCalls.add(response.tool_call_id);
|
|
286
|
+
console.log(`⏳ ${response.tool_name} passed ElevenLabs' 120 s tool limit; its result will be sent as a message`);
|
|
287
|
+
}
|
|
288
|
+
break;
|
|
289
|
+
}
|
|
290
|
+
case 'agent_chat_response_part': {
|
|
291
|
+
const part = msg.text_response_part;
|
|
292
|
+
const pending = conn.pending;
|
|
293
|
+
if (!pending?.onDelta || part?.type !== 'delta' || !part.text) break;
|
|
294
|
+
// Separate replies within one turn are joined with a blank line, as agent_response texts are.
|
|
295
|
+
if (pending.streamedResponseId && pending.streamedResponseId !== part.response_id) pending.onDelta('\n\n');
|
|
296
|
+
pending.streamedResponseId = part.response_id;
|
|
297
|
+
pending.onDelta(part.text);
|
|
298
|
+
break;
|
|
299
|
+
}
|
|
300
|
+
case 'agent_response_complete':
|
|
301
|
+
// Sent once the whole turn is delivered, tool chains included (measured 2026-10-08), so a text reply
|
|
302
|
+
// no longer waits on the settle guess.
|
|
303
|
+
if (conn.pending) settle(conn, null);
|
|
304
|
+
break;
|
|
305
|
+
case 'client_error':
|
|
306
|
+
console.error(`🚨 ElevenLabs client_error: ${JSON.stringify(msg.error_event)}`);
|
|
307
|
+
break;
|
|
308
|
+
default:
|
|
309
|
+
break;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function handleToolCall(conn, call) {
|
|
314
|
+
if (!call?.tool_name || !call.tool_call_id) return;
|
|
315
|
+
if (!conn.pending) {
|
|
316
|
+
// Arrived after the turn was returned. After a 120 s tool timeout the agent often re-sends the call that Claude
|
|
317
|
+
// Code is still running, so it is told to wait instead of being invited to run it a third time.
|
|
318
|
+
const stillRunning = conn.timedOutToolCalls.size > 0;
|
|
319
|
+
conn.ws.send(JSON.stringify({
|
|
320
|
+
type: 'client_tool_result', tool_call_id: call.tool_call_id, is_error: !stillRunning,
|
|
321
|
+
result: stillRunning
|
|
322
|
+
? 'Your earlier tool call is still running in Claude Code. Its result will arrive as the next message; wait for it and do not call any tool now.'
|
|
323
|
+
: 'This tool call arrived after the turn ended. Request it again in your next turn.'
|
|
324
|
+
}));
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
const name = toolRegistry.claudeNameFor(call.tool_name);
|
|
328
|
+
if (call.parameters) call.parameters = withWindowsPaths(call.parameters);
|
|
329
|
+
console.log(`🔧 ${name} ${JSON.stringify(call.parameters || {}).slice(0, 160)}`);
|
|
330
|
+
conn.pending.toolCalls.push({ id: call.tool_call_id, name, input: call.parameters || {} });
|
|
331
|
+
conn.openToolCallIds.add(call.tool_call_id);
|
|
332
|
+
settleSoon(conn);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// On Windows, models copy Git Bash paths (/tmp/..., /c/Users/...) from `pwd` into file tools; Claude Code reads those
|
|
336
|
+
// as outside the project and asks for permission. Git's own cygpath gives the exact Windows equivalent.
|
|
337
|
+
const PATH_KEYS = ['file_path', 'path', 'notebook_path'];
|
|
338
|
+
// A cygpath call per new path froze the whole proxy for 0.2-1.9 s (measured 2026-10-29), so every window stalled and
|
|
339
|
+
// the watchdog called it dead. Its answer only depends on Git Bash's mounts: ask once at start, convert in memory.
|
|
340
|
+
const gitBashMounts = [];
|
|
341
|
+
if (process.platform === 'win32') {
|
|
342
|
+
execFile('cygpath', ['-w', '/tmp', '/'], { encoding: 'utf8', windowsHide: true }, (error, stdout) => {
|
|
343
|
+
if (error) return; // cygpath missing: drive letters still convert below.
|
|
344
|
+
const [tmp, root] = stdout.trim().split(/\r?\n/);
|
|
345
|
+
if (tmp) gitBashMounts.push(['/tmp', tmp.replace(/\\$/, '')]);
|
|
346
|
+
if (root) gitBashMounts.push(['', root.replace(/\\$/, '')]);
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function toWindowsPath(value) {
|
|
351
|
+
if (process.platform !== 'win32' || typeof value !== 'string' || !value.startsWith('/')) return value;
|
|
352
|
+
const drive = value.match(/^\/([a-zA-Z])(\/.*)?$/);
|
|
353
|
+
if (drive) return `${drive[1].toUpperCase()}:\\${(drive[2] || '').slice(1).replace(/\//g, '\\')}`;
|
|
354
|
+
const mount = gitBashMounts.find(([prefix]) => value === prefix || value.startsWith(`${prefix}/`));
|
|
355
|
+
return mount ? `${mount[1]}${value.slice(mount[0].length).replace(/\//g, '\\')}` : value.replace(/\//g, '\\');
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function withWindowsPaths(input) {
|
|
359
|
+
const output = { ...input };
|
|
360
|
+
for (const key of PATH_KEYS) output[key] = toWindowsPath(output[key]);
|
|
361
|
+
for (const key of PATH_KEYS) if (output[key] === undefined) delete output[key];
|
|
362
|
+
return output;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// The agent can emit text and several tool calls for one turn as separate events, so tool calls settle after a short
|
|
366
|
+
// quiet gap (agent_response_complete only comes after their results). Text alone waits for agent_response_complete;
|
|
367
|
+
// the timer is a fallback for a lost event, since a "Now adding X" sentence can precede its tool call by many seconds.
|
|
368
|
+
const TEXT_FALLBACK_SETTLE_MS = 40000;
|
|
369
|
+
|
|
370
|
+
function settleSoon(conn) {
|
|
371
|
+
const pending = conn.pending;
|
|
372
|
+
clearTimeout(pending.settleTimer);
|
|
373
|
+
const wait = pending.toolCalls.length ? SETTLE_MS : TEXT_FALLBACK_SETTLE_MS;
|
|
374
|
+
pending.settleTimer = setTimeout(() => settle(conn, null), wait);
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function settle(conn, failure) {
|
|
378
|
+
const pending = conn.pending;
|
|
379
|
+
if (!pending) return;
|
|
380
|
+
conn.pending = null;
|
|
381
|
+
clearTimeout(pending.settleTimer);
|
|
382
|
+
clearTimeout(pending.timeout);
|
|
383
|
+
if (failure?.error) pending.reject(failure.error);
|
|
384
|
+
else pending.resolve({ text: pending.text, toolCalls: pending.toolCalls });
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// Images reach ElevenLabs only as files uploaded to the conversation and referenced from a multimodal_message.
|
|
388
|
+
const MAX_FILES_PER_MESSAGE = 5;
|
|
389
|
+
|
|
390
|
+
// ElevenLabs refuses an 11th file in one conversation; the request loop answers this error with a fresh conversation.
|
|
391
|
+
const MAX_FILES_PER_CONVERSATION = 10;
|
|
392
|
+
const EYES_PROMPT = 'You are the eyes of a coding agent that cannot see these images. For each image, in order, describe everything '
|
|
393
|
+
+ 'it would need: all visible text verbatim (code, errors, labels, numbers), layout and positions, colours, UI state, and '
|
|
394
|
+
+ 'anything that looks wrong. Be exhaustive and factual; do not guess beyond what is visible.';
|
|
395
|
+
|
|
396
|
+
async function describeImages(llm, settings, images, question) {
|
|
397
|
+
const parts = [];
|
|
398
|
+
for (let start = 0; start < images.length; start += MAX_FILES_PER_CONVERSATION) {
|
|
399
|
+
const chunk = images.slice(start, start + MAX_FILES_PER_CONVERSATION);
|
|
400
|
+
const key = `eyes_${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
|
401
|
+
const eyes = await withAgentSettings(settings, () => openConversation(key, { llm, prompt: EYES_PROMPT, toolIds: [] }));
|
|
402
|
+
try {
|
|
403
|
+
const answer = await sendTurn(eyes, {
|
|
404
|
+
text: `Describe these ${chunk.length} image(s). The agent's current task: ${question || '(not stated)'}`,
|
|
405
|
+
toolResults: [], images: chunk, history: []
|
|
406
|
+
});
|
|
407
|
+
parts.push(answer.text);
|
|
408
|
+
} finally {
|
|
409
|
+
eyes.ws.close();
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
console.log(`👁️ Described ${images.length} image(s) in a side conversation (main chat is at the 10-file limit)`);
|
|
413
|
+
return parts.join('\n\n');
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
const SHUNT_MAX_LINES = 350;
|
|
417
|
+
const SHUNT_LLM = 'gemini-3.8-flash';
|
|
418
|
+
|
|
419
|
+
async function shuntBigReads(toolResults, priorContent, task) {
|
|
420
|
+
if (config.shunt === false) return;
|
|
421
|
+
for (const { result, filePath, lineCount } of oversizedWholeFileReads(toolResults, priorContent, SHUNT_MAX_LINES)) {
|
|
422
|
+
const key = `shunt_${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
|
423
|
+
const worker = await withAgentSettings(agentSettingsFor(SHUNT_LLM, 'low'), () => openConversation(key, { llm: SHUNT_LLM, prompt: WORKER_PROMPT, toolIds: [] }));
|
|
424
|
+
try {
|
|
425
|
+
const digest = await sendTurn(worker, { text: `Agent's task: ${task || '(not stated)'}\n\nFile ${filePath}:\n${result.content}`, toolResults: [], history: [] });
|
|
426
|
+
console.log(`📉 Shunt: ${filePath} ${result.content.length} -> ${digest.text.length} chars`);
|
|
427
|
+
result.content = shuntNote(filePath, lineCount, SHUNT_LLM, digest.text);
|
|
428
|
+
} catch (error) {
|
|
429
|
+
// The full file is the safe fallback: a failed digest must never cost the main model information.
|
|
430
|
+
console.error(`⚠️ Shunt failed for ${filePath}, sending the whole file: ${error.message}`);
|
|
431
|
+
} finally {
|
|
432
|
+
worker.ws.close();
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
async function uploadImages(conn, images) {
|
|
438
|
+
const fileIds = [];
|
|
439
|
+
for (const [index, image] of images.entries()) {
|
|
440
|
+
const extension = (image.mediaType.split('/')[1] || 'png').replace('jpeg', 'jpg');
|
|
441
|
+
const form = new FormData();
|
|
442
|
+
form.append('file', new Blob([Buffer.from(image.data, 'base64')], { type: image.mediaType }), `image-${index + 1}.${extension}`);
|
|
443
|
+
const response = await fetch(`${API_BASE}/conversations/${conn.conversationId}/files`, { method: 'POST', headers: HEADERS, body: form });
|
|
444
|
+
if (!response.ok) throw new Error(`Image upload failed (${response.status}): ${(await response.text()).slice(0, 200)}`);
|
|
445
|
+
fileIds.push((await response.json()).file_id);
|
|
446
|
+
conn.filesUploaded += 1;
|
|
447
|
+
}
|
|
448
|
+
return fileIds;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
function sendMultimodal(conn, text, fileIds) {
|
|
452
|
+
for (let start = 0; start < fileIds.length; start += MAX_FILES_PER_MESSAGE) {
|
|
453
|
+
conn.ws.send(JSON.stringify({
|
|
454
|
+
type: 'multimodal_message',
|
|
455
|
+
text: { type: 'user_message', text: start === 0 ? text : 'More images:', source_medium: 'image' },
|
|
456
|
+
files: fileIds.slice(start, start + MAX_FILES_PER_MESSAGE).map(fileId => ({ type: 'file_input', file_id: fileId }))
|
|
457
|
+
}));
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// A fresh conversation is seeded with up to half the model's window (about 3 characters per token) after the system
|
|
462
|
+
// prompt; the other half is left for the work itself.
|
|
463
|
+
// The replay is uncached history paid again on every later turn: half a 1M window replayed 690k chars (~170k
|
|
464
|
+
// tokens) per new conversation. A fifth of the context limit keeps the pinned instructions and the recent work.
|
|
465
|
+
function replayBudget(llm) {
|
|
466
|
+
const window = llmList.find(item => item.llm === llm)?.max_context_limit || 128000;
|
|
467
|
+
return Math.max(20000, Math.floor(Math.min(window, config.contextLimit) * 0.2 * 3));
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
function sendTurn(conn, { text, toolResults, history, images = [], replayChars = Infinity, onDelta = null }) {
|
|
471
|
+
if (conn.pending) throw new Error('A request is already active for this conversation');
|
|
472
|
+
const requestId = String(++conn.messageId);
|
|
473
|
+
|
|
474
|
+
return new Promise((resolve, reject) => {
|
|
475
|
+
const pending = { resolve, reject, text: '', toolCalls: [], settleTimer: null, onDelta };
|
|
476
|
+
conn.pending = pending;
|
|
477
|
+
pending.timeout = setTimeout(() => {
|
|
478
|
+
if (conn.pending !== pending) return;
|
|
479
|
+
settle(conn, { error: new Error(`No reply from ${conn.llm} within ${REQUEST_TIMEOUT_MS / 1000}s`) });
|
|
480
|
+
conn.ws.terminate();
|
|
481
|
+
}, REQUEST_TIMEOUT_MS);
|
|
482
|
+
const send = async () => {
|
|
483
|
+
if (conn.ws.readyState !== WebSocket.OPEN) throw new Error('Conversation socket is not open');
|
|
484
|
+
const fileIds = images.length ? await uploadImages(conn, images) : [];
|
|
485
|
+
// A close or timeout can settle this turn while the upload is in flight.
|
|
486
|
+
if (conn.pending !== pending) return;
|
|
487
|
+
if (conn.ws.readyState !== WebSocket.OPEN) throw new Error('Conversation socket is not open');
|
|
488
|
+
|
|
489
|
+
// Claude Code resends the whole thread every turn, so a fresh conversation (reconnect, /model switch,
|
|
490
|
+
// --resume, compaction) is seeded from what Claude Code sent.
|
|
491
|
+
if (conn.messageId === 1 && history.length) {
|
|
492
|
+
const replay = formatConversationHistory(history, replayChars);
|
|
493
|
+
conn.replayChars = replay.length;
|
|
494
|
+
console.log(`📼 Replaying ${history.length} messages (${replay.length} chars) into ${conn.conversationId}`);
|
|
495
|
+
conn.ws.send(JSON.stringify({ type: 'contextual_update', text: `Conversation so far:\n${replay}` }));
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
const known = toolResults.filter(result => conn.openToolCallIds.has(result.toolUseId));
|
|
499
|
+
if (toolResults.length && known.length === toolResults.length) {
|
|
500
|
+
for (const result of toolResults) {
|
|
501
|
+
conn.openToolCallIds.delete(result.toolUseId);
|
|
502
|
+
conn.ws.send(JSON.stringify({
|
|
503
|
+
type: 'client_tool_result',
|
|
504
|
+
tool_call_id: result.toolUseId,
|
|
505
|
+
result: fileIds.length ? `${result.content}\n[The image output of this tool follows in the next message.]` : result.content,
|
|
506
|
+
is_error: result.isError
|
|
507
|
+
}));
|
|
508
|
+
}
|
|
509
|
+
if (text) conn.ws.send(JSON.stringify({ type: 'contextual_update', text }));
|
|
510
|
+
if (fileIds.length) sendMultimodal(conn, 'Image output of the tool call above.', fileIds);
|
|
511
|
+
return;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
// Results for calls this conversation never made (it was reopened) go in as text, otherwise the agent
|
|
515
|
+
// waits on tool_call_ids it does not know and never answers.
|
|
516
|
+
const resultText = toolResults
|
|
517
|
+
.map(result => `${result.isError ? 'Tool error' : 'Tool result'} (${result.toolUseId}):\n${result.content}`)
|
|
518
|
+
.join('\n\n');
|
|
519
|
+
for (const result of toolResults) conn.timedOutToolCalls.delete(result.toolUseId);
|
|
520
|
+
const turnText = [resultText, text, resultText ? 'Continue the task from here.' : ''].filter(Boolean).join('\n\n');
|
|
521
|
+
// Failed Opus opens received ~115k more tokens than prompt + replay + tools explain (2026-10-30); this pins the part.
|
|
522
|
+
if (conn.messageId === 1) {
|
|
523
|
+
console.log(`📏 first turn parts (chars): prompt ${conn.promptChars} | replay ${conn.replayChars} | turn ${turnText.length} | images ${fileIds.length} | tools ${conn.toolIds?.size ?? 0}`);
|
|
524
|
+
}
|
|
525
|
+
if (fileIds.length) sendMultimodal(conn, turnText || 'See the attached image.', fileIds);
|
|
526
|
+
else conn.ws.send(JSON.stringify({ type: 'user_message', id: requestId, text: turnText }));
|
|
527
|
+
};
|
|
528
|
+
send().catch(error => {
|
|
529
|
+
if (conn.pending === pending) settle(conn, { error });
|
|
530
|
+
});
|
|
531
|
+
});
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
// Forks and parallel subagents share the main thread's history, so a key built from that history put them all on one
|
|
535
|
+
// ElevenLabs conversation ("A request is already active"). A request now continues only the free conversation whose
|
|
536
|
+
// last reply is the one the request ends with; anything else gets its own conversation, seeded from its history.
|
|
537
|
+
let conversationCounter = 0;
|
|
538
|
+
// Before 0.1.9 about 9% of main-thread requests continued a conversation; every other one replayed a cut history.
|
|
539
|
+
const reuse = { requests: 0, continued: 0 };
|
|
540
|
+
|
|
541
|
+
// Claude Code's tool list changes mid-session (MCP servers connect late, ToolSearch loads deferred tools); a
|
|
542
|
+
// conversation that already has every requested tool is continued, only a genuinely new tool forces a fresh one.
|
|
543
|
+
function claimContinuingConversation(prefix, priorReply, toolIds) {
|
|
544
|
+
if (!priorReply) return null;
|
|
545
|
+
for (const [key, candidate] of connections) {
|
|
546
|
+
if (key.startsWith(prefix) && candidate.lastReply === priorReply && !candidate.claimed && !candidate.pending
|
|
547
|
+
&& toolIds.every(id => candidate.toolIds.has(id))
|
|
548
|
+
&& candidate.ws.readyState === WebSocket.OPEN) {
|
|
549
|
+
candidate.claimed = true;
|
|
550
|
+
return candidate;
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
return null;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
function saveConversation(threadId, llm, conversationId, messages) {
|
|
557
|
+
if (!fs.existsSync(CONVERSATIONS_DIR)) fs.mkdirSync(CONVERSATIONS_DIR, { recursive: true });
|
|
558
|
+
fs.writeFileSync(path.join(CONVERSATIONS_DIR, `${threadId}.json`),
|
|
559
|
+
JSON.stringify({ llm, conversationId, history: messages, updatedAt: Date.now() }, null, 1));
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
function anthropicError(res, status, type, message) {
|
|
563
|
+
return res.status(status).json({ type: 'error', error: { type, message } });
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// ============================================
|
|
567
|
+
// Amazon Bedrock: a direct API, so none of the ElevenLabs bridge limits (conversation setup, 50 s replies, 200 tools)
|
|
568
|
+
// ============================================
|
|
569
|
+
|
|
570
|
+
const BEDROCK_USAGE_FILE = path.join(LABS_DIR, 'bedrock-usage.jsonl');
|
|
571
|
+
let bedrockClient = null;
|
|
572
|
+
let bedrockClientKey = null;
|
|
573
|
+
|
|
574
|
+
function getBedrockClient() {
|
|
575
|
+
const apiKey = readBedrockKey(LABS_DIR);
|
|
576
|
+
if (!apiKey) return null;
|
|
577
|
+
if (apiKey !== bedrockClientKey) {
|
|
578
|
+
bedrockClient = createBedrockClient({ region: config.bedrockRegion, apiKey });
|
|
579
|
+
bedrockClientKey = apiKey;
|
|
580
|
+
}
|
|
581
|
+
return bedrockClient;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
// A session launched on a Bedrock model keeps Claude Code's own side calls (claude-haiku titles, compaction) there too.
|
|
585
|
+
function bedrockRoute(model, launchModel) {
|
|
586
|
+
const direct = bedrockModelId(aliases[String(model || '').replace(/\[1m\]$/i, '')]);
|
|
587
|
+
if (direct) return direct;
|
|
588
|
+
const launched = bedrockModelId(aliases[launchModel]);
|
|
589
|
+
return launched && (!model || /^claude-/.test(model)) ? launched : null;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
async function handleBedrock(req, res, modelId) {
|
|
593
|
+
const { model, stream, tools = [], messages = [] } = req.body;
|
|
594
|
+
const client = getBedrockClient();
|
|
595
|
+
if (!client) return anthropicError(res, 401, 'authentication_error', 'No Amazon Bedrock key on this machine. Run: labs bedrock');
|
|
596
|
+
const estimate = Math.ceil(JSON.stringify(req.body).length / 4);
|
|
597
|
+
console.log(`\n🟧 ${model} -> bedrock ${modelId} | ${messages.length} messages | ${tools.length} tools`);
|
|
598
|
+
const live = stream ? createLiveStream(res, { model, inputTokens: estimate }) : null;
|
|
599
|
+
const abort = new AbortController();
|
|
600
|
+
res.on('close', () => { if (!res.writableEnded) abort.abort(); });
|
|
601
|
+
const started = Date.now();
|
|
602
|
+
try {
|
|
603
|
+
const result = await streamConverse({ client, body: req.body, modelId, signal: abort.signal, onText: live && (delta => live.text(delta)) });
|
|
604
|
+
const message = createAnthropicMessage({
|
|
605
|
+
model,
|
|
606
|
+
text: live?.started ? live.streamedText : result.text,
|
|
607
|
+
toolCalls: result.toolCalls,
|
|
608
|
+
inputTokens: result.usage.inputTokens || estimate
|
|
609
|
+
});
|
|
610
|
+
if (result.usage.outputTokens) message.usage.output_tokens = result.usage.outputTokens;
|
|
611
|
+
if (result.stopReason === 'max_tokens') message.stop_reason = 'max_tokens';
|
|
612
|
+
const seconds = ((Date.now() - started) / 1000).toFixed(1);
|
|
613
|
+
console.log(`🟧 ${seconds}s | in ${result.usage.inputTokens} out ${result.usage.outputTokens} tokens | ${result.toolCalls.length} tool calls`);
|
|
614
|
+
fs.appendFileSync(BEDROCK_USAGE_FILE, `${JSON.stringify({ at: new Date().toISOString(), modelId, input: result.usage.inputTokens, output: result.usage.outputTokens, seconds: Number(seconds) })}\n`);
|
|
615
|
+
return live ? live.finish(message) : res.json(message);
|
|
616
|
+
} catch (error) {
|
|
617
|
+
const status = error.$metadata?.httpStatusCode;
|
|
618
|
+
const detail = `${error.name || 'Error'}${status ? ` ${status}` : ''}: ${error.message}`;
|
|
619
|
+
console.error(`🚨 bedrock ${modelId}: ${detail}`);
|
|
620
|
+
if (live?.started) return live.fail(new Error(`Bedrock ${modelId}: ${detail}`));
|
|
621
|
+
if (res.headersSent) return;
|
|
622
|
+
// 403 (access, verification) will not fix itself; anything else gets 500 so Claude Code retries the same model.
|
|
623
|
+
return status === 403
|
|
624
|
+
? anthropicError(res, 403, 'permission_error', `Bedrock ${modelId}: ${detail}`)
|
|
625
|
+
: anthropicError(res, 500, 'api_error', `Bedrock ${modelId}: ${detail}`);
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// ============================================
|
|
630
|
+
// Google Gemini / Vertex AI: direct streaming API, 1M context, native tool calls + thoughtSignature preservation
|
|
631
|
+
// ============================================
|
|
632
|
+
|
|
633
|
+
const GEMINI_USAGE_FILE = path.join(LABS_DIR, 'gemini-usage.jsonl');
|
|
634
|
+
const geminiSignatures = new ThoughtSignatureStore(path.join(LABS_DIR, 'gemini-signatures.json'));
|
|
635
|
+
// gemini-4-* models are served by the ElevenLabs gateway directly (no Google API key needed).
|
|
636
|
+
// Only models with the "gemini:" prefix go through the direct Google AI Studio / Vertex AI path.
|
|
637
|
+
const DIRECT_GEMINI_MODELS = new Set([]);
|
|
638
|
+
|
|
639
|
+
function geminiRoute(model, launchModel) {
|
|
640
|
+
const clean = String(model || '').replace(/\[1m\]$/i, '');
|
|
641
|
+
const directAlias = geminiModelId(aliases[clean]) || geminiModelId(clean);
|
|
642
|
+
if (directAlias) return directAlias;
|
|
643
|
+
if (DIRECT_GEMINI_MODELS.has(clean)) return clean;
|
|
644
|
+
const launched = geminiModelId(aliases[launchModel]) || geminiModelId(launchModel)
|
|
645
|
+
|| (DIRECT_GEMINI_MODELS.has(launchModel) ? launchModel : null);
|
|
646
|
+
return launched && (!model || /^claude-/.test(model)) ? launched : null;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
async function handleGemini(req, res, modelId) {
|
|
650
|
+
const { model, stream, tools = [], messages = [], output_config: outputConfig } = req.body;
|
|
651
|
+
const auth = resolveGeminiAuth(LABS_DIR, loadEffectiveConfig());
|
|
652
|
+
if (!auth) {
|
|
653
|
+
return anthropicError(res, 401, 'authentication_error', 'No Gemini API key or Vertex AI project configured. Run: labs gemini');
|
|
654
|
+
}
|
|
655
|
+
const effort = outputConfig?.effort || req.get('x-labs-effort') || config.defaultEffort || 'high';
|
|
656
|
+
const estimate = Math.ceil(JSON.stringify(req.body).length / 4);
|
|
657
|
+
console.log(`\n🔷 ${model} -> ${auth.mode} ${modelId} (effort=${effort}) | ${messages.length} messages | ${tools.length} tools`);
|
|
658
|
+
const live = stream ? createLiveStream(res, { model, inputTokens: estimate }) : null;
|
|
659
|
+
const abort = new AbortController();
|
|
660
|
+
res.on('close', () => { if (!res.writableEnded) abort.abort(); });
|
|
661
|
+
const started = Date.now();
|
|
662
|
+
try {
|
|
663
|
+
const result = await streamGemini({
|
|
664
|
+
auth,
|
|
665
|
+
body: req.body,
|
|
666
|
+
modelId,
|
|
667
|
+
effort,
|
|
668
|
+
signal: abort.signal,
|
|
669
|
+
signatures: geminiSignatures,
|
|
670
|
+
onText: live && (delta => live.text(delta)),
|
|
671
|
+
onThinking: live && (delta => live.thinking(delta))
|
|
672
|
+
});
|
|
673
|
+
const message = createAnthropicMessage({
|
|
674
|
+
model,
|
|
675
|
+
text: live?.started ? live.streamedText : result.text,
|
|
676
|
+
thinking: live?.started ? live.streamedThinking : result.thinking,
|
|
677
|
+
toolCalls: result.toolCalls,
|
|
678
|
+
inputTokens: result.usage.inputTokens || estimate
|
|
679
|
+
});
|
|
680
|
+
if (result.usage.outputTokens) message.usage.output_tokens = result.usage.outputTokens;
|
|
681
|
+
if (result.stopReason === 'max_tokens') message.stop_reason = 'max_tokens';
|
|
682
|
+
const seconds = ((Date.now() - started) / 1000).toFixed(1);
|
|
683
|
+
console.log(`🔷 ${seconds}s | in ${result.usage.inputTokens} (cached ${result.usage.cachedTokens || 0}) out ${result.usage.outputTokens} tokens | ${result.toolCalls.length} tool calls`);
|
|
684
|
+
fs.mkdirSync(LABS_DIR, { recursive: true });
|
|
685
|
+
fs.appendFileSync(GEMINI_USAGE_FILE, `${JSON.stringify({ at: new Date().toISOString(), mode: auth.mode, modelId, input: result.usage.inputTokens, cached: result.usage.cachedTokens || 0, output: result.usage.outputTokens, seconds: Number(seconds) })}\n`);
|
|
686
|
+
return live ? live.finish(message) : res.json(message);
|
|
687
|
+
} catch (error) {
|
|
688
|
+
const status = error.status;
|
|
689
|
+
const detail = `${status ? `${status}: ` : ''}${error.message}`;
|
|
690
|
+
console.error(`🚨 gemini ${modelId}: ${detail}`);
|
|
691
|
+
if (live?.started) return live.fail(new Error(`Gemini ${modelId}: ${detail}`));
|
|
692
|
+
if (res.headersSent) return;
|
|
693
|
+
if (status === 401 || status === 403) return anthropicError(res, status, 'authentication_error', `Gemini ${modelId}: ${detail}`);
|
|
694
|
+
if (status === 402) return anthropicError(res, 402, 'invalid_request_error', `Gemini ${modelId}: ${detail} (Top up at https://ai.studio/projects or switch to Vertex AI via: labs gemini)`);
|
|
695
|
+
if (status === 400) return anthropicError(res, 400, 'invalid_request_error', `Gemini ${modelId}: ${detail}`);
|
|
696
|
+
// Transient errors (429, 5xx, network) return 500 so Claude Code retries the same Gemini model without switching.
|
|
697
|
+
return anthropicError(res, 500, 'api_error', `Gemini ${modelId}: ${detail}`);
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
// ============================================
|
|
702
|
+
// Antigravity CLI (agy) ACP Bridge: Gemini 4 Hydrogen / 3.8 Flash / Claude 4.6 / GPT-OSS via signed-in agy CLI
|
|
703
|
+
// ============================================
|
|
704
|
+
|
|
705
|
+
function agyRoute(model, launchModel) {
|
|
706
|
+
const clean = String(model || '').replace(/\[1m\]$/i, '');
|
|
707
|
+
const explicit = agyModelId(aliases[clean]) || agyModelId(clean);
|
|
708
|
+
if (explicit) return explicit;
|
|
709
|
+
const launchedExplicit = agyModelId(aliases[launchModel]) || agyModelId(launchModel);
|
|
710
|
+
if (launchedExplicit) {
|
|
711
|
+
if (clean in AGY_MODELS) return clean;
|
|
712
|
+
if (/^claude-haiku/i.test(clean)) return 'gemini-3.8-flash';
|
|
713
|
+
if (!model || /^claude-/.test(model)) return launchedExplicit;
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
const cfg = loadEffectiveConfig();
|
|
717
|
+
if (!hasElevenLabs && !resolveGeminiAuth(LABS_DIR, cfg) && hasAgyCli()) {
|
|
718
|
+
const directTarget = aliases[clean] || clean;
|
|
719
|
+
if (isAgyFallbackModel(directTarget)) return directTarget;
|
|
720
|
+
const launchTarget = aliases[launchModel] || launchModel;
|
|
721
|
+
if (isAgyFallbackModel(launchTarget) && (!model || /^claude-/.test(model))) return launchTarget;
|
|
722
|
+
}
|
|
723
|
+
return null;
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
async function handleAgy(req, res, modelId) {
|
|
727
|
+
if (!hasAgyCli()) {
|
|
728
|
+
return anthropicError(res, 401, 'authentication_error', 'Antigravity CLI (agy) is not installed or not in PATH.');
|
|
729
|
+
}
|
|
730
|
+
const { model, stream, tools = [], messages = [], output_config: outputConfig } = req.body;
|
|
731
|
+
const launchModel = req.get('x-labs-model');
|
|
732
|
+
const isHaikuCall = /^claude-haiku/i.test(model || '') || (model === 'gemini-3.8-flash' && !/flash|gemini3/i.test(launchModel || ''));
|
|
733
|
+
const effort = isHaikuCall ? 'low' : (outputConfig?.effort || req.get('x-labs-effort') || config.defaultEffort || 'high');
|
|
734
|
+
const estimate = Math.ceil(JSON.stringify(req.body).length / 4);
|
|
735
|
+
console.log(`\n🧪 ${model} -> agy ${modelId} (effort=${effort}${tools.length === 0 ? ', side call' : ''}) | ${messages.length} messages | ${tools.length} tools | ${Math.round(JSON.stringify(req.body).length / 1024)} KB`);
|
|
736
|
+
const live = stream ? createLiveStream(res, { model, inputTokens: estimate }) : null;
|
|
737
|
+
const abort = new AbortController();
|
|
738
|
+
res.on('close', () => { if (!res.writableEnded) abort.abort(); });
|
|
739
|
+
const started = Date.now();
|
|
740
|
+
try {
|
|
741
|
+
const result = await agyBridge.runTurn({
|
|
742
|
+
req,
|
|
743
|
+
modelId,
|
|
744
|
+
effort,
|
|
745
|
+
body: {
|
|
746
|
+
...req.body,
|
|
747
|
+
tools: tools.filter(tool => tool.name && tool.input_schema)
|
|
748
|
+
},
|
|
749
|
+
signal: abort.signal,
|
|
750
|
+
onText: live && (delta => live.text(delta)),
|
|
751
|
+
onThinking: live && (delta => live.thinking(delta))
|
|
752
|
+
});
|
|
753
|
+
const inputTokens = result.usage?.inputTokens || result.contextUsed || estimate;
|
|
754
|
+
const message = createAnthropicMessage({
|
|
755
|
+
model,
|
|
756
|
+
text: live?.started ? live.streamedText : result.text,
|
|
757
|
+
thinking: live?.started ? live.streamedThinking : result.thinking,
|
|
758
|
+
toolCalls: result.toolCalls,
|
|
759
|
+
inputTokens
|
|
760
|
+
});
|
|
761
|
+
if (result.usage?.outputTokens) message.usage.output_tokens = result.usage.outputTokens;
|
|
762
|
+
const seconds = ((Date.now() - started) / 1000).toFixed(1);
|
|
763
|
+
console.log(`🧪 ${seconds}s | in ${inputTokens} (cached ${result.usage?.cachedReadTokens || 0}) out ${message.usage.output_tokens} tokens | ${result.toolCalls.length} tool calls`);
|
|
764
|
+
agyBridge.logUsage({
|
|
765
|
+
modelId,
|
|
766
|
+
input: result.usage?.inputTokens || 0,
|
|
767
|
+
cached: result.usage?.cachedReadTokens || 0,
|
|
768
|
+
output: result.usage?.outputTokens || 0,
|
|
769
|
+
seconds: Number(seconds)
|
|
770
|
+
});
|
|
771
|
+
return live ? live.finish(message) : res.json(message);
|
|
772
|
+
} catch (error) {
|
|
773
|
+
const detail = error.message || 'Unknown agy error';
|
|
774
|
+
console.error(`🚨 agy ${modelId}: ${detail}`);
|
|
775
|
+
if (live?.started) return live.fail(new Error(`agy ${modelId}: ${detail}`));
|
|
776
|
+
if (res.headersSent) return;
|
|
777
|
+
if (/not authenticated|login|unauthorized|auth/i.test(detail)) {
|
|
778
|
+
return anthropicError(res, 401, 'authentication_error', `agy ${modelId}: ${detail}. Run: agy acp --login`);
|
|
779
|
+
}
|
|
780
|
+
if (error.status === 429) {
|
|
781
|
+
return anthropicError(res, 429, 'rate_limit_error', `agy ${modelId}: ${detail}`);
|
|
782
|
+
}
|
|
783
|
+
return anthropicError(res, 500, 'api_error', `agy ${modelId}: ${detail}`);
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
// ============================================
|
|
788
|
+
// HTTP: Anthropic Messages API
|
|
789
|
+
// ============================================
|
|
790
|
+
|
|
791
|
+
const app = express();
|
|
792
|
+
const PROXY_KEY = loadProxyKey(LABS_DIR);
|
|
793
|
+
const agyBridge = createAgyBridge({ port: PORT, proxyKey: PROXY_KEY, labsDir: LABS_DIR, config });
|
|
794
|
+
app.use((req, res, next) => {
|
|
795
|
+
const refusal = rejectLocalRequest(
|
|
796
|
+
{ host: req.get('host'), path: req.path, authorization: req.get('authorization'), apiKey: hasChatSession(req) ? PROXY_KEY : req.get('x-api-key') },
|
|
797
|
+
{ port: PORT, key: PROXY_KEY });
|
|
798
|
+
return refusal ? anthropicError(res, refusal.status, refusal.type, refusal.message) : next();
|
|
799
|
+
});
|
|
800
|
+
app.use(bodyParser.json({ limit: '50mb' }));
|
|
801
|
+
mountChat(app, { labsDir: LABS_DIR, proxyKey: PROXY_KEY });
|
|
802
|
+
agyBridge.mount(app);
|
|
803
|
+
|
|
804
|
+
app.post('/v1/messages', async (req, res) => {
|
|
805
|
+
const { model, messages = [], system, stream, metadata, tools = [], max_tokens: maxTokens, output_config: outputConfig } = req.body;
|
|
806
|
+
const launchModel = req.get('x-labs-model');
|
|
807
|
+
const agyId = agyRoute(model, launchModel);
|
|
808
|
+
if (agyId) return handleAgy(req, res, agyId);
|
|
809
|
+
const geminiId = geminiRoute(model, launchModel);
|
|
810
|
+
if (geminiId) return handleGemini(req, res, geminiId);
|
|
811
|
+
const bedrockId = bedrockRoute(model, launchModel);
|
|
812
|
+
if (bedrockId) return handleBedrock(req, res, bedrockId);
|
|
813
|
+
if (!hasElevenLabs) {
|
|
814
|
+
return anthropicError(res, 401, 'authentication_error', 'ElevenLabs is not configured. Run: labs setup (or use labs --model gemini / labs --model glm)');
|
|
815
|
+
}
|
|
816
|
+
// Claude Code answers repeated errors by falling back opus -> sonnet -> haiku on its own; on the main thread
|
|
817
|
+
// (tools present) a Claude id therefore means "fallback", so stay on the model the user launched with.
|
|
818
|
+
const isClaudeFallback = /^claude-/.test(model || '') && (req.body.tools || []).length > 0 && Boolean(launchModel);
|
|
819
|
+
const requested = resolveLlm(isClaudeFallback ? launchModel : model, launchModel, aliases, llmIds);
|
|
820
|
+
// Claude Code's side calls (titles, summaries, compaction) carry no tools: 215 of them ran on Opus and Sonnet in
|
|
821
|
+
// one day, each 30k-500k uncached tokens. They go to config.sideModel ("sideModel": false keeps the asked model).
|
|
822
|
+
const sideModel = tools.length === 0 && config.sideModel && llmIds.has(config.sideModel) ? config.sideModel : null;
|
|
823
|
+
const llm = requested && (sideModel || requested);
|
|
824
|
+
console.log(`\n🤖 ${model} -> ${llm || 'UNKNOWN'}${sideModel ? ' (side call)' : ''} | ${messages.length} messages | ${tools.length} tools`);
|
|
825
|
+
if (!llm) return anthropicError(res, 400, 'invalid_request_error', `Unknown model "${model}". Run "labs models" to list models.`);
|
|
826
|
+
|
|
827
|
+
let live = null;
|
|
828
|
+
try {
|
|
829
|
+
const latest = extractLatestUserContent(messages);
|
|
830
|
+
if (!latest.text && latest.toolResults.length === 0 && latest.images.length === 0) {
|
|
831
|
+
return anthropicError(res, 400, 'invalid_request_error', 'No text or tool result in the latest user message');
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
// Claude Code's side calls (titles, summaries) carry no tools; keep them out of the coding conversation.
|
|
835
|
+
const isSideRequest = tools.length === 0;
|
|
836
|
+
const sessionId = req.get('x-labs-session-id') || metadata?.session_id || `side_${Date.now()}`;
|
|
837
|
+
const threadId = isValidSessionId(sessionId) ? createThreadId(sessionId, messages) : createThreadId('anon', messages);
|
|
838
|
+
const toolIds = isSideRequest ? [] : await toolRegistry.ensure(tools.filter(isForwardedTool));
|
|
839
|
+
const priorContent = lastAssistantContent(messages);
|
|
840
|
+
const priorReply = priorContent ? replySignature(priorContent) : null;
|
|
841
|
+
// Everything up to the last reply is history; the user turn and system messages after it are this turn.
|
|
842
|
+
const history = messages.slice(0, messages.findLastIndex(message => message.role === 'assistant') + 1);
|
|
843
|
+
if (!isSideRequest) await shuntBigReads(latest.toolResults, priorContent, formatConversationHistory(history.slice(-1)).slice(0, 2000));
|
|
844
|
+
|
|
845
|
+
// Claude Code decides when to auto-compact from input_tokens, so report the whole request, not just the last turn.
|
|
846
|
+
// Base64 images and documents are thousands of characters but roughly 1.5k tokens each to a model; counting
|
|
847
|
+
// their raw length made Claude Code believe the window was full and compact after every prompt.
|
|
848
|
+
const IMAGE_TOKENS_AS_CHARS = 6000;
|
|
849
|
+
const withoutBinary = JSON.stringify(messages, (field, value) =>
|
|
850
|
+
field === 'data' && typeof value === 'string' && value.length > IMAGE_TOKENS_AS_CHARS ? 'x'.repeat(IMAGE_TOKENS_AS_CHARS) : value);
|
|
851
|
+
const requestChars = JSON.stringify(system || '').length + withoutBinary.length + JSON.stringify(tools.filter(isForwardedTool)).length;
|
|
852
|
+
live = stream ? createLiveStream(res, { model, inputTokens: Math.ceil(requestChars / 4) }) : null;
|
|
853
|
+
let conn;
|
|
854
|
+
let result;
|
|
855
|
+
let continued = false;
|
|
856
|
+
let slowRetried = 0;
|
|
857
|
+
for (;;) {
|
|
858
|
+
const settings = agentSettingsFor(llm, outputConfig?.effort || 'high', maxTokens);
|
|
859
|
+
const prefix = `${llm}:${settings.reasoning_effort}:`;
|
|
860
|
+
conn = isSideRequest ? null : claimContinuingConversation(prefix, priorReply, toolIds);
|
|
861
|
+
continued = Boolean(conn);
|
|
862
|
+
if (!conn) {
|
|
863
|
+
const key = isSideRequest
|
|
864
|
+
? `side_${Date.now()}_${Math.random().toString(36).slice(2)}`
|
|
865
|
+
: `${prefix}${threadId}:${++conversationCounter}`;
|
|
866
|
+
const conversationTools = isSideRequest ? [] : [...new Set([...toolIds, ...toolRegistry.recentIds(PRELOAD_WINDOW_MS, PRELOAD_MAX_TOOLS).filter(id => toolRegistry.isAttached(id))])];
|
|
867
|
+
conn = await withAgentSettings(settings, () => openConversation(key, { llm, prompt: `${systemText(system) || 'You are a helpful assistant.'}${BRIDGE_NOTE}`, toolIds: conversationTools }));
|
|
868
|
+
conn.claimed = true;
|
|
869
|
+
}
|
|
870
|
+
// Past the 10-file limit the main conversation stays put: a side conversation looks at the new images and
|
|
871
|
+
// its description enters the same chat as text, so no context is lost to a fresh conversation.
|
|
872
|
+
if (latest.images.length && conn.filesUploaded + latest.images.length > MAX_FILES_PER_CONVERSATION) {
|
|
873
|
+
const description = await describeImages(llm, settings, latest.images, latest.text);
|
|
874
|
+
latest.text = `${latest.text}\n\n[Image descriptions. This chat already holds ElevenLabs' maximum of ${MAX_FILES_PER_CONVERSATION} images, so a vision pass on the same model described the new ones:]\n${description}`;
|
|
875
|
+
latest.images = [];
|
|
876
|
+
}
|
|
877
|
+
try {
|
|
878
|
+
result = await sendTurn(conn, {
|
|
879
|
+
text: latest.text, toolResults: latest.toolResults, images: latest.images, history,
|
|
880
|
+
replayChars: replayBudget(llm), onDelta: live && (delta => live.text(delta))
|
|
881
|
+
});
|
|
882
|
+
conn.claimed = false;
|
|
883
|
+
break;
|
|
884
|
+
} catch (error) {
|
|
885
|
+
conn.claimed = false;
|
|
886
|
+
const slow = /Cascade Error: TimeoutError|took too long/.test(error.message);
|
|
887
|
+
if (live?.started || !slow) throw error;
|
|
888
|
+
// Each error Claude Code sees counts toward its "high demand" model switch, and Boss wants the chosen
|
|
889
|
+
// effort kept, so a slow first token is retried at the same model and effort, never lowered.
|
|
890
|
+
if (++slowRetried > MAX_SLOW_RETRIES) throw error;
|
|
891
|
+
console.log(`🔁 ${llm} slow first token; retry ${slowRetried}/${MAX_SLOW_RETRIES} at effort=${settings.reasoning_effort}`);
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
if (!isSideRequest) {
|
|
896
|
+
reuse.requests += 1;
|
|
897
|
+
if (continued) reuse.continued += 1;
|
|
898
|
+
console.log(`♻️ ${continued ? 'continued' : 'NEW'} conversation | reuse ${reuse.continued}/${reuse.requests}`);
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
const message = createAnthropicMessage({
|
|
902
|
+
model,
|
|
903
|
+
text: live?.started ? live.streamedText : result.text || '',
|
|
904
|
+
toolCalls: result.toolCalls || [],
|
|
905
|
+
inputTokens: conn.contextTokens || Math.ceil(requestChars / 4)
|
|
906
|
+
});
|
|
907
|
+
|
|
908
|
+
conn.lastReply = replySignature(message.content);
|
|
909
|
+
if (isSideRequest) conn.ws.close();
|
|
910
|
+
else saveConversation(threadId, llm, conn.conversationId, [...messages, { role: 'assistant', content: message.content }]);
|
|
911
|
+
|
|
912
|
+
return live ? live.finish(message) : res.json(message);
|
|
913
|
+
} catch (error) {
|
|
914
|
+
// A bare "status code 400" hid the cause for a whole day; ElevenLabs puts the reason in the response body.
|
|
915
|
+
const detail = error.response?.data ? `${error.message}: ${JSON.stringify(error.response.data).slice(0, 300)}` : error.message;
|
|
916
|
+
console.error(`🚨 ${llm}: ${detail}`);
|
|
917
|
+
if (live?.started) return live.fail(new Error(`ElevenLabs ${llm}: ${detail}`));
|
|
918
|
+
// 500, not 529: Claude Code retries a 500 on the same model, but answers repeated 529s by switching models.
|
|
919
|
+
if (!res.headersSent) return anthropicError(res, 500, 'api_error', `ElevenLabs ${llm}: ${detail}`);
|
|
920
|
+
}
|
|
921
|
+
});
|
|
922
|
+
|
|
923
|
+
app.get('/health', (req, res) => res.json({ name: 'labs-claude', version: VERSION, credentials: credentialFingerprint(config), code: CODE }));
|
|
924
|
+
|
|
925
|
+
app.post('/shutdown', (req, res) => {
|
|
926
|
+
res.json({ ok: true });
|
|
927
|
+
agyBridge.shutdown();
|
|
928
|
+
setTimeout(() => process.exit(0), 100);
|
|
929
|
+
});
|
|
930
|
+
|
|
931
|
+
app.get('/v1/models', (req, res) => {
|
|
932
|
+
const aliasEntries = Object.entries(aliases).map(([id, llm]) => ({ id, type: 'model', display_name: `${id} (${llm})` }));
|
|
933
|
+
const agyEntries = Object.keys(AGY_MODELS)
|
|
934
|
+
.filter(id => !(id in aliases))
|
|
935
|
+
.map(id => ({ id, type: 'model', display_name: `${id} (agy)` }));
|
|
936
|
+
res.json({ data: [...agyEntries, ...aliasEntries] });
|
|
937
|
+
});
|
|
938
|
+
|
|
939
|
+
app.get('/v1/sessions', (req, res) => {
|
|
940
|
+
if (!fs.existsSync(CONVERSATIONS_DIR)) return res.json({ sessions: [] });
|
|
941
|
+
const sessions = fs.readdirSync(CONVERSATIONS_DIR).filter(file => file.endsWith('.json')).map(file => {
|
|
942
|
+
const data = JSON.parse(fs.readFileSync(path.join(CONVERSATIONS_DIR, file), 'utf8'));
|
|
943
|
+
return { id: file.replace('.json', ''), llm: data.llm || data.agentId, messageCount: (data.history || []).length, updatedAt: data.updatedAt };
|
|
944
|
+
});
|
|
945
|
+
res.json({ sessions: sessions.sort((a, b) => b.updatedAt - a.updatedAt) });
|
|
946
|
+
});
|
|
947
|
+
|
|
948
|
+
app.delete('/v1/sessions/:sessionId', (req, res) => {
|
|
949
|
+
const { sessionId } = req.params;
|
|
950
|
+
if (!isValidSessionId(sessionId)) return res.status(400).json({ error: 'Invalid session ID' });
|
|
951
|
+
const filePath = path.join(CONVERSATIONS_DIR, `${sessionId}.json`);
|
|
952
|
+
if (!fs.existsSync(filePath)) return res.status(404).json({ error: 'Session not found' });
|
|
953
|
+
fs.unlinkSync(filePath);
|
|
954
|
+
res.json({ success: true });
|
|
955
|
+
});
|
|
956
|
+
|
|
957
|
+
process.on('uncaughtException', error => console.error(`💥 Uncaught: ${error.stack}`));
|
|
958
|
+
process.on('unhandledRejection', error => console.error(`💥 Unhandled rejection: ${error?.stack || error}`));
|
|
959
|
+
|
|
960
|
+
process.on('SIGINT', () => {
|
|
961
|
+
agyBridge.shutdown();
|
|
962
|
+
connections.forEach(conn => conn.ws.close());
|
|
963
|
+
process.exit(0);
|
|
964
|
+
});
|
|
965
|
+
|
|
966
|
+
// Express 5 hands a failed listen to this callback; ignoring it logged "LIVE" for every duplicate (319 in one log),
|
|
967
|
+
// which hid the one proxy that really serves. The port is the single-instance lock.
|
|
968
|
+
app.listen(PORT, '127.0.0.1', error => {
|
|
969
|
+
if (error) {
|
|
970
|
+
console.log(`🟰 ${new Date().toISOString()} another labs proxy already holds port ${PORT}; this copy exits (${error.code})`);
|
|
971
|
+
process.exit(0);
|
|
972
|
+
}
|
|
973
|
+
console.log(`✅ ${new Date().toISOString()} Proxy LIVE at http://localhost:${PORT}${hasElevenLabs ? ` | bridge agent ${config.bridgeAgent}` : ' | direct API mode'}`);
|
|
974
|
+
agyBridge.warmup();
|
|
975
|
+
refreshLlmList();
|
|
976
|
+
});
|