labs-claude 0.2.6 ā 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 +157 -122
- package/bin/labs.js +392 -178
- package/package.json +35 -34
- package/src/agy.js +1016 -0
- package/src/anthropic-protocol.js +84 -17
- package/src/auto-fallback.js +95 -0
- package/src/autostart.js +43 -43
- package/src/bedrock.js +162 -162
- package/src/browser-setup.js +38 -38
- package/src/chat/index.html +543 -534
- package/src/chat-routes.js +149 -149
- package/src/config.js +43 -5
- package/src/gateway-client.js +173 -0
- package/src/gemini.js +474 -0
- package/src/image-mcp.js +174 -0
- package/src/launch-args.js +15 -4
- package/src/local-auth.js +33 -33
- package/src/proxy-manager.js +87 -82
- package/src/proxy.js +187 -12
- package/src/read-shunt.js +26 -26
- package/src/setup.js +43 -1
- package/src/subscription-failure.js +36 -0
- package/src/ui.js +181 -0
- package/src/usage.js +84 -44
- package/src/web-mcp.js +253 -0
package/src/local-auth.js
CHANGED
|
@@ -1,33 +1,33 @@
|
|
|
1
|
-
const { randomBytes, timingSafeEqual } = require('crypto');
|
|
2
|
-
const fs = require('fs');
|
|
3
|
-
const path = require('path');
|
|
4
|
-
|
|
5
|
-
// Any local program, or a web page that rebinds a domain to 127.0.0.1, could otherwise spend the user's ElevenLabs
|
|
6
|
-
// credits through the proxy and read saved conversations. Claude Code sends the key as its ANTHROPIC_AUTH_TOKEN.
|
|
7
|
-
function loadProxyKey(labsDir) {
|
|
8
|
-
const file = path.join(labsDir, 'proxy-key');
|
|
9
|
-
if (!fs.existsSync(file)) {
|
|
10
|
-
fs.mkdirSync(labsDir, { recursive: true });
|
|
11
|
-
fs.writeFileSync(file, randomBytes(32).toString('hex'), { mode: 0o600 });
|
|
12
|
-
}
|
|
13
|
-
return fs.readFileSync(file, 'utf8').trim();
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
function sameKey(given, key) {
|
|
17
|
-
const a = Buffer.from(String(given || ''));
|
|
18
|
-
const b = Buffer.from(key);
|
|
19
|
-
return a.length === b.length && timingSafeEqual(a, b);
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
// Returns null for an allowed request, otherwise the Anthropic-style error to answer with.
|
|
23
|
-
function rejectLocalRequest({ host, path: route, authorization, apiKey }, { port, key }) {
|
|
24
|
-
if (![`127.0.0.1:${port}`, `localhost:${port}`].includes(host)) {
|
|
25
|
-
return { status: 403, type: 'permission_error', message: `Host "${host}" is not the local labs proxy` };
|
|
26
|
-
}
|
|
27
|
-
// The chat page itself is static (no data) and its login checks the key on its own.
|
|
28
|
-
if (['/health', '/chat', '/chat/', '/chat/login', '/chat/open'].includes(route)) return null;
|
|
29
|
-
const given = apiKey || String(authorization || '').replace(/^Bearer\s+/i, '');
|
|
30
|
-
return sameKey(given, key) ? null : { status: 401, type: 'authentication_error', message: 'labs proxy key required (start Claude Code with the labs command)' };
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
module.exports = { loadProxyKey, rejectLocalRequest };
|
|
1
|
+
const { randomBytes, timingSafeEqual } = require('crypto');
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
|
|
5
|
+
// Any local program, or a web page that rebinds a domain to 127.0.0.1, could otherwise spend the user's ElevenLabs
|
|
6
|
+
// credits through the proxy and read saved conversations. Claude Code sends the key as its ANTHROPIC_AUTH_TOKEN.
|
|
7
|
+
function loadProxyKey(labsDir) {
|
|
8
|
+
const file = path.join(labsDir, 'proxy-key');
|
|
9
|
+
if (!fs.existsSync(file)) {
|
|
10
|
+
fs.mkdirSync(labsDir, { recursive: true });
|
|
11
|
+
fs.writeFileSync(file, randomBytes(32).toString('hex'), { mode: 0o600 });
|
|
12
|
+
}
|
|
13
|
+
return fs.readFileSync(file, 'utf8').trim();
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function sameKey(given, key) {
|
|
17
|
+
const a = Buffer.from(String(given || ''));
|
|
18
|
+
const b = Buffer.from(key);
|
|
19
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Returns null for an allowed request, otherwise the Anthropic-style error to answer with.
|
|
23
|
+
function rejectLocalRequest({ host, path: route, authorization, apiKey }, { port, key }) {
|
|
24
|
+
if (![`127.0.0.1:${port}`, `localhost:${port}`].includes(host)) {
|
|
25
|
+
return { status: 403, type: 'permission_error', message: `Host "${host}" is not the local labs proxy` };
|
|
26
|
+
}
|
|
27
|
+
// The chat page itself is static (no data) and its login checks the key on its own.
|
|
28
|
+
if (['/health', '/chat', '/chat/', '/chat/login', '/chat/open'].includes(route)) return null;
|
|
29
|
+
const given = apiKey || String(authorization || '').replace(/^Bearer\s+/i, '');
|
|
30
|
+
return sameKey(given, key) ? null : { status: 401, type: 'authentication_error', message: 'labs proxy key required (start Claude Code with the labs command)' };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
module.exports = { loadProxyKey, rejectLocalRequest };
|
package/src/proxy-manager.js
CHANGED
|
@@ -1,82 +1,87 @@
|
|
|
1
|
-
const axios = require('axios');
|
|
2
|
-
const fs = require('fs');
|
|
3
|
-
const path = require('path');
|
|
4
|
-
const { spawn } = require('child_process');
|
|
5
|
-
const { LABS_DIR } = require('./config');
|
|
6
|
-
const { loadProxyKey } = require('./local-auth');
|
|
7
|
-
const { version: VERSION } = require('../package.json');
|
|
8
|
-
|
|
9
|
-
async function health(port) {
|
|
10
|
-
try {
|
|
11
|
-
return (await axios.get(`http://127.0.0.1:${port}/health`, { timeout: 1000 })).data;
|
|
12
|
-
} catch {
|
|
13
|
-
return null;
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
// Reuses a running proxy of the same version; an older version (after `npm update -g`)
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
child.
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
//
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
restarting
|
|
68
|
-
//
|
|
69
|
-
|
|
70
|
-
await
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
|
|
1
|
+
const axios = require('axios');
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
const { spawn } = require('child_process');
|
|
5
|
+
const { LABS_DIR, codeFingerprint, credentialFingerprint, loadConfig } = require('./config');
|
|
6
|
+
const { loadProxyKey } = require('./local-auth');
|
|
7
|
+
const { version: VERSION } = require('../package.json');
|
|
8
|
+
|
|
9
|
+
async function health(port) {
|
|
10
|
+
try {
|
|
11
|
+
return (await axios.get(`http://127.0.0.1:${port}/health`, { timeout: 1000 })).data;
|
|
12
|
+
} catch {
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Reuses a running proxy of the same version, key and code; an older version (after `npm update -g`), one still holding
|
|
18
|
+
// an old ElevenLabs key or bridge agent (after `labs setup` with a new account), or one running code that has since
|
|
19
|
+
// changed on disk is stopped and replaced.
|
|
20
|
+
async function ensureProxy(port) {
|
|
21
|
+
const wanted = credentialFingerprint(loadConfig());
|
|
22
|
+
const code = codeFingerprint();
|
|
23
|
+
const isCurrent = info => info?.name === 'labs-claude' && info.version === VERSION && info.credentials === wanted && info.code === code;
|
|
24
|
+
const running = await health(port);
|
|
25
|
+
if (isCurrent(running)) return true;
|
|
26
|
+
if (running?.name === 'labs-claude') {
|
|
27
|
+
await stopProxy(port);
|
|
28
|
+
await new Promise(resolve => setTimeout(resolve, 500));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
fs.mkdirSync(LABS_DIR, { recursive: true });
|
|
32
|
+
const log = fs.openSync(path.join(LABS_DIR, 'proxy.log'), 'a');
|
|
33
|
+
const child = spawn(process.execPath, [path.join(__dirname, 'proxy.js')], {
|
|
34
|
+
detached: true,
|
|
35
|
+
stdio: ['ignore', log, log],
|
|
36
|
+
windowsHide: true
|
|
37
|
+
});
|
|
38
|
+
child.unref();
|
|
39
|
+
|
|
40
|
+
for (let attempt = 0; attempt < 120; attempt += 1) {
|
|
41
|
+
if (isCurrent(await health(port))) return true;
|
|
42
|
+
await new Promise(resolve => setTimeout(resolve, 250));
|
|
43
|
+
}
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Claude Code only reaches the proxy, so a proxy that died (crash, `labs stop`, an upgrade) left every open window
|
|
48
|
+
// retrying ECONNREFUSED until it gave up. While Claude Code runs, the launcher restarts a dead proxy within seconds.
|
|
49
|
+
// It never replaces a running proxy of another version: windows of different versions would fight over the port.
|
|
50
|
+
const WATCHDOG_MS = 5000;
|
|
51
|
+
const BUSY_PROXY_TIMEOUT_MS = 3000;
|
|
52
|
+
|
|
53
|
+
// Only a refused connection means no proxy. A slow /health is a busy proxy: treating it as dead spawned duplicates.
|
|
54
|
+
async function isProxyDown(port) {
|
|
55
|
+
try {
|
|
56
|
+
await axios.get(`http://127.0.0.1:${port}/health`, { timeout: BUSY_PROXY_TIMEOUT_MS });
|
|
57
|
+
return false;
|
|
58
|
+
} catch (error) {
|
|
59
|
+
return error.code === 'ECONNREFUSED';
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function keepProxyAlive(port) {
|
|
64
|
+
let restarting = false;
|
|
65
|
+
let misses = 0;
|
|
66
|
+
const timer = setInterval(async () => {
|
|
67
|
+
if (restarting) return;
|
|
68
|
+
// Two misses in a row: a newer labs replacing the proxy leaves the port free for a moment, and restarting
|
|
69
|
+
// this window's older version in that gap would take the port from the upgrade.
|
|
70
|
+
misses = await isProxyDown(port) ? misses + 1 : 0;
|
|
71
|
+
if (misses < 2) return;
|
|
72
|
+
restarting = true;
|
|
73
|
+
// Never print here: this runs inside Claude Code's terminal, and a line written there lands in Boss's input box.
|
|
74
|
+
fs.appendFileSync(path.join(LABS_DIR, 'proxy.log'), `ā ļø ${new Date().toISOString()} watchdog: labs proxy was down; restarting it\n`);
|
|
75
|
+
await ensureProxy(port).catch(() => {});
|
|
76
|
+
restarting = false;
|
|
77
|
+
}, WATCHDOG_MS);
|
|
78
|
+
timer.unref();
|
|
79
|
+
return timer;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function stopProxy(port) {
|
|
83
|
+
return axios.post(`http://127.0.0.1:${port}/shutdown`, null, { headers: { 'x-api-key': loadProxyKey(LABS_DIR) } })
|
|
84
|
+
.then(() => true, () => false);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
module.exports = { ensureProxy, keepProxyAlive, stopProxy };
|
package/src/proxy.js
CHANGED
|
@@ -20,8 +20,11 @@ const { ToolRegistry } = require('./elevenlabs-tools');
|
|
|
20
20
|
const { oversizedWholeFileReads, shuntNote, WORKER_PROMPT } = require('./read-shunt');
|
|
21
21
|
const { loadProxyKey, rejectLocalRequest } = require('./local-auth');
|
|
22
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');
|
|
23
25
|
const { hasChatSession, mountChat } = require('./chat-routes');
|
|
24
|
-
const { API_BASE, LABS_DIR,
|
|
26
|
+
const { API_BASE, LABS_DIR, codeFingerprint, credentialFingerprint, loadEffectiveConfig, loadLlmList, saveLlmList } = require('./config');
|
|
27
|
+
const CODE = codeFingerprint();
|
|
25
28
|
const { version: VERSION } = require('../package.json');
|
|
26
29
|
|
|
27
30
|
console.log(`=== labs-claude proxy ${VERSION} ===`);
|
|
@@ -30,13 +33,10 @@ const SETTLE_MS = 800;
|
|
|
30
33
|
const REQUEST_TIMEOUT_MS = 600000;
|
|
31
34
|
const CONVERSATIONS_DIR = path.join(LABS_DIR, 'conversations');
|
|
32
35
|
|
|
33
|
-
const config =
|
|
34
|
-
|
|
35
|
-
console.error('ā Not set up. Run: labs setup');
|
|
36
|
-
process.exit(1);
|
|
37
|
-
}
|
|
36
|
+
const config = loadEffectiveConfig();
|
|
37
|
+
const hasElevenLabs = Boolean(config.apiKey && config.bridgeAgent);
|
|
38
38
|
const PORT = config.port;
|
|
39
|
-
const HEADERS = { 'xi-api-key': config.apiKey };
|
|
39
|
+
const HEADERS = hasElevenLabs ? { 'xi-api-key': config.apiKey } : {};
|
|
40
40
|
const aliases = config.models;
|
|
41
41
|
let llmList = loadLlmList();
|
|
42
42
|
let llmIds = new Set(llmList.map(item => item.llm));
|
|
@@ -76,15 +76,16 @@ const BRIDGE_NOTE = [
|
|
|
76
76
|
'Read the page with browser_snapshot before clicking, and use the element refs it returns.'
|
|
77
77
|
].join('\n');
|
|
78
78
|
|
|
79
|
-
const toolRegistry = new ToolRegistry({
|
|
79
|
+
const toolRegistry = hasElevenLabs ? new ToolRegistry({
|
|
80
80
|
http: axios,
|
|
81
81
|
apiBase: API_BASE,
|
|
82
82
|
headers: HEADERS,
|
|
83
83
|
file: path.join(LABS_DIR, `tool-registry-${config.bridgeAgent}.json`),
|
|
84
84
|
agentId: config.bridgeAgent
|
|
85
|
-
});
|
|
85
|
+
}) : null;
|
|
86
86
|
|
|
87
87
|
async function refreshLlmList() {
|
|
88
|
+
if (!hasElevenLabs) return;
|
|
88
89
|
try {
|
|
89
90
|
const response = await axios.get(`${API_BASE}/llm/list`, { headers: HEADERS });
|
|
90
91
|
saveLlmList(response.data.llms);
|
|
@@ -625,12 +626,171 @@ async function handleBedrock(req, res, modelId) {
|
|
|
625
626
|
}
|
|
626
627
|
}
|
|
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
|
+
|
|
628
787
|
// ============================================
|
|
629
788
|
// HTTP: Anthropic Messages API
|
|
630
789
|
// ============================================
|
|
631
790
|
|
|
632
791
|
const app = express();
|
|
633
792
|
const PROXY_KEY = loadProxyKey(LABS_DIR);
|
|
793
|
+
const agyBridge = createAgyBridge({ port: PORT, proxyKey: PROXY_KEY, labsDir: LABS_DIR, config });
|
|
634
794
|
app.use((req, res, next) => {
|
|
635
795
|
const refusal = rejectLocalRequest(
|
|
636
796
|
{ host: req.get('host'), path: req.path, authorization: req.get('authorization'), apiKey: hasChatSession(req) ? PROXY_KEY : req.get('x-api-key') },
|
|
@@ -639,12 +799,20 @@ app.use((req, res, next) => {
|
|
|
639
799
|
});
|
|
640
800
|
app.use(bodyParser.json({ limit: '50mb' }));
|
|
641
801
|
mountChat(app, { labsDir: LABS_DIR, proxyKey: PROXY_KEY });
|
|
802
|
+
agyBridge.mount(app);
|
|
642
803
|
|
|
643
804
|
app.post('/v1/messages', async (req, res) => {
|
|
644
805
|
const { model, messages = [], system, stream, metadata, tools = [], max_tokens: maxTokens, output_config: outputConfig } = req.body;
|
|
645
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);
|
|
646
811
|
const bedrockId = bedrockRoute(model, launchModel);
|
|
647
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
|
+
}
|
|
648
816
|
// Claude Code answers repeated errors by falling back opus -> sonnet -> haiku on its own; on the main thread
|
|
649
817
|
// (tools present) a Claude id therefore means "fallback", so stay on the model the user launched with.
|
|
650
818
|
const isClaudeFallback = /^claude-/.test(model || '') && (req.body.tools || []).length > 0 && Boolean(launchModel);
|
|
@@ -752,15 +920,20 @@ app.post('/v1/messages', async (req, res) => {
|
|
|
752
920
|
}
|
|
753
921
|
});
|
|
754
922
|
|
|
755
|
-
app.get('/health', (req, res) => res.json({ name: 'labs-claude', version: VERSION }));
|
|
923
|
+
app.get('/health', (req, res) => res.json({ name: 'labs-claude', version: VERSION, credentials: credentialFingerprint(config), code: CODE }));
|
|
756
924
|
|
|
757
925
|
app.post('/shutdown', (req, res) => {
|
|
758
926
|
res.json({ ok: true });
|
|
927
|
+
agyBridge.shutdown();
|
|
759
928
|
setTimeout(() => process.exit(0), 100);
|
|
760
929
|
});
|
|
761
930
|
|
|
762
931
|
app.get('/v1/models', (req, res) => {
|
|
763
|
-
|
|
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] });
|
|
764
937
|
});
|
|
765
938
|
|
|
766
939
|
app.get('/v1/sessions', (req, res) => {
|
|
@@ -785,6 +958,7 @@ process.on('uncaughtException', error => console.error(`š„ Uncaught: ${error.s
|
|
|
785
958
|
process.on('unhandledRejection', error => console.error(`š„ Unhandled rejection: ${error?.stack || error}`));
|
|
786
959
|
|
|
787
960
|
process.on('SIGINT', () => {
|
|
961
|
+
agyBridge.shutdown();
|
|
788
962
|
connections.forEach(conn => conn.ws.close());
|
|
789
963
|
process.exit(0);
|
|
790
964
|
});
|
|
@@ -796,6 +970,7 @@ app.listen(PORT, '127.0.0.1', error => {
|
|
|
796
970
|
console.log(`š° ${new Date().toISOString()} another labs proxy already holds port ${PORT}; this copy exits (${error.code})`);
|
|
797
971
|
process.exit(0);
|
|
798
972
|
}
|
|
799
|
-
console.log(`ā
${new Date().toISOString()} Proxy LIVE at http://localhost:${PORT} | bridge agent ${config.bridgeAgent}`);
|
|
973
|
+
console.log(`ā
${new Date().toISOString()} Proxy LIVE at http://localhost:${PORT}${hasElevenLabs ? ` | bridge agent ${config.bridgeAgent}` : ' | direct API mode'}`);
|
|
974
|
+
agyBridge.warmup();
|
|
800
975
|
refreshLlmList();
|
|
801
976
|
});
|
package/src/read-shunt.js
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
|
-
// Spotify's "Shunt" (2026-09): a whole-file Read of a big file goes to a cheap worker model, and the main model gets
|
|
2
|
-
// a digest with line ranges instead of every line. Reads with offset/limit are exact on purpose and pass untouched,
|
|
3
|
-
// so the main model can still fetch the precise lines it needs before an Edit.
|
|
4
|
-
function oversizedWholeFileReads(toolResults, priorContent, maxLines) {
|
|
5
|
-
if (!Array.isArray(priorContent)) return [];
|
|
6
|
-
const calls = new Map(priorContent.filter(block => block.type === 'tool_use').map(block => [block.id, block]));
|
|
7
|
-
return toolResults.flatMap(result => {
|
|
8
|
-
const call = calls.get(result.toolUseId);
|
|
9
|
-
if (!call || call.name !== 'Read' || result.isError) return [];
|
|
10
|
-
if (call.input?.offset !== undefined || call.input?.limit !== undefined) return [];
|
|
11
|
-
const lineCount = result.content.split('\n').length;
|
|
12
|
-
return lineCount > maxLines ? [{ result, filePath: call.input?.file_path || '(unknown file)', lineCount }] : [];
|
|
13
|
-
});
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
const WORKER_PROMPT = 'You read files for a coding agent that will not see them. Given a file (with line numbers) and '
|
|
17
|
-
+ 'the agent\'s current task, write a digest: what the file is for; every function, class, section and export with '
|
|
18
|
-
+ 'its line range; important constants, config keys and identifiers; and, copied verbatim with line numbers, every '
|
|
19
|
-
+ 'part that matters for the task. Be factual and complete; never invent lines.';
|
|
20
|
-
|
|
21
|
-
function shuntNote(filePath, lineCount, model, digest) {
|
|
22
|
-
return `[labs: ${filePath} has ${lineCount} lines. To save context, ${model} read the whole file and wrote this `
|
|
23
|
-
+ 'digest. Read it again with offset and limit for the exact lines before you Edit.]\n\n' + digest;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
module.exports = { oversizedWholeFileReads, shuntNote, WORKER_PROMPT };
|
|
1
|
+
// Spotify's "Shunt" (2026-09): a whole-file Read of a big file goes to a cheap worker model, and the main model gets
|
|
2
|
+
// a digest with line ranges instead of every line. Reads with offset/limit are exact on purpose and pass untouched,
|
|
3
|
+
// so the main model can still fetch the precise lines it needs before an Edit.
|
|
4
|
+
function oversizedWholeFileReads(toolResults, priorContent, maxLines) {
|
|
5
|
+
if (!Array.isArray(priorContent)) return [];
|
|
6
|
+
const calls = new Map(priorContent.filter(block => block.type === 'tool_use').map(block => [block.id, block]));
|
|
7
|
+
return toolResults.flatMap(result => {
|
|
8
|
+
const call = calls.get(result.toolUseId);
|
|
9
|
+
if (!call || call.name !== 'Read' || result.isError) return [];
|
|
10
|
+
if (call.input?.offset !== undefined || call.input?.limit !== undefined) return [];
|
|
11
|
+
const lineCount = result.content.split('\n').length;
|
|
12
|
+
return lineCount > maxLines ? [{ result, filePath: call.input?.file_path || '(unknown file)', lineCount }] : [];
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const WORKER_PROMPT = 'You read files for a coding agent that will not see them. Given a file (with line numbers) and '
|
|
17
|
+
+ 'the agent\'s current task, write a digest: what the file is for; every function, class, section and export with '
|
|
18
|
+
+ 'its line range; important constants, config keys and identifiers; and, copied verbatim with line numbers, every '
|
|
19
|
+
+ 'part that matters for the task. Be factual and complete; never invent lines.';
|
|
20
|
+
|
|
21
|
+
function shuntNote(filePath, lineCount, model, digest) {
|
|
22
|
+
return `[labs: ${filePath} has ${lineCount} lines. To save context, ${model} read the whole file and wrote this `
|
|
23
|
+
+ 'digest. Read it again with offset and limit for the exact lines before you Edit.]\n\n' + digest;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
module.exports = { oversizedWholeFileReads, shuntNote, WORKER_PROMPT };
|
package/src/setup.js
CHANGED
|
@@ -4,6 +4,7 @@ const { execFileSync } = require('child_process');
|
|
|
4
4
|
const path = require('path');
|
|
5
5
|
const { API_BASE, CONFIG_PATH, LABS_DIR, loadConfig, saveConfig, saveLlmList } = require('./config');
|
|
6
6
|
const { saveBedrockKey } = require('./bedrock');
|
|
7
|
+
const { AISTUDIO_BASE, saveGeminiKey } = require('./gemini');
|
|
7
8
|
const { EXTENSION_URL, installBrowserServer } = require('./browser-setup');
|
|
8
9
|
|
|
9
10
|
const BRIDGE_AGENT_NAME = 'Labs Claude Code Bridge';
|
|
@@ -164,4 +165,45 @@ async function setupBedrock() {
|
|
|
164
165
|
console.log(`ā
Saved to ${path.join(LABS_DIR, 'bedrock-key')}. Start with: labs --model glm`);
|
|
165
166
|
}
|
|
166
167
|
|
|
167
|
-
|
|
168
|
+
async function setupGemini() {
|
|
169
|
+
console.log('\nš· Google Gemini 4 setup (labs --model gemini | labs --model hydrogen | labs --model carbon)');
|
|
170
|
+
console.log(' 1. Google AI Studio API key (https://aistudio.google.com/apikey)');
|
|
171
|
+
console.log(' 2. Google Cloud Vertex AI (sign in with your Google account via gcloud ADC)\n');
|
|
172
|
+
const choice = (await ask('Choose [1/2] (default 1): ')) || '1';
|
|
173
|
+
|
|
174
|
+
if (choice === '2') {
|
|
175
|
+
const existing = loadConfig() || {};
|
|
176
|
+
const project = await ask(`Google Cloud Project ID${existing.vertexProject ? ` [${existing.vertexProject}]` : ''}: `) || existing.vertexProject;
|
|
177
|
+
if (!project) return console.log('No project ID entered. Nothing saved.');
|
|
178
|
+
const region = (await ask(`Vertex AI region [${existing.vertexRegion || 'global'}]: `)) || existing.vertexRegion || 'global';
|
|
179
|
+
saveConfig({ ...existing, vertexProject: project, vertexRegion: region });
|
|
180
|
+
try {
|
|
181
|
+
execFileSync('gcloud', ['auth', 'application-default', 'print-access-token'], { stdio: 'ignore' });
|
|
182
|
+
console.log(`ā
Saved Vertex AI (${project}, ${region}) and verified Google ADC login.`);
|
|
183
|
+
} catch {
|
|
184
|
+
console.log(`ā
Saved Vertex AI (${project}, ${region}).`);
|
|
185
|
+
console.log('ā ļø Sign in with your Google account next:\n gcloud auth application-default login');
|
|
186
|
+
}
|
|
187
|
+
return console.log('š Start with: labs --model gemini');
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const key = await askHidden('Paste your Gemini API key (hidden; or set GEMINI_API_KEY env var): ');
|
|
191
|
+
if (!key) return console.log('Nothing saved.');
|
|
192
|
+
try {
|
|
193
|
+
const res = await fetch(`${AISTUDIO_BASE}/models?pageSize=100`, { headers: { 'x-goog-api-key': key } });
|
|
194
|
+
if (!res.ok) {
|
|
195
|
+
const detail = await res.text();
|
|
196
|
+
console.log(`ā Google AI Studio rejected the key (${res.status}): ${detail.slice(0, 200)}`);
|
|
197
|
+
return process.exit(1);
|
|
198
|
+
}
|
|
199
|
+
const data = await res.json();
|
|
200
|
+
const hasHydrogen = (data.models || []).some(m => m.name === 'models/gemini-4-hydrogen');
|
|
201
|
+
console.log(`ā
Key works (${(data.models || []).length} models${hasHydrogen ? ', gemini-4-hydrogen available' : ''}).`);
|
|
202
|
+
} catch (error) {
|
|
203
|
+
console.log(`ā ļø Could not reach Google AI Studio to verify (${error.message}); saving anyway.`);
|
|
204
|
+
}
|
|
205
|
+
saveGeminiKey(LABS_DIR, key);
|
|
206
|
+
console.log(`ā
Saved to ${path.join(LABS_DIR, 'gemini-key')}. Start with: labs --model gemini`);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
module.exports = { runSetup, setupBedrock, setupGemini, ask, askHidden };
|