@codehz/ai 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -493,7 +493,6 @@ declare function emitMalformedStreamWarning(factory: EventFactory, options: {
493
493
  providerLabel: string;
494
494
  transportLabel: string;
495
495
  }): AIStreamEvent | undefined;
496
- declare function metadataSourceList(...groups: Array<Array<NonNullable<BackendTrace["metadataSources"]>[number]> | undefined>): string[] | undefined;
497
496
  //#endregion
498
497
  //#region src/helpers/adapter-base.d.ts
499
498
  type ProviderResponse = unknown;
@@ -540,8 +539,11 @@ declare abstract class AdapterBase implements BackendAdapter {
540
539
  * 子类可在返回前自定义覆盖。
541
540
  */
542
541
  protected buildResponse(request: NormalizedRequest, result: StreamResult, _factory: EventFactory): AIResponse;
543
- /** 从 output items 中提取文本内容。 */
544
- protected extractText(output: OutputItem[]): string;
542
+ /**
543
+ * 统一 finalize auxiliary → response.completed。
544
+ * adapter 在调用前组装 output / replay / stopReason 等业务字段。
545
+ */
546
+ protected emitStreamCompleted(factory: EventFactory, request: NormalizedRequest, auxiliary: AdapterAuxiliaryState, result: StreamResult): AsyncIterable<AIStreamEvent>;
545
547
  protected createAuxiliaryState(request: NormalizedRequest): AdapterAuxiliaryState;
546
548
  }
547
549
  //#endregion
@@ -982,60 +984,11 @@ declare function blockToText(b: ContentBlock): string;
982
984
  * 将 ContentBlock 数组拼接为纯文本,块间以换行符分隔。
983
985
  */
984
986
  declare function contentBlocksToText(blocks: ContentBlock[]): string;
985
- /**
986
- * 将 instructions(string | InstructionBlock[])归一化为纯文本。
987
- */
988
- declare function instructionsToText(instructions: string | InstructionBlock[]): string;
989
987
  /**
990
988
  * 从 OutputItem 数组中提取所有 message 类型 item 的文本内容。
991
989
  */
992
990
  declare function extractText(output: OutputItem[]): string;
993
991
  //#endregion
994
- //#region src/helpers/sse-parser.d.ts
995
- /**
996
- * 通用 SSE (Server-Sent Events) 解析器
997
- *
998
- * 解析标准 SSE 格式(event: + data: 行),适用于:
999
- * - Anthropic Messages API (messages.ts)
1000
- * - OpenAI Responses API (responses.ts)
1001
- *
1002
- * 注意:OpenAI Chat Completions API 使用简化 SSE(仅有 data: 行),
1003
- * 由 chat-completions.ts 中的 parseChatSSE 处理。
1004
- *
1005
- * 用法:
1006
- * ```ts
1007
- * const { events, rest } = parseSSEEvents(buffer);
1008
- * for (const ev of events) {
1009
- * // ev.type — 事件类型字符串
1010
- * // ev.data — 已解析的 JSON 数据
1011
- * }
1012
- * // rest 是未处理的剩余 buffer,需要累积到下次调用
1013
- * ```
1014
- */
1015
- type SSEEvent = {
1016
- type: string;
1017
- data: unknown;
1018
- };
1019
- type SSEParseResult = {
1020
- events: SSEEvent[];
1021
- rest: string;
1022
- malformedEvents: number;
1023
- };
1024
- type ParseSSEOptions = {
1025
- allowEOF?: boolean;
1026
- };
1027
- /**
1028
- * 将 SSE 文本块解析为事件数组。
1029
- * 累积事件行直到遇到空行,支持 [DONE] 标记。
1030
- * 返回已解析的事件和未处理的剩余 buffer(用于增量解析)。
1031
- *
1032
- * 关键行为:
1033
- * - 只解析完整的 event(以空行结尾)
1034
- * - 未完成的行保留在 rest 中,等待下次 chunk 补全
1035
- * - 支持跨 chunk 的 event 分片
1036
- */
1037
- declare function parseSSEEvents(chunk: string, options?: ParseSSEOptions): SSEParseResult;
1038
- //#endregion
1039
992
  //#region src/helpers/synthetic-stream.d.ts
