Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/core/src/agent/agent-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,7 @@ export class AgentCore extends YesImBotService<Config> {
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, {
Expand Down
15 changes: 13 additions & 2 deletions packages/core/src/agent/heartbeat-processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand All @@ -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 ?? "未知错误"}`);
}
Expand Down Expand Up @@ -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();
}
Expand All @@ -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;
}
Expand Down
50 changes: 47 additions & 3 deletions packages/core/src/agent/reply-turn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand Down Expand Up @@ -107,9 +108,14 @@ async function withGuardedEncoder<T>(
// 同 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) {
Expand All @@ -121,7 +127,20 @@ async function withGuardedEncoder<T>(
// 普通发送在自己的编码器中移除父异步链的旧保护。
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;
Expand Down Expand Up @@ -161,6 +180,31 @@ async function withGuardedEncoder<T>(
}
}
}
/** Capture adapter-confirmed content while preserving the guarded bot's send path. */
export async function sendMessageWithReceipts(bot: Bot, channelId: string, content: Parameters<Bot["sendMessage"]>[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;
Expand Down
78 changes: 60 additions & 18 deletions packages/core/src/extension/builtin/core-util/index.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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 },
);
}
}

Expand Down Expand Up @@ -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<string, unknown>) : 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("; ");
}
Expand All @@ -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<void> {
const sameSession =
bot === originalSession.bot &&
Expand Down Expand Up @@ -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) {
Expand Down
23 changes: 16 additions & 7 deletions packages/core/src/model/chat-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Response>;
const streamOptions = {
...chatOptions,
Expand All @@ -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;
Expand All @@ -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) {
Expand Down Expand Up @@ -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 }));
Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading