ai-protocol-adapters 1.0.0-alpha.18 → 1.0.0-alpha.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -5831,10 +5831,6 @@ declare class FormatValidator {
5831
5831
  };
5832
5832
  }
5833
5833
 
5834
- /**
5835
- * 流式协议适配器 - OpenAI到Anthropic的SSE转换
5836
- * 基于编译后的JavaScript文件重新生成的TypeScript源码
5837
- */
5838
5834
  interface ToolCallState {
5839
5835
  id: string;
5840
5836
  name: string;
@@ -5877,6 +5873,13 @@ interface ConversionResult$1 {
5877
5873
  anthropicSSE: string;
5878
5874
  anthropicStandardResponse: any;
5879
5875
  }
5876
+ interface AnthropicToOpenAIChunkResult {
5877
+ buffer: string;
5878
+ chunks: OpenAIStreamChunk[];
5879
+ finishReason?: OpenAIFinishReason;
5880
+ streamStopped: boolean;
5881
+ }
5882
+ type OpenAIFinishReason = NonNullable<OpenAIStreamChunk['choices'][number]['finish_reason']>;
5880
5883
  declare class StreamingProtocolAdapter {
5881
5884
  private config;
5882
5885
  constructor(options?: StreamingProtocolAdapterOptions);
@@ -5905,6 +5908,16 @@ declare class StreamingProtocolAdapter {
5905
5908
  * 转换OpenAI流式响应为Anthropic SSE格式
5906
5909
  */
5907
5910
  convertOpenAIStreamToAnthropic(openaiStream: string, originalRequest: any): ConversionResult$1;
5911
+ /**
5912
+ * 增量解析Anthropic SSE,转换为OpenAI流式chunk
5913
+ * 供 OpenAI Chat Completions 端点直接复用
5914
+ */
5915
+ convertAnthropicSSEChunkToOpenAI(params: {
5916
+ buffer: string;
5917
+ chunk: string;
5918
+ model: string;
5919
+ flush?: boolean;
5920
+ }): AnthropicToOpenAIChunkResult;
5908
5921
  /**
5909
5922
  * 将OpenAI流转换为Anthropic SSE格式
5910
5923
  */
@@ -5954,6 +5967,10 @@ declare class StreamingProtocolAdapter {
5954
5967
  * 创建转换状态对象
5955
5968
  */
5956
5969
  private createConversionState;
5970
+ private parseAnthropicSSEEvent;
5971
+ private extractTextFromAnthropicDelta;
5972
+ private mapAnthropicStopReasonToOpenAI;
5973
+ private buildOpenAIStreamChunk;
5957
5974
  /**
5958
5975
  * 转换消息格式
5959
5976
  */
@@ -7365,4 +7382,4 @@ declare const FEATURES: {
7365
7382
  readonly externalPackageVerified: true;
7366
7383
  };
7367
7384
 
7368
- export { A2ORequestAdapter, A2ORequestAdapterStatic, ADAPTERS_VERSION, type AnthropicContentBlock, AnthropicContentBlockBaseSchema, AnthropicContentBlockDeltaEventSchema, AnthropicContentBlockSchema, AnthropicContentBlockStartEventSchema, AnthropicContentBlockStopEventSchema, AnthropicErrorEventSchema, type AnthropicImageContentBlock, AnthropicImageContentBlockSchema, AnthropicImageSourceSchema, type AnthropicMessage, AnthropicMessageDeltaEventSchema, AnthropicMessageSchema, AnthropicMessageStartEventSchema, AnthropicMessageStopEventSchema, AnthropicMetadataSchema, AnthropicPingEventSchema, type AnthropicRequest, AnthropicRequestSchema, type AnthropicResponse, AnthropicResponseSchema, type AnthropicSDKConfig, AnthropicSDKWrapper, type AnthropicStreamEvent, AnthropicStreamEventBaseSchema, AnthropicStreamEventSchema, AnthropicSystemMessageSchema, type AnthropicTextContentBlock, AnthropicTextContentBlockSchema, type AnthropicTool, AnthropicToolInputSchemaSchema, type AnthropicToolResultContentBlock, AnthropicToolResultContentBlockSchema, AnthropicToolSchema, type AnthropicToolUseContentBlock, AnthropicToolUseContentBlockSchema, type AnthropicUsage, AnthropicUsageSchema, type BaseSDKClient, A2ORequestAdapter as ClaudeToOpenAIConverter, type ConversionFixResult, ConversionFixer, type ConversionResult$1 as ConversionResult, type ConversionState, ConversionValidator, type ConvertedRequest, type ConvertedResponse, EMERGENCY_HEALING_STRATEGIES, type EnhancedAdapterOptions, type EnhancedConversionResult, ErrorDetector, type ErrorInfo, ErrorRecovery, type ErrorSeverity, type ErrorType, FEATURES, FormatValidator, type HealingContext, type HealingResult, type HealingRule, StandardProtocolAdapter as NonStreamingIOConverter, O2ASSEAdapter, O2ASSEAdapterStatic, type OpenAIChoice, OpenAIChoiceSchema, OpenAIFunctionParametersSchema, OpenAIFunctionSchema, type OpenAIMessage, OpenAIMessageContentSchema, OpenAIMessageSchema, type OpenAIRequest$1 as OpenAIRequest, OpenAIRequestSchema, type OpenAIResponse$1 as OpenAIResponse, OpenAIResponseSchema, type OpenAISDKConfig, OpenAISDKWrapper, type OpenAIStreamChunk, OpenAIStreamChunkSchema, O2ASSEAdapter as OpenAIToClaudeSSEConverter, type OpenAITool, type OpenAIToolCall, OpenAIToolCallSchema, OpenAIToolSchema, type OpenAIUsage, OpenAIUsageSchema, ProtocolHealer, RECOVERY_STRATEGIES, REQUEST_HEALING_STRATEGIES, RESPONSE_HEALING_STRATEGIES, type RecoveryResult, type RecoveryStrategy, type RequestOptions, type SDKConfig, SDKFactory, type SDKProvider, type SDKResponse, type SDKStreamEvent, SSEEventGenerator, STREAM_HEALING_STRATEGIES, type ConversionResult as SchemaConversionResult, StandardProtocolAdapter as StandardGateway, StandardProtocolAdapter, type StandardProtocolAdapterOptions, StreamingProtocolAdapter as StreamingGateway, StreamingProtocolAdapter as StreamingIOConverter, StreamingProtocolAdapter, type StreamingProtocolAdapterOptions, type UnifiedSDKConfig, type ValidationResult, attemptRecovery, conversionValidator, createAnthropicSDK, createOpenAISDK, createValidator, downloadImageAsBase64, errorRecovery, getAllHealingStrategies, getGlobalLogger, getRecoveryRecommendations, getStrategiesForContext, healA2ORequest, healO2ARequest, healO2AResponse, healingValidate, isBase64DataUri, isExternalUrl, isRecoverable, protocolHealer, safeValidate, sdkFactory, selectSDKByModel, strictValidate, validateA2OConversion, validateAnthropicRequest, validateAnthropicResponse, validateAnthropicStreamEvent, validateBatch, validateO2AConversion, validateOpenAIRequest, validateOpenAIResponse, validateOpenAIStreamChunk, validateSDKConfig, validateStreamConversion };
7385
+ export { A2ORequestAdapter, A2ORequestAdapterStatic, ADAPTERS_VERSION, type AnthropicContentBlock, AnthropicContentBlockBaseSchema, AnthropicContentBlockDeltaEventSchema, AnthropicContentBlockSchema, AnthropicContentBlockStartEventSchema, AnthropicContentBlockStopEventSchema, AnthropicErrorEventSchema, type AnthropicImageContentBlock, AnthropicImageContentBlockSchema, AnthropicImageSourceSchema, type AnthropicMessage, AnthropicMessageDeltaEventSchema, AnthropicMessageSchema, AnthropicMessageStartEventSchema, AnthropicMessageStopEventSchema, AnthropicMetadataSchema, AnthropicPingEventSchema, type AnthropicRequest, AnthropicRequestSchema, type AnthropicResponse, AnthropicResponseSchema, type AnthropicSDKConfig, AnthropicSDKWrapper, type AnthropicStreamEvent, AnthropicStreamEventBaseSchema, AnthropicStreamEventSchema, AnthropicSystemMessageSchema, type AnthropicTextContentBlock, AnthropicTextContentBlockSchema, type AnthropicToOpenAIChunkResult, type AnthropicTool, AnthropicToolInputSchemaSchema, type AnthropicToolResultContentBlock, AnthropicToolResultContentBlockSchema, AnthropicToolSchema, type AnthropicToolUseContentBlock, AnthropicToolUseContentBlockSchema, type AnthropicUsage, AnthropicUsageSchema, type BaseSDKClient, A2ORequestAdapter as ClaudeToOpenAIConverter, type ConversionFixResult, ConversionFixer, type ConversionResult$1 as ConversionResult, type ConversionState, ConversionValidator, type ConvertedRequest, type ConvertedResponse, EMERGENCY_HEALING_STRATEGIES, type EnhancedAdapterOptions, type EnhancedConversionResult, ErrorDetector, type ErrorInfo, ErrorRecovery, type ErrorSeverity, type ErrorType, FEATURES, FormatValidator, type HealingContext, type HealingResult, type HealingRule, StandardProtocolAdapter as NonStreamingIOConverter, O2ASSEAdapter, O2ASSEAdapterStatic, type OpenAIChoice, OpenAIChoiceSchema, OpenAIFunctionParametersSchema, OpenAIFunctionSchema, type OpenAIMessage, OpenAIMessageContentSchema, OpenAIMessageSchema, type OpenAIRequest$1 as OpenAIRequest, OpenAIRequestSchema, type OpenAIResponse$1 as OpenAIResponse, OpenAIResponseSchema, type OpenAISDKConfig, OpenAISDKWrapper, type OpenAIStreamChunk, OpenAIStreamChunkSchema, O2ASSEAdapter as OpenAIToClaudeSSEConverter, type OpenAITool, type OpenAIToolCall, OpenAIToolCallSchema, OpenAIToolSchema, type OpenAIUsage, OpenAIUsageSchema, ProtocolHealer, RECOVERY_STRATEGIES, REQUEST_HEALING_STRATEGIES, RESPONSE_HEALING_STRATEGIES, type RecoveryResult, type RecoveryStrategy, type RequestOptions, type SDKConfig, SDKFactory, type SDKProvider, type SDKResponse, type SDKStreamEvent, SSEEventGenerator, STREAM_HEALING_STRATEGIES, type ConversionResult as SchemaConversionResult, StandardProtocolAdapter as StandardGateway, StandardProtocolAdapter, type StandardProtocolAdapterOptions, StreamingProtocolAdapter as StreamingGateway, StreamingProtocolAdapter as StreamingIOConverter, StreamingProtocolAdapter, type StreamingProtocolAdapterOptions, type UnifiedSDKConfig, type ValidationResult, attemptRecovery, conversionValidator, createAnthropicSDK, createOpenAISDK, createValidator, downloadImageAsBase64, errorRecovery, getAllHealingStrategies, getGlobalLogger, getRecoveryRecommendations, getStrategiesForContext, healA2ORequest, healO2ARequest, healO2AResponse, healingValidate, isBase64DataUri, isExternalUrl, isRecoverable, protocolHealer, safeValidate, sdkFactory, selectSDKByModel, strictValidate, validateA2OConversion, validateAnthropicRequest, validateAnthropicResponse, validateAnthropicStreamEvent, validateBatch, validateO2AConversion, validateOpenAIRequest, validateOpenAIResponse, validateOpenAIStreamChunk, validateSDKConfig, validateStreamConversion };
package/dist/index.d.ts CHANGED
@@ -5831,10 +5831,6 @@ declare class FormatValidator {
5831
5831
  };
5832
5832
  }
5833
5833
 
5834
- /**
5835
- * 流式协议适配器 - OpenAI到Anthropic的SSE转换
5836
- * 基于编译后的JavaScript文件重新生成的TypeScript源码
5837
- */
5838
5834
  interface ToolCallState {
5839
5835
  id: string;
5840
5836
  name: string;
@@ -5877,6 +5873,13 @@ interface ConversionResult$1 {
5877
5873
  anthropicSSE: string;
5878
5874
  anthropicStandardResponse: any;
5879
5875
  }
5876
+ interface AnthropicToOpenAIChunkResult {
5877
+ buffer: string;
5878
+ chunks: OpenAIStreamChunk[];
5879
+ finishReason?: OpenAIFinishReason;
5880
+ streamStopped: boolean;
5881
+ }
5882
+ type OpenAIFinishReason = NonNullable<OpenAIStreamChunk['choices'][number]['finish_reason']>;
5880
5883
  declare class StreamingProtocolAdapter {
5881
5884
  private config;
5882
5885
  constructor(options?: StreamingProtocolAdapterOptions);
@@ -5905,6 +5908,16 @@ declare class StreamingProtocolAdapter {
5905
5908
  * 转换OpenAI流式响应为Anthropic SSE格式
5906
5909
  */
5907
5910
  convertOpenAIStreamToAnthropic(openaiStream: string, originalRequest: any): ConversionResult$1;
5911
+ /**
5912
+ * 增量解析Anthropic SSE,转换为OpenAI流式chunk
5913
+ * 供 OpenAI Chat Completions 端点直接复用
5914
+ */
5915
+ convertAnthropicSSEChunkToOpenAI(params: {
5916
+ buffer: string;
5917
+ chunk: string;
5918
+ model: string;
5919
+ flush?: boolean;
5920
+ }): AnthropicToOpenAIChunkResult;
5908
5921
  /**
5909
5922
  * 将OpenAI流转换为Anthropic SSE格式
5910
5923
  */
@@ -5954,6 +5967,10 @@ declare class StreamingProtocolAdapter {
5954
5967
  * 创建转换状态对象
5955
5968
  */
5956
5969
  private createConversionState;
5970
+ private parseAnthropicSSEEvent;
5971
+ private extractTextFromAnthropicDelta;
5972
+ private mapAnthropicStopReasonToOpenAI;
5973
+ private buildOpenAIStreamChunk;
5957
5974
  /**
5958
5975
  * 转换消息格式
5959
5976
  */
@@ -7365,4 +7382,4 @@ declare const FEATURES: {
7365
7382
  readonly externalPackageVerified: true;
7366
7383
  };
7367
7384
 
7368
- export { A2ORequestAdapter, A2ORequestAdapterStatic, ADAPTERS_VERSION, type AnthropicContentBlock, AnthropicContentBlockBaseSchema, AnthropicContentBlockDeltaEventSchema, AnthropicContentBlockSchema, AnthropicContentBlockStartEventSchema, AnthropicContentBlockStopEventSchema, AnthropicErrorEventSchema, type AnthropicImageContentBlock, AnthropicImageContentBlockSchema, AnthropicImageSourceSchema, type AnthropicMessage, AnthropicMessageDeltaEventSchema, AnthropicMessageSchema, AnthropicMessageStartEventSchema, AnthropicMessageStopEventSchema, AnthropicMetadataSchema, AnthropicPingEventSchema, type AnthropicRequest, AnthropicRequestSchema, type AnthropicResponse, AnthropicResponseSchema, type AnthropicSDKConfig, AnthropicSDKWrapper, type AnthropicStreamEvent, AnthropicStreamEventBaseSchema, AnthropicStreamEventSchema, AnthropicSystemMessageSchema, type AnthropicTextContentBlock, AnthropicTextContentBlockSchema, type AnthropicTool, AnthropicToolInputSchemaSchema, type AnthropicToolResultContentBlock, AnthropicToolResultContentBlockSchema, AnthropicToolSchema, type AnthropicToolUseContentBlock, AnthropicToolUseContentBlockSchema, type AnthropicUsage, AnthropicUsageSchema, type BaseSDKClient, A2ORequestAdapter as ClaudeToOpenAIConverter, type ConversionFixResult, ConversionFixer, type ConversionResult$1 as ConversionResult, type ConversionState, ConversionValidator, type ConvertedRequest, type ConvertedResponse, EMERGENCY_HEALING_STRATEGIES, type EnhancedAdapterOptions, type EnhancedConversionResult, ErrorDetector, type ErrorInfo, ErrorRecovery, type ErrorSeverity, type ErrorType, FEATURES, FormatValidator, type HealingContext, type HealingResult, type HealingRule, StandardProtocolAdapter as NonStreamingIOConverter, O2ASSEAdapter, O2ASSEAdapterStatic, type OpenAIChoice, OpenAIChoiceSchema, OpenAIFunctionParametersSchema, OpenAIFunctionSchema, type OpenAIMessage, OpenAIMessageContentSchema, OpenAIMessageSchema, type OpenAIRequest$1 as OpenAIRequest, OpenAIRequestSchema, type OpenAIResponse$1 as OpenAIResponse, OpenAIResponseSchema, type OpenAISDKConfig, OpenAISDKWrapper, type OpenAIStreamChunk, OpenAIStreamChunkSchema, O2ASSEAdapter as OpenAIToClaudeSSEConverter, type OpenAITool, type OpenAIToolCall, OpenAIToolCallSchema, OpenAIToolSchema, type OpenAIUsage, OpenAIUsageSchema, ProtocolHealer, RECOVERY_STRATEGIES, REQUEST_HEALING_STRATEGIES, RESPONSE_HEALING_STRATEGIES, type RecoveryResult, type RecoveryStrategy, type RequestOptions, type SDKConfig, SDKFactory, type SDKProvider, type SDKResponse, type SDKStreamEvent, SSEEventGenerator, STREAM_HEALING_STRATEGIES, type ConversionResult as SchemaConversionResult, StandardProtocolAdapter as StandardGateway, StandardProtocolAdapter, type StandardProtocolAdapterOptions, StreamingProtocolAdapter as StreamingGateway, StreamingProtocolAdapter as StreamingIOConverter, StreamingProtocolAdapter, type StreamingProtocolAdapterOptions, type UnifiedSDKConfig, type ValidationResult, attemptRecovery, conversionValidator, createAnthropicSDK, createOpenAISDK, createValidator, downloadImageAsBase64, errorRecovery, getAllHealingStrategies, getGlobalLogger, getRecoveryRecommendations, getStrategiesForContext, healA2ORequest, healO2ARequest, healO2AResponse, healingValidate, isBase64DataUri, isExternalUrl, isRecoverable, protocolHealer, safeValidate, sdkFactory, selectSDKByModel, strictValidate, validateA2OConversion, validateAnthropicRequest, validateAnthropicResponse, validateAnthropicStreamEvent, validateBatch, validateO2AConversion, validateOpenAIRequest, validateOpenAIResponse, validateOpenAIStreamChunk, validateSDKConfig, validateStreamConversion };
7385
+ export { A2ORequestAdapter, A2ORequestAdapterStatic, ADAPTERS_VERSION, type AnthropicContentBlock, AnthropicContentBlockBaseSchema, AnthropicContentBlockDeltaEventSchema, AnthropicContentBlockSchema, AnthropicContentBlockStartEventSchema, AnthropicContentBlockStopEventSchema, AnthropicErrorEventSchema, type AnthropicImageContentBlock, AnthropicImageContentBlockSchema, AnthropicImageSourceSchema, type AnthropicMessage, AnthropicMessageDeltaEventSchema, AnthropicMessageSchema, AnthropicMessageStartEventSchema, AnthropicMessageStopEventSchema, AnthropicMetadataSchema, AnthropicPingEventSchema, type AnthropicRequest, AnthropicRequestSchema, type AnthropicResponse, AnthropicResponseSchema, type AnthropicSDKConfig, AnthropicSDKWrapper, type AnthropicStreamEvent, AnthropicStreamEventBaseSchema, AnthropicStreamEventSchema, AnthropicSystemMessageSchema, type AnthropicTextContentBlock, AnthropicTextContentBlockSchema, type AnthropicToOpenAIChunkResult, type AnthropicTool, AnthropicToolInputSchemaSchema, type AnthropicToolResultContentBlock, AnthropicToolResultContentBlockSchema, AnthropicToolSchema, type AnthropicToolUseContentBlock, AnthropicToolUseContentBlockSchema, type AnthropicUsage, AnthropicUsageSchema, type BaseSDKClient, A2ORequestAdapter as ClaudeToOpenAIConverter, type ConversionFixResult, ConversionFixer, type ConversionResult$1 as ConversionResult, type ConversionState, ConversionValidator, type ConvertedRequest, type ConvertedResponse, EMERGENCY_HEALING_STRATEGIES, type EnhancedAdapterOptions, type EnhancedConversionResult, ErrorDetector, type ErrorInfo, ErrorRecovery, type ErrorSeverity, type ErrorType, FEATURES, FormatValidator, type HealingContext, type HealingResult, type HealingRule, StandardProtocolAdapter as NonStreamingIOConverter, O2ASSEAdapter, O2ASSEAdapterStatic, type OpenAIChoice, OpenAIChoiceSchema, OpenAIFunctionParametersSchema, OpenAIFunctionSchema, type OpenAIMessage, OpenAIMessageContentSchema, OpenAIMessageSchema, type OpenAIRequest$1 as OpenAIRequest, OpenAIRequestSchema, type OpenAIResponse$1 as OpenAIResponse, OpenAIResponseSchema, type OpenAISDKConfig, OpenAISDKWrapper, type OpenAIStreamChunk, OpenAIStreamChunkSchema, O2ASSEAdapter as OpenAIToClaudeSSEConverter, type OpenAITool, type OpenAIToolCall, OpenAIToolCallSchema, OpenAIToolSchema, type OpenAIUsage, OpenAIUsageSchema, ProtocolHealer, RECOVERY_STRATEGIES, REQUEST_HEALING_STRATEGIES, RESPONSE_HEALING_STRATEGIES, type RecoveryResult, type RecoveryStrategy, type RequestOptions, type SDKConfig, SDKFactory, type SDKProvider, type SDKResponse, type SDKStreamEvent, SSEEventGenerator, STREAM_HEALING_STRATEGIES, type ConversionResult as SchemaConversionResult, StandardProtocolAdapter as StandardGateway, StandardProtocolAdapter, type StandardProtocolAdapterOptions, StreamingProtocolAdapter as StreamingGateway, StreamingProtocolAdapter as StreamingIOConverter, StreamingProtocolAdapter, type StreamingProtocolAdapterOptions, type UnifiedSDKConfig, type ValidationResult, attemptRecovery, conversionValidator, createAnthropicSDK, createOpenAISDK, createValidator, downloadImageAsBase64, errorRecovery, getAllHealingStrategies, getGlobalLogger, getRecoveryRecommendations, getStrategiesForContext, healA2ORequest, healO2ARequest, healO2AResponse, healingValidate, isBase64DataUri, isExternalUrl, isRecoverable, protocolHealer, safeValidate, sdkFactory, selectSDKByModel, strictValidate, validateA2OConversion, validateAnthropicRequest, validateAnthropicResponse, validateAnthropicStreamEvent, validateBatch, validateO2AConversion, validateOpenAIRequest, validateOpenAIResponse, validateOpenAIStreamChunk, validateSDKConfig, validateStreamConversion };
package/dist/index.js CHANGED
@@ -4138,6 +4138,57 @@ var StreamingProtocolAdapter = class {
4138
4138
  };
4139
4139
  }
4140
4140
  }
4141
+ /**
4142
+ * 增量解析Anthropic SSE,转换为OpenAI流式chunk
4143
+ * 供 OpenAI Chat Completions 端点直接复用
4144
+ */
4145
+ convertAnthropicSSEChunkToOpenAI(params) {
4146
+ const { buffer, chunk, model, flush = false } = params;
4147
+ let localBuffer = buffer + (chunk || "");
4148
+ const emittedChunks = [];
4149
+ let finishReason;
4150
+ let streamStopped = false;
4151
+ const processEvent = (eventText) => {
4152
+ const { eventType, data } = this.parseAnthropicSSEEvent(eventText);
4153
+ if (!eventType || !data) {
4154
+ return;
4155
+ }
4156
+ if (eventType === "content_block_delta") {
4157
+ const text = this.extractTextFromAnthropicDelta(data);
4158
+ if (text) {
4159
+ emittedChunks.push(this.buildOpenAIStreamChunk(model, text));
4160
+ }
4161
+ } else if (eventType === "message_stop") {
4162
+ finishReason = this.mapAnthropicStopReasonToOpenAI(data?.stop_reason);
4163
+ streamStopped = true;
4164
+ }
4165
+ };
4166
+ while (true) {
4167
+ const separatorIndex = localBuffer.indexOf("\n\n");
4168
+ if (separatorIndex === -1) {
4169
+ break;
4170
+ }
4171
+ const rawEvent = localBuffer.slice(0, separatorIndex);
4172
+ localBuffer = localBuffer.slice(separatorIndex + 2);
4173
+ if (!rawEvent.trim()) {
4174
+ continue;
4175
+ }
4176
+ processEvent(rawEvent);
4177
+ if (streamStopped) {
4178
+ break;
4179
+ }
4180
+ }
4181
+ if (flush && localBuffer.trim()) {
4182
+ processEvent(localBuffer);
4183
+ localBuffer = "";
4184
+ }
4185
+ return {
4186
+ buffer: localBuffer,
4187
+ chunks: emittedChunks,
4188
+ finishReason,
4189
+ streamStopped
4190
+ };
4191
+ }
4141
4192
  /**
4142
4193
  * 将OpenAI流转换为Anthropic SSE格式
4143
4194
  */
@@ -4655,6 +4706,64 @@ var StreamingProtocolAdapter = class {
4655
4706
  nextToolBlockIndex: 1
4656
4707
  };
4657
4708
  }
4709
+ parseAnthropicSSEEvent(rawEvent) {
4710
+ const lines = rawEvent.split("\n");
4711
+ let eventType = null;
4712
+ const dataLines = [];
4713
+ for (const line of lines) {
4714
+ if (line.startsWith("event:")) {
4715
+ eventType = line.slice(6).trim();
4716
+ } else if (line.startsWith("data:")) {
4717
+ dataLines.push(line.slice(5).trim());
4718
+ }
4719
+ }
4720
+ const dataString = dataLines.join("\n");
4721
+ let data = null;
4722
+ if (dataString) {
4723
+ try {
4724
+ data = JSON.parse(dataString);
4725
+ } catch (error) {
4726
+ this.logDebug("Failed to parse Anthropic SSE JSON", { error });
4727
+ }
4728
+ }
4729
+ return { eventType, data };
4730
+ }
4731
+ extractTextFromAnthropicDelta(data) {
4732
+ const delta = data?.delta;
4733
+ if (!delta) return null;
4734
+ if (typeof delta.text === "string") {
4735
+ return delta.text;
4736
+ }
4737
+ if (delta.type === "text_delta" && typeof delta.text === "string") {
4738
+ return delta.text;
4739
+ }
4740
+ return null;
4741
+ }
4742
+ mapAnthropicStopReasonToOpenAI(reason) {
4743
+ switch (reason) {
4744
+ case "max_tokens":
4745
+ return "length";
4746
+ case "tool_use":
4747
+ return "tool_calls";
4748
+ case "stop_sequence":
4749
+ case "end_turn":
4750
+ default:
4751
+ return "stop";
4752
+ }
4753
+ }
4754
+ buildOpenAIStreamChunk(model, content, finishReason = null) {
4755
+ return {
4756
+ id: `chatcmpl-${Date.now()}`,
4757
+ object: "chat.completion.chunk",
4758
+ created: Math.floor(Date.now() / 1e3),
4759
+ model,
4760
+ choices: [{
4761
+ index: 0,
4762
+ delta: content ? { content } : {},
4763
+ finish_reason: finishReason
4764
+ }]
4765
+ };
4766
+ }
4658
4767
  /**
4659
4768
  * 转换消息格式
4660
4769
  */
package/dist/index.mjs CHANGED
@@ -4028,6 +4028,57 @@ var StreamingProtocolAdapter = class {
4028
4028
  };
4029
4029
  }
4030
4030
  }
4031
+ /**
4032
+ * 增量解析Anthropic SSE,转换为OpenAI流式chunk
4033
+ * 供 OpenAI Chat Completions 端点直接复用
4034
+ */
4035
+ convertAnthropicSSEChunkToOpenAI(params) {
4036
+ const { buffer, chunk, model, flush = false } = params;
4037
+ let localBuffer = buffer + (chunk || "");
4038
+ const emittedChunks = [];
4039
+ let finishReason;
4040
+ let streamStopped = false;
4041
+ const processEvent = (eventText) => {
4042
+ const { eventType, data } = this.parseAnthropicSSEEvent(eventText);
4043
+ if (!eventType || !data) {
4044
+ return;
4045
+ }
4046
+ if (eventType === "content_block_delta") {
4047
+ const text = this.extractTextFromAnthropicDelta(data);
4048
+ if (text) {
4049
+ emittedChunks.push(this.buildOpenAIStreamChunk(model, text));
4050
+ }
4051
+ } else if (eventType === "message_stop") {
4052
+ finishReason = this.mapAnthropicStopReasonToOpenAI(data?.stop_reason);
4053
+ streamStopped = true;
4054
+ }
4055
+ };
4056
+ while (true) {
4057
+ const separatorIndex = localBuffer.indexOf("\n\n");
4058
+ if (separatorIndex === -1) {
4059
+ break;
4060
+ }
4061
+ const rawEvent = localBuffer.slice(0, separatorIndex);
4062
+ localBuffer = localBuffer.slice(separatorIndex + 2);
4063
+ if (!rawEvent.trim()) {
4064
+ continue;
4065
+ }
4066
+ processEvent(rawEvent);
4067
+ if (streamStopped) {
4068
+ break;
4069
+ }
4070
+ }
4071
+ if (flush && localBuffer.trim()) {
4072
+ processEvent(localBuffer);
4073
+ localBuffer = "";
4074
+ }
4075
+ return {
4076
+ buffer: localBuffer,
4077
+ chunks: emittedChunks,
4078
+ finishReason,
4079
+ streamStopped
4080
+ };
4081
+ }
4031
4082
  /**
4032
4083
  * 将OpenAI流转换为Anthropic SSE格式
4033
4084
  */
@@ -4545,6 +4596,64 @@ var StreamingProtocolAdapter = class {
4545
4596
  nextToolBlockIndex: 1
4546
4597
  };
4547
4598
  }
4599
+ parseAnthropicSSEEvent(rawEvent) {
4600
+ const lines = rawEvent.split("\n");
4601
+ let eventType = null;
4602
+ const dataLines = [];
4603
+ for (const line of lines) {
4604
+ if (line.startsWith("event:")) {
4605
+ eventType = line.slice(6).trim();
4606
+ } else if (line.startsWith("data:")) {
4607
+ dataLines.push(line.slice(5).trim());
4608
+ }
4609
+ }
4610
+ const dataString = dataLines.join("\n");
4611
+ let data = null;
4612
+ if (dataString) {
4613
+ try {
4614
+ data = JSON.parse(dataString);
4615
+ } catch (error) {
4616
+ this.logDebug("Failed to parse Anthropic SSE JSON", { error });
4617
+ }
4618
+ }
4619
+ return { eventType, data };
4620
+ }
4621
+ extractTextFromAnthropicDelta(data) {
4622
+ const delta = data?.delta;
4623
+ if (!delta) return null;
4624
+ if (typeof delta.text === "string") {
4625
+ return delta.text;
4626
+ }
4627
+ if (delta.type === "text_delta" && typeof delta.text === "string") {
4628
+ return delta.text;
4629
+ }
4630
+ return null;
4631
+ }
4632
+ mapAnthropicStopReasonToOpenAI(reason) {
4633
+ switch (reason) {
4634
+ case "max_tokens":
4635
+ return "length";
4636
+ case "tool_use":
4637
+ return "tool_calls";
4638
+ case "stop_sequence":
4639
+ case "end_turn":
4640
+ default:
4641
+ return "stop";
4642
+ }
4643
+ }
4644
+ buildOpenAIStreamChunk(model, content, finishReason = null) {
4645
+ return {
4646
+ id: `chatcmpl-${Date.now()}`,
4647
+ object: "chat.completion.chunk",
4648
+ created: Math.floor(Date.now() / 1e3),
4649
+ model,
4650
+ choices: [{
4651
+ index: 0,
4652
+ delta: content ? { content } : {},
4653
+ finish_reason: finishReason
4654
+ }]
4655
+ };
4656
+ }
4548
4657
  /**
4549
4658
  * 转换消息格式
4550
4659
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-protocol-adapters",
3
- "version": "1.0.0-alpha.18",
3
+ "version": "1.0.0-alpha.19",
4
4
  "description": "Universal AI Protocol Converter - OpenAI ⇄ Anthropic with full TypeScript support",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",