@simulacra-ai/anthropic 0.0.3 → 0.0.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/dist/index.d.ts CHANGED
@@ -1,2 +1,64 @@
1
- export { AnthropicProvider, type AnthropicProviderConfig } from "./anthropic-provider.ts";
2
- //# sourceMappingURL=index.d.ts.map
1
+ import Anthropic from '@anthropic-ai/sdk';
2
+ import { ModelProvider, ProviderContextTransformer, ModelRequest, StreamReceiver, CancellationToken } from '@simulacra-ai/core';
3
+
4
+ /**
5
+ * Configuration options for the Anthropic provider.
6
+ */
7
+ interface AnthropicProviderConfig extends Record<string, unknown> {
8
+ /** The model identifier to use. */
9
+ model: string;
10
+ /** The maximum number of tokens to generate in the response. */
11
+ max_tokens?: number;
12
+ /** Configuration for extended thinking mode. */
13
+ thinking?: {
14
+ /** Whether to enable extended thinking. */
15
+ enable: boolean;
16
+ /** The token budget allocated for thinking. */
17
+ budget_tokens?: number;
18
+ };
19
+ /** Configuration for prompt caching. Enabled by default when omitted. Cache writes cost more per token than standard requests, but cache reads on subsequent turns cost less. */
20
+ prompt_caching?: {
21
+ /** Whether to cache the system prompt. */
22
+ system_prompt?: boolean;
23
+ /** Whether to cache the tool definitions. */
24
+ toolkit?: boolean;
25
+ };
26
+ /** Use Claude Code's stored OAuth credentials for authentication. When true, the provider reads tokens from Claude Code's credentials file and refreshes them automatically. */
27
+ claude_code_auth?: boolean;
28
+ }
29
+ /**
30
+ * Model provider implementation for Anthropic's Claude models.
31
+ *
32
+ * This provider wraps the Anthropic SDK to provide streaming completions with support
33
+ * for tool use, extended thinking, and prompt caching. It handles message formatting,
34
+ * content streaming, and usage tracking according to the ModelProvider interface.
35
+ */
36
+ declare class AnthropicProvider implements ModelProvider {
37
+ #private;
38
+ readonly context_transformers: ProviderContextTransformer[];
39
+ /**
40
+ * Creates a new Anthropic provider instance.
41
+ *
42
+ * @param sdk - The initialized Anthropic SDK client.
43
+ * @param config - Configuration options for the provider.
44
+ * @param context_transformers - Provider-level context transformers.
45
+ */
46
+ constructor(sdk: Anthropic, config: AnthropicProviderConfig, context_transformers?: ProviderContextTransformer[]);
47
+ /**
48
+ * Executes a model request and streams the response through the provided receiver.
49
+ *
50
+ * @param request - The request containing messages, tools, and system prompt.
51
+ * @param receiver - The receiver that handles streaming events.
52
+ * @param cancellation - Token to signal cancellation of the request.
53
+ * @returns A promise that resolves when the request completes.
54
+ */
55
+ execute_request(request: ModelRequest, receiver: StreamReceiver, cancellation: CancellationToken): Promise<void>;
56
+ /**
57
+ * Creates a clone of this provider with the same configuration.
58
+ *
59
+ * @returns A new provider instance with identical configuration.
60
+ */
61
+ clone(): ModelProvider;
62
+ }
63
+
64
+ export { AnthropicProvider, type AnthropicProviderConfig };
package/dist/index.js CHANGED
@@ -1,2 +1,495 @@
1
- export { AnthropicProvider } from "./anthropic-provider.js";
1
+ // src/anthropic-provider.ts
2
+ import { readFileSync, writeFileSync, copyFileSync } from "fs";
3
+ import { homedir } from "os";
4
+ import { join } from "path";
5
+ var claude_oauth = null;
6
+ var claude_creds_path = null;
7
+ var claude_request_options_promise = null;
8
+ var AnthropicProvider = class _AnthropicProvider {
9
+ #sdk;
10
+ #config;
11
+ context_transformers;
12
+ /**
13
+ * Creates a new Anthropic provider instance.
14
+ *
15
+ * @param sdk - The initialized Anthropic SDK client.
16
+ * @param config - Configuration options for the provider.
17
+ * @param context_transformers - Provider-level context transformers.
18
+ */
19
+ constructor(sdk, config, context_transformers = []) {
20
+ this.#sdk = sdk;
21
+ this.#config = config;
22
+ this.context_transformers = context_transformers;
23
+ }
24
+ /**
25
+ * Executes a model request and streams the response through the provided receiver.
26
+ *
27
+ * @param request - The request containing messages, tools, and system prompt.
28
+ * @param receiver - The receiver that handles streaming events.
29
+ * @param cancellation - Token to signal cancellation of the request.
30
+ * @returns A promise that resolves when the request completes.
31
+ */
32
+ async execute_request(request, receiver, cancellation) {
33
+ const {
34
+ model,
35
+ max_tokens,
36
+ thinking,
37
+ prompt_caching,
38
+ claude_code_auth: _,
39
+ ...api_extras
40
+ } = this.#config;
41
+ const cache_system = prompt_caching?.system_prompt !== false;
42
+ const cache_tools = prompt_caching?.toolkit !== false;
43
+ const tools = request.tools.map((t) => to_anthropic_tool(t));
44
+ if (cache_tools && tools.length > 0) {
45
+ const last = tools.length - 1;
46
+ tools[last].cache_control = { type: "ephemeral" };
47
+ }
48
+ const system = cache_system && request.system ? [{ type: "text", text: request.system, cache_control: { type: "ephemeral" } }] : request.system;
49
+ const params = {
50
+ ...api_extras,
51
+ model,
52
+ stream: true,
53
+ system,
54
+ max_tokens: max_tokens ?? 8192,
55
+ thinking: thinking?.enable && thinking?.budget_tokens ? {
56
+ type: "enabled",
57
+ budget_tokens: thinking.budget_tokens
58
+ } : {
59
+ type: "disabled"
60
+ },
61
+ tools,
62
+ messages: request.messages.map((m) => to_anthropic_message(m))
63
+ };
64
+ receiver.before_request({ params });
65
+ receiver.request_raw(params);
66
+ const response = await this.#sdk.messages.create(
67
+ params,
68
+ this.#config.claude_code_auth ? await ensure_claude_request_options() : void 0
69
+ );
70
+ this.#stream_response(response, receiver, cancellation);
71
+ }
72
+ /**
73
+ * Creates a clone of this provider with the same configuration.
74
+ *
75
+ * @returns A new provider instance with identical configuration.
76
+ */
77
+ clone() {
78
+ return new _AnthropicProvider(this.#sdk, this.#config, this.context_transformers);
79
+ }
80
+ async #stream_response(stream, receiver, cancellation) {
81
+ try {
82
+ let usage = {};
83
+ let message = {
84
+ content: []
85
+ };
86
+ const json = [];
87
+ for await (const chunk of stream) {
88
+ if (cancellation.is_cancellation_requested) {
89
+ receiver.cancel();
90
+ return;
91
+ }
92
+ receiver.stream_raw(chunk);
93
+ switch (chunk.type) {
94
+ case "message_start": {
95
+ usage = Object.fromEntries(
96
+ Object.entries(chunk.message.usage).filter(([, v]) => typeof v === "number")
97
+ );
98
+ message = chunk.message;
99
+ receiver.start_message({
100
+ usage,
101
+ message: from_anthropic_message(message)
102
+ });
103
+ break;
104
+ }
105
+ case "message_delta": {
106
+ usage = {
107
+ ...usage,
108
+ ...Object.fromEntries(
109
+ Object.entries(chunk.usage).filter(([, v]) => typeof v === "number")
110
+ )
111
+ };
112
+ message = { ...message, ...chunk.delta };
113
+ receiver.update_message({
114
+ usage,
115
+ message: from_anthropic_message(message)
116
+ });
117
+ break;
118
+ }
119
+ case "message_stop": {
120
+ const raw_stop = message.stop_reason ?? "end_turn";
121
+ const stop_reason = ["tool_use", "stop_sequence", "end_turn", "max_tokens", "error"].includes(raw_stop) ? raw_stop : "other";
122
+ receiver.complete_message({
123
+ usage,
124
+ stop_reason,
125
+ message: from_anthropic_message(message)
126
+ });
127
+ break;
128
+ }
129
+ case "content_block_start": {
130
+ message.content[chunk.index] = chunk.content_block;
131
+ receiver.start_content({
132
+ usage,
133
+ message: from_anthropic_message(message),
134
+ content: from_anthropic_content(chunk.content_block)
135
+ });
136
+ receiver.update_message({
137
+ usage,
138
+ message: from_anthropic_message(message)
139
+ });
140
+ break;
141
+ }
142
+ case "content_block_delta": {
143
+ switch (chunk.delta.type) {
144
+ case "text_delta": {
145
+ const content = message.content[chunk.index];
146
+ content.text += chunk.delta.text;
147
+ break;
148
+ }
149
+ case "citations_delta": {
150
+ const content = message.content[chunk.index];
151
+ content.citations = [...content.citations ?? [], chunk.delta.citation];
152
+ break;
153
+ }
154
+ case "thinking_delta": {
155
+ const content = message.content[chunk.index];
156
+ content.thinking += chunk.delta.thinking;
157
+ break;
158
+ }
159
+ case "input_json_delta": {
160
+ if (!json[chunk.index]) {
161
+ json[chunk.index] = "";
162
+ }
163
+ json[chunk.index] += chunk.delta.partial_json;
164
+ break;
165
+ }
166
+ case "signature_delta": {
167
+ const content = message.content[chunk.index];
168
+ content.signature = (content.signature ?? "") + chunk.delta.signature;
169
+ break;
170
+ }
171
+ }
172
+ receiver.update_content({
173
+ usage,
174
+ message: from_anthropic_message(message),
175
+ content: from_anthropic_content(message.content[chunk.index])
176
+ });
177
+ break;
178
+ }
179
+ case "content_block_stop": {
180
+ const content_block = message.content[chunk.index];
181
+ if (content_block.type === "tool_use" && json[chunk.index]) {
182
+ content_block.input = {
183
+ ...content_block.input ?? {},
184
+ ...JSON.parse(json[chunk.index])
185
+ };
186
+ }
187
+ receiver.complete_content({
188
+ usage,
189
+ message: from_anthropic_message(message),
190
+ content: from_anthropic_content(content_block)
191
+ });
192
+ break;
193
+ }
194
+ }
195
+ }
196
+ receiver.response_raw(message);
197
+ } catch (error) {
198
+ receiver.error(error);
199
+ }
200
+ }
201
+ };
202
+ function parameter_to_json_schema(param) {
203
+ switch (param.type) {
204
+ case "object": {
205
+ const properties = {};
206
+ const required = [];
207
+ for (const [key, child] of Object.entries(param.properties)) {
208
+ properties[key] = parameter_to_json_schema(child);
209
+ if (child.required) {
210
+ required.push(key);
211
+ }
212
+ }
213
+ return {
214
+ type: "object",
215
+ ...param.description ? { description: param.description } : {},
216
+ ...Object.keys(properties).length ? { properties } : {},
217
+ ...required.length ? { required } : {}
218
+ };
219
+ }
220
+ case "array":
221
+ return {
222
+ type: "array",
223
+ ...param.description ? { description: param.description } : {},
224
+ items: parameter_to_json_schema(param.items)
225
+ };
226
+ case "number":
227
+ return {
228
+ type: "number",
229
+ ...param.description ? { description: param.description } : {}
230
+ };
231
+ case "boolean":
232
+ return {
233
+ type: "boolean",
234
+ ...param.description ? { description: param.description } : {}
235
+ };
236
+ case "string":
237
+ return "enum" in param && param.enum ? {
238
+ type: "string",
239
+ enum: param.enum,
240
+ ...param.description ? { description: param.description } : {}
241
+ } : { type: "string", ...param.description ? { description: param.description } : {} };
242
+ }
243
+ }
244
+ function to_anthropic_tool(tool) {
245
+ const properties = {};
246
+ const required = [];
247
+ for (const param of tool.parameters) {
248
+ const schema = parameter_to_json_schema(param);
249
+ if (param.description) {
250
+ schema.description = param.description;
251
+ }
252
+ properties[param.name] = schema;
253
+ if (param.required) {
254
+ required.push(param.name);
255
+ }
256
+ }
257
+ return {
258
+ name: tool.name,
259
+ description: tool.description,
260
+ input_schema: {
261
+ type: "object",
262
+ ...Object.keys(properties).length ? { properties } : {},
263
+ ...required.length ? { required } : {}
264
+ }
265
+ };
266
+ }
267
+ function from_anthropic_message(message) {
268
+ if (typeof message.content === "string") {
269
+ return {
270
+ role: message.role,
271
+ content: [
272
+ {
273
+ type: "text",
274
+ text: message.content
275
+ }
276
+ ]
277
+ };
278
+ }
279
+ return {
280
+ role: message.role,
281
+ content: (message.content ?? []).map(
282
+ (c) => from_anthropic_content(c, Array.isArray(message.content) ? message.content : void 0)
283
+ )
284
+ };
285
+ }
286
+ function from_anthropic_content(content, allContent) {
287
+ switch (content.type) {
288
+ case "text": {
289
+ const { type: _, text, ...extended } = content;
290
+ return {
291
+ type: "text",
292
+ text,
293
+ extended
294
+ };
295
+ }
296
+ case "tool_use": {
297
+ const { type: _, id, name, input, ...extended } = content;
298
+ return {
299
+ type: "tool",
300
+ tool_request_id: id,
301
+ tool: name,
302
+ params: input,
303
+ extended
304
+ };
305
+ }
306
+ case "tool_result": {
307
+ const { type: _, tool_use_id, content: tool_content, ...extended } = content;
308
+ let tool_name = "";
309
+ if (allContent) {
310
+ const matching = allContent.find(
311
+ (c) => c.type === "tool_use" && "id" in c && c.id === tool_use_id
312
+ );
313
+ if (matching) {
314
+ tool_name = matching.name ?? "";
315
+ }
316
+ }
317
+ return {
318
+ type: "tool_result",
319
+ tool_request_id: tool_use_id,
320
+ tool: tool_name,
321
+ result: typeof tool_content === "string" ? (() => {
322
+ try {
323
+ return JSON.parse(tool_content);
324
+ } catch {
325
+ return { text: tool_content };
326
+ }
327
+ })() : tool_content,
328
+ extended
329
+ };
330
+ }
331
+ case "thinking": {
332
+ const { type: _, thinking, ...extended } = content;
333
+ return {
334
+ type: "thinking",
335
+ thought: thinking,
336
+ extended
337
+ };
338
+ }
339
+ case "redacted_thinking": {
340
+ const { type: _, ...extended } = content;
341
+ return {
342
+ type: "thinking",
343
+ thought: extended.data,
344
+ extended
345
+ };
346
+ }
347
+ default:
348
+ return {
349
+ type: "raw",
350
+ model_kind: "anthropic",
351
+ data: JSON.stringify(content)
352
+ };
353
+ }
354
+ }
355
+ function to_anthropic_message(message) {
356
+ return {
357
+ role: message.role,
358
+ content: message.content.length === 1 && message.content[0].type === "text" ? message.content[0].text : message.content.map((c) => to_anthropic_content(c))
359
+ };
360
+ }
361
+ function to_anthropic_content(content) {
362
+ switch (content.type) {
363
+ case "text":
364
+ return {
365
+ type: "text",
366
+ text: content.text,
367
+ citations: Array.isArray(content.extended?.citations) ? content.extended.citations : []
368
+ };
369
+ case "tool":
370
+ return {
371
+ type: "tool_use",
372
+ id: content.tool_request_id,
373
+ name: content.tool,
374
+ input: content.params
375
+ };
376
+ case "raw":
377
+ if (content.model_kind !== "anthropic") {
378
+ return {
379
+ type: "text",
380
+ text: content.data
381
+ };
382
+ }
383
+ try {
384
+ return {
385
+ ...JSON.parse(content.data)
386
+ };
387
+ } catch {
388
+ return {
389
+ data: content.data
390
+ };
391
+ }
392
+ case "tool_result":
393
+ return {
394
+ type: "tool_result",
395
+ tool_use_id: content.tool_request_id,
396
+ is_error: content.result.result === false ? true : void 0,
397
+ content: JSON.stringify(content.result)
398
+ };
399
+ case "thinking":
400
+ if (!content.extended?.signature) {
401
+ return {
402
+ type: "text",
403
+ text: content.thought
404
+ };
405
+ }
406
+ return {
407
+ type: "thinking",
408
+ thinking: content.thought,
409
+ signature: content.extended?.signature
410
+ };
411
+ default:
412
+ throw new Error("unexpected content type");
413
+ }
414
+ }
415
+ function ensure_claude_request_options() {
416
+ if (!claude_oauth || !claude_creds_path) {
417
+ const { path: credsPath, oauth } = read_claude_credentials();
418
+ claude_oauth = oauth;
419
+ claude_creds_path = credsPath;
420
+ }
421
+ if (!claude_request_options_promise) {
422
+ claude_request_options_promise = refresh_claude_token(claude_creds_path, claude_oauth).then(
423
+ (token) => ({
424
+ headers: {
425
+ "x-api-key": null,
426
+ authorization: `Bearer ${token}`,
427
+ "anthropic-beta": "oauth-2025-04-20"
428
+ }
429
+ })
430
+ ).finally(() => {
431
+ claude_request_options_promise = null;
432
+ });
433
+ }
434
+ return claude_request_options_promise;
435
+ }
436
+ function get_claude_config_dir() {
437
+ return process.env["CLAUDE_CONFIG_DIR"] || join(homedir(), ".claude");
438
+ }
439
+ function read_claude_credentials() {
440
+ const configDir = get_claude_config_dir();
441
+ const credsPath = join(configDir, ".credentials.json");
442
+ let raw;
443
+ try {
444
+ raw = readFileSync(credsPath, "utf8");
445
+ } catch (e) {
446
+ throw new Error(
447
+ `Could not read Claude Code credentials at ${credsPath}. Make sure Claude Code is installed and authenticated. (${e.message})`
448
+ );
449
+ }
450
+ let creds;
451
+ try {
452
+ creds = JSON.parse(raw);
453
+ } catch (e) {
454
+ throw new Error(
455
+ `Invalid JSON in Claude Code credentials at ${credsPath}. (${e.message})`
456
+ );
457
+ }
458
+ if (!creds.claudeAiOauth) {
459
+ throw new Error(`No OAuth credentials found in ${credsPath}.`);
460
+ }
461
+ return { path: credsPath, oauth: creds.claudeAiOauth };
462
+ }
463
+ async function refresh_claude_token(credsPath, oauth) {
464
+ if (oauth.expiresAt > Date.now() + 6e4) {
465
+ return oauth.accessToken;
466
+ }
467
+ const res = await fetch("https://api.anthropic.com/v1/oauth/token", {
468
+ method: "POST",
469
+ headers: { "Content-Type": "application/json" },
470
+ body: JSON.stringify({
471
+ grant_type: "refresh_token",
472
+ refresh_token: oauth.refreshToken
473
+ })
474
+ });
475
+ if (!res.ok) {
476
+ const body = await res.text();
477
+ throw new Error(`Claude Code OAuth token refresh failed (${res.status}): ${body}`);
478
+ }
479
+ const data = await res.json();
480
+ oauth.accessToken = data.access_token;
481
+ oauth.refreshToken = data.refresh_token || oauth.refreshToken;
482
+ oauth.expiresAt = Date.now() + data.expires_in * 1e3;
483
+ try {
484
+ copyFileSync(credsPath, `${credsPath}.${Date.now()}.bak`);
485
+ const creds = JSON.parse(readFileSync(credsPath, "utf8"));
486
+ creds.claudeAiOauth = { ...oauth };
487
+ writeFileSync(credsPath, JSON.stringify(creds, null, 2));
488
+ } catch {
489
+ }
490
+ return data.access_token;
491
+ }
492
+ export {
493
+ AnthropicProvider
494
+ };
2
495
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAgC,MAAM,yBAAyB,CAAC"}
1
+ {"version":3,"sources":["../src/anthropic-provider.ts"],"sourcesContent":["import Anthropic from \"@anthropic-ai/sdk\";\nimport { readFileSync, writeFileSync, copyFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport type {\n AssistantContent,\n AssistantMessage,\n CancellationToken,\n Content,\n Message,\n ModelProvider,\n ModelRequest,\n ParameterType,\n ProviderContextTransformer,\n StreamReceiver,\n ToolDefinition,\n} from \"@simulacra-ai/core\";\n\n/**\n * Configuration options for the Anthropic provider.\n */\nexport interface AnthropicProviderConfig extends Record<string, unknown> {\n /** The model identifier to use. */\n model: string;\n /** The maximum number of tokens to generate in the response. */\n max_tokens?: number;\n /** Configuration for extended thinking mode. */\n thinking?: {\n /** Whether to enable extended thinking. */\n enable: boolean;\n /** The token budget allocated for thinking. */\n budget_tokens?: number;\n };\n /** Configuration for prompt caching. Enabled by default when omitted. Cache writes cost more per token than standard requests, but cache reads on subsequent turns cost less. */\n prompt_caching?: {\n /** Whether to cache the system prompt. */\n system_prompt?: boolean;\n /** Whether to cache the tool definitions. */\n toolkit?: boolean;\n };\n /** Use Claude Code's stored OAuth credentials for authentication. When true, the provider reads tokens from Claude Code's credentials file and refreshes them automatically. */\n claude_code_auth?: boolean;\n}\n\ninterface ClaudeCodeOAuth {\n accessToken: string;\n refreshToken: string;\n expiresAt: number;\n [key: string]: unknown;\n}\n\nlet claude_oauth: ClaudeCodeOAuth | null = null;\nlet claude_creds_path: string | null = null;\nlet claude_request_options_promise: Promise<Anthropic.RequestOptions> | null = null;\n\n/**\n * Model provider implementation for Anthropic's Claude models.\n *\n * This provider wraps the Anthropic SDK to provide streaming completions with support\n * for tool use, extended thinking, and prompt caching. It handles message formatting,\n * content streaming, and usage tracking according to the ModelProvider interface.\n */\nexport class AnthropicProvider implements ModelProvider {\n readonly #sdk: Anthropic;\n readonly #config: AnthropicProviderConfig;\n readonly context_transformers: ProviderContextTransformer[];\n\n /**\n * Creates a new Anthropic provider instance.\n *\n * @param sdk - The initialized Anthropic SDK client.\n * @param config - Configuration options for the provider.\n * @param context_transformers - Provider-level context transformers.\n */\n constructor(\n sdk: Anthropic,\n config: AnthropicProviderConfig,\n context_transformers: ProviderContextTransformer[] = [],\n ) {\n this.#sdk = sdk;\n this.#config = config;\n this.context_transformers = context_transformers;\n }\n\n /**\n * Executes a model request and streams the response through the provided receiver.\n *\n * @param request - The request containing messages, tools, and system prompt.\n * @param receiver - The receiver that handles streaming events.\n * @param cancellation - Token to signal cancellation of the request.\n * @returns A promise that resolves when the request completes.\n */\n async execute_request(\n request: ModelRequest,\n receiver: StreamReceiver,\n cancellation: CancellationToken,\n ): Promise<void> {\n const {\n model,\n max_tokens,\n thinking,\n prompt_caching,\n claude_code_auth: _,\n ...api_extras\n } = this.#config;\n const cache_system = prompt_caching?.system_prompt !== false;\n const cache_tools = prompt_caching?.toolkit !== false;\n\n const tools = request.tools.map((t) => to_anthropic_tool(t));\n\n if (cache_tools && tools.length > 0) {\n const last = tools.length - 1;\n (tools[last] as Anthropic.Messages.Tool).cache_control = { type: \"ephemeral\" };\n }\n\n const system: Anthropic.MessageCreateParamsStreaming[\"system\"] =\n cache_system && request.system\n ? [{ type: \"text\", text: request.system, cache_control: { type: \"ephemeral\" } }]\n : request.system;\n\n const params: Anthropic.MessageCreateParamsStreaming = {\n ...api_extras,\n model,\n stream: true,\n system,\n max_tokens: max_tokens ?? 8_192,\n thinking:\n thinking?.enable && thinking?.budget_tokens\n ? {\n type: \"enabled\",\n budget_tokens: thinking.budget_tokens,\n }\n : {\n type: \"disabled\",\n },\n tools,\n messages: request.messages.map((m) => to_anthropic_message(m)),\n };\n receiver.before_request({ params });\n receiver.request_raw(params);\n\n const response = await this.#sdk.messages.create(\n params,\n this.#config.claude_code_auth ? await ensure_claude_request_options() : undefined,\n );\n\n // Intentionally not awaited. Streaming is event-driven through the receiver.\n // The policy wraps only connection establishment; chunk processing flows\n // asynchronously via StreamListener events back to the conversation.\n this.#stream_response(response, receiver, cancellation);\n }\n\n /**\n * Creates a clone of this provider with the same configuration.\n *\n * @returns A new provider instance with identical configuration.\n */\n clone(): ModelProvider {\n return new AnthropicProvider(this.#sdk, this.#config, this.context_transformers);\n }\n\n async #stream_response(\n stream: AsyncIterable<Anthropic.Messages.RawMessageStreamEvent>,\n receiver: StreamReceiver,\n cancellation: CancellationToken,\n ) {\n try {\n let usage: Record<string, number> = {};\n let message: Partial<Anthropic.Message> & { content: Anthropic.ContentBlock[] } = {\n content: [],\n };\n const json: string[] = [];\n for await (const chunk of stream) {\n if (cancellation.is_cancellation_requested) {\n receiver.cancel();\n return;\n }\n receiver.stream_raw(chunk);\n switch (chunk.type) {\n case \"message_start\": {\n usage = Object.fromEntries(\n Object.entries(chunk.message.usage).filter(([, v]) => typeof v === \"number\"),\n ) as Record<string, number>;\n message = chunk.message;\n receiver.start_message({\n usage,\n message: from_anthropic_message(message) as AssistantMessage,\n });\n break;\n }\n case \"message_delta\": {\n usage = {\n ...usage,\n ...Object.fromEntries(\n Object.entries(chunk.usage).filter(([, v]) => typeof v === \"number\"),\n ),\n };\n message = { ...message, ...chunk.delta };\n receiver.update_message({\n usage,\n message: from_anthropic_message(message) as AssistantMessage,\n });\n break;\n }\n case \"message_stop\": {\n const raw_stop = message.stop_reason ?? \"end_turn\";\n const stop_reason = (\n [\"tool_use\", \"stop_sequence\", \"end_turn\", \"max_tokens\", \"error\"].includes(raw_stop)\n ? raw_stop\n : \"other\"\n ) as \"tool_use\" | \"stop_sequence\" | \"end_turn\" | \"max_tokens\" | \"error\" | \"other\";\n receiver.complete_message({\n usage,\n stop_reason,\n message: from_anthropic_message(message) as AssistantMessage,\n });\n break;\n }\n case \"content_block_start\": {\n message.content[chunk.index] = chunk.content_block;\n receiver.start_content({\n usage,\n message: from_anthropic_message(message) as AssistantMessage,\n content: from_anthropic_content(chunk.content_block) as Partial<AssistantContent>,\n });\n receiver.update_message({\n usage,\n message: from_anthropic_message(message) as AssistantMessage,\n });\n break;\n }\n case \"content_block_delta\": {\n switch (chunk.delta.type) {\n case \"text_delta\": {\n const content = message.content[chunk.index] as Anthropic.TextBlock;\n content.text += chunk.delta.text;\n break;\n }\n case \"citations_delta\": {\n const content = message.content[chunk.index] as Anthropic.TextBlock;\n content.citations = [...(content.citations ?? []), chunk.delta.citation];\n break;\n }\n case \"thinking_delta\": {\n const content = message.content[chunk.index] as Anthropic.ThinkingBlock;\n content.thinking += chunk.delta.thinking;\n break;\n }\n case \"input_json_delta\": {\n if (!json[chunk.index]) {\n json[chunk.index] = \"\";\n }\n json[chunk.index] += chunk.delta.partial_json;\n break;\n }\n case \"signature_delta\": {\n const content = message.content[chunk.index] as Anthropic.ThinkingBlock;\n content.signature = (content.signature ?? \"\") + chunk.delta.signature;\n break;\n }\n }\n receiver.update_content({\n usage,\n message: from_anthropic_message(message) as AssistantMessage,\n content: from_anthropic_content(message.content[chunk.index]) as AssistantContent,\n });\n break;\n }\n case \"content_block_stop\": {\n const content_block = message.content[chunk.index];\n if (content_block.type === \"tool_use\" && json[chunk.index]) {\n content_block.input = {\n ...(content_block.input ?? {}),\n ...JSON.parse(json[chunk.index]),\n };\n }\n receiver.complete_content({\n usage,\n message: from_anthropic_message(message) as AssistantMessage,\n content: from_anthropic_content(content_block) as AssistantContent,\n });\n break;\n }\n }\n }\n receiver.response_raw(message);\n } catch (error) {\n receiver.error(error);\n }\n }\n}\n\nfunction parameter_to_json_schema(param: ParameterType): Record<string, unknown> {\n switch (param.type) {\n case \"object\": {\n const properties: Record<string, Record<string, unknown>> = {};\n const required: string[] = [];\n for (const [key, child] of Object.entries(param.properties)) {\n properties[key] = parameter_to_json_schema(child);\n if (child.required) {\n required.push(key);\n }\n }\n return {\n type: \"object\",\n ...(param.description ? { description: param.description } : {}),\n ...(Object.keys(properties).length ? { properties } : {}),\n ...(required.length ? { required } : {}),\n };\n }\n case \"array\":\n return {\n type: \"array\",\n ...(param.description ? { description: param.description } : {}),\n items: parameter_to_json_schema(param.items),\n };\n case \"number\":\n return {\n type: \"number\",\n ...(param.description ? { description: param.description } : {}),\n };\n case \"boolean\":\n return {\n type: \"boolean\",\n ...(param.description ? { description: param.description } : {}),\n };\n case \"string\":\n return \"enum\" in param && param.enum\n ? {\n type: \"string\",\n enum: param.enum,\n ...(param.description ? { description: param.description } : {}),\n }\n : { type: \"string\", ...(param.description ? { description: param.description } : {}) };\n }\n}\n\nfunction to_anthropic_tool(tool: ToolDefinition): Anthropic.Messages.ToolUnion {\n const properties: Record<string, Record<string, unknown>> = {};\n const required: string[] = [];\n\n for (const param of tool.parameters) {\n const schema = parameter_to_json_schema(param);\n if (param.description) {\n schema.description = param.description;\n }\n properties[param.name] = schema;\n if (param.required) {\n required.push(param.name);\n }\n }\n\n return {\n name: tool.name,\n description: tool.description,\n input_schema: {\n type: \"object\",\n ...(Object.keys(properties).length ? { properties } : {}),\n ...(required.length ? { required } : {}),\n },\n };\n}\n\nfunction from_anthropic_message(message: Partial<Anthropic.MessageParam>) {\n if (typeof message.content === \"string\") {\n return {\n role: message.role,\n content: [\n {\n type: \"text\",\n text: message.content,\n },\n ],\n } as Message;\n }\n return {\n role: message.role,\n content: (message.content ?? []).map((c) =>\n from_anthropic_content(c, Array.isArray(message.content) ? message.content : undefined),\n ),\n } as Message;\n}\n\nfunction from_anthropic_content(\n content: Partial<Anthropic.ContentBlockParam>,\n allContent?: Partial<Anthropic.ContentBlockParam>[],\n) {\n switch (content.type) {\n case \"text\": {\n const { type: _, text, ...extended } = content;\n return {\n type: \"text\",\n text,\n extended,\n };\n }\n case \"tool_use\": {\n const { type: _, id, name, input, ...extended } = content;\n return {\n type: \"tool\",\n tool_request_id: id,\n tool: name,\n params: input as Record<string, unknown>,\n extended,\n };\n }\n case \"tool_result\": {\n const { type: _, tool_use_id, content: tool_content, ...extended } = content;\n let tool_name = \"\";\n if (allContent) {\n const matching = allContent.find(\n (c): c is Partial<Anthropic.Messages.ToolUseBlockParam> =>\n c.type === \"tool_use\" && \"id\" in c && c.id === tool_use_id,\n );\n if (matching) {\n tool_name = matching.name ?? \"\";\n }\n }\n return {\n type: \"tool_result\",\n tool_request_id: tool_use_id,\n tool: tool_name,\n result:\n typeof tool_content === \"string\"\n ? (() => {\n try {\n return JSON.parse(tool_content as string);\n } catch {\n return { text: tool_content };\n }\n })()\n : tool_content,\n extended,\n };\n }\n case \"thinking\": {\n const { type: _, thinking, ...extended } = content;\n return {\n type: \"thinking\",\n thought: thinking,\n extended,\n };\n }\n case \"redacted_thinking\": {\n const { type: _, ...extended } = content;\n return {\n type: \"thinking\",\n thought: extended.data,\n extended,\n };\n }\n default:\n return {\n type: \"raw\",\n model_kind: \"anthropic\",\n data: JSON.stringify(content),\n };\n }\n}\n\nfunction to_anthropic_message(message: Readonly<Message>) {\n return {\n role: message.role,\n content:\n message.content.length === 1 && message.content[0].type === \"text\"\n ? message.content[0].text\n : message.content.map((c) => to_anthropic_content(c)),\n };\n}\n\nfunction to_anthropic_content(content: Readonly<Content>) {\n switch (content.type) {\n case \"text\":\n return {\n type: \"text\",\n text: content.text,\n citations: Array.isArray(content.extended?.citations) ? content.extended.citations : [],\n };\n case \"tool\":\n return {\n type: \"tool_use\",\n id: content.tool_request_id,\n name: content.tool,\n input: content.params,\n };\n case \"raw\":\n if (content.model_kind !== \"anthropic\") {\n return {\n type: \"text\",\n text: content.data,\n };\n }\n try {\n return {\n ...JSON.parse(content.data),\n };\n } catch {\n return {\n data: content.data,\n };\n }\n case \"tool_result\":\n return {\n type: \"tool_result\",\n tool_use_id: content.tool_request_id,\n is_error: content.result.result === false ? true : undefined,\n content: JSON.stringify(content.result),\n };\n case \"thinking\":\n if (!content.extended?.signature) {\n return {\n type: \"text\",\n text: content.thought,\n };\n }\n return {\n type: \"thinking\",\n thinking: content.thought,\n signature: content.extended?.signature,\n };\n default:\n throw new Error(\"unexpected content type\");\n }\n}\n\nfunction ensure_claude_request_options(): Promise<Anthropic.RequestOptions> {\n if (!claude_oauth || !claude_creds_path) {\n const { path: credsPath, oauth } = read_claude_credentials();\n claude_oauth = oauth;\n claude_creds_path = credsPath;\n }\n if (!claude_request_options_promise) {\n claude_request_options_promise = refresh_claude_token(claude_creds_path, claude_oauth)\n .then(\n (token) =>\n ({\n headers: {\n \"x-api-key\": null,\n authorization: `Bearer ${token}`,\n \"anthropic-beta\": \"oauth-2025-04-20\",\n },\n }) as Anthropic.RequestOptions,\n )\n .finally(() => {\n claude_request_options_promise = null;\n });\n }\n return claude_request_options_promise;\n}\n\nfunction get_claude_config_dir(): string {\n return process.env[\"CLAUDE_CONFIG_DIR\"] || join(homedir(), \".claude\");\n}\n\nfunction read_claude_credentials(): { path: string; oauth: ClaudeCodeOAuth } {\n const configDir = get_claude_config_dir();\n const credsPath = join(configDir, \".credentials.json\");\n\n let raw: string;\n try {\n raw = readFileSync(credsPath, \"utf8\");\n } catch (e) {\n throw new Error(\n `Could not read Claude Code credentials at ${credsPath}. ` +\n `Make sure Claude Code is installed and authenticated. ` +\n `(${(e as Error).message})`,\n );\n }\n\n let creds: Record<string, unknown>;\n try {\n creds = JSON.parse(raw);\n } catch (e) {\n throw new Error(\n `Invalid JSON in Claude Code credentials at ${credsPath}. (${(e as Error).message})`,\n );\n }\n if (!creds.claudeAiOauth) {\n throw new Error(`No OAuth credentials found in ${credsPath}.`);\n }\n\n return { path: credsPath, oauth: creds.claudeAiOauth as ClaudeCodeOAuth };\n}\n\nasync function refresh_claude_token(credsPath: string, oauth: ClaudeCodeOAuth): Promise<string> {\n if (oauth.expiresAt > Date.now() + 60_000) {\n return oauth.accessToken;\n }\n\n const res = await fetch(\"https://api.anthropic.com/v1/oauth/token\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n grant_type: \"refresh_token\",\n refresh_token: oauth.refreshToken,\n }),\n });\n\n if (!res.ok) {\n const body = await res.text();\n throw new Error(`Claude Code OAuth token refresh failed (${res.status}): ${body}`);\n }\n\n const data = (await res.json()) as {\n access_token: string;\n refresh_token?: string;\n expires_in: number;\n };\n\n // Update in-memory state first so the token is usable even if file ops fail\n oauth.accessToken = data.access_token;\n oauth.refreshToken = data.refresh_token || oauth.refreshToken;\n oauth.expiresAt = Date.now() + data.expires_in * 1000;\n\n try {\n copyFileSync(credsPath, `${credsPath}.${Date.now()}.bak`);\n const creds = JSON.parse(readFileSync(credsPath, \"utf8\"));\n creds.claudeAiOauth = { ...oauth };\n writeFileSync(credsPath, JSON.stringify(creds, null, 2));\n } catch {\n // File persistence is best-effort; in-memory state is already updated\n }\n\n return data.access_token;\n}\n"],"mappings":";AACA,SAAS,cAAc,eAAe,oBAAoB;AAC1D,SAAS,eAAe;AACxB,SAAS,YAAY;AAiDrB,IAAI,eAAuC;AAC3C,IAAI,oBAAmC;AACvC,IAAI,iCAA2E;AASxE,IAAM,oBAAN,MAAM,mBAA2C;AAAA,EAC7C;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAST,YACE,KACA,QACA,uBAAqD,CAAC,GACtD;AACA,SAAK,OAAO;AACZ,SAAK,UAAU;AACf,SAAK,uBAAuB;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,MAAM,gBACJ,SACA,UACA,cACe;AACf,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,kBAAkB;AAAA,MAClB,GAAG;AAAA,IACL,IAAI,KAAK;AACT,UAAM,eAAe,gBAAgB,kBAAkB;AACvD,UAAM,cAAc,gBAAgB,YAAY;AAEhD,UAAM,QAAQ,Q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AAI,MAAM,iCAAiC,SAAS,GAAG;AAAA,EAC/D;AAEA,SAAO,EAAE,MAAM,WAAW,OAAO,MAAM,cAAiC;AAC1E;AAEA,eAAe,qBAAqB,WAAmB,OAAyC;AAC9F,MAAI,MAAM,YAAY,KAAK,IAAI,IAAI,KAAQ;AACzC,WAAO,MAAM;AAAA,EACf;AAEA,QAAM,MAAM,MAAM,MAAM,4CAA4C;AAAA,IAClE,QAAQ;AAAA,IACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,IAC9C,MAAM,KAAK,UAAU;AAAA,MACnB,YAAY;AAAA,MACZ,eAAe,MAAM;AAAA,IACvB,CAAC;AAAA,EACH,CAAC;AAED,MAAI,CAAC,IAAI,IAAI;AACX,UAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,UAAM,IAAI,MAAM,2CAA2C,IAAI,MAAM,MAAM,IAAI,EAAE;AAAA,EACnF;AAEA,QAAM,OAAQ,MAAM,IAAI,KAAK;AAO7B,QAAM,cAAc,KAAK;AACzB,QAAM,eAAe,KAAK,iBAAiB,MAAM;AACjD,QAAM,YAAY,KAAK,IAAI,IAAI,KAAK,aAAa;AAEjD,MAAI;AACF,iBAAa,WAAW,GAAG,SAAS,IAAI,KAAK,IAAI,CAAC,MAAM;AACxD,UAAM,QAAQ,KAAK,MAAM,aAAa,WAAW,MAAM,CAAC;AACxD,UAAM,gBAAgB,EAAE,GAAG,MAAM;AACjC,kBAAc,WAAW,KAAK,UAAU,OAAO,MAAM,CAAC,CAAC;AAAA,EACzD,QAAQ;AAAA,EAER;AAEA,SAAO,KAAK;AACd;","names":[]}
package/package.json CHANGED
@@ -1,23 +1,29 @@
1
1
  {
2
2
  "name": "@simulacra-ai/anthropic",
3
- "version": "0.0.3",
3
+ "version": "0.0.4",
4
4
  "description": "Anthropic Claude provider for the Simulacra conversation engine",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  ".": {
8
- "types": "./dist/index.d.ts",
9
- "default": "./dist/index.js"
8
+ "require": {
9
+ "types": "./dist/index.d.cts",
10
+ "default": "./dist/index.cjs"
11
+ },
12
+ "import": {
13
+ "types": "./dist/index.d.ts",
14
+ "default": "./dist/index.js"
15
+ }
10
16
  }
11
17
  },
