labs-claude 0.3.0 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/gemini.js ADDED
@@ -0,0 +1,474 @@
1
+ const { createHash, randomUUID } = require('crypto');
2
+ const { execFileSync } = require('child_process');
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+
7
+ // Aliases whose value starts with this prefix run directly on Google Gemini / Vertex AI instead of ElevenLabs.
8
+ const GEMINI_PREFIX = 'gemini:';
9
+ const AISTUDIO_BASE = 'https://generativelanguage.googleapis.com/v1beta';
10
+ const MAX_OUTPUT_TOKENS = 65536;
11
+ const SIGNATURES_MAX = 2000;
12
+ const TOKEN_TTL_MS = 45 * 60 * 1000;
13
+ const SUPPORTED_IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/webp']);
14
+ const EFFORT_TO_LEVEL = { none: 'LOW', minimal: 'LOW', low: 'LOW', medium: 'MEDIUM', high: 'HIGH', xhigh: 'XHIGH', max: 'XHIGH' };
15
+
16
+ function geminiModelId(llm) {
17
+ return typeof llm === 'string' && llm.startsWith(GEMINI_PREFIX) ? llm.slice(GEMINI_PREFIX.length) : null;
18
+ }
19
+
20
+ // Gemini function names must match ^[a-zA-Z_][a-zA-Z0-9_.:-]{0,63}$.
21
+ function geminiToolName(name) {
22
+ if (/^[a-zA-Z_][a-zA-Z0-9_.:-]{0,63}$/.test(name)) return name;
23
+ const hash = createHash('sha1').update(name).digest('hex').slice(0, 8);
24
+ const cleaned = name.replace(/[^a-zA-Z0-9_.:-]/g, '_');
25
+ const prefixed = /^[a-zA-Z_]/.test(cleaned) ? cleaned : `t_${cleaned}`;
26
+ return `${prefixed.slice(0, 55)}_${hash}`;
27
+ }
28
+
29
+ function thinkingLevelFor(effort) {
30
+ const key = String(effort || 'high').toLowerCase();
31
+ return EFFORT_TO_LEVEL[key] || 'HIGH';
32
+ }
33
+
34
+ // Gemini functionDeclarations accept an OpenAPI-subset Schema and reject JSON-Schema keys like $schema, const,
35
+ // additionalProperties, and null-union arrays.
36
+ function sanitizeSchema(schema) {
37
+ if (!schema || typeof schema !== 'object') return { type: 'object' };
38
+
39
+ const branches = schema.anyOf || schema.oneOf;
40
+ if (Array.isArray(branches) && branches.length) {
41
+ const hasNull = branches.some(b => b?.type === 'null');
42
+ const chosen = branches.find(b => b && b.type !== 'null') || branches[0];
43
+ const merged = sanitizeSchema({
44
+ ...chosen,
45
+ ...(schema.description && !chosen.description ? { description: schema.description } : {})
46
+ });
47
+ if (hasNull) merged.nullable = true;
48
+ return merged;
49
+ }
50
+
51
+ const out = {};
52
+ if (schema.description) out.description = String(schema.description);
53
+
54
+ if (schema.const !== undefined) {
55
+ out.type = typeof schema.const === 'number' ? 'number'
56
+ : typeof schema.const === 'boolean' ? 'boolean' : 'string';
57
+ out.enum = [String(schema.const)];
58
+ } else if (Array.isArray(schema.type)) {
59
+ const nonNull = schema.type.find(t => t !== 'null') || 'string';
60
+ out.type = nonNull;
61
+ if (schema.type.includes('null')) out.nullable = true;
62
+ } else if (schema.type) {
63
+ out.type = schema.type === 'null' ? 'string' : schema.type;
64
+ } else if (schema.properties) {
65
+ out.type = 'object';
66
+ } else if (schema.items) {
67
+ out.type = 'array';
68
+ } else {
69
+ out.type = 'string';
70
+ }
71
+
72
+ if (Array.isArray(schema.enum)) out.enum = schema.enum.map(v => typeof v === 'string' ? v : String(v));
73
+ if (schema.nullable === true) out.nullable = true;
74
+
75
+ if (out.type === 'object') {
76
+ const props = {};
77
+ for (const [key, child] of Object.entries(schema.properties || {})) {
78
+ props[key] = sanitizeSchema(child);
79
+ }
80
+ if (Object.keys(props).length) {
81
+ out.properties = props;
82
+ const required = (schema.required || []).filter(k => k in props);
83
+ if (required.length) out.required = required;
84
+ }
85
+ } else if (out.type === 'array') {
86
+ out.items = sanitizeSchema(schema.items || { type: 'string' });
87
+ }
88
+
89
+ return out;
90
+ }
91
+
92
+ function textOf(content) {
93
+ if (typeof content === 'string') return content;
94
+ return (content || []).map(block => block.type === 'text' ? block.text : `[${block.type}]`).join('\n');
95
+ }
96
+
97
+ function imagePart(source) {
98
+ const mimeType = source?.media_type === 'image/jpg' ? 'image/jpeg' : source?.media_type;
99
+ if (source?.type !== 'base64' || !SUPPORTED_IMAGE_TYPES.has(mimeType)) {
100
+ return { text: '[image in an unsupported format was left out]' };
101
+ }
102
+ return { inlineData: { mimeType, data: source.data } };
103
+ }
104
+
105
+ function toolResultPayload(content) {
106
+ if (typeof content === 'string' || content == null) {
107
+ return { output: String(content || '(no output)') };
108
+ }
109
+ const text = content
110
+ .map(b => b.type === 'text' ? b.text : b.type === 'image' ? '[image omitted]' : textOf([b]))
111
+ .filter(Boolean)
112
+ .join('\n');
113
+ return { output: text || '(no output)' };
114
+ }
115
+
116
+ // Persists tool_use_id -> thoughtSignature across turns and --resume restarts so Gemini 4 never rejects tool history.
117
+ class ThoughtSignatureStore {
118
+ constructor(file) {
119
+ this.file = file;
120
+ this.map = new Map();
121
+ if (file && fs.existsSync(file)) {
122
+ try {
123
+ const entries = JSON.parse(fs.readFileSync(file, 'utf8'));
124
+ for (const [id, sig] of entries) this.map.set(id, sig);
125
+ } catch {
126
+ // Ignore corrupt cache; new turns repopulate it.
127
+ }
128
+ }
129
+ }
130
+
131
+ get(id) {
132
+ return id ? this.map.get(id) : undefined;
133
+ }
134
+
135
+ set(id, signature) {
136
+ if (!id || !signature) return;
137
+ this.map.delete(id);
138
+ this.map.set(id, signature);
139
+ while (this.map.size > SIGNATURES_MAX) {
140
+ const oldest = this.map.keys().next().value;
141
+ this.map.delete(oldest);
142
+ }
143
+ if (this.file) {
144
+ fs.mkdirSync(path.dirname(this.file), { recursive: true });
145
+ fs.writeFileSync(this.file, JSON.stringify([...this.map.entries()]), { mode: 0o600 });
146
+ }
147
+ }
148
+ }
149
+
150
+ function toGeminiRequest(body, modelId, { effort = 'high', includeThoughts = false, signatures = null } = {}) {
151
+ const tools = (body.tools || []).filter(tool => tool.name && tool.input_schema);
152
+ const withTools = tools.length > 0;
153
+ const toolNameMap = new Map(tools.map(tool => [geminiToolName(tool.name), tool.name]));
154
+ const callNamesById = new Map();
155
+
156
+ for (const message of body.messages || []) {
157
+ if (message.role !== 'assistant' || !Array.isArray(message.content)) continue;
158
+ for (const block of message.content) {
159
+ if (block.type === 'tool_use' && block.id && block.name) {
160
+ callNamesById.set(block.id, geminiToolName(block.name));
161
+ }
162
+ }
163
+ }
164
+
165
+ const contents = [];
166
+ for (const message of body.messages || []) {
167
+ if (message.role !== 'user' && message.role !== 'assistant') continue;
168
+ const role = message.role === 'assistant' ? 'model' : 'user';
169
+ const blocks = typeof message.content === 'string'
170
+ ? [{ type: 'text', text: message.content }]
171
+ : message.content || [];
172
+
173
+ const parts = [];
174
+ for (const block of blocks) {
175
+ if (block.type === 'text') {
176
+ if (block.text?.trim()) parts.push({ text: block.text });
177
+ } else if (block.type === 'image') {
178
+ parts.push(imagePart(block.source));
179
+ } else if (block.type === 'document') {
180
+ if (block.source?.type === 'text') parts.push({ text: block.source.data });
181
+ else if (block.source?.type === 'base64' && block.source.media_type === 'application/pdf') {
182
+ parts.push({ inlineData: { mimeType: 'application/pdf', data: block.source.data } });
183
+ } else {
184
+ parts.push({ text: '[a document was left out]' });
185
+ }
186
+ } else if (block.type === 'tool_use') {
187
+ if (!withTools) {
188
+ parts.push({ text: `[called tool ${block.name} with ${JSON.stringify(block.input || {})}]` });
189
+ } else {
190
+ const part = {
191
+ functionCall: {
192
+ ...(block.id ? { id: block.id } : {}),
193
+ name: geminiToolName(block.name),
194
+ args: block.input || {}
195
+ }
196
+ };
197
+ const sig = block.thought_signature || signatures?.get(block.id);
198
+ if (sig) part.thoughtSignature = sig;
199
+ parts.push(part);
200
+ }
201
+ } else if (block.type === 'tool_result') {
202
+ if (!withTools) {
203
+ parts.push({ text: `[tool result]\n${textOf(block.content)}` });
204
+ } else {
205
+ const responseObj = toolResultPayload(block.content);
206
+ if (block.is_error) responseObj.isError = true;
207
+ parts.push({
208
+ functionResponse: {
209
+ ...(block.tool_use_id ? { id: block.tool_use_id } : {}),
210
+ name: callNamesById.get(block.tool_use_id) || 'tool',
211
+ response: responseObj
212
+ }
213
+ });
214
+ }
215
+ }
216
+ }
217
+
218
+ if (!parts.length) continue;
219
+ const last = contents.at(-1);
220
+ if (last?.role === role) last.parts.push(...parts);
221
+ else contents.push({ role, parts });
222
+ }
223
+
224
+ if (contents[0]?.role === 'model') contents.unshift({ role: 'user', parts: [{ text: '(continue)' }] });
225
+
226
+ const systemText = typeof body.system === 'string' ? body.system : textOf(body.system);
227
+ const generationConfig = {
228
+ maxOutputTokens: Math.min(body.max_tokens || 32768, MAX_OUTPUT_TOKENS)
229
+ };
230
+ if (typeof body.temperature === 'number') generationConfig.temperature = body.temperature;
231
+ if (/^gemini-4/i.test(modelId)) {
232
+ generationConfig.thinkingConfig = {
233
+ thinkingLevel: thinkingLevelFor(effort),
234
+ ...(includeThoughts ? { includeThoughts: true } : {})
235
+ };
236
+ }
237
+
238
+ const request = { contents, generationConfig };
239
+ if (systemText.trim()) request.systemInstruction = { parts: [{ text: systemText }] };
240
+ if (withTools) {
241
+ request.tools = [{
242
+ functionDeclarations: tools.map(tool => ({
243
+ name: geminiToolName(tool.name),
244
+ description: tool.description || tool.name,
245
+ parameters: sanitizeSchema(tool.input_schema)
246
+ }))
247
+ }];
248
+ }
249
+
250
+ return { request, toolNameMap };
251
+ }
252
+
253
+ function readGeminiKey(labsDir) {
254
+ if (process.env.GEMINI_API_KEY) return process.env.GEMINI_API_KEY.trim();
255
+ const file = path.join(labsDir, 'gemini-key');
256
+ return fs.existsSync(file) ? fs.readFileSync(file, 'utf8').trim() : null;
257
+ }
258
+
259
+ function saveGeminiKey(labsDir, key) {
260
+ fs.mkdirSync(labsDir, { recursive: true });
261
+ fs.writeFileSync(path.join(labsDir, 'gemini-key'), key.trim(), { mode: 0o600 });
262
+ }
263
+
264
+ function readVertexConfig(config = {}) {
265
+ const project = process.env.ANTHROPIC_VERTEX_PROJECT_ID || process.env.GOOGLE_CLOUD_PROJECT || config.vertexProject;
266
+ const region = process.env.CLOUD_ML_REGION || config.vertexRegion || 'global';
267
+ return project ? { project, region } : null;
268
+ }
269
+
270
+ function gcloudAdcPath() {
271
+ if (process.env.GOOGLE_APPLICATION_CREDENTIALS) return process.env.GOOGLE_APPLICATION_CREDENTIALS;
272
+ if (process.platform === 'win32' && process.env.APPDATA) {
273
+ return path.join(process.env.APPDATA, 'gcloud', 'application_default_credentials.json');
274
+ }
275
+ return path.join(os.homedir(), '.config', 'gcloud', 'application_default_credentials.json');
276
+ }
277
+
278
+ let cachedVertexToken = { token: null, expiresAt: 0 };
279
+
280
+ async function getVertexAccessToken() {
281
+ if (cachedVertexToken.token && Date.now() < cachedVertexToken.expiresAt) {
282
+ return cachedVertexToken.token;
283
+ }
284
+
285
+ const adcFile = gcloudAdcPath();
286
+ if (fs.existsSync(adcFile)) {
287
+ try {
288
+ const creds = JSON.parse(fs.readFileSync(adcFile, 'utf8'));
289
+ if (creds.type === 'authorized_user' && creds.refresh_token && creds.client_id && creds.client_secret) {
290
+ const res = await fetch('https://oauth2.googleapis.com/token', {
291
+ method: 'POST',
292
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
293
+ body: new URLSearchParams({
294
+ client_id: creds.client_id,
295
+ client_secret: creds.client_secret,
296
+ refresh_token: creds.refresh_token,
297
+ grant_type: 'refresh_token'
298
+ })
299
+ });
300
+ if (res.ok) {
301
+ const data = await res.json();
302
+ if (data.access_token) {
303
+ cachedVertexToken = { token: data.access_token, expiresAt: Date.now() + TOKEN_TTL_MS };
304
+ return data.access_token;
305
+ }
306
+ }
307
+ }
308
+ } catch {
309
+ // Fall through to gcloud CLI lookup.
310
+ }
311
+ }
312
+
313
+ try {
314
+ const token = execFileSync('gcloud', ['auth', 'application-default', 'print-access-token'], {
315
+ encoding: 'utf8',
316
+ stdio: ['ignore', 'pipe', 'pipe']
317
+ }).trim();
318
+ if (token) {
319
+ cachedVertexToken = { token, expiresAt: Date.now() + TOKEN_TTL_MS };
320
+ return token;
321
+ }
322
+ } catch {
323
+ // Handled below with actionable message.
324
+ }
325
+
326
+ const err = new Error('Google Cloud ADC credentials not found. Run: gcloud auth application-default login');
327
+ err.status = 401;
328
+ throw err;
329
+ }
330
+
331
+ function resolveGeminiAuth(labsDir, config = {}) {
332
+ const apiKey = readGeminiKey(labsDir);
333
+ if (apiKey) return { mode: 'aistudio', apiKey };
334
+ const vertex = readVertexConfig(config);
335
+ if (vertex) return { mode: 'vertex', ...vertex };
336
+ return null;
337
+ }
338
+
339
+ function buildEndpoint(auth, modelId) {
340
+ if (auth.mode === 'vertex') {
341
+ const host = auth.region === 'global'
342
+ ? 'aiplatform.googleapis.com'
343
+ : `${auth.region}-aiplatform.googleapis.com`;
344
+ return `https://${host}/v1/projects/${encodeURIComponent(auth.project)}/locations/${encodeURIComponent(auth.region)}/publishers/google/models/${encodeURIComponent(modelId)}:streamGenerateContent?alt=sse`;
345
+ }
346
+ return `${AISTUDIO_BASE}/models/${encodeURIComponent(modelId)}:streamGenerateContent?alt=sse`;
347
+ }
348
+
349
+ // Consumes Gemini SSE stream chunks and emits text deltas while collecting function calls and thought signatures.
350
+ async function consumeGeminiSse(stream, { toolNameMap, onText, onThinking, signatures }) {
351
+ const decoder = new TextDecoder();
352
+ let buffer = '';
353
+ let text = '';
354
+ let thinking = '';
355
+ let finishReason = null;
356
+ const toolCalls = [];
357
+ const usage = { inputTokens: 0, outputTokens: 0, cachedTokens: 0 };
358
+
359
+ const handlePayload = raw => {
360
+ const data = JSON.parse(raw);
361
+ if (data.usageMetadata) {
362
+ usage.inputTokens = data.usageMetadata.promptTokenCount || usage.inputTokens;
363
+ usage.cachedTokens = data.usageMetadata.cachedContentTokenCount || usage.cachedTokens;
364
+ const out = (data.usageMetadata.candidatesTokenCount || 0) + (data.usageMetadata.thoughtsTokenCount || 0);
365
+ if (out) usage.outputTokens = out;
366
+ }
367
+ const candidate = data.candidates?.[0];
368
+ if (!candidate) return;
369
+ if (candidate.finishReason) finishReason = candidate.finishReason;
370
+ for (const part of candidate.content?.parts || []) {
371
+ if (part.thought === true) {
372
+ if (typeof part.text === 'string' && part.text.length) {
373
+ thinking += part.text;
374
+ if (onThinking) onThinking(part.text);
375
+ }
376
+ continue;
377
+ }
378
+ if (typeof part.text === 'string' && part.text.length) {
379
+ text += part.text;
380
+ if (onText) onText(part.text);
381
+ } else if (part.functionCall) {
382
+ const callId = part.functionCall.id || `call_${randomUUID().replace(/-/g, '').slice(0, 20)}`;
383
+ const name = toolNameMap.get(part.functionCall.name) || part.functionCall.name;
384
+ if (part.thoughtSignature) signatures?.set(callId, part.thoughtSignature);
385
+ toolCalls.push({
386
+ id: callId,
387
+ name,
388
+ input: part.functionCall.args || {},
389
+ ...(part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {})
390
+ });
391
+ }
392
+ }
393
+ };
394
+
395
+ const drain = flush => {
396
+ const lines = buffer.split(/\r?\n/);
397
+ buffer = flush ? '' : lines.pop();
398
+ for (const line of lines) {
399
+ if (!line.startsWith('data:')) continue;
400
+ const payload = line.slice(5).trim();
401
+ if (!payload || payload === '[DONE]') continue;
402
+ handlePayload(payload);
403
+ }
404
+ };
405
+
406
+ for await (const chunk of stream) {
407
+ buffer += typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true });
408
+ drain(false);
409
+ }
410
+ buffer += decoder.decode();
411
+ drain(true);
412
+
413
+ return {
414
+ text,
415
+ thinking,
416
+ toolCalls,
417
+ usage,
418
+ stopReason: finishReason === 'MAX_TOKENS' ? 'max_tokens' : finishReason
419
+ };
420
+ }
421
+
422
+ async function streamGemini({ auth, body, modelId, effort, onText, onThinking, signal, signatures, fetchImpl = fetch }) {
423
+ const { request, toolNameMap } = toGeminiRequest(body, modelId, {
424
+ effort,
425
+ includeThoughts: Boolean(onThinking),
426
+ signatures
427
+ });
428
+ const headers = { 'Content-Type': 'application/json' };
429
+ if (auth.mode === 'vertex') {
430
+ headers.Authorization = `Bearer ${await getVertexAccessToken()}`;
431
+ } else {
432
+ headers['x-goog-api-key'] = auth.apiKey;
433
+ }
434
+
435
+ const response = await fetchImpl(buildEndpoint(auth, modelId), {
436
+ method: 'POST',
437
+ headers,
438
+ body: JSON.stringify(request),
439
+ signal
440
+ });
441
+
442
+ if (!response.ok) {
443
+ let detail = response.statusText || `HTTP ${response.status}`;
444
+ try {
445
+ const parsed = JSON.parse(await response.text());
446
+ detail = parsed.error?.message || JSON.stringify(parsed).slice(0, 300);
447
+ } catch {
448
+ // Keep HTTP status text.
449
+ }
450
+ const error = new Error(detail);
451
+ error.status = response.status;
452
+ throw error;
453
+ }
454
+
455
+ return consumeGeminiSse(response.body, { toolNameMap, onText, onThinking, signatures });
456
+ }
457
+
458
+ module.exports = {
459
+ AISTUDIO_BASE,
460
+ GEMINI_PREFIX,
461
+ ThoughtSignatureStore,
462
+ buildEndpoint,
463
+ consumeGeminiSse,
464
+ geminiModelId,
465
+ geminiToolName,
466
+ readGeminiKey,
467
+ readVertexConfig,
468
+ resolveGeminiAuth,
469
+ sanitizeSchema,
470
+ saveGeminiKey,
471
+ streamGemini,
472
+ thinkingLevelFor,
473
+ toGeminiRequest
474
+ };
@@ -0,0 +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.instant.uz', 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 };
@@ -19,16 +19,27 @@ function parseLaunchArgs(args, { aliases, llmIds, defaultModel }) {
19
19
  if (!aliases[modelName] && !llmIds.has(modelName)) {
20
20
  throw new Error(`Unknown model "${modelName}". Run "labs models --all" to list models.`);
21
21
  }
22
- return { modelName, claudeArgs: [...claudeArgs, '--model', modelName] };
22
+ return { modelName, claudeArgs: withBypassDefault([...claudeArgs, '--model', modelName]) };
23
23
  }
