@makaio/adapter-anthropic-sdk 1.0.0-dev-1795338532209 → 1.0.0-dev-1795406265449

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/agent.d.ts CHANGED
@@ -2,7 +2,7 @@ import { BaseStreamAgent, type StreamAdapterSubjectSpec } from '@makaio/framewor
2
2
  import type { NormalizedCallUsage } from '@makaio/framework/adapters';
3
3
  import { AnthropicSdkConnector } from './connector.js';
4
4
  import { AnthropicSdkConnectorSubjects, type AnthropicSdkConnectorBus, type ToolCall } from './namespaces/index.js';
5
- import type { SessionMessageBlock } from '@makaio/framework/contracts';
5
+ import type { CallContext, SessionMessageBlock } from '@makaio/framework/contracts';
6
6
  /**
7
7
  * Subject spec for the Anthropic SDK adapter, satisfying `StreamAdapterSubjectSpec`.
8
8
  *
@@ -67,6 +67,7 @@ export declare class AnthropicSdkAgent extends BaseStreamAgent<AnthropicSdkConne
67
67
  *
68
68
  * Granularity is `provider-call`: each usage event is merged from the
69
69
  * `message_start`/`message_delta` frames of exactly one Anthropic request.
70
+ * @param call - Call context of the usage event being translated
70
71
  * @param payload - Anthropic usage event payload
71
72
  * @returns Normalized usage metrics
72
73
  */
@@ -76,9 +77,10 @@ export declare class AnthropicSdkAgent extends BaseStreamAgent<AnthropicSdkConne
76
77
  *
77
78
  * Uses `cache_read_input_tokens` for the cached token count and
78
79
  * defaults to `DEFAULT_CONTEXT_WINDOW_SIZE` (200,000) for Claude models.
80
+ * @param call - Call context of the usage event being translated
79
81
  * @param payload - Anthropic usage event payload
80
82
  */
81
- protected emitUsageContextWindowUpdate(payload: Record<string, unknown>): Promise<void>;
83
+ protected emitUsageContextWindowUpdate(call: CallContext, payload: Record<string, unknown>): Promise<void>;
82
84
  /**
83
85
  * Reserve a block index for a tool call using Anthropic's provider-native block index.
84
86
  *
package/dist/config.d.ts CHANGED
@@ -10,13 +10,13 @@ export declare const AnthropicSdkConfig: {
10
10
  adapterId?: string;
11
11
  }>>(input: TInput) => Promise<Partial<Omit<AnthropicSdkAgentConfig & {
12
12
  adapterId?: string;
13
- }, "adapterName" | "agentId" | "bus" | "sessionId">> & Omit<TInput, "adapterProviderAuth" | "compatibleProviderAuths" | "providerConfig" | "providerContextRequired"> & import("@makaio/framework/adapters/config").FactoryGuaranteedFields<{
13
+ }, "adapterName" | "agentId" | "bus" | "globalBus" | "sessionId">> & Omit<TInput, "adapterProviderAuth" | "compatibleProviderAuths" | "providerConfig" | "providerContextRequired"> & import("@makaio/framework/adapters/config").FactoryGuaranteedFields<{
14
14
  baseUrl?: string | undefined;
15
15
  requestCorrelationHeaders?: "factory-v1" | undefined;
16
16
  maxTokens?: number | undefined;
17
17
  } | undefined> extends infer T ? { [KeyType in keyof T]: T[KeyType]; } : never>;
18
18
  getDefaults: () => Partial<Omit<AnthropicSdkAgentConfig & {
19
19
  adapterId?: string;
20
- }, "adapterName" | "agentId" | "bus" | "sessionId">>;
20
+ }, "adapterName" | "agentId" | "bus" | "globalBus" | "sessionId">>;
21
21
  };
22
22
  //# sourceMappingURL=config.d.ts.map
@@ -1,3 +1,4 @@
1
+ import type { CallContext } from '@makaio/framework/core';
1
2
  import type { WireSessionSubjects } from '@makaio/framework/adapters';
2
3
  import { BaseStreamConnector } from '@makaio/framework/adapters/stream-session';
3
4
  import type { AnthropicSdkAgentConfig, AnthropicSdkBus } from './types/index.js';
@@ -33,23 +34,25 @@ export declare class AnthropicSdkConnector extends BaseStreamConnector<Anthropic
33
34
  *
34
35
  * Also converts fetched tools to Anthropic format and caches them in
35
36
  * `this.anthropicTools` for use in `createSession`.
37
+ * @param call - Call of the message initializing the session
36
38
  */
37
- protected fetchTools(): Promise<void>;
39
+ protected fetchTools(call: CallContext): Promise<void>;
38
40
  /**
39
41
  * Re-fetch native tools and re-resolve MCP direct-inject tools.
40
42
  *
41
43
  * Called at turn boundary when `hasPendingToolRefresh` is true.
42
44
  * Re-fetches Anthropic-format tools from the registry, re-prepares MCP
43
- * direct tools (and arms the ledger injection flag via `super.refreshTools()`),
45
+ * direct tools (and arms the ledger injection flag via `super.refreshTools(call)`),
44
46
  * then notifies the active session so the next API call uses the updated
45
47
  * merged tool list. The ledger `recordInjection` is deferred to
46
48
  * `onTurnStarted` so it uses the canonical turn number.
49
+ * @param call - Call of the turn event triggering the refresh
47
50
  */
