@shareai-lab/kode-sdk 1.0.0-beta.9 → 2.7.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.
Files changed (193) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +115 -273
  3. package/README.zh-CN.md +114 -0
  4. package/dist/core/agent/breakpoint-manager.d.ts +16 -0
  5. package/dist/core/agent/breakpoint-manager.js +36 -0
  6. package/dist/core/agent/message-queue.d.ts +26 -0
  7. package/dist/core/agent/message-queue.js +57 -0
  8. package/dist/core/agent/permission-manager.d.ts +9 -0
  9. package/dist/core/agent/permission-manager.js +32 -0
  10. package/dist/core/agent/todo-manager.d.ts +26 -0
  11. package/dist/core/agent/todo-manager.js +91 -0
  12. package/dist/core/agent/tool-runner.d.ts +9 -0
  13. package/dist/core/agent/tool-runner.js +45 -0
  14. package/dist/core/agent.d.ts +228 -62
  15. package/dist/core/agent.js +1890 -615
  16. package/dist/core/config.d.ts +10 -0
  17. package/dist/core/config.js +2 -0
  18. package/dist/core/context-manager.d.ts +82 -0
  19. package/dist/core/context-manager.js +241 -0
  20. package/dist/core/errors.d.ts +22 -0
  21. package/dist/core/errors.js +49 -0
  22. package/dist/core/events.d.ts +41 -10
  23. package/dist/core/events.js +270 -68
  24. package/dist/core/file-pool.d.ts +41 -0
  25. package/dist/core/file-pool.js +102 -0
  26. package/dist/core/hooks.d.ts +3 -3
  27. package/dist/core/hooks.js +1 -1
  28. package/dist/core/permission-modes.d.ts +31 -0
  29. package/dist/core/permission-modes.js +61 -0
  30. package/dist/core/pool.d.ts +56 -13
  31. package/dist/core/pool.js +244 -34
  32. package/dist/core/room.d.ts +2 -2
  33. package/dist/core/room.js +10 -10
  34. package/dist/core/scheduler.d.ts +30 -23
  35. package/dist/core/scheduler.js +42 -168
  36. package/dist/core/skills/index.d.ts +10 -0
  37. package/dist/core/skills/index.js +20 -0
  38. package/dist/core/skills/management-manager.d.ts +130 -0
  39. package/dist/core/skills/management-manager.js +557 -0
  40. package/dist/core/skills/manager.d.ts +47 -0
  41. package/dist/core/skills/manager.js +243 -0
  42. package/dist/core/skills/operation-queue.d.ts +87 -0
  43. package/dist/core/skills/operation-queue.js +113 -0
  44. package/dist/core/skills/sandbox-file-manager.d.ts +82 -0
  45. package/dist/core/skills/sandbox-file-manager.js +183 -0
  46. package/dist/core/skills/types.d.ts +120 -0
  47. package/dist/core/skills/types.js +9 -0
  48. package/dist/core/skills/xml-generator.d.ts +13 -0
  49. package/dist/core/skills/xml-generator.js +70 -0
  50. package/dist/core/template.d.ts +57 -0
  51. package/dist/core/template.js +35 -0
  52. package/dist/core/time-bridge.d.ts +18 -0
  53. package/dist/core/time-bridge.js +100 -0
  54. package/dist/core/todo.d.ts +34 -0
  55. package/dist/core/todo.js +89 -0
  56. package/dist/core/types.d.ts +311 -114
  57. package/dist/core/types.js +1 -12
  58. package/dist/index.d.ts +47 -9
  59. package/dist/index.js +108 -15
  60. package/dist/infra/db/postgres/postgres-store.d.ts +97 -0
  61. package/dist/infra/db/postgres/postgres-store.js +1073 -0
  62. package/dist/infra/db/sqlite/sqlite-store.d.ts +84 -0
  63. package/dist/infra/db/sqlite/sqlite-store.js +800 -0
  64. package/dist/infra/e2b/e2b-fs.d.ts +29 -0
  65. package/dist/infra/e2b/e2b-fs.js +128 -0
  66. package/dist/infra/e2b/e2b-sandbox.d.ts +37 -0
  67. package/dist/infra/e2b/e2b-sandbox.js +156 -0
  68. package/dist/infra/e2b/e2b-template.d.ts +24 -0
  69. package/dist/infra/e2b/e2b-template.js +105 -0
  70. package/dist/infra/e2b/index.d.ts +4 -0
  71. package/dist/infra/e2b/index.js +9 -0
  72. package/dist/infra/e2b/types.d.ts +46 -0
  73. package/dist/infra/e2b/types.js +2 -0
  74. package/dist/infra/provider.d.ts +17 -58
  75. package/dist/infra/provider.js +65 -116
  76. package/dist/infra/providers/anthropic.d.ts +42 -0
  77. package/dist/infra/providers/anthropic.js +308 -0
  78. package/dist/infra/providers/core/errors.d.ts +230 -0
  79. package/dist/infra/providers/core/errors.js +353 -0
  80. package/dist/infra/providers/core/fork.d.ts +106 -0
  81. package/dist/infra/providers/core/fork.js +418 -0
  82. package/dist/infra/providers/core/index.d.ts +10 -0
  83. package/dist/infra/providers/core/index.js +76 -0
  84. package/dist/infra/providers/core/logger.d.ts +186 -0
  85. package/dist/infra/providers/core/logger.js +191 -0
  86. package/dist/infra/providers/core/retry.d.ts +62 -0
  87. package/dist/infra/providers/core/retry.js +189 -0
  88. package/dist/infra/providers/core/usage.d.ts +151 -0
  89. package/dist/infra/providers/core/usage.js +376 -0
  90. package/dist/infra/providers/gemini.d.ts +49 -0
  91. package/dist/infra/providers/gemini.js +493 -0
  92. package/dist/infra/providers/index.d.ts +25 -0
  93. package/dist/infra/providers/index.js +83 -0
  94. package/dist/infra/providers/openai.d.ts +123 -0
  95. package/dist/infra/providers/openai.js +662 -0
  96. package/dist/infra/providers/types.d.ts +334 -0
  97. package/dist/infra/providers/types.js +20 -0
  98. package/dist/infra/providers/utils.d.ts +53 -0
  99. package/dist/infra/providers/utils.js +400 -0
  100. package/dist/infra/sandbox-factory.d.ts +13 -0
  101. package/dist/infra/sandbox-factory.js +30 -0
  102. package/dist/infra/sandbox.d.ts +35 -6
  103. package/dist/infra/sandbox.js +174 -8
  104. package/dist/infra/store/factory.d.ts +45 -0
  105. package/dist/infra/store/factory.js +80 -0
  106. package/dist/infra/store/index.d.ts +3 -0
  107. package/dist/infra/store/index.js +26 -0
  108. package/dist/infra/store/json-store.d.ts +67 -0
  109. package/dist/infra/store/json-store.js +606 -0
  110. package/dist/infra/store/types.d.ts +342 -0
  111. package/dist/infra/store/types.js +2 -0
  112. package/dist/infra/store.d.ts +12 -32
  113. package/dist/infra/store.js +27 -130
  114. package/dist/tools/bash_kill/index.d.ts +1 -0
  115. package/dist/tools/bash_kill/index.js +35 -0
  116. package/dist/tools/bash_kill/prompt.d.ts +2 -0
  117. package/dist/tools/bash_kill/prompt.js +14 -0
  118. package/dist/tools/bash_logs/index.d.ts +1 -0
  119. package/dist/tools/bash_logs/index.js +40 -0
  120. package/dist/tools/bash_logs/prompt.d.ts +2 -0
  121. package/dist/tools/bash_logs/prompt.js +14 -0
  122. package/dist/tools/bash_run/index.d.ts +16 -0
  123. package/dist/tools/bash_run/index.js +61 -0
  124. package/dist/tools/bash_run/prompt.d.ts +2 -0
  125. package/dist/tools/bash_run/prompt.js +18 -0
  126. package/dist/tools/builtin.d.ts +7 -13
  127. package/dist/tools/builtin.js +19 -90
  128. package/dist/tools/define.d.ts +101 -0
  129. package/dist/tools/define.js +214 -0
  130. package/dist/tools/fs_edit/index.d.ts +1 -0
  131. package/dist/tools/fs_edit/index.js +62 -0
  132. package/dist/tools/fs_edit/prompt.d.ts +2 -0
  133. package/dist/tools/fs_edit/prompt.js +15 -0
  134. package/dist/tools/fs_glob/index.d.ts +1 -0
  135. package/dist/tools/fs_glob/index.js +40 -0
  136. package/dist/tools/fs_glob/prompt.d.ts +2 -0
  137. package/dist/tools/fs_glob/prompt.js +15 -0
  138. package/dist/tools/fs_grep/index.d.ts +1 -0
  139. package/dist/tools/fs_grep/index.js +66 -0
  140. package/dist/tools/fs_grep/prompt.d.ts +2 -0
  141. package/dist/tools/fs_grep/prompt.js +16 -0
  142. package/dist/tools/fs_multi_edit/index.d.ts +1 -0
  143. package/dist/tools/fs_multi_edit/index.js +106 -0
  144. package/dist/tools/fs_multi_edit/prompt.d.ts +2 -0
  145. package/dist/tools/fs_multi_edit/prompt.js +16 -0
  146. package/dist/tools/fs_read/index.d.ts +1 -0
  147. package/dist/tools/fs_read/index.js +40 -0
  148. package/dist/tools/fs_read/prompt.d.ts +2 -0
  149. package/dist/tools/fs_read/prompt.js +16 -0
  150. package/dist/tools/fs_write/index.d.ts +1 -0
  151. package/dist/tools/fs_write/index.js +40 -0
  152. package/dist/tools/fs_write/prompt.d.ts +2 -0
  153. package/dist/tools/fs_write/prompt.js +15 -0
  154. package/dist/tools/index.d.ts +11 -0
  155. package/dist/tools/index.js +61 -0
  156. package/dist/tools/mcp.d.ts +69 -0
  157. package/dist/tools/mcp.js +185 -0
  158. package/dist/tools/registry.d.ts +29 -0
  159. package/dist/tools/registry.js +26 -0
  160. package/dist/tools/scripts.d.ts +22 -0
  161. package/dist/tools/scripts.js +205 -0
  162. package/dist/tools/skills.d.ts +20 -0
  163. package/dist/tools/skills.js +115 -0
  164. package/dist/tools/task_run/index.d.ts +7 -0
  165. package/dist/tools/task_run/index.js +58 -0
  166. package/dist/tools/task_run/prompt.d.ts +5 -0
  167. package/dist/tools/task_run/prompt.js +25 -0
  168. package/dist/tools/todo_read/index.d.ts +1 -0
  169. package/dist/tools/todo_read/index.js +29 -0
  170. package/dist/tools/todo_read/prompt.d.ts +2 -0
  171. package/dist/tools/todo_read/prompt.js +18 -0
  172. package/dist/tools/todo_write/index.d.ts +1 -0
  173. package/dist/tools/todo_write/index.js +42 -0
  174. package/dist/tools/todo_write/prompt.d.ts +2 -0
  175. package/dist/tools/todo_write/prompt.js +23 -0
  176. package/dist/tools/tool.d.ts +43 -0
  177. package/dist/tools/tool.js +211 -0
  178. package/dist/tools/toolkit.d.ts +69 -0
  179. package/dist/tools/toolkit.js +98 -0
  180. package/dist/tools/type-inference.d.ts +127 -0
  181. package/dist/tools/type-inference.js +207 -0
  182. package/dist/utils/agent-id.d.ts +1 -0
  183. package/dist/utils/agent-id.js +28 -0
  184. package/dist/utils/logger.d.ts +15 -0
  185. package/dist/utils/logger.js +44 -0
  186. package/dist/utils/session-id.js +16 -16
  187. package/package.json +35 -11
  188. package/dist/tools/bash.d.ts +0 -63
  189. package/dist/tools/bash.js +0 -92
  190. package/dist/tools/fs.d.ts +0 -96
  191. package/dist/tools/fs.js +0 -100
  192. package/dist/tools/task.d.ts +0 -38
  193. package/dist/tools/task.js +0 -45
@@ -1,118 +1,67 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AnthropicProvider = void 0;
4
- class AnthropicProvider {
5
- constructor(apiKey, model = 'claude-3-5-sonnet-20241022', baseUrl = 'https://api.anthropic.com') {
6
- this.apiKey = apiKey;
7
- this.model = model;
8
- this.baseUrl = baseUrl;
9
- }
10
- async complete(messages, opts) {
11
- const body = {
12
- model: this.model,
13
- messages: this.formatMessages(messages),
14
- max_tokens: opts?.maxTokens || 4096,
15
- };
16
- if (opts?.temperature !== undefined)
17
- body.temperature = opts.temperature;
18
- if (opts?.system)
19
- body.system = opts.system;
20
- if (opts?.tools && opts.tools.length > 0)
21
- body.tools = opts.tools;
22
- const response = await fetch(`${this.baseUrl}/v1/messages`, {
23
- method: 'POST',
24
- headers: {
25
- 'Content-Type': 'application/json',
26
- 'x-api-key': this.apiKey,
27
- 'anthropic-version': '2023-06-01',
28
- },
29
- body: JSON.stringify(body),
30
- });
31
- if (!response.ok) {
32
- const error = await response.text();
33
- throw new Error(`Anthropic API error: ${response.status} ${error}`);
34
- }
35
- const data = await response.json();
36
- return {
37
- role: 'assistant',
38
- content: data.content,
39
- usage: data.usage,
40
- stop_reason: data.stop_reason,
41
- };
42
- }
43
- async *stream(messages, opts) {
44
- const body = {
45
- model: this.model,
46
- messages: this.formatMessages(messages),
47
- max_tokens: opts?.maxTokens || 4096,
48
- stream: true,
49
- };
50
- if (opts?.temperature !== undefined)
51
- body.temperature = opts.temperature;
52
- if (opts?.system)
53
- body.system = opts.system;
54
- if (opts?.tools && opts.tools.length > 0)
55
- body.tools = opts.tools;
56
- const response = await fetch(`${this.baseUrl}/v1/messages`, {
57
- method: 'POST',
58
- headers: {
59
- 'Content-Type': 'application/json',
60
- 'x-api-key': this.apiKey,
61
- 'anthropic-version': '2023-06-01',
62
- },
63
- body: JSON.stringify(body),
64
- });
65
- if (!response.ok) {
66
- const error = await response.text();
67
- throw new Error(`Anthropic API error: ${response.status} ${error}`);
68
- }
69
- const reader = response.body?.getReader();
70
- if (!reader)
71
- throw new Error('No response body');
72
- const decoder = new TextDecoder();
73
- let buffer = '';
74
- while (true) {
75
- const { done, value } = await reader.read();
76
- if (done)
77
- break;
78
- buffer += decoder.decode(value, { stream: true });
79
- const lines = buffer.split('\n');
80
- buffer = lines.pop() || '';
81
- for (const line of lines) {
82
- if (!line.trim() || !line.startsWith('data: '))
83
- continue;
84
- const data = line.slice(6);
85
- if (data === '[DONE]')
86
- continue;
87
- try {
88
- const event = JSON.parse(data);
89
- if (event.type === 'content_block_start') {
90
- yield { type: 'content_block_start', index: event.index, content_block: event.content_block };
91
- }
92
- else if (event.type === 'content_block_delta') {
93
- yield { type: 'content_block_delta', index: event.index, delta: event.delta };
94
- }
95
- else if (event.type === 'content_block_stop') {
96
- yield { type: 'content_block_stop', index: event.index };
97
- }
98
- else if (event.type === 'message_delta') {
99
- yield { type: 'message_delta', delta: event.delta, usage: event.usage };
100
- }
101
- else if (event.type === 'message_stop') {
102
- yield { type: 'message_stop' };
103
- }
104
- }
105
- catch (e) {
106
- // Skip invalid JSON
107
- }
108
- }
109
- }
2
+ /**
3
+ * Provider Module
4
+ *
5
+ * Re-exports from the providers module for backward compatibility.
6
+ * The actual implementations are in src/infra/providers/.
7
+ *
8
+ * Usage:
9
+ * ```typescript
10
+ * import { AnthropicProvider, OpenAIProvider, GeminiProvider } from './infra/provider';
11
+ * // or
12
+ * import { AnthropicProvider } from './infra/providers';
13
+ * ```
14
+ */
15
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
16
+ if (k2 === undefined) k2 = k;
17
+ var desc = Object.getOwnPropertyDescriptor(m, k);
18
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
19
+ desc = { enumerable: true, get: function() { return m[k]; } };
110
20
  }
111
- formatMessages(messages) {
112
- return messages.map((msg) => ({
113
- role: msg.role === 'system' ? 'user' : msg.role,
114
- content: msg.content,
115
- }));
116
- }
117
- }
118
- exports.AnthropicProvider = AnthropicProvider;
21
+ Object.defineProperty(o, k2, desc);
22
+ }) : (function(o, m, k, k2) {
23
+ if (k2 === undefined) k2 = k;
24
+ o[k2] = m[k];
25
+ }));
26
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
27
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
28
+ };
29
+ Object.defineProperty(exports, "__esModule", { value: true });
30
+ exports.normalizeAnthropicDelta = exports.normalizeAnthropicContentBlock = exports.normalizeAnthropicContent = exports.mergeAnthropicBetaHeader = exports.hasAnthropicFileBlocks = exports.sanitizeGeminiSchema = exports.buildGeminiFilePart = exports.buildGeminiImagePart = exports.extractReasoningDetails = exports.splitThinkText = exports.normalizeThinkBlocks = exports.joinReasoningBlocks = exports.concatTextWithReasoning = exports.AUDIO_UNSUPPORTED_TEXT = exports.IMAGE_UNSUPPORTED_TEXT = exports.FILE_UNSUPPORTED_TEXT = exports.safeJsonStringify = exports.formatToolResult = exports.joinTextBlocks = exports.markTransportIfDegraded = exports.getMessageBlocks = exports.normalizeGeminiBaseUrl = exports.normalizeAnthropicBaseUrl = exports.normalizeOpenAIBaseUrl = exports.normalizeBaseUrl = exports.withProxy = exports.getProxyDispatcher = exports.resolveProxyUrl = exports.GeminiProvider = exports.OpenAIProvider = exports.AnthropicProvider = void 0;
31
+ // Re-export provider implementations
32
+ var providers_1 = require("./providers");
33
+ Object.defineProperty(exports, "AnthropicProvider", { enumerable: true, get: function () { return providers_1.AnthropicProvider; } });
34
+ Object.defineProperty(exports, "OpenAIProvider", { enumerable: true, get: function () { return providers_1.OpenAIProvider; } });
35
+ Object.defineProperty(exports, "GeminiProvider", { enumerable: true, get: function () { return providers_1.GeminiProvider; } });
36
+ // Re-export utilities for backward compatibility
37
+ var providers_2 = require("./providers");
38
+ Object.defineProperty(exports, "resolveProxyUrl", { enumerable: true, get: function () { return providers_2.resolveProxyUrl; } });
39
+ Object.defineProperty(exports, "getProxyDispatcher", { enumerable: true, get: function () { return providers_2.getProxyDispatcher; } });
40
+ Object.defineProperty(exports, "withProxy", { enumerable: true, get: function () { return providers_2.withProxy; } });
41
+ Object.defineProperty(exports, "normalizeBaseUrl", { enumerable: true, get: function () { return providers_2.normalizeBaseUrl; } });
42
+ Object.defineProperty(exports, "normalizeOpenAIBaseUrl", { enumerable: true, get: function () { return providers_2.normalizeOpenAIBaseUrl; } });
43
+ Object.defineProperty(exports, "normalizeAnthropicBaseUrl", { enumerable: true, get: function () { return providers_2.normalizeAnthropicBaseUrl; } });
44
+ Object.defineProperty(exports, "normalizeGeminiBaseUrl", { enumerable: true, get: function () { return providers_2.normalizeGeminiBaseUrl; } });
45
+ Object.defineProperty(exports, "getMessageBlocks", { enumerable: true, get: function () { return providers_2.getMessageBlocks; } });
46
+ Object.defineProperty(exports, "markTransportIfDegraded", { enumerable: true, get: function () { return providers_2.markTransportIfDegraded; } });
47
+ Object.defineProperty(exports, "joinTextBlocks", { enumerable: true, get: function () { return providers_2.joinTextBlocks; } });
48
+ Object.defineProperty(exports, "formatToolResult", { enumerable: true, get: function () { return providers_2.formatToolResult; } });
49
+ Object.defineProperty(exports, "safeJsonStringify", { enumerable: true, get: function () { return providers_2.safeJsonStringify; } });
50
+ Object.defineProperty(exports, "FILE_UNSUPPORTED_TEXT", { enumerable: true, get: function () { return providers_2.FILE_UNSUPPORTED_TEXT; } });
51
+ Object.defineProperty(exports, "IMAGE_UNSUPPORTED_TEXT", { enumerable: true, get: function () { return providers_2.IMAGE_UNSUPPORTED_TEXT; } });
52
+ Object.defineProperty(exports, "AUDIO_UNSUPPORTED_TEXT", { enumerable: true, get: function () { return providers_2.AUDIO_UNSUPPORTED_TEXT; } });
53
+ Object.defineProperty(exports, "concatTextWithReasoning", { enumerable: true, get: function () { return providers_2.concatTextWithReasoning; } });
54
+ Object.defineProperty(exports, "joinReasoningBlocks", { enumerable: true, get: function () { return providers_2.joinReasoningBlocks; } });
55
+ Object.defineProperty(exports, "normalizeThinkBlocks", { enumerable: true, get: function () { return providers_2.normalizeThinkBlocks; } });
56
+ Object.defineProperty(exports, "splitThinkText", { enumerable: true, get: function () { return providers_2.splitThinkText; } });
57
+ Object.defineProperty(exports, "extractReasoningDetails", { enumerable: true, get: function () { return providers_2.extractReasoningDetails; } });
58
+ Object.defineProperty(exports, "buildGeminiImagePart", { enumerable: true, get: function () { return providers_2.buildGeminiImagePart; } });
59
+ Object.defineProperty(exports, "buildGeminiFilePart", { enumerable: true, get: function () { return providers_2.buildGeminiFilePart; } });
60
+ Object.defineProperty(exports, "sanitizeGeminiSchema", { enumerable: true, get: function () { return providers_2.sanitizeGeminiSchema; } });
61
+ Object.defineProperty(exports, "hasAnthropicFileBlocks", { enumerable: true, get: function () { return providers_2.hasAnthropicFileBlocks; } });
62
+ Object.defineProperty(exports, "mergeAnthropicBetaHeader", { enumerable: true, get: function () { return providers_2.mergeAnthropicBetaHeader; } });
63
+ Object.defineProperty(exports, "normalizeAnthropicContent", { enumerable: true, get: function () { return providers_2.normalizeAnthropicContent; } });
64
+ Object.defineProperty(exports, "normalizeAnthropicContentBlock", { enumerable: true, get: function () { return providers_2.normalizeAnthropicContentBlock; } });
65
+ Object.defineProperty(exports, "normalizeAnthropicDelta", { enumerable: true, get: function () { return providers_2.normalizeAnthropicDelta; } });
66
+ // Re-export core module (errors, usage, retry, logging, fork)
67
+ __exportStar(require("./providers/core"), exports);
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Anthropic Provider Adapter
3
+ *
4
+ * Converts internal Anthropic-style messages to Anthropic API format.
5
+ * Supports:
6
+ * - Extended thinking with interleaved-thinking-2025-05-14 beta
7
+ * - Files API with files-api-2025-04-14 beta
8
+ * - Streaming with SSE
9
+ * - Signature preservation for multi-turn conversations
10
+ */
11
+ import { Message } from '../../core/types';
12
+ import { ModelProvider, ModelResponse, ModelStreamChunk, ModelConfig, UploadFileInput, UploadFileResult, CompletionOptions, ReasoningTransport, ThinkingOptions } from './types';
13
+ export interface AnthropicProviderOptions {
14
+ reasoningTransport?: ReasoningTransport;
15
+ extraHeaders?: Record<string, string>;
16
+ extraBody?: Record<string, any>;
17
+ providerOptions?: Record<string, any>;
18
+ multimodal?: ModelConfig['multimodal'];
19
+ thinking?: ThinkingOptions;
20
+ }
21
+ export declare class AnthropicProvider implements ModelProvider {
22
+ private apiKey;
23
+ readonly maxWindowSize = 200000;
24
+ readonly maxOutputTokens = 4096;
25
+ readonly temperature = 0.7;
26
+ readonly model: string;
27
+ private readonly baseUrl;
28
+ private readonly dispatcher?;
29
+ private readonly reasoningTransport;
30
+ private readonly extraHeaders?;
31
+ private readonly extraBody?;
32
+ private readonly providerOptions?;
33
+ private readonly multimodal?;
34
+ private readonly thinking?;
35
+ constructor(apiKey: string, model?: string, baseUrl?: string, proxyUrl?: string, options?: AnthropicProviderOptions);
36
+ complete(messages: Message[], opts?: CompletionOptions): Promise<ModelResponse>;
37
+ stream(messages: Message[], opts?: CompletionOptions): AsyncIterable<ModelStreamChunk>;
38
+ private formatMessages;
39
+ private buildThinkingConfig;
40
+ uploadFile(input: UploadFileInput): Promise<UploadFileResult | null>;
41
+ toConfig(): ModelConfig;
42
+ }
@@ -0,0 +1,308 @@
1
+ "use strict";
2
+ /**
3
+ * Anthropic Provider Adapter
4
+ *
5
+ * Converts internal Anthropic-style messages to Anthropic API format.
6
+ * Supports:
7
+ * - Extended thinking with interleaved-thinking-2025-05-14 beta
8
+ * - Files API with files-api-2025-04-14 beta
9
+ * - Streaming with SSE
10
+ * - Signature preservation for multi-turn conversations
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.AnthropicProvider = void 0;
14
+ const utils_1 = require("./utils");
15
+ class AnthropicProvider {
16
+ constructor(apiKey, model = 'claude-3-5-sonnet-20241022', baseUrl = 'https://api.anthropic.com', proxyUrl, options) {
17
+ this.apiKey = apiKey;
18
+ this.maxWindowSize = 200000;
19
+ this.maxOutputTokens = 4096;
20
+ this.temperature = 0.7;
21
+ this.model = model;
22
+ this.baseUrl = (0, utils_1.normalizeAnthropicBaseUrl)(baseUrl);
23
+ this.dispatcher = (0, utils_1.getProxyDispatcher)(proxyUrl);
24
+ this.reasoningTransport = options?.reasoningTransport ?? 'provider';
25
+ this.extraHeaders = options?.extraHeaders;
26
+ this.extraBody = options?.extraBody;
27
+ this.providerOptions = options?.providerOptions;
28
+ this.multimodal = options?.multimodal;
29
+ this.thinking = options?.thinking;
30
+ }
31
+ async complete(messages, opts) {
32
+ const body = {
33
+ ...(this.extraBody || {}),
34
+ model: this.model,
35
+ messages: this.formatMessages(messages),
36
+ max_tokens: opts?.maxTokens || 4096,
37
+ };
38
+ if (opts?.temperature !== undefined)
39
+ body.temperature = opts.temperature;
40
+ if (opts?.system)
41
+ body.system = opts.system;
42
+ if (opts?.tools && opts.tools.length > 0)
43
+ body.tools = opts.tools;
44
+ const thinkingConfig = opts?.thinking ?? this.thinking;
45
+ if (this.reasoningTransport === 'provider' && !body.thinking) {
46
+ body.thinking = this.buildThinkingConfig(thinkingConfig);
47
+ }
48
+ const betaEntries = [];
49
+ if (this.reasoningTransport === 'provider') {
50
+ betaEntries.push('interleaved-thinking-2025-05-14');
51
+ }
52
+ if ((0, utils_1.hasAnthropicFileBlocks)(messages)) {
53
+ betaEntries.push('files-api-2025-04-14');
54
+ }
55
+ const headers = {
56
+ 'Content-Type': 'application/json',
57
+ 'x-api-key': this.apiKey,
58
+ 'anthropic-version': '2023-06-01',
59
+ ...(this.extraHeaders || {}),
60
+ };
61
+ const mergedBeta = (0, utils_1.mergeAnthropicBetaHeader)(headers['anthropic-beta'], betaEntries);
62
+ if (mergedBeta) {
63
+ headers['anthropic-beta'] = mergedBeta;
64
+ }
65
+ const response = await fetch(`${this.baseUrl}/v1/messages`, (0, utils_1.withProxy)({
66
+ method: 'POST',
67
+ headers,
68
+ body: JSON.stringify(body),
69
+ }, this.dispatcher));
70
+ if (!response.ok) {
71
+ const error = await response.text();
72
+ throw new Error(`Anthropic API error: ${response.status} ${error}`);
73
+ }
74
+ const data = await response.json();
75
+ const content = (0, utils_1.normalizeAnthropicContent)(data.content, this.reasoningTransport);
76
+ return {
77
+ role: 'assistant',
78
+ content,
79
+ usage: data.usage,
80
+ stop_reason: data.stop_reason,
81
+ };
82
+ }
83
+ async *stream(messages, opts) {
84
+ const body = {
85
+ model: this.model,
86
+ messages: this.formatMessages(messages),
87
+ max_tokens: opts?.maxTokens || 4096,
88
+ stream: true,
89
+ ...(this.extraBody || {}),
90
+ };
91
+ if (opts?.temperature !== undefined)
92
+ body.temperature = opts.temperature;
93
+ if (opts?.system)
94
+ body.system = opts.system;
95
+ if (opts?.tools && opts.tools.length > 0)
96
+ body.tools = opts.tools;
97
+ const thinkingConfig = opts?.thinking ?? this.thinking;
98
+ if (this.reasoningTransport === 'provider' && !body.thinking) {
99
+ body.thinking = this.buildThinkingConfig(thinkingConfig);
100
+ }
101
+ const betaEntries = [];
102
+ if (this.reasoningTransport === 'provider') {
103
+ betaEntries.push('interleaved-thinking-2025-05-14');
104
+ }
105
+ if ((0, utils_1.hasAnthropicFileBlocks)(messages)) {
106
+ betaEntries.push('files-api-2025-04-14');
107
+ }
108
+ const headers = {
109
+ 'Content-Type': 'application/json',
110
+ 'x-api-key': this.apiKey,
111
+ 'anthropic-version': '2023-06-01',
112
+ ...(this.extraHeaders || {}),
113
+ };
114
+ const mergedBeta = (0, utils_1.mergeAnthropicBetaHeader)(headers['anthropic-beta'], betaEntries);
115
+ if (mergedBeta) {
116
+ headers['anthropic-beta'] = mergedBeta;
117
+ }
118
+ const response = await fetch(`${this.baseUrl}/v1/messages`, (0, utils_1.withProxy)({
119
+ method: 'POST',
120
+ headers,
121
+ body: JSON.stringify(body),
122
+ }, this.dispatcher));
123
+ if (!response.ok) {
124
+ const error = await response.text();
125
+ throw new Error(`Anthropic API error: ${response.status} ${error}`);
126
+ }
127
+ const reader = response.body?.getReader();
128
+ if (!reader)
129
+ throw new Error('No response body');
130
+ const decoder = new TextDecoder();
131
+ let buffer = '';
132
+ while (true) {
133
+ const { done, value } = await reader.read();
134
+ if (done)
135
+ break;
136
+ buffer += decoder.decode(value, { stream: true });
137
+ const lines = buffer.split('\n');
138
+ buffer = lines.pop() || '';
139
+ for (const line of lines) {
140
+ if (!line.trim() || !line.startsWith('data: '))
141
+ continue;
142
+ const data = line.slice(6);
143
+ if (data === '[DONE]')
144
+ continue;
145
+ try {
146
+ const event = JSON.parse(data);
147
+ if (event.type === 'content_block_start') {
148
+ const block = (0, utils_1.normalizeAnthropicContentBlock)(event.content_block, this.reasoningTransport);
149
+ if (!block) {
150
+ continue;
151
+ }
152
+ yield { type: 'content_block_start', index: event.index, content_block: block };
153
+ }
154
+ else if (event.type === 'content_block_delta') {
155
+ const delta = (0, utils_1.normalizeAnthropicDelta)(event.delta);
156
+ yield { type: 'content_block_delta', index: event.index, delta };
157
+ }
158
+ else if (event.type === 'content_block_stop') {
159
+ yield { type: 'content_block_stop', index: event.index };
160
+ }
161
+ else if (event.type === 'message_delta') {
162
+ yield { type: 'message_delta', delta: event.delta, usage: event.usage };
163
+ }
164
+ else if (event.type === 'message_stop') {
165
+ yield { type: 'message_stop' };
166
+ }
167
+ }
168
+ catch {
169
+ // Skip invalid JSON
170
+ }
171
+ }
172
+ }
173
+ }
174
+ formatMessages(messages) {
175
+ return messages.map((msg) => {
176
+ const blocks = (0, utils_1.getMessageBlocks)(msg);
177
+ let degraded = false;
178
+ const content = blocks.map((block) => {
179
+ if (block.type === 'text') {
180
+ return { type: 'text', text: block.text };
181
+ }
182
+ if (block.type === 'reasoning') {
183
+ if (this.reasoningTransport === 'text') {
184
+ return { type: 'text', text: `<think>${block.reasoning}</think>` };
185
+ }
186
+ const result = { type: 'thinking', thinking: block.reasoning };
187
+ if (block.meta?.signature) {
188
+ result.signature = block.meta.signature;
189
+ }
190
+ return result;
191
+ }
192
+ if (block.type === 'image') {
193
+ if (block.base64 && block.mime_type) {
194
+ return {
195
+ type: 'image',
196
+ source: {
197
+ type: 'base64',
198
+ media_type: block.mime_type,
199
+ data: block.base64,
200
+ },
201
+ };
202
+ }
203
+ degraded = true;
204
+ return { type: 'text', text: utils_1.IMAGE_UNSUPPORTED_TEXT };
205
+ }
206
+ if (block.type === 'audio') {
207
+ degraded = true;
208
+ return { type: 'text', text: utils_1.AUDIO_UNSUPPORTED_TEXT };
209
+ }
210
+ if (block.type === 'file') {
211
+ if (block.file_id) {
212
+ return {
213
+ type: 'document',
214
+ source: { type: 'file', file_id: block.file_id },
215
+ };
216
+ }
217
+ degraded = true;
218
+ return { type: 'text', text: utils_1.FILE_UNSUPPORTED_TEXT };
219
+ }
220
+ if (block.type === 'tool_use') {
221
+ return {
222
+ type: 'tool_use',
223
+ id: block.id,
224
+ name: block.name,
225
+ input: block.input ?? {},
226
+ };
227
+ }
228
+ if (block.type === 'tool_result') {
229
+ return {
230
+ type: 'tool_result',
231
+ tool_use_id: block.tool_use_id,
232
+ content: (0, utils_1.formatToolResult)(block.content),
233
+ is_error: block.is_error,
234
+ };
235
+ }
236
+ return block;
237
+ });
238
+ if (degraded) {
239
+ (0, utils_1.markTransportIfDegraded)(msg, blocks);
240
+ }
241
+ return {
242
+ role: msg.role === 'system' ? 'user' : msg.role,
243
+ content,
244
+ };
245
+ });
246
+ }
247
+ buildThinkingConfig(thinking) {
248
+ if (!thinking?.enabled && !thinking?.budgetTokens) {
249
+ return { type: 'enabled' };
250
+ }
251
+ const config = { type: 'enabled' };
252
+ if (thinking?.budgetTokens) {
253
+ config.budget_tokens = thinking.budgetTokens;
254
+ }
255
+ return config;
256
+ }
257
+ async uploadFile(input) {
258
+ if (input.kind !== 'file') {
259
+ return null;
260
+ }
261
+ const FormDataCtor = globalThis.FormData;
262
+ const BlobCtor = globalThis.Blob;
263
+ if (!FormDataCtor || !BlobCtor) {
264
+ return null;
265
+ }
266
+ const endpoint = `${(0, utils_1.normalizeAnthropicBaseUrl)(this.baseUrl)}/v1/files`;
267
+ const form = new FormDataCtor();
268
+ form.append('file', new BlobCtor([input.data], { type: input.mimeType }), input.filename || 'file.pdf');
269
+ form.append('purpose', 'document');
270
+ const response = await fetch(endpoint, (0, utils_1.withProxy)({
271
+ method: 'POST',
272
+ headers: {
273
+ 'x-api-key': this.apiKey,
274
+ 'anthropic-version': '2023-06-01',
275
+ 'anthropic-beta': 'files-api-2025-04-14',
276
+ ...(this.extraHeaders || {}),
277
+ },
278
+ body: form,
279
+ }, this.dispatcher));
280
+ if (!response.ok) {
281
+ const error = await response.text();
282
+ throw new Error(`Anthropic file upload error: ${response.status} ${error}`);
283
+ }
284
+ const data = await response.json();
285
+ const fileId = data?.id ?? data?.file_id;
286
+ if (!fileId) {
287
+ return null;
288
+ }
289
+ return { fileId };
290
+ }
291
+ toConfig() {
292
+ return {
293
+ provider: 'anthropic',
294
+ model: this.model,
295
+ baseUrl: this.baseUrl,
296
+ apiKey: this.apiKey,
297
+ maxTokens: this.maxOutputTokens,
298
+ temperature: this.temperature,
299
+ reasoningTransport: this.reasoningTransport,
300
+ extraHeaders: this.extraHeaders,
301
+ extraBody: this.extraBody,
302
+ providerOptions: this.providerOptions,
303
+ multimodal: this.multimodal,
304
+ thinking: this.thinking,
305
+ };
306
+ }
307
+ }
308
+ exports.AnthropicProvider = AnthropicProvider;