24
24
 
25
- function withLabsHeaders(headers, sessionId, modelName) {
25
+ // Boss's choice (2026-11-12): every labs session runs with no permission prompts unless he names a mode himself.
26
+ // Auto mode cannot work on Qwen anyway: its safety check asks Qwen, which never answers in the expected shape.
27
+ function withBypassDefault(args) {
28
+ const named = args.some(a => a === '--permission-mode' || a.startsWith('--permission-mode=') || a === '--dangerously-skip-permissions');
29
+ return named ? args : [...args, '--permission-mode', 'bypassPermissions'];
30
+ }
31
+
32
+ function withLabsHeaders(headers, sessionId, modelName, effort, cwd) {
26
33
  const lines = String(headers || '')
27
34
  .split(/\r?\n/)
28
35
  .filter(line => line.trim()
29
36
  && !/^\s*x-labs-session-id\s*:/i.test(line)
30
- && !/^\s*x-labs-model\s*:/i.test(line));
37
+ && !/^\s*x-labs-model\s*:/i.test(line)
38
+ && !/^\s*x-labs-effort\s*:/i.test(line)
39
+ && !/^\s*x-labs-cwd\s*:/i.test(line));
31
40
  lines.push(`X-Labs-Session-Id: ${sessionId}`, `X-Labs-Model: ${modelName}`);
41
+ if (effort) lines.push(`X-Labs-Effort: ${effort}`);
42
+ if (cwd) lines.push(`X-Labs-Cwd: ${cwd}`);
32
43
  return lines.join('\n');
33
44
  }
34
45
 
@@ -41,4 +52,4 @@ function chromeCompatibilityWarning(args) {
41
52
  + 'See https://code.claude.com/docs/en/chrome';
42
53
  }
43
54
 
44
- module.exports = { parseLaunchArgs, withLabsHeaders, chromeCompatibilityWarning };
55
+ module.exports = { parseLaunchArgs, withBypassDefault, withLabsHeaders, chromeCompatibilityWarning };