48
- protected refreshTools(): Promise<void>;
51
+ protected refreshTools(call: CallContext): Promise<void>;
49
52
  /**
50
53
  * Construct the Anthropic SDK session with all required config.
51
54
  *
52
- * Called by `BaseStreamConnector.initializeSession()` after `fetchTools()`
55
+ * Called by `BaseStreamConnector.initializeSession()` after `fetchTools(call)`
53
56
  * has resolved credentials and initialized `this.client`.
54
57
  * @returns A new `AnthropicSdkSession` instance
55
58
  */
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import { a as AnthropicSdkAdapterName, c as AnthropicSdkAgent, d as ANTHROPIC_SDK_NAMESPACE, i as AnthropicSdkConnector, l as AnthropicSdkConnectorNamespace, n as AnthropicSdkAdapter, o as AnthropicSdkSession, r as createAnthropicSdkAdapter, s as AnthropicSdkConnectorTurn, t as anthropicSdkPackage, u as AnthropicSdkConnectorSubjects } from "./package-CYLUpLS-.mjs";
2
+ import { a as AnthropicSdkAdapterName, c as AnthropicSdkAgent, d as ANTHROPIC_SDK_NAMESPACE, i as AnthropicSdkConnector, l as AnthropicSdkConnectorNamespace, n as AnthropicSdkAdapter, o as AnthropicSdkSession, r as createAnthropicSdkAdapter, s as AnthropicSdkConnectorTurn, t as anthropicSdkPackage, u as AnthropicSdkConnectorSubjects } from "./package-ml6mifti.mjs";
3
3
  import { UserMessageQueue } from "@makaio/framework/adapters";
4
4
 
5
5
  export { ANTHROPIC_SDK_NAMESPACE, AnthropicSdkAdapter, AnthropicSdkAdapterName, AnthropicSdkAgent, AnthropicSdkConnector, AnthropicSdkConnectorNamespace, AnthropicSdkConnectorSubjects, AnthropicSdkConnectorTurn, AnthropicSdkSession, UserMessageQueue, anthropicSdkPackage, createAnthropicSdkAdapter };