12
18
  "files": [
13
19
  "dist"
14
20
  ],
15
21
  "scripts": {
16
- "build": "tsc -p tsconfig.json",
22
+ "build": "tsup",
17
23
  "clean": "rm -rf dist *.tsbuildinfo"
18
24
  },
19
25
  "peerDependencies": {
20
- "@simulacra-ai/core": "0.0.3",
26
+ "@simulacra-ai/core": "0.0.4",
21
27
  "@anthropic-ai/sdk": ">=0.30.0 <1.0.0"
22
28
  },
23
29
  "repository": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"anthropic-provider.d.ts","sourceRoot":"","sources":["../src/anthropic-provider.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,mBAAmB,CAAC;AAE1C,OAAO,KAAK,EAGV,iBAAiB,EAGjB,aAAa,EACb,YAAY,EAEZ,0BAA0B,EAC1B,cAAc,EAEf,MAAM,oBAAoB,CAAC;AAE5B;;GAEG;AACH,MAAM,WAAW,uBAAwB,SAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IACtE,mCAAmC;IACnC,KAAK,EAAE,MAAM,CAAC;IACd,gEAAgE;IAChE,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,gDAAgD;IAChD,QAAQ,CAAC,EAAE;QACT,2CAA2C;QAC3C,MAAM,EAAE,OAAO,CAAC;QAChB,+CAA+C;QAC/C,aAAa,CAAC,EAAE,MAAM,CAAC;KACxB,CAAC;IACF,iLAAiL;IACjL,cAAc,CAAC,EAAE;QACf,0CAA0C;QAC1C,aAAa,CAAC,EAAE,OAAO,CAAC;QACxB,6CAA6C;QAC7C,OAAO,CAAC,EAAE,OAAO,CAAC;KACnB,CAAC;CACH;AAED;;;;;;GAMG;AACH,qBAAa,iBAAkB,YAAW,aAAa;;IAGrD,QAAQ,CAAC,oBAAoB,EAAE,0BAA0B,EAAE,CAAC;IAE5D;;;;;;OAMG;gBAED,GAAG,EAAE,SAAS,EACd,MAAM,EAAE,uBAAuB,EAC/B,oBAAoB,GAAE,0BAA0B,EAAO;IAOzD;;;;;;;OAOG;IACG,eAAe,CACnB,OAAO,EAAE,YAAY,EACrB,QAAQ,EAAE,cAAc,EACxB,YAAY,EAAE,iBAAiB,GAC9B,OAAO,CAAC,IAAI,CAAC;IA8ChB;;;;OAIG;IACH,KAAK,IAAI,aAAa;CAqIvB"}