@makaio/adapter-anthropic-sdk 1.0.0-dev-1779051654000
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/LICENSE +21 -0
- package/README.md +99 -0
- package/descriptor.json +21 -0
- package/dist/index.d.mts +1828 -0
- package/dist/index.mjs +1980 -0
- package/package.json +64 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,1980 @@
|
|
|
1
|
+
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
+
import { AIAdapter, ProceduralConnectorTurn, ScopedToolApprovalSchema, UserMessageQueue, createAdapterNamespace, createToolApprovalHandler, formatContextBlocksAsText, isTextLikeMimeType, mergeScopedToolApproval, normalizeMimeType, resolveConformanceTestPreset, resolveTestConfig, serializeBlockToText, serializeTurnContext } from "@makaio/framework/adapters";
|
|
3
|
+
import Anthropic, { APIError } from "@anthropic-ai/sdk";
|
|
4
|
+
import { AgentCompleteEventSchema, AgentStartedEventSchema, BaseStreamAgent, BaseStreamConnector, BaseStreamSession, ErrorEventSchema, MessageCompleteEventSchema, ReasoningCompleteEventSchema, ReasoningDeltaEventSchema, ToolCallSchema, ToolCompletedEventSchema, ToolStartedEventSchema, TurnStateChangedSchema, filterToolsWithSchema, handleToolCalls, loadToolsFromRegistry } from "@makaio/framework/adapters/stream-session";
|
|
5
|
+
import { createAdapterConfigFactory, resolveConnectorCredentials } from "@makaio/framework/adapters/config";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { AuthenticationError, ModelUnavailableError, QuotaExceededError, RateLimitError } from "@makaio/framework/core";
|
|
8
|
+
import { dep } from "@makaio/framework/contracts";
|
|
9
|
+
|
|
10
|
+
//#region src/types/index.ts
|
|
11
|
+
/**
|
|
12
|
+
* Anthropic SDK adapter namespace identifier.
|
|
13
|
+
*/
|
|
14
|
+
const ANTHROPIC_SDK_NAMESPACE = "adapter:anthropic-sdk";
|
|
15
|
+
|
|
16
|
+
//#endregion
|
|
17
|
+
//#region src/namespaces/schemas/chunk.ts
|
|
18
|
+
/**
|
|
19
|
+
* Schema for a text delta within a streaming chunk.
|
|
20
|
+
* Matches Anthropic TextDelta structure.
|
|
21
|
+
*/
|
|
22
|
+
const TextDeltaSchema = z.object({
|
|
23
|
+
type: z.literal("text_delta"),
|
|
24
|
+
text: z.string()
|
|
25
|
+
});
|
|
26
|
+
/**
|
|
27
|
+
* Schema for a thinking/reasoning delta within a streaming chunk.
|
|
28
|
+
* Matches Anthropic ThinkingDelta structure.
|
|
29
|
+
*/
|
|
30
|
+
const ThinkingDeltaSchema = z.object({
|
|
31
|
+
type: z.literal("thinking_delta"),
|
|
32
|
+
thinking: z.string()
|
|
33
|
+
});
|
|
34
|
+
/**
|
|
35
|
+
* Schema for a tool input JSON delta within a streaming chunk.
|
|
36
|
+
* Matches Anthropic InputJSONDelta structure.
|
|
37
|
+
*/
|
|
38
|
+
const InputJsonDeltaSchema = z.object({
|
|
39
|
+
type: z.literal("input_json_delta"),
|
|
40
|
+
partial_json: z.string()
|
|
41
|
+
});
|
|
42
|
+
/**
|
|
43
|
+
* Schema for the content block delta within a streaming chunk.
|
|
44
|
+
* Discriminated union of supported delta types.
|
|
45
|
+
*/
|
|
46
|
+
const ContentBlockDeltaSchema = z.discriminatedUnion("type", [
|
|
47
|
+
TextDeltaSchema,
|
|
48
|
+
ThinkingDeltaSchema,
|
|
49
|
+
InputJsonDeltaSchema
|
|
50
|
+
]);
|
|
51
|
+
/**
|
|
52
|
+
* Schema for streaming chunk event.
|
|
53
|
+
* Based on Anthropic RawContentBlockDeltaEvent structure.
|
|
54
|
+
* @see https://docs.anthropic.com/en/api/messages-streaming
|
|
55
|
+
*/
|
|
56
|
+
const ChunkEventSchema = z.object({
|
|
57
|
+
eventType: z.literal("chunk"),
|
|
58
|
+
/** Index of the content block this delta belongs to */
|
|
59
|
+
index: z.number(),
|
|
60
|
+
/** Content delta for this chunk */
|
|
61
|
+
delta: ContentBlockDeltaSchema
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
//#endregion
|
|
65
|
+
//#region src/namespaces/schemas/usage.ts
|
|
66
|
+
/**
|
|
67
|
+
* Schema for token usage event.
|
|
68
|
+
* Based on Anthropic Usage structure.
|
|
69
|
+
* @see https://docs.anthropic.com/en/api/messages
|
|
70
|
+
*/
|
|
71
|
+
const UsageEventSchema = z.object({
|
|
72
|
+
eventType: z.literal("usage"),
|
|
73
|
+
/** Number of tokens in the prompt (input) */
|
|
74
|
+
prompt_tokens: z.number(),
|
|
75
|
+
/** Number of tokens in the generated completion (output) */
|
|
76
|
+
completion_tokens: z.number(),
|
|
77
|
+
/** Total tokens used (prompt + completion) */
|
|
78
|
+
total_tokens: z.number(),
|
|
79
|
+
/** Number of tokens read from cache */
|
|
80
|
+
cache_read_input_tokens: z.number().optional(),
|
|
81
|
+
/** Number of tokens written to cache */
|
|
82
|
+
cache_creation_input_tokens: z.number().optional()
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
//#endregion
|
|
86
|
+
//#region src/namespaces/schemas/tool-calls.ts
|
|
87
|
+
/**
|
|
88
|
+
* Schema for a single tool call.
|
|
89
|
+
* Normalized from Anthropic ToolUseBlock structure.
|
|
90
|
+
* Extends the base schema with `blockIndex` for stable cross-event ordering.
|
|
91
|
+
*/
|
|
92
|
+
const ToolCallSchema$1 = ToolCallSchema.extend({
|
|
93
|
+
/** Original Anthropic content block index (for stable cross-event ordering). */
|
|
94
|
+
blockIndex: z.number().int().nonnegative() });
|
|
95
|
+
/**
|
|
96
|
+
* Schema for tool calls event.
|
|
97
|
+
* Emitted when the model requests tool/function execution.
|
|
98
|
+
*/
|
|
99
|
+
const ToolCallsEventSchema = z.object({
|
|
100
|
+
eventType: z.literal("tool_calls"),
|
|
101
|
+
/** Array of tool calls requested by the model */
|
|
102
|
+
toolCalls: z.array(ToolCallSchema$1)
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
//#endregion
|
|
106
|
+
//#region src/namespaces/schemas/message.ts
|
|
107
|
+
/**
|
|
108
|
+
* Schema for tool call in message complete event.
|
|
109
|
+
* Matches Anthropic ToolUseBlock structure normalized for adapter use.
|
|
110
|
+
*/
|
|
111
|
+
const MessageToolCallSchema = z.object({
|
|
112
|
+
id: z.string(),
|
|
113
|
+
/** Original Anthropic content block index for step reconstruction. */
|
|
114
|
+
blockIndex: z.number().int().nonnegative(),
|
|
115
|
+
type: z.literal("function"),
|
|
116
|
+
function: z.object({
|
|
117
|
+
name: z.string(),
|
|
118
|
+
arguments: z.string()
|
|
119
|
+
})
|
|
120
|
+
});
|
|
121
|
+
/**
|
|
122
|
+
* Schema for message complete event.
|
|
123
|
+
* Emitted when a full assistant message has been assembled from streaming chunks.
|
|
124
|
+
* Extends the base schema with Anthropic-specific `finish_reason` values
|
|
125
|
+
* (including `pause_turn`) and the `blockIndex` field on tool calls.
|
|
126
|
+
*/
|
|
127
|
+
const MessageCompleteEventSchema$1 = MessageCompleteEventSchema.extend({
|
|
128
|
+
/** Tool calls requested by the model. */
|
|
129
|
+
tool_calls: z.array(MessageToolCallSchema).optional(),
|
|
130
|
+
/** Why generation stopped (Anthropic-specific values). */
|
|
131
|
+
finish_reason: z.enum([
|
|
132
|
+
"end_turn",
|
|
133
|
+
"max_tokens",
|
|
134
|
+
"stop_sequence",
|
|
135
|
+
"tool_use",
|
|
136
|
+
"pause_turn"
|
|
137
|
+
]).nullable()
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
//#endregion
|
|
141
|
+
//#region src/namespaces/schemas/reasoning.ts
|
|
142
|
+
/**
|
|
143
|
+
* Schema for reasoning delta event.
|
|
144
|
+
* Emitted during streaming when the model outputs extended thinking content.
|
|
145
|
+
* Supported by Anthropic models with extended thinking enabled.
|
|
146
|
+
*/
|
|
147
|
+
const ReasoningDeltaEventSchema$1 = ReasoningDeltaEventSchema;
|
|
148
|
+
/**
|
|
149
|
+
* Schema for reasoning complete event.
|
|
150
|
+
* Emitted when full reasoning/thinking content has been assembled.
|
|
151
|
+
* Extends the base schema with the Anthropic-specific `signature` field.
|
|
152
|
+
*/
|
|
153
|
+
const ReasoningCompleteEventSchema$1 = ReasoningCompleteEventSchema.extend({
|
|
154
|
+
/**
|
|
155
|
+
* Optional Anthropic thinking signature assembled from `signature_delta`.
|
|
156
|
+
* Persisted as reasoning block metadata for native history round-trip.
|
|
157
|
+
*/
|
|
158
|
+
signature: z.string().optional() });
|
|
159
|
+
|
|
160
|
+
//#endregion
|
|
161
|
+
//#region src/namespaces/index.ts
|
|
162
|
+
/**
|
|
163
|
+
* Discriminated union of all SDK event types.
|
|
164
|
+
* Uses discriminatedUnion for type-safe event routing based on eventType.
|
|
165
|
+
* Turn lifecycle events use dedicated `turn.*` subjects below because the shared
|
|
166
|
+
* stream-session state schema is keyed by state transition fields, not `eventType`.
|
|
167
|
+
*/
|
|
168
|
+
const SdkEventMessageSchema = z.discriminatedUnion("eventType", [
|
|
169
|
+
ChunkEventSchema,
|
|
170
|
+
UsageEventSchema,
|
|
171
|
+
ToolCallsEventSchema,
|
|
172
|
+
MessageCompleteEventSchema$1,
|
|
173
|
+
ReasoningDeltaEventSchema$1,
|
|
174
|
+
ReasoningCompleteEventSchema$1,
|
|
175
|
+
AgentStartedEventSchema,
|
|
176
|
+
AgentCompleteEventSchema,
|
|
177
|
+
ErrorEventSchema,
|
|
178
|
+
ToolStartedEventSchema,
|
|
179
|
+
ToolCompletedEventSchema
|
|
180
|
+
]);
|
|
181
|
+
/**
|
|
182
|
+
* Envelope schema for sdk.event catch-all subject.
|
|
183
|
+
* Wraps the discriminated union in an envelope for proper TypeScript narrowing at emit time.
|
|
184
|
+
* Pattern matches codex-mcp's \{ id, msg \} envelope.
|
|
185
|
+
*/
|
|
186
|
+
const SdkEventSchema = z.object({
|
|
187
|
+
event: SdkEventMessageSchema,
|
|
188
|
+
adapterName: z.string().optional(),
|
|
189
|
+
agentId: z.string().optional(),
|
|
190
|
+
adapterId: z.string().optional(),
|
|
191
|
+
adapterSessionId: z.string().optional(),
|
|
192
|
+
sessionId: z.string().optional()
|
|
193
|
+
});
|
|
194
|
+
/**
|
|
195
|
+
* Schema for raw Anthropic streaming events.
|
|
196
|
+
* Passthrough schema for observability - captures raw API response.
|
|
197
|
+
* Used by stream-bridge to emit unprocessed events before normalization.
|
|
198
|
+
*/
|
|
199
|
+
const RawChunkSchema = z.custom(() => true);
|
|
200
|
+
/**
|
|
201
|
+
* Anthropic SDK Adapter Namespace with semantic subjects.
|
|
202
|
+
*
|
|
203
|
+
* Provides typed subjects for:
|
|
204
|
+
* - sdk.event: Catch-all for raw SDK events (for observability/debugging)
|
|
205
|
+
* - tool_approval: RPC for tool execution approval
|
|
206
|
+
* - Semantic subjects: Individual typed events for agent layer processing
|
|
207
|
+
*/
|
|
208
|
+
const AnthropicSdkConnectorNamespace = createAdapterNamespace(ANTHROPIC_SDK_NAMESPACE, {
|
|
209
|
+
"sdk.raw": RawChunkSchema,
|
|
210
|
+
"sdk.event": SdkEventSchema,
|
|
211
|
+
tool_approval: ScopedToolApprovalSchema,
|
|
212
|
+
chunk: ChunkEventSchema,
|
|
213
|
+
usage: UsageEventSchema,
|
|
214
|
+
message_complete: MessageCompleteEventSchema$1,
|
|
215
|
+
reasoning_delta: ReasoningDeltaEventSchema$1,
|
|
216
|
+
reasoning_complete: ReasoningCompleteEventSchema$1,
|
|
217
|
+
tool_calls: ToolCallsEventSchema,
|
|
218
|
+
tool_started: ToolStartedEventSchema,
|
|
219
|
+
tool_completed: ToolCompletedEventSchema,
|
|
220
|
+
agent_started: AgentStartedEventSchema,
|
|
221
|
+
agent_complete: AgentCompleteEventSchema,
|
|
222
|
+
error: ErrorEventSchema,
|
|
223
|
+
"turn.state_changed": TurnStateChangedSchema,
|
|
224
|
+
"turn.turn_started": TurnStateChangedSchema,
|
|
225
|
+
"turn.step_started": TurnStateChangedSchema,
|
|
226
|
+
"turn.step_finished": TurnStateChangedSchema,
|
|
227
|
+
"turn.turn_finished": TurnStateChangedSchema
|
|
228
|
+
});
|
|
229
|
+
/**
|
|
230
|
+
* Typed subject literals for Anthropic SDK adapter.
|
|
231
|
+
* Use these constants to subscribe to specific message types with full type safety.
|
|
232
|
+
* @example
|
|
233
|
+
* ```typescript
|
|
234
|
+
* connector.on(AnthropicSdkSubjects.chunk, (ctx) => {
|
|
235
|
+
* // ctx.payload is typed as ChunkEvent
|
|
236
|
+
* console.debug(ctx.payload.delta);
|
|
237
|
+
* });
|
|
238
|
+
* ```
|
|
239
|
+
*/
|
|
240
|
+
const AnthropicSdkConnectorSubjects = AnthropicSdkConnectorNamespace.subjects;
|
|
241
|
+
|
|
242
|
+
//#endregion
|
|
243
|
+
//#region src/tool-handling.ts
|
|
244
|
+
const ADAPTER_LABEL = "AnthropicSdkAgent";
|
|
245
|
+
/**
|
|
246
|
+
* Register tool approval handler on scoped connector.
|
|
247
|
+
*
|
|
248
|
+
* Wires AnthropicSdkConnectorSubjects.tool_approval → AgentSubjects.toolApprove.
|
|
249
|
+
* Used by agent.ts wireToolApprovalRpc() for consistent approval flow.
|
|
250
|
+
*
|
|
251
|
+
* The handler receives `AgentToolApproveRequest` from the connector (already
|
|
252
|
+
* transformed via toGlobalToolApproval), enriches with context if needed,
|
|
253
|
+
* and forwards to global MakaioBus.
|
|
254
|
+
* @param connector - Anthropic SDK connector (needs only `on` method)
|
|
255
|
+
* @param context - Adapter context for request enrichment (static or lazy callback)
|
|
256
|
+
* @returns Unsubscribe function
|
|
257
|
+
*/
|
|
258
|
+
const registerToolApprovalHandler = createToolApprovalHandler(AnthropicSdkConnectorSubjects.tool_approval, (payload, context) => mergeScopedToolApproval(payload, context, "anthropic-sdk"), (response) => response);
|
|
259
|
+
/**
|
|
260
|
+
* Convert ToolListItem[] to Anthropic Tool[] format.
|
|
261
|
+
*
|
|
262
|
+
* Filters to only tools with inputSchema (required for Anthropic tool use).
|
|
263
|
+
* Maps name, description, and input_schema to Anthropic's expected structure.
|
|
264
|
+
* @param tools - Tools from ToolRegistry
|
|
265
|
+
* @returns Anthropic-formatted tools
|
|
266
|
+
*/
|
|
267
|
+
function toAnthropicToolFormat(tools) {
|
|
268
|
+
return filterToolsWithSchema(tools).map((tool) => ({
|
|
269
|
+
name: tool.name,
|
|
270
|
+
description: tool.description,
|
|
271
|
+
input_schema: tool.inputSchema
|
|
272
|
+
}));
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Convenience: Load tools and convert to Anthropic format in one call.
|
|
276
|
+
* @param adapterId - Adapter instance ID
|
|
277
|
+
* @param adapterName - Adapter type name
|
|
278
|
+
* @returns Anthropic-formatted tools ready for messages.create
|
|
279
|
+
*/
|
|
280
|
+
async function fetchToolsForAnthropic(adapterId, adapterName) {
|
|
281
|
+
return toAnthropicToolFormat(await loadToolsFromRegistry(adapterId, adapterName));
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Process tool calls: request approval, execute, and return tool result blocks.
|
|
285
|
+
*
|
|
286
|
+
* Returns Anthropic-format tool results: `{ role: 'user', content: [{ type: 'tool_result', ... }] }`
|
|
287
|
+
* is assembled by the caller using the returned ToolResultBlockParam[].
|
|
288
|
+
* @param toolCalls - Array of normalized tool calls from the stream-bridge tool_calls event
|
|
289
|
+
* @param callbacks - Injected callbacks for event emission, approval requests, and optional ledger recording
|
|
290
|
+
* @param contextOverrides - Execution context (cwd, env, sessionId, agentId, turnId)
|
|
291
|
+
* @returns Tool result blocks to inject into the next user message
|
|
292
|
+
*/
|
|
293
|
+
async function handleToolCalls$1(toolCalls, callbacks, contextOverrides) {
|
|
294
|
+
return handleToolCalls(toolCalls, callbacks, contextOverrides, (toolCallId, content, isError) => ({
|
|
295
|
+
type: "tool_result",
|
|
296
|
+
tool_use_id: toolCallId,
|
|
297
|
+
content,
|
|
298
|
+
is_error: isError
|
|
299
|
+
}), ADAPTER_LABEL);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
//#endregion
|
|
303
|
+
//#region src/turn.ts
|
|
304
|
+
/**
|
|
305
|
+
* Turn state machine for the Anthropic SDK adapter.
|
|
306
|
+
*
|
|
307
|
+
* Tracks state transitions for a single user message.
|
|
308
|
+
* Unlike Claude Code, the Anthropic SDK adapter has no true pause/resume —
|
|
309
|
+
* we abort and restart the request with merged content instead.
|
|
310
|
+
*
|
|
311
|
+
* State flow:
|
|
312
|
+
* idle → turn_started → step_started → step_finished → turn_finished
|
|
313
|
+
*
|
|
314
|
+
* On immediate: abort current turn, merge content, start new turn.
|
|
315
|
+
*/
|
|
316
|
+
var AnthropicSdkConnectorTurn = class extends ProceduralConnectorTurn {
|
|
317
|
+
abortController;
|
|
318
|
+
constructor(bus, adapterId, adapterName, agentId, messageHandle) {
|
|
319
|
+
super({
|
|
320
|
+
bus,
|
|
321
|
+
adapterId,
|
|
322
|
+
adapterName,
|
|
323
|
+
agentId,
|
|
324
|
+
messageHandle,
|
|
325
|
+
turnSubjects: AnthropicSdkConnectorSubjects.turn
|
|
326
|
+
}, "idle");
|
|
327
|
+
this.abortController = new AbortController();
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Get the AbortSignal for this turn.
|
|
331
|
+
* Pass to the Anthropic client stream for cancellation.
|
|
332
|
+
* @returns The abort signal for this turn
|
|
333
|
+
*/
|
|
334
|
+
getAbortSignal() {
|
|
335
|
+
return this.abortController.signal;
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Pause (abort) at next opportunity.
|
|
339
|
+
* The Anthropic SDK adapter does not support true pause — caller restarts
|
|
340
|
+
* with merged content when a replacement turn arrives.
|
|
341
|
+
* @returns Pause result indicating turn state
|
|
342
|
+
*/
|
|
343
|
+
async pause() {
|
|
344
|
+
const result = await super.pause();
|
|
345
|
+
if (!result.turnEnded) this.abortController.abort();
|
|
346
|
+
return result;
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
|
|
350
|
+
//#endregion
|
|
351
|
+
//#region src/stream-bridge.ts
|
|
352
|
+
/**
|
|
353
|
+
* Create a fresh stream processing state object.
|
|
354
|
+
* @returns Empty initial state.
|
|
355
|
+
*/
|
|
356
|
+
function createStreamState() {
|
|
357
|
+
return {
|
|
358
|
+
content: "",
|
|
359
|
+
reasoning: "",
|
|
360
|
+
reasoningSignature: void 0,
|
|
361
|
+
stopReason: null,
|
|
362
|
+
usage: null,
|
|
363
|
+
toolCalls: [],
|
|
364
|
+
contentBlocks: /* @__PURE__ */ new Map()
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Merge Anthropic's initial Usage object (from message_start) into MergedUsage.
|
|
369
|
+
* @param usage - Usage from the message_start event.
|
|
370
|
+
* @returns MergedUsage with input token counts.
|
|
371
|
+
*/
|
|
372
|
+
function mergeInitialUsage(usage) {
|
|
373
|
+
return {
|
|
374
|
+
inputTokens: usage.input_tokens,
|
|
375
|
+
outputTokens: 0,
|
|
376
|
+
cacheReadInputTokens: usage.cache_read_input_tokens ?? void 0,
|
|
377
|
+
cacheCreationInputTokens: usage.cache_creation_input_tokens ?? void 0
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Merge output-token delta usage (from message_delta) into existing MergedUsage.
|
|
382
|
+
* @param existing - MergedUsage populated from message_start.
|
|
383
|
+
* @param delta - MessageDeltaUsage from the message_delta event.
|
|
384
|
+
* @returns Updated MergedUsage with output token counts.
|
|
385
|
+
*/
|
|
386
|
+
function mergeDeltaUsage(existing, delta) {
|
|
387
|
+
return {
|
|
388
|
+
...existing,
|
|
389
|
+
outputTokens: delta.output_tokens,
|
|
390
|
+
cacheReadInputTokens: delta.cache_read_input_tokens ?? existing.cacheReadInputTokens,
|
|
391
|
+
cacheCreationInputTokens: delta.cache_creation_input_tokens ?? existing.cacheCreationInputTokens
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* Build an EventEmitter bound to the given bus and identity metadata.
|
|
396
|
+
* @param config - Stream bridge configuration providing bus and identity.
|
|
397
|
+
* @param metadata - Envelope metadata attached to every emitted event.
|
|
398
|
+
* @returns Async emitter for SdkEventMessage payloads.
|
|
399
|
+
*/
|
|
400
|
+
function buildEventEmitter(config, metadata) {
|
|
401
|
+
return async (event) => {
|
|
402
|
+
await config.bus.emit(AnthropicSdkConnectorSubjects.sdk.event, {
|
|
403
|
+
event,
|
|
404
|
+
...metadata
|
|
405
|
+
});
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* Handle content_block_delta: accumulate delta content and emit streaming events.
|
|
410
|
+
* @param index - Content block index from the stream event.
|
|
411
|
+
* @param event - The full content_block_delta event.
|
|
412
|
+
* @param state - Mutable stream state.
|
|
413
|
+
* @param emitEvent - Normalized event emitter.
|
|
414
|
+
*/
|
|
415
|
+
async function handleContentBlockDelta(index, event, state, emitEvent) {
|
|
416
|
+
const block = state.contentBlocks.get(index);
|
|
417
|
+
const rawDelta = event.delta;
|
|
418
|
+
if (rawDelta.type === "text_delta") {
|
|
419
|
+
if (block) block.text = (block.text ?? "") + rawDelta.text;
|
|
420
|
+
state.content += rawDelta.text;
|
|
421
|
+
await emitEvent({
|
|
422
|
+
eventType: "chunk",
|
|
423
|
+
index,
|
|
424
|
+
delta: {
|
|
425
|
+
type: "text_delta",
|
|
426
|
+
text: rawDelta.text
|
|
427
|
+
}
|
|
428
|
+
});
|
|
429
|
+
} else if (rawDelta.type === "thinking_delta") {
|
|
430
|
+
if (block) block.thinking = (block.thinking ?? "") + rawDelta.thinking;
|
|
431
|
+
state.reasoning += rawDelta.thinking;
|
|
432
|
+
await emitEvent({
|
|
433
|
+
eventType: "reasoning_delta",
|
|
434
|
+
content: rawDelta.thinking
|
|
435
|
+
});
|
|
436
|
+
await emitEvent({
|
|
437
|
+
eventType: "chunk",
|
|
438
|
+
index,
|
|
439
|
+
delta: {
|
|
440
|
+
type: "thinking_delta",
|
|
441
|
+
thinking: rawDelta.thinking
|
|
442
|
+
}
|
|
443
|
+
});
|
|
444
|
+
} else if (rawDelta.type === "input_json_delta") {
|
|
445
|
+
if (block) block.jsonAccumulator = (block.jsonAccumulator ?? "") + rawDelta.partial_json;
|
|
446
|
+
await emitEvent({
|
|
447
|
+
eventType: "chunk",
|
|
448
|
+
index,
|
|
449
|
+
delta: {
|
|
450
|
+
type: "input_json_delta",
|
|
451
|
+
partial_json: rawDelta.partial_json
|
|
452
|
+
}
|
|
453
|
+
});
|
|
454
|
+
} else if (rawDelta.type === "signature_delta") {
|
|
455
|
+
if (block) block.signature = (block.signature ?? "") + rawDelta.signature;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
/**
|
|
459
|
+
* Handle content_block_stop: finalize the block and harvest completed tool calls.
|
|
460
|
+
* @param index - Content block index from the stream event.
|
|
461
|
+
* @param state - Mutable stream state.
|
|
462
|
+
*/
|
|
463
|
+
function handleContentBlockStop(index, state) {
|
|
464
|
+
const block = state.contentBlocks.get(index);
|
|
465
|
+
if (!block) return;
|
|
466
|
+
if (block.type === "thinking" && block.signature && state.reasoningSignature === void 0) state.reasoningSignature = block.signature;
|
|
467
|
+
if (block.type === "tool_use" && block.toolId && block.toolName !== void 0) state.toolCalls.push({
|
|
468
|
+
id: block.toolId,
|
|
469
|
+
name: block.toolName,
|
|
470
|
+
arguments: block.jsonAccumulator?.trim() ? block.jsonAccumulator : "{}",
|
|
471
|
+
blockIndex: index
|
|
472
|
+
});
|
|
473
|
+
state.contentBlocks.delete(index);
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* Emit final semantic events once the stream has ended.
|
|
477
|
+
* @param state - Final aggregated stream state.
|
|
478
|
+
* @param emitEvent - Normalized event emitter.
|
|
479
|
+
*/
|
|
480
|
+
async function emitFinalEvents(state, emitEvent) {
|
|
481
|
+
if (state.usage) {
|
|
482
|
+
const { inputTokens, outputTokens, cacheReadInputTokens, cacheCreationInputTokens } = state.usage;
|
|
483
|
+
await emitEvent({
|
|
484
|
+
eventType: "usage",
|
|
485
|
+
prompt_tokens: inputTokens,
|
|
486
|
+
completion_tokens: outputTokens,
|
|
487
|
+
total_tokens: inputTokens + outputTokens,
|
|
488
|
+
cache_read_input_tokens: cacheReadInputTokens ?? 0,
|
|
489
|
+
cache_creation_input_tokens: cacheCreationInputTokens ?? 0
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
const toolCallPayload = state.toolCalls.length > 0 ? state.toolCalls.map((tc) => ({
|
|
493
|
+
id: tc.id,
|
|
494
|
+
blockIndex: tc.blockIndex,
|
|
495
|
+
type: "function",
|
|
496
|
+
function: {
|
|
497
|
+
name: tc.name,
|
|
498
|
+
arguments: tc.arguments
|
|
499
|
+
}
|
|
500
|
+
})) : void 0;
|
|
501
|
+
if (toolCallPayload) await emitEvent({
|
|
502
|
+
eventType: "tool_calls",
|
|
503
|
+
toolCalls: toolCallPayload
|
|
504
|
+
});
|
|
505
|
+
if (state.reasoning) await emitEvent({
|
|
506
|
+
eventType: "reasoning_complete",
|
|
507
|
+
content: state.reasoning,
|
|
508
|
+
...state.reasoningSignature !== void 0 ? { signature: state.reasoningSignature } : {}
|
|
509
|
+
});
|
|
510
|
+
await emitEvent({
|
|
511
|
+
eventType: "message_complete",
|
|
512
|
+
content: state.content || null,
|
|
513
|
+
reasoning: state.reasoning || void 0,
|
|
514
|
+
tool_calls: toolCallPayload,
|
|
515
|
+
finish_reason: state.stopReason ?? null
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* Processes an Anthropic message stream and emits normalized bus events.
|
|
520
|
+
*
|
|
521
|
+
* Translates Anthropic's block-based streaming protocol (message_start →
|
|
522
|
+
* content_block_start → content_block_delta → content_block_stop →
|
|
523
|
+
* message_delta → message_stop) into semantic adapter events.
|
|
524
|
+
*
|
|
525
|
+
* Emits to bus as the stream progresses:
|
|
526
|
+
* - sdk.raw: Each raw Anthropic event (observability)
|
|
527
|
+
* - sdk.event: Semantic events — chunk, reasoning_delta, reasoning_complete, usage, tool_calls, message_complete
|
|
528
|
+
* @param stream - The Anthropic streaming response.
|
|
529
|
+
* @param config - Bridge configuration with bus, agent identity, and model.
|
|
530
|
+
*/
|
|
531
|
+
async function processStream(stream, config) {
|
|
532
|
+
const state = createStreamState();
|
|
533
|
+
const metadata = {
|
|
534
|
+
adapterName: config.adapterName,
|
|
535
|
+
agentId: config.agentId,
|
|
536
|
+
adapterId: config.adapterId
|
|
537
|
+
};
|
|
538
|
+
const emitEvent = buildEventEmitter(config, config.adapterSessionId ? {
|
|
539
|
+
...metadata,
|
|
540
|
+
adapterSessionId: config.adapterSessionId
|
|
541
|
+
} : metadata);
|
|
542
|
+
for await (const event of stream) {
|
|
543
|
+
config.logLowLevelEvent?.(event);
|
|
544
|
+
await config.bus.emit(AnthropicSdkConnectorSubjects.sdk.raw, event);
|
|
545
|
+
switch (event.type) {
|
|
546
|
+
case "message_start":
|
|
547
|
+
state.usage = mergeInitialUsage(event.message.usage);
|
|
548
|
+
break;
|
|
549
|
+
case "content_block_start": {
|
|
550
|
+
const cb = event.content_block;
|
|
551
|
+
if (cb.type === "text") state.contentBlocks.set(event.index, {
|
|
552
|
+
type: "text",
|
|
553
|
+
text: ""
|
|
554
|
+
});
|
|
555
|
+
else if (cb.type === "tool_use") state.contentBlocks.set(event.index, {
|
|
556
|
+
type: "tool_use",
|
|
557
|
+
toolId: cb.id,
|
|
558
|
+
toolName: cb.name,
|
|
559
|
+
jsonAccumulator: ""
|
|
560
|
+
});
|
|
561
|
+
else if (cb.type === "thinking") state.contentBlocks.set(event.index, {
|
|
562
|
+
type: "thinking",
|
|
563
|
+
thinking: "",
|
|
564
|
+
signature: ""
|
|
565
|
+
});
|
|
566
|
+
break;
|
|
567
|
+
}
|
|
568
|
+
case "content_block_delta":
|
|
569
|
+
await handleContentBlockDelta(event.index, event, state, emitEvent);
|
|
570
|
+
break;
|
|
571
|
+
case "content_block_stop":
|
|
572
|
+
handleContentBlockStop(event.index, state);
|
|
573
|
+
break;
|
|
574
|
+
case "message_delta":
|
|
575
|
+
state.stopReason = event.delta.stop_reason ?? null;
|
|
576
|
+
if (state.usage) state.usage = mergeDeltaUsage(state.usage, event.usage);
|
|
577
|
+
break;
|
|
578
|
+
case "message_stop": break;
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
await emitFinalEvents(state, emitEvent);
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
//#endregion
|
|
585
|
+
//#region src/utils/convertMessageHistory.ts
|
|
586
|
+
/** Valid media types for Anthropic base64 image sources. */
|
|
587
|
+
const VALID_IMAGE_MEDIA_TYPES = [
|
|
588
|
+
"image/jpeg",
|
|
589
|
+
"image/png",
|
|
590
|
+
"image/gif",
|
|
591
|
+
"image/webp"
|
|
592
|
+
];
|
|
593
|
+
/**
|
|
594
|
+
* Resolve a MIME type against an allowed set, returning a fallback when absent or unrecognised.
|
|
595
|
+
* @param mimeType - MIME type string from the content source, if present.
|
|
596
|
+
* @param validTypes - Read-only tuple of accepted MIME type literals.
|
|
597
|
+
* @param fallback - Value to return when `mimeType` is absent or not in `validTypes`.
|
|
598
|
+
* @returns The matched type or `fallback`.
|
|
599
|
+
*/
|
|
600
|
+
function resolveMediaType(mimeType, validTypes, fallback) {
|
|
601
|
+
if (mimeType !== void 0 && validTypes.includes(mimeType)) return mimeType;
|
|
602
|
+
return fallback;
|
|
603
|
+
}
|
|
604
|
+
/**
|
|
605
|
+
* Resolve the `media_type` for an Anthropic base64 image source.
|
|
606
|
+
*
|
|
607
|
+
* Falls back to `'image/jpeg'` when the MIME type is absent or not in the
|
|
608
|
+
* set of types the Anthropic API accepts.
|
|
609
|
+
* @param mimeType - MIME type string from the content source, if present.
|
|
610
|
+
* @returns A valid Anthropic image media type.
|
|
611
|
+
*/
|
|
612
|
+
function resolveImageMediaType(mimeType) {
|
|
613
|
+
return resolveMediaType(mimeType, VALID_IMAGE_MEDIA_TYPES, "image/jpeg");
|
|
614
|
+
}
|
|
615
|
+
/**
|
|
616
|
+
* Convert a {@link ContentSource} to a native Anthropic {@link ImageBlockParam}.
|
|
617
|
+
* @param source - The content source for the image block.
|
|
618
|
+
* @param normalizedMimeType - Pre-normalized MIME type to use instead of `source.mimeType`.
|
|
619
|
+
* When provided, the caller's value is preferred; `source.mimeType` is always normalized
|
|
620
|
+
* before comparison regardless.
|
|
621
|
+
* @returns An Anthropic `ImageBlockParam`.
|
|
622
|
+
*/
|
|
623
|
+
function imageSourceToParam(source, normalizedMimeType) {
|
|
624
|
+
if (source.type === "base64") return {
|
|
625
|
+
type: "image",
|
|
626
|
+
source: {
|
|
627
|
+
type: "base64",
|
|
628
|
+
data: source.data,
|
|
629
|
+
media_type: resolveImageMediaType(normalizedMimeType ?? normalizeMimeType(source.mimeType))
|
|
630
|
+
}
|
|
631
|
+
};
|
|
632
|
+
return {
|
|
633
|
+
type: "image",
|
|
634
|
+
source: {
|
|
635
|
+
type: "url",
|
|
636
|
+
url: source.url
|
|
637
|
+
}
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* Convert a {@link ContentSource} to a native Anthropic {@link DocumentBlockParam}.
|
|
642
|
+
*
|
|
643
|
+
* Selects the correct Anthropic source shape based on the normalized media type:
|
|
644
|
+
* - `'text/plain'` maps to {@link PlainTextSource} (`type: 'text'`).
|
|
645
|
+
* - All other accepted types (or absent/unknown MIME) map to {@link Base64PDFSource}
|
|
646
|
+
* (`type: 'base64'`, `media_type: 'application/pdf'`).
|
|
647
|
+
* @param source - The content source for the document block.
|
|
648
|
+
* @returns An Anthropic `DocumentBlockParam`.
|
|
649
|
+
*/
|
|
650
|
+
function documentSourceToParam(source) {
|
|
651
|
+
if (source.type === "base64") {
|
|
652
|
+
if (normalizeMimeType(source.mimeType) === "text/plain") return {
|
|
653
|
+
type: "document",
|
|
654
|
+
source: {
|
|
655
|
+
type: "text",
|
|
656
|
+
data: Buffer.from(source.data, "base64").toString("utf8"),
|
|
657
|
+
media_type: "text/plain"
|
|
658
|
+
}
|
|
659
|
+
};
|
|
660
|
+
return {
|
|
661
|
+
type: "document",
|
|
662
|
+
source: {
|
|
663
|
+
type: "base64",
|
|
664
|
+
data: source.data,
|
|
665
|
+
media_type: "application/pdf"
|
|
666
|
+
}
|
|
667
|
+
};
|
|
668
|
+
}
|
|
669
|
+
return {
|
|
670
|
+
type: "document",
|
|
671
|
+
source: {
|
|
672
|
+
type: "url",
|
|
673
|
+
url: source.url
|
|
674
|
+
}
|
|
675
|
+
};
|
|
676
|
+
}
|
|
677
|
+
/**
|
|
678
|
+
* Convert a single user {@link MessageBlock} to an Anthropic {@link UserContentBlock}.
|
|
679
|
+
*
|
|
680
|
+
* - `text` blocks become `TextBlockParam`.
|
|
681
|
+
* - `image` blocks become native `ImageBlockParam`.
|
|
682
|
+
* - `document` blocks become native `DocumentBlockParam`.
|
|
683
|
+
* - `attachment` blocks are mapped by the normalized `source.mimeType`: Anthropic-supported image types
|
|
684
|
+
* (`image/jpeg`, `image/png`, `image/gif`, `image/webp`) produce `ImageBlockParam`; unsupported image
|
|
685
|
+
* variants (e.g. `image/svg+xml`) fall through to the text path; `application/pdf` produces a base64
|
|
686
|
+
* `DocumentBlockParam`; text-like MIME types (including those with parameters like "text/plain; charset=utf-8")
|
|
687
|
+
* produce a decoded plain-text `DocumentBlockParam`; all other MIME types or non-base64 sources fall back to
|
|
688
|
+
* `TextBlockParam`.
|
|
689
|
+
* - All other block types fall back to a `TextBlockParam` via `serializeBlockToText`.
|
|
690
|
+
* @param block - The message block to convert.
|
|
691
|
+
* @returns An Anthropic user content block.
|
|
692
|
+
*/
|
|
693
|
+
function userBlockToContentBlock(block) {
|
|
694
|
+
switch (block.type) {
|
|
695
|
+
case "text": return {
|
|
696
|
+
type: "text",
|
|
697
|
+
text: block.content
|
|
698
|
+
};
|
|
699
|
+
case "image": {
|
|
700
|
+
const normalizedMime = block.source.type === "base64" ? normalizeMimeType(block.source.mimeType) : void 0;
|
|
701
|
+
return imageSourceToParam(block.source, normalizedMime);
|
|
702
|
+
}
|
|
703
|
+
case "document": return documentSourceToParam(block.source);
|
|
704
|
+
case "attachment": {
|
|
705
|
+
if (block.source.type !== "base64") return {
|
|
706
|
+
type: "text",
|
|
707
|
+
text: serializeBlockToText(block)
|
|
708
|
+
};
|
|
709
|
+
const normalizedMimeType = normalizeMimeType(block.source.mimeType);
|
|
710
|
+
if (VALID_IMAGE_MEDIA_TYPES.includes(normalizedMimeType)) return imageSourceToParam(block.source, normalizedMimeType);
|
|
711
|
+
if (normalizedMimeType === "application/pdf") return documentSourceToParam(block.source);
|
|
712
|
+
if (isTextLikeMimeType(normalizedMimeType)) return {
|
|
713
|
+
type: "document",
|
|
714
|
+
source: {
|
|
715
|
+
type: "text",
|
|
716
|
+
data: Buffer.from(block.source.data, "base64").toString("utf-8"),
|
|
717
|
+
media_type: "text/plain"
|
|
718
|
+
}
|
|
719
|
+
};
|
|
720
|
+
return {
|
|
721
|
+
type: "text",
|
|
722
|
+
text: serializeBlockToText(block)
|
|
723
|
+
};
|
|
724
|
+
}
|
|
725
|
+
default: return {
|
|
726
|
+
type: "text",
|
|
727
|
+
text: serializeBlockToText(block)
|
|
728
|
+
};
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* Convert a reasoning block to an {@link AssistantContentBlock}.
|
|
733
|
+
*
|
|
734
|
+
* Emits a native `ThinkingBlockParam` when `metadata.signature` is present
|
|
735
|
+
* (captured from Anthropic `signature_delta` events during streaming). Falls
|
|
736
|
+
* back to a `text` block when only content is available, and returns `null`
|
|
737
|
+
* when both are absent so the caller can skip the block.
|
|
738
|
+
* @param block - Reasoning message block.
|
|
739
|
+
* @returns An assistant content block, or `null` to skip.
|
|
740
|
+
*/
|
|
741
|
+
function reasoningToContentBlock(block) {
|
|
742
|
+
const signature = typeof block.metadata?.signature === "string" ? block.metadata.signature : void 0;
|
|
743
|
+
if (signature !== void 0) return {
|
|
744
|
+
type: "thinking",
|
|
745
|
+
thinking: block.content,
|
|
746
|
+
signature
|
|
747
|
+
};
|
|
748
|
+
if (block.content.length > 0) return {
|
|
749
|
+
type: "text",
|
|
750
|
+
text: block.content
|
|
751
|
+
};
|
|
752
|
+
return null;
|
|
753
|
+
}
|
|
754
|
+
/**
|
|
755
|
+
* Build the Anthropic {@link MessageParam} entries for a single assistant turn.
|
|
756
|
+
*
|
|
757
|
+
* Returns an assistant message followed by an optional user message containing
|
|
758
|
+
* matched tool results. Orphan tool outputs (no corresponding tool call in the
|
|
759
|
+
* same turn) are appended to the assistant content as text blocks.
|
|
760
|
+
* @param blocks - All blocks belonging to the assistant message.
|
|
761
|
+
* @returns Zero, one, or two {@link MessageParam} entries.
|
|
762
|
+
*/
|
|
763
|
+
function buildAssistantParams(blocks) {
|
|
764
|
+
const contentBlocks = [];
|
|
765
|
+
const toolOutputs = [];
|
|
766
|
+
const toolCallIds = /* @__PURE__ */ new Set();
|
|
767
|
+
for (const block of blocks) switch (block.type) {
|
|
768
|
+
case "text":
|
|
769
|
+
if (block.content.length > 0) contentBlocks.push({
|
|
770
|
+
type: "text",
|
|
771
|
+
text: block.content
|
|
772
|
+
});
|
|
773
|
+
break;
|
|
774
|
+
case "reasoning": {
|
|
775
|
+
const converted = reasoningToContentBlock(block);
|
|
776
|
+
if (converted !== null) contentBlocks.push(converted);
|
|
777
|
+
break;
|
|
778
|
+
}
|
|
779
|
+
case "tool_call": {
|
|
780
|
+
toolCallIds.add(block.toolCallId);
|
|
781
|
+
const toolUseBlock = {
|
|
782
|
+
type: "tool_use",
|
|
783
|
+
id: block.toolCallId,
|
|
784
|
+
name: block.name,
|
|
785
|
+
input: block.args
|
|
786
|
+
};
|
|
787
|
+
contentBlocks.push(toolUseBlock);
|
|
788
|
+
break;
|
|
789
|
+
}
|
|
790
|
+
case "tool_output":
|
|
791
|
+
toolOutputs.push({
|
|
792
|
+
toolCallId: block.toolCallId,
|
|
793
|
+
content: block.output,
|
|
794
|
+
isError: block.isError
|
|
795
|
+
});
|
|
796
|
+
break;
|
|
797
|
+
}
|
|
798
|
+
const matchedOutputs = toolOutputs.filter((o) => toolCallIds.has(o.toolCallId));
|
|
799
|
+
const orphanOutputs = toolOutputs.filter((o) => !toolCallIds.has(o.toolCallId));
|
|
800
|
+
for (const orphan of orphanOutputs) {
|
|
801
|
+
const label = orphan.isError ? "Error" : "Result";
|
|
802
|
+
contentBlocks.push({
|
|
803
|
+
type: "text",
|
|
804
|
+
text: `[Tool ${label} ${orphan.toolCallId}]\n${orphan.content}`
|
|
805
|
+
});
|
|
806
|
+
}
|
|
807
|
+
const result = [];
|
|
808
|
+
if (contentBlocks.length > 0) result.push({
|
|
809
|
+
role: "assistant",
|
|
810
|
+
content: contentBlocks
|
|
811
|
+
});
|
|
812
|
+
if (matchedOutputs.length > 0) {
|
|
813
|
+
const toolResultBlocks = matchedOutputs.map((output) => ({
|
|
814
|
+
type: "tool_result",
|
|
815
|
+
tool_use_id: output.toolCallId,
|
|
816
|
+
content: output.isError ? `[Tool Error]\n${output.content}` : output.content,
|
|
817
|
+
...output.isError ? { is_error: true } : {}
|
|
818
|
+
}));
|
|
819
|
+
result.push({
|
|
820
|
+
role: "user",
|
|
821
|
+
content: toolResultBlocks
|
|
822
|
+
});
|
|
823
|
+
}
|
|
824
|
+
return result;
|
|
825
|
+
}
|
|
826
|
+
/**
|
|
827
|
+
* Convert an array of user {@link MessageBlock}s to the Anthropic `content` field value
|
|
828
|
+
* for a user {@link MessageParam}.
|
|
829
|
+
*
|
|
830
|
+
* Applies the same conversion as {@link convertMessageHistory} does for user messages
|
|
831
|
+
* in the history, making it reusable for the current-turn user message.
|
|
832
|
+
*
|
|
833
|
+
* - A single text block is returned as a plain string (keeps the wire format simple).
|
|
834
|
+
* - Multiple blocks or any non-text block are returned as a {@link UserContentBlock} array.
|
|
835
|
+
* - Empty text blocks are dropped.
|
|
836
|
+
* @param blocks - Message blocks from the current user turn.
|
|
837
|
+
* @returns The Anthropic `content` field value: a string or content block array.
|
|
838
|
+
*/
|
|
839
|
+
function convertCurrentTurnBlocks(blocks) {
|
|
840
|
+
const contentBlocks = blocks.map(userBlockToContentBlock).filter((b) => {
|
|
841
|
+
return b.type !== "text" || b.text.length > 0;
|
|
842
|
+
});
|
|
843
|
+
if (contentBlocks.length === 1 && contentBlocks[0].type === "text") return contentBlocks[0].text;
|
|
844
|
+
return contentBlocks;
|
|
845
|
+
}
|
|
846
|
+
/**
|
|
847
|
+
* Converts Makaio normalized message history to Anthropic {@link MessageParam} format.
|
|
848
|
+
*
|
|
849
|
+
* Anthropic differs from OpenAI in several key ways:
|
|
850
|
+
* - System messages are top-level params (excluded from the output array).
|
|
851
|
+
* - Assistant messages use a content block array (`text`, `tool_use`).
|
|
852
|
+
* - Tool results are emitted as a `role: 'user'` message containing
|
|
853
|
+
* `tool_result` content blocks, not as a separate `role: 'tool'` message.
|
|
854
|
+
* - Reasoning blocks are emitted as native `thinking` blocks when
|
|
855
|
+
* `block.metadata.signature` is present (captured from Anthropic
|
|
856
|
+
* `signature_delta` events during streaming); without a signature they fall
|
|
857
|
+
* back to `text` blocks so context is not silently lost.
|
|
858
|
+
* @param history - Makaio normalized message array.
|
|
859
|
+
* @returns Anthropic-formatted message params (system messages excluded).
|
|
860
|
+
*/
|
|
861
|
+
function convertMessageHistory(history) {
|
|
862
|
+
const result = [];
|
|
863
|
+
for (const msg of history) {
|
|
864
|
+
const blocks = Array.isArray(msg.blocks) ? msg.blocks : [msg.blocks];
|
|
865
|
+
if (msg.role === "system") continue;
|
|
866
|
+
if (msg.role === "assistant") result.push(...buildAssistantParams(blocks));
|
|
867
|
+
else {
|
|
868
|
+
const content = convertCurrentTurnBlocks(blocks);
|
|
869
|
+
if (typeof content === "string" && content.length === 0) continue;
|
|
870
|
+
if (Array.isArray(content) && content.length === 0) continue;
|
|
871
|
+
result.push({
|
|
872
|
+
role: "user",
|
|
873
|
+
content
|
|
874
|
+
});
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
return result;
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
//#endregion
|
|
881
|
+
//#region src/utils/parse-tool-use-input.ts
|
|
882
|
+
/**
|
|
883
|
+
* Parse tool_use JSON input for Anthropic assistant history reconstruction.
|
|
884
|
+
*
|
|
885
|
+
* Anthropic assistant `tool_use` blocks require an object input shape. When
|
|
886
|
+
* stream-normalized tool arguments are malformed or non-object JSON values,
|
|
887
|
+
* preserve continuity by returning a marker object instead of throwing.
|
|
888
|
+
* @param rawArgs - Serialized tool arguments
|
|
889
|
+
* @returns Parsed tool args object or fallback marker object on invalid input
|
|
890
|
+
*/
|
|
891
|
+
function parseToolUseInput(rawArgs) {
|
|
892
|
+
try {
|
|
893
|
+
const parsed = JSON.parse(rawArgs);
|
|
894
|
+
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) return parsed;
|
|
895
|
+
} catch {}
|
|
896
|
+
return {
|
|
897
|
+
raw: rawArgs,
|
|
898
|
+
parseError: true
|
|
899
|
+
};
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
//#endregion
|
|
903
|
+
//#region src/utils/classifyAnthropicError.ts
|
|
904
|
+
/**
|
|
905
|
+
* Narrows an opaque `APIError.error` value to `AnthropicErrorBody`.
|
|
906
|
+
* The Anthropic SDK types `error` as `Object | undefined`; this guard
|
|
907
|
+
* confirms it is a plain object with an optional `type` string.
|
|
908
|
+
* @param value - The raw error body from `APIError.error`.
|
|
909
|
+
* @returns `true` when the value can be treated as `AnthropicErrorBody`.
|
|
910
|
+
*/
|
|
911
|
+
function isAnthropicErrorBody(value) {
|
|
912
|
+
return typeof value === "object" && value !== null;
|
|
913
|
+
}
|
|
914
|
+
/**
|
|
915
|
+
* Maps Anthropic SDK errors to Makaio error subclasses.
|
|
916
|
+
*
|
|
917
|
+
* Classification priority:
|
|
918
|
+
* 1. HTTP status codes (definitive).
|
|
919
|
+
* 2. Error body `type` field (Anthropic API error objects).
|
|
920
|
+
* 3. Message content (fallback heuristics).
|
|
921
|
+
*
|
|
922
|
+
* Anthropic-specific status 529 (overloaded) is mapped to {@link RateLimitError}
|
|
923
|
+
* as the closest Makaio semantic — both indicate a transient capacity constraint.
|
|
924
|
+
* @param error - The error thrown by the Anthropic SDK.
|
|
925
|
+
* @returns A classified Makaio error, or the original error when unrecognised.
|
|
926
|
+
*/
|
|
927
|
+
function classifyAnthropicError(error) {
|
|
928
|
+
if (!(error instanceof Error)) return new Error(String(error));
|
|
929
|
+
if (!(error instanceof APIError)) return classifyByMessage(error);
|
|
930
|
+
const { status, message } = error;
|
|
931
|
+
const errorType = isAnthropicErrorBody(error.error) ? error.error.type : void 0;
|
|
932
|
+
if (status === 401 || status === 403) return new AuthenticationError(message);
|
|
933
|
+
if (status === 404) {
|
|
934
|
+
if (message.toLowerCase().includes("model")) return new ModelUnavailableError(message);
|
|
935
|
+
return new Error(message);
|
|
936
|
+
}
|
|
937
|
+
if (status === 429) return classifyRateLimitOrQuota(message, errorType);
|
|
938
|
+
if (status === 529) return new RateLimitError(message);
|
|
939
|
+
if (errorType !== void 0) {
|
|
940
|
+
const classified = classifyByErrorType(errorType, message);
|
|
941
|
+
if (classified !== void 0) return classified;
|
|
942
|
+
}
|
|
943
|
+
return classifyByMessage(error);
|
|
944
|
+
}
|
|
945
|
+
/**
|
|
946
|
+
* Distinguishes quota exhaustion from transient rate limiting for HTTP 429 responses.
|
|
947
|
+
* @param message - The error message string.
|
|
948
|
+
* @param errorType - The Anthropic API error type from the response body, if present.
|
|
949
|
+
* @returns {@link QuotaExceededError} for quota exhaustion, {@link RateLimitError} otherwise.
|
|
950
|
+
*/
|
|
951
|
+
function classifyRateLimitOrQuota(message, errorType) {
|
|
952
|
+
const messageLower = message.toLowerCase();
|
|
953
|
+
if (messageLower.includes("quota") || messageLower.includes("credit") || errorType === "billing_error") return new QuotaExceededError(message);
|
|
954
|
+
return new RateLimitError(message);
|
|
955
|
+
}
|
|
956
|
+
/**
|
|
957
|
+
* Maps Anthropic API error body `type` strings to Makaio error subclasses.
|
|
958
|
+
* @param errorType - The `type` field from the Anthropic error response body.
|
|
959
|
+
* @param message - The error message string.
|
|
960
|
+
* @returns A Makaio error subclass, or `undefined` when the type is unrecognised.
|
|
961
|
+
*/
|
|
962
|
+
function classifyByErrorType(errorType, message) {
|
|
963
|
+
switch (errorType) {
|
|
964
|
+
case "authentication_error":
|
|
965
|
+
case "permission_error": return new AuthenticationError(message);
|
|
966
|
+
case "not_found_error": return message.toLowerCase().includes("model") ? new ModelUnavailableError(message) : new Error(message);
|
|
967
|
+
case "rate_limit_error": return new RateLimitError(message);
|
|
968
|
+
case "billing_error": return new QuotaExceededError(message);
|
|
969
|
+
case "overloaded_error": return new RateLimitError(message);
|
|
970
|
+
default: return;
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
/**
|
|
974
|
+
* Heuristic fallback classifier that inspects error message content.
|
|
975
|
+
* Used when neither status codes nor error body types are available.
|
|
976
|
+
* @param error - The original error instance.
|
|
977
|
+
* @returns A Makaio error subclass when a known pattern is detected, or the original error.
|
|
978
|
+
*/
|
|
979
|
+
function classifyByMessage(error) {
|
|
980
|
+
const messageLower = error.message.toLowerCase();
|
|
981
|
+
if (messageLower.includes("authentication") || messageLower.includes("unauthorized")) return new AuthenticationError(error.message);
|
|
982
|
+
if (messageLower.includes("rate limit") || messageLower.includes("too many requests")) return new RateLimitError(error.message);
|
|
983
|
+
if (messageLower.includes("quota") || messageLower.includes("credit")) return new QuotaExceededError(error.message);
|
|
984
|
+
if (messageLower.includes("model not found") || messageLower.includes("unknown model")) return new ModelUnavailableError(error.message);
|
|
985
|
+
return error;
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
//#endregion
|
|
989
|
+
//#region src/utils/parseReasoningLevel.ts
|
|
990
|
+
/**
|
|
991
|
+
* Canonical token budget mapping for Claude extended thinking.
|
|
992
|
+
*
|
|
993
|
+
* Shared across all Claude models since they use the same thinking token API.
|
|
994
|
+
* Also consumed by {@link provider.ts} to populate `supportedReasoningLevels`
|
|
995
|
+
* on each model entry — keeping the two sources in sync automatically.
|
|
996
|
+
*/
|
|
997
|
+
const claudeReasoningLevelMap = {
|
|
998
|
+
none: 0,
|
|
999
|
+
low: 4e3,
|
|
1000
|
+
medium: 8e3,
|
|
1001
|
+
high: 16e3,
|
|
1002
|
+
"extra-high": 32e3
|
|
1003
|
+
};
|
|
1004
|
+
/**
|
|
1005
|
+
* Maps a Makaio reasoning level to Anthropic's thinking budget in tokens.
|
|
1006
|
+
* @param level - The reasoning level to map.
|
|
1007
|
+
* @returns Token budget for Anthropic's `thinking` parameter (0 means omit thinking entirely).
|
|
1008
|
+
*/
|
|
1009
|
+
function parseReasoningLevel(level) {
|
|
1010
|
+
return claudeReasoningLevelMap[level] ?? 0;
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
//#endregion
|
|
1014
|
+
//#region src/utils/buildMessageCreateRequest.ts
|
|
1015
|
+
/** Default max_tokens for Anthropic API requests. */
|
|
1016
|
+
const DEFAULT_MAX_TOKENS = 32e3;
|
|
1017
|
+
/**
|
|
1018
|
+
* Assembles parameters for an Anthropic `messages.create()` streaming call.
|
|
1019
|
+
*
|
|
1020
|
+
* Key differences from the OpenAI equivalent:
|
|
1021
|
+
* - `max_tokens` is required — defaults to {@link DEFAULT_MAX_TOKENS}.
|
|
1022
|
+
* - The system prompt is a top-level field with `cache_control: { type: 'ephemeral' }` for prompt caching.
|
|
1023
|
+
* - Reasoning is expressed via `thinking: { type: 'enabled', budget_tokens }` instead of `reasoning_effort`.
|
|
1024
|
+
* - Usage is always included in Anthropic streaming responses; no `stream_options` needed.
|
|
1025
|
+
* @param input - Request components and model capability metadata.
|
|
1026
|
+
* @returns Anthropic API request parameters with `stream: true`.
|
|
1027
|
+
*/
|
|
1028
|
+
function buildMessageCreateRequest(input) {
|
|
1029
|
+
const { model, messages, systemPrompt, tools, reasoningEffort, supportsReasoningEffort } = input;
|
|
1030
|
+
const maxTokens = input.maxTokens ?? DEFAULT_MAX_TOKENS;
|
|
1031
|
+
const system = buildSystemParam(systemPrompt);
|
|
1032
|
+
const thinking = buildThinkingParam(reasoningEffort, supportsReasoningEffort, maxTokens);
|
|
1033
|
+
return {
|
|
1034
|
+
model,
|
|
1035
|
+
messages,
|
|
1036
|
+
max_tokens: maxTokens,
|
|
1037
|
+
stream: true,
|
|
1038
|
+
...system !== void 0 ? { cache_control: {
|
|
1039
|
+
type: "ephemeral",
|
|
1040
|
+
ttl: "5m"
|
|
1041
|
+
} } : {},
|
|
1042
|
+
...system !== void 0 ? { system } : {},
|
|
1043
|
+
...tools !== void 0 && tools.length > 0 ? { tools } : {},
|
|
1044
|
+
...thinking !== void 0 ? { thinking } : {}
|
|
1045
|
+
};
|
|
1046
|
+
}
|
|
1047
|
+
/**
|
|
1048
|
+
* Wraps the system prompt string in a `TextBlockParam` array with prompt caching enabled.
|
|
1049
|
+
* Returns `undefined` when no system prompt is provided.
|
|
1050
|
+
* @param systemPrompt - The resolved system prompt string, if any.
|
|
1051
|
+
* @returns A single-element `TextBlockParam` array with ephemeral cache control, or `undefined`.
|
|
1052
|
+
*/
|
|
1053
|
+
function buildSystemParam(systemPrompt) {
|
|
1054
|
+
if (!systemPrompt) return;
|
|
1055
|
+
return [{
|
|
1056
|
+
type: "text",
|
|
1057
|
+
text: systemPrompt,
|
|
1058
|
+
cache_control: { type: "ephemeral" }
|
|
1059
|
+
}];
|
|
1060
|
+
}
|
|
1061
|
+
/**
|
|
1062
|
+
* Maps a Makaio reasoning level to Anthropic's `thinking` config param.
|
|
1063
|
+
* Returns `undefined` when the model does not support reasoning or the level is `'none'`.
|
|
1064
|
+
* @param reasoningEffort - The Makaio reasoning effort to convert.
|
|
1065
|
+
* @param supportsReasoningEffort - Whether the model supports extended thinking.
|
|
1066
|
+
* @param maxTokens - The request-level max token limit that thinking must remain below.
|
|
1067
|
+
* @returns An enabled `ThinkingConfigParam` or `undefined`.
|
|
1068
|
+
*/
|
|
1069
|
+
function buildThinkingParam(reasoningEffort, supportsReasoningEffort, maxTokens) {
|
|
1070
|
+
if (!supportsReasoningEffort || !reasoningEffort) return;
|
|
1071
|
+
const budgetTokens = Math.min(parseReasoningLevel(reasoningEffort), maxTokens - 1);
|
|
1072
|
+
if (budgetTokens <= 0) return;
|
|
1073
|
+
return {
|
|
1074
|
+
type: "enabled",
|
|
1075
|
+
budget_tokens: budgetTokens
|
|
1076
|
+
};
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
//#endregion
|
|
1080
|
+
//#region src/session.ts
|
|
1081
|
+
/**
|
|
1082
|
+
* Session for Anthropic SDK lifecycle management.
|
|
1083
|
+
*
|
|
1084
|
+
* Manages Anthropic client calls across multiple user messages:
|
|
1085
|
+
* - Creates Turn instances for each user message
|
|
1086
|
+
* - Handles immediate mode via abort+restart (no true pause)
|
|
1087
|
+
* - Processes message queue with merge support
|
|
1088
|
+
*
|
|
1089
|
+
* Key difference from Claude Code: Anthropic SDK adapter has no server-side
|
|
1090
|
+
* session. Each turn rebuilds the messages[] array with full history.
|
|
1091
|
+
*/
|
|
1092
|
+
var AnthropicSdkSession = class extends BaseStreamSession {
|
|
1093
|
+
messages = [];
|
|
1094
|
+
/**
|
|
1095
|
+
* Runtime reasoning effort level; updated by `updateReasoning()`.
|
|
1096
|
+
* Initialized from `config.reasoningEffort` at session construction.
|
|
1097
|
+
*/
|
|
1098
|
+
currentReasoningEffort;
|
|
1099
|
+
/**
|
|
1100
|
+
* Mutable tool list for this session.
|
|
1101
|
+
* Rebuilt whenever either `nativeTools` or `mcpTools` changes.
|
|
1102
|
+
*/
|
|
1103
|
+
currentTools;
|
|
1104
|
+
/** Latest native registry tools for this live session. */
|
|
1105
|
+
nativeTools;
|
|
1106
|
+
/**
|
|
1107
|
+
* Latest MCP direct-inject tools converted to Anthropic format.
|
|
1108
|
+
* Stored separately so that `replaceNativeTools` can rebuild `currentTools`
|
|
1109
|
+
* without losing the MCP tool set.
|
|
1110
|
+
*/
|
|
1111
|
+
mcpTools = [];
|
|
1112
|
+
/**
|
|
1113
|
+
* Create an Anthropic SDK connector session.
|
|
1114
|
+
* @param config - Session configuration (bus identity, model/cwd defaults, Anthropic client/tools, and lifecycle hooks).
|
|
1115
|
+
*/
|
|
1116
|
+
constructor(config) {
|
|
1117
|
+
super(config);
|
|
1118
|
+
this.currentReasoningEffort = config.reasoningEffort;
|
|
1119
|
+
this.nativeTools = config.anthropicTools;
|
|
1120
|
+
this.currentTools = config.anthropicTools;
|
|
1121
|
+
}
|
|
1122
|
+
/**
|
|
1123
|
+
* Replace the native registry tool set used for subsequent turns.
|
|
1124
|
+
*
|
|
1125
|
+
* Rebuilds `currentTools` so that MCP tools registered via `updateTools`
|
|
1126
|
+
* are preserved alongside the new native tools.
|
|
1127
|
+
* @param tools - Fresh Anthropic-formatted native tools
|
|
1128
|
+
*/
|
|
1129
|
+
replaceNativeTools(tools) {
|
|
1130
|
+
this.nativeTools = tools;
|
|
1131
|
+
this.currentTools = [...this.nativeTools, ...this.mcpTools];
|
|
1132
|
+
}
|
|
1133
|
+
/**
|
|
1134
|
+
* Update the session's tool set for the next API call.
|
|
1135
|
+
*
|
|
1136
|
+
* Converts generic `ToolListItem[]` (MCP direct-inject tools) to
|
|
1137
|
+
* Anthropic `Tool[]` format and merges them with the existing native tools.
|
|
1138
|
+
* @param tools - New MCP direct-inject tools in generic format
|
|
1139
|
+
*/
|
|
1140
|
+
updateTools(tools) {
|
|
1141
|
+
this.mcpTools = toAnthropicToolFormat(tools);
|
|
1142
|
+
this.currentTools = [...this.nativeTools, ...this.mcpTools];
|
|
1143
|
+
}
|
|
1144
|
+
/**
|
|
1145
|
+
* Update the reasoning effort level used for subsequent API calls.
|
|
1146
|
+
*
|
|
1147
|
+
* Called by the connector's `changeReasoningInPlace()` to sync the session
|
|
1148
|
+
* with the requested reasoning level without requiring a full session swap.
|
|
1149
|
+
* The updated value is picked up by `executeApiCall` on the next turn.
|
|
1150
|
+
* @internal Direct calls bypass capability validation — only the mutation
|
|
1151
|
+
* manager should call this (via the connector's `changeReasoningInPlace`).
|
|
1152
|
+
* @param level - New reasoning effort level
|
|
1153
|
+
*/
|
|
1154
|
+
updateReasoning(level) {
|
|
1155
|
+
this.currentReasoningEffort = level;
|
|
1156
|
+
}
|
|
1157
|
+
/**
|
|
1158
|
+
* Return the names of all tools that would be sent in the next API call.
|
|
1159
|
+
*
|
|
1160
|
+
* Reflects the merged set of native and MCP tools after any `replaceNativeTools`
|
|
1161
|
+
* or `updateTools` calls.
|
|
1162
|
+
* @returns Ordered list of tool names matching the next API request
|
|
1163
|
+
*/
|
|
1164
|
+
getEffectiveToolNames() {
|
|
1165
|
+
return this.currentTools.map((tool) => tool.name);
|
|
1166
|
+
}
|
|
1167
|
+
/**
|
|
1168
|
+
* Create an Anthropic SDK turn for the given message handle.
|
|
1169
|
+
* @param handle - The message handle this turn will process
|
|
1170
|
+
* @returns A new `AnthropicSdkConnectorTurn` instance
|
|
1171
|
+
*/
|
|
1172
|
+
createTurn(handle) {
|
|
1173
|
+
return new AnthropicSdkConnectorTurn(this.bus, this.config.adapterId, this.config.adapterName, this.config.agentId, handle);
|
|
1174
|
+
}
|
|
1175
|
+
/**
|
|
1176
|
+
* Build the messages array from handle history and optional merged content.
|
|
1177
|
+
* @param handle - The message handle containing history
|
|
1178
|
+
* @param mergedContent - Optional content from superseded/merged messages
|
|
1179
|
+
*/
|
|
1180
|
+
buildMessages(handle, mergedContent) {
|
|
1181
|
+
if (handle.messageHistory) this.messages = convertMessageHistory(handle.messageHistory);
|
|
1182
|
+
if (mergedContent && mergedContent.length > 0) for (const content of mergedContent) {
|
|
1183
|
+
this.messages.push({
|
|
1184
|
+
role: "user",
|
|
1185
|
+
content
|
|
1186
|
+
});
|
|
1187
|
+
this.messages.push({
|
|
1188
|
+
role: "assistant",
|
|
1189
|
+
content: "Acknowledged."
|
|
1190
|
+
});
|
|
1191
|
+
}
|
|
1192
|
+
const userContent = convertCurrentTurnBlocks(handle.message.blocks);
|
|
1193
|
+
if (typeof userContent === "string" ? userContent.trim().length === 0 : userContent.length === 0) throw new Error(`[AnthropicSdkSession] Cannot send empty user content (messageId=${handle.messageId})`);
|
|
1194
|
+
const contextText = formatContextBlocksAsText(serializeTurnContext(handle.turnContext));
|
|
1195
|
+
if (contextText.length > 0) if (typeof userContent === "string") this.messages.push({
|
|
1196
|
+
role: "user",
|
|
1197
|
+
content: `${contextText}\n\n${userContent}`
|
|
1198
|
+
});
|
|
1199
|
+
else this.messages.push({
|
|
1200
|
+
role: "user",
|
|
1201
|
+
content: [{
|
|
1202
|
+
type: "text",
|
|
1203
|
+
text: contextText
|
|
1204
|
+
}, ...userContent]
|
|
1205
|
+
});
|
|
1206
|
+
else this.messages.push({
|
|
1207
|
+
role: "user",
|
|
1208
|
+
content: userContent
|
|
1209
|
+
});
|
|
1210
|
+
}
|
|
1211
|
+
/**
|
|
1212
|
+
* Execute the Anthropic streaming API call.
|
|
1213
|
+
*
|
|
1214
|
+
* Calls `client.messages.create` with the current messages array and
|
|
1215
|
+
* pipes the resulting stream through the stream-bridge event emitter.
|
|
1216
|
+
* @param turn - Captured turn instance for this run loop
|
|
1217
|
+
* @param abortSignal - Combined abort signal (turn abort + stream timeout)
|
|
1218
|
+
* @param adapterSessionId - Turn-scoped adapter session ID for event correlation
|
|
1219
|
+
*/
|
|
1220
|
+
async executeApiCall(turn, abortSignal, adapterSessionId) {
|
|
1221
|
+
const supportsReasoningEffort = this.currentReasoningEffort !== void 0 && this.currentReasoningEffort !== "none";
|
|
1222
|
+
const requestParams = buildMessageCreateRequest({
|
|
1223
|
+
model: this.currentModel,
|
|
1224
|
+
messages: this.messages,
|
|
1225
|
+
tools: this.currentTools,
|
|
1226
|
+
reasoningEffort: this.currentReasoningEffort,
|
|
1227
|
+
supportsReasoningEffort,
|
|
1228
|
+
systemPrompt: this.config.systemPrompt,
|
|
1229
|
+
maxTokens: this.config.maxTokens
|
|
1230
|
+
});
|
|
1231
|
+
const stream = await this.config.client.messages.create(requestParams, { signal: abortSignal });
|
|
1232
|
+
await turn.markStepStarted();
|
|
1233
|
+
try {
|
|
1234
|
+
await processStream(stream, {
|
|
1235
|
+
bus: this.config.bus,
|
|
1236
|
+
agentId: this.config.agentId,
|
|
1237
|
+
adapterId: this.config.adapterId,
|
|
1238
|
+
adapterName: this.config.adapterName,
|
|
1239
|
+
adapterSessionId,
|
|
1240
|
+
model: this.currentModel,
|
|
1241
|
+
logLowLevelEvent: this.config.logLowLevelEvent
|
|
1242
|
+
});
|
|
1243
|
+
} finally {
|
|
1244
|
+
await turn.markStepFinished();
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
/**
|
|
1248
|
+
* Return the Anthropic SDK event bus subject for `message_complete` waiting.
|
|
1249
|
+
* @returns The `sdk.event` subject for the Anthropic adapter namespace
|
|
1250
|
+
*/
|
|
1251
|
+
getSdkEventSubject() {
|
|
1252
|
+
return AnthropicSdkConnectorSubjects.sdk.event;
|
|
1253
|
+
}
|
|
1254
|
+
/**
|
|
1255
|
+
* Apply a `message_complete` event to the Anthropic messages array and
|
|
1256
|
+
* recurse for tool calls.
|
|
1257
|
+
*
|
|
1258
|
+
* Appends assistant content as Anthropic `MessageParam[]` blocks. When
|
|
1259
|
+
* `finish_reason` is `'tool_use'`, executes tools and continues the loop.
|
|
1260
|
+
* @param result - The parsed Anthropic `message_complete` event
|
|
1261
|
+
* @param currentHandle - The active message handle
|
|
1262
|
+
* @param toolCallIteration - Current tool recursion depth
|
|
1263
|
+
* @param turn - Captured turn instance for this run loop
|
|
1264
|
+
*/
|
|
1265
|
+
async applyMessageComplete(result, currentHandle, toolCallIteration, turn) {
|
|
1266
|
+
if (this.shouldAbortTurnProcessing(turn, currentHandle)) return;
|
|
1267
|
+
const messageContent = result.content || null;
|
|
1268
|
+
if (result.tool_calls && result.tool_calls.length > 0) {
|
|
1269
|
+
const assistantContent = [];
|
|
1270
|
+
if (messageContent) assistantContent.push({
|
|
1271
|
+
type: "text",
|
|
1272
|
+
text: messageContent
|
|
1273
|
+
});
|
|
1274
|
+
for (const tc of result.tool_calls) {
|
|
1275
|
+
const parsedArgs = parseToolUseInput(tc.function.arguments);
|
|
1276
|
+
assistantContent.push({
|
|
1277
|
+
type: "tool_use",
|
|
1278
|
+
id: tc.id,
|
|
1279
|
+
name: tc.function.name,
|
|
1280
|
+
input: parsedArgs
|
|
1281
|
+
});
|
|
1282
|
+
}
|
|
1283
|
+
this.messages.push({
|
|
1284
|
+
role: "assistant",
|
|
1285
|
+
content: assistantContent
|
|
1286
|
+
});
|
|
1287
|
+
} else this.messages.push({
|
|
1288
|
+
role: "assistant",
|
|
1289
|
+
content: messageContent ?? ""
|
|
1290
|
+
});
|
|
1291
|
+
this.lastAssistantMessage = messageContent || "";
|
|
1292
|
+
if (result.finish_reason === "tool_use" && result.tool_calls && result.tool_calls.length > 0) {
|
|
1293
|
+
if (toolCallIteration >= BaseStreamSession.MAX_TOOL_CALL_ITERATIONS) throw new Error(`Tool call iteration limit exceeded (${BaseStreamSession.MAX_TOOL_CALL_ITERATIONS}). Aborting to prevent context blowup.`);
|
|
1294
|
+
const toolResultBlocks = await handleToolCalls$1(result.tool_calls, {
|
|
1295
|
+
emitSdkEvent: this.config.emitSdkEvent,
|
|
1296
|
+
requestToolApproval: this.config.requestToolApproval,
|
|
1297
|
+
recordMcpCall: this.config.recordMcpCall
|
|
1298
|
+
}, {
|
|
1299
|
+
env: this.config.env,
|
|
1300
|
+
cwd: this.currentCwd,
|
|
1301
|
+
sessionId: this.config.sessionId,
|
|
1302
|
+
agentId: this.config.agentId,
|
|
1303
|
+
adapterId: this.config.adapterId,
|
|
1304
|
+
adapterName: this.config.adapterName,
|
|
1305
|
+
turnId: currentHandle.messageId,
|
|
1306
|
+
turnContext: currentHandle.turnContext,
|
|
1307
|
+
reasoning: result.reasoning,
|
|
1308
|
+
constraints: this.buildToolConstraints()
|
|
1309
|
+
});
|
|
1310
|
+
this.messages.push({
|
|
1311
|
+
role: "user",
|
|
1312
|
+
content: toolResultBlocks
|
|
1313
|
+
});
|
|
1314
|
+
await this.runTurnIteration(turn, currentHandle, toolCallIteration + 1);
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
/**
|
|
1318
|
+
* Classify an Anthropic SDK error into the appropriate Makaio error type.
|
|
1319
|
+
* @param error - The raw error from the Anthropic SDK
|
|
1320
|
+
* @returns A classified `Error` instance
|
|
1321
|
+
*/
|
|
1322
|
+
classifyError(error) {
|
|
1323
|
+
return classifyAnthropicError(error);
|
|
1324
|
+
}
|
|
1325
|
+
};
|
|
1326
|
+
|
|
1327
|
+
//#endregion
|
|
1328
|
+
//#region src/constants.ts
|
|
1329
|
+
/** Stable adapter type name for bus routing and persistence. */
|
|
1330
|
+
const AnthropicSdkAdapterName = "anthropic-sdk";
|
|
1331
|
+
/** Default model for new sessions. */
|
|
1332
|
+
const DEFAULT_MODEL = "claude-sonnet-4-5-20250929";
|
|
1333
|
+
/** Default timeout configuration for Anthropic SDK adapter. */
|
|
1334
|
+
const DEFAULT_TIMEOUTS = {
|
|
1335
|
+
initialization: 3e4,
|
|
1336
|
+
acknowledgement: 12e4,
|
|
1337
|
+
completion: 12e4,
|
|
1338
|
+
toolApproval: 5e3,
|
|
1339
|
+
eventWait: 3e4
|
|
1340
|
+
};
|
|
1341
|
+
|
|
1342
|
+
//#endregion
|
|
1343
|
+
//#region src/connector.ts
|
|
1344
|
+
/** Default scoped bus for Anthropic SDK adapter */
|
|
1345
|
+
const defaultBus = await AnthropicSdkConnectorNamespace.scopedBus();
|
|
1346
|
+
/**
|
|
1347
|
+
* Anthropic SDK Connector — Wraps the Anthropic SDK for agentic message creation.
|
|
1348
|
+
*
|
|
1349
|
+
* Implements the agentic loop pattern:
|
|
1350
|
+
* 1. Send user message to Anthropic via messages.create (streaming)
|
|
1351
|
+
* 2. Process streaming response via stream-bridge
|
|
1352
|
+
* 3. If tool_use blocks present, execute tools via Bus RPC and recurse
|
|
1353
|
+
* 4. When no tool_use blocks, mark turn complete
|
|
1354
|
+
*
|
|
1355
|
+
* Tools are fetched from ToolRegistry via MakaioBus.request(ToolSubjects.list)
|
|
1356
|
+
* on the first turn. Tool execution routes through MakaioBus.request(ToolSubjects.execute)
|
|
1357
|
+
* to the ToolRegistry, which validates input and executes the tool handler.
|
|
1358
|
+
*
|
|
1359
|
+
* Credential resolution happens in `fetchTools()` (the first async lifecycle hook)
|
|
1360
|
+
* via `resolveConnectorCredentials()`. Plaintext credentials are stored in instance
|
|
1361
|
+
* fields and never leave the connector.
|
|
1362
|
+
*/
|
|
1363
|
+
var AnthropicSdkConnector = class extends BaseStreamConnector {
|
|
1364
|
+
/** Resolved API key (populated in fetchTools before createSession is called). */
|
|
1365
|
+
resolvedApiKey = "";
|
|
1366
|
+
client;
|
|
1367
|
+
/** Anthropic-format tools for messages.create (fetched from bus on first turn) */
|
|
1368
|
+
anthropicTools = [];
|
|
1369
|
+
/**
|
|
1370
|
+
* Emit an SDK event wrapped in envelope for type-safe discriminated union handling.
|
|
1371
|
+
* @param event - The typed SDK event message to emit
|
|
1372
|
+
*/
|
|
1373
|
+
async emitSdkEvent(event) {
|
|
1374
|
+
await this.emit(AnthropicSdkConnectorSubjects.sdk.event, { event });
|
|
1375
|
+
}
|
|
1376
|
+
constructor(config) {
|
|
1377
|
+
super({
|
|
1378
|
+
...config,
|
|
1379
|
+
bus: config?.bus ?? defaultBus,
|
|
1380
|
+
adapterId: config?.adapterId ?? crypto.randomUUID(),
|
|
1381
|
+
adapterName: config?.adapterName ?? "anthropic-sdk"
|
|
1382
|
+
});
|
|
1383
|
+
this.model = config?.model ?? "claude-sonnet-4-5-20250929";
|
|
1384
|
+
this.initAdapterSessionId();
|
|
1385
|
+
}
|
|
1386
|
+
/**
|
|
1387
|
+
* Resolve credentials and fetch available tools from the bus.
|
|
1388
|
+
*
|
|
1389
|
+
* Resolves `apiKey` from `providerContext.credentialRefs` via the encrypted
|
|
1390
|
+
* credential channel, then initializes the Anthropic SDK client. Called once
|
|
1391
|
+
* by `BaseStreamConnector.initializeSession()` before `createSession()`.
|
|
1392
|
+
*
|
|
1393
|
+
* Also converts fetched tools to Anthropic format and caches them in
|
|
1394
|
+
* `this.anthropicTools` for use in `createSession`.
|
|
1395
|
+
*/
|
|
1396
|
+
async fetchTools() {
|
|
1397
|
+
const credentialRefs = this.config.providerContext?.credentialRefs ?? {};
|
|
1398
|
+
const credentials = await resolveConnectorCredentials(this.config.bus, credentialRefs);
|
|
1399
|
+
this.resolvedApiKey = credentials["apiKey"] ?? "";
|
|
1400
|
+
const baseUrl = this.config.providerConfig?.baseUrl;
|
|
1401
|
+
this.client = new Anthropic({
|
|
1402
|
+
...this.resolvedApiKey ? { apiKey: this.resolvedApiKey } : {},
|
|
1403
|
+
baseURL: baseUrl ?? void 0
|
|
1404
|
+
});
|
|
1405
|
+
this.anthropicTools = await fetchToolsForAnthropic(this.adapterId, this.adapterName);
|
|
1406
|
+
}
|
|
1407
|
+
/**
|
|
1408
|
+
* Re-fetch native tools and re-resolve MCP direct-inject tools.
|
|
1409
|
+
*
|
|
1410
|
+
* Called at turn boundary when `hasPendingToolRefresh` is true.
|
|
1411
|
+
* Re-fetches Anthropic-format tools from the registry, re-prepares MCP
|
|
1412
|
+
* direct tools (and arms the ledger injection flag via `super.refreshTools()`),
|
|
1413
|
+
* then notifies the active session so the next API call uses the updated
|
|
1414
|
+
* merged tool list. The ledger `recordInjection` is deferred to
|
|
1415
|
+
* `onTurnStarted` so it uses the canonical turn number.
|
|
1416
|
+
*/
|
|
1417
|
+
async refreshTools() {
|
|
1418
|
+
this.anthropicTools = await fetchToolsForAnthropic(this.adapterId, this.adapterName);
|
|
1419
|
+
await super.refreshTools();
|
|
1420
|
+
const session = this.getSession();
|
|
1421
|
+
session?.replaceNativeTools(this.anthropicTools);
|
|
1422
|
+
session?.updateTools?.(this.mcpDirectTools);
|
|
1423
|
+
}
|
|
1424
|
+
/**
|
|
1425
|
+
* Construct the Anthropic SDK session with all required config.
|
|
1426
|
+
*
|
|
1427
|
+
* Called by `BaseStreamConnector.initializeSession()` after `fetchTools()`
|
|
1428
|
+
* has resolved credentials and initialized `this.client`.
|
|
1429
|
+
* @returns A new `AnthropicSdkSession` instance
|
|
1430
|
+
*/
|
|
1431
|
+
createSession() {
|
|
1432
|
+
if (!this.client) throw new Error("[AnthropicSdkConnector] createSession() called before fetchTools() — client not initialized");
|
|
1433
|
+
const systemPrompt = this.resolveSystemPrompt();
|
|
1434
|
+
return new AnthropicSdkSession({
|
|
1435
|
+
bus: this.config.bus,
|
|
1436
|
+
adapterId: this.config.adapterId ?? "",
|
|
1437
|
+
adapterName: this.config.adapterName ?? "",
|
|
1438
|
+
agentId: this.agentId,
|
|
1439
|
+
sessionId: this.config.sessionId,
|
|
1440
|
+
cwd: this.cwd,
|
|
1441
|
+
model: this.model ?? "",
|
|
1442
|
+
reasoningEffort: this.config.reasoningEffort,
|
|
1443
|
+
streamStartTimeoutMs: this.getTimeoutMs("eventWait"),
|
|
1444
|
+
env: this.config.env ?? {},
|
|
1445
|
+
client: this.client,
|
|
1446
|
+
anthropicTools: this.anthropicTools,
|
|
1447
|
+
systemPrompt,
|
|
1448
|
+
maxTokens: this.config.providerConfig?.maxTokens,
|
|
1449
|
+
allowedDirectories: this.config.allowedDirectories,
|
|
1450
|
+
supportedReasoningLevels: this.config.supportedReasoningLevels,
|
|
1451
|
+
emitSdkEvent: this.emitSdkEvent.bind(this),
|
|
1452
|
+
handleError: this.handleError.bind(this),
|
|
1453
|
+
requestToolApproval: (payload) => this.requestToolApprovalWithHandling(AnthropicSdkConnectorSubjects.tool_approval, payload),
|
|
1454
|
+
logLowLevelEvent: this.logLowLevelEvent,
|
|
1455
|
+
onTurnStart: (handle) => {
|
|
1456
|
+
this.pendingMessageHandle = handle;
|
|
1457
|
+
},
|
|
1458
|
+
onTurnComplete: (_handle, result) => {
|
|
1459
|
+
this.lastResult = result;
|
|
1460
|
+
this.pendingMessageHandle = void 0;
|
|
1461
|
+
},
|
|
1462
|
+
recordMcpCall: this.config.toolLedger ? (toolFullName) => {
|
|
1463
|
+
this.config.toolLedger?.recordCall(toolFullName, this.currentTurnNumber);
|
|
1464
|
+
} : void 0
|
|
1465
|
+
});
|
|
1466
|
+
}
|
|
1467
|
+
/**
|
|
1468
|
+
* Get Anthropic namespace turn subjects.
|
|
1469
|
+
* @returns Turn subject definitions
|
|
1470
|
+
*/
|
|
1471
|
+
getTurnSubjects() {
|
|
1472
|
+
return AnthropicSdkConnectorSubjects.turn;
|
|
1473
|
+
}
|
|
1474
|
+
};
|
|
1475
|
+
|
|
1476
|
+
//#endregion
|
|
1477
|
+
//#region src/agent.ts
|
|
1478
|
+
const DEFAULT_CONTEXT_WINDOW_SIZE = 2e5;
|
|
1479
|
+
/**
|
|
1480
|
+
* Anthropic SDK Agent — Middle layer between AnthropicSdkAdapter and AnthropicSdkConnector.
|
|
1481
|
+
*
|
|
1482
|
+
* Responsibilities:
|
|
1483
|
+
* 1. Wire connector's scoped bus events to global agent.* subjects
|
|
1484
|
+
* 2. Auto-enrich payloads with AgentContext via emitGlobal()
|
|
1485
|
+
*
|
|
1486
|
+
* Event Flow:
|
|
1487
|
+
* - AnthropicSdkConnector emits to semantic subjects (chunk, usage, etc.)
|
|
1488
|
+
* - AnthropicSdkAgent subscribes to semantic subjects and emits to global bus (agent.*)
|
|
1489
|
+
* - Downstream consumers subscribe to normalized agent.* subjects
|
|
1490
|
+
*
|
|
1491
|
+
* Extends `BaseStreamAgent` which provides all shared wiring logic. This class only
|
|
1492
|
+
* implements the adapter-specific abstract hooks.
|
|
1493
|
+
*/
|
|
1494
|
+
var AnthropicSdkAgent = class extends BaseStreamAgent {
|
|
1495
|
+
/**
|
|
1496
|
+
* Keep AIAgent's internal block index counter in sync with provider block indices.
|
|
1497
|
+
*
|
|
1498
|
+
* Some steps (tool_use) emit provider-native indices directly instead of going through
|
|
1499
|
+
* emitStepStarted/emitStepFinished, so we advance the local counter to avoid reusing
|
|
1500
|
+
* stale indices for later text/reasoning steps in the same turn.
|
|
1501
|
+
* @param blockIndex - Provider block index that has been reserved/emitted
|
|
1502
|
+
*/
|
|
1503
|
+
reconcileInternalBlockIndex(blockIndex) {
|
|
1504
|
+
while (this.getBlockIndex() <= blockIndex) this.incrementBlockIndex();
|
|
1505
|
+
}
|
|
1506
|
+
/**
|
|
1507
|
+
* Tier 1: Route sdk.event catch-all to typed semantic subjects.
|
|
1508
|
+
*
|
|
1509
|
+
* Uses `createConnectorEventMapping` for type-safe discriminated union routing.
|
|
1510
|
+
* The envelope `'event'` field carries the discriminated union keyed on `'eventType'`.
|
|
1511
|
+
*/
|
|
1512
|
+
wireSdkEvents() {
|
|
1513
|
+
this.createConnectorEventMapping(AnthropicSdkConnectorSubjects.sdk.event, "eventType", {
|
|
1514
|
+
chunk: AnthropicSdkConnectorSubjects.chunk,
|
|
1515
|
+
usage: AnthropicSdkConnectorSubjects.usage,
|
|
1516
|
+
tool_calls: AnthropicSdkConnectorSubjects.tool_calls,
|
|
1517
|
+
message_complete: AnthropicSdkConnectorSubjects.message_complete,
|
|
1518
|
+
reasoning_delta: AnthropicSdkConnectorSubjects.reasoning_delta,
|
|
1519
|
+
reasoning_complete: AnthropicSdkConnectorSubjects.reasoning_complete,
|
|
1520
|
+
agent_started: AnthropicSdkConnectorSubjects.agent_started,
|
|
1521
|
+
agent_complete: AnthropicSdkConnectorSubjects.agent_complete,
|
|
1522
|
+
error: AnthropicSdkConnectorSubjects.error,
|
|
1523
|
+
tool_started: AnthropicSdkConnectorSubjects.tool_started,
|
|
1524
|
+
tool_completed: AnthropicSdkConnectorSubjects.tool_completed
|
|
1525
|
+
}, "event");
|
|
1526
|
+
}
|
|
1527
|
+
/**
|
|
1528
|
+
* Return the Anthropic SDK adapter's connector subject spec.
|
|
1529
|
+
*
|
|
1530
|
+
* Maps adapter subject constants to the `StreamAdapterSubjectSpec` interface used
|
|
1531
|
+
* by `BaseStreamAgent` to subscribe to semantic events.
|
|
1532
|
+
* @returns Anthropic-specific subject spec
|
|
1533
|
+
*/
|
|
1534
|
+
getConnectorSubjects() {
|
|
1535
|
+
return {
|
|
1536
|
+
chunk: AnthropicSdkConnectorSubjects.chunk,
|
|
1537
|
+
usage: AnthropicSdkConnectorSubjects.usage,
|
|
1538
|
+
toolCalls: AnthropicSdkConnectorSubjects.tool_calls,
|
|
1539
|
+
reasoningComplete: AnthropicSdkConnectorSubjects.reasoning_complete,
|
|
1540
|
+
messageComplete: AnthropicSdkConnectorSubjects.message_complete,
|
|
1541
|
+
reasoningDelta: AnthropicSdkConnectorSubjects.reasoning_delta,
|
|
1542
|
+
toolStarted: AnthropicSdkConnectorSubjects.tool_started,
|
|
1543
|
+
toolCompleted: AnthropicSdkConnectorSubjects.tool_completed,
|
|
1544
|
+
agentStarted: AnthropicSdkConnectorSubjects.agent_started,
|
|
1545
|
+
agentComplete: AnthropicSdkConnectorSubjects.agent_complete,
|
|
1546
|
+
error: AnthropicSdkConnectorSubjects.error
|
|
1547
|
+
};
|
|
1548
|
+
}
|
|
1549
|
+
/**
|
|
1550
|
+
* Extract plain text from an Anthropic chunk event payload.
|
|
1551
|
+
*
|
|
1552
|
+
* Anthropic chunk events carry a discriminated `delta` union. Text content is
|
|
1553
|
+
* only present when `delta.type === 'text_delta'`.
|
|
1554
|
+
* @param payload - Anthropic chunk event payload
|
|
1555
|
+
* @returns The text content, or empty string for non-text deltas
|
|
1556
|
+
*/
|
|
1557
|
+
extractChunkText(payload) {
|
|
1558
|
+
const { delta } = payload;
|
|
1559
|
+
if (delta.type === "text_delta") return delta.text ?? "";
|
|
1560
|
+
return "";
|
|
1561
|
+
}
|
|
1562
|
+
/**
|
|
1563
|
+
* Map an Anthropic usage event payload to the shared `NormalizedCallUsage` format.
|
|
1564
|
+
*
|
|
1565
|
+
* Reads Anthropic-specific cache fields: `cache_read_input_tokens` and
|
|
1566
|
+
* `cache_creation_input_tokens`.
|
|
1567
|
+
* @param payload - Anthropic usage event payload
|
|
1568
|
+
* @returns Normalized usage metrics
|
|
1569
|
+
*/
|
|
1570
|
+
extractUsagePayload(payload) {
|
|
1571
|
+
const usage = payload;
|
|
1572
|
+
return {
|
|
1573
|
+
provider: "anthropic",
|
|
1574
|
+
inputTokens: usage.prompt_tokens,
|
|
1575
|
+
inputCachedTokens: usage.cache_read_input_tokens ?? 0,
|
|
1576
|
+
cacheWriteTokens: usage.cache_creation_input_tokens ?? 0,
|
|
1577
|
+
outputTokens: usage.completion_tokens,
|
|
1578
|
+
reasoningTokens: 0,
|
|
1579
|
+
totalTokens: usage.total_tokens,
|
|
1580
|
+
costUnits: usage.total_tokens,
|
|
1581
|
+
costUnitType: "tokens"
|
|
1582
|
+
};
|
|
1583
|
+
}
|
|
1584
|
+
/**
|
|
1585
|
+
* Emit context window update after Anthropic usage tracking.
|
|
1586
|
+
*
|
|
1587
|
+
* Uses `cache_read_input_tokens` for the cached token count and
|
|
1588
|
+
* defaults to `DEFAULT_CONTEXT_WINDOW_SIZE` (200,000) for Claude models.
|
|
1589
|
+
* @param payload - Anthropic usage event payload
|
|
1590
|
+
*/
|
|
1591
|
+
async emitUsageContextWindowUpdate(payload) {
|
|
1592
|
+
const usage = payload;
|
|
1593
|
+
await this.emitContextWindowUpdate({
|
|
1594
|
+
currentTokens: usage.total_tokens ?? usage.prompt_tokens + (usage.cache_creation_input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0) + usage.completion_tokens,
|
|
1595
|
+
maxTokens: this.getContextWindowSize() ?? DEFAULT_CONTEXT_WINDOW_SIZE,
|
|
1596
|
+
cachedTokens: usage.cache_read_input_tokens
|
|
1597
|
+
});
|
|
1598
|
+
}
|
|
1599
|
+
/**
|
|
1600
|
+
* Reserve a block index for a tool call using Anthropic's provider-native block index.
|
|
1601
|
+
*
|
|
1602
|
+
* Anthropic sends `blockIndex` on each tool call entry in the tool_calls event.
|
|
1603
|
+
* Using the provider index preserves the correct ordering in persisted step history,
|
|
1604
|
+
* even when tool_calls events arrive before text step events.
|
|
1605
|
+
* @param tc - Anthropic tool call entry (carries `blockIndex`)
|
|
1606
|
+
* @returns Provider-native block index from the tool call
|
|
1607
|
+
*/
|
|
1608
|
+
reserveToolCallBlockIndex(tc) {
|
|
1609
|
+
return tc.blockIndex;
|
|
1610
|
+
}
|
|
1611
|
+
/**
|
|
1612
|
+
* Reconcile internal block index after emitting a tool call step.
|
|
1613
|
+
*
|
|
1614
|
+
* Advances the internal block index counter to stay ahead of the provider-native
|
|
1615
|
+
* index, so subsequent text/reasoning steps don't reuse stale indices.
|
|
1616
|
+
* @param blockIndex - The provider block index just emitted
|
|
1617
|
+
*/
|
|
1618
|
+
afterToolCallStepEmitted(blockIndex) {
|
|
1619
|
+
this.reconcileInternalBlockIndex(blockIndex);
|
|
1620
|
+
}
|
|
1621
|
+
/**
|
|
1622
|
+
* Return the fallback block index when no map entry exists for a toolCallId.
|
|
1623
|
+
*
|
|
1624
|
+
* Allocates the current block index and immediately increments the counter to keep
|
|
1625
|
+
* block indices monotonic and non-negative.
|
|
1626
|
+
* @returns Current block index (before increment)
|
|
1627
|
+
*/
|
|
1628
|
+
getFallbackToolCompletedBlockIndex() {
|
|
1629
|
+
const blockIndex = this.getBlockIndex();
|
|
1630
|
+
this.incrementBlockIndex();
|
|
1631
|
+
return blockIndex;
|
|
1632
|
+
}
|
|
1633
|
+
/**
|
|
1634
|
+
* Reconcile internal block index after emitting a tool_completed step.
|
|
1635
|
+
*
|
|
1636
|
+
* Ensures the internal counter is ahead of the resolved block index so later
|
|
1637
|
+
* text/reasoning steps receive fresh, non-conflicting indices.
|
|
1638
|
+
* @param resolvedBlockIndex - The block index used for this tool's step.finished
|
|
1639
|
+
*/
|
|
1640
|
+
afterToolCompletedStepEmitted(resolvedBlockIndex) {
|
|
1641
|
+
this.reconcileInternalBlockIndex(resolvedBlockIndex);
|
|
1642
|
+
}
|
|
1643
|
+
/**
|
|
1644
|
+
* Build the reasoning `SessionMessageBlock` from an Anthropic reasoning_complete payload.
|
|
1645
|
+
*
|
|
1646
|
+
* Includes the `signature` field in block metadata when present. Anthropic requires
|
|
1647
|
+
* the signature for native history round-trip (persisted extended thinking blocks
|
|
1648
|
+
* must include the signature for subsequent API calls).
|
|
1649
|
+
* @param payload - Anthropic reasoning complete event payload
|
|
1650
|
+
* @returns Reasoning block with optional signature metadata
|
|
1651
|
+
*/
|
|
1652
|
+
buildReasoningBlock(payload) {
|
|
1653
|
+
const { content, signature } = payload;
|
|
1654
|
+
if (signature === void 0) return {
|
|
1655
|
+
type: "reasoning",
|
|
1656
|
+
content
|
|
1657
|
+
};
|
|
1658
|
+
return {
|
|
1659
|
+
type: "reasoning",
|
|
1660
|
+
content,
|
|
1661
|
+
metadata: { signature }
|
|
1662
|
+
};
|
|
1663
|
+
}
|
|
1664
|
+
/**
|
|
1665
|
+
* Wire tool approval RPC from connector's scoped bus to global AgentSubjects.toolApprove.
|
|
1666
|
+
*
|
|
1667
|
+
* Uses centralized tool-handling helper for consistent approval flow.
|
|
1668
|
+
* Uses lazy callback to resolve adapterSessionId at request time (not constructor time).
|
|
1669
|
+
* @param connector - The AnthropicSdkConnector to wire RPC from
|
|
1670
|
+
*/
|
|
1671
|
+
wireToolApprovalRpc(connector) {
|
|
1672
|
+
this.addConnectorWiringCleanup(registerToolApprovalHandler(connector, async () => ({
|
|
1673
|
+
adapterId: this.adapterId,
|
|
1674
|
+
adapterName: this.adapterName,
|
|
1675
|
+
agentId: this.agentId,
|
|
1676
|
+
adapterSessionId: await this.getAdapterSessionId(),
|
|
1677
|
+
sessionId: this.sessionId
|
|
1678
|
+
})));
|
|
1679
|
+
}
|
|
1680
|
+
};
|
|
1681
|
+
|
|
1682
|
+
//#endregion
|
|
1683
|
+
//#region src/schemas.ts
|
|
1684
|
+
/**
|
|
1685
|
+
* Zod schema for Anthropic SDK provider-specific configuration.
|
|
1686
|
+
*
|
|
1687
|
+
* Used for:
|
|
1688
|
+
* 1. Type-safe config resolution
|
|
1689
|
+
* 2. Serialization to JSON Schema for web-ui form generation
|
|
1690
|
+
* 3. Runtime validation
|
|
1691
|
+
*/
|
|
1692
|
+
const AnthropicSdkProviderConfigSchema = z.object({
|
|
1693
|
+
/**
|
|
1694
|
+
* Base URL for Anthropic-compatible APIs.
|
|
1695
|
+
* Defaults to Anthropic's API. Use for alternatives like:
|
|
1696
|
+
* - Z.ai proxy: 'https://api.z.ai/api/anthropic'
|
|
1697
|
+
*/
|
|
1698
|
+
baseUrl: z.string().optional().meta({
|
|
1699
|
+
title: "Base URL",
|
|
1700
|
+
description: "Override the default Anthropic API URL"
|
|
1701
|
+
}),
|
|
1702
|
+
/**
|
|
1703
|
+
* Maximum number of tokens to generate per request.
|
|
1704
|
+
* Defaults to 32,000 when not set.
|
|
1705
|
+
*/
|
|
1706
|
+
maxTokens: z.number().int().positive().optional().meta({
|
|
1707
|
+
title: "Max Tokens",
|
|
1708
|
+
description: "Maximum number of tokens to generate per API request (default: 32,000)"
|
|
1709
|
+
})
|
|
1710
|
+
});
|
|
1711
|
+
/**
|
|
1712
|
+
* Zod schema for Anthropic SDK credential input.
|
|
1713
|
+
*
|
|
1714
|
+
* Used for:
|
|
1715
|
+
* 1. Write-only credential capture in settings UI
|
|
1716
|
+
* 2. Secure storage in credential service
|
|
1717
|
+
*/
|
|
1718
|
+
const AnthropicSdkCredentialSchema = z.object({
|
|
1719
|
+
/**
|
|
1720
|
+
* API key for Anthropic.
|
|
1721
|
+
*/
|
|
1722
|
+
apiKey: z.string().optional().meta({
|
|
1723
|
+
title: "API Key",
|
|
1724
|
+
format: "password",
|
|
1725
|
+
description: "Anthropic API key"
|
|
1726
|
+
}) });
|
|
1727
|
+
|
|
1728
|
+
//#endregion
|
|
1729
|
+
//#region src/config.ts
|
|
1730
|
+
/**
|
|
1731
|
+
* Config factory for the Anthropic SDK adapter.
|
|
1732
|
+
*
|
|
1733
|
+
* Resolves model, timeouts, and provider config from the ProviderConfig entity
|
|
1734
|
+
* via the bus, using the Anthropic wire protocol.
|
|
1735
|
+
*/
|
|
1736
|
+
const AnthropicSdkConfig = createAdapterConfigFactory(() => ({
|
|
1737
|
+
adapterName: AnthropicSdkAdapterName,
|
|
1738
|
+
adapterDefaults: {
|
|
1739
|
+
reasoningEffort: "low",
|
|
1740
|
+
providerConfig: {}
|
|
1741
|
+
},
|
|
1742
|
+
schema: AnthropicSdkProviderConfigSchema,
|
|
1743
|
+
adapterDefinition: { defaultTimeouts: DEFAULT_TIMEOUTS },
|
|
1744
|
+
protocol: "anthropic"
|
|
1745
|
+
}));
|
|
1746
|
+
|
|
1747
|
+
//#endregion
|
|
1748
|
+
//#region src/adapter.ts
|
|
1749
|
+
/**
|
|
1750
|
+
* Anthropic SDK Adapter — Domain-level adapter using the three-layer architecture.
|
|
1751
|
+
*
|
|
1752
|
+
* Architecture:
|
|
1753
|
+
* ```
|
|
1754
|
+
* AnthropicSdkAdapter extends AIAdapter
|
|
1755
|
+
* -> creates via agentFactory()
|
|
1756
|
+
* AnthropicSdkAgent extends AIAgent
|
|
1757
|
+
* -> creates via connectorFactory()
|
|
1758
|
+
* AnthropicSdkConnector extends ProceduralAgentConnector
|
|
1759
|
+
* ```
|
|
1760
|
+
*
|
|
1761
|
+
* Responsibilities:
|
|
1762
|
+
* - Handle adapter.startAgent RPC (inherited from AIAdapter)
|
|
1763
|
+
* - Create AnthropicSdkAgent instances with proper configuration
|
|
1764
|
+
* - Emit adapter.initialized and adapter.session.created events
|
|
1765
|
+
* - Manage agent lifecycle (tracking, disposal)
|
|
1766
|
+
* @example
|
|
1767
|
+
* ```typescript
|
|
1768
|
+
* // Using the class directly
|
|
1769
|
+
* const adapter = new AnthropicSdkAdapter();
|
|
1770
|
+
* await adapter.init();
|
|
1771
|
+
*
|
|
1772
|
+
* // Using the convenience factory
|
|
1773
|
+
* const adapter = await createAnthropicSdkAdapter();
|
|
1774
|
+
* ```
|
|
1775
|
+
*/
|
|
1776
|
+
var AnthropicSdkAdapter = class extends AIAdapter {
|
|
1777
|
+
constructor(config) {
|
|
1778
|
+
super({
|
|
1779
|
+
name: AnthropicSdkAdapterName,
|
|
1780
|
+
capabilities: [
|
|
1781
|
+
"tools",
|
|
1782
|
+
"streaming",
|
|
1783
|
+
"systemPrompt:override",
|
|
1784
|
+
"systemPrompt:append"
|
|
1785
|
+
],
|
|
1786
|
+
...config,
|
|
1787
|
+
namespace: AnthropicSdkConnectorNamespace,
|
|
1788
|
+
agentFactory: (agentConfig) => {
|
|
1789
|
+
return new AnthropicSdkAgent(agentConfig);
|
|
1790
|
+
},
|
|
1791
|
+
configFactory: AnthropicSdkConfig.getConfig,
|
|
1792
|
+
connectorFactory: (fullConfig) => new AnthropicSdkConnector(fullConfig),
|
|
1793
|
+
definitionProviders: config?.definitionProviders
|
|
1794
|
+
});
|
|
1795
|
+
}
|
|
1796
|
+
};
|
|
1797
|
+
/**
|
|
1798
|
+
* Factory function to create and initialize an Anthropic SDK adapter.
|
|
1799
|
+
*
|
|
1800
|
+
* Convenience wrapper that creates the adapter and calls init() for you.
|
|
1801
|
+
* @param config - Optional adapter configuration
|
|
1802
|
+
* @returns Initialized AnthropicSdkAdapter instance
|
|
1803
|
+
* @example
|
|
1804
|
+
* ```typescript
|
|
1805
|
+
* const adapter = await createAnthropicSdkAdapter();
|
|
1806
|
+
*
|
|
1807
|
+
* // Adapter is ready to handle requests via bus
|
|
1808
|
+
* // e.g., MakaioBus.request(AdapterSubjects.startAgent, { adapterId: adapter.adapterId, ... })
|
|
1809
|
+
* ```
|
|
1810
|
+
*/
|
|
1811
|
+
async function createAnthropicSdkAdapter(config) {
|
|
1812
|
+
const adapter = new AnthropicSdkAdapter(config);
|
|
1813
|
+
await adapter.init();
|
|
1814
|
+
return adapter;
|
|
1815
|
+
}
|
|
1816
|
+
|
|
1817
|
+
//#endregion
|
|
1818
|
+
//#region src/provider.ts
|
|
1819
|
+
/**
|
|
1820
|
+
* Provider IDs and preset configuration for the Anthropic SDK adapter.
|
|
1821
|
+
*
|
|
1822
|
+
* The Anthropic SDK adapter supports any Anthropic-compatible API.
|
|
1823
|
+
* Provider compatibility is declared by stable definition ID — the adapter
|
|
1824
|
+
* subsystem resolves each ID to a full ProviderDefinitionInput from the
|
|
1825
|
+
* provider registry at boot time.
|
|
1826
|
+
*
|
|
1827
|
+
* Add new provider IDs here when introducing an Anthropic-compatible provider.
|
|
1828
|
+
*/
|
|
1829
|
+
const providerIds = [
|
|
1830
|
+
"z-ai",
|
|
1831
|
+
"alibaba",
|
|
1832
|
+
"opencode-go-anthropic",
|
|
1833
|
+
"anthropic"
|
|
1834
|
+
];
|
|
1835
|
+
/**
|
|
1836
|
+
* Default provider id to use when no provider is explicitly configured.
|
|
1837
|
+
*
|
|
1838
|
+
* Semantically `anthropic` — the native provider for this adapter.
|
|
1839
|
+
*/
|
|
1840
|
+
const defaultPresetId = "anthropic";
|
|
1841
|
+
/**
|
|
1842
|
+
* Provider id used for conformance tests.
|
|
1843
|
+
*
|
|
1844
|
+
* Set to `opencode-go-anthropic` so test runs exercise the Anthropic-compatible
|
|
1845
|
+
* OpenCode Go preset without hitting the direct Anthropic API.
|
|
1846
|
+
*/
|
|
1847
|
+
const testPresetId = "opencode-go-anthropic";
|
|
1848
|
+
|
|
1849
|
+
//#endregion
|
|
1850
|
+
//#region src/definition.ts
|
|
1851
|
+
const adapterDefinition = {
|
|
1852
|
+
name: AnthropicSdkAdapterName,
|
|
1853
|
+
displayName: "Anthropic SDK",
|
|
1854
|
+
defaultPresetId,
|
|
1855
|
+
description: "Anthropic Messages API with streaming, tool calling, and extended thinking",
|
|
1856
|
+
providers: providerIds.map((definitionId) => ({ definitionId })),
|
|
1857
|
+
providerConfigSchema: AnthropicSdkProviderConfigSchema,
|
|
1858
|
+
providerCredentialSchema: AnthropicSdkCredentialSchema,
|
|
1859
|
+
defaultTimeouts: DEFAULT_TIMEOUTS,
|
|
1860
|
+
helpLinks: [{
|
|
1861
|
+
label: "Anthropic API Documentation",
|
|
1862
|
+
url: "https://docs.anthropic.com/en/api"
|
|
1863
|
+
}, {
|
|
1864
|
+
label: "API Keys",
|
|
1865
|
+
url: "https://console.anthropic.com/settings/keys"
|
|
1866
|
+
}],
|
|
1867
|
+
instructions: `To use Anthropic directly, you need an API key:
|
|
1868
|
+
|
|
1869
|
+
1. Go to [console.anthropic.com/settings/keys](https://console.anthropic.com/settings/keys)
|
|
1870
|
+
2. Create a new API key
|
|
1871
|
+
3. Copy and paste it below
|
|
1872
|
+
|
|
1873
|
+
> **Tip:** Use \`keychain:anthropic:api-key\` to store securely in your system keychain.
|
|
1874
|
+
|
|
1875
|
+
Alternatively, select the **Z.ai** preset to use the Z.ai Anthropic-compatible proxy with your Z.ai API key.`,
|
|
1876
|
+
protocol: "anthropic",
|
|
1877
|
+
createAdapter: createAnthropicSdkAdapter
|
|
1878
|
+
};
|
|
1879
|
+
|
|
1880
|
+
//#endregion
|
|
1881
|
+
//#region src/package.ts
|
|
1882
|
+
/**
|
|
1883
|
+
* MakaioNodeExtension<IMakaioBus> descriptor for the Anthropic SDK adapter.
|
|
1884
|
+
*
|
|
1885
|
+
* Wraps the existing {@link adapterDefinition} in the standard
|
|
1886
|
+
* `MakaioNodeExtension<IMakaioBus>` shape so the runtime coordinator can discover and
|
|
1887
|
+
* register this adapter through the unified adapter contribution surface.
|
|
1888
|
+
*/
|
|
1889
|
+
/**
|
|
1890
|
+
* Package descriptor for the Anthropic SDK adapter.
|
|
1891
|
+
*
|
|
1892
|
+
* API-only adapter (no client binary dependency). Declares the `anthropic`
|
|
1893
|
+
* wire protocol, which covers the native Anthropic Messages API as well as
|
|
1894
|
+
* compatible proxies (Z.ai, Alibaba, opencode-go).
|
|
1895
|
+
*/
|
|
1896
|
+
const anthropicSdkPackage = {
|
|
1897
|
+
name: AnthropicSdkAdapterName,
|
|
1898
|
+
displayName: "Anthropic SDK",
|
|
1899
|
+
version: "0.1.0",
|
|
1900
|
+
dependencies: [
|
|
1901
|
+
dep("provider-anthropic"),
|
|
1902
|
+
dep("provider-z-ai"),
|
|
1903
|
+
dep("provider-alibaba"),
|
|
1904
|
+
dep("provider-opencode-go")
|
|
1905
|
+
],
|
|
1906
|
+
adapters: [{
|
|
1907
|
+
manifest: {
|
|
1908
|
+
name: AnthropicSdkAdapterName,
|
|
1909
|
+
displayName: "Anthropic SDK",
|
|
1910
|
+
description: "Anthropic Messages API with streaming, tool calling, and extended thinking",
|
|
1911
|
+
protocols: ["anthropic"]
|
|
1912
|
+
},
|
|
1913
|
+
definition: adapterDefinition
|
|
1914
|
+
}]
|
|
1915
|
+
};
|
|
1916
|
+
|
|
1917
|
+
//#endregion
|
|
1918
|
+
//#region src/index.ts
|
|
1919
|
+
/**
|
|
1920
|
+
* Anthropic SDK Adapter
|
|
1921
|
+
*
|
|
1922
|
+
* Provides a three-layer adapter implementation for the Anthropic SDK:
|
|
1923
|
+
* - AnthropicSdkAdapter: Domain-level adapter, handles adapter.* subjects
|
|
1924
|
+
* - AnthropicSdkAgent: Agent wrapper, handles agent.* subjects
|
|
1925
|
+
* - AnthropicSdkConnector: SDK connector, handles provider communication
|
|
1926
|
+
* @example
|
|
1927
|
+
* ```typescript
|
|
1928
|
+
* import { AnthropicSdkAdapter, createAnthropicSdkAdapter } from '@makaio/adapter-anthropic-sdk';
|
|
1929
|
+
*
|
|
1930
|
+
* // Using the class-based adapter
|
|
1931
|
+
* const adapter = new AnthropicSdkAdapter();
|
|
1932
|
+
* await adapter.init();
|
|
1933
|
+
*
|
|
1934
|
+
* // Or using the convenience factory
|
|
1935
|
+
* const adapter = await createAnthropicSdkAdapter();
|
|
1936
|
+
*
|
|
1937
|
+
* // Adapter is ready to handle adapter.startAgent RPC via bus
|
|
1938
|
+
* // Start agents via MakaioBus.request(AdapterSubjects.startAgent, { adapterId, ... })
|
|
1939
|
+
* ```
|
|
1940
|
+
* @packageDocumentation
|
|
1941
|
+
*/
|
|
1942
|
+
/**
|
|
1943
|
+
* Creates test configuration for conformance test suite.
|
|
1944
|
+
* Sets up scoped bus and tool approval proxy.
|
|
1945
|
+
* @param options - Provider definitions supplied by the conformance harness
|
|
1946
|
+
* @returns Configuration for running conformance tests against this adapter
|
|
1947
|
+
*/
|
|
1948
|
+
const createTestConfig = async (options) => {
|
|
1949
|
+
const { scopedBus } = AnthropicSdkConnectorNamespace;
|
|
1950
|
+
const bus = await scopedBus();
|
|
1951
|
+
const testPreset = resolveConformanceTestPreset({
|
|
1952
|
+
adapterName: AnthropicSdkAdapterName,
|
|
1953
|
+
defaultProviderId: testPresetId,
|
|
1954
|
+
providerIds,
|
|
1955
|
+
providerDefinitions: options?.providerDefinitions,
|
|
1956
|
+
reasoningEffort: "low"
|
|
1957
|
+
});
|
|
1958
|
+
return {
|
|
1959
|
+
createConnector: async (options) => new AnthropicSdkConnector(await AnthropicSdkConfig.getConfig(resolveTestConfig(options, bus, testPreset.provider, testPreset.providers))),
|
|
1960
|
+
bus,
|
|
1961
|
+
registerToolApprovalHandler,
|
|
1962
|
+
capabilities: {
|
|
1963
|
+
supportsReplace: true,
|
|
1964
|
+
supportsInterrupt: true,
|
|
1965
|
+
supportsUsageMetrics: true
|
|
1966
|
+
},
|
|
1967
|
+
options: {
|
|
1968
|
+
defaultTimeout: 9e4,
|
|
1969
|
+
concurrency: 8,
|
|
1970
|
+
primaryModel: testPreset.primaryModel,
|
|
1971
|
+
secondaryModel: testPreset.secondaryModel
|
|
1972
|
+
},
|
|
1973
|
+
createAdapter: async (options) => createAnthropicSdkAdapter({ adapterId: options?.adapterId }),
|
|
1974
|
+
adapterName: AnthropicSdkAdapterName,
|
|
1975
|
+
testProviderContext: testPreset.providerContext
|
|
1976
|
+
};
|
|
1977
|
+
};
|
|
1978
|
+
|
|
1979
|
+
//#endregion
|
|
1980
|
+
export { ANTHROPIC_SDK_NAMESPACE, AnthropicSdkAdapter, AnthropicSdkAdapterName, AnthropicSdkAgent, AnthropicSdkConnector, AnthropicSdkConnectorNamespace, AnthropicSdkConnectorSubjects, AnthropicSdkConnectorTurn, AnthropicSdkSession, UserMessageQueue, anthropicSdkPackage, createAnthropicSdkAdapter, createTestConfig };
|