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.
@@ -1,149 +1,149 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const { spawn } = require('child_process');
4
- const { randomBytes, timingSafeEqual } = require('crypto');
5
-
6
- // Cookies on 127.0.0.1 are shared across ports, so other local servers would receive this cookie: it holds a random
7
- // session token kept only in this process's memory, never the proxy key itself.
8
- const COOKIE = 'labs_chat_session';
9
- const SESSION_MS = 30 * 24 * 60 * 60 * 1000;
10
- const sessions = new Map();
11
- // One-time login codes: `labs chat` asks for one with the proxy key and opens it, so the key is never pasted.
12
- const loginCodes = new Map();
13
- const CODE_MS = 60 * 1000;
14
- const ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
15
- const LABS_BIN = path.join(__dirname, '..', 'bin', 'labs.js');
16
- const PAGE = path.join(__dirname, 'chat', 'index.html');
17
-
18
- function chatCookie(req) {
19
- const match = String(req.get('cookie') || '').match(new RegExp(`(?:^|;\\s*)${COOKIE}=([^;]+)`));
20
- return match ? decodeURIComponent(match[1]) : null;
21
- }
22
-
23
- // A chat request counts as the owner only with a live session cookie AND the X-Labs-Chat header, which a cross-site
24
- // form or image cannot send.
25
- function hasChatSession(req) {
26
- const token = chatCookie(req);
27
- const expires = token && sessions.get(token);
28
- if (!expires) return false;
29
- if (expires < Date.now()) {
30
- sessions.delete(token);
31
- return false;
32
- }
33
- return req.get('x-labs-chat') === '1';
34
- }
35
-
36
- function sameKey(given, key) {
37
- const a = Buffer.from(String(given || ''));
38
- const b = Buffer.from(key);
39
- return a.length === b.length && timingSafeEqual(a, b);
40
- }
41
-
42
- // The page is static and holds no data; every /chat/api call and /v1/messages need the proxy key, which the browser
43
- // carries as an HttpOnly, SameSite=Strict cookie after one login, so other sites cannot use it.
44
- function mountChat(app, { labsDir, proxyKey }) {
45
- const chatDir = path.join(labsDir, 'chat');
46
- const fileFor = id => path.join(chatDir, `${id}.json`);
47
-
48
- // Both live under dot folders (~/.npm-global, ~/.labs), which Express refuses to send by default.
49
- const SEND_OPTIONS = { dotfiles: 'allow' };
50
-
51
- app.get(['/chat', '/chat/'], (req, res) => res.sendFile(PAGE, SEND_OPTIONS));
52
-
53
- const startSession = res => {
54
- const token = randomBytes(32).toString('hex');
55
- sessions.set(token, Date.now() + SESSION_MS);
56
- res.set('Set-Cookie', `${COOKIE}=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${SESSION_MS / 1000}`);
57
- };
58
-
59
- app.post('/chat/login', (req, res) => {
60
- if (!sameKey(req.body?.key, proxyKey)) return res.status(401).json({ error: 'Wrong key' });
61
- startSession(res);
62
- res.json({ ok: true });
63
- });
64
-
65
- // Behind the proxy-key check like every /chat/api route.
66
- app.post('/chat/api/login-link', (req, res) => {
67
- const code = randomBytes(32).toString('hex');
68
- loginCodes.set(code, Date.now() + CODE_MS);
69
- res.json({ path: `/chat/open?code=${code}` });
70
- });
71
-
72
- app.get('/chat/open', (req, res) => {
73
- const code = String(req.query.code || '');
74
- const expires = loginCodes.get(code);
75
- loginCodes.delete(code);
76
- if (expires && expires > Date.now()) startSession(res);
77
- res.redirect(302, '/chat');
78
- });
79
-
80
- app.get('/chat/api/me', (req, res) => res.json({ ok: true }));
81
-
82
- app.get('/chat/api/conversations', (req, res) => {
83
- if (!fs.existsSync(chatDir)) return res.json({ conversations: [] });
84
- const conversations = fs.readdirSync(chatDir).filter(file => file.endsWith('.json')).map(file => {
85
- const { id, title, updatedAt, mode } = JSON.parse(fs.readFileSync(path.join(chatDir, file), 'utf8'));
86
- return { id, title, updatedAt, mode };
87
- });
88
- res.json({ conversations: conversations.sort((a, b) => b.updatedAt - a.updatedAt) });
89
- });
90
-
91
- app.get('/chat/api/conversations/:id', (req, res) => {
92
- const { id } = req.params;
93
- if (!ID_PATTERN.test(id) || !fs.existsSync(fileFor(id))) return res.status(404).json({ error: 'Not found' });
94
- res.sendFile(fileFor(id), SEND_OPTIONS);
95
- });
96
-
97
- app.put('/chat/api/conversations/:id', (req, res) => {
98
- const { id } = req.params;
99
- if (!ID_PATTERN.test(id)) return res.status(400).json({ error: 'Bad id' });
100
- fs.mkdirSync(chatDir, { recursive: true });
101
- const { title, mode, messages, events, usage, folder, sessionId } = req.body || {};
102
- fs.writeFileSync(fileFor(id), JSON.stringify({ id, title, mode, messages, events, usage, folder, sessionId, updatedAt: Date.now() }));
103
- res.json({ ok: true });
104
- });
105
-
106
- app.delete('/chat/api/conversations/:id', (req, res) => {
107
- const { id } = req.params;
108
- if (ID_PATTERN.test(id) && fs.existsSync(fileFor(id))) fs.unlinkSync(fileFor(id));
109
- res.json({ ok: true });
110
- });
111
-
112
- // Agent mode = the real Claude Code on the chosen model, run headless in the chosen folder; its stream-json lines
113
- // are passed to the page as server-sent events.
114
- app.post('/chat/api/agent', (req, res) => {
115
- const { folder, prompt, model = 'glm', sessionId, access = 'edits' } = req.body || {};
116
- if (!folder || !path.isAbsolute(folder) || !fs.existsSync(folder) || !fs.statSync(folder).isDirectory()) {
117
- return res.status(400).json({ error: `Folder not found: ${folder}` });
118
- }
119
- if (!prompt || typeof prompt !== 'string') return res.status(400).json({ error: 'Empty prompt' });
120
- if (sessionId && !/^[0-9a-f-]{36}$/i.test(sessionId)) return res.status(400).json({ error: 'Bad session id' });
121
-
122
- const args = [LABS_BIN, '--model', model, '-p', prompt, '--output-format', 'stream-json', '--verbose',
123
- '--permission-mode', access === 'full' ? 'bypassPermissions' : 'acceptEdits'];
124
- if (sessionId) args.push('--resume', sessionId);
125
- // stdin closed: with -p, Claude Code otherwise waits 3 s for piped input on every run.
126
- const child = spawn(process.execPath, args, { cwd: folder, env: process.env, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
127
-
128
- res.status(200).set({ 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
129
- const send = data => res.write(`data: ${JSON.stringify(data)}\n\n`);
130
- let buffer = '';
131
- child.stdout.on('data', chunk => {
132
- buffer += chunk;
133
- const lines = buffer.split('\n');
134
- buffer = lines.pop();
135
- for (const line of lines) {
136
- if (!line.trim()) continue;
137
- try { send(JSON.parse(line)); } catch { send({ type: 'log', text: line }); }
138
- }
139
- });
140
- child.stderr.on('data', chunk => send({ type: 'log', text: String(chunk) }));
141
- child.on('close', code => {
142
- send({ type: 'exit', code });
143
- res.end();
144
- });
145
- res.on('close', () => { if (child.exitCode === null) child.kill(); });
146
- });
147
- }
148
-
149
- module.exports = { hasChatSession, mountChat };
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { spawn } = require('child_process');
4
+ const { randomBytes, timingSafeEqual } = require('crypto');
5
+
6
+ // Cookies on 127.0.0.1 are shared across ports, so other local servers would receive this cookie: it holds a random
7
+ // session token kept only in this process's memory, never the proxy key itself.
8
+ const COOKIE = 'labs_chat_session';
9
+ const SESSION_MS = 30 * 24 * 60 * 60 * 1000;
10
+ const sessions = new Map();
11
+ // One-time login codes: `labs chat` asks for one with the proxy key and opens it, so the key is never pasted.
12
+ const loginCodes = new Map();
13
+ const CODE_MS = 60 * 1000;
14
+ const ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
15
+ const LABS_BIN = path.join(__dirname, '..', 'bin', 'labs.js');
16
+ const PAGE = path.join(__dirname, 'chat', 'index.html');
17
+
18
+ function chatCookie(req) {
19
+ const match = String(req.get('cookie') || '').match(new RegExp(`(?:^|;\\s*)${COOKIE}=([^;]+)`));
20
+ return match ? decodeURIComponent(match[1]) : null;
21
+ }
22
+
23
+ // A chat request counts as the owner only with a live session cookie AND the X-Labs-Chat header, which a cross-site
24
+ // form or image cannot send.
25
+ function hasChatSession(req) {
26
+ const token = chatCookie(req);
27
+ const expires = token && sessions.get(token);
28
+ if (!expires) return false;
29
+ if (expires < Date.now()) {
30
+ sessions.delete(token);
31
+ return false;
32
+ }
33
+ return req.get('x-labs-chat') === '1';
34
+ }
35
+
36
+ function sameKey(given, key) {
37
+ const a = Buffer.from(String(given || ''));
38
+ const b = Buffer.from(key);
39
+ return a.length === b.length && timingSafeEqual(a, b);
40
+ }
41
+
42
+ // The page is static and holds no data; every /chat/api call and /v1/messages need the proxy key, which the browser
43
+ // carries as an HttpOnly, SameSite=Strict cookie after one login, so other sites cannot use it.
44
+ function mountChat(app, { labsDir, proxyKey }) {
45
+ const chatDir = path.join(labsDir, 'chat');
46
+ const fileFor = id => path.join(chatDir, `${id}.json`);
47
+
48
+ // Both live under dot folders (~/.npm-global, ~/.labs), which Express refuses to send by default.
49
+ const SEND_OPTIONS = { dotfiles: 'allow' };
50
+
51
+ app.get(['/chat', '/chat/'], (req, res) => res.sendFile(PAGE, SEND_OPTIONS));
52
+
53
+ const startSession = res => {
54
+ const token = randomBytes(32).toString('hex');
55
+ sessions.set(token, Date.now() + SESSION_MS);
56
+ res.set('Set-Cookie', `${COOKIE}=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${SESSION_MS / 1000}`);
57
+ };
58
+
59
+ app.post('/chat/login', (req, res) => {
60
+ if (!sameKey(req.body?.key, proxyKey)) return res.status(401).json({ error: 'Wrong key' });
61
+ startSession(res);
62
+ res.json({ ok: true });
63
+ });
64
+
65
+ // Behind the proxy-key check like every /chat/api route.
66
+ app.post('/chat/api/login-link', (req, res) => {
67
+ const code = randomBytes(32).toString('hex');
68
+ loginCodes.set(code, Date.now() + CODE_MS);
69
+ res.json({ path: `/chat/open?code=${code}` });
70
+ });
71
+
72
+ app.get('/chat/open', (req, res) => {
73
+ const code = String(req.query.code || '');
74
+ const expires = loginCodes.get(code);
75
+ loginCodes.delete(code);
76
+ if (expires && expires > Date.now()) startSession(res);
77
+ res.redirect(302, '/chat');
78
+ });
79
+
80
+ app.get('/chat/api/me', (req, res) => res.json({ ok: true }));
81
+
82
+ app.get('/chat/api/conversations', (req, res) => {
83
+ if (!fs.existsSync(chatDir)) return res.json({ conversations: [] });
84
+ const conversations = fs.readdirSync(chatDir).filter(file => file.endsWith('.json')).map(file => {
85
+ const { id, title, updatedAt, mode } = JSON.parse(fs.readFileSync(path.join(chatDir, file), 'utf8'));
86
+ return { id, title, updatedAt, mode };
87
+ });
88
+ res.json({ conversations: conversations.sort((a, b) => b.updatedAt - a.updatedAt) });
89
+ });
90
+
91
+ app.get('/chat/api/conversations/:id', (req, res) => {
92
+ const { id } = req.params;
93
+ if (!ID_PATTERN.test(id) || !fs.existsSync(fileFor(id))) return res.status(404).json({ error: 'Not found' });
94
+ res.sendFile(fileFor(id), SEND_OPTIONS);
95
+ });
96
+
97
+ app.put('/chat/api/conversations/:id', (req, res) => {
98
+ const { id } = req.params;
99
+ if (!ID_PATTERN.test(id)) return res.status(400).json({ error: 'Bad id' });
100
+ fs.mkdirSync(chatDir, { recursive: true });
101
+ const { title, mode, messages, events, usage, folder, sessionId } = req.body || {};
102
+ fs.writeFileSync(fileFor(id), JSON.stringify({ id, title, mode, messages, events, usage, folder, sessionId, updatedAt: Date.now() }));
103
+ res.json({ ok: true });
104
+ });
105
+
106
+ app.delete('/chat/api/conversations/:id', (req, res) => {
107
+ const { id } = req.params;
108
+ if (ID_PATTERN.test(id) && fs.existsSync(fileFor(id))) fs.unlinkSync(fileFor(id));
109
+ res.json({ ok: true });
110
+ });
111
+
112
+ // Agent mode = the real Claude Code on the chosen model, run headless in the chosen folder; its stream-json lines
113
+ // are passed to the page as server-sent events.
114
+ app.post('/chat/api/agent', (req, res) => {
115
+ const { folder, prompt, model = 'glm', sessionId, access = 'edits' } = req.body || {};
116
+ if (!folder || !path.isAbsolute(folder) || !fs.existsSync(folder) || !fs.statSync(folder).isDirectory()) {
117
+ return res.status(400).json({ error: `Folder not found: ${folder}` });
118
+ }
119
+ if (!prompt || typeof prompt !== 'string') return res.status(400).json({ error: 'Empty prompt' });
120
+ if (sessionId && !/^[0-9a-f-]{36}$/i.test(sessionId)) return res.status(400).json({ error: 'Bad session id' });
121
+
122
+ const args = [LABS_BIN, '--model', model, '-p', prompt, '--output-format', 'stream-json', '--verbose',
123
+ '--permission-mode', access === 'full' ? 'bypassPermissions' : 'acceptEdits'];
124
+ if (sessionId) args.push('--resume', sessionId);
125
+ // stdin closed: with -p, Claude Code otherwise waits 3 s for piped input on every run.
126
+ const child = spawn(process.execPath, args, { cwd: folder, env: process.env, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
127
+
128
+ res.status(200).set({ 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
129
+ const send = data => res.write(`data: ${JSON.stringify(data)}\n\n`);
130
+ let buffer = '';
131
+ child.stdout.on('data', chunk => {
132
+ buffer += chunk;
133
+ const lines = buffer.split('\n');
134
+ buffer = lines.pop();
135
+ for (const line of lines) {
136
+ if (!line.trim()) continue;
137
+ try { send(JSON.parse(line)); } catch { send({ type: 'log', text: line }); }
138
+ }
139
+ });
140
+ child.stderr.on('data', chunk => send({ type: 'log', text: String(chunk) }));
141
+ child.on('close', code => {
142
+ send({ type: 'exit', code });
143
+ res.end();
144
+ });
145
+ res.on('close', () => { if (child.exitCode === null) child.kill(); });
146
+ });
147
+ }
148
+
149
+ module.exports = { hasChatSession, mountChat };
package/src/config.js CHANGED
@@ -1,3 +1,4 @@
1
+ const crypto = require('crypto');
1
2
  const fs = require('fs');
2
3
  const os = require('os');
3
4
  const path = require('path');
@@ -17,7 +18,17 @@ const DEFAULT_MODELS = {
17
18
  opus: 'claude-opus-5-5',
18
19
  sonnet: 'claude-sonnet-5-5',
19
20
  haiku: 'claude-haiku-4-5',
20
- gemini: 'gemini-3.8-flash',
21
+ hydrogen: 'gemini-4-hydrogen',
22
+ gemini: 'gemini-4-hydrogen',
23
+ gem: 'agy:gemini-4-hydrogen',
24
+ 'agy-flash': 'agy:gemini-3.8-flash',
25
+ 'agy-sonnet': 'agy:claude-sonnet-4-6',
26
+ 'agy-opus': 'agy:claude-opus-4-6-thinking',
27
+ 'agy-oss': 'agy:gpt-oss-120b-medium',
28
+ neon: 'gemini-4-neon',
29
+ argon: 'gemini-4-argon',
30
+ nano: 'gemini-4-nano',
31
+ gemini3: 'gemini-3.8-flash',
21
32
  'gemini-pro': 'gemini-3.1-pro-preview',
22
33
  // GLM 5.3 runs on Amazon Bedrock with the user's own AWS key (labs bedrock), not on ElevenLabs.
23
34
  glm: 'bedrock:us.zai.glm-5.3',
@@ -26,9 +37,7 @@ const DEFAULT_MODELS = {
26
37
  deepseek: 'deepseek-v41-flash'
27
38
  };
28
39
 
29
- function loadConfig() {
30
- if (!fs.existsSync(CONFIG_PATH)) return null;
31
- const stored = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
40
+ function withDefaults(stored = {}) {
32
41
  return {
33
42
  port: DEFAULT_PORT,
34
43
  defaultModel: 'astra',
@@ -37,6 +46,8 @@ function loadConfig() {
37
46
  contextLimit: 300000,
38
47
  // Titles, summaries and compaction (requests without tools) ran on Opus/Sonnet; a cheap 1M model does them.
39
48
  sideModel: 'gemini-3.8-flash',
49
+ geminiContextLimit: 1000000,
50
+ vertexRegion: 'global',
40
51
  bedrockRegion: 'us-east-1',
41
52
  // Bedrock bills every input token on every turn; 200k keeps one GLM 5.3 turn under ~$0.35.
42
53
  bedrockContextLimit: 200000,
@@ -46,6 +57,33 @@ function loadConfig() {
46
57
  };
47
58
  }
48
59
 
60
+ function loadConfig() {
61
+ if (!fs.existsSync(CONFIG_PATH)) return null;
62
+ return withDefaults(JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')));
63
+ }
64
+
65
+ function loadEffectiveConfig() {
66
+ const stored = fs.existsSync(CONFIG_PATH) ? JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')) : {};
67
+ return withDefaults(stored);
68
+ }
69
+
70
+ // A running proxy keeps the key it started with. A short hash lets the launcher see that the key or agent changed
71
+ // (a friend switched ElevenLabs accounts and every turn kept failing on the old key) without exposing the key.
72
+ function credentialFingerprint(config) {
73
+ if (!config?.apiKey) return null;
74
+ return crypto.createHash('sha256').update(`${config.apiKey}:${config.bridgeAgent || ''}`).digest('hex').slice(0, 12);
75
+ }
76
+
77
+ // The proxy's own code. The version number does not move on every change (a git pull, a dev link), and on
78
+ // 2026-11-28 a proxy from 26 Nov kept serving an old Antigravity bridge: first turns 60-83 s instead of 6 s.
79
+ function codeFingerprint(dir = __dirname) {
80
+ const hash = crypto.createHash('sha256');
81
+ for (const file of fs.readdirSync(dir).filter(f => f.endsWith('.js')).sort()) {
82
+ hash.update(file).update(fs.readFileSync(path.join(dir, file)));
83
+ }
84
+ return hash.digest('hex').slice(0, 12);
85
+ }
86
+
49
87
  function saveConfig(config) {
50
88
  fs.mkdirSync(LABS_DIR, { recursive: true });
51
89
  fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), { mode: 0o600 });
@@ -60,4 +98,4 @@ function saveLlmList(llms) {
60
98
  fs.writeFileSync(LLM_LIST_PATH, JSON.stringify(llms, null, 1));
61
99
  }
62
100
 
63
- module.exports = { API_BASE, CONFIG_PATH, DEFAULT_MODELS, LABS_DIR, loadConfig, loadLlmList, saveConfig, saveLlmList };
101
+ module.exports = { API_BASE, CONFIG_PATH, DEFAULT_MODELS, LABS_DIR, codeFingerprint, credentialFingerprint, loadConfig, loadEffectiveConfig, loadLlmList, saveConfig, saveLlmList };
@@ -0,0 +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
+ 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 };