@@ -3,7 +3,6 @@ import { AIAdapter, ProceduralConnectorTurn, ScopedToolApprovalSchema, bindProvi
3
3
  import { AgentCompleteEventSchema, AgentStartedEventSchema, BaseStreamAgent, BaseStreamConnector, BaseStreamSession, ErrorEventSchema, MessageCompleteEventSchema, ReasoningCompleteEventSchema, ReasoningDeltaEventSchema, ToolCallSchema, ToolCompletedEventSchema, ToolStartedEventSchema, TurnStateChangedSchema, filterToolsWithSchema, handleToolCalls, loadToolsFromRegistry } from "@makaio/framework/adapters/stream-session";
4
4
  import { z } from "zod";
5
5
  import Anthropic, { APIError } from "@anthropic-ai/sdk";
6
- import { MakaioBus } from "@makaio/framework/bus";
7
6
  import { AuthenticationError, ModelUnavailableError, QuotaExceededError, RateLimitError } from "@makaio/framework/core";
8
7
  import { createAdapterConfigFactory } from "@makaio/framework/adapters/config";
9
8
  import { defineAdapterProviderAuth, dep } from "@makaio/framework/contracts";
@@ -280,27 +279,29 @@ function toAnthropicToolFormat(tools) {
280
279
  }
281
280
  /**
282
281
  * Convenience: Load tools and convert to Anthropic format in one call.
282
+ * @param call - Call of the message requesting registry tools
283
283
  * @param bus - Bus that owns the ToolRegistry handlers
284
284
  * @param adapterId - Adapter instance ID
285
285
  * @param adapterName - Adapter type name
286
286
  * @param options - Optional adapter runtime tool allow/deny filters
287
287
  * @returns Anthropic-formatted tools ready for messages.create
288
288
  */
289
- async function fetchToolsForAnthropic(bus, adapterId, adapterName, options) {
290
- return toAnthropicToolFormat(await loadToolsFromRegistry(bus, adapterId, adapterName, options));
289
+ async function fetchToolsForAnthropic(call, bus, adapterId, adapterName, options) {
290
+ return toAnthropicToolFormat(await loadToolsFromRegistry(call, bus, adapterId, adapterName, options));
291
291
  }
292
292
  /**
293
293
  * Process tool calls: request approval, execute, and return tool result blocks.
294
294
  *
295
295
  * Returns Anthropic-format tool results: `{ role: 'user', content: [{ type: 'tool_result', ... }] }`
296
296
  * is assembled by the caller using the returned ToolResultBlockParam[].
297
+ * @param call - Call context of the turn's message handle; forwarded to approval, lifecycle events and tool execution
297
298
  * @param toolCalls - Array of normalized tool calls from the stream-bridge tool_calls event
298
299
  * @param callbacks - Injected callbacks for event emission, approval requests, and optional ledger recording
299
300
  * @param contextOverrides - Execution context (cwd, env, sessionId, agentId, turnId)
300
301
  * @returns Tool result blocks to inject into the next user message
301
302
  */
302
- async function handleToolCalls$1(toolCalls, callbacks, contextOverrides) {
303
- return handleToolCalls(toolCalls, callbacks, contextOverrides, (toolCallId, content, isError) => ({
303
+ async function handleToolCalls$1(call, toolCalls, callbacks, contextOverrides) {
304
+ return handleToolCalls(call, toolCalls, callbacks, contextOverrides, (toolCallId, content, isError) => ({
304
305
  type: "tool_result",
305
306
  tool_use_id: toolCallId,
306
307
  content,
@@ -401,6 +402,7 @@ var AnthropicSdkAgent = class extends BaseStreamAgent {
401
402
  *
402
403
  * Granularity is `provider-call`: each usage event is merged from the
403
404
  * `message_start`/`message_delta` frames of exactly one Anthropic request.
405
+ * @param call - Call context of the usage event being translated
404
406
  * @param payload - Anthropic usage event payload
405
407
  * @returns Normalized usage metrics
406
408
  */
@@ -427,11 +429,12 @@ var AnthropicSdkAgent = class extends BaseStreamAgent {
427
429
  *
428
430
  * Uses `cache_read_input_tokens` for the cached token count and
429
431
  * defaults to `DEFAULT_CONTEXT_WINDOW_SIZE` (200,000) for Claude models.
432
+ * @param call - Call context of the usage event being translated
430
433
  * @param payload - Anthropic usage event payload
431
434
  */
432
- async emitUsageContextWindowUpdate(payload) {
435
+ async emitUsageContextWindowUpdate(call, payload) {
433
436
  const usage = payload;
434
- await this.emitContextWindowUpdate({
437
+ await this.emitContextWindowUpdate(call, {
435
438
  currentTokens: usage.total_tokens ?? usage.prompt_tokens + (usage.cache_creation_input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0) + usage.completion_tokens,
436
439
  maxTokens: this.getContextWindowSize() ?? DEFAULT_CONTEXT_WINDOW_SIZE,
437
440
  cachedTokens: usage.cache_read_input_tokens
@@ -510,11 +513,11 @@ var AnthropicSdkAgent = class extends BaseStreamAgent {
510
513
  * @param connector - The AnthropicSdkConnector to wire RPC from
511
514
  */
512
515
  wireToolApprovalRpc(connector) {
513
- this.addConnectorWiringCleanup(registerToolApprovalHandler(connector, async () => ({
516
+ this.addConnectorWiringCleanup(registerToolApprovalHandler(connector, async (call) => ({
514
517
  adapterId: this.adapterId,
515
518
  adapterName: this.adapterName,
516
519
  agentId: this.agentId,
517
- adapterSessionId: await this.getAdapterSessionId(),
520
+ adapterSessionId: await this.getAdapterSessionId(call),
518
521
  sessionId: this.sessionId
519
522
  }), this.config.globalBus));
520
523
  }
@@ -559,10 +562,11 @@ var AnthropicSdkConnectorTurn = class extends ProceduralConnectorTurn {
559
562
  * Pause (abort) at next opportunity.
560
563
  * The Anthropic SDK adapter does not support true pause — caller restarts
561
564
  * with merged content when a replacement turn arrives.
565
+ * @param call - Call of the message requesting the pause
562
566
  * @returns Pause result indicating turn state
563
567
  */
564
- async pause() {
565
- const result = await super.pause();
568
+ async pause(call) {
569
+ const result = await super.pause(call);
566
570
  if (!result.turnEnded) this.abortController.abort();
567
571
  return result;
568
572
  }
@@ -632,14 +636,14 @@ function createStreamState() {
632
636
  * @returns Async emitter for SdkEventMessage payloads.
633
637
  */
634
638
  function buildEventEmitter(config, metadata) {
635
- return async (event) => {
639
+ return async (call, event) => {
636
640
  const correlatedEvent = event.eventType === "usage" && config.requestCorrelation !== void 0 ? {
637
641
  ...event,
638
642
  llmCallId: config.requestCorrelation.llmCallId,
639
643
  ...config.requestCorrelation.executionId !== void 0 ? { executionId: config.requestCorrelation.executionId } : {},
640
644
  ...config.requestCorrelation.frameId !== void 0 ? { frameId: config.requestCorrelation.frameId } : {}
641
645
  } : event;
642
- await config.bus.emit(AnthropicSdkConnectorSubjects.sdk.event, {
646
+ await config.bus.emit(call, AnthropicSdkConnectorSubjects.sdk.event, {
643
647
  event: correlatedEvent,
644
648
  ...metadata
645
649
  });
@@ -647,18 +651,19 @@ function buildEventEmitter(config, metadata) {
647
651
  }
648
652
  /**
649
653
  * Handle content_block_delta: accumulate delta content and emit streaming events.
654
+ * @param call - Call context of the handled message.
650
655
  * @param index - Content block index from the stream event.
651
656
  * @param event - The full content_block_delta event.
652
657
  * @param state - Mutable stream state.
653
658
  * @param emitEvent - Normalized event emitter.
654
659
  */
655
- async function handleContentBlockDelta(index, event, state, emitEvent) {
660
+ async function handleContentBlockDelta(call, index, event, state, emitEvent) {
656
661
  const block = state.contentBlocks.get(index);
657
662
  const rawDelta = event.delta;
658
663
  if (rawDelta.type === "text_delta") {
659
664
  if (block) block.text = (block.text ?? "") + rawDelta.text;
660
665
  state.content += rawDelta.text;
661
- await emitEvent({
666
+ await emitEvent(call, {
662
667
  eventType: "chunk",
663
668
  index,
664
669
  delta: {
@@ -669,11 +674,11 @@ async function handleContentBlockDelta(index, event, state, emitEvent) {
669
674
  } else if (rawDelta.type === "thinking_delta") {
670
675
  if (block) block.thinking = (block.thinking ?? "") + rawDelta.thinking;
671
676
  state.reasoning += rawDelta.thinking;
672
- await emitEvent({
677
+ await emitEvent(call, {
673
678
  eventType: "reasoning_delta",
674
679
  content: rawDelta.thinking
675
680
  });
676
- await emitEvent({
681
+ await emitEvent(call, {
677
682
  eventType: "chunk",
678
683
  index,
679
684
  delta: {
@@ -683,7 +688,7 @@ async function handleContentBlockDelta(index, event, state, emitEvent) {
683
688
  });
684
689
  } else if (rawDelta.type === "input_json_delta") {
685
690
  if (block) block.jsonAccumulator = (block.jsonAccumulator ?? "") + rawDelta.partial_json;
686
- await emitEvent({
691
+ await emitEvent(call, {
687
692
  eventType: "chunk",
688
693
  index,
689
694
  delta: {
@@ -714,13 +719,14 @@ function handleContentBlockStop(index, state) {
714
719
  }
715
720
  /**
716
721
  * Emit final semantic events once the stream has ended.
722
+ * @param call - Call context of the handled message.
717
723
  * @param state - Final aggregated stream state.
718
724
  * @param emitEvent - Normalized event emitter.
719
725
  */
720
- async function emitFinalEvents(state, emitEvent) {
726
+ async function emitFinalEvents(call, state, emitEvent) {
721
727
  if (state.usage) {
722
728
  const { inputTokens, outputTokens, cacheReadInputTokens, cacheCreationInputTokens } = state.usage;
723
- await emitEvent({
729
+ await emitEvent(call, {
724
730
  eventType: "usage",
725
731
  prompt_tokens: inputTokens,
726
732
  completion_tokens: outputTokens,
@@ -738,16 +744,16 @@ async function emitFinalEvents(state, emitEvent) {
738
744
  arguments: tc.arguments
739
745
  }
740
746
  })) : void 0;
741
- if (toolCallPayload) await emitEvent({
747
+ if (toolCallPayload) await emitEvent(call, {
742
748
  eventType: "tool_calls",
743
749
  toolCalls: toolCallPayload
744
750
  });
745
- if (state.reasoning) await emitEvent({
751
+ if (state.reasoning) await emitEvent(call, {
746
752
  eventType: "reasoning_complete",
747
753
  content: state.reasoning,
748
754
  ...state.reasoningSignature !== void 0 ? { signature: state.reasoningSignature } : {}
749
755
  });
750
- await emitEvent({
756
+ await emitEvent(call, {
751
757
  eventType: "message_complete",
752
758
  content: state.content || null,
753
759
  reasoning: state.reasoning || void 0,
@@ -765,10 +771,11 @@ async function emitFinalEvents(state, emitEvent) {
765
771
  * Emits to bus as the stream progresses:
766
772
  * - sdk.raw: Each raw Anthropic event (observability)
767
773
  * - sdk.event: Semantic events — chunk, reasoning_delta, reasoning_complete, usage, tool_calls, message_complete
774
+ * @param call - Call context of the handled message.
768
775
  * @param stream - The Anthropic streaming response.
769
776
  * @param config - Bridge configuration with bus, agent identity, and model.
770
777
  */
771
- async function processStream(stream, config) {
778
+ async function processStream(call, stream, config) {
772
779
  const state = createStreamState();
773
780
  const metadata = {
774
781
  adapterName: config.adapterName,
@@ -781,7 +788,7 @@ async function processStream(stream, config) {
781
788
  } : metadata);
782
789
  for await (const event of stream) {
783
790
  config.logLowLevelEvent?.(event);
784
- await config.bus.emit(AnthropicSdkConnectorSubjects.sdk.raw, event);
791
+ await config.bus.emit(call, AnthropicSdkConnectorSubjects.sdk.raw, event);
785
792
  switch (event.type) {
786
793
  case "message_start":
787
794
  state.usage = mergeInitialUsage(event.message.usage);
@@ -806,7 +813,7 @@ async function processStream(stream, config) {
806
813
  break;
807
814
  }
808
815
  case "content_block_delta":
809
- await handleContentBlockDelta(event.index, event, state, emitEvent);
816
+ await handleContentBlockDelta(call, event.index, event, state, emitEvent);
810
817
  break;
811
818
  case "content_block_stop":
812
819
  handleContentBlockStop(event.index, state);
@@ -818,7 +825,7 @@ async function processStream(stream, config) {
818
825
  case "message_stop": break;
819
826
  }
820
827
  }
821
- await emitFinalEvents(state, emitEvent);
828
+ await emitFinalEvents(call, state, emitEvent);
822
829
  }
823
830
 
824
831
  //#endregion
@@ -1518,9 +1525,9 @@ var AnthropicSdkSession = class extends BaseStreamSession {
1518
1525
  signal: abortSignal,
1519
1526
  ...this.config.requestCorrelationHeaders === "factory-v1" ? { headers: buildFactoryUsageCorrelationHeaders(requestCorrelation) } : {}
1520
1527
  });
1521
- await turn.markStepStarted();
1528
+ await turn.markStepStarted(handle.call);
1522
1529
  try {
1523
- await processStream(stream, {
1530
+ await processStream(handle.call, stream, {
1524
1531
  bus: this.config.bus,
1525
1532
  agentId: this.config.agentId,
1526
1533
  adapterId: this.config.adapterId,
@@ -1531,7 +1538,7 @@ var AnthropicSdkSession = class extends BaseStreamSession {
1531
1538
  logLowLevelEvent: this.config.logLowLevelEvent
1532
1539
  });
1533
1540
  } finally {
1534
- await turn.markStepFinished();
1541
+ await turn.markStepFinished(handle.call);
1535
1542
  }
1536
1543
  }
1537
1544
  /**
@@ -1581,8 +1588,8 @@ var AnthropicSdkSession = class extends BaseStreamSession {
1581
1588
  this.lastAssistantMessage = messageContent || "";
1582
1589
  if (result.finish_reason === "tool_use" && result.tool_calls && result.tool_calls.length > 0) {
1583
1590
  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.`);
1584
- const toolResultBlocks = await handleToolCalls$1(result.tool_calls, {
1585
- bus: this.config.globalBus ?? MakaioBus,
1591
+ const toolResultBlocks = await handleToolCalls$1(currentHandle.call, result.tool_calls, {
1592
+ bus: this.config.globalBus,
1586
1593
  emitSdkEvent: this.config.emitSdkEvent,
1587
1594
  requestToolApproval: this.config.requestToolApproval,
1588
1595
  recordMcpCall: this.config.recordMcpCall
@@ -1704,8 +1711,6 @@ function resolveAnthropicConstructorAuth(auth) {
1704
1711
 
1705
1712
  //#endregion
1706
1713
  //#region src/connector.ts
1707
- /** Default scoped bus for Anthropic SDK adapter */
1708
- const defaultBus = await AnthropicSdkConnectorNamespace.scopedBus();
1709
1714
  /**
1710
1715
  * Anthropic SDK Connector — Wraps the Anthropic SDK for agentic message creation.
1711
1716
  *
@@ -1729,17 +1734,17 @@ var AnthropicSdkConnector = class extends BaseStreamConnector {
1729
1734
  anthropicTools = [];
1730
1735
  /**
1731
1736
  * Emit an SDK event wrapped in envelope for type-safe discriminated union handling.
1737
+ * @param call - Call context of the turn the event belongs to
1732
1738
  * @param event - The typed SDK event message to emit
1733
1739
  */
1734
- async emitSdkEvent(event) {
1735
- await this.emit(AnthropicSdkConnectorSubjects.sdk.event, { event });
1740
+ async emitSdkEvent(call, event) {
1741
+ await this.emit(call, AnthropicSdkConnectorSubjects.sdk.event, { event });
1736
1742
  }
1737
1743
  constructor(config) {
1738
1744
  const { adapterAuth, ...baseConfig } = config;
1739
1745
  super({
1740
1746
  ...baseConfig,
1741
1747
  env: baseConfig.env ?? {},
1742
- bus: config?.bus ?? defaultBus,
1743
1748
  adapterId: config?.adapterId ?? crypto.randomUUID(),
1744
1749
  adapterName: config?.adapterName ?? "anthropic-sdk"
1745
1750
  });
@@ -1753,14 +1758,15 @@ var AnthropicSdkConnector = class extends BaseStreamConnector {
1753
1758
  *
1754
1759
  * Also converts fetched tools to Anthropic format and caches them in
1755
1760
  * `this.anthropicTools` for use in `createSession`.
1761
+ * @param call - Call of the message initializing the session
1756
1762
  */
1757
- async fetchTools() {
1763
+ async fetchTools(call) {
1758
1764
  const baseUrl = this.config.providerConfig?.baseUrl;
1759
1765
  this.client = new Anthropic({
1760
1766
  ...this.constructorAuth,
1761
1767
  baseURL: baseUrl ?? void 0
1762
1768
  });
1763
- this.anthropicTools = await fetchToolsForAnthropic(this.config.globalBus ?? MakaioBus, this.adapterId, this.adapterName, {
1769
+ this.anthropicTools = await fetchToolsForAnthropic(call, this.config.globalBus, this.adapterId, this.adapterName, {
1764
1770
  allowedTools: this.config.allowedTools,
1765
1771
  disallowedTools: this.config.disallowedTools
1766
1772
  });
@@ -1770,17 +1776,18 @@ var AnthropicSdkConnector = class extends BaseStreamConnector {
1770
1776
  *
1771
1777
  * Called at turn boundary when `hasPendingToolRefresh` is true.
1772
1778
  * Re-fetches Anthropic-format tools from the registry, re-prepares MCP
1773
- * direct tools (and arms the ledger injection flag via `super.refreshTools()`),
1779
+ * direct tools (and arms the ledger injection flag via `super.refreshTools(call)`),
1774
1780
  * then notifies the active session so the next API call uses the updated
1775
1781
  * merged tool list. The ledger `recordInjection` is deferred to
1776
1782
  * `onTurnStarted` so it uses the canonical turn number.
1783
+ * @param call - Call of the turn event triggering the refresh
1777
1784
  */
1778
- async refreshTools() {
1779
- this.anthropicTools = await fetchToolsForAnthropic(this.config.globalBus ?? MakaioBus, this.adapterId, this.adapterName, {
1785
+ async refreshTools(call) {
1786
+ this.anthropicTools = await fetchToolsForAnthropic(call, this.config.globalBus, this.adapterId, this.adapterName, {
1780
1787
  allowedTools: this.config.allowedTools,
1781
1788
  disallowedTools: this.config.disallowedTools
1782
1789
  });
1783
- await super.refreshTools();
1790
+ await super.refreshTools(call);
1784
1791
  const session = this.getSession();
1785
1792
  session?.replaceNativeTools(this.anthropicTools);
1786
1793
  session?.updateTools?.(this.mcpDirectTools);
@@ -1788,7 +1795,7 @@ var AnthropicSdkConnector = class extends BaseStreamConnector {
1788
1795
  /**
1789
1796
  * Construct the Anthropic SDK session with all required config.
1790
1797
  *
1791
- * Called by `BaseStreamConnector.initializeSession()` after `fetchTools()`
1798
+ * Called by `BaseStreamConnector.initializeSession()` after `fetchTools(call)`
1792
1799
  * has resolved credentials and initialized `this.client`.
1793
1800
  * @returns A new `AnthropicSdkSession` instance
1794
1801
  */
@@ -1815,9 +1822,9 @@ var AnthropicSdkConnector = class extends BaseStreamConnector {
1815
1822
  allowedDirectories: this.config.allowedDirectories,
1816
1823
  supportedReasoningLevels: this.config.supportedReasoningLevels,
1817
1824
  emitSdkEvent: this.emitSdkEvent.bind(this),
1818
- globalBus: this.config.globalBus ?? MakaioBus,
1825
+ globalBus: this.config.globalBus,
1819
1826
  handleError: this.handleError.bind(this),
1820
- requestToolApproval: (payload) => this.requestToolApprovalWithHandling(AnthropicSdkConnectorSubjects.tool_approval, payload),
1827
+ requestToolApproval: (call, payload) => this.requestToolApprovalWithHandling(call, AnthropicSdkConnectorSubjects.tool_approval, payload),
1821
1828
  logLowLevelEvent: this.logLowLevelEvent,
1822
1829
  onTurnStart: (handle) => {
1823
1830
  this.pendingMessageHandle = handle;
package/dist/server.mjs CHANGED
@@ -1,4 +1,4 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import { t as anthropicSdkPackage } from "./package-CYLUpLS-.mjs";
2
+ import { t as anthropicSdkPackage } from "./package-ml6mifti.mjs";
3
3
 
4
4
  export { anthropicSdkPackage as default };
package/dist/session.d.ts CHANGED
@@ -6,6 +6,16 @@ import type { AnthropicSdkSessionConfig } from './types/index.js';
6
6
  import { BaseStreamSession } from '@makaio/framework/adapters/stream-session';
7
7
  import type { ScopedSubjectDefinition } from '@makaio/framework/core';
8
8
  import type { ToolListItem } from '@makaio/framework/contracts';
9
+ import type { IMakaioBus } from '@makaio/framework/bus';
10
+ /**
11
+ * Session configuration with the host bus required.
12
+ *
13
+ * The session no longer falls back to the process-wide bus: the owner that builds the
14
+ * session passes the bus its tool execution runs on.
15
+ */
16
+ type AnthropicSdkSessionConfigWithBus = AnthropicSdkSessionConfig & {
17
+ globalBus: IMakaioBus;
18
+ };
9
19
  /**
10
20
  * Session for Anthropic SDK lifecycle management.
11
21
  *
@@ -17,7 +27,7 @@ import type { ToolListItem } from '@makaio/framework/contracts';
17
27
  * Key difference from Claude Code: Anthropic SDK adapter has no server-side
18
28
  * session. Each turn rebuilds the messages[] array with full history.
19
29
  */
20
- export declare class AnthropicSdkSession extends BaseStreamSession<AnthropicSdkSessionConfig, AnthropicSdkConnectorTurn, MessageCompleteEvent> {
30
+ export declare class AnthropicSdkSession extends BaseStreamSession<AnthropicSdkSessionConfigWithBus, AnthropicSdkConnectorTurn, MessageCompleteEvent> {
21
31
  protected messages: MessageParam[];
22
32
  /**
23
33
  * Runtime reasoning effort level; updated by `updateReasoning()`.
@@ -47,7 +57,7 @@ export declare class AnthropicSdkSession extends BaseStreamSession<AnthropicSdkS
47
57
  * Create an Anthropic SDK connector session.
48
58
  * @param config - Session configuration (bus identity, model/cwd defaults, Anthropic client/tools, and lifecycle hooks).
49
59
  */
50
- constructor(config: AnthropicSdkSessionConfig);
60
+ constructor(config: AnthropicSdkSessionConfigWithBus);
51
61
  /**
52
62
  * Replace the native registry tool set used for subsequent turns.
53
63
  *
@@ -151,4 +161,5 @@ export declare class AnthropicSdkSession extends BaseStreamSession<AnthropicSdkS
151
161
  */
152
162
  protected classifyError(error: unknown): Error;
153
163
  }
164
+ export {};
154
165
  //# sourceMappingURL=session.d.ts.map
@@ -8,6 +8,7 @@
8
8
  * reasoning_complete, usage, tool_calls, message_complete).
9
9
  */
10
10
  import type { RawMessageStreamEvent } from '@anthropic-ai/sdk/resources/messages/messages.js';
11
+ import type { CallContext } from '@makaio/framework/core';
11
12
  import type { StreamBridgeConfig } from './types/index.js';
12
13
  /**
13
14
  * Processes an Anthropic message stream and emits normalized bus events.
@@ -19,8 +20,9 @@ import type { StreamBridgeConfig } from './types/index.js';
19
20
  * Emits to bus as the stream progresses:
20
21
  * - sdk.raw: Each raw Anthropic event (observability)
21
22
  * - sdk.event: Semantic events — chunk, reasoning_delta, reasoning_complete, usage, tool_calls, message_complete
23
+ * @param call - Call context of the handled message.
22
24
  * @param stream - The Anthropic streaming response.
23
25
  * @param config - Bridge configuration with bus, agent identity, and model.
24
26
  */
25
- export declare function processStream(stream: AsyncIterable<RawMessageStreamEvent>, config: StreamBridgeConfig): Promise<void>;
27
+ export declare function processStream(call: CallContext, stream: AsyncIterable<RawMessageStreamEvent>, config: StreamBridgeConfig): Promise<void>;
26
28
  //# sourceMappingURL=stream-bridge.d.ts.map
@@ -14,7 +14,7 @@
14
14
  * │
15
15
  * ├─► stream-bridge ──► tool_calls (with ToolCall[])
16
16
  * │
17
- * └─► handleToolCalls(toolCalls, callbacks, context)
17
+ * └─► handleToolCalls(call, toolCalls, callbacks, context)
18
18
  * │
19
19
  * ├─► requestToolApproval() ──► scoped bus ──► global bus
20
20
  * │
@@ -42,7 +42,7 @@
42
42
  import type { Tool, ToolResultBlockParam } from '@anthropic-ai/sdk/resources/messages/messages.js';
43
43
  import type { IMakaioBus } from '@makaio/framework/bus';
44
44
  import { AnthropicSdkConnectorSubjects, type SdkEventMessage, type ToolCall } from './namespaces/index.js';
45
- import type { ExtractSubjectPayload, ExtractSubjectResponse } from '@makaio/framework/core';
45
+ import type { CallContext, ExtractSubjectPayload, ExtractSubjectResponse } from '@makaio/framework/core';
46
46
  import { type ToolListItem } from '@makaio/framework/contracts';
47
47
  import { type ToolApprovalContext } from '@makaio/framework/adapters';
48
48
  export type { ToolApprovalContext } from '@makaio/framework/adapters';
@@ -61,7 +61,7 @@ export type { ToolCallPayload, ToolExecutionContextOverrides };
61
61
  * @param context - Adapter context for request enrichment (static or lazy callback)
62
62
  * @returns Unsubscribe function
63
63
  */
64
- export declare const registerToolApprovalHandler: (connector: Pick<import("@makaio/framework/adapters").AIAgentConnector, 'on'>, context: ToolApprovalContext | (() => Promise<ToolApprovalContext>), globalBus: IMakaioBus) => () => void;
64
+ export declare const registerToolApprovalHandler: (connector: Pick<import("@makaio/framework/adapters").AIAgentConnector, 'on'>, context: ToolApprovalContext | ((call: CallContext) => Promise<ToolApprovalContext>), globalBus: IMakaioBus) => () => void;
65
65
  export { loadToolsFromRegistry, extractToolCallPayload, executeTool };
66
66
  /**
67
67
  * Convert ToolListItem[] to Anthropic Tool[] format.
@@ -74,17 +74,18 @@ export { loadToolsFromRegistry, extractToolCallPayload, executeTool };
74
74
  export declare function toAnthropicToolFormat(tools: ToolListItem[]): Tool[];
75
75
  /**
76
76
  * Convenience: Load tools and convert to Anthropic format in one call.
77
+ * @param call - Call of the message requesting registry tools
77
78
  * @param bus - Bus that owns the ToolRegistry handlers
78
79
  * @param adapterId - Adapter instance ID
79
80
  * @param adapterName - Adapter type name
80
81
  * @param options - Optional adapter runtime tool allow/deny filters
81
82
  * @returns Anthropic-formatted tools ready for messages.create
82
83
  */
83
- export declare function fetchToolsForAnthropic(bus: IMakaioBus, adapterId: string, adapterName: string, options?: ToolRegistryLoadOptions): Promise<Tool[]>;
84
+ export declare function fetchToolsForAnthropic(call: CallContext, bus: IMakaioBus, adapterId: string, adapterName: string, options?: ToolRegistryLoadOptions): Promise<Tool[]>;
84
85
  type AnthropicToolCallsCallbacks = {
85
86
  bus: IMakaioBus;
86
- emitSdkEvent: (event: SdkEventMessage) => Promise<void>;
87
- requestToolApproval: (payload: Omit<ExtractSubjectPayload<typeof AnthropicSdkConnectorSubjects.tool_approval>, 'adapterName' | 'adapterId' | 'agentId' | 'adapterSessionId' | 'sessionId'>) => Promise<ExtractSubjectResponse<typeof AnthropicSdkConnectorSubjects.tool_approval>>;
87
+ emitSdkEvent: (call: CallContext, event: SdkEventMessage) => Promise<void>;
88
+ requestToolApproval: (call: CallContext, payload: Omit<ExtractSubjectPayload<typeof AnthropicSdkConnectorSubjects.tool_approval>, 'adapterName' | 'adapterId' | 'agentId' | 'adapterSessionId' | 'sessionId'>) => Promise<ExtractSubjectResponse<typeof AnthropicSdkConnectorSubjects.tool_approval>>;
88
89
  /** Optional mcp_call ledger callback forwarded from the session config. */
89
90
  recordMcpCall?: (toolFullName: string) => void;
90
91
  };
@@ -93,10 +94,11 @@ type AnthropicToolCallsCallbacks = {
93
94
  *
94
95
  * Returns Anthropic-format tool results: `{ role: 'user', content: [{ type: 'tool_result', ... }] }`
95
96
  * is assembled by the caller using the returned ToolResultBlockParam[].
97
+ * @param call - Call context of the turn's message handle; forwarded to approval, lifecycle events and tool execution
96
98
  * @param toolCalls - Array of normalized tool calls from the stream-bridge tool_calls event
97
99
  * @param callbacks - Injected callbacks for event emission, approval requests, and optional ledger recording
98
100
  * @param contextOverrides - Execution context (cwd, env, sessionId, agentId, turnId)
99
101
  * @returns Tool result blocks to inject into the next user message
100
102
  */
101
- export declare function handleToolCalls(toolCalls: ToolCall[], callbacks: AnthropicToolCallsCallbacks, contextOverrides: ToolExecutionContextOverrides): Promise<ToolResultBlockParam[]>;
103
+ export declare function handleToolCalls(call: CallContext, toolCalls: ToolCall[], callbacks: AnthropicToolCallsCallbacks, contextOverrides: ToolExecutionContextOverrides): Promise<ToolResultBlockParam[]>;
102
104
  //# sourceMappingURL=tool-handling.d.ts.map
package/dist/turn.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { ProceduralConnectorTurn } from '@makaio/framework/adapters';
2
2
  import type { MessageHandle } from '@makaio/framework/adapters';
3
+ import type { CallContext } from '@makaio/framework/contracts';
3
4
  import { type AnthropicSdkConnectorBus } from './namespaces/index.js';
4
5
  import type { StreamSessionTurnState } from '@makaio/framework/adapters/stream-session';
5
6
  /**
@@ -27,8 +28,9 @@ export declare class AnthropicSdkConnectorTurn extends ProceduralConnectorTurn<S
27
28
  * Pause (abort) at next opportunity.
28
29
  * The Anthropic SDK adapter does not support true pause — caller restarts
29
30
  * with merged content when a replacement turn arrives.
31
+ * @param call - Call of the message requesting the pause
30
32
  * @returns Pause result indicating turn state
31
33
  */
32
- pause(): ReturnType<ProceduralConnectorTurn['pause']>;
34
+ pause(call: CallContext): ReturnType<ProceduralConnectorTurn['pause']>;
33
35
  }
34
36
  //# sourceMappingURL=turn.d.ts.map
@@ -1,4 +1,5 @@
1
1
  import type { IMakaioBus, ScopedBus } from '@makaio/framework/bus';
2
+ import type { CallContext } from '@makaio/framework/core';
2
3
  import { type BaseAgentConnectorConfig, type MessageHandle, type AIReasoningLevel, type ReasoningLevelMap, type MessageResult, type ProviderRequestCorrelation } from '@makaio/framework/adapters';
3
4
  import type { AnthropicSdkProviderSettings } from '../schemas.js';
4
5
  import type Anthropic from '@anthropic-ai/sdk';
@@ -117,12 +118,20 @@ export interface AnthropicSdkSessionConfig {
117
118
  * Forwarded as `constraints.allowedDirectories` in every tool call.
118
119
  */
119
120
  allowedDirectories?: string[];
120
- /** Emit a typed SDK event to the connector bus */
121
- emitSdkEvent: (event: SdkEventMessage) => Promise<void>;
121
+ /**
122
+ * Emit a typed SDK event to the connector bus
123
+ * @param call - Call context of the turn the event belongs to
124
+ * @param event - SDK event to emit
125
+ */
126
+ emitSdkEvent: (call: CallContext, event: SdkEventMessage) => Promise<void>;
122
127
  /** Handle a connector-level error */
123
128
  handleError: (error: Error, rethrow: boolean) => void;
124
- /** Request tool approval via bus RPC */
125
- requestToolApproval: (payload: AnthropicToolApprovalPayload) => Promise<AnthropicToolApprovalResponse>;
129
+ /**
130
+ * Request tool approval via bus RPC
131
+ * @param call - Call context of the turn the approval belongs to
132
+ * @param payload - Approval payload
133
+ */
134
+ requestToolApproval: (call: CallContext, payload: AnthropicToolApprovalPayload) => Promise<AnthropicToolApprovalResponse>;
126
135
  logLowLevelEvent?: (event: unknown) => void;
127
136
  onTurnStart?: (handle: MessageHandle) => void;
128
137
  onTurnComplete?: (handle: MessageHandle, result: MessageResult) => void;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@makaio/adapter-anthropic-sdk",
3
3
  "description": "Anthropic SDK adapter using the official @anthropic-ai/sdk streaming API.",
4
- "version": "1.0.0-dev-1795338532209",
4
+ "version": "1.0.0-dev-1795406265449",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",