diff --git a/packages/core/src/agent/agent-core.ts b/packages/core/src/agent/agent-core.ts index 1565f790b..a1dc901a1 100644 --- a/packages/core/src/agent/agent-core.ts +++ b/packages/core/src/agent/agent-core.ts @@ -374,7 +374,7 @@ export class AgentCore extends YesImBotService { const willingnessAfterReply = this.willing.getCurrentWillingness(scoreKey); /* prettier-ignore */ - this.logger.debug(`[${channelCid}] 回复成功,意愿值已更新: ${willingnessBeforeReply.toFixed(2)} -> ${willingnessAfterReply.toFixed(2)}`); + this.logger.debug(`[${channelCid}] 回复成功,意愿值已更新 | 计分键: ${scoreKey} | ${willingnessBeforeReply.toFixed(2)} -> ${willingnessAfterReply.toFixed(2)}`); } const completed = valid(); this.recordDecision(stimulus, { diff --git a/packages/core/src/agent/heartbeat-processor.ts b/packages/core/src/agent/heartbeat-processor.ts index 0334ff1a0..1c782760e 100644 --- a/packages/core/src/agent/heartbeat-processor.ts +++ b/packages/core/src/agent/heartbeat-processor.ts @@ -605,7 +605,10 @@ export class HeartbeatProcessor { assertReplyTurn(); const result = await this.invokeAction(turnId, action, session); assertReplyTurn(); - if (action.function === "send_message" && result.status === "success") { + if ( + action.function === "send_message" && + (result.status === "success" || result.metadata?.delivery?.messageIds?.some((id: unknown) => typeof id === "string" && id.trim())) + ) { replySent = true; onReplySent(); } @@ -615,6 +618,7 @@ export class HeartbeatProcessor { status: result.status, result: result.result, error: result.error, + metadata: result.metadata, }); if (result.status !== "success") throw new Error(`工具 ${action.function} 执行失败: ${result.error?.message ?? "未知错误"}`); } @@ -666,7 +670,10 @@ export class HeartbeatProcessor { assertReplyTurn(); const result = await this.invokeAction(turnId, action, session); assertReplyTurn(); - if (action.function === "send_message" && result.status === "success") { + if ( + action.function === "send_message" && + (result.status === "success" || result.metadata?.delivery?.messageIds?.some((id: unknown) => typeof id === "string" && id.trim())) + ) { replySent = true; onReplySent(); } @@ -676,7 +683,11 @@ export class HeartbeatProcessor { status: result.status, result: result.result, error: result.error, + metadata: result.metadata, }); + if (action.function === "send_message" && result.status !== "success" && result.metadata?.delivery?.messageIds?.length) { + throw new Error(`消息仅部分发送,停止本轮以避免重复投递: ${result.error?.message ?? "未知错误"}`); + } } return replySent; } diff --git a/packages/core/src/agent/reply-turn.ts b/packages/core/src/agent/reply-turn.ts index 543a85b72..975927d14 100644 --- a/packages/core/src/agent/reply-turn.ts +++ b/packages/core/src/agent/reply-turn.ts @@ -2,6 +2,7 @@ import { AsyncLocalStorage } from "node:async_hooks"; import type { Bot, Session } from "koishi"; +import { MessageDeliveryError, confirmedMessages, messageReceiptSink, type ConfirmedMessage } from "../shared/message-delivery"; import type { ReplyTarget } from "./reply-control"; type ReplyTurn = { valid: () => boolean; signal?: AbortSignal; canSend?: (target: ReplyTarget) => boolean }; @@ -107,9 +108,14 @@ async function withGuardedEncoder( // 同 bot、频道和异步链上的普通发送/新 turn 也必须有本次调用的令牌。 const guarded = args[3]?.[encoderSendToken] === token && String(args[1]) === String(channelId); const encoderOptions = { ...args[3] }; - if (guarded) delete encoderOptions[encoderSendToken]; + if (guarded) { + delete encoderOptions[encoderSendToken]; + delete encoderOptions[messageReceiptSink]; + } + const receiptSink = guarded ? args[3]?.[messageReceiptSink] : undefined; const encoderArgs = [...args]; - encoderArgs[0] = bot; + // OneBot enforces destination checks through its bot receiver. + encoderArgs[0] = guardedBots.has(args[0]) ? args[0] : bot; if (guarded) encoderArgs[3] = encoderOptions; const encoder = Reflect.construct(target, encoderArgs); for (const key of ["send", "prepare", "render", "visit", "flush"] as const) { @@ -121,7 +127,20 @@ async function withGuardedEncoder( // 普通发送在自己的编码器中移除父异步链的旧保护。 if (guarded) scope.set(bot, () => check(encoder.channelId, encoder.session?.guildId)); else scope.delete(bot); - return outboundScopes.run(scope, () => method.apply(encoder, args)); + const result = outboundScopes.run(scope, () => method.apply(encoder, args)); + if (guarded && key === "send") { + return Promise.resolve(result) + .then((value) => { + receiptSink?.(Array.isArray(encoder.results) ? encoder.results : []); + return value; + }) + .catch((error) => { + const deliveryError = new MessageDeliveryError(error, Array.isArray(encoder.results) ? encoder.results : []); + if (deliveryError.messages.length) throw deliveryError; + throw error; + }); + } + return result; }; } return encoder; @@ -161,6 +180,31 @@ async function withGuardedEncoder( } } } +/** Capture adapter-confirmed content while preserving the guarded bot's send path. */ +export async function sendMessageWithReceipts(bot: Bot, channelId: string, content: Parameters[1], referrer?: any, options?: any) { + let raw = bot; + while (guardedBots.has(raw)) raw = guardedBots.get(raw)!.bot; + let messages: ConfirmedMessage[] | undefined; + const sendOptions = { + ...options, + [messageReceiptSink]: (receipts: ConfirmedMessage[]) => { + messages = confirmedMessages(receipts); + }, + }; + // Adapters without encoders retain their exact calling convention. + if (!(raw.constructor as typeof Bot).MessageEncoder) { + const ids = await bot.sendMessage(channelId, content, referrer, options); + return { ids, messages }; + } + const ids = await withGuardedEncoder( + raw, + channelId, + sendOptions, + () => {}, + (scopedOptions) => bot.sendMessage(channelId, content, referrer, scopedOptions), + ); + return { ids, messages }; +} export function isReplyTurnCancelled(): boolean { const turn = turns.getStore(); return turn?.signal?.aborted === true || turn?.valid() === false; diff --git a/packages/core/src/extension/builtin/core-util/index.ts b/packages/core/src/extension/builtin/core-util/index.ts index 3ab0087c3..1910c4cc7 100644 --- a/packages/core/src/extension/builtin/core-util/index.ts +++ b/packages/core/src/extension/builtin/core-util/index.ts @@ -1,14 +1,19 @@ import { Bot, Context, h, Logger, Schema, Session, sleep, Universal } from "koishi"; -import { assertReplyDestination, guardReplyBot, replyTurnSignal } from "../../../agent/reply-turn"; +import { assertReplyDestination, guardReplyBot, replyTurnSignal, sendMessageWithReceipts } from "../../../agent/reply-turn"; import { AssetService } from "../../../asset"; import { Extension, Tool, withInnerThoughts } from "../../../extension/decorators"; import { Failed, Success } from "../../../extension/helpers"; import { Infer } from "../../../extension/types"; import { IChatModel, ModelDescriptor } from "../../../model"; import { withUsageScope } from "../../../model/usage"; +import { MessageDeliveryError, type ConfirmedMessage } from "../../../shared/message-delivery"; import { isEmpty, parseConversationChannelId } from "../../../shared/utils"; +function sendErrorScalar(key: string, value: unknown): string { + return (typeof value === "string" || typeof value === "number") && String(value).trim() ? `${key}=${String(value).slice(0, 512)}` : ""; +} + interface CoreUtilConfig { typing: { baseDelay: number; @@ -101,15 +106,23 @@ export default class CoreUtilExtension { return Failed("消息内容为空"); } + const delivery = { messageIds: [] as string[], sentMessages: 0, totalMessages: messages.length }; try { const { bot, channelId, channel, userId, guild } = await this.determineTarget(session, target, self_id, target_type, guild_id); - await this.sendMessagesWithHumanLikeDelay(messages, bot, channelId, session, channel, userId, guild); + await this.sendMessagesWithHumanLikeDelay(messages, bot, channelId, session, channel, userId, guild, delivery); - return Success(); + return Success(undefined, { delivery }); } catch (error) { - //this.logger.error(error); - return Failed(`发送消息失败。错误: ${this.getSendErrorMessage(error) || "未知发送错误"}`); + const partial = delivery.messageIds.length > 0; + return Failed( + { + name: partial ? "PartialDeliveryError" : "ToolError", + message: `${partial ? `消息未全部发送:已完整发送 ${delivery.sentMessages}/${delivery.totalMessages} 段(确认 ${delivery.messageIds.length} 条消息),请勿重复发送已送达内容` : "发送消息失败"}。错误: ${this.getSendErrorMessage(error) || "未知发送错误"}`, + retryable: false, + }, + { delivery }, + ); } } @@ -308,11 +321,17 @@ export default class CoreUtilExtension { if (typeof error === "string") return error; if (!error || typeof error !== "object" || seen.has(error)) return ""; seen.add(error); - const details = error as { message?: string; errors?: unknown[]; cause?: unknown }; + const details = error as { message?: string; errors?: unknown[]; cause?: unknown; code?: unknown; response?: { status?: unknown; data?: unknown } }; + // Only expose diagnostic fields, never serialize request config or headers. + const data = details.response?.data; + const api = data && typeof data === "object" ? (data as Record) : undefined; const messages = [ ...(Array.isArray(details.errors) ? details.errors.map((inner) => this.getSendErrorMessage(inner, seen)) : []), this.getSendErrorMessage(details.cause, seen), typeof details.message === "string" ? details.message : "", + sendErrorScalar("code", details.code), + sendErrorScalar("HTTP", details.response?.status), + ...["code", "message", "msg", "trace_id"].map((key) => sendErrorScalar(key, api?.[key])), ].filter(Boolean); return [...new Set(messages)].join("; "); } @@ -332,6 +351,7 @@ export default class CoreUtilExtension { channel?: Universal.Channel, userId?: string, guild?: Universal.Guild, + delivery = { messageIds: [] as string[], sentMessages: 0, totalMessages: messages.length }, ): Promise { const sameSession = bot === originalSession.bot && @@ -379,21 +399,43 @@ export default class CoreUtilExtension { }); // --- 发送消息 --- - const messageIds = sameSession - ? await bot.sendMessage(channelId, content, originalSession.event.referrer, { session: originalSession }) - : routingSession - ? await bot.sendMessage(channelId, content, undefined, { session: routingSession }) - : await bot.sendMessage(channelId, content); - if (!messageIds?.length) { + let messageIds: string[]; + let receipts: ConfirmedMessage[] | undefined; + let partialError: MessageDeliveryError | undefined; + try { + const sent = await sendMessageWithReceipts( + bot, + channelId, + content, + sameSession ? originalSession.event.referrer : undefined, + sameSession ? { session: originalSession } : routingSession ? { session: routingSession } : undefined, + ); + messageIds = sent.ids; + receipts = sent.messages; + } catch (error) { + if (!(error instanceof MessageDeliveryError)) throw error; + partialError = error; + messageIds = error.messages.map((message) => message.id); + } + const confirmedIds = [...new Set((Array.isArray(messageIds) ? messageIds : []).filter((id) => typeof id === "string" && id.trim()))]; + if (!confirmedIds.length) { + if (partialError) throw partialError; throw new Error("适配器未返回消息 ID,无法确认发送结果"); } - - // --- 发送后处理 --- - if (messageIds && messageIds.length > 0) { - for (const messageId of new Set(messageIds)) { - await this.emitAfterSendEvent(bot, channelId, quoted, messageId, originalSession, channel, guild); - } + for (const id of confirmedIds) if (!delivery.messageIds.includes(id)) delivery.messageIds.push(id); + if (!partialError) delivery.sentMessages++; + + // Preserve confirmed external effects even if a later encoder request failed. + for (const messageId of confirmedIds) { + const confirmed = partialError?.messages ?? receipts; + const sentContent = confirmed + ? (confirmed.find((message) => message.id === messageId)?.content ?? "") + : confirmedIds.length === 1 + ? quoted + : ""; + await this.emitAfterSendEvent(bot, channelId, sentContent, messageId, originalSession, channel, guild); } + if (partialError) throw partialError; // 如果还有下一条消息,增加一个“段落间隔”延迟 if (i < messages.length - 1) { diff --git a/packages/core/src/model/chat-model.ts b/packages/core/src/model/chat-model.ts index 8914b75ac..f07a68e73 100644 --- a/packages/core/src/model/chat-model.ts +++ b/packages/core/src/model/chat-model.ts @@ -277,6 +277,12 @@ export class ChatModel extends BaseModel implements IChatModel { let completion = new StreamCompletion(); let buffer: string[] = []; let diagnostics = new StreamDiagnostics(stime); + const markStreamStarted = () => { + if (streamStarted) return; + onStreamStart?.(); + streamStarted = true; + this.logger.debug(`🌊 流式传输已开始 | 延迟: ${Date.now() - stime}ms`); + }; const originalFetch = chatOptions.fetch as (url: any, init: any) => Promise; const streamOptions = { ...chatOptions, @@ -288,11 +294,7 @@ export class ChatModel extends BaseModel implements IChatModel { // Validate complete SSE text before the transport EOF gate, not in downstream SDK events. const responseCompletion = (completion = new StreamCompletion((textDelta) => { if (responseCompletion.earlyExit || !textDelta) return; - if (!streamStarted) { - onStreamStart?.(); - streamStarted = true; - this.logger.debug(`🌊 流式传输已开始 | 延迟: ${Date.now() - stime}ms`); - } + markStreamStarted(); buffer.push(textDelta); finalContentParts.push(textDelta); if (!validator) return; @@ -301,7 +303,7 @@ export class ChatModel extends BaseModel implements IChatModel { responseCompletion.earlyExit = true; this.logger.debug(`✅ 内容有效,可提前结束流 | 耗时: ${Date.now() - stime}ms`); if (validationResult.parsedData) finalContentParts.splice(0, finalContentParts.length, JSON.stringify(validationResult.parsedData)); - })); + }, markStreamStarted)); diagnostics.recordResponse(response); this.logger.debug(`[${requestId}] HTTP 响应 | ${JSON.stringify(diagnostics.summary())}`); if (response.ok) { @@ -557,7 +559,10 @@ class StreamCompletion { hasTools = false; earlyExit = false; - constructor(private readonly onContent?: (text: string) => void) {} + constructor( + private readonly onContent?: (text: string) => void, + private readonly onNativeActivity?: () => void, + ) {} observe(chunk: Uint8Array): void { this.scan(this.decoder.decode(chunk, { stream: true })); @@ -589,6 +594,10 @@ class StreamCompletion { continue; } if (typeof choice?.finish_reason === "string" && choice.finish_reason.length > 0) this.completed = true; + if (choice?.delta?.yib_native_activity === true) { + this.hasTools = true; + this.onNativeActivity?.(); + } if (choice?.delta?.tool_calls?.length) this.hasTools = true; // Match the SDK's first-choice text path; validator failures must propagate. else if (typeof choice?.delta?.content === "string") this.onContent?.(choice.delta.content); diff --git a/packages/core/src/model/config.ts b/packages/core/src/model/config.ts index 6aa620187..17b143957 100644 --- a/packages/core/src/model/config.ts +++ b/packages/core/src/model/config.ts @@ -185,6 +185,28 @@ export const ModelConfigSchema: Schema = Schema.object({ .description("断路器策略"), }).description("单个模型配置"); +// Anthropic models have differing sampling constraints; leave sampling unset unless explicitly configured. +const NativeAnthropicModelConfigSchema = Schema.object({ + ...ModelConfigSchema.dict!, + parameters: Schema.object({ + ...ModelConfigSchema.dict!.parameters.dict!, + temperature: Schema.number().description("采样温度(可选,请遵循模型限制)"), + topP: Schema.number().description("核采样概率(可选,请遵循模型限制)"), + }) + .collapse() + .description("生成参数"), +}).description("单个模型配置") as Schema; + +// LM Studio native chat exposes server integrations, not client-owned function tools. +const NativeLMStudioModelConfigSchema = Schema.object({ + ...ModelConfigSchema.dict!, + abilities: Schema.array(Schema.union(Object.values(ModelAbility))) + .role("checkbox") + .default([ModelAbility.Chat]) + .description("模型支持的能力"), + disableNativeToolCalling: Schema.boolean().default(true).hidden(), +}).description("单个模型配置") as Schema; + const PROVIDERS = { TypeSafe: { baseURL: "https://api.typesafe.ai/v1/", link: "https://typesafe.ai/" }, OpenAI: { baseURL: "https://api.openai.com/v1/", link: "https://platform.openai.com/account/api-keys" }, @@ -193,32 +215,33 @@ const PROVIDERS = { Fireworks: { baseURL: "https://api.fireworks.ai/inference/v1/", link: "https://console.fireworks.ai/api-keys" }, DeepSeek: { baseURL: "https://api.deepseek.com/", link: "https://platform.deepseek.com/api_keys" }, "Google Gemini": { - baseURL: "https://generativelanguage.googleapis.com/v1beta/openai/", + baseURL: "https://generativelanguage.googleapis.com/v1beta/", link: "https://aistudio.google.com/app/apikey", }, - "LM Studio": { baseURL: "http://localhost:5000/v1/", link: "https://lmstudio.ai/docs/app/api/endpoints/openai" }, + "LM Studio": { baseURL: "http://localhost:1234/", link: "https://lmstudio.ai/docs/developer/openai-compat" }, "Workers AI": { baseURL: "https://api.cloudflare.com/client/v4/", link: "https://dash.cloudflare.com/?to=/:account/workers-ai" }, Zhipu: { baseURL: "https://open.bigmodel.cn/api/paas/v4/", link: "https://open.bigmodel.cn/usercenter/apikeys" }, "Silicon Flow": { baseURL: "https://api.siliconflow.cn/v1/", link: "https://console.siliconflow.cn/account/key" }, - Qwen: { baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1/", link: "https://dashscope.console.aliyun.com/apiKey" }, - Ollama: { baseURL: "http://localhost:11434/v1/", link: "https://ollama.com/" }, + Qwen: { baseURL: "https://dashscope.aliyuncs.com/api/v1/", link: "https://dashscope.console.aliyun.com/apiKey" }, + Ollama: { baseURL: "http://localhost:11434/", link: "https://ollama.com/" }, // "Azure OpenAI": { // baseURL: "https://.services.ai.azure.com/models/", // link: "https://oai.azure.com/", // }, Cerebras: { baseURL: "https://api.cerebras.ai/v1/", link: "https://inference-docs.cerebras.ai/api-reference/chat-completions" }, DeepInfra: { baseURL: "https://api.deepinfra.com/v1/openai/", link: "https://deepinfra.com/dash/api_keys" }, + "Featherless AI": { baseURL: "https://api.featherless.ai/v1/", link: "https://featherless.ai/login" }, "Fatherless AI": { baseURL: "https://api.featherless.ai/v1/", link: "https://featherless.ai/login" }, Groq: { baseURL: "https://api.groq.com/openai/v1/", link: "https://console.groq.com/keys" }, - Minimax: { baseURL: "https://api.minimax.chat/v1/", link: "https://platform.minimaxi.com/api-key" }, - "Minimax (International)": { baseURL: "https://api.minimaxi.chat/v1/", link: "https://www.minimax.io/user-center/api-keys" }, + Minimax: { baseURL: "https://api.minimax.cn/v1/", link: "https://platform.minimaxi.com/api-key" }, + "Minimax (International)": { baseURL: "https://api.minimax.io/v1/", link: "https://platform.minimax.io/console/access" }, Mistral: { baseURL: "https://api.mistral.ai/v1/", link: "https://console.mistral.ai/api-keys/" }, Moonshot: { baseURL: "https://api.moonshot.cn/v1/", link: "https://platform.moonshot.cn/console/api-keys" }, Novita: { baseURL: "https://api.novita.ai/v3/openai/", link: "https://novita.ai/get-started" }, OpenRouter: { baseURL: "https://openrouter.ai/api/v1/", link: "https://openrouter.ai/keys" }, Perplexity: { baseURL: "https://api.perplexity.ai/", link: "https://www.perplexity.ai/settings/api" }, Stepfun: { baseURL: "https://api.stepfun.com/v1/", link: "https://platform.stepfun.com/my-keys" }, - "Tencent Hunyuan": { baseURL: "https://api.hunyuan.cloud.tencent.com/v1/", link: "https://console.cloud.tencent.com/cam/capi" }, + "Tencent Hunyuan": { baseURL: "https://api.hunyuan.cloud.tencent.com/v1/", link: "https://console.cloud.tencent.com/hunyuan/start" }, "Together AI": { baseURL: "https://api.together.xyz/v1/", link: "https://api.together.ai/settings/api-keys" }, "XAI (Grok)": { baseURL: "https://api.x.ai/v1/", link: "https://docs.x.ai/docs/overview" }, } as const; @@ -229,31 +252,96 @@ export type ProviderType = keyof typeof PROVIDERS; const DEFAULT_PROVIDER_TYPE: ProviderType = "OpenAI"; +export type ProviderProtocol = + | "chat-completions" + | "gemini-native" + | "anthropic-native" + | "ollama-native" + | "qwen-native" + | "workers-native" + | "lmstudio-native"; + +/** Provider type owns the wire protocol. Some official vendor APIs already use Chat Completions. */ +export function getProviderProtocol(type: ProviderType): ProviderProtocol { + if (type === "Google Gemini") return "gemini-native"; + if (type === "Anthropic") return "anthropic-native"; + if (type === "Ollama") return "ollama-native"; + if (type === "Qwen") return "qwen-native"; + if (type === "Workers AI") return "workers-native"; + if (type === "LM Studio") return "lmstudio-native"; + return "chat-completions"; +} + +export function getProviderBaseURL(config: Pick): string { + if (config.type === "Workers AI") { + if (!config.accountId || !/^[a-zA-Z0-9_-]+$/.test(config.accountId)) throw new Error("Workers AI 需要有效的 Cloudflare 账户 ID"); + return `https://api.cloudflare.com/client/v4/accounts/${config.accountId}/ai/`; + } + return config.baseURL ?? PROVIDERS[config.type]?.baseURL; +} + export interface ProviderConfig { name: string; type: ProviderType; baseURL?: string; + accountId?: string; apiKey: string; proxy?: string; models: ModelConfig[]; } export const ProviderConfigSchema: Schema = Schema.intersect([ + // Adapt saved defaults before resolving the visible fields; keep their console schema unchanged. + Schema.transform(Schema.any(), (config) => { + // Console validation reconstructs this callback without module scope. + const roots: Record = { + "Google Gemini": ["https://generativelanguage.googleapis.com/v1beta/openai/", "https://generativelanguage.googleapis.com/v1beta/"], + Qwen: ["https://dashscope.aliyuncs.com/compatible-mode/v1/", "https://dashscope.aliyuncs.com/api/v1/"], + Ollama: ["http://localhost:11434/v1/", "http://localhost:11434/"], + }; + const migration = roots[config?.type]; + if (migration && typeof config.baseURL === "string" && config.baseURL.replace(/\/?$/, "/") === migration[0]) { + config.baseURL = migration[1]; + } + return {}; + }).hidden(), Schema.object({ name: Schema.string().required().description("提供商名称"), - type: Schema.union(PROVIDER_TYPES).default(DEFAULT_PROVIDER_TYPE).description("提供商类型"), + type: Schema.union(PROVIDER_TYPES.map((type) => Schema.const(type).description(type === "Fatherless AI" ? "Featherless AI(旧配置名称)" : type))) + .default(DEFAULT_PROVIDER_TYPE) + .description("提供商类型"), }), Schema.union( PROVIDER_TYPES.map((type) => { return Schema.object({ - // Only the default branch may match when the provider type is omitted. + // Provider type determines the wire protocol; compatible gateways use OpenAI Compatible. type: type === DEFAULT_PROVIDER_TYPE ? Schema.const(type) : Schema.const(type).required(), - baseURL: Schema.string().default(PROVIDERS[type].baseURL).role("link").description(`提供商的 API 地址`), + ...(type === "Workers AI" + ? { + accountId: Schema.string() + .pattern(/^[a-zA-Z0-9_-]+$/) + .required() + .description("Cloudflare 账户 ID"), + } + : { + baseURL: Schema.string() + .default(PROVIDERS[type].baseURL) + .role("link") + .description( + ["Google Gemini", "Anthropic", "Qwen", "Ollama", "LM Studio"].includes(type) + ? "原生 API 根地址(兼容服务请选择 OpenAI Compatible)" + : "提供商的 API 地址", + ), + }), apiKey: Schema.string() .role("secret") .description(`提供商的 API 密钥${PROVIDERS[type].link ? ` (获取地址 - ${PROVIDERS[type].link})` : ""}`), proxy: Schema.string().description("代理地址"), - models: Schema.array(ModelConfigSchema).required().description("模型列表"), + models: Schema.array( + type === "Anthropic" ? NativeAnthropicModelConfigSchema : type === "LM Studio" ? NativeLMStudioModelConfigSchema : ModelConfigSchema, + ) + .required() + .description("模型列表"), }); }), ), diff --git a/packages/core/src/model/factories.ts b/packages/core/src/model/factories.ts index 4a23d9757..9adf29043 100644 --- a/packages/core/src/model/factories.ts +++ b/packages/core/src/model/factories.ts @@ -10,7 +10,6 @@ import { createOpenAI, createQwen, createSiliconFlow, - createWorkersAI, createZhipu, createCerebras, createDeepInfra, @@ -28,7 +27,7 @@ import { createTogetherAI, createXAI, } from "../dependencies/xsai"; -import type { ProviderConfig, ProviderType } from "./config"; +import { getProviderBaseURL, type ProviderConfig, type ProviderType } from "./config"; import type { EvaluationRequestOptions } from "./evaluation-client"; // --- 接口定义 --- @@ -50,7 +49,8 @@ export interface IProviderFactory { class OpenAIFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { apiKey, baseURL } = config; + const { apiKey } = config; + const baseURL = getProviderBaseURL(config); const client = createOpenAI(apiKey, baseURL); return { chat: client.chat, @@ -65,7 +65,7 @@ class OpenAIFactory implements IProviderFactory { class OllamaFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { baseURL } = config; + const baseURL = getProviderBaseURL(config); const client = createOllama(baseURL); return { chat: client.chat, embed: client.embed, model: client.model }; } @@ -73,7 +73,8 @@ class OllamaFactory implements IProviderFactory { class AnthropicFactory implements IProviderFactory { public createClient(config: ProviderConfig): IProviderClient { - const { apiKey, baseURL } = config; + const { apiKey } = config; + const baseURL = getProviderBaseURL(config); const client = createAnthropic(apiKey, baseURL); return { chat: client.chat, model: client.model }; } @@ -113,7 +114,8 @@ class AnthropicFactory implements IProviderFactory { class FireworksFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { apiKey, baseURL } = config; + const { apiKey } = config; + const baseURL = getProviderBaseURL(config); const client = createFireworks(apiKey, baseURL); return { chat: client.chat, embed: client.embed, model: client.model }; } @@ -121,7 +123,8 @@ class FireworksFactory implements IProviderFactory { class DeepSeekFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { apiKey, baseURL } = config; + const { apiKey } = config; + const baseURL = getProviderBaseURL(config); const client = createDeepSeek(apiKey, baseURL); return { chat: client.chat, model: client.model }; } @@ -129,7 +132,8 @@ class DeepSeekFactory implements IProviderFactory { class GoogleGenerativeAIFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { apiKey, baseURL } = config; + const { apiKey } = config; + const baseURL = getProviderBaseURL(config); const client = createGoogleGenerativeAI(apiKey, baseURL); return { chat: client.chat, embed: client.embed, model: client.model }; } @@ -137,7 +141,7 @@ class GoogleGenerativeAIFactory implements IProviderFactory { class LMStudioFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { baseURL } = config; + const baseURL = getProviderBaseURL(config); const client = createLMStudio(baseURL); return { chat: client.chat, embed: client.embed, model: client.model }; } @@ -145,7 +149,8 @@ class LMStudioFactory implements IProviderFactory { class ZhipuFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { apiKey, baseURL } = config; + const { apiKey } = config; + const baseURL = getProviderBaseURL(config); const client = createZhipu(apiKey, baseURL); return { chat: client.chat, embed: client.embed, model: client.model }; } @@ -153,7 +158,8 @@ class ZhipuFactory implements IProviderFactory { class SiliconFlowFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { apiKey, baseURL } = config; + const { apiKey } = config; + const baseURL = getProviderBaseURL(config); const client = createSiliconFlow(apiKey, baseURL); return { chat: client.chat, @@ -167,7 +173,8 @@ class SiliconFlowFactory implements IProviderFactory { class QwenFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { apiKey, baseURL } = config; + const { apiKey } = config; + const baseURL = getProviderBaseURL(config); const client = createQwen(apiKey, baseURL); return { chat: client.chat, embed: client.embed, model: client.model }; } @@ -179,18 +186,16 @@ class QwenFactory implements IProviderFactory { */ class WorkersAIFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { apiKey, accountId } = config as ProviderConfig & { accountId: string }; - if (!accountId) { - throw new Error("WorkersAIFactory: `accountId` is required in the provider configuration."); - } - const client = createWorkersAI(apiKey, accountId); - return { chat: client.chat, embed: client.embed }; + const baseURL = getProviderBaseURL(config); + const options = (model: string) => ({ apiKey: config.apiKey, baseURL, model }); + return { chat: options, embed: options }; } } class CerebrasFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { apiKey, baseURL } = config; + const { apiKey } = config; + const baseURL = getProviderBaseURL(config); const client = createCerebras(apiKey, baseURL); return { chat: client.chat, model: client.model }; } @@ -198,7 +203,8 @@ class CerebrasFactory implements IProviderFactory { class DeepInfraFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { apiKey, baseURL } = config; + const { apiKey } = config; + const baseURL = getProviderBaseURL(config); const client = createDeepInfra(apiKey, baseURL); return { chat: client.chat, embed: client.embed, model: client.model }; } @@ -206,7 +212,8 @@ class DeepInfraFactory implements IProviderFactory { class FatherlessAIFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { apiKey, baseURL } = config; + const { apiKey } = config; + const baseURL = getProviderBaseURL(config); const client = createFatherless(apiKey, baseURL); return { chat: client.chat, model: client.model }; } @@ -214,7 +221,8 @@ class FatherlessAIFactory implements IProviderFactory { class GroqFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { apiKey, baseURL } = config; + const { apiKey } = config; + const baseURL = getProviderBaseURL(config); const client = createGroq(apiKey, baseURL); return { chat: client.chat, transcript: client.transcription, model: client.model }; } @@ -222,7 +230,8 @@ class GroqFactory implements IProviderFactory { class MinimaxFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { apiKey, baseURL } = config; + const { apiKey } = config; + const baseURL = getProviderBaseURL(config); const client = createMinimax(apiKey, baseURL); return { chat: client.chat }; } @@ -230,7 +239,8 @@ class MinimaxFactory implements IProviderFactory { class MinimaxiFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { apiKey, baseURL } = config; + const { apiKey } = config; + const baseURL = getProviderBaseURL(config); const client = createMinimaxi(apiKey, baseURL); return { chat: client.chat }; } @@ -238,7 +248,8 @@ class MinimaxiFactory implements IProviderFactory { class MistralFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { apiKey, baseURL } = config; + const { apiKey } = config; + const baseURL = getProviderBaseURL(config); const client = createMistral(apiKey, baseURL); return { chat: client.chat, embed: client.embed, model: client.model }; } @@ -246,7 +257,8 @@ class MistralFactory implements IProviderFactory { class MoonshotFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { apiKey, baseURL } = config; + const { apiKey } = config; + const baseURL = getProviderBaseURL(config); const client = createMoonshot(apiKey, baseURL); return { chat: client.chat, model: client.model }; } @@ -254,7 +266,8 @@ class MoonshotFactory implements IProviderFactory { class NovitaFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { apiKey, baseURL } = config; + const { apiKey } = config; + const baseURL = getProviderBaseURL(config); const client = createNovita(apiKey, baseURL); return { chat: client.chat, model: client.model }; } @@ -262,7 +275,8 @@ class NovitaFactory implements IProviderFactory { class OpenRouterFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { apiKey, baseURL } = config; + const { apiKey } = config; + const baseURL = getProviderBaseURL(config); const client = createOpenRouter(apiKey, baseURL); return { chat: client.chat, model: client.model }; } @@ -270,7 +284,8 @@ class OpenRouterFactory implements IProviderFactory { class PerplexityFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { apiKey, baseURL } = config; + const { apiKey } = config; + const baseURL = getProviderBaseURL(config); const client = createPerplexity(apiKey, baseURL); return { chat: client.chat }; } @@ -278,7 +293,8 @@ class PerplexityFactory implements IProviderFactory { class StepfunFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { apiKey, baseURL } = config; + const { apiKey } = config; + const baseURL = getProviderBaseURL(config); const client = createStepfun(apiKey, baseURL); return { chat: client.chat, speech: client.speech, transcript: client.transcription, model: client.model }; } @@ -286,7 +302,8 @@ class StepfunFactory implements IProviderFactory { class TencentHunyuanFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { apiKey, baseURL } = config; + const { apiKey } = config; + const baseURL = getProviderBaseURL(config); const client = createTencentHunyuan(apiKey, baseURL); return { chat: client.chat, embed: client.embed }; } @@ -294,7 +311,8 @@ class TencentHunyuanFactory implements IProviderFactory { class TogetherAIFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { apiKey, baseURL } = config; + const { apiKey } = config; + const baseURL = getProviderBaseURL(config); const client = createTogetherAI(apiKey, baseURL); return { chat: client.chat, embed: client.embed, model: client.model }; } @@ -302,7 +320,8 @@ class TogetherAIFactory implements IProviderFactory { class XAIFactory implements IProviderFactory { createClient(config: ProviderConfig): IProviderClient { - const { apiKey, baseURL } = config; + const { apiKey } = config; + const baseURL = getProviderBaseURL(config); const client = createXAI(apiKey, baseURL); return { chat: client.chat, model: client.model }; } @@ -340,6 +359,7 @@ class FactoryRegistry { // this.register("Azure OpenAI", new AzureOpenAIFactory()); this.register("Cerebras", new CerebrasFactory()); this.register("DeepInfra", new DeepInfraFactory()); + this.register("Featherless AI", new FatherlessAIFactory()); this.register("Fatherless AI", new FatherlessAIFactory()); this.register("Groq", new GroqFactory()); this.register("Minimax", new MinimaxFactory()); diff --git a/packages/core/src/model/native-fetch.ts b/packages/core/src/model/native-fetch.ts new file mode 100644 index 000000000..7a6499ad1 --- /dev/null +++ b/packages/core/src/model/native-fetch.ts @@ -0,0 +1,88 @@ +import { getProviderBaseURL, getProviderProtocol, type ProviderConfig } from "./config"; +import { anthropicRequest, anthropicResponse, anthropicStream } from "./native/anthropic"; +import { geminiEmbeddings, geminiRequest, geminiResponse, geminiStream } from "./native/gemini"; +import { createLMStudioFetch } from "./native/lmstudio"; +import { createOllamaFetch } from "./native/ollama"; +import { createQwenFetch } from "./native/qwen"; +import { Json, nativeSSE } from "./native/shared"; +import { createWorkersFetch } from "./native/workers"; + +function normalizedJson(value: unknown, response: Response): Response { + const headers = new Headers({ "content-type": "application/json" }); + for (const key of ["request-id", "x-request-id", "x-goog-request-id"]) { + const value = response.headers.get(key); + if (value) headers.set(key, value); + } + return new Response(JSON.stringify(value), { status: response.status, statusText: response.statusText, headers }); +} + +/** Protocol translation is inside the existing proxy/abort and usage observation paths. */ +export function createNativeFetch(config: ProviderConfig, transport: typeof globalThis.fetch): typeof globalThis.fetch { + const protocol = getProviderProtocol(config.type); + if (!protocol || protocol === "chat-completions") return transport; + const base = new URL(getProviderBaseURL(config)); + if (!["http:", "https:"].includes(base.protocol) || base.username || base.password) throw new Error("原生 API 地址必须为不含凭据的 HTTP(S) URL"); + if (protocol === "ollama-native") return createOllamaFetch(config, transport); + if (protocol === "qwen-native") return createQwenFetch(config, transport); + if (protocol === "workers-native") return createWorkersFetch({ ...config, baseURL: base.href }, transport); + if (protocol === "lmstudio-native") return createLMStudioFetch(config, transport); + base.pathname = base.pathname.replace(/\/?$/, "/"); + return (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(typeof input === "string" || input instanceof URL ? input : input.url); + const relative = url.origin === base.origin && url.pathname.startsWith(base.pathname) ? url.pathname.slice(base.pathname.length) : ""; + const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined)); + headers.delete("authorization"); + if (protocol === "gemini-native") headers.set("x-goog-api-key", config.apiKey); + else { + headers.set("x-api-key", config.apiKey); + if (!headers.has("anthropic-version")) headers.set("anthropic-version", "2023-06-01"); + } + if ((init?.method ?? "GET") === "GET" && relative === "models") return transport(input, { ...init, headers, redirect: "error" }); + if (relative !== "chat/completions" && relative !== "embeddings") throw new Error("原生接入不支持此 API 路径"); + if (typeof init?.body !== "string") throw new Error("原生接入需要 JSON 请求体"); + const body: Json = JSON.parse(init.body); + if (typeof body.model !== "string" || !body.model) throw new Error("原生接入缺少模型 ID"); + const model = body.model.replace(/^models\//, ""); + const endpoint = new URL(base); + headers.set("content-type", "application/json"); + let payload: Json; + if (relative === "embeddings") { + if (protocol !== "gemini-native") throw new Error("Anthropic 原生接入不支持嵌入"); + endpoint.pathname += `models/${encodeURIComponent(model)}:batchEmbedContents`; + payload = geminiEmbeddings(body); + } else if (protocol === "gemini-native") { + endpoint.pathname += `models/${encodeURIComponent(model)}:${body.stream ? "streamGenerateContent" : "generateContent"}`; + if (body.stream) endpoint.searchParams.set("alt", "sse"); + payload = geminiRequest(body); + } else { + endpoint.pathname += "messages"; + payload = anthropicRequest(body); + } + const response = await transport(endpoint, { ...init, method: "POST", headers, redirect: "error", body: JSON.stringify(payload) }); + if (!response.ok) return response; + if (relative === "embeddings") { + const value = await response.json(); + if ( + !Array.isArray(value.embeddings) || + value.embeddings.length !== payload.requests.length || + value.embeddings.some( + (item: Json) => + !Array.isArray(item.values) || + !item.values.length || + item.values.some((value: unknown) => typeof value !== "number" || !Number.isFinite(value)), + ) + ) + throw new Error("Gemini 嵌入响应不完整"); + return normalizedJson( + { data: value.embeddings.map((item: Json, index: number) => ({ index, object: "embedding", embedding: item.values })) }, + response, + ); + } + if (body.stream) { + const adapter = protocol === "gemini-native" ? geminiStream() : anthropicStream(); + return nativeSSE(response, adapter.consume, adapter.finish); + } + const value = await response.json(); + return normalizedJson(protocol === "gemini-native" ? geminiResponse(value) : anthropicResponse(value), response); + }) as typeof globalThis.fetch; +} diff --git a/packages/core/src/model/native/anthropic.ts b/packages/core/src/model/native/anthropic.ts new file mode 100644 index 000000000..0c1fdd764 --- /dev/null +++ b/packages/core/src/model/native/anthropic.ts @@ -0,0 +1,203 @@ +import { choice, completed, inlineImage, Json, partsOf, rejectUnknown, safeToolArguments, toolData, toolId } from "./shared"; + +function anthropicParts(content: unknown): Json[] { + return partsOf(content).map((part) => { + if (part.type === "text") return { type: "text", text: part.text, ...(part.cache_control ? { cache_control: part.cache_control } : {}) }; + if (part.type === "image_url") { + const url = part.image_url?.url; + const inline = typeof url === "string" ? inlineImage(url) : undefined; + if (inline) return { type: "image", source: { type: "base64", media_type: inline.mimeType, data: inline.data } }; + if (typeof url === "string" && /^https?:\/\//.test(url)) return { type: "image", source: { type: "url", url } }; + throw new Error("Anthropic 图片需要 HTTP URL 或 base64 data URL"); + } + throw new Error(`Anthropic 原生接入不支持消息内容 ${part.type}`); + }); +} +export function anthropicRequest(body: Json): Json { + rejectUnknown(body, [ + "model", + "messages", + "stream", + "stream_options", + "temperature", + "top_p", + "top_k", + "max_tokens", + "max_completion_tokens", + "stop", + "tools", + "tool_choice", + "thinking", + "output_config", + "metadata", + "n", + "cache_control", + "service_tier", + ]); + if (body.temperature !== undefined && body.top_p !== undefined) throw new Error("Anthropic 原生接入不能同时设置 temperature 和 top_p"); + if (body.n !== undefined && body.n !== 1) throw new Error("Anthropic 原生接入仅支持 n=1"); + const system: Json[] = []; + const messages: Json[] = []; + for (const message of body.messages ?? []) { + if (message.role === "system" || message.role === "developer") { + system.push(...anthropicParts(message.content)); + continue; + } + let content: Json[]; + let role: string; + if (message.role === "tool") { + role = "user"; + content = [ + { + type: "tool_result", + tool_use_id: toolData(message.tool_call_id, "anthropic-native").id, + content: Array.isArray(message.content) ? anthropicParts(message.content) : (message.content ?? ""), + }, + ]; + } else { + if (!["user", "assistant"].includes(message.role)) throw new Error(`Anthropic 不支持消息角色 ${message.role}`); + role = message.role; + content = anthropicParts(message.content); + if (message.tool_calls?.length) { + const meta = toolData(message.tool_calls[0].id, "anthropic-native"); + if (meta.parts.length) content = meta.parts; + else + content.push( + ...message.tool_calls.map((call: Json) => ({ + type: "tool_use", + id: toolData(call.id, "anthropic-native").id, + name: call.function.name, + input: safeToolArguments(call.function.arguments), + })), + ); + } + } + // Adjacent user tool results form a single native user turn. + if (messages.at(-1)?.role === role) messages.at(-1)!.content.push(...content); + else messages.push({ role, content }); + } + const result: Json = { model: body.model, messages, max_tokens: body.max_completion_tokens ?? body.max_tokens ?? 4096, stream: !!body.stream }; + if (system.length) result.system = system; + for (const key of ["temperature", "top_p", "top_k", "thinking", "output_config", "metadata", "cache_control", "service_tier"]) + if (body[key] !== undefined) result[key] = body[key]; + if (body.stop) result.stop_sequences = Array.isArray(body.stop) ? body.stop : [body.stop]; + if (body.tools?.length) + result.tools = body.tools.map((tool: Json) => { + if (tool.type !== "function" || !tool.function?.name) throw new Error("Anthropic 原生接入仅支持函数工具"); + return { + name: tool.function.name, + description: tool.function.description, + input_schema: tool.function.parameters, + ...(tool.function.strict !== undefined ? { strict: tool.function.strict } : {}), + }; + }); + if (body.tool_choice !== undefined) { + const choice = body.tool_choice; + const type = choice === "required" ? "any" : choice === "auto" ? "auto" : choice === "none" ? "none" : choice?.type === "function" ? "tool" : null; + if (!type) throw new Error("Anthropic 不支持此 tool_choice"); + result.tool_choice = { type, ...(type === "tool" ? { name: choice.function.name } : {}) }; + } + return result; +} +export function anthropicUsage(value: Json = {}): Json { + const input = + value.input_tokens !== undefined ? value.input_tokens + (value.cache_read_input_tokens ?? 0) + (value.cache_creation_input_tokens ?? 0) : undefined; + return { + prompt_tokens: input, + completion_tokens: value.output_tokens, + total_tokens: input !== undefined && value.output_tokens !== undefined ? input + value.output_tokens : undefined, + prompt_tokens_details: { cached_tokens: value.cache_read_input_tokens, cache_write_tokens: value.cache_creation_input_tokens }, + }; +} +function finishReason(reason: string, toolBearing = false): string { + if (toolBearing && reason !== "tool_use") throw new Error(`Anthropic 工具调用未正常完成,禁止执行: ${reason ?? "缺少结束原因"}`); + if (!["end_turn", "stop_sequence", "tool_use", "max_tokens", "refusal", "model_context_window_exceeded"].includes(reason)) + throw new Error(`Anthropic 原生回复异常结束: ${reason}`); + if (reason === "model_context_window_exceeded") return "length"; + return reason === "tool_use" ? "tool_calls" : reason === "max_tokens" ? "length" : reason === "refusal" ? "content_filter" : "stop"; +} +function toolCalls(parts: Json[]): Json[] { + for (const part of parts) + if (!part || !["text", "tool_use", "thinking", "redacted_thinking"].includes(part.type)) throw new Error("Anthropic 原生回复包含不支持的内容类型"); + return parts + .filter((part) => part.type === "tool_use") + .map((part) => ({ + id: toolId("anthropic-native", part.id, parts), + type: "function", + function: { name: part.name, arguments: JSON.stringify(part.input ?? {}) }, + })); +} +export function anthropicResponse(value: Json): Json { + if (!Array.isArray(value.content)) throw new Error("Anthropic 未返回有效回复内容"); + const calls = toolCalls(value.content); + return completed( + { + content: value.content + .filter((part: Json) => part.type === "text") + .map((part: Json) => part.text) + .join(""), + ...(calls.length ? { tool_calls: calls } : {}), + }, + finishReason(value.stop_reason, calls.length > 0), + anthropicUsage(value.usage), + value.id, + ); +} +export function anthropicStream() { + const blocks: Json[] = []; + const argumentsText = new Map(); + let usage: Json = {}; + let reason = ""; + let finished = false; + return { + consume(value: Json): Json[] { + if (value.type === "message_start") { + usage = { ...usage, ...value.message?.usage }; + return []; + } + if (value.type === "content_block_start") { + blocks[value.index] = { ...value.content_block }; + if (value.content_block.type === "tool_use") { + argumentsText.set(value.index, ""); + return [choice({ yib_native_activity: true })]; + } + return value.content_block.type === "text" && value.content_block.text ? [choice({ content: value.content_block.text })] : []; + } + if (value.type === "content_block_delta") { + const block = blocks[value.index]; + if (!block) throw new Error("Anthropic 流内容块缺少起始事件"); + const delta = value.delta; + if (delta.type === "text_delta") { + block.text = (block.text ?? "") + delta.text; + return [choice({ content: delta.text })]; + } + if (delta.type === "input_json_delta") argumentsText.set(value.index, (argumentsText.get(value.index) ?? "") + delta.partial_json); + else if (delta.type === "thinking_delta") block.thinking = (block.thinking ?? "") + delta.thinking; + else if (delta.type === "signature_delta") block.signature = (block.signature ?? "") + delta.signature; + else if (delta.type !== "citations_delta") throw new Error(`Anthropic 原生流不支持增量类型 ${delta.type}`); + return []; + } + if (value.type === "content_block_stop") { + const block = blocks[value.index]; + if (block?.type === "tool_use") { + const text = argumentsText.get(value.index); + if (text) block.input = safeToolArguments(text); + } + } + if (value.type === "message_delta") { + usage = { ...usage, ...value.usage }; + reason = value.delta?.stop_reason ?? reason; + } + if (value.type === "message_stop") finished = true; + return []; + }, + finish(): Json[] { + if (!finished || !reason) throw new Error("Anthropic 流已截断,未收到完整结束事件"); + const calls = toolCalls(blocks); + return [ + ...calls.map((call, index) => choice({ tool_calls: [{ index, ...call }] })), + { ...choice({}, finishReason(reason, calls.length > 0)), usage: anthropicUsage(usage) }, + ]; + }, + }; +} diff --git a/packages/core/src/model/native/gemini.ts b/packages/core/src/model/native/gemini.ts new file mode 100644 index 000000000..4e9a8f931 --- /dev/null +++ b/packages/core/src/model/native/gemini.ts @@ -0,0 +1,219 @@ +import { choice, completed, inlineImage, Json, partsOf, rejectUnknown, safeToolArguments, toolData, toolId } from "./shared"; + +function geminiParts(content: unknown): Json[] { + return partsOf(content).map((part) => { + if (part.type === "text") return { text: part.text }; + if (part.type === "image_url") { + const url = part.image_url?.url; + const inline = typeof url === "string" ? inlineImage(url) : undefined; + if (inline) return { inlineData: inline }; + // Remote HTTP images require explicit upload/file API handling, not an implicit server-side fetch. + throw new Error("Gemini 原生图片目前需要 base64 data URL"); + } + throw new Error(`Gemini 原生接入不支持消息内容 ${part.type}`); + }); +} +function geminiToolResult(content: unknown): string { + if (content == null) return ""; + if (typeof content === "string") return content; + if (!Array.isArray(content) || content.some((part) => part?.type !== "text" || typeof part.text !== "string")) + throw new Error("Gemini 原生工具结果目前仅支持文本,不支持图片或音频"); + return content.map((part) => part.text).join(""); +} +export function geminiRequest(body: Json): Json { + rejectUnknown(body, [ + "model", + "messages", + "stream", + "stream_options", + "temperature", + "top_p", + "top_k", + "max_tokens", + "max_completion_tokens", + "stop", + "tools", + "tool_choice", + "response_format", + "seed", + "n", + "generation_config", + "safety_settings", + "cached_content", + "tool_config", + ]); + if (body.n !== undefined && body.n !== 1) throw new Error("Gemini 原生接入仅支持 n=1"); + const system: Json[] = []; + const contents: Json[] = []; + const calls = new Map(); + for (const message of body.messages ?? []) { + if (message.role === "system" || message.role === "developer") { + system.push(...geminiParts(message.content)); + continue; + } + if (message.role === "tool") { + const call = calls.get(message.tool_call_id); + if (!call) throw new Error("Gemini 工具结果缺少对应调用"); + const metadata = toolData(message.tool_call_id, "gemini-native"); + const functionResponse = { + name: call.function.name, + ...(metadata.id ? { id: metadata.id } : {}), + response: { result: geminiToolResult(message.content) }, + }; + const last = contents.at(-1); + if (last?.role === "user") last.parts.push({ functionResponse }); + else contents.push({ role: "user", parts: [{ functionResponse }] }); + continue; + } + if (!["user", "assistant"].includes(message.role)) throw new Error(`Gemini 不支持消息角色 ${message.role}`); + let parts = geminiParts(message.content); + if (message.tool_calls?.length) { + const meta = toolData(message.tool_calls[0].id, "gemini-native"); + if (meta.parts.length) parts = meta.parts; + else + for (const call of message.tool_calls) { + const nativeId = toolData(call.id, "gemini-native").id; + parts.push({ + functionCall: { name: call.function.name, args: safeToolArguments(call.function.arguments), ...(nativeId ? { id: nativeId } : {}) }, + }); + } + for (const call of message.tool_calls) calls.set(call.id, call); + } + contents.push({ role: message.role === "assistant" ? "model" : "user", parts }); + } + const generationConfig: Json = { ...body.generation_config }; + const fields = { temperature: "temperature", top_p: "topP", top_k: "topK", seed: "seed" }; + for (const [key, target] of Object.entries(fields)) if (body[key] !== undefined) generationConfig[target] = body[key]; + if (body.max_completion_tokens !== undefined || body.max_tokens !== undefined) + generationConfig.maxOutputTokens = body.max_completion_tokens ?? body.max_tokens; + if (body.stop) generationConfig.stopSequences = Array.isArray(body.stop) ? body.stop : [body.stop]; + if (body.response_format?.type === "json_object") generationConfig.responseMimeType = "application/json"; + else if (body.response_format?.type === "json_schema") { + generationConfig.responseMimeType = "application/json"; + generationConfig.responseJsonSchema = body.response_format.json_schema?.schema; + } else if (body.response_format && body.response_format.type !== "text") throw new Error("Gemini 不支持此 response_format"); + const request: Json = { contents, ...(system.length ? { systemInstruction: { parts: system } } : {}), generationConfig }; + if (body.tools?.length) + request.tools = [ + { + functionDeclarations: body.tools.map((tool: Json) => { + if (tool.type !== "function" || !tool.function?.name) throw new Error("Gemini 原生接入仅支持函数工具"); + if (tool.function.strict) throw new Error("Gemini 原生函数工具不支持 strict;请使用参数校验或兼容协议"); + return { name: tool.function.name, description: tool.function.description, parametersJsonSchema: tool.function.parameters }; + }), + }, + ]; + if (body.tool_choice !== undefined) { + const choice = body.tool_choice; + const mode = choice === "none" ? "NONE" : choice === "required" ? "ANY" : choice === "auto" ? "AUTO" : choice?.type === "function" ? "ANY" : null; + if (!mode) throw new Error("Gemini 不支持此 tool_choice"); + request.toolConfig = { functionCallingConfig: { mode, ...(choice?.function?.name ? { allowedFunctionNames: [choice.function.name] } : {}) } }; + } + if (body.tool_config) request.toolConfig = body.tool_config; + if (body.safety_settings) request.safetySettings = body.safety_settings; + if (body.cached_content) request.cachedContent = body.cached_content; + return request; +} +export function geminiUsage(value: Json = {}): Json { + return { + prompt_tokens: value.promptTokenCount, + completion_tokens: + value.candidatesTokenCount !== undefined || value.thoughtsTokenCount !== undefined + ? (value.candidatesTokenCount ?? 0) + (value.thoughtsTokenCount ?? 0) + : undefined, + total_tokens: value.totalTokenCount, + prompt_tokens_details: { cached_tokens: value.cachedContentTokenCount }, + completion_tokens_details: { reasoning_tokens: value.thoughtsTokenCount }, + }; +} +function finishReason(reason: string | undefined, calls: boolean): string { + if (calls && reason !== "STOP") throw new Error(`Gemini 工具调用未正常完成,禁止执行: ${reason ?? "缺少结束原因"}`); + if (reason && !["STOP", "MAX_TOKENS", "SAFETY", "RECITATION", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII"].includes(reason)) + throw new Error(`Gemini 原生回复异常结束: ${reason}`); + if (calls) return "tool_calls"; + if (reason === "MAX_TOKENS") return "length"; + if (reason === "STOP") return "stop"; + if (["SAFETY", "RECITATION", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII"].includes(reason ?? "")) return "content_filter"; + return "stop"; +} +function toolCalls(parts: Json[]): Json[] { + return parts + .filter((part) => part.functionCall) + .map((part) => ({ + id: toolId("gemini-native", part.functionCall.id, parts), + type: "function", + function: { name: part.functionCall.name, arguments: JSON.stringify(part.functionCall.args ?? {}) }, + })); +} +function validateParts(parts: Json[]) { + for (const part of parts) + if (!part || (!Object.hasOwn(part, "text") && !part.functionCall && !part.thoughtSignature)) throw new Error("Gemini 原生回复包含不支持的内容类型"); +} +export function geminiResponse(value: Json): Json { + if (value.error) throw new Error(value.error.message ?? "Gemini 返回错误"); + const candidate = value.candidates?.[0]; + if (!candidate) throw new Error(`Gemini 未返回候选回复${value.promptFeedback?.blockReason ? `: ${value.promptFeedback.blockReason}` : ""}`); + const parts = candidate.content?.parts ?? []; + validateParts(parts); + const calls = toolCalls(parts); + return completed( + { + content: parts + .filter((part: Json) => part.text && !part.thought) + .map((part: Json) => part.text) + .join(""), + ...(calls.length ? { tool_calls: calls } : {}), + }, + finishReason(candidate.finishReason, calls.length > 0), + geminiUsage(value.usageMetadata), + value.responseId, + ); +} +export function geminiStream() { + let finished = false; + let usage: Json = {}; + const parts: Json[] = []; + let reason: string | undefined; + return { + consume(value: Json): Json[] { + const out: Json[] = []; + if (value.usageMetadata) usage = { ...usage, ...value.usageMetadata }; + const candidate = value.candidates?.[0]; + if (value.promptFeedback?.blockReason && !candidate) throw new Error(`Gemini 回复被阻止: ${value.promptFeedback.blockReason}`); + for (const part of candidate?.content?.parts ?? []) { + parts.push(part); + if (part.functionCall?.name) out.push(choice({ yib_native_activity: true })); + if (part.text && !part.thought) out.push(choice({ content: part.text })); + } + if (candidate?.finishReason) { + finished = true; + reason = candidate.finishReason; + } + return out; + }, + finish(): Json[] { + if (!finished) throw new Error("Gemini 流已截断,未收到结束原因"); + validateParts(parts); + const calls = toolCalls(parts); + return [ + ...calls.map((call, index) => choice({ tool_calls: [{ index, ...call }] })), + { ...choice({}, finishReason(reason, calls.length > 0)), usage: geminiUsage(usage) }, + ]; + }, + }; +} +export function geminiEmbeddings(body: Json): Json { + rejectUnknown(body, ["model", "input", "dimensions", "encoding_format", "task_type", "title"]); + if (body.encoding_format && body.encoding_format !== "float") throw new Error("Gemini 原生嵌入仅支持 float 格式"); + const inputs = Array.isArray(body.input) ? body.input : [body.input]; + if (!inputs.length || inputs.some((input) => typeof input !== "string")) throw new Error("Gemini 原生嵌入需要字符串或非空字符串数组"); + return { + requests: inputs.map((input) => ({ + model: `models/${String(body.model).replace(/^models\//, "")}`, + content: { parts: [{ text: input }] }, + ...(body.dimensions !== undefined ? { outputDimensionality: body.dimensions } : {}), + ...(body.task_type ? { taskType: body.task_type } : {}), + ...(body.title ? { title: body.title } : {}), + })), + }; +} diff --git a/packages/core/src/model/native/lmstudio.ts b/packages/core/src/model/native/lmstudio.ts new file mode 100644 index 000000000..0b4f81b5d --- /dev/null +++ b/packages/core/src/model/native/lmstudio.ts @@ -0,0 +1,151 @@ +import type { ProviderConfig } from "../config"; +import { choice, completed, inlineImage, Json, nativeSSE, partsOf, rejectUnknown } from "./shared"; + +function nativeRequest(body: Json): Json { + rejectUnknown(body, [ + "model", + "messages", + "stream", + "stream_options", + "temperature", + "top_p", + "top_k", + "min_p", + "repeat_penalty", + "max_tokens", + "max_completion_tokens", + "tools", + "tool_choice", + "n", + "reasoning", + ]); + if (body.tools?.length || (body.tool_choice !== undefined && body.tool_choice !== "none")) + throw new Error("LM Studio 原生对话不支持客户端自定义函数工具,请禁用原生工具调用以使用 JSON 动作"); + if (body.n !== undefined && body.n !== 1) throw new Error("LM Studio 原生对话仅支持 n=1"); + if (!Array.isArray(body.messages)) throw new Error("LM Studio 原生接入需要 messages 数组"); + const system: string[] = []; + const input: Json[] = []; + let userTurns = 0; + for (const message of body.messages) { + if (message.tool_calls?.length || !["user", "system", "developer"].includes(message.role)) + throw new Error("LM Studio 原生对话无法回放 assistant/tool 历史,请使用有状态会话或 OpenAI Compatible 类型"); + if (message.role !== "user") { + if (typeof message.content !== "string") throw new Error("LM Studio 原生系统提示必须为文本"); + system.push(message.content); + continue; + } + userTurns++; + for (const part of partsOf(message.content)) { + if (part.type === "text" && typeof part.text === "string") input.push({ type: "text", content: part.text }); + else if (part.type === "image_url" && typeof part.image_url?.url === "string" && inlineImage(part.image_url.url)) + input.push({ type: "image", data_url: part.image_url.url }); + else throw new Error("LM Studio 原生 HTTP 对话仅支持文本与 base64 图片 data URL,不支持远程图片地址或文件上传"); + } + } + if (userTurns !== 1 || !input.length) throw new Error("LM Studio 原生对话需要且仅支持一条当前 user 输入"); + const result: Json = { model: body.model, input, ...(system.length ? { system_prompt: system.join("\n\n") } : {}), stream: !!body.stream, store: false }; + for (const key of ["temperature", "top_p", "top_k", "min_p", "repeat_penalty", "reasoning"]) if (body[key] !== undefined) result[key] = body[key]; + if (body.max_tokens !== undefined || body.max_completion_tokens !== undefined) result.max_output_tokens = body.max_completion_tokens ?? body.max_tokens; + return result; +} +function resultOf(value: Json): Json { + if (!Array.isArray(value.output)) throw new Error("LM Studio 原生接口未返回有效 output"); + for (const item of value.output) + if (!item || !["message", "reasoning"].includes(item.type) || typeof item.content !== "string") + throw new Error("LM Studio 返回了未启用的服务端工具或无效输出"); + const input = value.stats?.input_tokens; + const output = value.stats?.total_output_tokens; + return completed( + { + content: value.output + .filter((item: Json) => item.type === "message") + .map((item: Json) => item.content) + .join(""), + }, + "stop", + { + prompt_tokens: input, + completion_tokens: output, + total_tokens: input !== undefined && output !== undefined ? input + output : undefined, + completion_tokens_details: { reasoning_tokens: value.stats?.reasoning_output_tokens }, + }, + value.response_id, + ); +} +/** Native v1 supports current-user inputs, not arbitrary stateless history or client function tools. + * No integrations are enabled. Images must be data URLs. Embeddings deliberately use the sole + * documented HTTP endpoint /v1/embeddings (OpenAI-compatible), not an invented native endpoint. */ +export function createLMStudioFetch(config: ProviderConfig, transport: typeof globalThis.fetch): typeof globalThis.fetch { + const base = new URL(config.baseURL || "http://localhost:1234/"); + if (!["http:", "https:"].includes(base.protocol) || base.username || base.password) throw new Error("LM Studio 原生 API 地址必须是不含凭据的 HTTP(S) URL"); + base.pathname = base.pathname.replace(/\/?$/, "/"); + return (async (input: RequestInfo | URL, init?: RequestInit) => { + const request = input instanceof Request ? input : undefined; + const url = new URL(request ? request.url : String(input)); + if (url.origin !== base.origin || !url.pathname.startsWith(base.pathname)) throw new Error("LM Studio 请求超出已配置的 API 根地址"); + const path = url.pathname.slice(base.pathname.length); + const headers = new Headers(init?.headers ?? request?.headers); + if (config.apiKey) headers.set("authorization", `Bearer ${config.apiKey}`); + const options = { ...init, headers, redirect: "error" as const, signal: init?.signal ?? request?.signal }; + if (path === "models" && (init?.method ?? request?.method ?? "GET") === "GET") { + const response = await transport(new URL("api/v1/models", base), { ...options, method: "GET" }); + if (!response.ok) return response; + const value = await response.json(); + if (!Array.isArray(value.models)) throw new Error("LM Studio 原生模型列表响应无效"); + return Response.json({ ...value, data: value.models.map((model: Json) => ({ ...model, id: model.key })) }); + } + if (!["embeddings", "chat/completions"].includes(path) || typeof init?.body !== "string") + throw new Error("LM Studio 原生接入不支持此 API 路径或请求体"); + const body: Json = JSON.parse(init.body); + if (typeof body.model !== "string" || !body.model) throw new Error("LM Studio 原生接入缺少模型 ID"); + headers.set("content-type", "application/json"); + if (path === "embeddings") return transport(new URL("v1/embeddings", base), { ...options, method: "POST", body: init.body }); + const payload = nativeRequest(body); + const response = await transport(new URL("api/v1/chat", base), { ...options, method: "POST", body: JSON.stringify(payload) }); + if (!response.ok) return response; + if (!body.stream) return Response.json(resultOf(await response.json())); + let end: Json | undefined; + let started = false; + return nativeSSE( + response, + (event) => { + if (end) throw new Error("LM Studio 原生流在 chat.end 后仍有数据"); + if (event.type === "chat.start") { + started = true; + return []; + } + if (event.type?.startsWith("tool_call.")) throw new Error("LM Studio 原生流返回了未启用的服务端工具事件"); + if (event.type === "chat.end") { + if (!event.result) throw new Error("LM Studio 原生流缺少结束 result"); + end = resultOf(event.result); + return []; + } + if (event.type === "message.delta") { + if (typeof event.content !== "string") throw new Error("LM Studio 原生流文本增量无效"); + return [choice({ content: event.content })]; + } + if ( + [ + "model_load.start", + "model_load.progress", + "model_load.end", + "prompt_processing.start", + "prompt_processing.progress", + "prompt_processing.end", + "reasoning.start", + "reasoning.delta", + "reasoning.end", + "message.start", + "message.end", + ].includes(event.type) + ) + return []; + throw new Error(`LM Studio 不支持此原生流事件 ${event.type}`); + }, + () => { + if (!started || !end) throw new Error("LM Studio 原生流已截断"); + return [{ ...choice({}, "stop"), usage: end.usage }]; + }, + ); + }) as typeof globalThis.fetch; +} diff --git a/packages/core/src/model/native/ollama.ts b/packages/core/src/model/native/ollama.ts new file mode 100644 index 000000000..7ba2a0ea2 --- /dev/null +++ b/packages/core/src/model/native/ollama.ts @@ -0,0 +1,299 @@ +import { randomUUID } from "node:crypto"; + +import type { ProviderConfig } from "../config"; +import { choice, completed, inlineImage, type Json, nativeSSE, partsOf, rejectUnknown, safeToolArguments } from "./shared"; + +function decodeToolId(id: string): { id?: string; thinking?: string } { + if (typeof id !== "string" || !id) throw new Error("Ollama 工具调用缺少 ID"); + if (!id.startsWith("yib-ollama:")) return { id }; + try { + const value = JSON.parse(Buffer.from(id.slice(11), "base64url").toString("utf8")); + if ((value.id !== undefined && typeof value.id !== "string") || (value.thinking !== undefined && typeof value.thinking !== "string")) throw new Error(); + return value; + } catch { + throw new Error("Ollama 工具调用元数据无效"); + } +} +function encodeToolId(nativeId: string | undefined, thinking: string | undefined): string { + return `yib-ollama:${Buffer.from(JSON.stringify({ id: nativeId, nonce: nativeId ? undefined : randomUUID(), thinking }), "utf8").toString("base64url")}`; +} +function text(content: unknown): string { + return partsOf(content) + .map((part) => { + if (part.type !== "text" || typeof part.text !== "string") throw new Error("Ollama 工具结果仅支持文本,不支持媒体"); + return part.text; + }) + .join(""); +} +function messages(input: Json[]): Json[] { + const names = new Map(); + return input.map((message) => { + if (message.role === "tool") { + const name = names.get(message.tool_call_id); + if (!name) throw new Error("Ollama 工具结果缺少对应调用"); + return { role: "tool", tool_name: name, content: text(message.content) }; + } + if (!["user", "assistant", "system", "developer"].includes(message.role)) throw new Error("Ollama 不支持此消息角色"); + const images: string[] = []; + const content = partsOf(message.content) + .map((part) => { + if (part.type === "text" && typeof part.text === "string") return part.text; + if (part.type === "image_url" && message.role === "user") { + const image = inlineImage(part.image_url?.url ?? ""); + if (!image) throw new Error("Ollama 原生图片需要 base64 data URL"); + images.push(image.data); + return ""; + } + throw new Error(`Ollama 原生接入不支持消息内容 ${part.type}`); + }) + .join(""); + let thinking = typeof message.thinking === "string" ? message.thinking : undefined; + const toolCalls = message.tool_calls?.map((call: Json) => { + if (call.type !== "function" || typeof call.id !== "string" || typeof call.function?.name !== "string") throw new Error("Ollama 工具调用格式无效"); + names.set(call.id, call.function.name); + const metadata = decodeToolId(call.id); + if (metadata.thinking !== undefined) thinking = metadata.thinking; + return { + ...(metadata.id !== undefined ? { id: metadata.id } : {}), + type: "function", + function: { name: call.function.name, arguments: safeToolArguments(call.function.arguments) }, + }; + }); + return { + role: message.role === "developer" ? "system" : message.role, + content, + ...(images.length ? { images } : {}), + ...(thinking !== undefined ? { thinking } : {}), + ...(toolCalls?.length ? { tool_calls: toolCalls } : {}), + }; + }); +} +function request(body: Json): Json { + rejectUnknown(body, [ + "model", + "messages", + "stream", + "stream_options", + "temperature", + "top_p", + "top_k", + "seed", + "max_tokens", + "max_completion_tokens", + "stop", + "tools", + "tool_choice", + "response_format", + "options", + "think", + "keep_alive", + "n", + ]); + if (body.n !== undefined && body.n !== 1) throw new Error("Ollama 原生接入仅支持 n=1"); + if ( + body.tool_choice !== undefined && + !["auto", "none", "required"].includes(body.tool_choice) && + !(body.tool_choice?.type === "function" && typeof body.tool_choice.function?.name === "string") + ) + throw new Error("Ollama 原生接口不支持此 tool_choice"); + const options: Json = { ...body.options }; + for (const key of ["temperature", "top_p", "top_k", "seed"]) if (body[key] !== undefined) options[key] = body[key]; + const stop = body.stop ?? options.stop; + if (stop !== undefined) { + if (typeof stop === "string") options.stop = [stop]; + else if (Array.isArray(stop) && stop.every((item) => typeof item === "string")) options.stop = stop; + else throw new Error("Ollama stop 必须为字符串或字符串数组"); + } + if (body.max_completion_tokens !== undefined || body.max_tokens !== undefined) options.num_predict = body.max_completion_tokens ?? body.max_tokens; + const result: Json = { model: body.model, messages: messages(body.messages ?? []), stream: !!body.stream, options }; + for (const key of ["think", "keep_alive"]) if (body[key] !== undefined) result[key] = body[key]; + if (body.tools?.length && body.tool_choice !== "none") + result.tools = body.tools.map((tool: Json) => { + if (tool.type !== "function" || !tool.function?.name || tool.function.strict) throw new Error("Ollama 原生接口仅支持非 strict 函数工具"); + return { + type: "function", + function: { name: tool.function.name, description: tool.function.description, parameters: tool.function.parameters ?? {} }, + }; + }); + if (body.response_format?.type === "json_object") result.format = "json"; + else if (body.response_format?.type === "json_schema") result.format = body.response_format.json_schema?.schema; + else if (body.response_format && body.response_format.type !== "text") throw new Error("Ollama 不支持此 response_format"); + return result; +} +function usage(value: Json): Json { + const input = value.prompt_eval_count, + output = value.eval_count; + return { + prompt_tokens: input, + completion_tokens: output, + ...(input !== undefined && output !== undefined ? { total_tokens: input + output } : {}), + ...(value.prompt_eval_cached_count !== undefined ? { prompt_tokens_details: { cached_tokens: value.prompt_eval_cached_count } } : {}), + }; +} +function tools(values: Json[], thinking?: string): Json[] { + return values.map((call) => { + if (typeof call.function?.name !== "string" || !call.function.name) throw new Error("Ollama 工具回复缺少名称"); + const args = call.function.arguments; + if (!args || typeof args !== "object" || Array.isArray(args)) throw new Error("Ollama 工具参数必须为对象"); + return { id: encodeToolId(call.id, thinking), type: "function", function: { name: call.function.name, arguments: JSON.stringify(args) } }; + }); +} +function validateChoice(selected: unknown, calls: Json[]) { + if (selected === "none" && calls.length) throw new Error("Ollama tool_choice none 不允许工具调用"); + if (selected === "required" && !calls.length) throw new Error("Ollama tool_choice required 未返回工具调用"); + if (selected && typeof selected === "object") { + const name = (selected as Json).function.name; + if (!calls.length || calls.some((call) => call.function.name !== name)) throw new Error("Ollama tool_choice 未返回指定的工具调用"); + } +} +function validateTerminal(value: Json, calls: Json[]): string { + if (value.done !== true) throw new Error("Ollama 回复已截断,缺少 done 结束标识"); + if (calls.length && value.done_reason !== "stop") throw new Error(`Ollama 工具回复未正常完成,禁止执行: ${value.done_reason}`); + if (value.done_reason && !["stop", "length"].includes(value.done_reason)) throw new Error(`Ollama 原生回复异常结束: ${value.done_reason}`); + return calls.length ? "tool_calls" : value.done_reason === "length" ? "length" : "stop"; +} +function json(value: unknown, response: Response): Response { + const headers = new Headers({ "content-type": "application/json" }); + for (const key of ["request-id", "x-request-id"]) if (response.headers.has(key)) headers.set(key, response.headers.get(key)!); + return new Response(JSON.stringify(value), { status: response.status, statusText: response.statusText, headers }); +} +function stream(response: Response, selected: unknown): Response { + if (!response.body) throw new Error("Ollama 返回空响应体"); + const decoder = new TextDecoder(), + encoder = new TextEncoder(); + let buffer = ""; + const encodeRecord = (line: string) => { + const value = JSON.parse(line); + if (typeof value.error === "string") value.error = { message: value.error }; + return encoder.encode(`data: ${JSON.stringify(value)}\n\n`); + }; + const source = response.body.pipeThrough( + new TransformStream({ + transform(chunk, controller) { + buffer += decoder.decode(chunk, { stream: true }); + const lines = buffer.split("\n"); + buffer = lines.pop()!; + for (const line of lines) if (line.trim()) controller.enqueue(encodeRecord(line)); + }, + flush(controller) { + buffer += decoder.decode(); + if (buffer.trim()) controller.enqueue(encodeRecord(buffer)); + }, + }), + ); + let terminal: Json | undefined; + let thinking = ""; + const calls = new Map(); + return nativeSSE( + new Response(source, { status: response.status, headers: response.headers }), + (value) => { + if (terminal) throw new Error("Ollama 结束标识之后仍有额外数据"); + const out: Json[] = []; + if (value.message?.content) out.push(choice({ content: value.message.content })); + if (value.message?.thinking) { + thinking += value.message.thinking; + out.push(choice({ reasoning_content: value.message.thinking })); + } + for (const call of value.message?.tool_calls ?? []) { + out.push(choice({ yib_native_activity: true })); + const index = call.function?.index ?? call.index ?? calls.size; + if (!Number.isSafeInteger(index) || index < 0) throw new Error("Ollama 工具调用索引无效"); + const previous = calls.get(index); + const incoming = call.function?.arguments; + if (incoming !== undefined && (!incoming || typeof incoming !== "object" || Array.isArray(incoming))) + throw new Error("Ollama 流工具参数必须为对象"); + const args = incoming === undefined ? previous?.function?.arguments : { ...previous?.function?.arguments, ...incoming }; + calls.set(index, { ...previous, ...call, function: { ...previous?.function, ...call.function, arguments: args } }); + } + if (value.done === true) terminal = value; + return out; + }, + () => { + const ordered = [...calls.entries()].sort(([a], [b]) => a - b); + if (ordered.some(([index], expected) => index !== expected)) throw new Error("Ollama 工具调用索引不完整"); + const toolCalls = tools( + ordered.map(([, call]) => call), + thinking, + ); + const reason = validateTerminal(terminal ?? {}, toolCalls); + validateChoice(selected, toolCalls); + return [...toolCalls.map((call, index) => choice({ tool_calls: [{ index, ...call }] })), { ...choice({}, reason), usage: usage(terminal!) }]; + }, + ); +} + +/** Native Ollama /api endpoints; the caller's existing fetch handles proxy and cancellation. */ +export function createOllamaFetch(config: ProviderConfig, transport: typeof globalThis.fetch): typeof globalThis.fetch { + const base = new URL(config.baseURL || "http://localhost:11434/"); + if (!["http:", "https:"].includes(base.protocol) || base.username || base.password) throw new Error("Ollama API 根地址无效"); + base.pathname = base.pathname.replace(/\/?$/, "/"); + return (async (input: RequestInfo | URL, init?: RequestInit) => { + const inputURL = new URL(typeof input === "string" || input instanceof URL ? input : input.url); + const path = inputURL.origin === base.origin && inputURL.pathname.startsWith(base.pathname) ? inputURL.pathname.slice(base.pathname.length) : ""; + const headers = new Headers(init?.headers); + headers.set("content-type", "application/json"); + if (config.apiKey) headers.set("authorization", `Bearer ${config.apiKey}`); + else headers.delete("authorization"); + const endpoint = new URL(base); + if ((init?.method ?? "GET") === "GET" && path === "models") { + endpoint.pathname += "api/tags"; + const response = await transport(endpoint, { ...init, headers, redirect: "error" }); + if (!response.ok) return response; + const value = await response.json(); + if (!Array.isArray(value.models)) throw new Error("Ollama 模型列表响应无效"); + return json({ data: value.models.map((model: Json) => ({ ...model, id: model.model ?? model.name })) }, response); + } + if (typeof init?.body !== "string") throw new Error("Ollama 原生接入需要 JSON 请求体"); + const body = JSON.parse(init.body); + if (typeof body.model !== "string" || !body.model) throw new Error("Ollama 原生接入缺少模型 ID"); + let payload: Json; + if (path === "chat/completions") { + endpoint.pathname += "api/chat"; + payload = request(body); + } else if (path === "embeddings") { + rejectUnknown(body, ["model", "input", "dimensions", "encoding_format", "truncate", "keep_alive", "options"]); + if (body.encoding_format && body.encoding_format !== "float") throw new Error("Ollama 嵌入仅支持 float 格式"); + const inputs = Array.isArray(body.input) ? body.input : [body.input]; + if (!inputs.length || inputs.some((item: unknown) => typeof item !== "string")) throw new Error("Ollama 嵌入需要文本输入"); + endpoint.pathname += "api/embed"; + payload = { + model: body.model, + input: body.input, + truncate: body.truncate ?? false, + ...(body.dimensions !== undefined ? { dimensions: body.dimensions } : {}), + ...(body.keep_alive !== undefined ? { keep_alive: body.keep_alive } : {}), + ...(body.options !== undefined ? { options: body.options } : {}), + }; + } else throw new Error("Ollama 原生接入不支持此 API 路径"); + const response = await transport(endpoint, { ...init, method: "POST", headers, redirect: "error", body: JSON.stringify(payload) }); + if (!response.ok) return response; + if (path === "chat/completions" && body.stream) return stream(response, body.tool_choice); + const value = await response.json(); + if (value.error) throw new Error(`Ollama 原生接口错误: ${value.error}`); + if (path === "embeddings") { + const count = Array.isArray(body.input) ? body.input.length : 1; + if ( + !Array.isArray(value.embeddings) || + value.embeddings.length !== count || + value.embeddings.some((v: unknown) => !Array.isArray(v) || !v.length || v.some((n) => typeof n !== "number" || !Number.isFinite(n))) + ) + throw new Error("Ollama 嵌入响应不完整"); + return json( + { + data: value.embeddings.map((embedding: number[], index: number) => ({ index, object: "embedding", embedding })), + ...(value.prompt_eval_count !== undefined + ? { usage: { prompt_tokens: value.prompt_eval_count, total_tokens: value.prompt_eval_count } } + : {}), + }, + response, + ); + } + const toolCalls = tools(value.message?.tool_calls ?? [], value.message?.thinking); + const reason = validateTerminal(value, toolCalls); + validateChoice(body.tool_choice, toolCalls); + return json( + completed({ content: value.message?.content ?? "", ...(toolCalls.length ? { tool_calls: toolCalls } : {}) }, reason, usage(value)), + response, + ); + }) as typeof globalThis.fetch; +} diff --git a/packages/core/src/model/native/qwen.ts b/packages/core/src/model/native/qwen.ts new file mode 100644 index 000000000..868b2f403 --- /dev/null +++ b/packages/core/src/model/native/qwen.ts @@ -0,0 +1,326 @@ +import type { ProviderConfig } from "../config"; +import { ModelAbility } from "../config"; +import { choice, completed, type Json, nativeSSE, partsOf, rejectUnknown, safeToolArguments } from "./shared"; + +function decodeToolId(id: string): { id: string; reasoning?: string } { + if (typeof id !== "string" || !id) throw new Error("Qwen 工具调用缺少 ID"); + if (!id.startsWith("yib-qwen:")) return { id }; + try { + const value = JSON.parse(Buffer.from(id.slice(9), "base64url").toString("utf8")); + if (typeof value.id !== "string" || !value.id || typeof value.reasoning !== "string") throw new Error(); + return value; + } catch { + throw new Error("Qwen 工具调用元数据无效"); + } +} +function encodeToolId(id: string, reasoning: string | undefined): string { + return reasoning ? `yib-qwen:${Buffer.from(JSON.stringify({ id, reasoning }), "utf8").toString("base64url")}` : id; +} +function text(content: unknown): string { + return partsOf(content) + .map((part) => { + if (part.type !== "text" || typeof part.text !== "string") throw new Error("Qwen 原生工具或文本模型不支持此图片/音频内容,请使用视觉模型"); + return part.text; + }) + .join(""); +} +function messages(input: Json[], visual: boolean): Json[] { + return input.map((message) => { + if (!["system", "developer", "user", "assistant", "tool"].includes(message.role)) throw new Error("Qwen 不支持此消息角色"); + const role = message.role === "developer" ? "system" : message.role; + let content: unknown; + if (!visual || role === "tool") content = text(message.content); + else + content = partsOf(message.content).map((part) => { + if (part.type === "text" && typeof part.text === "string") return { text: part.text }; + if ( + role === "user" && + part.type === "image_url" && + typeof part.image_url?.url === "string" && + /^(https?:\/\/|data:image\/)/.test(part.image_url.url) + ) + return { image: part.image_url.url }; + throw new Error(`Qwen 原生视觉接入不支持内容 ${part.type}`); + }); + const result: Json = { role, content }; + if (role === "tool") { + if (typeof message.tool_call_id !== "string" || !message.tool_call_id) throw new Error("Qwen 工具结果缺少调用 ID"); + result.tool_call_id = decodeToolId(message.tool_call_id).id; + } + if (message.tool_calls?.length) + result.tool_calls = message.tool_calls.map((call: Json) => { + if (!call.id || call.type !== "function" || !call.function?.name) throw new Error("Qwen 工具调用格式无效"); + safeToolArguments(call.function.arguments); + const metadata = decodeToolId(call.id); + if (metadata.reasoning !== undefined) result.reasoning_content = metadata.reasoning; + return { id: metadata.id, type: "function", function: { name: call.function.name, arguments: call.function.arguments } }; + }); + if (typeof message.reasoning_content === "string") result.reasoning_content = message.reasoning_content; + return result; + }); +} +function request(body: Json, visual: boolean): Json { + const parametersAllowed = [ + "temperature", + "top_p", + "top_k", + "seed", + "max_tokens", + "max_completion_tokens", + "stop", + "tools", + "tool_choice", + "response_format", + "enable_thinking", + "thinking_budget", + "reasoning_effort", + "enable_search", + "search_options", + "parallel_tool_calls", + "repetition_penalty", + "presence_penalty", + "frequency_penalty", + "tool_stream", + ]; + rejectUnknown(body, ["model", "messages", "stream", "stream_options", "max_completion_tokens", "n", "preserve_thinking", ...parametersAllowed]); + if (body.n !== undefined && body.n !== 1) throw new Error("Qwen 原生接入仅支持 n=1"); + const parameters: Json = { result_format: "message", incremental_output: true }; + if (body.preserve_thinking !== undefined) parameters.preserve_thinking = body.preserve_thinking; + for (const key of parametersAllowed) if (body[key] !== undefined) parameters[key] = body[key]; + const selected = body.tool_choice; + if ( + selected !== undefined && + !["auto", "none", "required"].includes(selected) && + !(selected?.type === "function" && typeof selected.function?.name === "string" && selected.function.name) + ) + throw new Error("Qwen 不支持此 tool_choice"); + if (selected !== undefined) parameters.tool_choice = selected === "none" ? "none" : "auto"; + if (selected === "none") delete parameters.tools; + if (body.tools?.length && selected !== "none") + parameters.tools = body.tools.map((tool: Json) => { + if (tool.type !== "function" || !tool.function?.name || tool.function.strict) throw new Error("Qwen 原生接入仅支持非 strict 函数工具"); + return { + type: "function", + function: { name: tool.function.name, description: tool.function.description ?? "", parameters: tool.function.parameters ?? {} }, + }; + }); + if (selected?.type === "function") { + parameters.tools = parameters.tools?.filter((tool: Json) => tool.function.name === selected.function.name); + if (!parameters.tools?.length) throw new Error("Qwen tool_choice 指定的工具未定义"); + } + return { model: body.model, input: { messages: messages(body.messages ?? [], visual) }, parameters }; +} +function checkError(value: Json) { + if (value.code || (value.status_code !== undefined && Number(value.status_code) !== 200)) + throw new Error(`Qwen 原生接口错误 ${value.code ?? value.status_code}: ${value.message ?? "未知错误"}`); +} +function numeric(...values: unknown[]): number | undefined { + return values.find((value) => typeof value === "number" && Number.isFinite(value) && value >= 0) as number | undefined; +} +function usage(value: Json = {}): Json { + const cached = numeric(value.prompt_tokens_details?.cached_tokens, value.cached_tokens); + const written = numeric(value.prompt_tokens_details?.cache_creation_input_tokens, value.cache_creation_input_tokens); + const reasoning = numeric(value.output_tokens_details?.reasoning_tokens); + return { + prompt_tokens: numeric(value.input_tokens), + completion_tokens: numeric(value.output_tokens), + total_tokens: numeric(value.total_tokens), + ...(cached !== undefined || written !== undefined + ? { + prompt_tokens_details: { + ...(cached !== undefined ? { cached_tokens: cached } : {}), + ...(written !== undefined ? { cache_write_tokens: written } : {}), + }, + } + : {}), + ...(reasoning !== undefined ? { completion_tokens_details: { reasoning_tokens: reasoning } } : {}), + }; +} +function validateChoice(selected: unknown, calls: Json[]) { + if (selected === "none" && calls.length) throw new Error("Qwen tool_choice none 不允许工具调用"); + if (selected === "required" && !calls.length) throw new Error("Qwen tool_choice required 未返回工具调用"); + if (selected && typeof selected === "object") { + const name = (selected as Json).function.name; + if (!calls.length || calls.some((call) => call.function.name !== name)) throw new Error("Qwen tool_choice 未返回指定的工具调用"); + } +} +function toolCalls(values: Json[], reasoning?: string): Json[] { + return values.map((call) => { + if ( + typeof call.id !== "string" || + !call.id || + typeof call.function?.name !== "string" || + !call.function.name || + typeof call.function.arguments !== "string" + ) + throw new Error("Qwen 工具回复缺少完整 ID、名称或参数"); + safeToolArguments(call.function.arguments); + return { id: encodeToolId(call.id, reasoning), type: "function", function: { name: call.function.name, arguments: call.function.arguments } }; + }); +} +function finishReason(reason: unknown, calls: Json[]): string { + if (calls.length && reason !== "tool_calls") throw new Error(`Qwen 工具回复未正常完成,禁止执行: ${String(reason)}`); + if (!["stop", "length", "tool_calls", "content_filter"].includes(String(reason))) throw new Error(`Qwen 原生回复缺少正常结束原因: ${String(reason)}`); + if (reason === "tool_calls" && !calls.length) throw new Error("Qwen 工具回复未包含完整工具调用"); + return String(reason); +} +function content(value: unknown): string { + if (typeof value === "string") return value; + if (value == null) return ""; + if (!Array.isArray(value) || value.some((part) => typeof part?.text !== "string")) throw new Error("Qwen 原生回复包含不支持的非文本内容"); + return value.map((part) => part.text).join(""); +} +function json(value: unknown, response: Response): Response { + const headers = new Headers({ "content-type": "application/json" }); + for (const key of ["request-id", "x-request-id"]) if (response.headers.has(key)) headers.set(key, response.headers.get(key)!); + return new Response(JSON.stringify(value), { status: response.status, statusText: response.statusText, headers }); +} +function stream(response: Response, selected: unknown): Response { + let reason: unknown; + let lastUsage: Json = {}; + let reasoning = ""; + const calls = new Map(); + return nativeSSE( + response, + (value) => { + checkError(value); + if (value.usage) + lastUsage = { + ...lastUsage, + ...value.usage, + prompt_tokens_details: { ...lastUsage.prompt_tokens_details, ...value.usage.prompt_tokens_details }, + output_tokens_details: { ...lastUsage.output_tokens_details, ...value.usage.output_tokens_details }, + }; + const candidate = value.output?.choices?.[0]; + if (!candidate) return []; + const message = candidate.message ?? {}; + const text = content(message.content); + if (reason !== undefined && (text || message.tool_calls?.length)) throw new Error("Qwen 结束标识之后仍有额外数据"); + const out: Json[] = []; + if (text) out.push(choice({ content: text })); + if (message.reasoning_content) { + reasoning += message.reasoning_content; + out.push(choice({ reasoning_content: message.reasoning_content })); + } + for (const call of message.tool_calls ?? []) { + out.push(choice({ yib_native_activity: true })); + const index = call.index ?? 0; + if (!Number.isSafeInteger(index) || index < 0) throw new Error("Qwen 工具调用索引无效"); + const previous = calls.get(index); + if (previous?.id && call.id && previous.id !== call.id) throw new Error("Qwen 工具调用 ID 在流中变化"); + const name = call.function?.name ?? ""; + const args = call.function?.arguments ?? ""; + if (typeof name !== "string" || typeof args !== "string") throw new Error("Qwen 流工具参数增量无效"); + if (previous?.function.name && name && previous.function.name !== name) throw new Error("Qwen 工具调用名称在流中变化"); + calls.set(index, { + id: call.id || previous?.id, + type: "function", + function: { + name: name || previous?.function.name || "", + arguments: (previous?.function.arguments ?? "") + args, + }, + }); + } + if (candidate.finish_reason !== null && candidate.finish_reason !== undefined && candidate.finish_reason !== "null") + reason = candidate.finish_reason; + return out; + }, + () => { + const indexed = [...calls.entries()].sort(([a], [b]) => a - b); + if (indexed.some(([index], expected) => index !== expected)) throw new Error("Qwen 工具调用索引不完整"); + const ordered = indexed.map(([, call]) => call); + const normalized = toolCalls(ordered, reasoning); + const terminal = finishReason(reason, normalized); + validateChoice(selected, normalized); + return [...normalized.map((call, index) => choice({ tool_calls: [{ index, ...call }] })), { ...choice({}, terminal), usage: usage(lastUsage) }]; + }, + ); +} + +/** DashScope native generation/embedding routes, selected from declared model capabilities. */ +export function createQwenFetch(config: ProviderConfig, transport: typeof globalThis.fetch): typeof globalThis.fetch { + const base = new URL(config.baseURL || "https://dashscope.aliyuncs.com/api/v1/"); + if (!["http:", "https:"].includes(base.protocol) || base.username || base.password) throw new Error("Qwen API 根地址无效"); + base.pathname = base.pathname.replace(/\/?$/, "/"); + return (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(typeof input === "string" || input instanceof URL ? input : input.url); + const path = url.origin === base.origin && url.pathname.startsWith(base.pathname) ? url.pathname.slice(base.pathname.length) : ""; + const headers = new Headers(init?.headers); + headers.set("authorization", `Bearer ${config.apiKey}`); + headers.set("content-type", "application/json"); + headers.delete("X-DashScope-SSE"); + if ((init?.method ?? "GET") === "GET" && path === "models") return transport(input, { ...init, headers, redirect: "error" }); + if (typeof init?.body !== "string") throw new Error("Qwen 原生接入需要 JSON 请求体"); + const body = JSON.parse(init.body); + if (typeof body.model !== "string" || !body.model) throw new Error("Qwen 原生接入缺少模型 ID"); + const endpoint = new URL(base); + let payload: Json; + if (path === "chat/completions") { + const visual = config.models?.find((model) => model.modelId === body.model)?.abilities.includes(ModelAbility.Vision) ?? false; + endpoint.pathname += `services/aigc/${visual ? "multimodal-generation" : "text-generation"}/generation`; + payload = request(body, visual); + if (body.stream) headers.set("X-DashScope-SSE", "enable"); + } else if (path === "embeddings") { + rejectUnknown(body, ["model", "input", "dimensions", "encoding_format", "text_type", "instruct"]); + if (body.encoding_format && body.encoding_format !== "float") throw new Error("Qwen 嵌入仅支持 float 格式"); + const inputs = Array.isArray(body.input) ? body.input : [body.input]; + if (!inputs.length || inputs.some((item: unknown) => typeof item !== "string")) throw new Error("Qwen 嵌入需要文本输入"); + endpoint.pathname += "services/embeddings/text-embedding/text-embedding"; + payload = { + model: body.model, + input: { texts: inputs }, + parameters: { + ...(body.dimensions !== undefined ? { dimension: body.dimensions } : {}), + ...(body.text_type !== undefined ? { text_type: body.text_type } : {}), + ...(body.instruct !== undefined ? { instruct: body.instruct } : {}), + }, + }; + } else throw new Error("Qwen 原生接入不支持此 API 路径"); + const response = await transport(endpoint, { ...init, method: "POST", headers, redirect: "error", body: JSON.stringify(payload) }); + if (!response.ok) return response; + if (path === "chat/completions" && body.stream) return stream(response, body.tool_choice); + const value = await response.json(); + checkError(value); + if (path === "embeddings") { + const vectors = value.output?.embeddings; + if (!Array.isArray(vectors) || vectors.length !== payload.input.texts.length) throw new Error("Qwen 嵌入响应不完整"); + const ordered = [...vectors].sort((a, b) => a.text_index - b.text_index); + if ( + ordered.some( + (item, index) => + item.text_index !== index || + !Array.isArray(item.embedding) || + !item.embedding.length || + item.embedding.some((n: unknown) => typeof n !== "number" || !Number.isFinite(n)), + ) + ) + throw new Error("Qwen 嵌入向量或索引无效"); + return json( + { + data: ordered.map((item) => ({ index: item.text_index, object: "embedding", embedding: item.embedding })), + ...(value.usage?.total_tokens !== undefined + ? { usage: { prompt_tokens: value.usage.total_tokens, total_tokens: value.usage.total_tokens } } + : {}), + }, + response, + ); + } + const candidate = value.output?.choices?.[0]; + if (!candidate?.message) throw new Error("Qwen 未返回有效回复"); + const calls = toolCalls(candidate.message.tool_calls ?? [], candidate.message.reasoning_content); + validateChoice(body.tool_choice, calls); + return json( + completed( + { + content: content(candidate.message.content), + ...(candidate.message.reasoning_content ? { reasoning_content: candidate.message.reasoning_content } : {}), + ...(calls.length ? { tool_calls: calls } : {}), + }, + finishReason(candidate.finish_reason, calls), + usage(value.usage), + value.request_id, + ), + response, + ); + }) as typeof globalThis.fetch; +} diff --git a/packages/core/src/model/native/shared.ts b/packages/core/src/model/native/shared.ts new file mode 100644 index 000000000..8e7929afd --- /dev/null +++ b/packages/core/src/model/native/shared.ts @@ -0,0 +1,116 @@ +import { randomUUID } from "node:crypto"; + +export type Json = Record; +export type NativeProtocol = "gemini-native" | "anthropic-native"; + +/** Opaque native parts travel with the tool ID through xsai's message history. */ +export function toolId(protocol: NativeProtocol, nativeId: string | undefined, parts: Json[]): string { + if (protocol === "anthropic-native" && !nativeId) throw new Error("Anthropic 原生工具调用缺少 ID"); + // The nonce identifies an ID-less call locally; it must never become a native function ID. + return `yib-native:${Buffer.from(JSON.stringify({ protocol, id: nativeId, nonce: nativeId === undefined ? randomUUID() : undefined, parts }), "utf8").toString("base64url")}`; +} +export function toolData(id: string, protocol: NativeProtocol): { id?: string; parts: Json[] } { + if (!id?.startsWith("yib-native:")) return { id, parts: [] }; + try { + const value = JSON.parse(Buffer.from(id.slice(11), "base64url").toString("utf8")); + if (value.protocol !== protocol || !Array.isArray(value.parts)) throw new Error(); + if (typeof value.id !== "string" && !(protocol === "gemini-native" && value.id === undefined && typeof value.nonce === "string")) throw new Error(); + return value; + } catch { + throw new Error("原生工具调用标识无效或接入协议不匹配"); + } +} +export function rejectUnknown(body: Json, allowed: string[]) { + for (const key of Object.keys(body)) { + if (body[key] !== undefined && !allowed.includes(key)) throw new Error(`原生接入不支持参数 ${key},请使用支持的原生参数或兼容协议`); + } +} +export function partsOf(content: unknown): Json[] { + if (typeof content === "string") return content ? [{ type: "text", text: content }] : []; + if (content == null) return []; + if (Array.isArray(content)) return content; + throw new Error("原生接入不支持此消息内容格式"); +} +export function inlineImage(url: string): { mimeType: string; data: string } | undefined { + const match = /^data:(image\/[\w.+-]+);base64,([A-Za-z0-9+/=]+)$/.exec(url); + if (match) return { mimeType: match[1], data: match[2] }; +} +export const choice = (delta: Json, finish: string | null = null) => ({ choices: [{ index: 0, delta, finish_reason: finish }] }); +export function completed(message: Json, finish: string, usage: Json, id?: string): Json { + return { + id: id ?? randomUUID(), + object: "chat.completion", + choices: [{ index: 0, message: { role: "assistant", ...message }, finish_reason: finish }], + usage, + }; +} +export function safeToolArguments(value: string): Json { + const parsed = JSON.parse(value || "{}"); + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("原生工具参数必须为 JSON 对象"); + return parsed; +} +/** One-event SSE parser. Output remains pull-driven and cancellation reaches the source. */ +export function nativeSSE(response: Response, consume: (data: Json) => Json[], finish: () => Json[]): Response { + if (!response.body) throw new Error("原生接口返回了空响应体"); + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + const encoder = new TextEncoder(); + let buffer = ""; + let ended = false; + const queue: Uint8Array[] = []; + const enqueue = (chunks: Json[]) => { + for (const item of chunks) queue.push(encoder.encode(`data: ${JSON.stringify(item)}\n\n`)); + }; + const event = (block: string) => { + const data = block + .split(/\r?\n/) + .filter((line) => line.startsWith("data:")) + .map((line) => line.slice(5).replace(/^ /, "")) + .join("\n"); + if (!data || data === "[DONE]") return; + const parsed = JSON.parse(data); + if (parsed.error || parsed.type === "error") throw new Error(`原生接口流错误: ${parsed.error?.message ?? parsed.message ?? "未知错误"}`); + enqueue(consume(parsed)); + }; + return new Response( + new ReadableStream({ + async pull(controller) { + try { + while (!queue.length && !ended) { + const next = await reader.read(); + buffer += decoder.decode(next.value, { stream: !next.done }); + let match: RegExpExecArray | null; + while ((match = /\r?\n\r?\n/.exec(buffer))) { + const block = buffer.slice(0, match.index); + buffer = buffer.slice(match.index + match[0].length); + event(block); + } + if (next.done) { + ended = true; + if (buffer.trim()) event(buffer); + enqueue(finish()); + queue.push(encoder.encode("data: [DONE]\n\n")); + } + } + if (queue.length) controller.enqueue(queue.shift()!); + else controller.close(); + } catch (error) { + ended = true; + await reader.cancel(error).catch(() => {}); + controller.error(error); + } + }, + async cancel(reason) { + ended = true; + await reader.cancel(reason); + }, + }), + { + status: response.status, + headers: { + "content-type": "text/event-stream", + ...(response.headers.get("request-id") ? { "request-id": response.headers.get("request-id")! } : {}), + }, + }, + ); +} diff --git a/packages/core/src/model/native/workers.ts b/packages/core/src/model/native/workers.ts new file mode 100644 index 000000000..2851faa47 --- /dev/null +++ b/packages/core/src/model/native/workers.ts @@ -0,0 +1,219 @@ +import { randomUUID } from "node:crypto"; + +import type { ProviderConfig } from "../config"; +import { choice, completed, Json, nativeSSE, rejectUnknown, safeToolArguments } from "./shared"; + +const convertTerminal = (line: string) => (/^data:\s*\[DONE\]\s*$/.test(line.trim()) ? 'data: {"yib_workers_done":true}' : line); + +function unwrap(value: Json): Json { + if (value.error) throw new Error(`Workers AI 原生接口错误: ${value.error.message ?? "未知错误"}`); + if (value.success === false || value.errors?.length) throw new Error(`Workers AI: ${value.errors?.map((e: Json) => e.message).join("; ") || "请求失败"}`); + return value.result ?? value; +} +function callsOf(value: unknown): Json[] { + if (value === undefined) return []; + if (!Array.isArray(value)) throw new Error("Workers AI 返回的 tool_calls 格式无效"); + return value.map((call) => { + if (!call || typeof call.name !== "string" || !call.name) throw new Error("Workers AI 原生工具名称无效"); + const args = typeof call.arguments === "string" ? safeToolArguments(call.arguments) : call.arguments; + if (!args || typeof args !== "object" || Array.isArray(args)) throw new Error("Workers AI 原生工具参数无效"); + return { + id: typeof call.id === "string" && call.id ? call.id : randomUUID(), + type: "function", + function: { name: call.name, arguments: JSON.stringify(args) }, + }; + }); +} +function chatBody(body: Json): Json { + rejectUnknown(body, [ + "model", + "messages", + "stream", + "stream_options", + "temperature", + "top_p", + "top_k", + "max_tokens", + "max_completion_tokens", + "repetition_penalty", + "frequency_penalty", + "presence_penalty", + "seed", + "tools", + "tool_choice", + "n", + ]); + if (body.n !== undefined && body.n !== 1) throw new Error("Workers AI 原生接入仅支持 n=1"); + const selected = body.tool_choice; + if ( + selected !== undefined && + !["auto", "none", "required"].includes(selected) && + !(selected?.type === "function" && typeof selected.function?.name === "string" && selected.function.name) + ) + throw new Error("Workers AI 原生接入不支持此 tool_choice"); + if ((selected === "required" || selected?.type === "function") && !body.tools?.length) throw new Error("Workers AI tool_choice 需要提供函数工具"); + if (selected?.type === "function" && !body.tools?.some((tool: Json) => tool.function?.name === selected.function.name)) + throw new Error("Workers AI tool_choice 指定了未声明的工具"); + if (!Array.isArray(body.messages)) throw new Error("Workers AI 原生接入需要 messages 数组"); + const messages = body.messages.map((message: Json) => { + if (!["system", "user", "assistant", "tool"].includes(message.role) || (message.content != null && typeof message.content !== "string")) + throw new Error("Workers AI 原生对话适配器仅支持文本消息"); + if (message.tool_calls?.length || message.role === "tool") + throw new Error("Workers AI 原生适配器不支持工具调用历史回放,请禁用原生工具调用以使用 JSON 动作"); + return { role: message.role, content: message.content ?? "" }; + }); + const result: Json = { messages, stream: !!body.stream }; + for (const key of ["temperature", "top_p", "top_k", "repetition_penalty", "frequency_penalty", "presence_penalty", "seed"]) + if (body[key] !== undefined) result[key] = body[key]; + if (body.max_completion_tokens !== undefined || body.max_tokens !== undefined) result.max_tokens = body.max_completion_tokens ?? body.max_tokens; + if (body.tools?.length && selected !== "none") + result.tools = body.tools.map((tool: Json) => { + if (tool.type !== "function" || typeof tool.function?.name !== "string" || tool.function.strict) + throw new Error("Workers AI 原生接入仅支持非 strict 的函数工具"); + return { + name: tool.function.name, + ...(tool.function.description !== undefined ? { description: tool.function.description } : {}), + parameters: tool.function.parameters ?? {}, + }; + }); + return result; +} +function validateChoice(selected: unknown, calls: Json[]): void { + if (selected === "none" && calls.length) throw new Error("Workers AI tool_choice none 不允许工具调用"); + if (selected === "required" && !calls.length) throw new Error("Workers AI tool_choice required 未返回工具调用"); + if (selected && typeof selected === "object" && "type" in selected && selected.type === "function") { + const name = (selected as Json).function.name; + if (!calls.length || calls.some((call) => call.function.name !== name)) throw new Error("Workers AI tool_choice 未返回指定的工具调用"); + } +} +/** Public /ai/run model schemas vary. This adapter supports response/tool_calls text models and dense embedding models. */ +export function createWorkersFetch(config: ProviderConfig, transport: typeof globalThis.fetch): typeof globalThis.fetch { + if (!config.accountId || !/^[a-zA-Z0-9_-]+$/.test(config.accountId)) throw new Error("Workers AI 需要有效的 accountId"); + const base = new URL(config.baseURL || `https://api.cloudflare.com/client/v4/accounts/${config.accountId}/ai/`); + if (!["http:", "https:"].includes(base.protocol) || base.username || base.password) throw new Error("Workers AI 原生 API 地址必须是不含凭据的 HTTP(S) URL"); + base.pathname = base.pathname.replace(/\/?$/, "/"); + return (async (input: RequestInfo | URL, init?: RequestInit) => { + const request = input instanceof Request ? input : undefined; + const url = new URL(request ? request.url : String(input)); + if (url.origin !== base.origin || !url.pathname.startsWith(base.pathname)) throw new Error("Workers AI 请求超出已配置的 API 根地址"); + const path = url.pathname.slice(base.pathname.length); + const headers = new Headers(init?.headers ?? request?.headers); + headers.set("authorization", `Bearer ${config.apiKey}`); + const options = { ...init, headers, redirect: "error" as const, signal: init?.signal ?? request?.signal }; + if ((init?.method ?? request?.method ?? "GET") === "GET" && path === "models") { + const response = await transport(new URL("models/search", base), { ...options, method: "GET" }); + if (!response.ok) return response; + const value = await response.json(); + const models = unwrap(value); + if (!Array.isArray(models)) throw new Error("Workers AI 模型列表响应无效"); + return Response.json({ ...value, data: models.map((m: Json) => ({ ...m, id: m.name })) }); + } + if (!["chat/completions", "embeddings"].includes(path) || typeof init?.body !== "string") + throw new Error("Workers AI 原生接入不支持此 API 路径或请求体"); + const body: Json = JSON.parse(init.body); + if (typeof body.model !== "string" || !/^@[a-zA-Z0-9_-]+\/[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_./-]+$/.test(body.model) || body.model.split("/").includes("..")) + throw new Error("Workers AI 模型 ID 无效,必须采用 @cf/提供商/模型 等格式"); + const embed = path === "embeddings"; + let payload: Json; + let count = 0; + if (embed) { + rejectUnknown(body, ["model", "input", "encoding_format", "pooling"]); + if (body.encoding_format !== undefined && body.encoding_format !== "float") throw new Error("Workers AI 原生嵌入仅支持 float 编码"); + if ( + !(typeof body.input === "string" || (Array.isArray(body.input) && body.input.length && body.input.every((x: unknown) => typeof x === "string"))) + ) + throw new Error("Workers AI 原生嵌入需要文本或非空文本数组"); + count = Array.isArray(body.input) ? body.input.length : 1; + payload = { text: body.input, ...(body.pooling !== undefined ? { pooling: body.pooling } : {}) }; + } else payload = chatBody(body); + headers.set("content-type", "application/json"); + const endpoint = new URL(base); + endpoint.pathname += `run/${body.model}`; + const response = await transport(endpoint, { ...options, method: "POST", body: JSON.stringify(payload) }); + if (!response.ok) return response; + if (embed) { + const result = unwrap(await response.json()); + if ( + !Array.isArray(result.data) || + result.data.length !== count || + result.data.some((v: unknown) => !Array.isArray(v) || !v.length || v.some((n: unknown) => typeof n !== "number" || !Number.isFinite(n))) + ) + throw new Error("Workers AI 原生嵌入响应不完整"); + return Response.json({ + data: result.data.map((embedding: number[], index: number) => ({ object: "embedding", embedding, index })), + usage: result.usage, + }); + } + if (!body.stream) { + const result = unwrap(await response.json()); + const calls = callsOf(result.tool_calls); + validateChoice(body.tool_choice, calls); + if (typeof result.response !== "string" && !calls.length) throw new Error("Workers AI 原生接口未返回有效回复"); + return Response.json( + completed( + { content: result.response ?? "", ...(calls.length ? { tool_calls: calls } : {}) }, + calls.length ? "tool_calls" : "stop", + result.usage ?? {}, + ), + ); + } + // shared nativeSSE ignores [DONE]. Convert that wire terminal into an explicit JSON event + // so tool calls are released only after a terminal marker AND successful source EOF. + if (!response.body) throw new Error("Workers AI 原生接口返回了空流响应体"); + const decoder = new TextDecoder(); + let buffer = ""; + const encode = new TextEncoder(); + const marked = response.body.pipeThrough( + new TransformStream({ + transform(chunk, controller) { + buffer += decoder.decode(chunk, { stream: true }); + let end: number; + while ((end = buffer.indexOf("\n")) >= 0) { + controller.enqueue(encode.encode(convertTerminal(buffer.slice(0, end).replace(/\r$/, "")) + "\n")); + buffer = buffer.slice(end + 1); + } + }, + flush(controller) { + buffer += decoder.decode(); + if (buffer) controller.enqueue(encode.encode(convertTerminal(buffer))); + }, + }), + ); + let terminal = false; + let sawOutput = false; + let usage: Json = {}; + const calls: Json[] = []; + return nativeSSE( + new Response(marked, { status: response.status, headers: response.headers }), + (value) => { + if (terminal) throw new Error("Workers AI 流结束事件后仍有数据"); + if (value.yib_workers_done) { + terminal = true; + return []; + } + const result = unwrap(value); + if (result.usage) usage = result.usage; + const output: Json[] = []; + if (result.response != null) { + if (typeof result.response !== "string") throw new Error("Workers AI 原生流文本增量无效"); + sawOutput = true; + output.push(choice({ content: result.response })); + } + if (result.tool_calls?.length) { + sawOutput = true; + calls.push(...callsOf(result.tool_calls)); + output.push(choice({ yib_native_activity: true })); + } + return output; + }, + () => { + if (!terminal || !sawOutput) throw new Error("Workers AI 原生流已截断或没有输出"); + validateChoice(body.tool_choice, calls); + return [ + ...calls.map((call, index) => choice({ tool_calls: [{ index, ...call }] })), + { ...choice({}, calls.length ? "tool_calls" : "stop"), usage }, + ]; + }, + ); + }) as typeof globalThis.fetch; +} diff --git a/packages/core/src/model/provider-instance.ts b/packages/core/src/model/provider-instance.ts index 3aba6fe1b..cebaec23d 100644 --- a/packages/core/src/model/provider-instance.ts +++ b/packages/core/src/model/provider-instance.ts @@ -10,6 +10,7 @@ import { ContextLimitResult, contextMetadataURL, parseContextLimit, readContextL import { EmbedModel, IEmbedModel } from "./embed-model"; import { EvaluationModel } from "./evaluation-model"; import { IProviderClient } from "./factories"; +import { createNativeFetch } from "./native-fetch"; import type { UsageOwner } from "./usage-owner"; export class ProviderInstance { @@ -42,6 +43,8 @@ export class ProviderInstance { this.fetch = ufetch as unknown as typeof globalThis.fetch; } + this.fetch = createNativeFetch(config, this.fetch); + // this.logger.info(`[初始化] 🔌 提供商实例已创建`); } @@ -78,7 +81,12 @@ export class ProviderInstance { return null; } - const finalModelConfig: ModelConfig = { ...modelConfig, providerName: this.name }; + const finalModelConfig: ModelConfig = { + ...modelConfig, + providerName: this.name, + // Native LM Studio chat cannot carry client-owned tools; retain the framework's JSON-action fallback. + ...(this.config.type === "LM Studio" ? { disableNativeToolCalling: true } : {}), + }; //this.logger.debug(`[获取模型] 🟢 成功 | 模型ID: ${modelId} | 能力: ${capabilityName}`); return new modelConstructor(this.ctx, providerCapability, finalModelConfig, this.fetch, this.logging, this.usageOwner); diff --git a/packages/core/src/shared/message-delivery.ts b/packages/core/src/shared/message-delivery.ts new file mode 100644 index 000000000..fd49d8eda --- /dev/null +++ b/packages/core/src/shared/message-delivery.ts @@ -0,0 +1,31 @@ +import { h } from "koishi"; + +// Internal encoder option: scoped to one send, never shared across concurrent calls. +export const messageReceiptSink = Symbol("message receipt sink"); + +export type ConfirmedMessage = { id: string; content?: string; elements?: h[] }; + +export function confirmedMessages(messages: ConfirmedMessage[]): ConfirmedMessage[] { + return messages + .filter((message) => typeof message?.id === "string" && message.id.trim().length > 0) + .map((message) => { + const content = + typeof message.content === "string" + ? message.content + : Array.isArray(message.elements) + ? message.elements.map((element) => h(element.type, element.attrs, element.children).toString()).join("") + : undefined; + return { id: message.id, ...(content !== undefined ? { content } : {}) }; + }); +} + +/** A failed send may still have delivered messages confirmed by its encoder. */ +export class MessageDeliveryError extends Error { + readonly messages: ConfirmedMessage[]; + + constructor(cause: unknown, messages: ConfirmedMessage[]) { + super(cause instanceof Error ? cause.message : "消息发送失败", { cause }); + this.name = "MessageDeliveryError"; + this.messages = confirmedMessages(messages); + } +} diff --git a/packages/core/src/world/context-builder.ts b/packages/core/src/world/context-builder.ts index f69d2881d..fe1b27c42 100644 --- a/packages/core/src/world/context-builder.ts +++ b/packages/core/src/world/context-builder.ts @@ -79,7 +79,9 @@ export class ContextBuilder { } else { let selfInGuild: Awaited> | undefined; try { - if (session.guildId) selfInGuild = await session.bot.getGuildMember(session.guildId, session.selfId); + if (session.guildId && typeof session.bot.getGuildMember === "function") { + selfInGuild = await session.bot.getGuildMember(session.guildId, session.selfId); + } } catch (error) { this.logger.error(`获取机器人自身信息失败 for id ${session.selfId}: ${error.message}`); } @@ -224,15 +226,15 @@ export class ContextBuilder { if (isDirect) { let userInfo: Awaited> | undefined; try { - userInfo = await session.bot.getUser(session.userId!); + if (typeof session.bot.getUser === "function") userInfo = await session.bot.getUser(session.userId!); } catch (error) { this.logger.debug(`获取用户信息失败 for user ${session.userId}: ${error.message}`); } - channelName = `与 ${userInfo?.name || session.userId} 的私聊`; + channelName = `与 ${userInfo?.name || session.author?.name || session.userId} 的私聊`; } else { try { - channelInfo = await session.bot.getChannel(channelId!); + if (typeof session.bot.getChannel === "function") channelInfo = await session.bot.getChannel(channelId!); channelName = channelInfo?.name ?? ""; } catch (error) { this.logger.debug(`获取频道信息失败 for channel ${channelId}: ${error.message}`); @@ -246,12 +248,14 @@ export class ContextBuilder { private async getSelfInfo(session: Session) { const { selfId } = session; try { - const user = await session.bot.getUser(selfId); - return { id: selfId, name: user.name ?? "" }; + if (typeof session.bot.getUser === "function") { + const user = await session.bot.getUser(selfId); + return { id: selfId, name: user.name ?? "" }; + } } catch (error) { this.logger.debug(`获取机器人自身信息失败 for id ${selfId}: ${error.message}`); - return { id: selfId, name: session.bot.user?.name || "Self" }; } + return { id: selfId, name: session.bot.user?.name || "Self" }; } private partitionL1History(selfId: string, history: L1HistoryItem[]) { diff --git a/packages/core/tests/config-provider-serialization.spec.ts b/packages/core/tests/config-provider-serialization.spec.ts new file mode 100644 index 000000000..31f9a8fa1 --- /dev/null +++ b/packages/core/tests/config-provider-serialization.spec.ts @@ -0,0 +1,19 @@ +import { Schema } from "koishi"; +import { expect, it } from "vitest"; + +import { Config } from "../src/config"; +import { PROVIDER_TYPES } from "../src/model/config"; +it.each(PROVIDER_TYPES)("accepts a %s provider through the serialized console schema", (type) => { + const schema = new Schema(JSON.parse(JSON.stringify(Config))); + expect(() => schema({ providers: [{ name: "test", type, apiKey: "test", accountId: "account123", models: [{ modelId: "m" }] }] })).not.toThrow(); +}); +it.each([ + ["Google Gemini", "https://generativelanguage.googleapis.com/v1beta/openai/", "https://generativelanguage.googleapis.com/v1beta/"], + ["Qwen", "https://dashscope.aliyuncs.com/compatible-mode/v1/", "https://dashscope.aliyuncs.com/api/v1/"], + ["Ollama", "http://localhost:11434/v1/", "http://localhost:11434/"], +])("migrates only the former official %s root in console validation", (type, oldURL, expected) => { + const schema = new Schema(JSON.parse(JSON.stringify(Config))); + const value = (baseURL: string) => ({ providers: [{ name: "test", type, apiKey: "test", baseURL, models: [{ modelId: "m" }] }] }); + expect(schema(value(oldURL)).providers[0].baseURL).toBe(expected); + expect(schema(value("https://custom.invalid/api/")).providers[0].baseURL).toBe("https://custom.invalid/api/"); +}); diff --git a/packages/core/tests/context-platform-capabilities.spec.ts b/packages/core/tests/context-platform-capabilities.spec.ts new file mode 100644 index 000000000..9df35adb1 --- /dev/null +++ b/packages/core/tests/context-platform-capabilities.spec.ts @@ -0,0 +1,133 @@ +import { expect, it, vi } from "vitest"; + +import { ContextBuilder } from "../src/world/context-builder"; + +function fixture(isDirect = false) { + const logger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }; + const bot: any = { + user: { id: "bot", name: "Cached Bot" }, + getUser: vi.fn(async (id: string) => ({ id, name: id === "bot" ? "Remote Bot" : "Remote Alice" })), + getChannel: vi.fn(async () => ({ id: "channel", name: "Remote Group" })), + }; + const session: any = { + platform: "qq", + selfId: "bot", + userId: "alice", + channelId: "channel", + guildId: "guild", + isDirect, + author: { id: "alice", name: "Alice" }, + bot, + }; + const builder = new ContextBuilder( + {} as any, + { l1_memory: { maxMessages: 100, keepFullTurnCount: 5 }, l2_memory: { enabled: false }, l3_memory: { enabled: false } } as any, + { getL1History: async () => [] } as any, + {} as any, + {} as any, + { getLogger: () => logger } as any, + ); + return { builder, session, bot, logger }; +} + +it("skips unavailable guild-member lookup without logging and preserves self identity", async () => { + const f = fixture(); + const state = await f.builder.build(f.session); + expect(state.self).toEqual({ id: "bot", name: "Remote Bot" }); + expect(state.users).toEqual([{ id: "bot", name: "Remote Bot", roles: ["self"] }]); + expect(f.logger.error).not.toHaveBeenCalled(); +}); + +it("retains guild-member lookup failures as diagnostics while keeping self identity", async () => { + const f = fixture(); + f.bot.getGuildMember = vi.fn(async () => { + throw new Error("guild lookup failed"); + }); + const state = await f.builder.build(f.session); + expect(f.bot.getGuildMember).toHaveBeenCalledWith("guild", "bot"); + expect(f.logger.error).toHaveBeenCalledWith("获取机器人自身信息失败 for id bot: guild lookup failed"); + expect(state.users).toEqual([{ id: "bot", name: "Remote Bot", roles: ["self"] }]); +}); + +it("preserves guild nickname and both string and object role identities", async () => { + const f = fixture(); + f.bot.getGuildMember = vi.fn(async () => ({ nick: "Guild Bot", name: "Member Bot", roles: ["admin", { id: "moderator" }] })); + const state = await f.builder.build(f.session); + expect(f.bot.getGuildMember).toHaveBeenCalledWith("guild", "bot"); + expect(state.users).toEqual([{ id: "bot", name: "Guild Bot", roles: ["self", "admin", "moderator"] }]); + expect(f.logger.error).not.toHaveBeenCalled(); +}); + +it("does not request a guild member without a guild ID", async () => { + const f = fixture(); + delete f.session.guildId; + f.bot.getGuildMember = vi.fn(); + await f.builder.build(f.session); + expect(f.bot.getGuildMember).not.toHaveBeenCalled(); +}); + +it("falls back to cached bot identity and unknown group when optional lookup methods are absent", async () => { + const f = fixture(); + delete f.bot.getUser; + delete f.bot.getChannel; + const state = await f.builder.build(f.session); + expect(state.self).toEqual({ id: "bot", name: "Cached Bot" }); + expect(state.channel.name).toBe("未知群组"); + expect(state.users).toEqual([{ id: "bot", name: "Cached Bot", roles: ["self"] }]); + expect(f.logger.debug).not.toHaveBeenCalled(); + expect(f.logger.error).not.toHaveBeenCalled(); +}); + +it("builds direct context without optional user lookup using the event author", async () => { + const f = fixture(true); + delete f.bot.getUser; + f.bot.getGuildMember = vi.fn(); + const state = await f.builder.build(f.session); + expect(state.channel.name).toBe("与 Alice 的私聊"); + expect(state.users).toEqual([ + { id: "alice", name: "Alice" }, + { id: "bot", name: "Cached Bot", roles: ["self"] }, + ]); + expect(f.bot.getGuildMember).not.toHaveBeenCalled(); + expect(f.logger.debug).not.toHaveBeenCalled(); +}); + +it("retains diagnostics for supported user and channel lookups that fail", async () => { + const f = fixture(); + f.bot.getGuildMember = vi.fn(async () => ({})); + f.bot.getUser = vi.fn(async () => { + throw new Error("user lookup failed"); + }); + f.bot.getChannel = vi.fn(async () => { + throw new Error("channel lookup failed"); + }); + const state = await f.builder.build(f.session); + expect(state.self).toEqual({ id: "bot", name: "Cached Bot" }); + expect(state.channel.name).toBe("未知群组"); + expect(f.logger.debug).toHaveBeenCalledWith("获取机器人自身信息失败 for id bot: user lookup failed"); + expect(f.logger.debug).toHaveBeenCalledWith("获取频道信息失败 for channel channel: channel lookup failed"); +}); + +it("retains direct user lookup diagnostics and falls back to the event author", async () => { + const f = fixture(true); + f.bot.getUser = vi.fn(async () => { + throw new Error("user lookup failed"); + }); + const state = await f.builder.build(f.session); + expect(state.channel.name).toBe("与 Alice 的私聊"); + expect(state.self).toEqual({ id: "bot", name: "Cached Bot" }); + expect(f.logger.debug).toHaveBeenCalledWith("获取用户信息失败 for user alice: user lookup failed"); + expect(f.logger.debug).toHaveBeenCalledWith("获取机器人自身信息失败 for id bot: user lookup failed"); +}); + +it("keeps ID and default name fallbacks when event and cached names are unavailable", async () => { + const f = fixture(true); + delete f.bot.getUser; + delete f.bot.user; + delete f.session.author; + const state = await f.builder.build(f.session); + expect(state.channel.name).toBe("与 alice 的私聊"); + expect(state.self).toEqual({ id: "bot", name: "Self" }); + expect(state.users?.find((user) => user.id === "bot")).toEqual({ id: "bot", name: "Self", roles: ["self"] }); + expect(f.logger.debug).not.toHaveBeenCalled(); +}); diff --git a/packages/core/tests/core-util-send.spec.ts b/packages/core/tests/core-util-send.spec.ts index e0e0629d1..a6c27e28b 100644 --- a/packages/core/tests/core-util-send.spec.ts +++ b/packages/core/tests/core-util-send.spec.ts @@ -1,7 +1,9 @@ +import { Bot, Context, MessageEncoder, h } from "koishi"; import { describe, expect, it } from "vitest"; import { withReplyTurn } from "../src/agent/reply-turn"; import CoreUtilExtension from "../src/extension/builtin/core-util"; +import { MessageDeliveryError } from "../src/shared/message-delivery"; function setup(send: (...args: any[]) => Promise = async () => ["sent"]) { const events: any[] = []; @@ -99,6 +101,51 @@ describe("send_message delivery", () => { expect(events).toEqual([]); }); + it("retains HTTP status and QQ error details without serializing request credentials", async () => { + const error = Object.assign(new Error("request failed"), { + code: "ERR_BAD_RESPONSE", + response: { status: 400, data: { code: 40054005, message: "duplicate sequence", trace_id: "qq-trace" }, headers: { authorization: "secret" } }, + config: { headers: { Authorization: "secret" } }, + }); + const { tool, session } = setup(async () => { + throw error; + }); + const result = await tool.sendMessage({ session, message: "hello" } as any); + expect(result.error?.message).toContain("40054005"); + expect(result.error?.message).toContain("duplicate sequence"); + expect(result.error?.message).toContain("400"); + expect(result.error?.message).toContain("qq-trace"); + expect(result.error?.message).not.toContain("secret"); + }); + + it("does not accept empty message IDs as confirmed delivery", async () => { + const { tool, session, events } = setup(async () => [""]); + expect((await tool.sendMessage({ session, message: "hello" } as any)).status).toBe("error"); + expect(events).toEqual([]); + }); + + it("records encoder-confirmed messages even when the same send rejects", async () => { + const { tool, session, events } = setup(async () => { + throw new MessageDeliveryError(new AggregateError([new Error("image refused")]), [{ id: "text-sent", content: "text only" }]); + }); + const result = await tool.sendMessage({ session, message: 'text only' } as any); + expect(result.status).toBe("error"); + expect(result.error?.message).toContain("image refused"); + expect(result.error?.retryable).toBe(false); + expect(result.metadata?.delivery.messageIds).toEqual(["text-sent"]); + expect(events).toHaveLength(1); + expect(events[0][1].event.message).toMatchObject({ id: "text-sent", content: "text only" }); + }); + + it("does not record the full attempted body when a partial encoder receipt has no content", async () => { + const { tool, session, events } = setup(async () => { + throw new MessageDeliveryError(new Error("image refused"), [{ id: "text-sent" }]); + }); + const result = await tool.sendMessage({ session, message: 'text' } as any); + expect(result.metadata?.delivery.messageIds).toEqual(["text-sent"]); + expect(events[0][1].event.message.content).toBe(""); + }); + it("retains nested errors and ordinary errors", async () => { const nested = Object.assign(new Error("aggregate"), { errors: [Object.assign(new Error(""), { errors: [new Error("inner reason")] }), new Error("second reason")], @@ -148,6 +195,9 @@ describe("send_message delivery", () => { expect(result.status).toBe("error"); expect(result.error?.message).toContain("later paragraph refused"); expect(attempted).toEqual(["first", "second"]); + expect(result.metadata?.delivery).toMatchObject({ messageIds: ["first-sent"], sentMessages: 1, totalMessages: 3 }); + expect(result.error?.retryable).toBe(false); + expect(result.error?.message).toContain("已完整发送 1/3 段"); expect(events.length).toBe(1); expect(events[0][1].event.message.id).toBe("first-sent"); }); @@ -313,3 +363,37 @@ it("preserves the direct destination category when resolving a private tool targ ); expect(result.status).toBe("success"); }); + +for (const guarded of [false, true]) { + it(`records successful encoder split content with reply guard ${guarded}`, async () => { + const ctx = new Context(); + class Encoder extends MessageEncoder { + async visit() { + this.results.push({ id: "text", content: "hello" }, { id: "image", elements: [h.image("https://test.invalid/a.png")] }); + } + async flush() {} + } + class SendingBot extends Bot { + static MessageEncoder = Encoder; + } + const bot = new SendingBot(ctx, {} as any, "slack"); + bot.user = { id: "bot" }; + const f = setup(); + f.ctx.bots = [bot]; + const session = bot.session({ channel: { id: "C", type: 0 }, message: { id: "source" } }); + const send = () => f.tool.sendMessage({ session, message: "hello" } as any); + const result = guarded ? await withReplyTurn(() => true, send) : await send(); + expect(result.status).toBe("success"); + expect(f.events.map((event) => event[1].event.message)).toMatchObject([ + { id: "text", content: "hello" }, + { id: "image", content: '' }, + ]); + await ctx.stop(); + }); +} + +it("leaves split receipt content unknown when an adapter returns only IDs", async () => { + const f = setup(async () => ["text", "image"]); + expect((await f.tool.sendMessage({ session: f.session, message: 'hello' } as any)).status).toBe("success"); + expect(f.events.map((event) => event[1].event.message.content)).toEqual(["", ""]); +}); diff --git a/packages/core/tests/native-lmstudio.spec.ts b/packages/core/tests/native-lmstudio.spec.ts new file mode 100644 index 000000000..50182d89b --- /dev/null +++ b/packages/core/tests/native-lmstudio.spec.ts @@ -0,0 +1,174 @@ +import { describe, expect, it } from "vitest"; + +import { ChatModel } from "../src/model/chat-model"; +import { ModelAbility } from "../src/model/config"; +import { createLMStudioFetch } from "../src/model/native/lmstudio"; +import { loggingStub, stubCtx } from "./helpers/yesimbot"; +const root = "https://example.test/relay/"; +const config = { type: "LM Studio", apiKey: "token", baseURL: root } as any; +const call = (f: typeof fetch, body: any = {}) => + f(root + "chat/completions", { + method: "POST", + body: JSON.stringify({ + model: "test", + messages: [ + { role: "system", content: "rules" }, + { role: "user", content: "hello" }, + ], + ...body, + }), + }); +function setup(response: () => Response) { + const calls: any[] = []; + return { + calls, + fetch: createLMStudioFetch(config, (async (url, init) => { + calls.push({ url: String(url), init, body: init?.body && JSON.parse(String(init.body)) }); + return response(); + }) as typeof fetch), + }; +} +const result = { output: [{ type: "message", content: "你好" }], stats: { input_tokens: 2, total_output_tokens: 3, reasoning_output_tokens: 1 } }; +const sse = (values: any[]) => new Response(values.map((v) => `event: ${v.type}\ndata: ${JSON.stringify(v)}\n\n`).join("")); +describe("LM Studio native", () => { + it("uses native chat without enabling server integrations", async () => { + const t = setup(() => Response.json(result)); + const out = await (await call(t.fetch)).json(); + expect(t.calls[0].url).toBe(root + "api/v1/chat"); + expect(t.calls[0].body).toEqual({ model: "test", input: [{ type: "text", content: "hello" }], system_prompt: "rules", stream: false, store: false }); + expect(out.choices[0].message.content).toBe("你好"); + expect(out.usage.total_tokens).toBe(5); + }); + for (const stream of [false, true]) + it(`works through ChatModel (${stream})`, async () => { + const t = setup(() => + stream ? sse([{ type: "chat.start" }, { type: "message.delta", content: "你好" }, { type: "chat.end", result }]) : Response.json(result), + ); + const m = new ChatModel( + stubCtx(), + () => ({ model: "test", baseURL: root, apiKey: "token" }), + { modelId: "test", abilities: [ModelAbility.Chat], parameters: { stream } }, + t.fetch, + loggingStub(), + ); + const out = await m.chat({ messages: [{ role: "user", content: "hello" }] }); + expect(out.text).toBe("你好"); + expect(out.usage?.total_tokens).toBe(5); + }); + it("rejects unsupported tools history remote images and integrations before sending", async () => { + const t = setup(() => Response.json(result)); + for (const body of [ + { tools: [{ type: "function", function: { name: "lookup" } }] }, + { + messages: [ + { role: "assistant", content: "old" }, + { role: "user", content: "new" }, + ], + }, + { integrations: ["danger"] }, + { messages: [{ role: "user", content: [{ type: "image_url", image_url: { url: "https://example.com/image.png" } }] }] }, + ]) + await expect(call(t.fetch, body)).rejects.toThrow(/./); + expect(t.calls).toHaveLength(0); + }); + it("maps data-url image input", async () => { + const t = setup(() => Response.json(result)); + await call(t.fetch, { messages: [{ role: "user", content: [{ type: "image_url", image_url: { url: "data:image/png;base64,aGk=" } }] }] }); + expect(t.calls[0].body.input).toEqual([{ type: "image", data_url: "data:image/png;base64,aGk=" }]); + }); + it("uses actual documented compatible embedding endpoint and native models", async () => { + const t = setup(() => Response.json({ models: [{ key: "test", max_context_length: 4096 }] })); + await t.fetch(root + "embeddings", { method: "POST", body: JSON.stringify({ model: "test", input: ["one"] }) }); + expect(t.calls[0].url).toBe(root + "v1/embeddings"); + const r = await (await t.fetch(root + "models")).json(); + expect(t.calls[1].url).toBe(root + "api/v1/models"); + expect(r.data[0].id).toBe("test"); + }); + for (const events of [ + [{ type: "message.delta", content: "partial" }], + [ + { type: "chat.end", result }, + { type: "error", error: { message: "failed" } }, + ], + [{ type: "chat.end", result: { output: [{ type: "tool_call", tool: "lookup", arguments: {} }], stats: {} } }], + ]) + it("rejects incomplete failed and server-tool streams", async () => { + const t = setup(() => sse(events)); + await expect((await call(t.fetch, { stream: true })).text()).rejects.toThrow(/./); + }); + it("preserves failed HTTP response", async () => { + const t = setup(() => new Response("bad", { status: 503 })); + expect((await call(t.fetch)).status).toBe(503); + }); +}); + +it("LM Studio rejects server tool JSON without reporting executable calls", async () => { + const t = setup(() => Response.json({ output: [{ type: "tool_call", tool: "lookup", arguments: {}, output: "already executed remotely" }], stats: {} })); + await expect(call(t.fetch)).rejects.toThrow(/服务端工具/); +}); +it("LM Studio preserves optional Bearer authentication and abort signal", async () => { + const t = setup(() => Response.json(result)); + const signal = new AbortController().signal; + await t.fetch(root + "chat/completions", { method: "POST", signal, body: JSON.stringify({ model: "test", messages: [{ role: "user", content: "hi" }] }) }); + expect(t.calls[0].init.signal).toBe(signal); + expect(t.calls[0].init.headers.get("authorization")).toBe("Bearer token"); +}); +it("LM Studio cancellation reaches native stream", async () => { + let cancelled = false; + const t = setup( + () => + new Response( + new ReadableStream({ + cancel() { + cancelled = true; + }, + }), + ), + ); + const r = await call(t.fetch, { stream: true }); + await r.body!.cancel(); + expect(cancelled).toBe(true); +}); + +it("LM Studio bridge crosses real local HTTP with native request and response shapes", async () => { + const { createServer } = await import("node:http"); + const { once } = await import("node:events"); + let path = ""; + let body: any; + const server = createServer(async (req, res) => { + path = req.url!; + let text = ""; + for await (const chunk of req) text += chunk; + body = JSON.parse(text); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify(result)); + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const address = server.address() as { port: number }; + const localRoot = `http://127.0.0.1:${address.port}/`; + try { + const { request } = await import("node:http"); + const { Readable } = await import("node:stream"); + const localTransport = ((url: any, init: any) => + new Promise((resolve, reject) => { + if (new URL(String(url)).hostname !== "127.0.0.1") return reject(new Error("Local test transport only")); + const req = request(String(url), { method: init.method, headers: Object.fromEntries(init.headers), signal: init.signal }, (res) => + resolve(new Response(Readable.toWeb(res) as ReadableStream, { status: res.statusCode })), + ); + req.on("error", reject); + req.end(init.body); + })) as typeof fetch; + const f = createLMStudioFetch({ ...config, baseURL: localRoot }, localTransport); + const response = await f(localRoot + "chat/completions", { + method: "POST", + body: JSON.stringify({ model: "test", messages: [{ role: "user", content: "hello" }] }), + }); + expect((await response.json()).choices[0].message.content).toBe("你好"); + expect(path).toBe("/api/v1/chat"); + expect(body).toEqual({ model: "test", input: [{ type: "text", content: "hello" }], stream: false, store: false }); + } finally { + server.closeAllConnections(); + await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve()))); + } +}); diff --git a/packages/core/tests/native-ollama.spec.ts b/packages/core/tests/native-ollama.spec.ts new file mode 100644 index 000000000..90c081173 --- /dev/null +++ b/packages/core/tests/native-ollama.spec.ts @@ -0,0 +1,311 @@ +import { expect, it } from "vitest"; + +import { ChatModel } from "../src/model/chat-model"; +import { ModelAbility } from "../src/model/config"; +import { createOllamaFetch } from "../src/model/native/ollama"; +import { loggingStub, stubCtx } from "./helpers/yesimbot"; +const cfg = { type: "Ollama", name: "local", baseURL: "http://local.test/prefix/", apiKey: "key", models: [] } as any; +const terminal = { message: { role: "assistant", content: "你好" }, done: true, done_reason: "stop", prompt_eval_count: 4, eval_count: 2 }; +function fixture(reply: () => Response) { + const calls: any[] = []; + const f = createOllamaFetch(cfg, (async (url: any, init: any) => { + calls.push({ url: String(url), init, body: init?.body && JSON.parse(init.body) }); + return reply(); + }) as any); + return { f, calls }; +} +const call = (f: typeof fetch, extra: any = {}) => + f(`${cfg.baseURL}chat/completions`, { method: "POST", body: JSON.stringify({ model: "test", messages: [{ role: "user", content: "hi" }], ...extra }) }); +function ndjson(events: any[], split = false) { + const bytes = new TextEncoder().encode(events.map((x) => JSON.stringify(x)).join("\n") + "\n"); + let i = 0; + return new Response( + new ReadableStream({ + pull(c) { + if (i === bytes.length) return c.close(); + const n = split ? 1 : bytes.length; + c.enqueue(bytes.slice(i, (i += n))); + }, + }), + { headers: { "content-type": "application/x-ndjson" } }, + ); +} +it("uses native Ollama chat with options and token counts", async () => { + const { f, calls } = fixture(() => Response.json(terminal)); + const out = await (await call(f, { temperature: 0.8, top_p: 0.9, max_tokens: 20 })).json(); + expect(calls[0].url).toBe("http://local.test/prefix/api/chat"); + expect(calls[0].body.options).toEqual({ temperature: 0.8, top_p: 0.9, num_predict: 20 }); + expect(out.usage).toMatchObject({ prompt_tokens: 4, completion_tokens: 2, total_tokens: 6 }); +}); +it("translates tool arguments/results and base64 images", async () => { + const { f, calls } = fixture(() => Response.json(terminal)); + await call(f, { + messages: [ + { + role: "user", + content: [ + { type: "text", text: "look" }, + { type: "image_url", image_url: { url: "data:image/png;base64,aGVsbG8=" } }, + ], + }, + { role: "assistant", content: "", tool_calls: [{ id: "call1", type: "function", function: { name: "lookup", arguments: '{"q":"x"}' } }] }, + { role: "tool", tool_call_id: "call1", content: [{ type: "text", text: "result" }] }, + ], + }); + expect(calls[0].body.messages[0]).toEqual({ role: "user", content: "look", images: ["aGVsbG8="] }); + expect(calls[0].body.messages[1].tool_calls[0].function.arguments).toEqual({ q: "x" }); + expect(calls[0].body.messages[2]).toEqual({ role: "tool", tool_name: "lookup", content: "result" }); +}); +it("uses native embeddings and tags without inventing context metadata", async () => { + const { f, calls } = fixture(() => Response.json({ embeddings: [[1], [2]], prompt_eval_count: 5, models: [{ name: "test", model: "test" }] })); + const r = await f(`${cfg.baseURL}embeddings`, { method: "POST", body: JSON.stringify({ model: "embed", input: ["a", "b"] }) }); + expect((await r.json()).data.map((x: any) => x.embedding)).toEqual([[1], [2]]); + expect(calls[0].url).toBe("http://local.test/prefix/api/embed"); + expect(calls[0].body.truncate).toBe(false); + const meta = await (await f(`${cfg.baseURL}models`, { method: "GET" })).json(); + expect(calls[1].url).toBe("http://local.test/prefix/api/tags"); + expect(meta.data[0]).toEqual({ name: "test", model: "test", id: "test" }); +}); +it("rejects unsupported controls, remote images and media tool results", async () => { + const { f, calls } = fixture(() => Response.json(terminal)); + await expect(call(f, { tool_choice: "invalid" })).rejects.toThrow(/tool_choice/); + await expect(call(f, { messages: [{ role: "user", content: [{ type: "image_url", image_url: { url: "https://image.test/x.png" } }] }] })).rejects.toThrow( + /base64/, + ); + await expect(call(f, { messages: [{ role: "tool", tool_call_id: "x", content: [{ type: "input_audio" }] }] })).rejects.toThrow(/不支持|缺少/); + expect(calls).toHaveLength(0); +}); +it("preserves failures and abort signal; rejects invalid embeddings", async () => { + const { f, calls } = fixture(() => new Response("busy", { status: 503 })); + const signal = new AbortController().signal; + const r = await f(`${cfg.baseURL}chat/completions`, { method: "POST", signal, body: JSON.stringify({ model: "test", messages: [] }) }); + expect(r.status).toBe(503); + expect(calls[0].init.signal).toBe(signal); + const bad = fixture(() => Response.json({ embeddings: [[1]] })); + await expect(bad.f(`${cfg.baseURL}embeddings`, { method: "POST", body: JSON.stringify({ model: "test", input: ["a", "b"] }) })).rejects.toThrow(/嵌入/); +}); +for (const stream of [false, true]) { + it(`ChatModel consumes Ollama ${stream ? "NDJSON" : "JSON"} text`, async () => { + const { f } = fixture(() => + stream + ? ndjson( + [ + { message: { content: "你" }, done: false }, + { ...terminal, message: { content: "好" } }, + ], + true, + ) + : Response.json(terminal), + ); + const model = new ChatModel( + stubCtx(), + () => ({ model: "test", baseURL: cfg.baseURL }), + { modelId: "test", abilities: [ModelAbility.Chat], parameters: { stream } }, + f, + loggingStub(), + ); + expect((await model.chat({ messages: [{ role: "user", content: "hi" }] })).text).toBe("你好"); + }); + for (const reason of ["stop", "length"]) + it(`ChatModel only executes complete Ollama tools (${stream}, ${reason})`, async () => { + const native = { + ...terminal, + done_reason: reason, + message: { content: "", tool_calls: [{ function: { name: "lookup", arguments: { q: "x" } } }] }, + }; + const { f } = fixture(() => + stream + ? ndjson([ + { message: native.message, done: false }, + { ...native, message: { content: "" } }, + ]) + : Response.json(native), + ); + let executions = 0; + const model = new ChatModel( + stubCtx(), + () => ({ model: "test", baseURL: cfg.baseURL }), + { modelId: "test", abilities: [ModelAbility.Chat], parameters: { stream } }, + f, + loggingStub(), + ); + const p = model.chat({ + singleStep: true, + messages: [{ role: "user", content: "hi" }], + tools: [ + { + type: "function", + function: { name: "lookup", parameters: {} }, + execute: () => { + executions++; + return {}; + }, + }, + ], + }); + const error = await p.then( + () => null, + (error) => error, + ); + expect(error === null).toBe(reason === "stop"); + expect(executions).toBe(reason === "stop" ? 1 : 0); + }); +} +it("rejects incomplete NDJSON before tool execution", async () => { + const { f } = fixture(() => ndjson([{ message: { tool_calls: [{ function: { name: "lookup", arguments: {} } }] }, done: false }])); + const r = await call(f, { stream: true }); + await expect(r.text()).rejects.toThrow(/结束|截断/); +}); +it("cancels the native source when downstream cancels", async () => { + let cancelled = false; + const { f } = fixture( + () => + new Response( + new ReadableStream({ + cancel() { + cancelled = true; + }, + }), + ), + ); + const r = await call(f, { stream: true }); + await r.body!.cancel(); + expect(cancelled).toBe(true); +}); +for (const stream of [false, true]) { + for (const selected of ["required", { type: "function", function: { name: "lookup" } }]) { + for (const matching of [false, true]) + it(`enforces Ollama tool choice locally without sending unsupported fields (${stream}, ${typeof selected}, ${matching})`, async () => { + const native = { ...terminal, message: { content: "", tool_calls: matching ? [{ function: { name: "lookup", arguments: {} } }] : [] } }; + const { f, calls } = fixture(() => (stream ? ndjson([native]) : Response.json(native))); + const p = call(f, { stream, tool_choice: selected, tools: [{ type: "function", function: { name: "lookup", parameters: {} } }] }).then( + async (r) => { + if (stream) await r.text(); + else await r.json(); + }, + ); + const error = await p.then( + () => null, + (error) => error, + ); + expect(error === null).toBe(matching); + expect(calls[0].body).not.toHaveProperty("tool_choice"); + expect(calls[0].body.tools).toHaveLength(1); + }); + } +} +it("signals real native tool activity before EOF and withholds execution", async () => { + let close!: () => void; + const bytes = new TextEncoder(); + const { f } = fixture( + () => + new Response( + new ReadableStream({ + start(c) { + c.enqueue( + bytes.encode(JSON.stringify({ message: { tool_calls: [{ function: { name: "lookup", arguments: {} } }] }, done: false }) + "\n"), + ); + close = () => { + c.enqueue(bytes.encode(JSON.stringify({ done: true, done_reason: "stop" }) + "\n")); + c.close(); + }; + }, + }), + { headers: { "content-type": "application/x-ndjson" } }, + ), + ); + let notify!: () => void; + const started = new Promise((resolve) => { + notify = () => resolve(true); + }); + let executions = 0, + count = 0; + const model = new ChatModel( + stubCtx(), + () => ({ model: "test", baseURL: cfg.baseURL }), + { modelId: "test", abilities: [ModelAbility.Chat], parameters: { stream: true } }, + f, + loggingStub(), + ); + const pending = model.chat({ + singleStep: true, + onStreamStart: () => { + count++; + notify(); + }, + messages: [{ role: "user", content: "hi" }], + tools: [ + { + type: "function", + function: { name: "lookup", parameters: {} }, + execute: () => { + executions++; + return {}; + }, + }, + ], + }); + const observed = await Promise.race([started, new Promise((resolve) => setTimeout(() => resolve(false), 100))]); + expect(executions).toBe(0); + close(); + await pending; + expect(observed).toBe(true); + expect(count).toBe(1); + expect(executions).toBe(1); +}); +it("preserves NDJSON business errors", async () => { + const { f } = fixture(() => ndjson([{ error: "model unavailable" }])); + await expect((await call(f, { stream: true })).text()).rejects.toThrow(/model unavailable/); +}); +it("rejects missing argument objects and sparse native tool indices", async () => { + for (const tool of [{ function: { name: "lookup" } }, { function: { index: 1, name: "lookup", arguments: {} } }]) { + const { f } = fixture(() => + ndjson([ + { message: { tool_calls: [tool] }, done: false }, + { done: true, done_reason: "stop" }, + ]), + ); + await expect((await call(f, { stream: true })).text()).rejects.toThrow(/参数|索引/); + } +}); +for (const streaming of [false, true]) + it(`ChatModel replays native Ollama thinking and native tool ID on the next tool turn (${streaming})`, async () => { + const nativeTool = { + ...terminal, + message: { content: "", thinking: "private native thinking", tool_calls: [{ id: "vendor-call", function: { name: "lookup", arguments: {} } }] }, + }; + const { f, calls } = fixture(() => + streaming ? ndjson([calls.length === 1 ? nativeTool : terminal]) : Response.json(calls.length === 1 ? nativeTool : terminal), + ); + const model = new ChatModel( + stubCtx(), + () => ({ model: "test", baseURL: cfg.baseURL }), + { modelId: "test", abilities: [ModelAbility.Chat], parameters: { stream: streaming } }, + f, + loggingStub(), + ); + const result = await model.chat({ + maxSteps: 2, + messages: [{ role: "user", content: "hi" }], + tools: [{ type: "function", function: { name: "lookup", parameters: {} }, execute: () => ({ ok: true }) }], + }); + expect(result.text).toBe("你好"); + expect(calls).toHaveLength(2); + expect(calls[1].body.messages[1]).toMatchObject({ + role: "assistant", + thinking: "private native thinking", + tool_calls: [{ id: "vendor-call", function: { name: "lookup", arguments: {} } }], + }); + expect(calls[1].body.messages[2]).toEqual({ role: "tool", tool_name: "lookup", content: '{"ok":true}' }); + expect(result.text).not.toContain("private native thinking"); + }); +it("normalizes Ollama scalar stop and validates native stop arrays", async () => { + const { f, calls } = fixture(() => Response.json(terminal)); + await call(f, { stop: "END" }); + expect(calls[0].body.options.stop).toEqual(["END"]); + await call(f, { stop: ["END", "STOP"] }); + expect(calls[1].body.options.stop).toEqual(["END", "STOP"]); + await expect(call(f, { stop: ["END", 3] })).rejects.toThrow(/stop/); + await expect(call(f, { stop: { invalid: true } })).rejects.toThrow(/stop/); + expect(calls).toHaveLength(2); +}); diff --git a/packages/core/tests/native-provider.spec.ts b/packages/core/tests/native-provider.spec.ts new file mode 100644 index 000000000..9016ee00c --- /dev/null +++ b/packages/core/tests/native-provider.spec.ts @@ -0,0 +1,640 @@ +import { streamText } from "@xsai/stream-text"; +import { describe, expect, it } from "vitest"; + +import { createNativeFetch } from "../src/model/native-fetch"; + +const config = (protocol: string) => + ({ + protocol, + type: protocol === "gemini-native" ? "Google Gemini" : "Anthropic", + apiKey: "secret", + baseURL: protocol === "gemini-native" ? "https://example.test/v1beta/" : "https://example.test/v1/", + }) as any; +const json = (data: unknown) => Response.json(data); +const response = { + candidates: [{ content: { parts: [{ text: "你好" }] }, finishReason: "STOP" }], + usageMetadata: { promptTokenCount: 4, candidatesTokenCount: 2, thoughtsTokenCount: 3, cachedContentTokenCount: 1, totalTokenCount: 9 }, +}; +const call = (fetch: typeof globalThis.fetch, body: any = {}, base = "v1beta") => + fetch(`https://example.test/${base}/chat/completions`, { + method: "POST", + body: JSON.stringify({ + model: "test", + messages: [ + { role: "system", content: "rules" }, + { role: "user", content: "hello" }, + ], + ...body, + }), + }); +function transport(result: () => Response) { + const calls: any[] = []; + return { + calls, + fetch: (async (url, init) => { + calls.push({ url: String(url), init, body: init?.body ? JSON.parse(String(init.body)) : undefined }); + return result(); + }) as typeof globalThis.fetch, + }; +} +function sse(events: any[], fragmented = false) { + const bytes = new TextEncoder().encode(events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join("")); + let offset = 0; + return new Response( + new ReadableStream({ + pull(c) { + if (offset === bytes.length) return c.close(); + const size = fragmented ? 1 : bytes.length; + c.enqueue(bytes.slice(offset, (offset += size))); + }, + }), + { headers: { "content-type": "text/event-stream" } }, + ); +} + +describe("native provider requests", () => { + it("leaves compatible transport untouched", () => { + const f = transport(() => json({})).fetch; + expect(createNativeFetch({ protocol: "openai-compatible" } as any, f)).toBe(f); + }); + it("uses native Gemini chat, system and usage", async () => { + const t = transport(() => json(response)); + const out = await (await call(createNativeFetch(config("gemini-native"), t.fetch))).json(); + expect(t.calls[0].url).toBe("https://example.test/v1beta/models/test:generateContent"); + expect(t.calls[0].init.headers.get("x-goog-api-key")).toBe("secret"); + expect(t.calls[0].body.systemInstruction.parts[0].text).toBe("rules"); + expect(out.choices[0].message.content).toBe("你好"); + expect(out.usage).toMatchObject({ prompt_tokens: 4, completion_tokens: 5, total_tokens: 9, prompt_tokens_details: { cached_tokens: 1 } }); + }); + it("uses Anthropic messages and normalizes cached usage", async () => { + const t = transport(() => + json({ + id: "a", + content: [{ type: "text", text: "hi" }], + stop_reason: "end_turn", + usage: { input_tokens: 3, output_tokens: 2, cache_read_input_tokens: 4, cache_creation_input_tokens: 5 }, + }), + ); + const out = await (await call(createNativeFetch(config("anthropic-native"), t.fetch), {}, "v1")).json(); + expect(t.calls[0].url).toBe("https://example.test/v1/messages"); + expect(t.calls[0].init.headers.get("x-api-key")).toBe("secret"); + expect(t.calls[0].init.headers.get("authorization")).toBeNull(); + expect(t.calls[0].body.system).toEqual([{ type: "text", text: "rules" }]); + expect(out.usage.prompt_tokens).toBe(12); + expect(out.usage.completion_tokens).toBe(2); + }); + it("preserves Gemini tool-call signatures across result continuation", async () => { + const t = transport(() => + json({ + candidates: [ + { + content: { parts: [{ functionCall: { name: "lookup", args: { q: "x" }, id: "native-id" }, thoughtSignature: "opaque-signature" }] }, + finishReason: "STOP", + }, + ], + }), + ); + const f = createNativeFetch(config("gemini-native"), t.fetch); + const out = await (await call(f)).json(); + const tool = out.choices[0].message.tool_calls[0]; + await call(f, { + messages: [ + { role: "assistant", content: "", tool_calls: [tool] }, + { role: "tool", tool_call_id: tool.id, content: "result" }, + ], + }); + expect(t.calls[1].body.contents[0].parts[0].thoughtSignature).toBe("opaque-signature"); + expect(t.calls[1].body.contents[1].parts[0].functionResponse).toMatchObject({ id: "native-id", name: "lookup", response: { result: "result" } }); + }); + it("preserves Anthropic signed thinking around tool results", async () => { + const thinking = { type: "thinking", thinking: "thought", signature: "sig" }; + const t = transport(() => + json({ id: "a", content: [thinking, { type: "tool_use", id: "tool_1", name: "lookup", input: { q: "x" } }], stop_reason: "tool_use", usage: {} }), + ); + const f = createNativeFetch(config("anthropic-native"), t.fetch); + const out = await (await call(f, {}, "v1")).json(); + const tool = out.choices[0].message.tool_calls[0]; + await call( + f, + { + messages: [ + { role: "assistant", content: "", tool_calls: [tool] }, + { role: "tool", tool_call_id: tool.id, content: "ok" }, + ], + }, + "v1", + ); + expect(t.calls[1].body.messages[0].content[0]).toEqual(thinking); + expect(t.calls[1].body.messages[1].content[0].tool_use_id).toBe("tool_1"); + }); + it("converts base64 images, rejects unsupported audio", async () => { + const t = transport(() => json(response)); + const f = createNativeFetch(config("gemini-native"), t.fetch); + await call(f, { messages: [{ role: "user", content: [{ type: "image_url", image_url: { url: "data:image/png;base64,aGVsbG8=" } }] }] }); + expect(t.calls[0].body.contents[0].parts[0].inlineData).toEqual({ mimeType: "image/png", data: "aGVsbG8=" }); + await expect(call(f, { messages: [{ role: "user", content: [{ type: "input_audio", input_audio: {} }] }] })).rejects.toThrow(/不支持|unsupported/i); + }); + it("does not silently discard incompatible controls", async () => { + const t = transport(() => json(response)); + await expect(call(createNativeFetch(config("gemini-native"), t.fetch), { logit_bias: { "1": 1 } })).rejects.toThrow(/logit_bias/); + expect(t.calls).toHaveLength(0); + }); + it("passes abort and HTTP failures through", async () => { + const controller = new AbortController(); + const t = transport(() => new Response("denied", { status: 429 })); + const f = createNativeFetch(config("gemini-native"), t.fetch); + const r = await f("https://example.test/v1beta/chat/completions", { + method: "POST", + signal: controller.signal, + body: JSON.stringify({ model: "test", messages: [] }), + }); + expect(r.status).toBe(429); + expect(await r.text()).toBe("denied"); + expect(t.calls[0].init.signal).toBe(controller.signal); + }); + it("uses native batch embeddings and returns vectors in order", async () => { + const t = transport(() => json({ embeddings: [{ values: [1, 2] }, { values: [3, 4] }] })); + const f = createNativeFetch(config("gemini-native"), t.fetch); + const r = await f("https://example.test/v1beta/embeddings", { + method: "POST", + body: JSON.stringify({ model: "models/embed-test", input: ["one", "two"], dimensions: 2 }), + }); + expect(t.calls[0].url).toBe("https://example.test/v1beta/models/embed-test:batchEmbedContents"); + expect(t.calls[0].body.requests[0]).toMatchObject({ model: "models/embed-test", content: { parts: [{ text: "one" }] }, outputDimensionality: 2 }); + expect((await r.json()).data.map((x: any) => x.embedding)).toEqual([ + [1, 2], + [3, 4], + ]); + }); + it("uses the provider type even when an obsolete saved protocol field disagrees", async () => { + const t = transport(() => json(response)); + const f = createNativeFetch({ ...config("gemini-native"), protocol: "openai-compatible" }, t.fetch); + await call(f); + expect(t.calls[0].url).toContain(":generateContent"); + }); + it("keeps explicitly compatible Gemini gateways on their configured chat endpoint", async () => { + const t = transport(() => json({})); + const f = createNativeFetch({ ...config("gemini-native"), type: "OpenAI Compatible" }, t.fetch); + await call(f); + expect(t.calls[0].url).toBe("https://example.test/v1beta/chat/completions"); + }); + it("authenticates metadata without pretending input limit is total context", async () => { + const t = transport(() => json({ models: [{ name: "models/test", inputTokenLimit: 100 }] })); + const f = createNativeFetch(config("gemini-native"), t.fetch); + const r = await f("https://example.test/v1beta/models", { method: "GET" }); + expect(t.calls[0].init.headers.get("x-goog-api-key")).toBe("secret"); + expect((await r.json()).models[0].inputTokenLimit).toBe(100); + }); +}); + +describe("native streaming", () => { + it("streams fragmented unicode through the actual xsai consumer", async () => { + const t = transport(() => + sse( + [ + { candidates: [{ content: { parts: [{ text: "你" }] } }] }, + { + candidates: [{ content: { parts: [{ text: "好" }] }, finishReason: "STOP" }], + usageMetadata: { promptTokenCount: 1, candidatesTokenCount: 2, totalTokenCount: 3 }, + }, + ], + true, + ), + ); + const stream = await streamText({ + baseURL: "https://example.test/v1beta/", + apiKey: "secret", + model: "test", + messages: [{ role: "user", content: "hi" }], + fetch: createNativeFetch(config("gemini-native"), t.fetch), + }); + let text = ""; + for await (const chunk of stream.textStream) text += chunk; + expect(text).toBe("你好"); + expect((await stream.usage)?.total_tokens).toBe(3); + expect(t.calls[0].url).toBe("https://example.test/v1beta/models/test:streamGenerateContent?alt=sse"); + }); + it("translates Anthropic tool argument deltas and usage", async () => { + const t = transport(() => + sse( + [ + { type: "message_start", message: { id: "a", usage: { input_tokens: 4, output_tokens: 0 } } }, + { type: "content_block_start", index: 0, content_block: { type: "tool_use", id: "call-1", name: "lookup", input: {} } }, + { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: '{"q":' } }, + { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: '"你好"}' } }, + { type: "content_block_stop", index: 0 }, + { type: "message_delta", delta: { stop_reason: "tool_use" }, usage: { output_tokens: 5 } }, + { type: "message_stop" }, + ], + true, + ), + ); + const r = await call(createNativeFetch(config("anthropic-native"), t.fetch), { stream: true }, "v1"); + const chunks = (await r.text()) + .split("\n") + .filter((x) => x.startsWith("data: {")) + .map((x) => JSON.parse(x.slice(6))); + const tool = chunks.flatMap((x) => x.choices?.[0]?.delta?.tool_calls ?? [])[0]; + expect(JSON.parse(tool.function.arguments)).toEqual({ q: "你好" }); + expect(chunks.find((x) => x.usage)?.usage).toMatchObject({ prompt_tokens: 4, completion_tokens: 5 }); + }); + it("reports in-band native errors instead of successful empty output", async () => { + const t = transport(() => sse([{ error: { message: "quota exceeded" } }])); + const r = await call(createNativeFetch(config("gemini-native"), t.fetch), { stream: true }); + await expect(r.text()).rejects.toThrow(/quota exceeded/); + }); + it("rejects a truncated stream lacking its finish event", async () => { + const t = transport(() => sse([{ candidates: [{ content: { parts: [{ text: "partial" }] } }] }])); + const r = await call(createNativeFetch(config("gemini-native"), t.fetch), { stream: true }); + await expect(r.text()).rejects.toThrow(/截断|结束|finish/i); + }); + it("cancels the upstream body when the caller cancels", async () => { + let cancelled = false; + const t = transport( + () => + new Response( + new ReadableStream({ + cancel() { + cancelled = true; + }, + }), + ), + ); + const r = await call(createNativeFetch(config("gemini-native"), t.fetch), { stream: true }); + await r.body!.cancel(); + expect(cancelled).toBe(true); + }); +}); + +import { ChatModel } from "../src/model/chat-model"; +import { ModelAbility } from "../src/model/config"; +import { EmbedModel } from "../src/model/embed-model"; +import { loggingStub, stubCtx } from "./helpers/yesimbot"; + +function chatModel(protocol: string, fetch: typeof globalThis.fetch, stream: boolean) { + const c = config(protocol); + return new ChatModel( + stubCtx(), + () => ({ baseURL: c.baseURL, apiKey: c.apiKey, model: "test" }), + { modelId: "test", abilities: [ModelAbility.Chat], parameters: { stream } }, + createNativeFetch(c, fetch), + loggingStub(), + ); +} +for (const stream of [false, true]) { + it(`ChatModel returns native Gemini text and usage (${stream ? "SSE" : "JSON"})`, async () => { + const t = transport(() => (stream ? sse([response], true) : json(response))); + const model = chatModel("gemini-native", t.fetch, stream); + const result = await model.chat({ messages: [{ role: "user", content: "hello" }] }); + expect(result.text).toBe("你好"); + expect(result.usage).toMatchObject({ prompt_tokens: 4, completion_tokens: 5 }); + }); + it(`ChatModel preserves native Anthropic single-step tool execution boundary (${stream ? "SSE" : "JSON"})`, async () => { + const native = { + id: "a", + content: [{ type: "tool_use", id: "call_1", name: "lookup", input: { q: "hello" } }], + usage: { input_tokens: 3, output_tokens: 4 }, + stop_reason: "tool_use", + }; + const t = transport(() => + stream + ? sse([ + { type: "message_start", message: native }, + { type: "content_block_start", index: 0, content_block: native.content[0] }, + { type: "content_block_stop", index: 0 }, + { type: "message_delta", delta: { stop_reason: "tool_use" }, usage: native.usage }, + { type: "message_stop" }, + ]) + : json(native), + ); + let calls = 0; + const model = chatModel("anthropic-native", t.fetch, stream); + const result = await model.chat({ + singleStep: true, + messages: [{ role: "user", content: "hello" }], + tools: [ + { + type: "function", + function: { name: "lookup", parameters: { type: "object", properties: { q: { type: "string" } } } }, + execute: () => { + calls++; + return {}; + }, + }, + ], + }); + expect(result.toolCalls).toHaveLength(1); + expect(result.toolCalls[0].toolName).toBe("lookup"); + // Existing xsai execution behavior is unchanged; the native bridge itself adds no execution. + expect(calls).toBe(1); + expect(result.usage).toMatchObject({ prompt_tokens: 3, completion_tokens: 4 }); + }); +} +it("EmbedModel consumes native Gemini batch vectors", async () => { + const c = config("gemini-native"); + const t = transport(() => json({ embeddings: [{ values: [1, 2] }, { values: [3, 4] }] })); + const model = new EmbedModel( + stubCtx(), + () => ({ baseURL: c.baseURL, apiKey: c.apiKey, model: "test" }), + { modelId: "test", abilities: [ModelAbility.Embedding] }, + createNativeFetch(c, t.fetch), + loggingStub(), + ); + expect((await model.embedMany(["one", "two"])).embeddings).toEqual([ + [1, 2], + [3, 4], + ]); +}); +it("rejects simultaneous Anthropic sampling controls before sending", async () => { + const t = transport(() => json({})); + await expect(call(createNativeFetch(config("anthropic-native"), t.fetch), { temperature: 0.85, top_p: 0.95 }, "v1")).rejects.toThrow(/temperature.*top_p/); + expect(t.calls).toHaveLength(0); +}); +it("delivers a native text chunk before upstream EOF", async () => { + let close!: () => void; + const first = new TextEncoder().encode(`data: ${JSON.stringify({ candidates: [{ content: { parts: [{ text: "early" }] } }] })}\n\n`); + const t = transport( + () => + new Response( + new ReadableStream({ + start(c) { + c.enqueue(first); + close = () => { + c.enqueue(new TextEncoder().encode(`data: ${JSON.stringify({ candidates: [{ finishReason: "STOP" }] })}\n\n`)); + c.close(); + }; + }, + }), + { headers: { "content-type": "text/event-stream" } }, + ), + ); + const response = await call(createNativeFetch(config("gemini-native"), t.fetch), { stream: true }); + const reader = response.body!.getReader(); + const early = await reader.read(); + expect(new TextDecoder().decode(early.value)).toContain("early"); + close(); + while (!(await reader.read()).done) { + /* drain */ + } +}); +it("fails rather than pretending unsupported strict Gemini tool schemas are enforced", async () => { + const t = transport(() => json(response)); + await expect( + call(createNativeFetch(config("gemini-native"), t.fetch), { + tools: [{ type: "function", function: { name: "lookup", parameters: {}, strict: true } }], + }), + ).rejects.toThrow(/strict/); + expect(t.calls).toHaveLength(0); +}); +it("does not turn native malformed-function termination into success", async () => { + const t = transport(() => json({ candidates: [{ content: { parts: [{ text: "partial" }] }, finishReason: "MALFORMED_FUNCTION_CALL" }] })); + await expect(call(createNativeFetch(config("gemini-native"), t.fetch))).rejects.toThrow(/MALFORMED_FUNCTION_CALL/); +}); + +for (const stream of [false, true]) { + for (const nativeId of [undefined, "native-call-id"]) { + it(`preserves Gemini ${nativeId ? "supplied" : "absent"} native function ID on signed ${stream ? "SSE" : "JSON"} continuation`, async () => { + const nativeCall = { name: "lookup", args: { q: "x" }, ...(nativeId ? { id: nativeId } : {}) }; + const native = { candidates: [{ content: { parts: [{ functionCall: nativeCall, thoughtSignature: "signed-call" }] }, finishReason: "STOP" }] }; + const t = transport(() => (stream && t.calls.length === 1 ? sse([native], true) : json(native))); + const f = createNativeFetch(config("gemini-native"), t.fetch); + const response = await call(f, { stream }); + let tool: any; + if (stream) { + const chunks = (await response.text()) + .split("\n") + .filter((line) => line.startsWith("data: {")) + .map((line) => JSON.parse(line.slice(6))); + tool = chunks.flatMap((chunk) => chunk.choices?.[0]?.delta?.tool_calls ?? [])[0]; + } else tool = (await response.json()).choices[0].message.tool_calls[0]; + expect(typeof tool.id).toBe("string"); + expect(tool.id.length).toBeGreaterThan(0); + const continuation = await call(f, { + stream: false, + messages: [ + { role: "assistant", content: "", tool_calls: [tool] }, + { role: "tool", tool_call_id: tool.id, content: "result" }, + ], + }); + await continuation.body?.cancel(); + const payload = t.calls[1].body; + expect(payload.contents[0].parts[0]).toEqual({ functionCall: nativeCall, thoughtSignature: "signed-call" }); + expect(payload.contents[1].parts[0].functionResponse).toEqual({ + name: "lookup", + ...(nativeId ? { id: nativeId } : {}), + response: { result: "result" }, + }); + expect(Object.hasOwn(payload.contents[1].parts[0].functionResponse, "id")).toBe(nativeId !== undefined); + }); + } +} +it("assigns distinct internal IDs to identical ID-less Gemini calls without fabricating native IDs", async () => { + const part = { functionCall: { name: "lookup", args: {} }, thoughtSignature: "signed" }; + const t = transport(() => json({ candidates: [{ content: { parts: [part, part] }, finishReason: "STOP" }] })); + const f = createNativeFetch(config("gemini-native"), t.fetch); + const tools = (await (await call(f)).json()).choices[0].message.tool_calls; + expect(tools[0].id).not.toBe(tools[1].id); + await call(f, { + messages: [ + { role: "assistant", content: "", tool_calls: tools }, + ...tools.map((tool: any) => ({ role: "tool", tool_call_id: tool.id, content: "ok" })), + ], + }); + for (const part of t.calls[1].body.contents[1].parts) expect(part.functionResponse).not.toHaveProperty("id"); +}); + +for (const protocol of ["gemini-native", "anthropic-native"]) { + for (const complete of [true, false]) { + it(`ChatModel sees ${protocol} tool activity before EOF and ${complete ? "executes only after completion" : "rejects a truncated tool response"}`, async () => { + let finishSource!: () => void; + const nativeStart = + protocol === "gemini-native" + ? [{ candidates: [{ content: { parts: [{ functionCall: { name: "lookup", args: { q: "x" } }, thoughtSignature: "sig" }] } }] }] + : [ + { type: "message_start", message: { usage: { input_tokens: 1, output_tokens: 0 } } }, + { type: "content_block_start", index: 0, content_block: { type: "tool_use", id: "call-1", name: "lookup", input: {} } }, + { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: '{"q":' } }, + { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: '"x"}' } }, + ]; + const nativeFinish = + protocol === "gemini-native" + ? [{ candidates: [{ finishReason: "STOP" }] }] + : [ + { type: "content_block_stop", index: 0 }, + { type: "message_delta", delta: { stop_reason: "tool_use" }, usage: { output_tokens: 2 } }, + { type: "message_stop" }, + ]; + const encoder = new TextEncoder(); + const frame = (event: any) => encoder.encode(`data: ${JSON.stringify(event)}\n\n`); + const upstream = new Response( + new ReadableStream({ + start(controller) { + for (const event of nativeStart) controller.enqueue(frame(event)); + finishSource = () => { + if (complete) for (const event of nativeFinish) controller.enqueue(frame(event)); + controller.close(); + }; + }, + }), + { headers: { "content-type": "text/event-stream" } }, + ); + const t = transport(() => upstream); + const model = chatModel(protocol, t.fetch, true); + let starts = 0; + let executions = 0; + let notifyStarted!: () => void; + const started = new Promise((resolve) => { + notifyStarted = () => resolve(true); + }); + const pending = model.chat({ + singleStep: true, + messages: [{ role: "user", content: "hi" }], + onStreamStart: () => { + starts++; + notifyStarted(); + }, + tools: [ + { + type: "function", + function: { name: "lookup", parameters: { type: "object", properties: { q: { type: "string" } } } }, + execute: () => { + executions++; + return {}; + }, + }, + ], + }); + let observed = false; + try { + observed = await Promise.race([started, new Promise((resolve) => setTimeout(() => resolve(false), 100))]); + expect(executions).toBe(0); + } finally { + finishSource(); + } + const outcome = await pending.then( + (result) => ({ result, error: null }), + (error) => ({ result: null, error }), + ); + expect(outcome.error === null).toBe(complete); + expect(outcome.result?.toolCalls?.length ?? 0).toBe(complete ? 1 : 0); + expect(executions).toBe(complete ? 1 : 0); + expect(outcome.error === null ? "" : String(outcome.error)).toMatch(complete ? /^$/ : /失败|截断|结束|EOF/); + expect(observed).toBe(true); + expect(starts).toBe(1); + }); + } +} + +for (const protocol of ["gemini-native", "anthropic-native"]) { + for (const kind of ["text", "image_url", "input_audio"]) { + it(`${protocol} ${kind === "text" || (protocol === "anthropic-native" && kind === "image_url") ? "translates" : "rejects"} ${kind} tool result parts`, async () => { + const t = transport(() => + protocol === "gemini-native" ? json(response) : json({ content: [{ type: "text", text: "ok" }], stop_reason: "end_turn", usage: {} }), + ); + const f = createNativeFetch(config(protocol), t.fetch); + const content = + kind === "text" + ? [ + { type: "text", text: "one" }, + { type: "text", text: "two" }, + ] + : kind === "image_url" + ? [{ type: "image_url", image_url: { url: "data:image/png;base64,aGVsbG8=" } }] + : [{ type: "input_audio", input_audio: { data: "aGVsbG8=", format: "wav" } }]; + const request = call( + f, + { + messages: [ + { + role: "assistant", + content: "", + tool_calls: [{ id: "native-call", type: "function", function: { name: "lookup", arguments: "{}" } }], + }, + { role: "tool", tool_call_id: "native-call", content }, + ], + }, + protocol === "gemini-native" ? "v1beta" : "v1", + ); + const shouldReject = kind === "input_audio" || (protocol === "gemini-native" && kind === "image_url"); + const error = await request.then( + () => null, + (error) => error, + ); + expect(error === null).toBe(!shouldReject); + expect(error === null ? "" : String(error)).toMatch(shouldReject ? /不支持/ : /^$/); + expect(t.calls).toHaveLength(shouldReject ? 0 : 1); + const payload = t.calls[0]?.body; + const actual = protocol === "gemini-native" ? payload?.contents[1].parts[0].functionResponse.response : payload?.messages[1].content[0].content; + const expected = shouldReject + ? undefined + : protocol === "gemini-native" + ? { result: "onetwo" } + : kind === "text" + ? content + : [{ type: "image", source: { type: "base64", media_type: "image/png", data: "aGVsbG8=" } }]; + expect(actual).toEqual(expected); + }); + } +} +it("preserves raw caller-supplied Gemini tool IDs on both sides of a continuation", async () => { + const t = transport(() => json(response)); + const f = createNativeFetch(config("gemini-native"), t.fetch); + await call(f, { + messages: [ + { role: "assistant", content: "", tool_calls: [{ id: "raw-call-id", type: "function", function: { name: "lookup", arguments: '{"q":"x"}' } }] }, + { role: "tool", tool_call_id: "raw-call-id", content: "ok" }, + ], + }); + expect(t.calls[0].body.contents[0].parts[0].functionCall).toEqual({ id: "raw-call-id", name: "lookup", args: { q: "x" } }); + expect(t.calls[0].body.contents[1].parts[0].functionResponse.id).toBe("raw-call-id"); +}); + +for (const protocol of ["gemini-native", "anthropic-native"]) { + for (const stream of [false, true]) { + for (const reason of protocol === "gemini-native" ? ["MAX_TOKENS", "SAFETY", undefined] : ["max_tokens", "refusal", "pause_turn"]) { + it(`ChatModel never executes ${protocol} tool data after ${String(reason)} (${stream ? "SSE" : "JSON"})`, async () => { + const gemini = { + candidates: [ + { content: { parts: [{ functionCall: { name: "lookup", args: { q: "partial" } } }] }, ...(reason ? { finishReason: reason } : {}) }, + ], + }; + const anthropic = { + content: [{ type: "tool_use", id: "native-call", name: "lookup", input: { q: "partial" } }], + stop_reason: reason, + usage: {}, + }; + const events = + protocol === "gemini-native" + ? [gemini] + : [ + { type: "message_start", message: { usage: {} } }, + { type: "content_block_start", index: 0, content_block: anthropic.content[0] }, + { type: "content_block_stop", index: 0 }, + { type: "message_delta", delta: { stop_reason: reason }, usage: {} }, + { type: "message_stop" }, + ]; + const t = transport(() => (stream ? sse(events) : json(protocol === "gemini-native" ? gemini : anthropic))); + const model = chatModel(protocol, t.fetch, stream); + let executions = 0; + await expect( + model.chat({ + singleStep: true, + messages: [{ role: "user", content: "hi" }], + tools: [ + { + type: "function", + function: { name: "lookup", parameters: { type: "object", properties: { q: { type: "string" } } } }, + execute: () => { + executions++; + return {}; + }, + }, + ], + }), + ).rejects.toThrow(/./); + expect(executions).toBe(0); + expect(t.calls).toHaveLength(1); + }); + } + } +} diff --git a/packages/core/tests/native-qwen.spec.ts b/packages/core/tests/native-qwen.spec.ts new file mode 100644 index 000000000..440d42f0d --- /dev/null +++ b/packages/core/tests/native-qwen.spec.ts @@ -0,0 +1,508 @@ +import { expect, it } from "vitest"; + +import { ChatModel } from "../src/model/chat-model"; +import { ModelAbility } from "../src/model/config"; +import { createQwenFetch } from "../src/model/native/qwen"; +import { loggingStub, stubCtx } from "./helpers/yesimbot"; +const cfg = { + type: "Qwen", + name: "qwen", + apiKey: "key", + baseURL: "https://qwen.test/prefix/api/v1/", + models: [{ modelId: "vision-custom-name", abilities: [ModelAbility.Chat, ModelAbility.Vision] }], +} as any; +const terminal = { + output: { choices: [{ message: { role: "assistant", content: "你好" }, finish_reason: "stop" }] }, + usage: { input_tokens: 4, output_tokens: 2, total_tokens: 6 }, + request_id: "req", +}; +function fixture(reply: () => Response) { + const calls: any[] = []; + const f = createQwenFetch(cfg, (async (url: any, init: any) => { + calls.push({ url: String(url), init, body: init?.body && JSON.parse(init.body) }); + return reply(); + }) as any); + return { f, calls }; +} +const call = (f: typeof fetch, extra: any = {}) => + f(`${cfg.baseURL}chat/completions`, { method: "POST", body: JSON.stringify({ model: "test", messages: [{ role: "user", content: "hi" }], ...extra }) }); +function sse(events: any[]) { + return new Response(events.map((x) => `data: ${JSON.stringify(x)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); +} +it("uses native DashScope text generation and parameters", async () => { + const { f, calls } = fixture(() => Response.json(terminal)); + const result = await (await call(f, { temperature: 0.8, max_tokens: 20 })).json(); + expect(calls[0].url).toBe(`${cfg.baseURL}services/aigc/text-generation/generation`); + expect(calls[0].body).toMatchObject({ + model: "test", + input: { messages: [{ role: "user", content: "hi" }] }, + parameters: { result_format: "message", incremental_output: true, temperature: 0.8, max_tokens: 20 }, + }); + expect(calls[0].init.headers.get("authorization")).toBe("Bearer key"); + expect(result.choices[0].message.content).toBe("你好"); + expect(result.usage).toMatchObject({ prompt_tokens: 4, completion_tokens: 2, total_tokens: 6 }); +}); +it("routes visual models by declared ability and converts image parts", async () => { + const { f, calls } = fixture(() => Response.json(terminal)); + await call(f, { + model: "vision-custom-name", + messages: [ + { + role: "user", + content: [ + { type: "text", text: "look" }, + { type: "image_url", image_url: { url: "https://image.test/x.png" } }, + ], + }, + ], + }); + expect(calls[0].url).toBe(`${cfg.baseURL}services/aigc/multimodal-generation/generation`); + expect(calls[0].body.input.messages[0].content).toEqual([{ text: "look" }, { image: "https://image.test/x.png" }]); + await expect( + call(f, { + model: "qwen-vl-guessed-name", + messages: [{ role: "user", content: [{ type: "image_url", image_url: { url: "https://image.test/x.png" } }] }], + }), + ).rejects.toThrow(/视觉|图片/); +}); +it("orders native embedding vectors and preserves actual input tokens", async () => { + const { f, calls } = fixture(() => + Response.json({ + output: { + embeddings: [ + { text_index: 1, embedding: [2] }, + { text_index: 0, embedding: [1] }, + ], + }, + usage: { total_tokens: 5 }, + }), + ); + const out = await ( + await f(`${cfg.baseURL}embeddings`, { method: "POST", body: JSON.stringify({ model: "embed", input: ["a", "b"], dimensions: 1 }) }) + ).json(); + expect(calls[0].url).toBe(`${cfg.baseURL}services/embeddings/text-embedding/text-embedding`); + expect(calls[0].body).toEqual({ model: "embed", input: { texts: ["a", "b"] }, parameters: { dimension: 1 } }); + expect(out.data.map((x: any) => x.embedding)).toEqual([[1], [2]]); + expect(out.usage.prompt_tokens).toBe(5); +}); +it("preserves tool IDs/results and rejects media tool responses", async () => { + const { f, calls } = fixture(() => Response.json(terminal)); + const messages = [ + { role: "assistant", content: "", tool_calls: [{ id: "call1", type: "function", function: { name: "lookup", arguments: "{}" } }] }, + { role: "tool", tool_call_id: "call1", content: [{ type: "text", text: "ok" }] }, + ]; + await call(f, { messages }); + expect(calls[0].body.input.messages[1]).toEqual({ role: "tool", tool_call_id: "call1", content: "ok" }); + await expect(call(f, { messages: [{ ...messages[1], content: [{ type: "input_audio" }] }] })).rejects.toThrow(/不支持/); +}); +it("passes HTTP failures and rejects native business errors", async () => { + const fail = fixture(() => new Response("rate limited", { status: 429 })); + expect((await call(fail.f)).status).toBe(429); + const native = fixture(() => Response.json({ code: "InvalidParameter", message: "bad" })); + await expect(call(native.f)).rejects.toThrow(/InvalidParameter/); +}); +it("authenticates native model metadata without changing root", async () => { + const { f, calls } = fixture(() => Response.json({ data: [{ id: "test", context_length: 10 }] })); + expect((await (await f(`${cfg.baseURL}models`, { method: "GET" })).json()).data[0].context_length).toBe(10); + expect(calls[0].url).toBe(`${cfg.baseURL}models`); + expect(calls[0].init.headers.get("authorization")).toBe("Bearer key"); +}); +for (const stream of [false, true]) { + it(`ChatModel consumes native Qwen ${stream ? "SSE" : "JSON"}`, async () => { + const { f } = fixture(() => (stream ? sse([terminal]) : Response.json(terminal))); + const model = new ChatModel( + stubCtx(), + () => ({ model: "test", baseURL: cfg.baseURL }), + { modelId: "test", abilities: [ModelAbility.Chat], parameters: { stream } }, + f, + loggingStub(), + ); + const result = await model.chat({ messages: [{ role: "user", content: "hi" }] }); + expect(result.text).toBe("你好"); + expect(result.usage?.total_tokens).toBe(6); + }); + for (const reason of ["tool_calls", "length", "content_filter"]) + it(`ChatModel only executes complete Qwen tools (${stream}, ${reason})`, async () => { + const tool = { id: "call1", type: "function", function: { name: "lookup", arguments: '{"q":"x"}' } }; + const native = { output: { choices: [{ finish_reason: reason, message: { content: "", tool_calls: [tool] } }] }, usage: terminal.usage }; + const { f, calls } = fixture(() => + stream + ? sse([ + { + output: { + choices: [ + { + finish_reason: "null", + message: { content: "", tool_calls: [{ index: 0, ...tool, function: { name: "lookup", arguments: '{"q":' } }] }, + }, + ], + }, + }, + { + output: { + choices: [{ finish_reason: reason, message: { content: "", tool_calls: [{ index: 0, function: { arguments: '"x"}' } }] } }], + }, + usage: terminal.usage, + }, + ]) + : Response.json(native), + ); + let executions = 0; + const model = new ChatModel( + stubCtx(), + () => ({ model: "test", baseURL: cfg.baseURL }), + { modelId: "test", abilities: [ModelAbility.Chat], parameters: { stream } }, + f, + loggingStub(), + ); + const p = model.chat({ + singleStep: true, + messages: [{ role: "user", content: "hi" }], + tools: [ + { + type: "function", + function: { name: "lookup", parameters: {} }, + execute: () => { + executions++; + return {}; + }, + }, + ], + }); + const error = await p.then( + () => null, + (error) => error, + ); + expect(error === null).toBe(reason === "tool_calls"); + expect(executions).toBe(reason === "tool_calls" ? 1 : 0); + expect(calls[0].init.headers.get("X-DashScope-SSE")).toBe(stream ? "enable" : null); + }); +} +it("rejects SSE truncation before executable deltas", async () => { + const { f } = fixture(() => sse([{ output: { choices: [{ finish_reason: "null", message: { content: "partial" } }] } }])); + await expect((await call(f, { stream: true })).text()).rejects.toThrow(/截断|结束/); +}); +it("rejects unsupported generation controls", async () => { + const { f, calls } = fixture(() => Response.json(terminal)); + await expect(call(f, { logit_bias: { "1": 1 } })).rejects.toThrow(/logit_bias/); + expect(calls).toHaveLength(0); +}); +for (const streaming of [false, true]) + it(`preserves Qwen thinking and native IDs across tool continuation (${streaming})`, async () => { + const tool = { id: "native-id", type: "function", function: { name: "lookup", arguments: "{}" } }; + const native = { + output: { choices: [{ finish_reason: "tool_calls", message: { content: "", reasoning_content: "private-native-thought", tool_calls: [tool] } }] }, + }; + const { f, calls } = fixture(() => (streaming && calls.length === 1 ? sse([native]) : Response.json(native))); + const r = await call(f, { stream: streaming }); + const out = streaming + ? (await r.text()) + .split("\n") + .filter((x) => x.startsWith("data: {")) + .map((x) => JSON.parse(x.slice(6))) + .flatMap((x) => x.choices?.[0]?.delta?.tool_calls ?? [])[0] + : (await r.json()).choices[0].message.tool_calls[0]; + await call(f, { + preserve_thinking: true, + messages: [ + { role: "assistant", content: "", tool_calls: [out] }, + { role: "tool", tool_call_id: out.id, content: "done" }, + ], + }); + expect(calls[1].body.parameters.preserve_thinking).toBe(true); + expect(calls[1].body.input.messages[0].reasoning_content).toBe("private-native-thought"); + expect(calls[1].body.input.messages[0].tool_calls[0].id).toBe("native-id"); + expect(calls[1].body.input.messages[1].tool_call_id).toBe("native-id"); + }); +it("signals Qwen tool activity before EOF without exposing executable deltas", async () => { + let close!: () => void; + const encoder = new TextEncoder(); + const frame = (value: unknown) => encoder.encode(`data: ${JSON.stringify(value)}\n\n`); + const { f } = fixture( + () => + new Response( + new ReadableStream({ + start(c) { + c.enqueue( + frame({ + output: { + choices: [ + { + finish_reason: "null", + message: { tool_calls: [{ index: 0, id: "call1", function: { name: "lookup", arguments: "{}" } }] }, + }, + ], + }, + }), + ); + close = () => { + c.enqueue(frame({ output: { choices: [{ finish_reason: "tool_calls", message: { content: "" } }] } })); + c.close(); + }; + }, + }), + { headers: { "content-type": "text/event-stream" } }, + ), + ); + let notify!: () => void; + const started = new Promise((resolve) => { + notify = () => resolve(true); + }); + let executions = 0, + count = 0; + const model = new ChatModel( + stubCtx(), + () => ({ model: "test", baseURL: cfg.baseURL }), + { modelId: "test", abilities: [ModelAbility.Chat], parameters: { stream: true } }, + f, + loggingStub(), + ); + const pending = model.chat({ + singleStep: true, + onStreamStart: () => { + count++; + notify(); + }, + messages: [{ role: "user", content: "hi" }], + tools: [ + { + type: "function", + function: { name: "lookup", parameters: {} }, + execute: () => { + executions++; + return {}; + }, + }, + ], + }); + const observed = await Promise.race([started, new Promise((resolve) => setTimeout(() => resolve(false), 100))]); + expect(executions).toBe(0); + close(); + await pending; + expect(observed).toBe(true); + expect(count).toBe(1); + expect(executions).toBe(1); +}); +it("cancels Qwen native bodies and preserves abort signal", async () => { + let cancelled = false; + const { f, calls } = fixture( + () => + new Response( + new ReadableStream({ + cancel() { + cancelled = true; + }, + }), + ), + ); + const signal = new AbortController().signal; + const r = await f(`${cfg.baseURL}chat/completions`, { method: "POST", signal, body: JSON.stringify({ model: "test", messages: [], stream: true }) }); + await r.body!.cancel(); + expect(cancelled).toBe(true); + expect(calls[0].init.signal).toBe(signal); +}); +it("rejects Qwen in-band errors and sparse tool indices", async () => { + const fail = fixture(() => sse([{ code: "QuotaExceeded", message: "busy" }])); + await expect((await call(fail.f, { stream: true })).text()).rejects.toThrow(/QuotaExceeded/); + const sparse = fixture(() => + sse([ + { + output: { + choices: [ + { finish_reason: "tool_calls", message: { tool_calls: [{ index: 1, id: "call2", function: { name: "lookup", arguments: "{}" } }] } }, + ], + }, + }, + ]), + ); + await expect((await call(sparse.f, { stream: true })).text()).rejects.toThrow(/索引/); +}); + +it("keeps Qwen full-output and answer-only token caps distinct in native HTTP parameters", async () => { + const { f, calls } = fixture(() => Response.json(terminal)); + await call(f, { max_completion_tokens: 100 }); + expect(calls[0].body.parameters.max_completion_tokens).toBe(100); + expect(calls[0].body.parameters).not.toHaveProperty("max_tokens"); + await call(f, { max_completion_tokens: 100, max_tokens: 25 }); + expect(calls[1].body.parameters).toMatchObject({ max_completion_tokens: 100, max_tokens: 25 }); +}); +for (const streaming of [false, true]) + it(`preserves Qwen native cache and reasoning token details (${streaming})`, async () => { + const nativeUsage = { + input_tokens: 100, + output_tokens: 20, + total_tokens: 120, + cached_tokens: 1, + prompt_tokens_details: { cached_tokens: 7, cache_creation_input_tokens: 11 }, + output_tokens_details: { reasoning_tokens: 13 }, + }; + const native = { ...terminal, usage: nativeUsage }; + const { f } = fixture(() => (streaming ? sse([native]) : Response.json(native))); + const model = new ChatModel( + stubCtx(), + () => ({ model: "test", baseURL: cfg.baseURL }), + { modelId: "test", abilities: [ModelAbility.Chat], parameters: { stream: streaming } }, + f, + loggingStub(), + ); + const result = await model.chat({ messages: [{ role: "user", content: "hi" }] }); + expect(result.usage).toMatchObject({ + prompt_tokens: 100, + completion_tokens: 20, + total_tokens: 120, + prompt_tokens_details: { cached_tokens: 7, cache_write_tokens: 11 }, + completion_tokens_details: { reasoning_tokens: 13 }, + }); + }); +it("merges Qwen sparse streamed usage details without discarding earlier cache counts", async () => { + const { f } = fixture(() => + sse([ + { + output: { choices: [{ finish_reason: "null", message: { content: "你" } }] }, + usage: { input_tokens: 10, prompt_tokens_details: { cached_tokens: 3, cache_creation_input_tokens: 5 } }, + }, + { + output: { choices: [{ finish_reason: "stop", message: { content: "好" } }] }, + usage: { output_tokens: 5, prompt_tokens_details: { cache_creation_input_tokens: 8 }, output_tokens_details: { reasoning_tokens: 2 } }, + }, + ]), + ); + const frames = (await (await call(f, { stream: true })).text()) + .split("\n") + .filter((line) => line.startsWith("data: {")) + .map((line) => JSON.parse(line.slice(6))); + expect(frames.find((frame) => frame.usage)?.usage).toMatchObject({ + prompt_tokens: 10, + completion_tokens: 5, + prompt_tokens_details: { cached_tokens: 3, cache_write_tokens: 8 }, + completion_tokens_details: { reasoning_tokens: 2 }, + }); +}); +it("leaves unreported Qwen cache/reasoning counts absent and accepts legacy flat cached count", async () => { + const { f } = fixture(() => Response.json(terminal)); + const out = await (await call(f)).json(); + expect(out.usage).not.toHaveProperty("prompt_tokens_details"); + expect(out.usage).not.toHaveProperty("completion_tokens_details"); + const legacy = fixture(() => Response.json({ ...terminal, usage: { ...terminal.usage, cached_tokens: 0 } })); + expect((await (await call(legacy.f)).json()).usage.prompt_tokens_details.cached_tokens).toBe(0); +}); +for (const stream of [false, true]) { + for (const selected of ["required", { type: "function", function: { name: "lookup" } }]) { + for (const matching of [false, true]) { + it(`enforces Qwen thinking tool choice locally (${stream}, ${typeof selected}, ${matching})`, async () => { + const named = typeof selected === "object"; + const name = matching ? "lookup" : "other"; + const hasCall = matching || named; + const native = { + output: { + choices: [ + { + finish_reason: hasCall ? "tool_calls" : "stop", + message: { + content: hasCall ? "" : "no call", + ...(hasCall ? { tool_calls: [{ id: "call1", type: "function", function: { name, arguments: "{}" } }] } : {}), + }, + }, + ], + }, + }; + const { f, calls } = fixture(() => (stream ? sse([native]) : Response.json(native))); + const model = new ChatModel( + stubCtx(), + () => ({ model: "test", baseURL: cfg.baseURL }), + { modelId: "test", abilities: [ModelAbility.Chat], parameters: { stream } }, + f, + loggingStub(), + ); + let executions = 0; + const result = model.chat({ + singleStep: true, + toolChoice: selected, + enable_thinking: true, + messages: [{ role: "user", content: "hi" }], + tools: ["lookup", "other"].map((name) => ({ + type: "function", + function: { name, parameters: {} }, + execute: () => { + executions++; + return {}; + }, + })), + }); + const error = await result.then( + () => null, + (error) => error, + ); + expect(error === null).toBe(matching); + expect(executions).toBe(matching ? 1 : 0); + expect(calls[0].body.parameters.tool_choice).not.toBe("required"); + expect(typeof calls[0].body.parameters.tool_choice).not.toBe("object"); + expect(calls[0].body.parameters.enable_thinking).toBe(true); + }); + } + } +} +it("removes Qwen tools for none and rejects unsolicited native calls", async () => { + const native = { + output: { + choices: [ + { + finish_reason: "tool_calls", + message: { content: "", tool_calls: [{ id: "call1", type: "function", function: { name: "lookup", arguments: "{}" } }] }, + }, + ], + }, + }; + const { f, calls } = fixture(() => Response.json(native)); + await expect(call(f, { tool_choice: "none", tools: [{ type: "function", function: { name: "lookup", parameters: {} } }] })).rejects.toThrow(/tool_choice/); + expect(calls[0].body.parameters).not.toHaveProperty("tools"); +}); +it("preserves the first Qwen tool ID/name when official later incremental frames contain empty strings", async () => { + const { f } = fixture(() => + sse([ + { + output: { + choices: [ + { + finish_reason: "null", + message: { tool_calls: [{ index: 0, id: "original-id", type: "function", function: { name: "lookup", arguments: '{"q":' } }] }, + }, + ], + }, + }, + { + output: { + choices: [ + { finish_reason: "null", message: { tool_calls: [{ index: 0, id: "", type: "function", function: { name: "", arguments: '"x"}' } }] } }, + ], + }, + }, + { output: { choices: [{ finish_reason: "tool_calls", message: { content: "" } }] } }, + ]), + ); + const frames = (await (await call(f, { stream: true })).text()) + .split("\n") + .filter((line) => line.startsWith("data: {")) + .map((line) => JSON.parse(line.slice(6))); + expect(frames.flatMap((frame) => frame.choices?.[0]?.delta?.tool_calls ?? [])[0]).toMatchObject({ + id: "original-id", + function: { name: "lookup", arguments: '{"q":"x"}' }, + }); +}); +it("rejects conflicting nonempty Qwen tool identities in incremental frames", async () => { + const { f } = fixture(() => + sse([ + { + output: { + choices: [{ finish_reason: "null", message: { tool_calls: [{ index: 0, id: "id", function: { name: "lookup", arguments: "{}" } }] } }], + }, + }, + { + output: { + choices: [{ finish_reason: "tool_calls", message: { tool_calls: [{ index: 0, id: "id", function: { name: "changed", arguments: "" } }] } }], + }, + }, + ]), + ); + await expect((await call(f, { stream: true })).text()).rejects.toThrow(/名称/); +}); diff --git a/packages/core/tests/native-workers.spec.ts b/packages/core/tests/native-workers.spec.ts new file mode 100644 index 000000000..6988cf8bd --- /dev/null +++ b/packages/core/tests/native-workers.spec.ts @@ -0,0 +1,334 @@ +import { describe, expect, it } from "vitest"; + +import { ChatModel } from "../src/model/chat-model"; +import { ModelAbility } from "../src/model/config"; +import { createWorkersFetch } from "../src/model/native/workers"; +import { loggingStub, stubCtx } from "./helpers/yesimbot"; +const root = "https://example.test/accounts/acct/ai/"; +const config = { type: "Workers AI", apiKey: "secret", accountId: "acct", baseURL: root } as any; +const call = (f: typeof fetch, body: any = {}, path = "chat/completions") => + f(root + path, { method: "POST", body: JSON.stringify({ model: "@cf/vendor/model", messages: [{ role: "user", content: "hi" }], ...body }) }); +function setup(response: () => Response) { + const calls: any[] = []; + return { + calls, + fetch: createWorkersFetch(config, (async (url, init) => { + calls.push({ url: String(url), init, body: init?.body && JSON.parse(String(init.body)) }); + return response(); + }) as typeof fetch), + }; +} +const sse = (values: any[], done = true) => + new Response(values.map((v) => `data: ${JSON.stringify(v)}\n\n`).join("") + (done ? "data: [DONE]\n\n" : ""), { + headers: { "content-type": "text/event-stream" }, + }); +describe("Workers AI native", () => { + it("uses model run route and native functions", async () => { + const t = setup(() => Response.json({ success: true, result: { response: "", tool_calls: [{ name: "lookup", arguments: { q: "x" } }] } })); + const r = await (await call(t.fetch, { tools: [{ type: "function", function: { name: "lookup", parameters: {} } }] })).json(); + expect(t.calls[0].url).toBe(root + "run/@cf/vendor/model"); + expect(t.calls[0].body.tools).toEqual([{ name: "lookup", parameters: {} }]); + expect(t.calls[0].body.model).toBeUndefined(); + expect(r.choices[0].message.tool_calls[0].function).toEqual({ name: "lookup", arguments: '{"q":"x"}' }); + }); + it("maps native embeddings and rejects missing vectors", async () => { + const t = setup(() => + Response.json({ + success: true, + result: { + shape: [2, 2], + data: [ + [1, 2], + [3, 4], + ], + }, + }), + ); + const out = await (await call(t.fetch, { input: ["one", "two"], messages: undefined }, "embeddings")).json(); + expect(t.calls[0].body).toEqual({ text: ["one", "two"] }); + expect(out.data[1].embedding).toEqual([3, 4]); + const bad = setup(() => Response.json({ result: { data: [[1, 2]] }, success: true })); + await expect(call(bad.fetch, { input: ["one", "two"], messages: undefined }, "embeddings")).rejects.toThrow(/./); + }); + for (const stream of [false, true]) + it(`works through ChatModel (${stream})`, async () => { + const t = setup(() => + stream + ? sse([{ response: "你好" }, { response: null, usage: { prompt_tokens: 2, completion_tokens: 3, total_tokens: 5 } }]) + : Response.json({ result: { response: "你好", usage: { prompt_tokens: 2, completion_tokens: 3, total_tokens: 5 } }, success: true }), + ); + const model = new ChatModel( + stubCtx(), + () => ({ model: "@cf/vendor/model", baseURL: root, apiKey: "secret" }), + { modelId: "@cf/vendor/model", abilities: [ModelAbility.Chat], parameters: { stream } }, + t.fetch, + loggingStub(), + ); + const out = await model.chat({ messages: [{ role: "user", content: "hi" }] }); + expect(out.text).toBe("你好"); + expect(out.usage?.total_tokens).toBe(5); + }); + for (const tail of ["", 'data: {"error":{"message":"failed"}}\n\n', "data: broken\n\n"]) + it(`withholds tools for failed/truncated stream ${tail}`, async () => { + const t = setup(() => new Response('data: {"tool_calls":[{"name":"lookup","arguments":{}}]}\n\n' + tail)); + const response = await call(t.fetch, { stream: true }); + const reader = response.body!.getReader(); + let text = ""; + await expect( + (async () => { + while (true) { + const v = await reader.read(); + if (v.done) break; + text += new TextDecoder().decode(v.value); + } + })(), + ).rejects.toThrow(/./); + expect(text).not.toContain('"tool_calls"'); + expect(text).toContain("yib_native_activity"); + }); + it("preserves auth signal and HTTP errors", async () => { + const signal = new AbortController().signal; + const t = setup(() => new Response("quota", { status: 429 })); + const r = await t.fetch(root + "chat/completions", { method: "POST", signal, body: JSON.stringify({ model: "@cf/a/b", messages: [] }) }); + expect(r.status).toBe(429); + expect(t.calls[0].init.signal).toBe(signal); + expect(t.calls[0].init.headers.get("authorization")).toBe("Bearer secret"); + }); + it("rejects API envelope failure and malformed native tools", async () => { + await expect(call(setup(() => Response.json({ success: false, errors: [{ message: "denied" }] })).fetch)).rejects.toThrow(/denied/); + await expect( + call(setup(() => Response.json({ success: true, result: { tool_calls: [{ name: "lookup", arguments: "broken" }] } })).fetch), + ).rejects.toThrow(/./); + }); +}); + +for (const stream of [false, true]) { + it(`Workers ChatModel executes complete native tool only after valid completion (${stream})`, async () => { + const native = { response: "", tool_calls: [{ name: "lookup", arguments: { q: "hello" } }] }; + const t = setup(() => (stream ? sse([native]) : Response.json({ success: true, result: native }))); + let calls = 0; + const model = new ChatModel( + stubCtx(), + () => ({ model: "@cf/vendor/model", baseURL: root, apiKey: "secret" }), + { modelId: "@cf/vendor/model", abilities: [ModelAbility.Chat], parameters: { stream } }, + t.fetch, + loggingStub(), + ); + const result = await model.chat({ + singleStep: true, + messages: [{ role: "user", content: "hello" }], + tools: [ + { + type: "function", + function: { name: "lookup", parameters: { type: "object", properties: { q: { type: "string" } } } }, + execute: () => { + calls++; + return {}; + }, + }, + ], + }); + expect(result.toolCalls).toHaveLength(1); + expect(result.toolCalls[0].toolName).toBe("lookup"); + expect(calls).toBe(1); + }); +} +it("Workers ChatModel never executes buffered tool on truncated stream", async () => { + const t = setup(() => sse([{ tool_calls: [{ name: "lookup", arguments: {} }] }], false)); + let calls = 0; + const model = new ChatModel( + stubCtx(), + () => ({ model: "@cf/vendor/model", baseURL: root, apiKey: "secret" }), + { modelId: "@cf/vendor/model", abilities: [ModelAbility.Chat], parameters: { stream: true } }, + t.fetch, + loggingStub(), + ); + await expect( + model.chat({ + singleStep: true, + messages: [{ role: "user", content: "hello" }], + tools: [ + { + type: "function", + function: { name: "lookup", parameters: {} }, + execute: () => { + calls++; + return {}; + }, + }, + ], + }), + ).rejects.toThrow(/网络请求失败|截断/); + expect(calls).toBe(0); +}); +it("Workers delivers early activity before terminal and releases tool only at clean EOF", async () => { + let finish!: () => void; + const t = setup( + () => + new Response( + new ReadableStream({ + start(c) { + c.enqueue(new TextEncoder().encode('data: {"tool_calls":[{"name":"lookup","arguments":{}}]}\n\n')); + finish = () => { + c.enqueue(new TextEncoder().encode("data: [DONE]\n\n")); + c.close(); + }; + }, + }), + ), + ); + const response = await call(t.fetch, { stream: true }); + const reader = response.body!.getReader(); + const first = new TextDecoder().decode((await reader.read()).value); + expect(first).toContain("yib_native_activity"); + expect(first).not.toContain('"tool_calls"'); + finish(); + let tail = ""; + while (true) { + const next = await reader.read(); + if (next.done) break; + tail += new TextDecoder().decode(next.value); + } + expect(tail).toContain('"tool_calls"'); +}); +it("Workers cancellation reaches native stream", async () => { + let cancelled = false; + const t = setup( + () => + new Response( + new ReadableStream({ + cancel() { + cancelled = true; + }, + }), + ), + ); + const r = await call(t.fetch, { stream: true }); + await r.body!.cancel(); + await Promise.resolve(); + expect(cancelled).toBe(true); +}); + +it("Workers native bridge crosses a real local HTTP boundary with fragmented unicode SSE", async () => { + const { createServer } = await import("node:http"); + const { once } = await import("node:events"); + let requestPath = ""; + let requestBody: any; + const server = createServer(async (req, res) => { + requestPath = req.url!; + let text = ""; + for await (const chunk of req) text += chunk; + requestBody = JSON.parse(text); + res.writeHead(200, { "content-type": "text/event-stream" }); + const bytes = Buffer.from( + requestBody.tools ? 'data: {"tool_calls":[{"name":"lookup","arguments":{}}]}\n\ndata: [DONE]\n\n' : 'data: {"response":"你好"}\n\ndata: [DONE]\n\n', + ); + for (const byte of bytes) res.write(Buffer.from([byte])); + res.end(); + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const address = server.address() as { port: number }; + const localRoot = `http://127.0.0.1:${address.port}/accounts/acct/ai/`; + try { + const { request } = await import("node:http"); + const { Readable } = await import("node:stream"); + const localTransport = ((url: any, init: any) => + new Promise((resolve, reject) => { + if (new URL(String(url)).hostname !== "127.0.0.1") return reject(new Error("Local test transport only")); + const req = request(String(url), { method: init.method, headers: Object.fromEntries(init.headers), signal: init.signal }, (res) => + resolve(new Response(Readable.toWeb(res) as ReadableStream, { status: res.statusCode })), + ); + req.on("error", reject); + req.end(init.body); + })) as typeof fetch; + const f = createWorkersFetch({ ...config, baseURL: localRoot }, localTransport); + const response = await f(localRoot + "chat/completions", { + method: "POST", + body: JSON.stringify({ model: "@cf/vendor/model", messages: [{ role: "user", content: "hello" }], stream: true }), + }); + expect(await response.text()).toContain("你好"); + expect(requestPath).toBe("/accounts/acct/ai/run/@cf/vendor/model"); + expect(requestBody).toEqual({ messages: [{ role: "user", content: "hello" }], stream: true }); + const requiredResponse = await f(localRoot + "chat/completions", { + method: "POST", + body: JSON.stringify({ + model: "@cf/vendor/model", + messages: [{ role: "user", content: "hello" }], + stream: true, + tool_choice: "required", + tools: [{ type: "function", function: { name: "lookup", parameters: {} } }], + }), + }); + expect(await requiredResponse.text()).toContain('"name":"lookup"'); + expect(requestBody).not.toHaveProperty("tool_choice"); + expect(requestBody.tools).toEqual([{ name: "lookup", parameters: {} }]); + } finally { + server.closeAllConnections(); + await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve()))); + } +}); + +it("Workers rejects an in-band JSON error even when HTTP status is successful", async () => { + const t = setup(() => Response.json({ error: { message: "quota exceeded" }, response: "" })); + await expect(call(t.fetch)).rejects.toThrow(/quota exceeded/); +}); + +for (const stream of [false, true]) { + for (const selected of ["required", { type: "function", function: { name: "lookup" } }] as const) { + for (const returned of ["lookup", "other", "none"]) { + it(`Workers locally enforces ${JSON.stringify(selected)} before ChatModel tool execution (${stream}, ${returned})`, async () => { + const native = { + response: returned === "none" ? "no tool" : "", + ...(returned === "none" ? {} : { tool_calls: [{ name: returned, arguments: {} }] }), + }; + const t = setup(() => (stream ? sse([native]) : Response.json({ success: true, result: native }))); + let calls = 0; + const model = new ChatModel( + stubCtx(), + () => ({ model: "@cf/vendor/model", baseURL: root, apiKey: "secret" }), + { modelId: "@cf/vendor/model", abilities: [ModelAbility.Chat], parameters: { stream } }, + t.fetch, + loggingStub(), + ); + const request = model.chat({ + singleStep: true, + messages: [{ role: "user", content: "hello" }], + toolChoice: selected, + tools: ["lookup", "other"].map((name) => ({ + type: "function" as const, + function: { name, parameters: {} }, + execute: () => { + calls++; + return {}; + }, + })), + }); + const rejected = returned === "none" || (typeof selected !== "string" && returned !== "lookup"); + const outcome = await request.then( + (value) => ({ toolCalls: value.toolCalls.length, error: "" }), + (error) => ({ toolCalls: 0, error: String(error) }), + ); + expect(outcome.toolCalls).toBe(rejected ? 0 : 1); + expect(outcome.error).toMatch(rejected ? /tool_choice|网络请求失败/ : /^$/); + expect(calls).toBe(rejected ? 0 : 1); + expect(t.calls).toHaveLength(1); + expect(t.calls[0].body).not.toHaveProperty("tool_choice"); + }); + } + } + it(`Workers tool_choice none removes native tools and rejects unsolicited calls (${stream})`, async () => { + const native = { response: "", tool_calls: [{ name: "lookup", arguments: {} }] }; + const t = setup(() => (stream ? sse([native]) : Response.json({ success: true, result: native }))); + const response = call(t.fetch, { stream, tool_choice: "none", tools: [{ type: "function", function: { name: "lookup", parameters: {} } }] }); + const error = await response + .then((value) => value.text()) + .then( + () => "", + (error) => String(error), + ); + expect(error).toMatch(/tool_choice/); + expect(t.calls[0].body).not.toHaveProperty("tools"); + expect(t.calls[0].body).not.toHaveProperty("tool_choice"); + }); +} diff --git a/packages/core/tests/provider-config.spec.ts b/packages/core/tests/provider-config.spec.ts new file mode 100644 index 000000000..9e2f3f49b --- /dev/null +++ b/packages/core/tests/provider-config.spec.ts @@ -0,0 +1,156 @@ +import { describe, expect, it } from "vitest"; + +import { ProviderConfigSchema, PROVIDER_TYPES } from "../src/model/config"; +import { ProviderFactoryRegistry } from "../src/model/factories"; +import { createNativeFetch } from "../src/model/native-fetch"; +import { ProviderInstance } from "../src/model/provider-instance"; + +const config = (type: string, extra: Record = {}) => ProviderConfigSchema({ name: "test", type, models: [], ...extra }); + +describe("provider configuration", () => { + it("selects native Gemini and Anthropic by provider type without a protocol selector", () => { + expect(config("Google Gemini").baseURL).toBe("https://generativelanguage.googleapis.com/v1beta/"); + expect(config("Anthropic").baseURL).toBe("https://api.anthropic.com/v1/"); + expect(config("Google Gemini").protocol).toBeUndefined(); + expect(config("Anthropic").protocol).toBeUndefined(); + expect(config("Google Gemini", { baseURL: "https://gateway.example/custom/" }).baseURL).toBe("https://gateway.example/custom/"); + }); + it("offers compatible routing through the explicit compatible provider", () => { + const value = config("OpenAI Compatible", { baseURL: "https://gateway.example/openai/" }); + expect(value.baseURL).toBe("https://gateway.example/openai/"); + }); + it("does not inject incompatible sampling defaults for Anthropic", () => { + const native = config("Anthropic", { models: [{ modelId: "claude" }] }); + expect(native.models[0].parameters?.temperature).toBeUndefined(); + expect(native.models[0].parameters?.topP).toBeUndefined(); + const compatible = config("OpenAI Compatible", { models: [{ modelId: "claude" }] }); + expect(compatible.models[0].parameters?.temperature).toBe(0.85); + }); + it("uses native factory roots when programmatic configs omit baseURL", () => { + for (const [type, expected] of [ + ["Google Gemini", "https://generativelanguage.googleapis.com/v1beta/"], + ["Anthropic", "https://api.anthropic.com/v1/"], + ] as const) { + const client = ProviderFactoryRegistry.get(type)!.createClient({ name: "test", type, apiKey: "test", models: [] }); + expect(client.chat!("test").baseURL).toBe(expected); + } + }); + it("uses dedicated Ollama and Qwen roots rather than compatibility paths", () => { + expect(config("Ollama").baseURL).toBe("http://localhost:11434/"); + expect(config("Qwen").baseURL).toBe("https://dashscope.aliyuncs.com/api/v1/"); + }); + it("disables unsupported LM Studio native function calling by default", () => { + const value = config("LM Studio", { models: [{ modelId: "local" }] }); + expect(value.models[0].disableNativeToolCalling).toBe(true); + expect(value.models[0].abilities).not.toContain("函数调用"); + }); + it("keeps legacy LM Studio models on JSON actions when client tools cannot be represented", () => { + const value = config("LM Studio", { models: [{ modelId: "local", disableNativeToolCalling: false }] }); + const client = ProviderFactoryRegistry.get(value.type)!.createClient(value); + const logger = { debug() {}, info() {}, warn() {}, error() {} }; + const instance = new ProviderInstance({ yesimbot: {} } as any, value, client, { getLogger: () => logger } as any); + expect(instance.getChatModel("local")?.config.disableNativeToolCalling).toBe(true); + }); + it("requires a Cloudflare account ID and preserves it for the factory", () => { + expect(() => config("Workers AI")).toThrow(/expected|required/); + const value = config("Workers AI", { apiKey: "test-key", accountId: "account123" }); + expect(value.accountId).toBe("account123"); + const client = ProviderFactoryRegistry.get(value.type)!.createClient(value); + expect(client.chat!("test").baseURL).toContain("accounts/account123/"); + }); + it("uses current presets for new local and MiniMax providers", () => { + expect(config("LM Studio").baseURL).toBe("http://localhost:1234/"); + expect(config("Minimax").baseURL).toBe("https://api.minimax.cn/v1/"); + expect(config("Minimax (International)").baseURL).toBe("https://api.minimax.io/v1/"); + }); + it("supports the corrected Featherless name and the existing saved key", () => { + for (const type of ["Featherless AI", "Fatherless AI"]) { + const value = config(type); + expect(value.baseURL).toBe("https://api.featherless.ai/v1/"); + expect(ProviderFactoryRegistry.get(value.type)?.createClient(value).chat).toBeTypeOf("function"); + } + }); + it("routes each dedicated provider through its real native endpoint without a protocol setting", async () => { + const cases = [ + ["Google Gemini", "test", "/v1beta/models/test:generateContent"], + ["Anthropic", "test", "/v1/messages"], + ["Ollama", "test", "/api/chat"], + ["Qwen", "test", "/api/v1/services/aigc/text-generation/generation"], + ["Workers AI", "@cf/meta/test", "/client/v4/accounts/account123/ai/run/@cf/meta/test"], + ["LM Studio", "test", "/api/v1/chat"], + ] as const; + for (const [type, model, path] of cases) { + const value = config(type, { accountId: "account123", models: [{ modelId: model }] }); + const client = ProviderFactoryRegistry.get(value.type)!.createClient(value); + const options = client.chat!(model); + let sent: URL | undefined; + const transport = (async (url: RequestInfo | URL) => { + sent = new URL(String(url)); + return new Response("test rejection", { status: 429 }); + }) as typeof fetch; + const response = await createNativeFetch(value, transport)(new URL("chat/completions", options.baseURL), { + method: "POST", + body: JSON.stringify({ model, messages: [{ role: "user", content: "hi" }] }), + }); + expect(response.status).toBe(429); + expect(sent?.pathname).toBe(path); + } + }); + it.each([ + [ + "Google Gemini", + "https://generativelanguage.googleapis.com/v1beta/openai/", + "https://generativelanguage.googleapis.com/v1beta/models/test:generateContent", + ], + ["Qwen", "https://dashscope.aliyuncs.com/compatible-mode/v1/", "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation"], + ["Ollama", "http://localhost:11434/v1/", "http://localhost:11434/api/chat"], + ])("migrates saved %s official compatibility roots before sending native requests", async (type, oldRoot, expected) => { + for (const baseURL of [oldRoot, oldRoot.slice(0, -1)]) { + const value = config(type, { baseURL }); + const options = ProviderFactoryRegistry.get(value.type)!.createClient(value).chat!("test"); + let sent: string | undefined; + const transport = (async (url: RequestInfo | URL) => { + sent = String(url); + return new Response("test rejection", { status: 429 }); + }) as typeof fetch; + await createNativeFetch(value, transport)(new URL("chat/completions", options.baseURL), { + method: "POST", + body: JSON.stringify({ model: "test", messages: [{ role: "user", content: "hi" }] }), + }); + expect(sent).toBe(expected); + expect(config(type, { baseURL: value.baseURL }).baseURL).toBe(value.baseURL); + } + }); + it.each([ + ["Google Gemini", "https://generativelanguage.googleapis.com/v1beta/"], + ["Qwen", "https://dashscope.aliyuncs.com/api/v1/"], + ["Ollama", "http://localhost:11434/"], + ["Google Gemini", "https://gateway.example/v1beta/openai/"], + ["Qwen", "https://gateway.example/compatible-mode/v1/"], + ["Ollama", "http://custom-host:11434/v1/"], + ["Google Gemini", "https://generativelanguage.googleapis.com/custom/v1beta/openai/"], + ["Qwen", "https://dashscope.aliyuncs.com/compatible-mode/v1/?custom=1"], + ["Ollama", "http://localhost:11434/custom/v1/"], + ["LM Studio", "http://localhost:1234/v1/"], + ])("preserves explicit native or custom %s roots: %s", (type, baseURL) => { + expect(config(type, { baseURL }).baseURL).toBe(baseURL); + }); + it.each(["https://generativelanguage.googleapis.com/v1beta/openai/", "https://dashscope.aliyuncs.com/compatible-mode/v1/", "http://localhost:11434/v1/"])( + "preserves explicit OpenAI Compatible routing at %s", + async (baseURL) => { + const value = config("OpenAI Compatible", { baseURL }); + expect(value.baseURL).toBe(baseURL); + const options = ProviderFactoryRegistry.get(value.type)!.createClient(value).chat!("test"); + let sent: string | undefined; + const transport = (async (url: RequestInfo | URL) => { + sent = String(url); + return new Response("test rejection", { status: 429 }); + }) as typeof fetch; + await createNativeFetch(value, transport)(new URL("chat/completions", options.baseURL), { method: "POST" }); + expect(sent).toBe(`${baseURL}chat/completions`); + }, + ); + it("has a factory for every visible provider preset", () => { + for (const type of PROVIDER_TYPES) expect(ProviderFactoryRegistry.get(type)).toBeDefined(); + }); +}); diff --git a/packages/core/tests/reply-turn.spec.ts b/packages/core/tests/reply-turn.spec.ts index 4e91dcc66..23232548e 100644 --- a/packages/core/tests/reply-turn.spec.ts +++ b/packages/core/tests/reply-turn.spec.ts @@ -2,6 +2,89 @@ import { Bot, Context, MessageEncoder, Universal } from "koishi"; import { expect, it } from "vitest"; import { withReplyTurn, withReplyTurnGuard, assertReplyTurn, guardReplySession } from "../src/agent/reply-turn"; + +it("retains confirmed encoder deliveries when a later request fails without retrying", async () => { + const ctx = new Context(); + const failure = new Error("second request failed"); + let attempts = 0; + class Encoder extends MessageEncoder { + async visit() { + attempts++; + this.results.push({ id: "confirmed", content: "first" }, { id: "" }, { id: " " }, { id: 42 } as any); + this.errors.push(failure); + } + async flush() {} + } + class SendingBot extends Bot { + static MessageEncoder = Encoder; + } + const bot = new SendingBot(ctx, {} as any, "qq"); + bot.user = { id: "bot" }; + const session = bot.session({ channel: { id: "group" } }); + const error = await withReplyTurn( + () => true, + () => guardReplySession(session).bot.sendMessage("group", "reply"), + ).catch((error) => error); + expect(error.messages).toEqual([{ id: "confirmed", content: "first" }]); + expect(error.cause.errors).toEqual([failure]); + expect(attempts).toBe(1); + await ctx.stop(); +}); + +it("preserves the original encoder failure when nothing was confirmed", async () => { + const ctx = new Context(); + const failure = new Error("upload failed"); + class Encoder extends MessageEncoder { + async visit() { + throw failure; + } + async flush() {} + } + class SendingBot extends Bot { + static MessageEncoder = Encoder; + } + const bot = new SendingBot(ctx, {} as any, "qq"); + bot.user = { id: "bot" }; + const session = bot.session({ channel: { id: "group" } }); + await expect( + withReplyTurn( + () => true, + () => guardReplySession(session).bot.sendMessage("group", "reply"), + ), + ).rejects.toBe(failure); + await ctx.stop(); +}); + +it("keeps cancellation effective after an encoder has confirmed an earlier delivery", async () => { + const ctx = new Context(); + const controller = new AbortController(); + let laterRequests = 0; + class Encoder extends MessageEncoder { + async visit() { + this.results.push({ id: "confirmed" }); + controller.abort(); + } + async flush() { + laterRequests++; + } + } + class SendingBot extends Bot { + static MessageEncoder = Encoder; + } + const bot = new SendingBot(ctx, {} as any, "qq"); + bot.user = { id: "bot" }; + const session = bot.session({ channel: { id: "group" } }); + const error = await withReplyTurn( + () => true, + () => guardReplySession(session).bot.sendMessage("group", "reply"), + controller.signal, + ).catch((error) => error); + expect(error.messages).toEqual([{ id: "confirmed" }]); + expect(error.cause.name).toBe("AbortError"); + expect(laterRequests).toBe(0); + await ctx.stop(); +}); + it("stops delayed sends from cancelled turns but leaves normal commands working", async () => { let valid = true, sends = 0; diff --git a/packages/core/tests/send-heartbeat.spec.ts b/packages/core/tests/send-heartbeat.spec.ts index 11d5cefe6..f25862c0f 100644 --- a/packages/core/tests/send-heartbeat.spec.ts +++ b/packages/core/tests/send-heartbeat.spec.ts @@ -8,7 +8,7 @@ import { loggingStub, stubCtx } from "./helpers/yesimbot"; const modelResponse = (message: string) => JSON.stringify({ thoughts: {}, actions: [{ function: "send_message", params: { message } }], request_heartbeat: false }); -for (const scenario of ["success", "error", "query", "legacy"]) { +for (const scenario of ["success", "error", "query", "legacy", "partial"]) { it(`native heartbeat counts confirmed replies: ${scenario}`, async () => { const logger = { debug() {}, info() {}, warn() {}, error() {}, success() {} }; const name = scenario === "query" ? "lookup" : "send_message"; @@ -30,7 +30,10 @@ for (const scenario of ["success", "error", "query", "legacy"]) { tool: { getAvailableTools: () => [definition], getTool: () => definition, - invoke: async () => ({ status: scenario === "error" ? "error" : "success" }), + invoke: async () => ({ + status: ["error", "partial"].includes(scenario) ? "error" : "success", + metadata: scenario === "partial" ? { delivery: { messageIds: ["sent"] } } : undefined, + }), } as any, l1: { recordThought: async () => {}, @@ -45,7 +48,7 @@ for (const scenario of ["success", "error", "query", "legacy"]) { }); (processor as any)._prepareLlmRequest = async () => ({ messages: [] }); expect(await processor.runCycle({ session: { platform: "qq", channelId: "group", cid: "qq:group" } } as any)).toBe( - scenario === "success" || scenario === "legacy", + scenario === "success" || scenario === "legacy" || scenario === "partial", ); }); } @@ -340,3 +343,50 @@ for (const topLevel of [undefined, false]) { expect(result.replySent).toBe(false); }); } + +for (const streamAction of [false, true]) { + it(`${streamAction ? "streaming" : "normal"} heartbeat counts partial delivery while preserving failure observation`, async () => { + const observations: any[] = []; + const processor = streamingFixture( + async () => ({ text: modelResponse("hello") }), + async () => ({ + status: "error", + error: { name: "PartialDeliveryError", message: "second paragraph refused", retryable: false }, + metadata: { delivery: { messageIds: ["first-sent"], sentMessages: 1, totalMessages: 2 } }, + }), + ); + (processor as any).config.streamAction = streamAction; + (processor as any).interactionManager.recordObservation = async (...args: any[]) => observations.push(args[3]); + expect(await processor.runCycle(stimulus())).toBe(true); + expect(observations[0].status).toBe("error"); + expect(observations[0].metadata.delivery.messageIds).toEqual(["first-sent"]); + }); +} + +for (const streamAction of [false, true]) { + it(`${streamAction ? "streaming" : "normal"} heartbeat stops after a partially delivered send`, async () => { + let invocations = 0; + const processor = streamingFixture( + async () => ({ + text: JSON.stringify({ + thoughts: {}, + actions: [{ function: "send_message", params: { message: "hello" } }], + request_heartbeat: true, + }), + }), + async () => { + invocations++; + return { + status: "error", + error: { name: "PartialDeliveryError", message: "partial", retryable: false }, + metadata: { delivery: { messageIds: ["sent"] } }, + }; + }, + ); + (processor as any).config.streamAction = streamAction; + (processor as any).config.heartbeat = 3; + (processor as any).interactionManager.recordHeartbeat = async () => {}; + expect(await processor.runCycle(stimulus())).toBe(true); + expect(invocations).toBe(1); + }); +}