claude-connect 0.1.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.
@@ -0,0 +1,362 @@
1
+ import crypto from 'node:crypto';
2
+
3
+ function isObject(value) {
4
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
5
+ }
6
+
7
+ function collectText(value) {
8
+ if (typeof value === 'string') {
9
+ return value;
10
+ }
11
+
12
+ if (Array.isArray(value)) {
13
+ return value
14
+ .map((item) => {
15
+ if (typeof item === 'string') {
16
+ return item;
17
+ }
18
+
19
+ if (isObject(item) && item.type === 'text' && typeof item.text === 'string') {
20
+ return item.text;
21
+ }
22
+
23
+ return JSON.stringify(item);
24
+ })
25
+ .join('\n');
26
+ }
27
+
28
+ if (isObject(value) && value.type === 'text' && typeof value.text === 'string') {
29
+ return value.text;
30
+ }
31
+
32
+ if (value == null) {
33
+ return '';
34
+ }
35
+
36
+ return JSON.stringify(value);
37
+ }
38
+
39
+ function normalizeBlocks(content) {
40
+ if (Array.isArray(content)) {
41
+ return content;
42
+ }
43
+
44
+ if (typeof content === 'string') {
45
+ return [{ type: 'text', text: content }];
46
+ }
47
+
48
+ if (content == null) {
49
+ return [];
50
+ }
51
+
52
+ return [content];
53
+ }
54
+
55
+ function safeParseJson(value) {
56
+ if (typeof value !== 'string' || value.length === 0) {
57
+ return {};
58
+ }
59
+
60
+ try {
61
+ return JSON.parse(value);
62
+ } catch (_error) {
63
+ return {
64
+ raw: value
65
+ };
66
+ }
67
+ }
68
+
69
+ function mapStopReason(finishReason) {
70
+ switch (finishReason) {
71
+ case 'tool_calls':
72
+ return 'tool_use';
73
+ case 'length':
74
+ return 'max_tokens';
75
+ case 'stop':
76
+ case 'function_call':
77
+ return 'end_turn';
78
+ default:
79
+ return null;
80
+ }
81
+ }
82
+
83
+ export function estimateTokenCountFromAnthropicRequest(body) {
84
+ const systemText = collectText(body.system);
85
+ const messagesText = Array.isArray(body.messages)
86
+ ? body.messages
87
+ .map((message) => collectText(message?.content))
88
+ .join('\n')
89
+ : '';
90
+ const toolsText = Array.isArray(body.tools) ? JSON.stringify(body.tools) : '';
91
+ const totalLength = `${systemText}\n${messagesText}\n${toolsText}`.trim().length;
92
+
93
+ return Math.max(1, Math.ceil(totalLength / 4));
94
+ }
95
+
96
+ export function buildOpenAIRequestFromAnthropic({ body, model }) {
97
+ const messages = [];
98
+ const systemText = collectText(body.system).trim();
99
+
100
+ if (systemText.length > 0) {
101
+ messages.push({
102
+ role: 'system',
103
+ content: systemText
104
+ });
105
+ }
106
+
107
+ for (const message of Array.isArray(body.messages) ? body.messages : []) {
108
+ const blocks = normalizeBlocks(message?.content);
109
+
110
+ if (message?.role === 'user') {
111
+ let textParts = [];
112
+
113
+ for (const block of blocks) {
114
+ if (block?.type === 'tool_result') {
115
+ if (textParts.length > 0) {
116
+ messages.push({
117
+ role: 'user',
118
+ content: textParts.join('\n\n')
119
+ });
120
+ textParts = [];
121
+ }
122
+
123
+ messages.push({
124
+ role: 'tool',
125
+ tool_call_id: block.tool_use_id,
126
+ content: collectText(block.content)
127
+ });
128
+ continue;
129
+ }
130
+
131
+ textParts.push(collectText(block?.text ?? block));
132
+ }
133
+
134
+ if (textParts.length > 0) {
135
+ messages.push({
136
+ role: 'user',
137
+ content: textParts.join('\n\n')
138
+ });
139
+ }
140
+
141
+ continue;
142
+ }
143
+
144
+ if (message?.role === 'assistant') {
145
+ const textParts = [];
146
+ const toolCalls = [];
147
+
148
+ for (const block of blocks) {
149
+ if (block?.type === 'tool_use') {
150
+ toolCalls.push({
151
+ id: typeof block.id === 'string' && block.id.length > 0
152
+ ? block.id
153
+ : `call_${crypto.randomUUID().replace(/-/g, '')}`,
154
+ type: 'function',
155
+ function: {
156
+ name: block.name,
157
+ arguments: JSON.stringify(block.input ?? {})
158
+ }
159
+ });
160
+ continue;
161
+ }
162
+
163
+ textParts.push(collectText(block?.text ?? block));
164
+ }
165
+
166
+ messages.push({
167
+ role: 'assistant',
168
+ content: textParts.join('\n\n'),
169
+ ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {})
170
+ });
171
+ }
172
+ }
173
+
174
+ const request = {
175
+ model,
176
+ messages,
177
+ stream: false
178
+ };
179
+
180
+ if (typeof body.max_tokens === 'number') {
181
+ request.max_tokens = body.max_tokens;
182
+ }
183
+
184
+ if (typeof body.temperature === 'number') {
185
+ request.temperature = body.temperature;
186
+ }
187
+
188
+ if (Array.isArray(body.stop_sequences) && body.stop_sequences.length > 0) {
189
+ request.stop = body.stop_sequences;
190
+ }
191
+
192
+ if (Array.isArray(body.tools) && body.tools.length > 0) {
193
+ request.tools = body.tools.map((tool) => ({
194
+ type: 'function',
195
+ function: {
196
+ name: tool.name,
197
+ description: tool.description ?? '',
198
+ parameters: tool.input_schema ?? {
199
+ type: 'object',
200
+ properties: {}
201
+ }
202
+ }
203
+ }));
204
+ }
205
+
206
+ if (isObject(body.tool_choice) && typeof body.tool_choice.type === 'string') {
207
+ if (body.tool_choice.type === 'auto') {
208
+ request.tool_choice = 'auto';
209
+ } else if (body.tool_choice.type === 'any') {
210
+ request.tool_choice = 'required';
211
+ } else if (body.tool_choice.type === 'tool' && typeof body.tool_choice.name === 'string') {
212
+ request.tool_choice = {
213
+ type: 'function',
214
+ function: {
215
+ name: body.tool_choice.name
216
+ }
217
+ };
218
+ } else if (body.tool_choice.type === 'none') {
219
+ request.tool_choice = 'none';
220
+ }
221
+ }
222
+
223
+ return request;
224
+ }
225
+
226
+ export function buildAnthropicMessageFromOpenAI({ response, requestedModel }) {
227
+ const choice = response?.choices?.[0] ?? {};
228
+ const assistantMessage = choice?.message ?? {};
229
+ const content = [];
230
+ const text = typeof assistantMessage.content === 'string'
231
+ ? assistantMessage.content
232
+ : Array.isArray(assistantMessage.content)
233
+ ? assistantMessage.content
234
+ .map((item) => collectText(item))
235
+ .join('\n')
236
+ : '';
237
+
238
+ if (text.length > 0) {
239
+ content.push({
240
+ type: 'text',
241
+ text
242
+ });
243
+ }
244
+
245
+ for (const toolCall of Array.isArray(assistantMessage.tool_calls) ? assistantMessage.tool_calls : []) {
246
+ content.push({
247
+ type: 'tool_use',
248
+ id: toolCall.id || `toolu_${crypto.randomUUID().replace(/-/g, '')}`,
249
+ name: toolCall.function?.name || 'tool',
250
+ input: safeParseJson(toolCall.function?.arguments)
251
+ });
252
+ }
253
+
254
+ return {
255
+ id: typeof response?.id === 'string'
256
+ ? response.id
257
+ : `msg_${crypto.randomUUID().replace(/-/g, '')}`,
258
+ type: 'message',
259
+ role: 'assistant',
260
+ model: requestedModel || response?.model || 'unknown',
261
+ content,
262
+ stop_reason: mapStopReason(choice?.finish_reason),
263
+ stop_sequence: null,
264
+ usage: {
265
+ input_tokens: Number(response?.usage?.prompt_tokens ?? 0),
266
+ output_tokens: Number(response?.usage?.completion_tokens ?? 0)
267
+ }
268
+ };
269
+ }
270
+
271
+ function writeSseEvent(response, event, payload) {
272
+ response.write(`event: ${event}\n`);
273
+ response.write(`data: ${JSON.stringify(payload)}\n\n`);
274
+ }
275
+
276
+ export function writeAnthropicStreamFromMessage(response, message) {
277
+ writeSseEvent(response, 'message_start', {
278
+ type: 'message_start',
279
+ message: {
280
+ ...message,
281
+ content: [],
282
+ stop_reason: null,
283
+ stop_sequence: null,
284
+ usage: {
285
+ input_tokens: message.usage.input_tokens,
286
+ output_tokens: 0
287
+ }
288
+ }
289
+ });
290
+
291
+ message.content.forEach((block, index) => {
292
+ if (block.type === 'text') {
293
+ writeSseEvent(response, 'content_block_start', {
294
+ type: 'content_block_start',
295
+ index,
296
+ content_block: {
297
+ type: 'text',
298
+ text: ''
299
+ }
300
+ });
301
+
302
+ if (typeof block.text === 'string' && block.text.length > 0) {
303
+ writeSseEvent(response, 'content_block_delta', {
304
+ type: 'content_block_delta',
305
+ index,
306
+ delta: {
307
+ type: 'text_delta',
308
+ text: block.text
309
+ }
310
+ });
311
+ }
312
+
313
+ writeSseEvent(response, 'content_block_stop', {
314
+ type: 'content_block_stop',
315
+ index
316
+ });
317
+ return;
318
+ }
319
+
320
+ if (block.type === 'tool_use') {
321
+ writeSseEvent(response, 'content_block_start', {
322
+ type: 'content_block_start',
323
+ index,
324
+ content_block: {
325
+ type: 'tool_use',
326
+ id: block.id,
327
+ name: block.name,
328
+ input: {}
329
+ }
330
+ });
331
+
332
+ writeSseEvent(response, 'content_block_delta', {
333
+ type: 'content_block_delta',
334
+ index,
335
+ delta: {
336
+ type: 'input_json_delta',
337
+ partial_json: JSON.stringify(block.input ?? {})
338
+ }
339
+ });
340
+
341
+ writeSseEvent(response, 'content_block_stop', {
342
+ type: 'content_block_stop',
343
+ index
344
+ });
345
+ }
346
+ });
347
+
348
+ writeSseEvent(response, 'message_delta', {
349
+ type: 'message_delta',
350
+ delta: {
351
+ stop_reason: message.stop_reason,
352
+ stop_sequence: message.stop_sequence
353
+ },
354
+ usage: {
355
+ output_tokens: message.usage.output_tokens
356
+ }
357
+ });
358
+
359
+ writeSseEvent(response, 'message_stop', {
360
+ type: 'message_stop'
361
+ });
362
+ }