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.
@@ -3,11 +3,21 @@ const { createHash, randomUUID } = require('crypto');
3
3
  const modelDisplayNames = {
4
4
  astra: 'GPT-6 Astra',
5
5
  opus: 'Opus 5.5',
6
- glm: 'GLM-52',
6
+ glm: 'GLM-53',
7
7
  sol: 'GPT-6 Sol',
8
8
  qwen: 'Qwen3-6 35B',
9
9
  oss: 'GPT-OSS-120B',
10
- gemini: 'Gemini 3.8 Flash'
10
+ hydrogen: 'Gemini 4 Hydrogen',
11
+ gemini: 'Gemini 4 Hydrogen',
12
+ gem: 'Gemini 4 Hydrogen (agy)',
13
+ 'agy-flash': 'Gemini 3.8 Flash (agy)',
14
+ 'agy-sonnet': 'Claude Sonnet 4.6 (agy)',
15
+ 'agy-opus': 'Claude Opus 4.6 (agy)',
16
+ 'agy-oss': 'GPT-OSS 120B (agy)',
17
+ carbon: 'Gemini 4 Carbon',
18
+ neon: 'Gemini 4 Neon',
19
+ argon: 'Gemini 4 Argon',
20
+ gemini3: 'Gemini 3.8 Flash'
11
21
  };
12
22
 