1040
993
  type SyntheticStreamOptions = {
1041
994
  model: string;
@@ -1173,6 +1126,56 @@ declare class IncrementalStreamParser<T> {
1173
1126
  }
1174
1127
  declare function splitLines(buffer: string, allowEOF: boolean): StreamSplitResult;
1175
1128
  declare function splitSSEFrames(buffer: string, allowEOF: boolean): StreamSplitResult;
1129
+ type SseJsonEvent = {
1130
+ type: string;
1131
+ data: unknown;
1132
+ };
1133
+ /** 解析标准 SSE frame(event: + data:),用于 Messages / Responses。 */
1134
+ declare function parseSseJsonFrame(frame: string): StreamParseResult<SseJsonEvent>;
1135
+ declare function createSseJsonParser<T extends SseJsonEvent = SseJsonEvent>(): IncrementalStreamParser<T>;
1136
+ /** OpenAI Chat Completions 简化 SSE:仅 `data: ...` 行,忽略 `[DONE]`。 */
1137
+ declare function parseChatCompletionsDataLine(item: string): StreamParseResult<unknown>;
1138
+ declare function createChatCompletionsSseParser<T>(): IncrementalStreamParser<T>;
1139
+ /** NDJSON 行解析(Ollama 等):空行忽略,JSON 失败为 malformed。 */
1140
+ declare function createNdjsonLineParser<T>(isValid: (value: unknown) => value is T): IncrementalStreamParser<T>;
1141
+ //#endregion
1142
+ //#region src/helpers/provider-stream.d.ts
1143
+ type OpenProviderJsonStreamOptions = {
1144
+ fetchFn: FetchFn;
1145
+ url: string;
1146
+ headers: Record<string, string>;
1147
+ body: unknown;
1148
+ signal?: AbortSignal;
1149
+ };
1150
+ type OpenedProviderStream = {
1151
+ reader: ReadableStreamDefaultReader<Uint8Array>;
1152
+ headers: Headers;
1153
+ };
1154
+ /** POST JSON 并返回可读 body reader + response headers;统一网络/HTTP/空 body 错误。 */
1155
+ declare function openProviderJsonStream(options: OpenProviderJsonStreamOptions): Promise<OpenedProviderStream>;
1156
+ type ProviderStreamBatchOptions<T> = {
1157
+ reader: ReadableStreamDefaultReader<Uint8Array>;
1158
+ parser: IncrementalStreamParser<T>;
1159
+ factory: EventFactory;
1160
+ providerLabel: string;
1161
+ transportLabel: string;
1162
+ incompleteMessage: string;
1163
+ };
1164
+ type ProviderStreamBatch<T> = {
1165
+ items: T[];
1166
+ warnings: AIStreamEvent[];
1167
+ };
1168
+ /**
1169
+ * 读取并解析 provider 流。
1170
+ * 每个 batch 携带本轮解析出的 items 与(可选)malformed / incomplete warning。
1171
+ * 调用方应 `for await` 消费完毕;reader 在迭代结束时 cancel/release。
1172
+ */
1173
+ declare function iterateProviderStreamBatches<T>(options: ProviderStreamBatchOptions<T>): AsyncGenerator<ProviderStreamBatch<T>, void, undefined>;
1174
+ /** 一次性 complete 守卫:首次成功,后续返回 false。 */
1175
+ declare function createCompletionGate(): {
1176
+ readonly completed: boolean;
1177
+ tryComplete(): boolean;
1178
+ };
1176
1179
  //#endregion
1177
1180
  //#region src/helpers/request-mapper.d.ts
1178
1181
  declare class NormalizedRequestMapper {
@@ -1183,12 +1186,24 @@ declare class NormalizedRequestMapper {
1183
1186
  ensureReasoningBlocks(blocks: ContentBlock[], field: string): Array<Extract<ContentBlock, {
1184
1187
  type: "text";
1185
1188
  }>>;
1189
+ /** ensureTextBlocks + contentBlocksToText 的常见组合。 */
1190
+ textFromBlocks(blocks: ContentBlock[], field: string): string;
1186
1191
  parseToolArguments(item: ToolCallItem): Record<string, unknown>;
1187
1192
  rollbackTrailingAssistantMessages<T extends {
1188
1193
  role: string;
1189
1194
  }>(messages: T[]): void;
1195
+ mapToolsIfPresent<T>(tools: ToolDefinition[] | undefined, map: (tool: ToolDefinition) => T): T[] | undefined;
1196
+ /**
1197
+ * 将 canonical toolChoice 映射为 provider 形状。
1198
+ * 返回 undefined 表示调用方无需写入 body 字段。
1199
+ */
1200
+ mapToolChoice<T>(toolChoice: ToolChoice | undefined, mappers: {
1201
+ auto: T;
1202
+ none: T;
1203
+ tool: (name: string) => T;
1204
+ }): T | undefined;
1190
1205
  private ensureBlocks;
1191
1206
  }
1192
1207
  //#endregion
1193
- export { type AIClient, AIError, AIMappingError, AIProviderError, type AIRequest, AIRequestError, type AIResponse, AIStreamError, type AIStreamEvent, AdapterAuxiliaryState, AdapterBase, AuxiliaryCollector, type AuxiliaryFinalizeOptions, type AuxiliaryFinalizeResult, type AuxiliaryInfo, type BackendAdapter, type BackendTrace, type BillingInfo, type BillingPostprocessHook, type BillingSource, ChatCompletionsAdapter, type ChatCompletionsAdapterOptions, type ContentBlock, type CreateAIClientOptions, type EventFactory, type EventFactoryBackend, type EventFactoryState, type FetchFn, type IncludeSettings, IncrementalStreamParser, type InputItem, type InstructionBlock, type JsonContentBlock, type LookupResult, MAX_OPAQUE_JSON_DEPTH, MAX_OPAQUE_PAYLOAD_BYTES, type MessageCompletedEvent, type MessageDeltaEvent, type MessageItem, type MessageStartedEvent, MessagesAdapter, type MessagesAdapterOptions, MockAdapter, type MockAdapterOptions, type MockAuxiliaryStep, type MockCompleteStep, type MockErrorStep, type MockHandler, type MockHandlerContext, type MockHistoryRecord, type MockInputExpectation, type MockInterruptStep, type MockMessageStep, type MockOutputStep, type MockReasoningStep, type MockRequestExpectation, type MockStaticHandler, type MockStep, type MockTextStreamOptions, type MockThrowStep, type MockToolCallStep, type MockWarningStep, type NormalizeOptions, type NormalizedRequest, NormalizedRequestMapper, OllamaAdapter, type OllamaAdapterOptions, type OpaqueEnvelopeResult, type OpaqueItem, type OutputItem, PROVIDER_ERROR_MESSAGE_MAX_LEN, PROVIDER_ERROR_RAW_BODY_THRESHOLD, type ReasoningCompletedEvent, type ReasoningDeltaEvent, type ReasoningItem, type ReasoningStartedEvent, type ReplayItem, type ResponseAuxiliaryEvent, type ResponseCompletedEvent, type ResponseStartedEvent, type ResponseWarningEvent, ResponsesAdapter, type ResponsesAdapterOptions, type SSEEvent, type StopReason, type StreamEventBase, type StreamParseResult, type StreamResult, type StreamSplitResult, type SyntheticStreamOptions, type TextContentBlock, type ToolCallCompletedEvent, type ToolCallDeltaEvent, type ToolCallItem, type ToolCallStartedEvent, type ToolChoice, type ToolDefinition, type ToolResultItem, type Usage, type UsageSource, type ValidationIssue, WarningCode, aggregateEvents, assertMockRequest, assertOpaqueReplayEnvelope, assertValidRequest, blockToText, collectStream, contentBlocksToText, createAIClient, createEventFactory, emitMalformedStreamWarning, extractProviderErrorMessage, extractText, imageBlock, instructionsToText, jsonBlock, mapReasoningVisibility, mapStopReason, measureJsonDepth, messageItem, metadataSourceList, normalizeRequest, opaqueBlock, opaqueItem, parseSSEEvents, providerHttpError, reasoningItem, replayFromOutput, splitLines, splitSSEFrames, syntheticStream, textBlock, toolCallItem, toolResultItem, usageFromAnthropicMessages, usageFromChatCompletions, usageFromOllama, usageFromOpenAIResponses, validateOpaqueReplayEnvelope, validateRequest, withMockStreaming };
1208
+ export { type AIClient, AIError, AIMappingError, AIProviderError, type AIRequest, AIRequestError, type AIResponse, AIStreamError, type AIStreamEvent, AdapterAuxiliaryState, AdapterBase, AuxiliaryCollector, type AuxiliaryFinalizeOptions, type AuxiliaryFinalizeResult, type AuxiliaryInfo, type BackendAdapter, type BackendTrace, type BillingInfo, type BillingPostprocessHook, type BillingSource, ChatCompletionsAdapter, type ChatCompletionsAdapterOptions, type ContentBlock, type CreateAIClientOptions, type EventFactory, type EventFactoryBackend, type EventFactoryState, type FetchFn, type IncludeSettings, IncrementalStreamParser, type InputItem, type InstructionBlock, type JsonContentBlock, type LookupResult, MAX_OPAQUE_JSON_DEPTH, MAX_OPAQUE_PAYLOAD_BYTES, type MessageCompletedEvent, type MessageDeltaEvent, type MessageItem, type MessageStartedEvent, MessagesAdapter, type MessagesAdapterOptions, MockAdapter, type MockAdapterOptions, type MockAuxiliaryStep, type MockCompleteStep, type MockErrorStep, type MockHandler, type MockHandlerContext, type MockHistoryRecord, type MockInputExpectation, type MockInterruptStep, type MockMessageStep, type MockOutputStep, type MockReasoningStep, type MockRequestExpectation, type MockStaticHandler, type MockStep, type MockTextStreamOptions, type MockThrowStep, type MockToolCallStep, type MockWarningStep, type NormalizeOptions, type NormalizedRequest, NormalizedRequestMapper, OllamaAdapter, type OllamaAdapterOptions, type OpaqueEnvelopeResult, type OpaqueItem, type OpenProviderJsonStreamOptions, type OpenedProviderStream, type OutputItem, PROVIDER_ERROR_MESSAGE_MAX_LEN, PROVIDER_ERROR_RAW_BODY_THRESHOLD, type ProviderStreamBatch, type ProviderStreamBatchOptions, type ReasoningCompletedEvent, type ReasoningDeltaEvent, type ReasoningItem, type ReasoningStartedEvent, type ReplayItem, type ResponseAuxiliaryEvent, type ResponseCompletedEvent, type ResponseStartedEvent, type ResponseWarningEvent, ResponsesAdapter, type ResponsesAdapterOptions, type SseJsonEvent, type StopReason, type StreamEventBase, type StreamParseResult, type StreamResult, type StreamSplitResult, type SyntheticStreamOptions, type TextContentBlock, type ToolCallCompletedEvent, type ToolCallDeltaEvent, type ToolCallItem, type ToolCallStartedEvent, type ToolChoice, type ToolDefinition, type ToolResultItem, type Usage, type UsageSource, type ValidationIssue, WarningCode, aggregateEvents, assertMockRequest, assertOpaqueReplayEnvelope, assertValidRequest, blockToText, collectStream, contentBlocksToText, createAIClient, createChatCompletionsSseParser, createCompletionGate, createEventFactory, createNdjsonLineParser, createSseJsonParser, emitMalformedStreamWarning, extractProviderErrorMessage, extractText, imageBlock, iterateProviderStreamBatches, jsonBlock, mapReasoningVisibility, mapStopReason, measureJsonDepth, messageItem, normalizeRequest, opaqueBlock, opaqueItem, openProviderJsonStream, parseChatCompletionsDataLine, parseSseJsonFrame, providerHttpError, reasoningItem, replayFromOutput, splitLines, splitSSEFrames, syntheticStream, textBlock, toolCallItem, toolResultItem, usageFromAnthropicMessages, usageFromChatCompletions, usageFromOllama, usageFromOpenAIResponses, validateOpaqueReplayEnvelope, validateRequest, withMockStreaming };
1194
1209
  //# sourceMappingURL=index.d.mts.map