labs-claude 0.3.0 โ†’ 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,124 +1,173 @@
1
- // The laptop side of the labs gateway: save a key, open the console, start Claude Code on the box's Qwen.
2
- // Box models skip the local ElevenLabs proxy: Claude Code talks to the gateway directly with the user's labs key.
3
- const axios = require('axios');
4
- const crypto = require('crypto');
5
- const fs = require('fs');
6
- const path = require('path');
7
- const { execFileSync, spawn } = require('child_process');
8
- const { CONFIG_PATH, LABS_DIR, saveConfig } = require('./config');
9
-
10
- const GATEWAY_MODELS = { qwen: 'qwen-normal', 'qwen-normal': 'qwen-normal', 'qwen-uncensored': 'qwen-uncensored' };
11
- const DEFAULT_GATEWAY_URL = 'https://labs.instant.uz';
12
- const ADMIN_TOKEN_FILE = path.join(LABS_DIR, 'gateway-admin');
13
- // Same capability list the box's own claude-local uses, so /effort and thinking work on Qwen.
14
- const CAPS = 'effort,xhigh_effort,max_effort,thinking,interleaved_thinking';
15
-
16
- function gatewayModelFrom(args) {
17
- const i = args.findIndex(a => a === '--model' || a.startsWith('--model='));
18
- if (i < 0) return null;
19
- const name = args[i].includes('=') ? args[i].split('=')[1] : args[i + 1];
20
- return GATEWAY_MODELS[name] ? { name, id: GATEWAY_MODELS[name], index: i, inline: args[i].includes('=') } : null;
21
- }
22
-
23
- // The stored file only: loadConfig() mixes in ELEVENLABS_API_KEY from the environment, which must not reach the disk.
24
- function storedConfig() {
25
- return fs.existsSync(CONFIG_PATH) ? JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')) : {};
26
- }
27
-
28
- async function boxModels(url, key) {
29
- const { data } = await axios.get(`${url}/v1/models`, { headers: { 'x-api-key': key }, timeout: 8000 });
30
- return data.data || [];
31
- }
32
-
33
- async function saveGatewayKey(askHidden, ask) {
34
- const stored = storedConfig();
35
- const urlAnswer = await ask(`๐ŸŒ Gateway address [${stored.gatewayUrl || DEFAULT_GATEWAY_URL}]: `);
36
- const url = (urlAnswer || stored.gatewayUrl || DEFAULT_GATEWAY_URL).replace(/\/+$/, '');
37
- const key = await askHidden('๐Ÿ”‘ Paste your labs key (lk_..., hidden): ');
38
- if (!/^lk_[A-Za-z0-9_-]{20,}$/.test(key)) {
39
- console.log('โŒ That does not look like a labs key (it starts with lk_). Nothing saved.');
40
- return process.exit(1);
41
- }
42
- try {
43
- const models = await boxModels(url, key);
44
- console.log(models.length ? `โœ… Key works. Box is on: ${models.map(m => m.id).join(', ')}` : 'โœ… Key works. The box is sleeping right now.');
45
- } catch (error) {
46
- const status = error.response?.status;
47
- console.log(status === 401 ? 'โŒ The gateway refused this key. Nothing saved.' : `โŒ Could not reach ${url} (${error.code || error.message}). Nothing saved.`);
48
- return process.exit(1);
49
- }
50
- saveConfig({ ...stored, gatewayUrl: url, gatewayKey: key });
51
- console.log('๐Ÿ’พ Saved. Start with: labs --model qwen (or labs --model qwen-uncensored)');
52
- }
53
-
54
- async function prepareGatewayLaunch(config, args, picked) {
55
- if (!config.gatewayKey) {
56
- console.error('โŒ No labs key saved for the box. Ask for one, then run: labs key');
57
- process.exit(1);
58
- }
59
- const url = config.gatewayUrl || DEFAULT_GATEWAY_URL;
60
- let models;
61
- try {
62
- models = await boxModels(url, config.gatewayKey);
63
- } catch (error) {
64
- console.error(error.response?.status === 401
65
- ? 'โŒ The gateway refused your labs key (paused or deleted). Ask for a new one, then run: labs key'
66
- : `โŒ Could not reach the labs gateway at ${url} (${error.code || error.message}).`);
67
- process.exit(1);
68
- }
69
- const model = models.find(m => m.id === picked.id);
70
- if (!model) {
71
- console.error(models.length
72
- ? `โŒ ${picked.id} is not running on the box now. Running: ${models.map(m => m.id).join(', ')}`
73
- : '๐ŸŒ™ The box is sleeping, so Qwen is not reachable. Book box time in the group, or use: labs --model opus');
74
- process.exit(1);
75
- }
76
-
77
- const claudeArgs = args.filter((_, i) => i !== picked.index && (picked.inline || i !== picked.index + 1));
78
- if (!claudeArgs.some(a => a === '--effort' || a.startsWith('--effort='))) claudeArgs.push('--effort', config.defaultEffort || 'high');
79
- const env = {
80
- ...process.env,
81
- ANTHROPIC_BASE_URL: url,
82
- ANTHROPIC_AUTH_TOKEN: config.gatewayKey,
83
- ANTHROPIC_MODEL: picked.id,
84
- // Every row Claude Code can fall back to points at the same box model, so side calls and subagents stay on it.
85
- ANTHROPIC_DEFAULT_OPUS_MODEL: picked.id,
86
- ANTHROPIC_DEFAULT_SONNET_MODEL: picked.id,
87
- ANTHROPIC_DEFAULT_HAIKU_MODEL: picked.id,
88
- ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES: CAPS,
89
- ANTHROPIC_DEFAULT_SONNET_MODEL_SUPPORTED_CAPABILITIES: CAPS,
90
- ANTHROPIC_DEFAULT_HAIKU_MODEL_SUPPORTED_CAPABILITIES: CAPS,
91
- CLAUDE_CODE_SUBAGENT_MODEL: picked.id,
92
- CLAUDE_CODE_MAX_CONTEXT_TOKENS: String(model.max_model_len || 131072)
93
- };
94
- for (const name of ['ANTHROPIC_API_KEY', 'ANTHROPIC_CUSTOM_HEADERS']) delete env[name];
95
- const banner = `๐Ÿš€ Claude Code on the box: ${picked.id} (${Math.round((model.max_model_len || 131072) / 1000)}k context) via ${url}`;
96
- return { claudeArgs, env, banner };
97
- }
98
-
99
- // The admin token is made here and never printed: its hash goes to the server, the token stays in ~/.labs.
100
- function makeAdminToken(sshTarget) {
101
- if (!sshTarget) {
102
- console.log('Use: labs admin-token ubuntu@<server>');
103
- return process.exit(1);
104
- }
105
- const token = crypto.randomBytes(32).toString('base64url');
106
- const hash = crypto.createHash('sha256').update(token).digest('hex');
107
- execFileSync('ssh', [sshTarget, `mkdir -p ~/.labs-gateway && umask 077 && echo ${hash} > ~/.labs-gateway/admin.sha256`], { stdio: 'inherit' });
108
- fs.mkdirSync(LABS_DIR, { recursive: true });
109
- fs.writeFileSync(ADMIN_TOKEN_FILE, token, { mode: 0o600 });
110
- console.log(`โœ… New admin token saved in ${ADMIN_TOKEN_FILE}; the old one stops working now. Open the console with: labs console`);
111
- }
112
-
113
- function openConsole(config) {
114
- if (!fs.existsSync(ADMIN_TOKEN_FILE)) {
115
- console.log('โŒ No admin token on this laptop. Make one with: labs admin-token ubuntu@<server>');
116
- return process.exit(1);
117
- }
118
- const url = `${config.gatewayUrl || DEFAULT_GATEWAY_URL}/console#t=${fs.readFileSync(ADMIN_TOKEN_FILE, 'utf8').trim()}`;
119
- const opener = process.platform === 'win32' ? ['rundll32', ['url.dll,FileProtocolHandler', url]] : [process.platform === 'darwin' ? 'open' : 'xdg-open', [url]];
120
- spawn(opener[0], opener[1], { stdio: 'ignore', detached: true }).unref();
121
- console.log(`๐Ÿ–ฅ๏ธ Opening the console at ${config.gatewayUrl || DEFAULT_GATEWAY_URL}/console, already logged in.`);
122
- }
123
-
124
- module.exports = { GATEWAY_MODELS, gatewayModelFrom, prepareGatewayLaunch, saveGatewayKey, makeAdminToken, openConsole, storedConfig };
1
+ // The laptop side of the labs gateway: save a key, open the console, start Claude Code on the box's Qwen.
2
+ // Box models skip the local ElevenLabs proxy: Claude Code talks to the gateway directly with the user's labs key.
3
+ const axios = require('axios');
4
+ const crypto = require('crypto');
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { execFileSync, spawn } = require('child_process');
8
+ const { CONFIG_PATH, LABS_DIR, saveConfig } = require('./config');
9
+ const { withBypassDefault } = require('./launch-args');
10
+ const { c, randomQuip, playMascotIntro, withSpinner, printCard } = require('./ui');
11
+ const { version } = require('../package.json');
12
+
13
+ const GATEWAY_MODELS = { qwen: 'qwen-normal', 'qwen-normal': 'qwen-normal', 'qwen-uncensored': 'qwen-uncensored' };
14
+ const DEFAULT_GATEWAY_URL = 'https://labs.instant.uz';
15
+ const ADMIN_TOKEN_FILE = path.join(LABS_DIR, 'gateway-admin');
16
+ // Same capability list the box's own claude-local uses, so /effort and thinking work on Qwen.
17
+ const CAPS = 'effort,xhigh_effort,max_effort,thinking,interleaved_thinking';
18
+
19
+ // A friend who saved only a labs key (no ElevenLabs account) gets Qwen from a bare `labs`, never the ElevenLabs setup.
20
+ function boxOnlyArgs(args, stored, env = process.env) {
21
+ const named = args.some(a => a === '--model' || a.startsWith('--model='));
22
+ const command = ['models', 'usage', 'chat', 'stop', 'setup', 'update'].includes(args[0]);
23
+ const defaultModel = stored.defaultBoxModel || 'qwen';
24
+ return !named && !command && stored.gatewayKey && !stored.apiKey && !env.ELEVENLABS_API_KEY ? ['--model', defaultModel, ...args] : null;
25
+ }
26
+
27
+ function gatewayModelFrom(args) {
28
+ const i = args.findIndex(a => a === '--model' || a.startsWith('--model='));
29
+ if (i < 0) return null;
30
+ const name = args[i].includes('=') ? args[i].split('=')[1] : args[i + 1];
31
+ return GATEWAY_MODELS[name] ? { name, id: GATEWAY_MODELS[name], index: i, inline: args[i].includes('=') } : null;
32
+ }
33
+
34
+ // The stored file only: loadConfig() mixes in ELEVENLABS_API_KEY from the environment, which must not reach the disk.
35
+ function storedConfig() {
36
+ return fs.existsSync(CONFIG_PATH) ? JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')) : {};
37
+ }
38
+
39
+ async function boxModels(url, key) {
40
+ const { data } = await axios.get(`${url}/v1/models`, { headers: { 'x-api-key': key }, timeout: 8000 });
41
+ return data.data || [];
42
+ }
43
+
44
+ // `labs key lk_...` takes the key from the command line: on Windows PowerShell a Ctrl+V into the hidden prompt can
45
+ // arrive empty (a friend saw "does not look like a labs key" with a correct lk_ key, 22 Nov).
46
+ async function saveGatewayKey(askHidden, ask, givenKey) {
47
+ await playMascotIntro(version, 'Fast Qwen4 1M Setup ยท Native Vision ยท Web Search');
48
+ const stored = storedConfig();
49
+ const url = (stored.gatewayUrl || DEFAULT_GATEWAY_URL).replace(/\/+$/, '');
50
+ console.log(` ${c.dim('Gateway:')} ${c.cyan(url)}`);
51
+ const key = givenKey ? String(givenKey).trim() : await askHidden(` ${c.amber('๐Ÿ”‘')} Paste your labs key ${c.dim('(lk_..., hidden; or run: labs key lk_...)')}: `);
52
+ if (!/^lk_[A-Za-z0-9_-]{20,}$/.test(key)) {
53
+ console.log(key
54
+ ? ` ${c.rose('โœ–')} That does not look like a labs key (it starts with ${c.bold('lk_')}). Nothing saved.`
55
+ : ` ${c.rose('โœ–')} Nothing arrived (PowerShell sometimes swallows hidden Ctrl+V). Run instead:\n ${c.cyan('labs key lk_your_key_here')}`);
56
+ return process.exit(1);
57
+ }
58
+ let models = [];
59
+ try {
60
+ models = await withSpinner(randomQuip(), () => boxModels(url, key));
61
+ console.log(models.length
62
+ ? ` ${c.mint('โœ”')} Key verified ยท Box online: ${c.cyan(models.map(m => m.id).join(', '))}`
63
+ : ` ${c.mint('โœ”')} Key verified ยท ${c.amber('Box is sleeping right now (ready when it wakes).')}`);
64
+ } catch (error) {
65
+ const status = error.response?.status;
66
+ console.log(status === 401
67
+ ? ` ${c.rose('โœ–')} The gateway refused this key (paused or deleted). Nothing saved.`
68
+ : ` ${c.rose('โœ–')} Could not reach ${url} (${error.code || error.message}). Nothing saved.`);
69
+ return process.exit(1);
70
+ }
71
+
72
+ let defaultBoxModel = stored.defaultBoxModel || 'qwen';
73
+ let defaultEffort = stored.defaultEffort || 'high';
74
+ if (!givenKey && process.stdin.isTTY) {
75
+ console.log(`\n ${c.bold('Pick your default model:')}`);
76
+ console.log(` ${c.cyan('1.')} ${c.bold('qwen')} ${c.dim('Qwen4-35B-A3B ยท 1M ctx ยท Vision ยท 200โ€“400 tok/s (default)')}`);
77
+ console.log(` ${c.cyan('2.')} ${c.bold('qwen-uncensored')} ${c.dim('Same Qwen4 engine, direct alias')}`);
78
+ const mChoice = await ask(` Choose [${defaultBoxModel === 'qwen-uncensored' ? '2' : '1'}]: `);
79
+ if (mChoice === '2') defaultBoxModel = 'qwen-uncensored';
80
+ else if (mChoice === '1') defaultBoxModel = 'qwen';
81
+
82
+ console.log(`\n ${c.bold('Pick your default thinking effort:')}`);
83
+ console.log(` ${c.cyan('1.')} ${c.bold('high')} ${c.dim('Best everyday balance (auto-skips thinking on simple prompts)')}`);
84
+ console.log(` ${c.cyan('2.')} ${c.bold('xhigh')} ${c.dim('Deepest reasoning for tough bugs & architecture (max)')}`);
85
+ console.log(` ${c.cyan('3.')} ${c.bold('low')} ${c.dim('Minimal thinking, fastest multi-agent speed')}`);
86
+ const eChoice = await ask(' Choose [1]: ');
87
+ if (eChoice === '2') defaultEffort = 'xhigh';
88
+ else if (eChoice === '3') defaultEffort = 'low';
89
+ else if (eChoice === '1') defaultEffort = 'high';
90
+ }
91
+
92
+ saveConfig({ ...stored, gatewayUrl: url, gatewayKey: key, defaultBoxModel, defaultEffort });
93
+ printCard('You are all set!', [
94
+ `${c.mint('Run now:')} ${c.cyan('labs')} ${c.dim('(starts Claude Code on Qwen4 1M)')}`,
95
+ `${c.mint('Switch tab:')} ${c.cyan('/effort low')} ${c.dim('or')} ${c.cyan('/effort max')} ${c.dim('inside Claude Code')}`,
96
+ `${c.mint('Update CLI:')} ${c.cyan('labs update')}`,
97
+ ]);
98
+ }
99
+
100
+ async function prepareGatewayLaunch(config, args, picked) {
101
+ if (!config.gatewayKey) {
102
+ console.error('โŒ No labs key saved for the box. Ask for one, then run: labs key');
103
+ process.exit(1);
104
+ }
105
+ const url = config.gatewayUrl || DEFAULT_GATEWAY_URL;
106
+ let models;
107
+ try {
108
+ models = await boxModels(url, config.gatewayKey);
109
+ } catch (error) {
110
+ console.error(error.response?.status === 401
111
+ ? 'โŒ The gateway refused your labs key (paused or deleted). Ask for a new one, then run: labs key'
112
+ : `โŒ Could not reach the labs gateway at ${url} (${error.code || error.message}).`);
113
+ process.exit(1);
114
+ }
115
+ const model = models.find(m => m.id === picked.id);
116
+ if (!model) {
117
+ console.error(models.length
118
+ ? `โŒ ${picked.id} is not running on the box now. Running: ${models.map(m => m.id).join(', ')}`
119
+ : '๐ŸŒ™ The box is sleeping, so Qwen is not reachable. Book box time in the group, or use: labs --model opus');
120
+ process.exit(1);
121
+ }
122
+
123
+ const claudeArgs = args.filter((_, i) => i !== picked.index && (picked.inline || i !== picked.index + 1));
124
+ if (!claudeArgs.some(a => a === '--effort' || a.startsWith('--effort='))) claudeArgs.push('--effort', config.defaultEffort || 'high');
125
+ const env = {
126
+ ...process.env,
127
+ ANTHROPIC_BASE_URL: url,
128
+ ANTHROPIC_AUTH_TOKEN: config.gatewayKey,
129
+ ANTHROPIC_MODEL: picked.id,
130
+ // Every row Claude Code can fall back to points at the same box model, so side calls and subagents stay on it.
131
+ ANTHROPIC_DEFAULT_OPUS_MODEL: picked.id,
132
+ ANTHROPIC_DEFAULT_SONNET_MODEL: picked.id,
133
+ ANTHROPIC_DEFAULT_HAIKU_MODEL: picked.id,
134
+ ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES: CAPS,
135
+ ANTHROPIC_DEFAULT_SONNET_MODEL_SUPPORTED_CAPABILITIES: CAPS,
136
+ ANTHROPIC_DEFAULT_HAIKU_MODEL_SUPPORTED_CAPABILITIES: CAPS,
137
+ CLAUDE_CODE_SUBAGENT_MODEL: picked.id,
138
+ CLAUDE_CODE_MAX_CONTEXT_TOKENS: String(model.max_model_len || 131072)
139
+ };
140
+ for (const name of ['ANTHROPIC_API_KEY', 'ANTHROPIC_CUSTOM_HEADERS']) delete env[name];
141
+ const ctxLabel = (model.max_model_len || 131072) >= 1000000 ? '1M context' : `${Math.round((model.max_model_len || 131072) / 1000)}k context`;
142
+ const banner = `${c.mint('๐Ÿš€')} ${c.bold('Claude Code')} on ${c.cyan(picked.id)} ${c.dim(`(${ctxLabel} ยท Vision ยท Web)`)} via ${c.dim(url)}\n ${c.violet('โœฆ')} ${c.dim(randomQuip())}`;
143
+ // Qwen cannot use Claude Code's WebSearch (an Anthropic server tool); give it a search tool that runs here instead.
144
+ if (!claudeArgs.some(a => a === '--strict-mcp-config')) claudeArgs.push(...require('./web-mcp').webMcpArgs());
145
+ return { claudeArgs: withBypassDefault(claudeArgs), env, banner };
146
+ }
147
+
148
+ // The admin token is made here and never printed: its hash goes to the server, the token stays in ~/.labs.
149
+ function makeAdminToken(sshTarget) {
150
+ if (!sshTarget) {
151
+ console.log('Use: labs admin-token ubuntu@<server>');
152
+ return process.exit(1);
153
+ }
154
+ const token = crypto.randomBytes(32).toString('base64url');
155
+ const hash = crypto.createHash('sha256').update(token).digest('hex');
156
+ execFileSync('ssh', [sshTarget, `mkdir -p ~/.labs-gateway && umask 077 && echo ${hash} > ~/.labs-gateway/admin.sha256`], { stdio: 'inherit' });
157
+ fs.mkdirSync(LABS_DIR, { recursive: true });
158
+ fs.writeFileSync(ADMIN_TOKEN_FILE, token, { mode: 0o600 });
159
+ console.log(`โœ… New admin token saved in ${ADMIN_TOKEN_FILE}; the old one stops working now. Open the console with: labs console`);
160
+ }
161
+
162
+ function openConsole(config) {
163
+ if (!fs.existsSync(ADMIN_TOKEN_FILE)) {
164
+ console.log('โŒ No admin token on this laptop. Make one with: labs admin-token ubuntu@<server>');
165
+ return process.exit(1);
166
+ }
167
+ const url = `${config.gatewayUrl || DEFAULT_GATEWAY_URL}/console#t=${fs.readFileSync(ADMIN_TOKEN_FILE, 'utf8').trim()}`;
168
+ const opener = process.platform === 'win32' ? ['rundll32', ['url.dll,FileProtocolHandler', url]] : [process.platform === 'darwin' ? 'open' : 'xdg-open', [url]];
169
+ spawn(opener[0], opener[1], { stdio: 'ignore', detached: true }).unref();
170
+ console.log(`๐Ÿ–ฅ๏ธ Opening the console at ${config.gatewayUrl || DEFAULT_GATEWAY_URL}/console, already logged in.`);
171
+ }
172
+
173
+ module.exports = { boxOnlyArgs, GATEWAY_MODELS, gatewayModelFrom, prepareGatewayLaunch, saveGatewayKey, makeAdminToken, openConsole, storedConfig };