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.
- package/README.md +141 -122
- package/bin/labs.js +245 -178
- package/package.json +34 -34
- package/src/auto-fallback.js +95 -0
- package/src/autostart.js +43 -43
- package/src/bedrock.js +162 -162
- package/src/browser-setup.js +38 -38
- package/src/chat/index.html +534 -534
- package/src/chat-routes.js +149 -149
- package/src/config.js +71 -63
- package/src/gateway-client.js +124 -0
- package/src/local-auth.js +33 -33
- package/src/proxy-manager.js +85 -82
- package/src/proxy.js +801 -801
- package/src/read-shunt.js +26 -26
- package/src/setup.js +1 -1
- package/src/subscription-failure.js +36 -0
- package/src/usage.js +44 -44
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 };
|
package/src/bedrock.js
CHANGED
|
@@ -1,162 +1,162 @@
|
|
|
1
|
-
const { createHash } = require('crypto');
|
|
2
|
-
const fs = require('fs');
|
|
3
|
-
const path = require('path');
|
|
4
|
-
const { BedrockRuntimeClient, ConverseStreamCommand } = require('@aws-sdk/client-bedrock-runtime');
|
|
5
|
-
|
|
6
|
-
// Aliases whose value starts with this prefix run on Amazon Bedrock instead of ElevenLabs.
|
|
7
|
-
const BEDROCK_PREFIX = 'bedrock:';
|
|
8
|
-
const MAX_OUTPUT_TOKENS = 128000;
|
|
9
|
-
const IMAGE_FORMATS = { 'image/png': 'png', 'image/jpeg': 'jpeg', 'image/jpg': 'jpeg', 'image/gif': 'gif', 'image/webp': 'webp' };
|
|
10
|
-
|
|
11
|
-
function bedrockModelId(llm) {
|
|
12
|
-
return typeof llm === 'string' && llm.startsWith(BEDROCK_PREFIX) ? llm.slice(BEDROCK_PREFIX.length) : null;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
// Bedrock tool names must match ^[a-zA-Z0-9_-]{1,64}$; long MCP names get a short, stable stand-in.
|
|
16
|
-
function bedrockToolName(name) {
|
|
17
|
-
if (/^[a-zA-Z0-9_-]{1,64}$/.test(name)) return name;
|
|
18
|
-
const hash = createHash('sha1').update(name).digest('hex').slice(0, 8);
|
|
19
|
-
return `${name.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 55)}_${hash}`;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
function imageBlock(source) {
|
|
23
|
-
const format = IMAGE_FORMATS[source?.media_type];
|
|
24
|
-
if (source?.type !== 'base64' || !format) return { text: '[image in an unsupported format was left out]' };
|
|
25
|
-
return { image: { format, source: { bytes: Buffer.from(source.data, 'base64') } } };
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
function textOf(content) {
|
|
29
|
-
if (typeof content === 'string') return content;
|
|
30
|
-
return (content || []).map(block => block.type === 'text' ? block.text : `[${block.type}]`).join('\n');
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
function toolResultContent(content) {
|
|
34
|
-
const blocks = typeof content === 'string' || content == null
|
|
35
|
-
? [{ text: String(content ?? '') }]
|
|
36
|
-
: content.map(block => block.type === 'image' ? imageBlock(block.source) : { text: block.text ?? textOf([block]) });
|
|
37
|
-
const kept = blocks.filter(block => block.image || block.text.trim());
|
|
38
|
-
return kept.length ? kept : [{ text: '(no output)' }];
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
// Claude Code's history can hold tool blocks on a request without tools (titles, compaction); Bedrock refuses tool
|
|
42
|
-
// blocks without a toolConfig, so there they become plain text.
|
|
43
|
-
function convertBlock(block, withTools) {
|
|
44
|
-
switch (block.type) {
|
|
45
|
-
case 'text':
|
|
46
|
-
return block.text.trim() ? { text: block.text } : null;
|
|
47
|
-
case 'image':
|
|
48
|
-
return imageBlock(block.source);
|
|
49
|
-
case 'tool_use':
|
|
50
|
-
return withTools
|
|
51
|
-
? { toolUse: { toolUseId: block.id, name: bedrockToolName(block.name), input: block.input || {} } }
|
|
52
|
-
: { text: `[called tool ${block.name} with ${JSON.stringify(block.input || {})}]` };
|
|
53
|
-
case 'tool_result':
|
|
54
|
-
return withTools
|
|
55
|
-
? { toolResult: { toolUseId: block.tool_use_id, content: toolResultContent(block.content), status: block.is_error ? 'error' : 'success' } }
|
|
56
|
-
: { text: `[tool result]\n${textOf(block.content)}` };
|
|
57
|
-
case 'document':
|
|
58
|
-
return block.source?.type === 'text' ? { text: block.source.data } : { text: '[a document was left out]' };
|
|
59
|
-
default:
|
|
60
|
-
// thinking / redacted_thinking come from other models and carry signatures Bedrock cannot check.
|
|
61
|
-
return null;
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
function toConverse(body, modelId) {
|
|
66
|
-
const tools = (body.tools || []).filter(tool => tool.name && tool.input_schema);
|
|
67
|
-
const withTools = tools.length > 0;
|
|
68
|
-
const merged = [];
|
|
69
|
-
for (const message of body.messages || []) {
|
|
70
|
-
if (message.role !== 'user' && message.role !== 'assistant') continue;
|
|
71
|
-
const blocks = typeof message.content === 'string' ? [{ type: 'text', text: message.content }] : message.content || [];
|
|
72
|
-
const content = blocks.map(block => convertBlock(block, withTools)).filter(Boolean);
|
|
73
|
-
if (!content.length) continue;
|
|
74
|
-
const last = merged.at(-1);
|
|
75
|
-
// Bedrock needs strictly alternating roles; Claude Code sometimes sends two user turns in a row.
|
|
76
|
-
if (last?.role === message.role) last.content.push(...content);
|
|
77
|
-
else merged.push({ role: message.role, content });
|
|
78
|
-
}
|
|
79
|
-
if (merged[0]?.role === 'assistant') merged.unshift({ role: 'user', content: [{ text: '(continue)' }] });
|
|
80
|
-
|
|
81
|
-
const systemText = typeof body.system === 'string' ? body.system : textOf(body.system);
|
|
82
|
-
const request = {
|
|
83
|
-
modelId,
|
|
84
|
-
messages: merged,
|
|
85
|
-
inferenceConfig: { maxTokens: Math.min(body.max_tokens || 32000, MAX_OUTPUT_TOKENS) }
|
|
86
|
-
};
|
|
87
|
-
if (systemText.trim()) request.system = [{ text: systemText }];
|
|
88
|
-
if (typeof body.temperature === 'number') request.inferenceConfig.temperature = body.temperature;
|
|
89
|
-
if (withTools) {
|
|
90
|
-
request.toolConfig = {
|
|
91
|
-
tools: tools.map(tool => {
|
|
92
|
-
const { $schema, ...schema } = tool.input_schema;
|
|
93
|
-
return { toolSpec: { name: bedrockToolName(tool.name), description: tool.description || tool.name, inputSchema: { json: schema } } };
|
|
94
|
-
})
|
|
95
|
-
};
|
|
96
|
-
}
|
|
97
|
-
const toolNames = new Map(tools.map(tool => [bedrockToolName(tool.name), tool.name]));
|
|
98
|
-
return { request, toolNames };
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
function readBedrockKey(labsDir) {
|
|
102
|
-
const file = path.join(labsDir, 'bedrock-key');
|
|
103
|
-
return fs.existsSync(file) ? fs.readFileSync(file, 'utf8').trim() : process.env.AWS_BEARER_TOKEN_BEDROCK || null;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
function saveBedrockKey(labsDir, key) {
|
|
107
|
-
fs.mkdirSync(labsDir, { recursive: true });
|
|
108
|
-
fs.writeFileSync(path.join(labsDir, 'bedrock-key'), key.trim(), { mode: 0o600 });
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
function createBedrockClient({ region, apiKey, requestHandler }) {
|
|
112
|
-
return new BedrockRuntimeClient({
|
|
113
|
-
region,
|
|
114
|
-
token: async () => ({ token: apiKey }),
|
|
115
|
-
authSchemePreference: ['httpBearerAuth'],
|
|
116
|
-
...(requestHandler ? { requestHandler } : {})
|
|
117
|
-
});
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
async function streamConverse({ client, body, modelId, onText, signal }) {
|
|
121
|
-
const { request, toolNames } = toConverse(body, modelId);
|
|
122
|
-
const response = await client.send(new ConverseStreamCommand(request), { abortSignal: signal });
|
|
123
|
-
let text = '';
|
|
124
|
-
let stopReason = null;
|
|
125
|
-
const usage = { inputTokens: 0, outputTokens: 0 };
|
|
126
|
-
const tools = new Map();
|
|
127
|
-
for await (const event of response.stream) {
|
|
128
|
-
if (event.contentBlockStart?.start?.toolUse) {
|
|
129
|
-
const { toolUseId, name } = event.contentBlockStart.start.toolUse;
|
|
130
|
-
tools.set(event.contentBlockStart.contentBlockIndex, { id: toolUseId, name: toolNames.get(name) || name, json: '' });
|
|
131
|
-
} else if (event.contentBlockDelta) {
|
|
132
|
-
const { delta, contentBlockIndex } = event.contentBlockDelta;
|
|
133
|
-
if (delta.text) {
|
|
134
|
-
text += delta.text;
|
|
135
|
-
if (onText) onText(delta.text);
|
|
136
|
-
} else if (delta.toolUse) {
|
|
137
|
-
tools.get(contentBlockIndex).json += delta.toolUse.input || '';
|
|
138
|
-
}
|
|
139
|
-
} else if (event.messageStop) {
|
|
140
|
-
stopReason = event.messageStop.stopReason;
|
|
141
|
-
} else if (event.metadata?.usage) {
|
|
142
|
-
usage.inputTokens = event.metadata.usage.inputTokens || 0;
|
|
143
|
-
usage.outputTokens = event.metadata.usage.outputTokens || 0;
|
|
144
|
-
} else {
|
|
145
|
-
const failure = Object.entries(event).find(([key]) => key.endsWith('Exception'));
|
|
146
|
-
if (failure) throw new Error(`${failure[0]}: ${failure[1]?.message || 'stream failed'}`);
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
const toolCalls = [...tools.values()].map(tool => ({ id: tool.id, name: tool.name, input: tool.json ? JSON.parse(tool.json) : {} }));
|
|
150
|
-
return { text, toolCalls, usage, stopReason };
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
module.exports = {
|
|
154
|
-
BEDROCK_PREFIX,
|
|
155
|
-
bedrockModelId,
|
|
156
|
-
bedrockToolName,
|
|
157
|
-
createBedrockClient,
|
|
158
|
-
readBedrockKey,
|
|
159
|
-
saveBedrockKey,
|
|
160
|
-
streamConverse,
|
|
161
|
-
toConverse
|
|
162
|
-
};
|
|
1
|
+
const { createHash } = require('crypto');
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
const { BedrockRuntimeClient, ConverseStreamCommand } = require('@aws-sdk/client-bedrock-runtime');
|
|
5
|
+
|
|
6
|
+
// Aliases whose value starts with this prefix run on Amazon Bedrock instead of ElevenLabs.
|
|
7
|
+
const BEDROCK_PREFIX = 'bedrock:';
|
|
8
|
+
const MAX_OUTPUT_TOKENS = 128000;
|
|
9
|
+
const IMAGE_FORMATS = { 'image/png': 'png', 'image/jpeg': 'jpeg', 'image/jpg': 'jpeg', 'image/gif': 'gif', 'image/webp': 'webp' };
|
|
10
|
+
|
|
11
|
+
function bedrockModelId(llm) {
|
|
12
|
+
return typeof llm === 'string' && llm.startsWith(BEDROCK_PREFIX) ? llm.slice(BEDROCK_PREFIX.length) : null;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Bedrock tool names must match ^[a-zA-Z0-9_-]{1,64}$; long MCP names get a short, stable stand-in.
|
|
16
|
+
function bedrockToolName(name) {
|
|
17
|
+
if (/^[a-zA-Z0-9_-]{1,64}$/.test(name)) return name;
|
|
18
|
+
const hash = createHash('sha1').update(name).digest('hex').slice(0, 8);
|
|
19
|
+
return `${name.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 55)}_${hash}`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function imageBlock(source) {
|
|
23
|
+
const format = IMAGE_FORMATS[source?.media_type];
|
|
24
|
+
if (source?.type !== 'base64' || !format) return { text: '[image in an unsupported format was left out]' };
|
|
25
|
+
return { image: { format, source: { bytes: Buffer.from(source.data, 'base64') } } };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function textOf(content) {
|
|
29
|
+
if (typeof content === 'string') return content;
|
|
30
|
+
return (content || []).map(block => block.type === 'text' ? block.text : `[${block.type}]`).join('\n');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function toolResultContent(content) {
|
|
34
|
+
const blocks = typeof content === 'string' || content == null
|
|
35
|
+
? [{ text: String(content ?? '') }]
|
|
36
|
+
: content.map(block => block.type === 'image' ? imageBlock(block.source) : { text: block.text ?? textOf([block]) });
|
|
37
|
+
const kept = blocks.filter(block => block.image || block.text.trim());
|
|
38
|
+
return kept.length ? kept : [{ text: '(no output)' }];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Claude Code's history can hold tool blocks on a request without tools (titles, compaction); Bedrock refuses tool
|
|
42
|
+
// blocks without a toolConfig, so there they become plain text.
|
|
43
|
+
function convertBlock(block, withTools) {
|
|
44
|
+
switch (block.type) {
|
|
45
|
+
case 'text':
|
|
46
|
+
return block.text.trim() ? { text: block.text } : null;
|
|
47
|
+
case 'image':
|
|
48
|
+
return imageBlock(block.source);
|
|
49
|
+
case 'tool_use':
|
|
50
|
+
return withTools
|
|
51
|
+
? { toolUse: { toolUseId: block.id, name: bedrockToolName(block.name), input: block.input || {} } }
|
|
52
|
+
: { text: `[called tool ${block.name} with ${JSON.stringify(block.input || {})}]` };
|
|
53
|
+
case 'tool_result':
|
|
54
|
+
return withTools
|
|
55
|
+
? { toolResult: { toolUseId: block.tool_use_id, content: toolResultContent(block.content), status: block.is_error ? 'error' : 'success' } }
|
|
56
|
+
: { text: `[tool result]\n${textOf(block.content)}` };
|
|
57
|
+
case 'document':
|
|
58
|
+
return block.source?.type === 'text' ? { text: block.source.data } : { text: '[a document was left out]' };
|
|
59
|
+
default:
|
|
60
|
+
// thinking / redacted_thinking come from other models and carry signatures Bedrock cannot check.
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function toConverse(body, modelId) {
|
|
66
|
+
const tools = (body.tools || []).filter(tool => tool.name && tool.input_schema);
|
|
67
|
+
const withTools = tools.length > 0;
|
|
68
|
+
const merged = [];
|
|
69
|
+
for (const message of body.messages || []) {
|
|
70
|
+
if (message.role !== 'user' && message.role !== 'assistant') continue;
|
|
71
|
+
const blocks = typeof message.content === 'string' ? [{ type: 'text', text: message.content }] : message.content || [];
|
|
72
|
+
const content = blocks.map(block => convertBlock(block, withTools)).filter(Boolean);
|
|
73
|
+
if (!content.length) continue;
|
|
74
|
+
const last = merged.at(-1);
|
|
75
|
+
// Bedrock needs strictly alternating roles; Claude Code sometimes sends two user turns in a row.
|
|
76
|
+
if (last?.role === message.role) last.content.push(...content);
|
|
77
|
+
else merged.push({ role: message.role, content });
|
|
78
|
+
}
|
|
79
|
+
if (merged[0]?.role === 'assistant') merged.unshift({ role: 'user', content: [{ text: '(continue)' }] });
|
|
80
|
+
|
|
81
|
+
const systemText = typeof body.system === 'string' ? body.system : textOf(body.system);
|
|
82
|
+
const request = {
|
|
83
|
+
modelId,
|
|
84
|
+
messages: merged,
|
|
85
|
+
inferenceConfig: { maxTokens: Math.min(body.max_tokens || 32000, MAX_OUTPUT_TOKENS) }
|
|
86
|
+
};
|
|
87
|
+
if (systemText.trim()) request.system = [{ text: systemText }];
|
|
88
|
+
if (typeof body.temperature === 'number') request.inferenceConfig.temperature = body.temperature;
|
|
89
|
+
if (withTools) {
|
|
90
|
+
request.toolConfig = {
|
|
91
|
+
tools: tools.map(tool => {
|
|
92
|
+
const { $schema, ...schema } = tool.input_schema;
|
|
93
|
+
return { toolSpec: { name: bedrockToolName(tool.name), description: tool.description || tool.name, inputSchema: { json: schema } } };
|
|
94
|
+
})
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
const toolNames = new Map(tools.map(tool => [bedrockToolName(tool.name), tool.name]));
|
|
98
|
+
return { request, toolNames };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function readBedrockKey(labsDir) {
|
|
102
|
+
const file = path.join(labsDir, 'bedrock-key');
|
|
103
|
+
return fs.existsSync(file) ? fs.readFileSync(file, 'utf8').trim() : process.env.AWS_BEARER_TOKEN_BEDROCK || null;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function saveBedrockKey(labsDir, key) {
|
|
107
|
+
fs.mkdirSync(labsDir, { recursive: true });
|
|
108
|
+
fs.writeFileSync(path.join(labsDir, 'bedrock-key'), key.trim(), { mode: 0o600 });
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function createBedrockClient({ region, apiKey, requestHandler }) {
|
|
112
|
+
return new BedrockRuntimeClient({
|
|
113
|
+
region,
|
|
114
|
+
token: async () => ({ token: apiKey }),
|
|
115
|
+
authSchemePreference: ['httpBearerAuth'],
|
|
116
|
+
...(requestHandler ? { requestHandler } : {})
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function streamConverse({ client, body, modelId, onText, signal }) {
|
|
121
|
+
const { request, toolNames } = toConverse(body, modelId);
|
|
122
|
+
const response = await client.send(new ConverseStreamCommand(request), { abortSignal: signal });
|
|
123
|
+
let text = '';
|
|
124
|
+
let stopReason = null;
|
|
125
|
+
const usage = { inputTokens: 0, outputTokens: 0 };
|
|
126
|
+
const tools = new Map();
|
|
127
|
+
for await (const event of response.stream) {
|
|
128
|
+
if (event.contentBlockStart?.start?.toolUse) {
|
|
129
|
+
const { toolUseId, name } = event.contentBlockStart.start.toolUse;
|
|
130
|
+
tools.set(event.contentBlockStart.contentBlockIndex, { id: toolUseId, name: toolNames.get(name) || name, json: '' });
|
|
131
|
+
} else if (event.contentBlockDelta) {
|
|
132
|
+
const { delta, contentBlockIndex } = event.contentBlockDelta;
|
|
133
|
+
if (delta.text) {
|
|
134
|
+
text += delta.text;
|
|
135
|
+
if (onText) onText(delta.text);
|
|
136
|
+
} else if (delta.toolUse) {
|
|
137
|
+
tools.get(contentBlockIndex).json += delta.toolUse.input || '';
|
|
138
|
+
}
|
|
139
|
+
} else if (event.messageStop) {
|
|
140
|
+
stopReason = event.messageStop.stopReason;
|
|
141
|
+
} else if (event.metadata?.usage) {
|
|
142
|
+
usage.inputTokens = event.metadata.usage.inputTokens || 0;
|
|
143
|
+
usage.outputTokens = event.metadata.usage.outputTokens || 0;
|
|
144
|
+
} else {
|
|
145
|
+
const failure = Object.entries(event).find(([key]) => key.endsWith('Exception'));
|
|
146
|
+
if (failure) throw new Error(`${failure[0]}: ${failure[1]?.message || 'stream failed'}`);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const toolCalls = [...tools.values()].map(tool => ({ id: tool.id, name: tool.name, input: tool.json ? JSON.parse(tool.json) : {} }));
|
|
150
|
+
return { text, toolCalls, usage, stopReason };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
module.exports = {
|
|
154
|
+
BEDROCK_PREFIX,
|
|
155
|
+
bedrockModelId,
|
|
156
|
+
bedrockToolName,
|
|
157
|
+
createBedrockClient,
|
|
158
|
+
readBedrockKey,
|
|
159
|
+
saveBedrockKey,
|
|
160
|
+
streamConverse,
|
|
161
|
+
toConverse
|
|
162
|
+
};
|
package/src/browser-setup.js
CHANGED
|
@@ -1,38 +1,38 @@
|
|
|
1
|
-
const { execFileSync } = require('child_process');
|
|
2
|
-
|
|
3
|
-
// Claude in Chrome needs a claude.ai login, which labs replaces with its proxy key, so labs drives the user's real
|
|
4
|
-
// Chrome through Microsoft's official Playwright Extension instead (verified 2026-10-08: publisher Microsoft,
|
|
5
|
-
// linked from github.com/microsoft/playwright packages/extension).
|
|
6
|
-
const EXTENSION_URL = 'https://chromewebstore.google.com/detail/playwright-extension/mmlmfjhmonkocbjadbfplnigmagldckm';
|
|
7
|
-
const SERVER_NAME = 'labs-browser';
|
|
8
|
-
|
|
9
|
-
function browserServerArgs(token, platform = process.platform) {
|
|
10
|
-
// On Windows npx is a .cmd file, which Claude Code can only start through cmd.
|
|
11
|
-
const command = platform === 'win32' ? ['cmd', '/c', 'npx'] : ['npx'];
|
|
12
|
-
return [
|
|
13
|
-
'mcp', 'add', SERVER_NAME, '--scope', 'user',
|
|
14
|
-
...(token ? ['-e', `PLAYWRIGHT_MCP_EXTENSION_TOKEN=${token}`] : []),
|
|
15
|
-
'--', ...command, '--yes', '@playwright/mcp@latest', '--extension'
|
|
16
|
-
];
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
function runClaude(args) {
|
|
20
|
-
const options = { stdio: 'ignore' };
|
|
21
|
-
try {
|
|
22
|
-
execFileSync(process.platform === 'win32' ? 'claude.exe' : 'claude', args, options);
|
|
23
|
-
} catch (error) {
|
|
24
|
-
if (process.platform !== 'win32' || error.code !== 'ENOENT') throw error;
|
|
25
|
-
execFileSync('claude', args, { ...options, shell: true });
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
function installBrowserServer(token) {
|
|
30
|
-
try {
|
|
31
|
-
runClaude(['mcp', 'remove', SERVER_NAME, '--scope', 'user']);
|
|
32
|
-
} catch {
|
|
33
|
-
// Not configured yet.
|
|
34
|
-
}
|
|
35
|
-
runClaude(browserServerArgs(token));
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
module.exports = { EXTENSION_URL, browserServerArgs, installBrowserServer };
|
|
1
|
+
const { execFileSync } = require('child_process');
|
|
2
|
+
|
|
3
|
+
// Claude in Chrome needs a claude.ai login, which labs replaces with its proxy key, so labs drives the user's real
|
|
4
|
+
// Chrome through Microsoft's official Playwright Extension instead (verified 2026-10-08: publisher Microsoft,
|
|
5
|
+
// linked from github.com/microsoft/playwright packages/extension).
|
|
6
|
+
const EXTENSION_URL = 'https://chromewebstore.google.com/detail/playwright-extension/mmlmfjhmonkocbjadbfplnigmagldckm';
|
|
7
|
+
const SERVER_NAME = 'labs-browser';
|
|
8
|
+
|
|
9
|
+
function browserServerArgs(token, platform = process.platform) {
|
|
10
|
+
// On Windows npx is a .cmd file, which Claude Code can only start through cmd.
|
|
11
|
+
const command = platform === 'win32' ? ['cmd', '/c', 'npx'] : ['npx'];
|
|
12
|
+
return [
|
|
13
|
+
'mcp', 'add', SERVER_NAME, '--scope', 'user',
|
|
14
|
+
...(token ? ['-e', `PLAYWRIGHT_MCP_EXTENSION_TOKEN=${token}`] : []),
|
|
15
|
+
'--', ...command, '--yes', '@playwright/mcp@latest', '--extension'
|
|
16
|
+
];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function runClaude(args) {
|
|
20
|
+
const options = { stdio: 'ignore' };
|
|
21
|
+
try {
|
|
22
|
+
execFileSync(process.platform === 'win32' ? 'claude.exe' : 'claude', args, options);
|
|
23
|
+
} catch (error) {
|
|
24
|
+
if (process.platform !== 'win32' || error.code !== 'ENOENT') throw error;
|
|
25
|
+
execFileSync('claude', args, { ...options, shell: true });
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function installBrowserServer(token) {
|
|
30
|
+
try {
|
|
31
|
+
runClaude(['mcp', 'remove', SERVER_NAME, '--scope', 'user']);
|
|
32
|
+
} catch {
|
|
33
|
+
// Not configured yet.
|
|
34
|
+
}
|
|
35
|
+
runClaude(browserServerArgs(token));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
module.exports = { EXTENSION_URL, browserServerArgs, installBrowserServer };
|