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/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 };
|
package/src/ui.js
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// Colorful terminal UI, ASCII mascot, lightweight animations, and non-blocking npm update check.
|
|
2
|
+
// Zero external dependencies; degrades cleanly when stdout is not a TTY or NO_COLOR is set.
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const { spawnSync } = require('child_process');
|
|
6
|
+
|
|
7
|
+
const USE_COLOR = Boolean(process.stdout.isTTY && !process.env.NO_COLOR);
|
|
8
|
+
const ansi = (code, s) => (USE_COLOR ? `\x1b[${code}m${s}\x1b[0m` : String(s));
|
|
9
|
+
|
|
10
|
+
const c = {
|
|
11
|
+
bold: s => ansi('1', s),
|
|
12
|
+
dim: s => ansi('2', s),
|
|
13
|
+
cyan: s => ansi('38;2;56;189;248', s),
|
|
14
|
+
mint: s => ansi('38;2;52;211;153', s),
|
|
15
|
+
violet: s => ansi('38;2;167;139;250', s),
|
|
16
|
+
amber: s => ansi('38;2;251;191;36', s),
|
|
17
|
+
rose: s => ansi('38;2;251;113;133', s),
|
|
18
|
+
white: s => ansi('38;2;248;250;252', s),
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const MASCOT_FRAMES = [
|
|
22
|
+
[
|
|
23
|
+
' โญโโโโฎ ',
|
|
24
|
+
' โญโโโดโโโโดโโโฎ ',
|
|
25
|
+
' โ โ โ โ ',
|
|
26
|
+
' โ โก โ ',
|
|
27
|
+
' โฐโโฌโโโโโโฌโโฏ ',
|
|
28
|
+
' โฑ โโโโโ โฒ ',
|
|
29
|
+
' โฐโโโโโโโโโโฏ ',
|
|
30
|
+
],
|
|
31
|
+
[
|
|
32
|
+
' โญโโโโฎ โฆ ',
|
|
33
|
+
' โญโโโดโโโโดโโโฎ ',
|
|
34
|
+
' โ โ โ โ ',
|
|
35
|
+
' โ โก โ ',
|
|
36
|
+
' โฐโโฌโโโโโโฌโโฏ ',
|
|
37
|
+
' โฑ โโโโโ โฒ ',
|
|
38
|
+
' โฐโโโโโโโโโโฏ ',
|
|
39
|
+
],
|
|
40
|
+
[
|
|
41
|
+
' โฆ โญโโโโฎ ยท ',
|
|
42
|
+
' โญโโโดโโโโดโโโฎ ',
|
|
43
|
+
' โ โ โ โ ',
|
|
44
|
+
' โ โก โ ',
|
|
45
|
+
' โฐโโฌโโโโโโฌโโฏ ',
|
|
46
|
+
' โฑ โโโโโ โฒ ',
|
|
47
|
+
' โฐโโโโโโโโโโฏ ',
|
|
48
|
+
],
|
|
49
|
+
];
|
|
50
|
+
|
|
51
|
+
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
52
|
+
|
|
53
|
+
const KARPATHY_QUIPS = [
|
|
54
|
+
'Warming up 256 MoE experts (8 are coding, 248 are in standup)...',
|
|
55
|
+
'Karpathy mode: staring directly into the loss curve...',
|
|
56
|
+
'Convincing DFlash2 to guess 7 tokens ahead with zero brain loss...',
|
|
57
|
+
'Loading 1,048,576 tokens of context (more memory than your last sprint)...',
|
|
58
|
+
'Feeding Blackwell tensor cores 600 watts of pure unfiltered caffeine...',
|
|
59
|
+
'Checking RadixAttention prefix cache so TTFT stays sub-100ms...',
|
|
60
|
+
'Calibrating xhigh reasoning... please hold while the model overthinks...',
|
|
61
|
+
'Zero corporate rate limits detected. Full local throttle engaged.',
|
|
62
|
+
];
|
|
63
|
+
|
|
64
|
+
function randomQuip() {
|
|
65
|
+
return KARPATHY_QUIPS[Math.floor(Math.random() * KARPATHY_QUIPS.length)];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function playMascotIntro(version, subtitle = 'Claude Code ยท Qwen4 1M ยท Vision ยท Web') {
|
|
69
|
+
const quip = randomQuip();
|
|
70
|
+
const paintFrame = (frame, accent) => {
|
|
71
|
+
const lines = [
|
|
72
|
+
'',
|
|
73
|
+
` ${accent(frame[0])} ${c.bold(c.white('LABS'))} ${c.violet(`v${version}`)}`,
|
|
74
|
+
` ${accent(frame[1])} ${c.dim(subtitle)}`,
|
|
75
|
+
` ${c.cyan(frame[2])} ${c.mint('โ')} ${c.dim(quip)}`,
|
|
76
|
+
` ${c.cyan(frame[3])}`,
|
|
77
|
+
` ${accent(frame[4])}`,
|
|
78
|
+
` ${c.mint(frame[5])}`,
|
|
79
|
+
` ${c.mint(frame[6])}`,
|
|
80
|
+
'',
|
|
81
|
+
];
|
|
82
|
+
return lines.join('\n');
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
if (!USE_COLOR) {
|
|
86
|
+
console.log(paintFrame(MASCOT_FRAMES[2], s => s));
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const accents = [c.violet, c.cyan, c.mint];
|
|
91
|
+
for (let i = 0; i < MASCOT_FRAMES.length; i += 1) {
|
|
92
|
+
if (i > 0) process.stdout.write('\x1b[9A\x1b[0J');
|
|
93
|
+
process.stdout.write(paintFrame(MASCOT_FRAMES[i], accents[i]) + '\n');
|
|
94
|
+
if (i < MASCOT_FRAMES.length - 1) await sleep(130);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function withSpinner(label, fn) {
|
|
99
|
+
if (!USE_COLOR) {
|
|
100
|
+
process.stdout.write(` ... ${label}\n`);
|
|
101
|
+
return fn();
|
|
102
|
+
}
|
|
103
|
+
const frames = ['โ ', 'โ ', 'โ น', 'โ ธ', 'โ ผ', 'โ ด', 'โ ฆ', 'โ ง', 'โ ', 'โ '];
|
|
104
|
+
let idx = 0;
|
|
105
|
+
const timer = setInterval(() => {
|
|
106
|
+
process.stdout.write(`\r ${c.cyan(frames[idx++ % frames.length])} ${c.dim(label)}`);
|
|
107
|
+
}, 75);
|
|
108
|
+
try {
|
|
109
|
+
const result = await fn();
|
|
110
|
+
clearInterval(timer);
|
|
111
|
+
process.stdout.write(`\r ${c.mint('โ')} ${label}${' '.repeat(12)}\n`);
|
|
112
|
+
return result;
|
|
113
|
+
} catch (error) {
|
|
114
|
+
clearInterval(timer);
|
|
115
|
+
process.stdout.write(`\r ${c.rose('โ')} ${label}${' '.repeat(12)}\n`);
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function printCard(title, rows) {
|
|
121
|
+
const strip = s => String(s).replace(/\x1b\[[0-9;]*m/g, '');
|
|
122
|
+
const width = Math.max(44, strip(title).length + 4, ...rows.map(r => strip(r).length + 4));
|
|
123
|
+
const top = ` ${c.violet('โญโ')} ${c.bold(c.white(title))} ${c.violet('โ'.repeat(Math.max(1, width - strip(title).length - 3)) + 'โฎ')}`;
|
|
124
|
+
const bot = ` ${c.violet('โฐ' + 'โ'.repeat(width + 1) + 'โฏ')}`;
|
|
125
|
+
console.log('');
|
|
126
|
+
console.log(top);
|
|
127
|
+
for (const row of rows) {
|
|
128
|
+
const pad = Math.max(0, width - strip(row).length - 1);
|
|
129
|
+
console.log(` ${c.violet('โ')} ${row}${' '.repeat(pad)}${c.violet('โ')}`);
|
|
130
|
+
}
|
|
131
|
+
console.log(bot);
|
|
132
|
+
console.log('');
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function isNewerVersion(latest, current) {
|
|
136
|
+
const a = String(latest || '').split('.').map(Number);
|
|
137
|
+
const b = String(current || '').split('.').map(Number);
|
|
138
|
+
for (let i = 0; i < 3; i += 1) {
|
|
139
|
+
if ((a[i] || 0) > (b[i] || 0)) return true;
|
|
140
|
+
if ((a[i] || 0) < (b[i] || 0)) return false;
|
|
141
|
+
}
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Non-blocking 24h cached npm version check so friends always know when a newer labs-claude is out.
|
|
146
|
+
function checkUpdateNotice(currentVersion, labsDir) {
|
|
147
|
+
const cacheFile = path.join(labsDir, 'update-check.json');
|
|
148
|
+
let cached = null;
|
|
149
|
+
try {
|
|
150
|
+
if (fs.existsSync(cacheFile)) cached = JSON.parse(fs.readFileSync(cacheFile, 'utf8'));
|
|
151
|
+
} catch { /* ignore corrupt cache */ }
|
|
152
|
+
|
|
153
|
+
if (cached && cached.latest && isNewerVersion(cached.latest, currentVersion)) {
|
|
154
|
+
console.log(` ${c.amber('โฌ')} ${c.bold(`Update available:`)} ${c.dim(currentVersion)} โ ${c.mint(cached.latest)} ${c.dim('Run:')} ${c.cyan('labs update')}`);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const stale = !cached || (Date.now() - (cached.checkedAt || 0)) > 24 * 3600e3;
|
|
158
|
+
if (stale && typeof fetch === 'function') {
|
|
159
|
+
fetch('https://registry.npmjs.org/labs-claude/latest', { signal: AbortSignal.timeout(2500) })
|
|
160
|
+
.then(r => (r.ok ? r.json() : null))
|
|
161
|
+
.then(data => {
|
|
162
|
+
if (!data?.version) return;
|
|
163
|
+
fs.mkdirSync(labsDir, { recursive: true });
|
|
164
|
+
fs.writeFileSync(cacheFile, JSON.stringify({ latest: data.version, checkedAt: Date.now() }));
|
|
165
|
+
})
|
|
166
|
+
.catch(() => {});
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function runSelfUpdate(currentVersion) {
|
|
171
|
+
console.log(`\n ${c.cyan('โฌ')} Updating ${c.bold('labs-claude')} (current ${c.dim(currentVersion)}) from npm...\n`);
|
|
172
|
+
const cmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
|
|
173
|
+
const res = spawnSync(cmd, ['install', '-g', 'labs-claude@latest', '--prefer-online'], { stdio: 'inherit', shell: process.platform === 'win32' });
|
|
174
|
+
if (res.status !== 0) {
|
|
175
|
+
console.error(`\n ${c.rose('โ')} Update failed. Try manually: ${c.cyan('npm install -g labs-claude@latest --prefer-online')}`);
|
|
176
|
+
process.exit(res.status || 1);
|
|
177
|
+
}
|
|
178
|
+
console.log(`\n ${c.mint('โ')} Updated! Close and reopen any open labs terminals to use the new version.\n`);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
module.exports = { c, KARPATHY_QUIPS, randomQuip, playMascotIntro, withSpinner, printCard, isNewerVersion, checkUpdateNotice, runSelfUpdate };
|
package/src/usage.js
CHANGED
|
@@ -1,8 +1,48 @@
|
|
|
1
1
|
const axios = require('axios');
|
|
2
|
-
const
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
const { API_BASE, LABS_DIR } = require('./config');
|
|
3
5
|
|
|
4
|
-
|
|
6
|
+
function printJsonlUsage(title, file) {
|
|
7
|
+
if (!fs.existsSync(file)) return;
|
|
8
|
+
const rows = fs.readFileSync(file, 'utf8').trim().split(/\r?\n/).filter(Boolean).map(line => {
|
|
9
|
+
try { return JSON.parse(line); } catch { return null; }
|
|
10
|
+
}).filter(Boolean);
|
|
11
|
+
if (!rows.length) return;
|
|
12
|
+
const byModel = {};
|
|
13
|
+
for (const r of rows) {
|
|
14
|
+
const key = r.modelId || 'unknown';
|
|
15
|
+
const entry = byModel[key] ||= { calls: 0, input: 0, cached: 0, output: 0 };
|
|
16
|
+
entry.calls += 1;
|
|
17
|
+
entry.input += r.input || 0;
|
|
18
|
+
entry.cached += r.cached || 0;
|
|
19
|
+
entry.output += r.output || 0;
|
|
20
|
+
}
|
|
21
|
+
const pad = (v, w) => String(v).padStart(w);
|
|
22
|
+
console.log(`\n${title} (${rows.length} logged calls):`);
|
|
23
|
+
console.log(`${'model'.padEnd(26)}${pad('calls', 7)}${pad('input', 12)}${pad('cached', 12)}${pad('output', 10)}`);
|
|
24
|
+
for (const [model, row] of Object.entries(byModel)) {
|
|
25
|
+
console.log(`${model.padEnd(26)}${pad(row.calls, 7)}${pad(row.input.toLocaleString(), 12)}${pad(row.cached.toLocaleString(), 12)}${pad(row.output.toLocaleString(), 10)}`);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Totals what the bridge agent's recent conversations cost, per LLM, from ElevenLabs' own billing metadata, plus local Gemini/Bedrock usage logs.
|
|
5
30
|
async function printUsage(config, limit = 50) {
|
|
31
|
+
printJsonlUsage('๐งช Antigravity (agy) usage', path.join(LABS_DIR, 'agy-usage.jsonl'));
|
|
32
|
+
printJsonlUsage('๐ท Google Gemini usage', path.join(LABS_DIR, 'gemini-usage.jsonl'));
|
|
33
|
+
printJsonlUsage('๐ง Amazon Bedrock usage', path.join(LABS_DIR, 'bedrock-usage.jsonl'));
|
|
34
|
+
|
|
35
|
+
if (!config?.apiKey || !config?.bridgeAgent) {
|
|
36
|
+
if (!fs.existsSync(path.join(LABS_DIR, 'agy-usage.jsonl'))
|
|
37
|
+
&& !fs.existsSync(path.join(LABS_DIR, 'gemini-usage.jsonl'))
|
|
38
|
+
&& !fs.existsSync(path.join(LABS_DIR, 'bedrock-usage.jsonl'))) {
|
|
39
|
+
console.log('\nNo usage logged yet. Run a session with `labs --model gem` or set up ElevenLabs (`labs setup`).\n');
|
|
40
|
+
} else {
|
|
41
|
+
console.log('');
|
|
42
|
+
}
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
|
|
6
46
|
const headers = { 'xi-api-key': config.apiKey };
|
|
7
47
|
const subscription = (await axios.get('https://api.elevenlabs.io/v1/user/subscription', { headers })).data;
|
|
8
48
|
const list = (await axios.get(`${API_BASE}/conversations`, { headers, params: { agent_id: config.bridgeAgent, page_size: limit } })).data.conversations;
|
package/src/web-mcp.js
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
// labs-web: web search and page reading for Claude Code sessions on the box models (Qwen).
|
|
2
|
+
// Claude Code's own WebSearch is an Anthropic server tool, so it cannot run on Qwen ("Did no searches", 22 Nov).
|
|
3
|
+
// Search engines block cloud servers as bots, so this runs on the user's own computer, over their own internet:
|
|
4
|
+
// web_search -> DuckDuckGo HTML, then Bing HTML if DuckDuckGo gives nothing; web_fetch -> one page as plain text.
|
|
5
|
+
// An MCP server is JSON-RPC over stdio, one JSON object per line; stdout carries only protocol.
|
|
6
|
+
const readline = require('readline');
|
|
7
|
+
|
|
8
|
+
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124 Safari/537.36';
|
|
9
|
+
const MAX_PAGE = 20000;
|
|
10
|
+
|
|
11
|
+
const decode = s => String(s || '')
|
|
12
|
+
.replace(/&#x([0-9a-f]+);/gi, (_, h) => String.fromCodePoint(parseInt(h, 16)))
|
|
13
|
+
.replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d)))
|
|
14
|
+
.replace(/"/g, '"').replace(/'|'/g, "'").replace(/</g, '<').replace(/>/g, '>')
|
|
15
|
+
.replace(/ /g, ' ').replace(/&/g, '&');
|
|
16
|
+
const strip = s => decode(String(s || '').replace(/<[^>]+>/g, '')).replace(/\s+/g, ' ').trim();
|
|
17
|
+
|
|
18
|
+
function parseDuckDuckGo(page, n = 8) {
|
|
19
|
+
const out = [];
|
|
20
|
+
for (const part of String(page).split(/(?=<a[^>]*class="result__a")/).slice(1)) {
|
|
21
|
+
const a = part.match(/<a[^>]*class="result__a"[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/)
|
|
22
|
+
|| part.match(/<a[^>]*href="([^"]+)"[^>]*class="result__a"[^>]*>([\s\S]*?)<\/a>/);
|
|
23
|
+
if (!a) continue;
|
|
24
|
+
let url = decode(a[1]);
|
|
25
|
+
try { url = new URL(url, 'https://duckduckgo.com').searchParams.get('uddg') || url; } catch { /* keep */ }
|
|
26
|
+
if (url.startsWith('//')) url = 'https:' + url;
|
|
27
|
+
if (!/^https?:/.test(url) || url.includes('duckduckgo.com/y.js')) continue;
|
|
28
|
+
const sn = part.match(/class="result__snippet"[^>]*>([\s\S]*?)<\/a>/);
|
|
29
|
+
out.push({ title: strip(a[2]), url, snippet: strip(sn && sn[1]) });
|
|
30
|
+
if (out.length >= n) break;
|
|
31
|
+
}
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function parseBing(page, n = 8) {
|
|
36
|
+
const out = [];
|
|
37
|
+
for (const li of String(page).match(/<li class="b_algo"[\s\S]*?<\/li>/g) || []) {
|
|
38
|
+
const a = li.match(/<h2[^>]*>\s*<a[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/);
|
|
39
|
+
if (!a) continue;
|
|
40
|
+
let url = decode(a[1]);
|
|
41
|
+
// Bing wraps links as /ck/a?...&u=a1<base64url of the real address>
|
|
42
|
+
const u = url.match(/[?&]u=a1([^&]+)/);
|
|
43
|
+
if (u) { try { url = Buffer.from(u[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch { /* keep */ } }
|
|
44
|
+
if (!/^https?:/.test(url)) continue;
|
|
45
|
+
const p = li.match(/<p[^>]*>([\s\S]*?)<\/p>/);
|
|
46
|
+
out.push({ title: strip(a[2]), url, snippet: strip(p && p[1]) });
|
|
47
|
+
if (out.length >= n) break;
|
|
48
|
+
}
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Uzbek or legal wording: search lex.uz (the national law database) first.
|
|
53
|
+
const UZ = /[สปสผโโ]|\b(qonun|qaror|modda|hokim|kodeks|farmon|farmoyish|to'g'risida|ะทะฐะบะพะฝ|ะฟะพััะฐะฝะพะฒะปะตะฝะธ|ัะบะฐะท)/i;
|
|
54
|
+
const TECH = /\b(github|arxiv|qwen|vllm|cuda|python|rust|javascript|node|docker|llm|model|benchmark|paper|api|sdk|error|bug|mcp|sglang|nvfp4|pytorch|huggingface|claude|gpt|gemini)\b/i;
|
|
55
|
+
const pickSources = q => (UZ.test(q) ? ['lexuz', 'gnews', 'wikipedia'] : TECH.test(q) ? ['gh_issues', 'stackoverflow', 'huggingface', 'github', 'arxiv', 'hackernews'] : ['gnews', 'bingnews', 'wikipedia', 'hackernews']);
|
|
56
|
+
|
|
57
|
+
function parseLexUz(page, n = 8) {
|
|
58
|
+
const out = [];
|
|
59
|
+
for (const m of String(page).matchAll(/<a class="lx_link " href="(\/uz\/docs\/-?\d+)"[^>]*>([\s\S]*?)<\/a>[\s\S]{0,500}?badge-nine">([\s\S]*?)<\/span>/g)) {
|
|
60
|
+
out.push({ title: strip(m[2]), url: `https://lex.uz${m[1]}`, snippet: strip(m[3]) });
|
|
61
|
+
if (out.length >= n) break;
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function pageText(htmlText) {
|
|
67
|
+
const title = strip((String(htmlText).match(/<title[^>]*>([\s\S]*?)<\/title>/i) || [])[1]);
|
|
68
|
+
const body = String(htmlText)
|
|
69
|
+
.replace(/<(script|style|noscript|svg|head)[\s\S]*?<\/\1>/gi, ' ')
|
|
70
|
+
.replace(/<\/(p|div|h[1-6]|li|tr|br|section|article)>/gi, '\n')
|
|
71
|
+
.replace(/<br\s*\/?>/gi, '\n');
|
|
72
|
+
const text = decode(body.replace(/<[^>]+>/g, ' ')).split('\n').map(l => l.replace(/\s+/g, ' ').trim()).filter(Boolean).join('\n');
|
|
73
|
+
return { title, text };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function createWeb({ fetchImpl = fetch, timeoutMs = 20000, braveKey = process.env.LABS_BRAVE_KEYS || process.env.LABS_BRAVE_KEY || '' } = {}) {
|
|
77
|
+
const braveKeys = String(braveKey).split(',').map(s => s.trim()).filter(Boolean);
|
|
78
|
+
let braveIdx = 0;
|
|
79
|
+
const get = async (url, init = {}) => {
|
|
80
|
+
const ctl = new AbortController();
|
|
81
|
+
const t = setTimeout(() => ctl.abort(), timeoutMs);
|
|
82
|
+
try {
|
|
83
|
+
return await fetchImpl(url, { ...init, signal: ctl.signal, redirect: 'follow', headers: { 'user-agent': UA, 'accept-language': 'en-US,en;q=0.9,uz;q=0.8,ru;q=0.7', ...(init.headers || {}) } });
|
|
84
|
+
} finally { clearTimeout(t); }
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const json = async (url, headers = {}) => {
|
|
88
|
+
const r = await get(url, { headers: { accept: 'application/json', ...headers } });
|
|
89
|
+
if (!r.ok) throw new Error(String(r.status));
|
|
90
|
+
return r.json();
|
|
91
|
+
};
|
|
92
|
+
const tag = (re, text) => strip((String(text).match(re) || [])[1]);
|
|
93
|
+
// Key-free sources that still answer automated requests (checked 22 Nov from a home connection, where DuckDuckGo,
|
|
94
|
+
// Bing, Google, Brave, Startpage, Ecosia, Qwant, Yandex and Yahoo all returned bot pages or empty results).
|
|
95
|
+
const SOURCES = {
|
|
96
|
+
wikipedia: async (q, n) => {
|
|
97
|
+
const langs = UZ.test(q) ? ['uz', 'en'] : /[ะฐ-ัั]/i.test(q) ? ['ru', 'en'] : ['en'];
|
|
98
|
+
const out = [];
|
|
99
|
+
for (const l of langs) {
|
|
100
|
+
const d = await json(`https://${l}.wikipedia.org/w/api.php?action=query&list=search&format=json&srlimit=${n}&srsearch=${encodeURIComponent(q)}`);
|
|
101
|
+
for (const x of d.query?.search || []) out.push({ title: x.title, url: `https://${l}.wikipedia.org/wiki/${encodeURIComponent(x.title.replace(/ /g, '_'))}`, snippet: strip(x.snippet) });
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
},
|
|
105
|
+
github: async (q, n) => (await json(`https://api.github.com/search/repositories?per_page=${n}&q=${encodeURIComponent(q)}`)).items
|
|
106
|
+
.map(x => ({ title: `${x.full_name} (${x.stargazers_count} stars)`, url: x.html_url, snippet: x.description || '' })),
|
|
107
|
+
hackernews: async (q, n) => (await json(`https://hn.algolia.com/api/v1/search?hitsPerPage=${n}&query=${encodeURIComponent(q)}`)).hits
|
|
108
|
+
.filter(x => x.title).map(x => ({ title: x.title, url: x.url || `https://news.ycombinator.com/item?id=${x.objectID}`, snippet: `${x.points || 0} points, ${String(x.created_at || '').slice(0, 10)}` })),
|
|
109
|
+
arxiv: async (q, n) => {
|
|
110
|
+
const terms = q.split(/\s+/).filter(w => w.length > 2).slice(0, 6).map(w => `all:${encodeURIComponent(w)}`).join('+AND+');
|
|
111
|
+
const r = await get(`https://export.arxiv.org/api/query?max_results=${n}&sortBy=relevance&search_query=${terms}`);
|
|
112
|
+
return (await r.text()).split('<entry>').slice(1).map(e => ({
|
|
113
|
+
title: tag(/<title>([\s\S]*?)<\/title>/, e),
|
|
114
|
+
url: tag(/<id>([\s\S]*?)<\/id>/, e),
|
|
115
|
+
snippet: `${tag(/<published>([\s\S]*?)<\/published>/, e).slice(0, 10)}: ${tag(/<summary>([\s\S]*?)<\/summary>/, e).slice(0, 220)}`
|
|
116
|
+
}));
|
|
117
|
+
},
|
|
118
|
+
gnews: async (q, n) => { const r = await get(`https://news.google.com/rss/search?q=${encodeURIComponent(q)}&hl=en-US&gl=US&ceid=US:en`); return (await r.text()).split('<item>').slice(1, n + 1).map(it => ({ title: tag(/<title>([\s\S]*?)<\/title>/, it), url: tag(/<link>([\s\S]*?)<\/link>/, it), snippet: `${tag(/<pubDate>([\s\S]*?)<\/pubDate>/, it).slice(0, 22)} | ${tag(/<source[^>]*>([\s\S]*?)<\/source>/, it)}` })).filter(x => x.title && x.url); },
|
|
119
|
+
bingnews: async (q, n) => { const r = await get(`https://www.bing.com/news/search?q=${encodeURIComponent(q)}&format=rss`); return (await r.text()).split('<item>').slice(1, n + 1).map(it => { let u = tag(/<link>([\s\S]*?)<\/link>/, it); try { u = new URL(u).searchParams.get('url') || u; } catch {} return { title: tag(/<title>([\s\S]*?)<\/title>/, it), url: u, snippet: `${tag(/<pubDate>([\s\S]*?)<\/pubDate>/, it).slice(0, 22)} | ${tag(/<description>([\s\S]*?)<\/description>/, it).slice(0, 180)}` }; }).filter(x => x.title && x.url); },
|
|
120
|
+
gh_issues: async (q, n) => (await json(`https://api.github.com/search/issues?per_page=${n}&q=${encodeURIComponent(q)}`)).items.map(x => ({ title: `[GH ${x.state}] ${x.title}`, url: x.html_url, snippet: strip(x.body || '').slice(0, 200) })),
|
|
121
|
+
stackoverflow: async (q, n) => (await json(`https://api.stackexchange.com/2.3/search/excerpts?order=desc&sort=relevance&site=stackoverflow&pagesize=${n}&q=${encodeURIComponent(q)}`)).items.map(x => ({ title: `[SO] ${strip(x.title)}`, url: `https://stackoverflow.com/questions/${x.question_id}`, snippet: strip(x.excerpt || '').slice(0, 200) })),
|
|
122
|
+
huggingface: async (q, n) => (await json(`https://huggingface.co/api/models?search=${encodeURIComponent(q)}&sort=downloads&direction=-1&limit=${n}`)).map(x => ({ title: `${x.id} (${x.downloads || 0} dl, ${x.likes || 0} likes)`, url: `https://huggingface.co/${x.id}`, snippet: `${x.pipeline_tag || 'model'} | updated ${String(x.lastModified || '').slice(0, 10)}` })),
|
|
123
|
+
lexuz: async (q, n) => {
|
|
124
|
+
const r = await get(`https://lex.uz/uz/search/all?searchtitle=${encodeURIComponent(q)}`);
|
|
125
|
+
return parseLexUz(await r.text(), n);
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
async function search({ query, count = 8, sources, shortened = false }) {
|
|
130
|
+
const q = String(query || '').trim().slice(0, 300);
|
|
131
|
+
if (!q) throw new Error('Give a search query.');
|
|
132
|
+
const n = Math.max(1, Math.min(Number(count) || 8, 10));
|
|
133
|
+
// 1. A Brave Search key, if one is set: the only source here that covers the whole web reliably.
|
|
134
|
+
if (braveKeys.length && !sources) {
|
|
135
|
+
for (let attempt = 0; attempt < braveKeys.length; attempt += 1) {
|
|
136
|
+
const idx = (braveIdx + attempt) % braveKeys.length;
|
|
137
|
+
try {
|
|
138
|
+
const d = await json(`https://api.search.brave.com/res/v1/web/search?count=${n}&q=${encodeURIComponent(q)}`, { 'x-subscription-token': braveKeys[idx] });
|
|
139
|
+
const results = (d.web?.results || []).map(x => ({ title: strip(x.title), url: x.url, snippet: strip(x.description) }));
|
|
140
|
+
if (results.length) { braveIdx = idx; return { query: q, engine: `brave#${idx + 1}`, results }; }
|
|
141
|
+
} catch { /* auto-rotate to next Brave key */ }
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
// 2. DuckDuckGo: some connections still get results; most automated requests get its bot page (status 202).
|
|
145
|
+
if (!sources) {
|
|
146
|
+
try {
|
|
147
|
+
const r = await get('https://html.duckduckgo.com/html/', { method: 'POST', body: new URLSearchParams({ q }), headers: { 'content-type': 'application/x-www-form-urlencoded' } });
|
|
148
|
+
const results = r.status === 200 ? parseDuckDuckGo(await r.text(), n) : [];
|
|
149
|
+
if (results.length) return { query: q, engine: 'duckduckgo', results };
|
|
150
|
+
} catch { /* fall through */ }
|
|
151
|
+
}
|
|
152
|
+
// 3. The key-free sources, in parallel, interleaved.
|
|
153
|
+
const names = (Array.isArray(sources) && sources.length ? sources : pickSources(q)).filter(x => SOURCES[x]);
|
|
154
|
+
const per = Math.max(2, Math.ceil(n / Math.max(1, names.length)) + 1);
|
|
155
|
+
const got = await Promise.all(names.map(name => SOURCES[name](q, per).then(rs => rs.map(r => ({ ...r, source: name }))).catch(() => [])));
|
|
156
|
+
const results = [];
|
|
157
|
+
for (let k = 0; results.length < n && got.some(g => g[k]); k += 1) for (const g of got) if (g[k] && results.length < n) results.push(g[k]);
|
|
158
|
+
// Title search on these sources is literal: a long question finds little, so retry once with its 3 longest words.
|
|
159
|
+
const short = q.split(/\s+/).filter(w => w.length > 3).sort((x, y) => y.length - x.length).slice(0, 3).join(' ');
|
|
160
|
+
if (results.length < Math.min(3, n) && short && short !== q && !shortened) {
|
|
161
|
+
const again = await search({ query: short, count: n, sources: names, shortened: true });
|
|
162
|
+
for (const r of again.results) if (results.length < n && !results.some(x => x.url === r.url)) results.push(r);
|
|
163
|
+
}
|
|
164
|
+
return { query: q, engine: names.join('+'), results };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function fetchPage({ url, maxChars = MAX_PAGE }) {
|
|
168
|
+
if (!/^https?:\/\//i.test(String(url || ''))) throw new Error('Give a full http(s) address.');
|
|
169
|
+
const cap = Math.max(1000, Math.min(Number(maxChars) || MAX_PAGE, 60000));
|
|
170
|
+
try {
|
|
171
|
+
const jr = await get(`https://r.jina.ai/${url}`, { headers: { accept: 'text/markdown,text/plain' } });
|
|
172
|
+
if (jr.ok) {
|
|
173
|
+
const md = (await jr.text()).trim();
|
|
174
|
+
if (md.length > 200 && !md.includes('Target URL returned error')) {
|
|
175
|
+
const titleMatch = md.match(/^Title:\s*(.+)$/m);
|
|
176
|
+
return { url, title: titleMatch ? titleMatch[1].trim() : '', text: md.slice(0, cap), truncated: md.length > cap, chars: md.length };
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
} catch { /* fall back to direct fetch */ }
|
|
180
|
+
const r = await get(url);
|
|
181
|
+
const type = r.headers.get('content-type') || '';
|
|
182
|
+
if (!r.ok) throw new Error(`The page answered ${r.status}.`);
|
|
183
|
+
if (!/text|html|json|xml/.test(type)) throw new Error(`Not a text page (${type || 'unknown type'}).`);
|
|
184
|
+
const raw = await r.text();
|
|
185
|
+
const { title, text } = /html/.test(type) ? pageText(raw) : { title: '', text: raw };
|
|
186
|
+
return { url: r.url || url, title, text: text.slice(0, cap), truncated: text.length > cap, chars: text.length };
|
|
187
|
+
}
|
|
188
|
+
return { search, fetchPage };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const TOOLS = [
|
|
192
|
+
{
|
|
193
|
+
name: 'web_search',
|
|
194
|
+
description: 'Search the web (runs on this computer). Returns titles, addresses and snippets. Use web_fetch to read a result in full before you rely on it.',
|
|
195
|
+
inputSchema: { type: 'object', properties: { query: { type: 'string', description: 'what to search for' }, count: { type: 'integer', description: 'results, 1-10 (default 8)' } }, required: ['query'] }
|
|
196
|
+
},
|
|
197
|
+
{
|
|
198
|
+
name: 'web_fetch',
|
|
199
|
+
description: 'Read one web page as plain text (scripts and menus removed). Use it on addresses from web_search or ones the user gave.',
|
|
200
|
+
inputSchema: { type: 'object', properties: { url: { type: 'string', description: 'full http(s) address' }, maxChars: { type: 'integer', description: 'how much text to return (default 20000)' } }, required: ['url'] }
|
|
201
|
+
}
|
|
202
|
+
];
|
|
203
|
+
|
|
204
|
+
async function handle(message, web, version) {
|
|
205
|
+
const { method, params } = message;
|
|
206
|
+
if (method === 'initialize') {
|
|
207
|
+
return { protocolVersion: params?.protocolVersion || '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'labs-web', version },
|
|
208
|
+
instructions: 'Web search and page reading. Search first, then read the best 1-3 results with web_fetch, and cite the addresses you used.' };
|
|
209
|
+
}
|
|
210
|
+
if (method === 'tools/list') return { tools: TOOLS };
|
|
211
|
+
if (method === 'tools/call') {
|
|
212
|
+
try {
|
|
213
|
+
if (params?.name === 'web_search') {
|
|
214
|
+
const out = await web.search(params.arguments || {});
|
|
215
|
+
const lines = out.results.map((r, i) => `[${i + 1}] ${r.title}\n${r.url}\n${r.snippet}`);
|
|
216
|
+
return { content: [{ type: 'text', text: lines.length ? `Results for "${out.query}" (${out.engine}):\n\n${lines.join('\n\n')}` : `No results for "${out.query}".` }] };
|
|
217
|
+
}
|
|
218
|
+
if (params?.name === 'web_fetch') {
|
|
219
|
+
const out = await web.fetchPage(params.arguments || {});
|
|
220
|
+
return { content: [{ type: 'text', text: `${out.title ? out.title + '\n' : ''}${out.url}\n\n${out.text}${out.truncated ? `\n\n[cut at ${out.text.length} of ${out.chars} characters]` : ''}` }] };
|
|
221
|
+
}
|
|
222
|
+
return { content: [{ type: 'text', text: `Unknown tool ${params?.name}.` }], isError: true };
|
|
223
|
+
} catch (error) {
|
|
224
|
+
return { content: [{ type: 'text', text: error.name === 'AbortError' ? 'The site did not answer in time.' : error.message }], isError: true };
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
if (method === 'ping') return {};
|
|
228
|
+
return undefined; // notifications
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function serve({ web = createWeb(), version, input = process.stdin, output = process.stdout } = {}) {
|
|
232
|
+
const rl = readline.createInterface({ input });
|
|
233
|
+
rl.on('line', async line => {
|
|
234
|
+
if (!line.trim()) return;
|
|
235
|
+
let message;
|
|
236
|
+
try { message = JSON.parse(line); } catch { return; }
|
|
237
|
+
try {
|
|
238
|
+
const result = await handle(message, web, version);
|
|
239
|
+
if (message.id !== undefined && result !== undefined) output.write(JSON.stringify({ jsonrpc: '2.0', id: message.id, result }) + '\n');
|
|
240
|
+
} catch (error) {
|
|
241
|
+
if (message.id !== undefined) output.write(JSON.stringify({ jsonrpc: '2.0', id: message.id, error: { code: -32603, message: error.message } }) + '\n');
|
|
242
|
+
}
|
|
243
|
+
});
|
|
244
|
+
return rl;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// Claude Code flags that give a box session this tool and switch off the Anthropic-only WebSearch.
|
|
248
|
+
function webMcpArgs(labsBin = require.resolve('../bin/labs.js'), node = process.execPath) {
|
|
249
|
+
const config = { mcpServers: { 'labs-web': { command: node, args: [labsBin, 'web-mcp'] } } };
|
|
250
|
+
return ['--mcp-config', JSON.stringify(config), '--disallowedTools', 'WebSearch', 'WebFetch'];
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
module.exports = { createWeb, handle, serve, parseDuckDuckGo, parseBing, parseLexUz, pageText, pickSources, webMcpArgs, TOOLS };
|