labs-claude 0.2.6 → 0.3.0

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,63 +1,71 @@
1
- const fs = require('fs');
2
- const os = require('os');
3
- const path = require('path');
4
-
5
- const LABS_DIR = process.env.LABS_HOME || path.join(os.homedir(), '.labs');
6
- const CONFIG_PATH = path.join(LABS_DIR, 'config.json');
7
- const LLM_LIST_PATH = path.join(LABS_DIR, 'llm-list.json');
8
- const DEFAULT_PORT = 8081;
9
- const API_BASE = 'https://api.elevenlabs.io/v1/convai';
10
-
11
- // Short names for the strongest current ElevenLabs LLMs; any raw ElevenLabs LLM id also works.
12
- const DEFAULT_MODELS = {
13
- astra: 'gpt-6-astra',
14
- sol: 'gpt-6.1-sol',
15
- terra: 'gpt-5.6-terra',
16
- luna: 'gpt-6-luna',
17
- opus: 'claude-opus-5-5',
18
- sonnet: 'claude-sonnet-5-5',
19
- haiku: 'claude-haiku-4-5',
20
- gemini: 'gemini-3.8-flash',
21
- 'gemini-pro': 'gemini-3.1-pro-preview',
22
- // GLM 5.3 runs on Amazon Bedrock with the user's own AWS key (labs bedrock), not on ElevenLabs.
23
- glm: 'bedrock:us.zai.glm-5.3',
24
- glm52: 'glm-52',
25
- qwen: 'qwen35-397b-a17b',
26
- deepseek: 'deepseek-v41-flash'
27
- };
28
-
29
- function loadConfig() {
30
- if (!fs.existsSync(CONFIG_PATH)) return null;
31
- const stored = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
32
- return {
33
- port: DEFAULT_PORT,
34
- defaultModel: 'astra',
35
- // ElevenLabs caches only the system prompt, so every token of history is paid at full price on every turn
36
- // (measured 2026-10-08: 8 Opus turns at ~324k context cost $11.98). Claude Code compacts at this size.
37
- contextLimit: 300000,
38
- // Titles, summaries and compaction (requests without tools) ran on Opus/Sonnet; a cheap 1M model does them.
39
- sideModel: 'gemini-3.8-flash',
40
- bedrockRegion: 'us-east-1',
41
- // Bedrock bills every input token on every turn; 200k keeps one GLM 5.3 turn under ~$0.35.
42
- bedrockContextLimit: 200000,
43
- ...stored,
44
- models: { ...DEFAULT_MODELS, ...(stored.models || {}) },
45
- apiKey: process.env.ELEVENLABS_API_KEY || stored.apiKey
46
- };
47
- }
48
-
49
- function saveConfig(config) {
50
- fs.mkdirSync(LABS_DIR, { recursive: true });
51
- fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), { mode: 0o600 });
52
- }
53
-
54
- function loadLlmList() {
55
- return fs.existsSync(LLM_LIST_PATH) ? JSON.parse(fs.readFileSync(LLM_LIST_PATH, 'utf8')) : [];
56
- }
57
-
58
- function saveLlmList(llms) {
59
- fs.mkdirSync(LABS_DIR, { recursive: true });
60
- fs.writeFileSync(LLM_LIST_PATH, JSON.stringify(llms, null, 1));
61
- }
62
-
63
- module.exports = { API_BASE, CONFIG_PATH, DEFAULT_MODELS, LABS_DIR, loadConfig, loadLlmList, saveConfig, saveLlmList };
1
+ const crypto = require('crypto');
2
+ const fs = require('fs');
3
+ const os = require('os');
4
+ const path = require('path');
5
+
6
+ const LABS_DIR = process.env.LABS_HOME || path.join(os.homedir(), '.labs');
7
+ const CONFIG_PATH = path.join(LABS_DIR, 'config.json');
8
+ const LLM_LIST_PATH = path.join(LABS_DIR, 'llm-list.json');
9
+ const DEFAULT_PORT = 8081;
10
+ const API_BASE = 'https://api.elevenlabs.io/v1/convai';
11
+
12
+ // Short names for the strongest current ElevenLabs LLMs; any raw ElevenLabs LLM id also works.
13
+ const DEFAULT_MODELS = {
14
+ astra: 'gpt-6-astra',
15
+ sol: 'gpt-6.1-sol',
16
+ terra: 'gpt-5.6-terra',
17
+ luna: 'gpt-6-luna',
18
+ opus: 'claude-opus-5-5',
19
+ sonnet: 'claude-sonnet-5-5',
20
+ haiku: 'claude-haiku-4-5',
21
+ gemini: 'gemini-3.8-flash',
22
+ 'gemini-pro': 'gemini-3.1-pro-preview',
23
+ // GLM 5.3 runs on Amazon Bedrock with the user's own AWS key (labs bedrock), not on ElevenLabs.
24
+ glm: 'bedrock:us.zai.glm-5.3',
25
+ glm52: 'glm-52',
26
+ qwen: 'qwen35-397b-a17b',
27
+ deepseek: 'deepseek-v41-flash'
28
+ };
29
+
30
+ function loadConfig() {
31
+ if (!fs.existsSync(CONFIG_PATH)) return null;
32
+ const stored = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
33
+ return {
34
+ port: DEFAULT_PORT,
35
+ defaultModel: 'astra',
36
+ // ElevenLabs caches only the system prompt, so every token of history is paid at full price on every turn
37
+ // (measured 2026-10-08: 8 Opus turns at ~324k context cost $11.98). Claude Code compacts at this size.
38
+ contextLimit: 300000,
39
+ // Titles, summaries and compaction (requests without tools) ran on Opus/Sonnet; a cheap 1M model does them.
40
+ sideModel: 'gemini-3.8-flash',
41
+ bedrockRegion: 'us-east-1',
42
+ // Bedrock bills every input token on every turn; 200k keeps one GLM 5.3 turn under ~$0.35.
43
+ bedrockContextLimit: 200000,
44
+ ...stored,
45
+ models: { ...DEFAULT_MODELS, ...(stored.models || {}) },
46
+ apiKey: process.env.ELEVENLABS_API_KEY || stored.apiKey
47
+ };
48
+ }
49
+
50
+ // A running proxy keeps the key it started with. A short hash lets the launcher see that the key or agent changed
51
+ // (a friend switched ElevenLabs accounts and every turn kept failing on the old key) without exposing the key.
52
+ function credentialFingerprint(config) {
53
+ if (!config?.apiKey) return null;
54
+ return crypto.createHash('sha256').update(`${config.apiKey}:${config.bridgeAgent || ''}`).digest('hex').slice(0, 12);
55
+ }
56
+
57
+ function saveConfig(config) {
58
+ fs.mkdirSync(LABS_DIR, { recursive: true });
59
+ fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), { mode: 0o600 });
60
+ }
61
+
62
+ function loadLlmList() {
63
+ return fs.existsSync(LLM_LIST_PATH) ? JSON.parse(fs.readFileSync(LLM_LIST_PATH, 'utf8')) : [];
64
+ }
65
+
66
+ function saveLlmList(llms) {
67
+ fs.mkdirSync(LABS_DIR, { recursive: true });
68
+ fs.writeFileSync(LLM_LIST_PATH, JSON.stringify(llms, null, 1));
69
+ }
70
+
71
+ module.exports = { API_BASE, CONFIG_PATH, DEFAULT_MODELS, LABS_DIR, credentialFingerprint, loadConfig, loadLlmList, saveConfig, saveLlmList };
@@ -0,0 +1,124 @@
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 };
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 };