13
23
  function contentToText(content) {
@@ -91,7 +101,7 @@ function extractLatestUserTurn(messages) {
91
101
  return { text: '', toolResults: [], images: [] };
92
102
  }
93
103
 
94
- function createAnthropicMessage({ model, text = '', toolCalls = [], inputTokens = 0 }) {
104
+ function createAnthropicMessage({ model, text = '', thinking = '', toolCalls = [], inputTokens = 0 }) {
95
105
  const toolBlocks = toolCalls.map(tool => ({
96
106
  type: 'tool_use',
97
107
  id: tool.id,
@@ -99,10 +109,11 @@ function createAnthropicMessage({ model, text = '', toolCalls = [], inputTokens
99
109
  input: tool.input || {}
100
110
  }));
101
111
  const content = [
102
- ...(text || toolBlocks.length === 0 ? [{ type: 'text', text }] : []),
112
+ ...(thinking ? [{ type: 'thinking', thinking, signature: 'gemini' }] : []),
113
+ ...(text || (toolBlocks.length === 0 && !thinking) ? [{ type: 'text', text }] : []),
103
114
  ...toolBlocks
104
115
  ];
105
- const outputText = text + (toolBlocks.length ? JSON.stringify(toolBlocks) : '');
116
+ const outputText = thinking + text + (toolBlocks.length ? JSON.stringify(toolBlocks) : '');
106
117
 
107
118
  return {
108
119
  id: `msg_${randomUUID()}`,
@@ -208,7 +219,22 @@ function createAnthropicEvents(message) {
208
219
  });
209
220
 
210
221
  content.forEach((block, index) => {
211
- if (block.type === 'text') {
222
+ if (block.type === 'thinking') {
223
+ emit('content_block_start', {
224
+ type: 'content_block_start', index,
225
+ content_block: { type: 'thinking', thinking: '' }
226
+ });
227
+ if (block.thinking) {
228
+ emit('content_block_delta', {
229
+ type: 'content_block_delta', index,
230
+ delta: { type: 'thinking_delta', thinking: block.thinking }
231
+ });
232
+ }
233
+ emit('content_block_delta', {
234
+ type: 'content_block_delta', index,
235
+ delta: { type: 'signature_delta', signature: block.signature || 'gemini' }
236
+ });
237
+ } else if (block.type === 'text') {
212
238
  emit('content_block_start', {
213
239
  type: 'content_block_start', index,
214
240
  content_block: { type: 'text', text: '' }
@@ -267,28 +293,69 @@ const STREAM_PING_MS = 10000;
267
293
  // Nothing is sent before the first word, so an early failure can still be answered with an HTTP error and retried.
268
294
  function createLiveStream(response, { model, inputTokens }) {
269
295
  let pingTimer = null;
296
+ let activeBlock = null;
297
+ let nextIndex = 0;
298
+
299
+ const ensureStarted = () => {
300
+ if (live.started) return;
301
+ live.started = true;
302
+ startEventStream(response);
303
+ const { content, usage, ...start } = createAnthropicMessage({ model, inputTokens });
304
+ writeEvent(response, { event: 'message_start', data: { type: 'message_start', message: { ...start, content: [], stop_reason: null, usage: { input_tokens: inputTokens, output_tokens: 0 } } } });
305
+ pingTimer = setInterval(() => writeEvent(response, { event: 'ping', data: { type: 'ping' } }), STREAM_PING_MS);
306
+ };
307
+
308
+ const closeActiveBlock = () => {
309
+ if (!activeBlock) return;
310
+ if (activeBlock.type === 'thinking') {
311
+ writeEvent(response, { event: 'content_block_delta', data: { type: 'content_block_delta', index: activeBlock.index, delta: { type: 'signature_delta', signature: 'gemini' } } });
312
+ }
313
+ writeEvent(response, { event: 'content_block_stop', data: { type: 'content_block_stop', index: activeBlock.index } });
314
+ activeBlock = null;
315
+ };
316
+
270
317
  const live = {
271
318
  started: false,
272
319
  streamedText: '',
320
+ streamedThinking: '',
321
+ thinking(delta) {
322
+ if (!delta) return;
323
+ ensureStarted();
324
+ if (activeBlock?.type !== 'thinking') {
325
+ closeActiveBlock();
326
+ activeBlock = { type: 'thinking', index: nextIndex++ };
327
+ writeEvent(response, { event: 'content_block_start', data: { type: 'content_block_start', index: activeBlock.index, content_block: { type: 'thinking', thinking: '' } } });
328
+ }
329
+ live.streamedThinking += delta;
330
+ writeEvent(response, { event: 'content_block_delta', data: { type: 'content_block_delta', index: activeBlock.index, delta: { type: 'thinking_delta', thinking: delta } } });
331
+ },
273
332
  text(delta) {
274
- if (!live.started) {
275
- live.started = true;
276
- startEventStream(response);
277
- const { content, usage, ...start } = createAnthropicMessage({ model, inputTokens });
278
- writeEvent(response, { event: 'message_start', data: { type: 'message_start', message: { ...start, content: [], stop_reason: null, usage: { input_tokens: inputTokens, output_tokens: 0 } } } });
279
- writeEvent(response, { event: 'content_block_start', data: { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } } });
280
- pingTimer = setInterval(() => writeEvent(response, { event: 'ping', data: { type: 'ping' } }), STREAM_PING_MS);
333
+ ensureStarted();
334
+ if (activeBlock?.type !== 'text') {
335
+ closeActiveBlock();
336
+ activeBlock = { type: 'text', index: nextIndex++ };
337
+ writeEvent(response, { event: 'content_block_start', data: { type: 'content_block_start', index: activeBlock.index, content_block: { type: 'text', text: '' } } });
281
338
  }
282
339
  live.streamedText += delta;
283
- writeEvent(response, { event: 'content_block_delta', data: { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: delta } } });
340
+ writeEvent(response, { event: 'content_block_delta', data: { type: 'content_block_delta', index: activeBlock.index, delta: { type: 'text_delta', text: delta } } });
284
341
  },
285
342
  // The message must carry streamedText as its text, so the reply Claude Code stores matches what it was shown.
286
343
  finish(message) {
287
344
  live.stopPings();
288
345
  if (!live.started) return writeAnthropicEvents(response, createAnthropicEvents(message));
289
- writeEvent(response, { event: 'content_block_stop', data: { type: 'content_block_stop', index: 0 } });
290
- const rest = createAnthropicEvents(message).filter(({ event, data }) => event !== 'message_start' && data.index !== 0);
291
- for (const event of rest) writeEvent(response, event);
346
+ closeActiveBlock();
347
+ const remaining = {
348
+ ...message,
349
+ content: message.content.filter(block => !(block.type === 'thinking' && live.streamedThinking) && !(block.type === 'text' && live.streamedText))
350
+ };
351
+ const rest = createAnthropicEvents(remaining).filter(({ event }) => event !== 'message_start');
352
+ for (const event of rest) {
353
+ if (typeof event.data?.index === 'number') {
354
+ writeEvent(response, { ...event, data: { ...event.data, index: event.data.index + nextIndex } });
355
+ } else {
356
+ writeEvent(response, event);
357
+ }
358
+ }
292
359
  response.end();
293
360
  },
294
361
  fail(error) {
@@ -0,0 +1,95 @@
1
+ const fs = require('fs');
2
+ const os = require('os');
3
+ const path = require('path');
4
+ const { randomUUID } = require('crypto');
5
+ const { detectInText } = require('./subscription-failure');
6
+
7
+ const PROJECTS_DIR = path.join(os.homedir(), '.claude', 'projects');
8
+
9
+ // Flags that name the session or the model are rewritten per leg; everything else passes through untouched.
10
+ function stripSessionAndModelArgs(args) {
11
+ const out = [];
12
+ for (let i = 0; i < args.length; i += 1) {
13
+ const arg = args[i];
14
+ if (['--session-id', '--resume', '-r', '--model'].includes(arg)) { i += 1; continue; }
15
+ if (/^--(session-id|resume|model)=/.test(arg) || arg === '--continue' || arg === '-c') continue;
16
+ out.push(arg);
17
+ }
18
+ return out;
19
+ }
20
+
21
+ function findResumeId(args) {
22
+ const i = args.findIndex(arg => arg === '--resume' || arg === '-r' || arg === '--session-id');
23
+ if (i >= 0 && args[i + 1] && !args[i + 1].startsWith('-')) return args[i + 1];
24
+ const inline = args.find(arg => /^--(resume|session-id)=/.test(arg));
25
+ return inline ? inline.split('=')[1] : null;
26
+ }
27
+
28
+ // First leg: real Claude Code. A fresh session gets a known id so the transcript can be watched.
29
+ function planSubscriptionLeg(args) {
30
+ const sessionId = findResumeId(args);
31
+ const continuing = args.includes('--continue') || args.includes('-c');
32
+ if (sessionId || continuing) return { sessionId, fromStart: false, args };
33
+ const fresh = randomUUID();
34
+ return { sessionId: fresh, fromStart: true, args: [...args, '--session-id', fresh] };
35
+ }
36
+
37
+ // Second leg: the same session resumed through labs. The prompt/-p arguments stay, so `-p "task"` re-asks the task.
38
+ function planLabsLegArgs(args, sessionId) {
39
+ return [...stripSessionAndModelArgs(args), '--resume', sessionId, '--model', 'opus'];
40
+ }
41
+
42
+ function transcriptPath(sessionId) {
43
+ if (!fs.existsSync(PROJECTS_DIR)) return null;
44
+ for (const dir of fs.readdirSync(PROJECTS_DIR)) {
45
+ const file = path.join(PROJECTS_DIR, dir, `${sessionId}.jsonl`);
46
+ if (fs.existsSync(file)) return file;
47
+ }
48
+ return null;
49
+ }
50
+
51
+ function newestTranscriptSince(startedAt) {
52
+ if (!fs.existsSync(PROJECTS_DIR)) return null;
53
+ let best = null;
54
+ for (const dir of fs.readdirSync(PROJECTS_DIR)) {
55
+ const full = path.join(PROJECTS_DIR, dir);
56
+ if (!fs.statSync(full).isDirectory()) continue;
57
+ for (const name of fs.readdirSync(full).filter(n => n.endsWith('.jsonl'))) {
58
+ const file = path.join(full, name);
59
+ const mtime = fs.statSync(file).mtimeMs;
60
+ if (mtime >= startedAt && (!best || mtime > best.mtime)) best = { file, mtime };
61
+ }
62
+ }
63
+ return best?.file || null;
64
+ }
65
+
66
+ // Reads only bytes appended after the leg started, so an old limit message in a resumed session never triggers.
67
+ function createWatcher({ sessionId, startedAt, forceFallback, fromStart, onFailure, intervalMs = 1000 }) {
68
+ let file = sessionId ? transcriptPath(sessionId) : null;
69
+ let offset = fromStart ? 0 : (file ? fs.statSync(file).size : null);
70
+ let sawReply = false;
71
+ const poll = () => {
72
+ file = file || (sessionId ? transcriptPath(sessionId) : newestTranscriptSince(startedAt));
73
+ if (!file) return null;
74
+ const size = fs.statSync(file).size;
75
+ if (offset === null) offset = size;
76
+ if (size <= offset) return null;
77
+ const fd = fs.openSync(file, 'r');
78
+ const buffer = Buffer.alloc(size - offset);
79
+ fs.readSync(fd, buffer, 0, buffer.length, offset);
80
+ fs.closeSync(fd);
81
+ const text = buffer.toString('utf8');
82
+ const lastNewline = text.lastIndexOf('\n');
83
+ if (lastNewline < 0) return null;
84
+ offset += Buffer.byteLength(text.slice(0, lastNewline + 1));
85
+ const chunk = text.slice(0, lastNewline + 1);
86
+ const found = detectInText(chunk);
87
+ if (found) return found;
88
+ if (forceFallback && /"type":"assistant"/.test(chunk)) sawReply = true;
89
+ return forceFallback && sawReply ? { kind: 'forced', text: 'LABS_AUTO_FORCE_FALLBACK', sessionId } : null;
90
+ };
91
+ const timer = setInterval(() => { const found = poll(); if (found) { clearInterval(timer); onFailure(found); } }, intervalMs);
92
+ return { stop: () => clearInterval(timer), pollNow: poll };
93
+ }
94
+
95
+ module.exports = { stripSessionAndModelArgs, findResumeId, planSubscriptionLeg, planLabsLegArgs, createWatcher, transcriptPath, newestTranscriptSince };
package/src/autostart.js CHANGED
@@ -1,43 +1,43 @@
1
- const { spawnSync } = require('child_process');
2
- const path = require('path');
3
-
4
- const TASK_NAME = 'labs proxy';
5
- const LABS_BIN = path.join(__dirname, '..', 'bin', 'labs.js');
6
-
7
- const quote = text => `'${String(text).replace(/'/g, "''")}'`;
8
-
9
- // A logon trigger alone misses a proxy that crashes later, so the task also runs every 2 minutes; `labs serve` exits at
10
- // once when the proxy is healthy. Task Scheduler's defaults skip tasks on battery, which would leave a laptop without the
11
- // proxy, so both battery settings are switched off. conhost --headless keeps a console window from flashing.
12
- function registerScript() {
13
- return [
14
- `$action = New-ScheduledTaskAction -Execute 'conhost.exe' -Argument ${quote(`--headless "${process.execPath}" "${LABS_BIN}" serve`)}`,
15
- '$logon = New-ScheduledTaskTrigger -AtLogOn -User $env:USERNAME',
16
- '$every = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 2)',
17
- '$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable '
18
- + '-MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Minutes 1)',
19
- `Register-ScheduledTask -TaskName ${quote(TASK_NAME)} -Action $action -Trigger $logon,$every -Settings $settings `
20
- + "-Description 'Keeps the labs proxy (Claude Code + chat page on 127.0.0.1:8081) running.' -Force | Out-Null"
21
- ].join('; ');
22
- }
23
-
24
- function runPowerShell(script) {
25
- return spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { encoding: 'utf8', windowsHide: true });
26
- }
27
-
28
- function setAutostart(on) {
29
- if (process.platform !== 'win32') return { ok: false, message: 'labs autostart is Windows only for now.' };
30
- const script = on
31
- ? registerScript()
32
- : `Unregister-ScheduledTask -TaskName ${quote(TASK_NAME)} -Confirm:$false -ErrorAction SilentlyContinue`;
33
- const result = runPowerShell(script);
34
- if (result.status !== 0) return { ok: false, message: (result.stderr || result.stdout || 'PowerShell failed').trim() };
35
- return {
36
- ok: true,
37
- message: on
38
- ? `✅ Task "${TASK_NAME}" checks the proxy at login and every 2 minutes. Undo: labs autostart off`
39
- : `🛑 Task "${TASK_NAME}" removed. The proxy now starts only with labs or labs chat.`
40
- };
41
- }
42
-
43
- module.exports = { setAutostart, registerScript, TASK_NAME };
1
+ const { spawnSync } = require('child_process');
2
+ const path = require('path');
3
+
4
+ const TASK_NAME = 'labs proxy';
5
+ const LABS_BIN = path.join(__dirname, '..', 'bin', 'labs.js');
6
+
7
+ const quote = text => `'${String(text).replace(/'/g, "''")}'`;
8
+
9
+ // A logon trigger alone misses a proxy that crashes later, so the task also runs every 2 minutes; `labs serve` exits at
10
+ // once when the proxy is healthy. Task Scheduler's defaults skip tasks on battery, which would leave a laptop without the
11
+ // proxy, so both battery settings are switched off. conhost --headless keeps a console window from flashing.
12
+ function registerScript() {
13
+ return [
14
+ `$action = New-ScheduledTaskAction -Execute 'conhost.exe' -Argument ${quote(`--headless "${process.execPath}" "${LABS_BIN}" serve`)}`,
15
+ '$logon = New-ScheduledTaskTrigger -AtLogOn -User $env:USERNAME',
16
+ '$every = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 2)',
17
+ '$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable '
18
+ + '-MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Minutes 1)',
19
+ `Register-ScheduledTask -TaskName ${quote(TASK_NAME)} -Action $action -Trigger $logon,$every -Settings $settings `
20
+ + "-Description 'Keeps the labs proxy (Claude Code + chat page on 127.0.0.1:8081) running.' -Force | Out-Null"
21
+ ].join('; ');
22
+ }
23
+
24
+ function runPowerShell(script) {
25
+ return spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { encoding: 'utf8', windowsHide: true });
26
+ }
27
+
28
+ function setAutostart(on) {
29
+ if (process.platform !== 'win32') return { ok: false, message: 'labs autostart is Windows only for now.' };
30
+ const script = on
31
+ ? registerScript()
32
+ : `Unregister-ScheduledTask -TaskName ${quote(TASK_NAME)} -Confirm:$false -ErrorAction SilentlyContinue`;
33
+ const result = runPowerShell(script);
34
+ if (result.status !== 0) return { ok: false, message: (result.stderr || result.stdout || 'PowerShell failed').trim() };
35
+ return {
36
+ ok: true,
37
+ message: on
38
+ ? `✅ Task "${TASK_NAME}" checks the proxy at login and every 2 minutes. Undo: labs autostart off`
39
+ : `🛑 Task "${TASK_NAME}" removed. The proxy now starts only with labs or labs chat.`
40
+ };
41
+ }
42
+
43
+ module.exports = { setAutostart, registerScript, TASK_NAME };