labs-claude 0.12.2 → 0.12.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.
- package/package.json +1 -1
- package/src/admin-cli.js +1 -1
- package/src/dash.js +1 -1
- package/src/gateway-client.js +27 -5
- package/src/image-mcp.js +174 -174
package/package.json
CHANGED
package/src/admin-cli.js
CHANGED
|
@@ -12,7 +12,7 @@ const { storedConfig } = require('./gateway-client');
|
|
|
12
12
|
const { c, sparkline, randomQuip, playMascotIntro, withSpinner, printCard } = require('./ui');
|
|
13
13
|
const { version } = require('../package.json');
|
|
14
14
|
|
|
15
|
-
const DEFAULT_GATEWAY_URL = 'https://labs.
|
|
15
|
+
const DEFAULT_GATEWAY_URL = 'https://labs.humopedia.com';
|
|
16
16
|
const DEFAULT_BOX_INSTANCE = 'i-024bdf750d64da0f8';
|
|
17
17
|
const DEFAULT_BOX_REGION = 'us-east-2';
|
|
18
18
|
const ADMIN_TOKEN_FILE = path.join(LABS_DIR, 'gateway-admin');
|
package/src/dash.js
CHANGED
|
@@ -10,7 +10,7 @@ const { storedConfig, saveGatewayKey } = require('./gateway-client');
|
|
|
10
10
|
const { c, THEMES, activeTheme, gradient, visibleWidth, sparkline, randomQuip, play3DIntro, askMasked, runSelfUpdate } = require('./ui');
|
|
11
11
|
const { version } = require('../package.json');
|
|
12
12
|
|
|
13
|
-
const DEFAULT_GATEWAY_URL = 'https://labs.
|
|
13
|
+
const DEFAULT_GATEWAY_URL = 'https://labs.humopedia.com';
|
|
14
14
|
const IS_ADMIN = () => fs.existsSync(path.join(LABS_DIR, 'gateway-admin'));
|
|
15
15
|
|
|
16
16
|
function compact(n) {
|
package/src/gateway-client.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// Box models skip the local ElevenLabs proxy: Claude Code talks to the gateway directly with the user's labs key.
|
|
3
3
|
const axios = require('axios');
|
|
4
4
|
const crypto = require('crypto');
|
|
5
|
+
const https = require('https');
|
|
5
6
|
const fs = require('fs');
|
|
6
7
|
const path = require('path');
|
|
7
8
|
const { execFileSync, spawn } = require('child_process');
|
|
@@ -17,7 +18,7 @@ const GATEWAY_MODELS = {
|
|
|
17
18
|
'qwen-normal': 'qwen-normal',
|
|
18
19
|
'qwen-uncensored': 'qwen-uncensored'
|
|
19
20
|
};
|
|
20
|
-
const DEFAULT_GATEWAY_URL = 'https://labs.
|
|
21
|
+
const DEFAULT_GATEWAY_URL = 'https://labs.humopedia.com';
|
|
21
22
|
const ADMIN_TOKEN_FILE = path.join(LABS_DIR, 'gateway-admin');
|
|
22
23
|
const BOX_SETTINGS_FILE = path.join(LABS_DIR, 'box-settings.json');
|
|
23
24
|
// Same capability list the box's own claude-local uses, so /effort, xhigh, max, and thinking work on Qwen4.
|
|
@@ -43,12 +44,33 @@ function gatewayModelFrom(args) {
|
|
|
43
44
|
|
|
44
45
|
// The stored file only: loadConfig() mixes in ELEVENLABS_API_KEY from the environment, which must not reach the disk.
|
|
45
46
|
function storedConfig() {
|
|
46
|
-
|
|
47
|
+
const cfg = fs.existsSync(CONFIG_PATH) ? JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')) : {};
|
|
48
|
+
if (cfg.gatewayUrl && /^https?:\/\/labs\.instant\.uz\/?$/i.test(cfg.gatewayUrl)) {
|
|
49
|
+
cfg.gatewayUrl = DEFAULT_GATEWAY_URL;
|
|
50
|
+
}
|
|
51
|
+
return cfg;
|
|
47
52
|
}
|
|
48
53
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
54
|
+
const GATEWAY_HTTPS_AGENT = new https.Agent({ keepAlive: true, maxSockets: 4, family: 4 });
|
|
55
|
+
|
|
56
|
+
async function boxModels(url, key, retries = 3) {
|
|
57
|
+
let lastErr;
|
|
58
|
+
for (let i = 0; i < retries; i += 1) {
|
|
59
|
+
try {
|
|
60
|
+
const { data } = await axios.get(`${url}/v1/models`, {
|
|
61
|
+
headers: { 'x-api-key': key },
|
|
62
|
+
timeout: 6000,
|
|
63
|
+
httpsAgent: GATEWAY_HTTPS_AGENT,
|
|
64
|
+
});
|
|
65
|
+
return data.data || [];
|
|
66
|
+
} catch (err) {
|
|
67
|
+
lastErr = err;
|
|
68
|
+
const status = err?.response?.status;
|
|
69
|
+
if (status && status < 500) throw err;
|
|
70
|
+
if (i < retries - 1) await new Promise(r => setTimeout(r, 500 * (i + 1)));
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
throw lastErr;
|
|
52
74
|
}
|
|
53
75
|
|
|
54
76
|
// `labs key lk_...` takes the key from the command line: on Windows PowerShell a Ctrl+V into the hidden prompt can
|
package/src/image-mcp.js
CHANGED
|
@@ -1,174 +1,174 @@
|
|
|
1
|
-
// labs-image: lets any Claude Code chat or agent paint on the box (Qwen-Image) through the labs gateway.
|
|
2
|
-
// It saves each picture to disk and returns the path, so the agent opens it with its Read tool and actually looks.
|
|
3
|
-
// An MCP server is JSON-RPC over stdio, one JSON object per line; stdout carries only protocol, notes go to stderr.
|
|
4
|
-
const fs = require('fs');
|
|
5
|
-
const os = require('os');
|
|
6
|
-
const path = require('path');
|
|
7
|
-
const readline = require('readline');
|
|
8
|
-
|
|
9
|
-
const SIZES = {
|
|
10
|
-
square: [1024, 1024], portrait: [832, 1216], tall: [768, 1344], photo: [1216, 832],
|
|
11
|
-
wide: [1344, 768], eye: [1280, 736], big: [1920, 1088],
|
|
12
|
-
};
|
|
13
|
-
const SIZE_NOTES = {
|
|
14
|
-
square: '1:1', portrait: '2:3, posters and people', tall: '9:16, phone screens', photo: '3:2',
|
|
15
|
-
wide: '16:9, scenes and banners', eye: '1280x736, the drone camera frame', big: '1920x1088, slower',
|
|
16
|
-
};
|
|
17
|
-
const DEFAULT_FOLDER = path.join(os.homedir(), '.labs', 'pictures');
|
|
18
|
-
|
|
19
|
-
function createPainter({ baseUrl, key, folder = DEFAULT_FOLDER, pollMs = 2000, waitMs = 300000, fetchImpl = fetch }) {
|
|
20
|
-
const call = async (url, init = {}) => {
|
|
21
|
-
const r = await fetchImpl(`${baseUrl}${url}`, { ...init, headers: { 'x-api-key': key, 'content-type': 'application/json', ...(init.headers || {}) } });
|
|
22
|
-
return r;
|
|
23
|
-
};
|
|
24
|
-
const explain = async r => {
|
|
25
|
-
const body = await r.json().catch(() => ({}));
|
|
26
|
-
if (r.status === 401) return 'The gateway refused the labs key. Run `labs key` to save a working one.';
|
|
27
|
-
return body.error || `The gateway answered ${r.status}.`;
|
|
28
|
-
};
|
|
29
|
-
|
|
30
|
-
async function paint({ prompt, size = 'square', count = 1, seed = null }) {
|
|
31
|
-
if (!String(prompt || '').trim()) throw new Error('Write a prompt first.');
|
|
32
|
-
const dims = SIZES[size];
|
|
33
|
-
if (!dims) throw new Error(`Unknown size "${size}". Sizes: ${Object.keys(SIZES).join(', ')}.`);
|
|
34
|
-
const n = Math.max(1, Math.min(Number(count) || 1, 4));
|
|
35
|
-
const started = Date.now();
|
|
36
|
-
let r;
|
|
37
|
-
try {
|
|
38
|
-
r = await call('/v1/images', { method: 'POST', body: JSON.stringify({ prompt, width: dims[0], height: dims[1], count: n, seed }) });
|
|
39
|
-
} catch (error) {
|
|
40
|
-
throw new Error(`Could not reach ${baseUrl} (${error.cause?.code || error.message}).`);
|
|
41
|
-
}
|
|
42
|
-
if (!r.ok) throw new Error(await explain(r));
|
|
43
|
-
const { job, seed: usedSeed } = await r.json();
|
|
44
|
-
let state;
|
|
45
|
-
for (;;) {
|
|
46
|
-
const s = await call(`/v1/images/${encodeURIComponent(job)}`);
|
|
47
|
-
if (!s.ok) throw new Error(await explain(s));
|
|
48
|
-
state = await s.json();
|
|
49
|
-
if (state.status === 'done' || state.status === 'error') break;
|
|
50
|
-
if (Date.now() - started > waitMs) throw new Error(`Job ${job} is still painting after ${Math.round(waitMs / 1000)} s; the box may be busy.`);
|
|
51
|
-
await new Promise(res => setTimeout(res, pollMs));
|
|
52
|
-
}
|
|
53
|
-
if (state.status === 'error') throw new Error(`The box could not paint it: ${state.error || 'unknown error'}.`);
|
|
54
|
-
const day = new Date().toISOString().slice(0, 10);
|
|
55
|
-
const dir = path.join(folder, day);
|
|
56
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
57
|
-
const files = [];
|
|
58
|
-
for (const img of state.images || []) {
|
|
59
|
-
// The name becomes a file path: only the box's own shape (20261113-181354-b8b1) may reach the disk.
|
|
60
|
-
if (!/^\d{8}-\d{6}-[0-9a-f]{4,8}$/.test(String(img.id)) || !String(img.url).startsWith('/v1/images/file/')) {
|
|
61
|
-
throw new Error('The gateway sent a picture name that is not allowed; nothing was saved.');
|
|
62
|
-
}
|
|
63
|
-
const f = await call(img.url);
|
|
64
|
-
if (!f.ok) throw new Error(await explain(f));
|
|
65
|
-
const file = path.join(dir, `${img.id}.png`);
|
|
66
|
-
fs.writeFileSync(file, Buffer.from(await f.arrayBuffer()));
|
|
67
|
-
files.push({ file, width: img.width, height: img.height, seed: img.seed });
|
|
68
|
-
}
|
|
69
|
-
return { files, seed: usedSeed, seconds: Math.round((Date.now() - started) / 100) / 10, prompt };
|
|
70
|
-
}
|
|
71
|
-
return { paint };
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
const TOOLS = [
|
|
75
|
-
{
|
|
76
|
-
name: 'paint',
|
|
77
|
-
description: 'Paint pictures with Qwen-Image on the labs box. Returns the saved PNG paths: open each with the Read tool to look at it, then judge and repaint. Same seed + small prompt change = a controlled comparison. About 15 s per picture.',
|
|
78
|
-
inputSchema: {
|
|
79
|
-
type: 'object',
|
|
80
|
-
properties: {
|
|
81
|
-
prompt: { type: 'string', description: 'What to paint: subject, setting, light, camera, style. Concrete nouns beat adjectives.' },
|
|
82
|
-
size: { type: 'string', enum: Object.keys(SIZES), description: 'Default square.' },
|
|
83
|
-
count: { type: 'integer', minimum: 1, maximum: 4, description: 'Pictures per call, 1-4. Default 1.' },
|
|
84
|
-
seed: { type: 'integer', description: 'Reuse a seed to change only the prompt between rounds.' },
|
|
85
|
-
},
|
|
86
|
-
required: ['prompt'],
|
|
87
|
-
},
|
|
88
|
-
},
|
|
89
|
-
{ name: 'sizes', description: 'List the picture sizes paint() accepts.', inputSchema: { type: 'object', properties: {} } },
|
|
90
|
-
];
|
|
91
|
-
|
|
92
|
-
// Claude Code puts these words in every chat that has the tool: the art director's loop travels with the tool.
|
|
93
|
-
const INSTRUCTIONS = `labs-image paints on our own GPU box (Qwen-Image), free to use, about 15-30 s per picture.
|
|
94
|
-
Work like an art director, not a vending machine:
|
|
95
|
-
1. Write the brief as a picture: subject, setting, light (time of day, direction), camera (distance, lens, angle), style, mood. Nouns over adjectives.
|
|
96
|
-
2. paint() it, then open every returned path with the Read tool and LOOK. Never judge a picture you did not open.
|
|
97
|
-
3. Score 1-10 against the brief, line by line: subject right? setting present? light as asked? composition (subject placement, crop, clutter)? anatomy (hands, faces, eyes)? text spelled right? style match? Name the single worst gap.
|
|
98
|
-
4. Rewrite the prompt to fix that one gap (say the missing thing earlier and more concretely; drop words the model ignored). Keep the seed to compare fairly; change the seed only to explore.
|
|
99
|
-
5. Repeat until 9/10 or 4 rounds. Show the user every round side by side with its score and the one change made, so they see why the last one is better.`;
|
|
100
|
-
|
|
101
|
-
async function handle(message, painter, version) {
|
|
102
|
-
const { id, method, params } = message;
|
|
103
|
-
if (method === 'initialize') {
|
|
104
|
-
return { protocolVersion: params?.protocolVersion || '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'labs-image', version }, instructions: INSTRUCTIONS };
|
|
105
|
-
}
|
|
106
|
-
if (method === 'ping') return {};
|
|
107
|
-
if (method === 'tools/list') return { tools: TOOLS };
|
|
108
|
-
if (method === 'tools/call') {
|
|
109
|
-
const args = params?.arguments || {};
|
|
110
|
-
if (params?.name === 'sizes') {
|
|
111
|
-
return { content: [{ type: 'text', text: Object.entries(SIZES).map(([k, [w, h]]) => `${k}: ${w}x${h} (${SIZE_NOTES[k]})`).join('\n') }] };
|
|
112
|
-
}
|
|
113
|
-
if (params?.name !== 'paint') return { content: [{ type: 'text', text: `Unknown tool ${params?.name}.` }], isError: true };
|
|
114
|
-
try {
|
|
115
|
-
const out = await painter.paint(args);
|
|
116
|
-
const lines = out.files.map(f => `${f.file} (${f.width}x${f.height}, seed ${f.seed})`);
|
|
117
|
-
return { content: [{ type: 'text', text: `Painted ${out.files.length} in ${out.seconds} s.\n${lines.join('\n')}\nOpen each path with the Read tool to look at it before you judge it.` }] };
|
|
118
|
-
} catch (error) {
|
|
119
|
-
return { content: [{ type: 'text', text: error.message }], isError: true };
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
if (id === undefined) return undefined; // a notification needs no answer
|
|
123
|
-
throw Object.assign(new Error(`Method not found: ${method}`), { code: -32601 });
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
function serve({ painter, version, input = process.stdin, output = process.stdout }) {
|
|
127
|
-
const rl = readline.createInterface({ input });
|
|
128
|
-
rl.on('line', async line => {
|
|
129
|
-
if (!line.trim()) return;
|
|
130
|
-
let message;
|
|
131
|
-
try { message = JSON.parse(line); } catch { return; }
|
|
132
|
-
try {
|
|
133
|
-
const result = await handle(message, painter, version);
|
|
134
|
-
if (message.id !== undefined && result !== undefined) output.write(JSON.stringify({ jsonrpc: '2.0', id: message.id, result }) + '\n');
|
|
135
|
-
} catch (error) {
|
|
136
|
-
if (message.id !== undefined) output.write(JSON.stringify({ jsonrpc: '2.0', id: message.id, error: { code: error.code || -32603, message: error.message } }) + '\n');
|
|
137
|
-
}
|
|
138
|
-
});
|
|
139
|
-
return rl;
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
function painterFromConfig() {
|
|
143
|
-
const { storedConfig } = require('./gateway-client');
|
|
144
|
-
const config = storedConfig();
|
|
145
|
-
if (!config.gatewayKey) return null;
|
|
146
|
-
return createPainter({ baseUrl: config.gatewayUrl || 'https://labs.
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
const NO_KEY = 'No labs key saved on this computer. Run `labs key` once, then try again.';
|
|
150
|
-
|
|
151
|
-
// `labs image-mcp`: the stdio server Claude Code starts. No key yet → every paint() answers with how to fix it.
|
|
152
|
-
function serveFromConfig(version) {
|
|
153
|
-
const painter = painterFromConfig() || { paint: async () => { throw new Error(NO_KEY); } };
|
|
154
|
-
serve({ painter, version });
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
// `labs paint "a red kite over Samarkand" --size wide --count 2 --seed 7`: the same painter from any terminal.
|
|
158
|
-
async function paintFromCli(args) {
|
|
159
|
-
const painter = painterFromConfig();
|
|
160
|
-
if (!painter) { console.error(`❌ ${NO_KEY}`); return process.exit(1); }
|
|
161
|
-
const opt = name => { const i = args.indexOf(`--${name}`); return i >= 0 ? args[i + 1] : undefined; };
|
|
162
|
-
const flags = new Set(['--size', '--count', '--seed']);
|
|
163
|
-
const prompt = args.filter((a, i) => !flags.has(a) && !flags.has(args[i - 1])).join(' ');
|
|
164
|
-
try {
|
|
165
|
-
const out = await painter.paint({ prompt, size: opt('size'), count: opt('count'), seed: opt('seed') === undefined ? null : Number(opt('seed')) });
|
|
166
|
-
console.log(`🎨 ${out.files.length} picture(s) in ${out.seconds} s`);
|
|
167
|
-
out.files.forEach(f => console.log(` ${f.file} (${f.width}x${f.height}, seed ${f.seed})`));
|
|
168
|
-
} catch (error) {
|
|
169
|
-
console.error(`❌ ${error.message}`);
|
|
170
|
-
process.exit(1);
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
module.exports = { SIZES, createPainter, handle, serve, serveFromConfig, paintFromCli };
|
|
1
|
+
// labs-image: lets any Claude Code chat or agent paint on the box (Qwen-Image) through the labs gateway.
|
|
2
|
+
// It saves each picture to disk and returns the path, so the agent opens it with its Read tool and actually looks.
|
|
3
|
+
// An MCP server is JSON-RPC over stdio, one JSON object per line; stdout carries only protocol, notes go to stderr.
|
|
4
|
+
const fs = require('fs');
|
|
5
|
+
const os = require('os');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
const readline = require('readline');
|
|
8
|
+
|
|
9
|
+
const SIZES = {
|
|
10
|
+
square: [1024, 1024], portrait: [832, 1216], tall: [768, 1344], photo: [1216, 832],
|
|
11
|
+
wide: [1344, 768], eye: [1280, 736], big: [1920, 1088],
|
|
12
|
+
};
|
|
13
|
+
const SIZE_NOTES = {
|
|
14
|
+
square: '1:1', portrait: '2:3, posters and people', tall: '9:16, phone screens', photo: '3:2',
|
|
15
|
+
wide: '16:9, scenes and banners', eye: '1280x736, the drone camera frame', big: '1920x1088, slower',
|
|
16
|
+
};
|
|
17
|
+
const DEFAULT_FOLDER = path.join(os.homedir(), '.labs', 'pictures');
|
|
18
|
+
|
|
19
|
+
function createPainter({ baseUrl, key, folder = DEFAULT_FOLDER, pollMs = 2000, waitMs = 300000, fetchImpl = fetch }) {
|
|
20
|
+
const call = async (url, init = {}) => {
|
|
21
|
+
const r = await fetchImpl(`${baseUrl}${url}`, { ...init, headers: { 'x-api-key': key, 'content-type': 'application/json', ...(init.headers || {}) } });
|
|
22
|
+
return r;
|
|
23
|
+
};
|
|
24
|
+
const explain = async r => {
|
|
25
|
+
const body = await r.json().catch(() => ({}));
|
|
26
|
+
if (r.status === 401) return 'The gateway refused the labs key. Run `labs key` to save a working one.';
|
|
27
|
+
return body.error || `The gateway answered ${r.status}.`;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
async function paint({ prompt, size = 'square', count = 1, seed = null }) {
|
|
31
|
+
if (!String(prompt || '').trim()) throw new Error('Write a prompt first.');
|
|
32
|
+
const dims = SIZES[size];
|
|
33
|
+
if (!dims) throw new Error(`Unknown size "${size}". Sizes: ${Object.keys(SIZES).join(', ')}.`);
|
|
34
|
+
const n = Math.max(1, Math.min(Number(count) || 1, 4));
|
|
35
|
+
const started = Date.now();
|
|
36
|
+
let r;
|
|
37
|
+
try {
|
|
38
|
+
r = await call('/v1/images', { method: 'POST', body: JSON.stringify({ prompt, width: dims[0], height: dims[1], count: n, seed }) });
|
|
39
|
+
} catch (error) {
|
|
40
|
+
throw new Error(`Could not reach ${baseUrl} (${error.cause?.code || error.message}).`);
|
|
41
|
+
}
|
|
42
|
+
if (!r.ok) throw new Error(await explain(r));
|
|
43
|
+
const { job, seed: usedSeed } = await r.json();
|
|
44
|
+
let state;
|
|
45
|
+
for (;;) {
|
|
46
|
+
const s = await call(`/v1/images/${encodeURIComponent(job)}`);
|
|
47
|
+
if (!s.ok) throw new Error(await explain(s));
|
|
48
|
+
state = await s.json();
|
|
49
|
+
if (state.status === 'done' || state.status === 'error') break;
|
|
50
|
+
if (Date.now() - started > waitMs) throw new Error(`Job ${job} is still painting after ${Math.round(waitMs / 1000)} s; the box may be busy.`);
|
|
51
|
+
await new Promise(res => setTimeout(res, pollMs));
|
|
52
|
+
}
|
|
53
|
+
if (state.status === 'error') throw new Error(`The box could not paint it: ${state.error || 'unknown error'}.`);
|
|
54
|
+
const day = new Date().toISOString().slice(0, 10);
|
|
55
|
+
const dir = path.join(folder, day);
|
|
56
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
57
|
+
const files = [];
|
|
58
|
+
for (const img of state.images || []) {
|
|
59
|
+
// The name becomes a file path: only the box's own shape (20261113-181354-b8b1) may reach the disk.
|
|
60
|
+
if (!/^\d{8}-\d{6}-[0-9a-f]{4,8}$/.test(String(img.id)) || !String(img.url).startsWith('/v1/images/file/')) {
|
|
61
|
+
throw new Error('The gateway sent a picture name that is not allowed; nothing was saved.');
|
|
62
|
+
}
|
|
63
|
+
const f = await call(img.url);
|
|
64
|
+
if (!f.ok) throw new Error(await explain(f));
|
|
65
|
+
const file = path.join(dir, `${img.id}.png`);
|
|
66
|
+
fs.writeFileSync(file, Buffer.from(await f.arrayBuffer()));
|
|
67
|
+
files.push({ file, width: img.width, height: img.height, seed: img.seed });
|
|
68
|
+
}
|
|
69
|
+
return { files, seed: usedSeed, seconds: Math.round((Date.now() - started) / 100) / 10, prompt };
|
|
70
|
+
}
|
|
71
|
+
return { paint };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const TOOLS = [
|
|
75
|
+
{
|
|
76
|
+
name: 'paint',
|
|
77
|
+
description: 'Paint pictures with Qwen-Image on the labs box. Returns the saved PNG paths: open each with the Read tool to look at it, then judge and repaint. Same seed + small prompt change = a controlled comparison. About 15 s per picture.',
|
|
78
|
+
inputSchema: {
|
|
79
|
+
type: 'object',
|
|
80
|
+
properties: {
|
|
81
|
+
prompt: { type: 'string', description: 'What to paint: subject, setting, light, camera, style. Concrete nouns beat adjectives.' },
|
|
82
|
+
size: { type: 'string', enum: Object.keys(SIZES), description: 'Default square.' },
|
|
83
|
+
count: { type: 'integer', minimum: 1, maximum: 4, description: 'Pictures per call, 1-4. Default 1.' },
|
|
84
|
+
seed: { type: 'integer', description: 'Reuse a seed to change only the prompt between rounds.' },
|
|
85
|
+
},
|
|
86
|
+
required: ['prompt'],
|
|
87
|
+
},
|
|
88
|
+
},
|
|
89
|
+
{ name: 'sizes', description: 'List the picture sizes paint() accepts.', inputSchema: { type: 'object', properties: {} } },
|
|
90
|
+
];
|
|
91
|
+
|
|
92
|
+
// Claude Code puts these words in every chat that has the tool: the art director's loop travels with the tool.
|
|
93
|
+
const INSTRUCTIONS = `labs-image paints on our own GPU box (Qwen-Image), free to use, about 15-30 s per picture.
|
|
94
|
+
Work like an art director, not a vending machine:
|
|
95
|
+
1. Write the brief as a picture: subject, setting, light (time of day, direction), camera (distance, lens, angle), style, mood. Nouns over adjectives.
|
|
96
|
+
2. paint() it, then open every returned path with the Read tool and LOOK. Never judge a picture you did not open.
|
|
97
|
+
3. Score 1-10 against the brief, line by line: subject right? setting present? light as asked? composition (subject placement, crop, clutter)? anatomy (hands, faces, eyes)? text spelled right? style match? Name the single worst gap.
|
|
98
|
+
4. Rewrite the prompt to fix that one gap (say the missing thing earlier and more concretely; drop words the model ignored). Keep the seed to compare fairly; change the seed only to explore.
|
|
99
|
+
5. Repeat until 9/10 or 4 rounds. Show the user every round side by side with its score and the one change made, so they see why the last one is better.`;
|
|
100
|
+
|
|
101
|
+
async function handle(message, painter, version) {
|
|
102
|
+
const { id, method, params } = message;
|
|
103
|
+
if (method === 'initialize') {
|
|
104
|
+
return { protocolVersion: params?.protocolVersion || '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'labs-image', version }, instructions: INSTRUCTIONS };
|
|
105
|
+
}
|
|
106
|
+
if (method === 'ping') return {};
|
|
107
|
+
if (method === 'tools/list') return { tools: TOOLS };
|
|
108
|
+
if (method === 'tools/call') {
|
|
109
|
+
const args = params?.arguments || {};
|
|
110
|
+
if (params?.name === 'sizes') {
|
|
111
|
+
return { content: [{ type: 'text', text: Object.entries(SIZES).map(([k, [w, h]]) => `${k}: ${w}x${h} (${SIZE_NOTES[k]})`).join('\n') }] };
|
|
112
|
+
}
|
|
113
|
+
if (params?.name !== 'paint') return { content: [{ type: 'text', text: `Unknown tool ${params?.name}.` }], isError: true };
|
|
114
|
+
try {
|
|
115
|
+
const out = await painter.paint(args);
|
|
116
|
+
const lines = out.files.map(f => `${f.file} (${f.width}x${f.height}, seed ${f.seed})`);
|
|
117
|
+
return { content: [{ type: 'text', text: `Painted ${out.files.length} in ${out.seconds} s.\n${lines.join('\n')}\nOpen each path with the Read tool to look at it before you judge it.` }] };
|
|
118
|
+
} catch (error) {
|
|
119
|
+
return { content: [{ type: 'text', text: error.message }], isError: true };
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (id === undefined) return undefined; // a notification needs no answer
|
|
123
|
+
throw Object.assign(new Error(`Method not found: ${method}`), { code: -32601 });
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function serve({ painter, version, input = process.stdin, output = process.stdout }) {
|
|
127
|
+
const rl = readline.createInterface({ input });
|
|
128
|
+
rl.on('line', async line => {
|
|
129
|
+
if (!line.trim()) return;
|
|
130
|
+
let message;
|
|
131
|
+
try { message = JSON.parse(line); } catch { return; }
|
|
132
|
+
try {
|
|
133
|
+
const result = await handle(message, painter, version);
|
|
134
|
+
if (message.id !== undefined && result !== undefined) output.write(JSON.stringify({ jsonrpc: '2.0', id: message.id, result }) + '\n');
|
|
135
|
+
} catch (error) {
|
|
136
|
+
if (message.id !== undefined) output.write(JSON.stringify({ jsonrpc: '2.0', id: message.id, error: { code: error.code || -32603, message: error.message } }) + '\n');
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
return rl;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function painterFromConfig() {
|
|
143
|
+
const { storedConfig } = require('./gateway-client');
|
|
144
|
+
const config = storedConfig();
|
|
145
|
+
if (!config.gatewayKey) return null;
|
|
146
|
+
return createPainter({ baseUrl: config.gatewayUrl || 'https://labs.humopedia.com', key: config.gatewayKey });
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const NO_KEY = 'No labs key saved on this computer. Run `labs key` once, then try again.';
|
|
150
|
+
|
|
151
|
+
// `labs image-mcp`: the stdio server Claude Code starts. No key yet → every paint() answers with how to fix it.
|
|
152
|
+
function serveFromConfig(version) {
|
|
153
|
+
const painter = painterFromConfig() || { paint: async () => { throw new Error(NO_KEY); } };
|
|
154
|
+
serve({ painter, version });
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// `labs paint "a red kite over Samarkand" --size wide --count 2 --seed 7`: the same painter from any terminal.
|
|
158
|
+
async function paintFromCli(args) {
|
|
159
|
+
const painter = painterFromConfig();
|
|
160
|
+
if (!painter) { console.error(`❌ ${NO_KEY}`); return process.exit(1); }
|
|
161
|
+
const opt = name => { const i = args.indexOf(`--${name}`); return i >= 0 ? args[i + 1] : undefined; };
|
|
162
|
+
const flags = new Set(['--size', '--count', '--seed']);
|
|
163
|
+
const prompt = args.filter((a, i) => !flags.has(a) && !flags.has(args[i - 1])).join(' ');
|
|
164
|
+
try {
|
|
165
|
+
const out = await painter.paint({ prompt, size: opt('size'), count: opt('count'), seed: opt('seed') === undefined ? null : Number(opt('seed')) });
|
|
166
|
+
console.log(`🎨 ${out.files.length} picture(s) in ${out.seconds} s`);
|
|
167
|
+
out.files.forEach(f => console.log(` ${f.file} (${f.width}x${f.height}, seed ${f.seed})`));
|
|
168
|
+
} catch (error) {
|
|
169
|
+
console.error(`❌ ${error.message}`);
|
|
170
|
+
process.exit(1);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
module.exports = { SIZES, createPainter, handle, serve, serveFromConfig, paintFromCli };
|