From 96a1505048197a4aa90ca56342d1ca382fa3e900 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=AE=B8=E4=BB=99xhcz?= Date: Tue, 3 Nov 2026 01:55:59 +0800 Subject: [PATCH] fix(core): recover native tool calls with configurable corrections and diagnostic context --- packages/core/src/agent/agent-core.ts | 9 +- packages/core/src/agent/config.ts | 5 + .../core/src/agent/heartbeat-processor.ts | 199 +++++++++++++---- packages/core/src/model/chat-model.ts | 67 +++++- .../core/src/shared/diagnostic-sanitizer.ts | 66 +++++- packages/core/tests/decision-core.spec.ts | 3 + .../core/tests/diagnostic-sanitizer.spec.ts | 109 ++++++++++ .../native-reasoning-continuation.spec.ts | 204 ++++++++++++++++++ .../core/tests/native-tool-recovery.spec.ts | 204 ++++++++++++++++++ 9 files changed, 819 insertions(+), 47 deletions(-) create mode 100644 packages/core/tests/native-reasoning-continuation.spec.ts create mode 100644 packages/core/tests/native-tool-recovery.spec.ts diff --git a/packages/core/src/agent/agent-core.ts b/packages/core/src/agent/agent-core.ts index 1565f790b..6c09a0ff7 100644 --- a/packages/core/src/agent/agent-core.ts +++ b/packages/core/src/agent/agent-core.ts @@ -137,7 +137,14 @@ export class AgentCore extends YesImBotService { const channelCid = replyKey(this.replyTarget(session)); stimulus = { ...stimulus, channelCid, decisionId: this.decisions?.begin(this.replyTarget(session), type, session.messageId) }; if (!this.allowedCategories(stimulus).length) { - this.logger.debug(`[${channelCid}] 跳过意愿评估 | 原因: 回复类别已抑制 | 消息ID: ${session.messageId ?? "未知"}`); + const rule = this.replyControl.peek(this.replyTarget(session)); + this.logger.debug( + `[${channelCid}] 跳过意愿评估 | 原因: 回复类别已抑制 | 消息ID: ${session.messageId ?? "未知"} | 规则: ${JSON.stringify({ + categories: type === "user_message" ? messageCategories(session) : [type], + blocked: rule?.blocked ?? [], + expiresAt: rule?.expiresAt ?? null, + })}`, + ); this.recordDecision(stimulus, { stage: "blocked", reason: "reply_suppressed", allowed: [] }); return; } diff --git a/packages/core/src/agent/config.ts b/packages/core/src/agent/config.ts index c1bf561d1..d55317ce0 100644 --- a/packages/core/src/agent/config.ts +++ b/packages/core/src/agent/config.ts @@ -236,6 +236,7 @@ export type AgentBehaviorConfig = ArousalConfig & decisionRecording?: { enabled: boolean; directory: string; maxEntries: number; maxBytes: number; retentionHours: number }; streamAction: boolean; nativeToolCalling?: boolean; + nativeToolCorrectionRetries?: number; backgroundTools?: BackgroundToolsConfig; heartbeat: number; /** Soft input packing budget; 0 disables packing. The model capacity guard remains authoritative. */ @@ -276,6 +277,10 @@ export const AgentBehaviorConfigSchema: Schema = Schema.int .collapse() .description("后台工具任务"), nativeToolCalling: Schema.boolean().default(false).description("使用模型原生工具调用(需模型支持),关闭时沿用 JSON 动作"), + nativeToolCorrectionRetries: Schema.natural() + .max(Number.MAX_SAFE_INTEGER) + .default(1) + .description("原生工具调用参数或格式异常时的追加纠正次数,默认 1;0 关闭自动纠正。仅在工具尚未执行时生效,多次纠正会增加请求耗时与用量"), streamAction: Schema.boolean().default(false).experimental().description("实验性流式动作处理"), contextInputBudgetTokens: Schema.natural() .default(16000) diff --git a/packages/core/src/agent/heartbeat-processor.ts b/packages/core/src/agent/heartbeat-processor.ts index 0334ff1a0..d80151a68 100644 --- a/packages/core/src/agent/heartbeat-processor.ts +++ b/packages/core/src/agent/heartbeat-processor.ts @@ -1,3 +1,5 @@ +import { createHash } from "node:crypto"; + import { GenerateTextResult } from "@xsai/generate-text"; import type { Tool } from "@xsai/shared-chat"; import { Message } from "@xsai/shared-chat"; @@ -477,7 +479,7 @@ export class HeartbeatProcessor { /** * 解析并验证来自LLM的响应 */ - private parseAndValidateResponse(llmRawResponse: GenerateTextResult, cid: string): Omit | null { + private parseAndValidateResponse(llmRawResponse: GenerateTextResult, cid: string, reportError = true): Omit | null { const errorContext = { rawResponse: llmRawResponse.text, cid, @@ -489,13 +491,13 @@ export class HeartbeatProcessor { const { data, error } = parser.parse(llmRawResponse.text ?? ""); if (error || !data) { const parseError = new AppError(ErrorDefinitions.LLM.OUTPUT_PARSING_FAILED, { cause: error as any, context: errorContext }); - handleError(this.logger, parseError, `解析LLM响应时 (CID: ${cid})`); + if (reportError) handleError(this.logger, parseError, `解析LLM响应时 (CID: ${cid})`); return null; } if (!data.thoughts || typeof data.thoughts !== "object" || Array.isArray(data.thoughts) || !Array.isArray(data.actions)) { const formatError = new AppError(ErrorDefinitions.LLM.OUTPUT_PARSING_FAILED, { context: errorContext }); - handleError(this.logger, formatError, `验证LLM响应格式时 (CID: ${cid})`); + if (reportError) handleError(this.logger, formatError, `验证LLM响应格式时 (CID: ${cid})`); return null; } @@ -557,46 +559,163 @@ export class HeartbeatProcessor { // SDK 阶段不执行任何真实工具,失败重试不会重放消息。 execute: () => ({}), })); - assertReplyTurn(); - const response = await this.modelSwitcher.chat({ - requestPurpose: "主对话", - messages: nativeMessages, - nativeToolCallingFallback: { - messages, + let actions: Array<{ function: string; params: Record }> = []; + const configuredRetries = this.config.nativeToolCorrectionRetries ?? 1; + const correctionRetries = Number.isSafeInteger(configuredRetries) && configuredRetries >= 0 ? configuredRetries : 1; + for (let attempt = 0; attempt <= correctionRetries; attempt++) { + assertReplyTurn(); + const response = await this.modelSwitcher.chat({ + requestPurpose: "主对话", + messages: nativeMessages, + nativeToolCallingFallback: { + messages, + abortSignal: replyTurnSignal(), + validation: this.createJsonValidation(), + }, + tools, + toolChoice: "required", + maxSteps: 1, + singleStep: true, abortSignal: replyTurnSignal(), - validation: this.createJsonValidation(), - }, - tools, - toolChoice: "required", - maxSteps: 1, - singleStep: true, - abortSignal: replyTurnSignal(), - }); - assertReplyTurn(); - if (!response.toolCalls?.length) { - const legacy = this.parseAndValidateResponse(response, conversationCid(session)); - if (!legacy) throw new Error("模型没有返回有效工具调用"); - this.displayThoughts(legacy.thoughts); - await this.interactionManager.recordThought(turnId, session.platform, conversationChannelId(session)!, legacy.thoughts, manualRecallIds); - const replySent = await this.executeActions(turnId, session, legacy.actions, onReplySent); - return { continue: legacy.request_heartbeat, replySent }; - } - const seen = new Map(); - const actions: Array<{ function: string; params: Record }> = []; - // 完整校验后才执行,防止坏调用旁边的发送动作先发生。 - for (const call of response.toolCalls) { - const params = JSON.parse(call.args); - if (!params || typeof params !== "object" || Array.isArray(params)) throw new Error("工具参数必须是对象"); - const definition = this.toolService.getTool(call.toolName, session); - if (!definition) throw new Error(`工具不可用: ${call.toolName}`); - definition.parameters(params); - const signature = JSON.stringify([call.toolName, params]); - if (seen.has(call.toolCallId)) { - if (seen.get(call.toolCallId) !== signature) throw new Error("工具调用 ID 重复但参数不同"); + }); + assertReplyTurn(); + if (!response.toolCalls?.length) { + let toolMarkup = false; + if (/<\/?tool_call(?:\s|>)/i.test(response.text ?? "")) { + try { + JSON.parse(response.text!); + } catch { + toolMarkup = true; + } + } + const legacy = toolMarkup ? null : this.parseAndValidateResponse(response, conversationCid(session), false); + if (legacy) { + this.displayThoughts(legacy.thoughts); + await this.interactionManager.recordThought(turnId, session.platform, conversationChannelId(session)!, legacy.thoughts, manualRecallIds); + const replySent = await this.executeActions(turnId, session, legacy.actions, onReplySent); + return { continue: legacy.request_heartbeat, replySent }; + } + const failure = new AppError(ErrorDefinitions.LLM.OUTPUT_PARSING_FAILED, { context: { reason: "native_tool_call_missing" } }); + if (attempt >= correctionRetries) throw failure; + // Untrusted plain text is retained as data, never interpreted as an executable call. + nativeMessages.push( + { role: "assistant", content: response.text ?? "" }, + { + role: "system", + content: "上一轮未返回有效工具调用,未执行任何动作。请通过原生工具接口返回调用,不要把工具调用写在正文、XML 标签或代码块中。", + }, + ); continue; } - seen.set(call.toolCallId, signature); - actions.push({ function: call.toolName, params }); + const seen = new Map(); + const failures: Array<{ reason: string; toolName: string; toolCallId: string; path?: Array }> = []; + actions = []; + for (const call of response.toolCalls) { + const toolName = typeof call.toolName === "string" ? call.toolName : ""; + const toolCallId = typeof call.toolCallId === "string" ? call.toolCallId : ""; + const fail = (reason: string, path?: Array) => + failures.push({ reason, toolName, toolCallId, ...(path?.length ? { path } : {}) }); + if (!toolName || !toolCallId || toolName.length > 1024 || toolCallId.length > 1048576 || /\p{Cc}/u.test(toolName + toolCallId)) { + fail("invalid_tool_identity"); + continue; + } + let params: Record; + try { + params = JSON.parse(call.args); + } catch { + fail("invalid_argument_json"); + continue; + } + if (!params || typeof params !== "object" || Array.isArray(params)) { + fail("arguments_not_object"); + continue; + } + const definition = this.toolService.getTool(call.toolName, session); + if (!definition) { + fail("tool_unavailable"); + continue; + } + try { + definition.parameters(params); + } catch (error) { + const path = Array.isArray(error?.options?.path) + ? error.options.path + .filter((part: unknown) => typeof part === "number" || (typeof part === "string" && /^[\w.-]{1,128}$/.test(part))) + .slice(0, 16) + : []; + fail("invalid_arguments", path); + continue; + } + const signature = JSON.stringify([call.toolName, params]); + if (seen.has(call.toolCallId)) { + if (seen.get(call.toolCallId) !== signature) fail("conflicting_tool_call_id"); + continue; + } + seen.set(call.toolCallId, signature); + actions.push({ function: call.toolName, params }); + } + if (!failures.length) break; + const failure = new AppError(ErrorDefinitions.LLM.OUTPUT_PARSING_FAILED, { + context: { + reason: "native_tool_validation_failed", + calls: failures.map((item) => ({ + ...item, + toolName: item.toolName.replace(/\p{Cc}/gu, "").slice(0, 128), + toolCallId: + item.toolCallId.length > 256 + ? `sha256:${createHash("sha256").update(item.toolCallId).digest("hex")}` + : item.toolCallId.replace(/\p{Cc}/gu, ""), + })), + }, + }); + if (attempt >= correctionRetries) throw failure; + const calls = response.toolCalls; + const ids = calls.map((call) => call.toolCallId); + // Invalid/duplicate identifiers cannot form a valid assistant/tool message pair. + if ( + new Set(ids).size === ids.length && + ids.every((id) => typeof id === "string" && id.length > 0 && id.length <= 1048576 && !/\p{Cc}/u.test(id)) && + calls.every( + (call) => typeof call.toolName === "string" && call.toolName.length > 0 && call.toolName.length <= 1024 && !/\p{Cc}/u.test(call.toolName), + ) + ) { + const priorAssistant = [...(response.messages ?? [])] + .reverse() + .find( + (message): message is Extract => + message.role === "assistant" && + message.tool_calls?.length === calls.length && + message.tool_calls.every((call, index) => call.id === calls[index].toolCallId), + ); + nativeMessages.push({ + ...priorAssistant, + role: "assistant", + content: priorAssistant?.content ?? response.text ?? "", + tool_calls: calls.map((call, index) => ({ + ...priorAssistant?.tool_calls?.[index], + index, + id: call.toolCallId, + type: "function", + function: { ...priorAssistant?.tool_calls?.[index]?.function, name: call.toolName, arguments: call.args }, + })), + }); + for (const call of calls) { + const invalid = failures.find((item) => item.toolCallId === call.toolCallId); + nativeMessages.push({ + role: "tool", + tool_call_id: call.toolCallId, + content: JSON.stringify({ + status: "error", + executed: false, + error: invalid ? { reason: invalid.reason, ...(invalid.path ? { path: invalid.path } : {}) } : { reason: "batch_not_executed" }, + }), + }); + } + } + nativeMessages.push({ + role: "system", + content: "上一轮工具调用校验失败,整批工具均未执行。请根据工具定义和错误反馈修正调用,补齐必填参数;不要重复原先无效的调用标识。", + }); } let replySent = false; for (const action of actions) { diff --git a/packages/core/src/model/chat-model.ts b/packages/core/src/model/chat-model.ts index 8914b75ac..1a8c6f9d6 100644 --- a/packages/core/src/model/chat-model.ts +++ b/packages/core/src/model/chat-model.ts @@ -216,9 +216,28 @@ export class ChatModel extends BaseModel implements IChatModel { ): Promise { const stime = Date.now(); let result: GenerateTextResult; + let originalAssistant: Message | undefined; + const originalFetch = chatOptions.fetch as typeof fetch; try { result = await generateText({ ...chatOptions, + ...(singleStep + ? { + fetch: async (url: Parameters[0], init: Parameters[1]) => { + const response = await originalFetch(url, init); + if (response.ok) { + try { + const message = (await response.clone().json())?.choices?.[0]?.message; + if (message?.role === "assistant" && Array.isArray(message.tool_calls)) originalAssistant = message; + } catch { + // The SDK still validates the original response, including cancellation. + } + } + chatOptions.abortSignal?.throwIfAborted(); + return response; + }, + } + : {}), ...(singleStep ? { onStepFinish: (step: CompletionStep) => { @@ -229,7 +248,13 @@ export class ChatModel extends BaseModel implements IChatModel { }); } catch (error) { if (!(error instanceof SingleStepComplete)) throw error; - result = { ...error.step, steps: [error.step], messages: [], text: error.step.text ?? "" } as GenerateTextResult; + const calls = error.step.toolCalls ?? []; + const originalCalls = originalAssistant?.role === "assistant" ? originalAssistant.tool_calls : undefined; + const matched = + calls.length > 0 && + originalCalls?.length === calls.length && + originalCalls.every((call, index) => call.id === calls[index].toolCallId && call.function.name === calls[index].toolName); + result = { ...error.step, steps: [error.step], messages: matched ? [originalAssistant!] : [], text: error.step.text ?? "" } as GenerateTextResult; } if (isEmpty(result.text) && !result.toolCalls?.length) { throw new AppError(ErrorDefinitions.LLM.OUTPUT_EMPTY_CONTENT, { @@ -274,6 +299,7 @@ export class ChatModel extends BaseModel implements IChatModel { let finalUsage: any = undefined; let finalFinishReason: GenerateTextResult["finishReason"] = "unknown"; + const completedResponses: StreamCompletion[] = []; let completion = new StreamCompletion(); let buffer: string[] = []; let diagnostics = new StreamDiagnostics(stime); @@ -352,6 +378,7 @@ export class ChatModel extends BaseModel implements IChatModel { context: { streamDiagnostics: summary }, }); } + if (completed && responseCompletion.hasTools) completedResponses.push(responseCompletion); }, }), ); @@ -459,7 +486,10 @@ export class ChatModel extends BaseModel implements IChatModel { return { steps: finalSteps as Array>, - messages: [], + messages: completedResponses.flatMap((response) => { + const message = response.assistantMessage(finalToolCalls); + return message ? [message] : []; + }), text: finalText, toolCalls: finalToolCalls, toolResults: finalToolResults, @@ -556,6 +586,30 @@ class StreamCompletion { completed = false; hasTools = false; earlyExit = false; + private reasoningContent: string | undefined; + private text = ""; + private readonly toolIds = new Map(); + + assistantMessage(calls: CompletionToolCall[]): Message | undefined { + const ids = [...this.toolIds.entries()].sort(([left], [right]) => left - right).map(([, id]) => id); + if (!this.completed || !ids.length || new Set(ids).size !== ids.length) return; + const matched = ids.map((id) => { + const candidates = calls.filter((call) => call.toolCallId === id); + return candidates.length === 1 ? candidates[0] : undefined; + }); + if (matched.some((call) => !call)) return; + return { + role: "assistant", + content: this.text, + ...(this.reasoningContent === undefined ? {} : { reasoning_content: this.reasoningContent }), + tool_calls: matched.map((call, index) => ({ + index, + id: call!.toolCallId, + type: "function", + function: { name: call!.toolName, arguments: call!.args }, + })), + }; + } constructor(private readonly onContent?: (text: string) => void) {} @@ -589,7 +643,14 @@ class StreamCompletion { continue; } if (typeof choice?.finish_reason === "string" && choice.finish_reason.length > 0) this.completed = true; - if (choice?.delta?.tool_calls?.length) this.hasTools = true; + if (typeof choice?.delta?.reasoning_content === "string") this.reasoningContent = (this.reasoningContent ?? "") + choice.delta.reasoning_content; + if (typeof choice?.delta?.content === "string") this.text += choice.delta.content; + if (choice?.delta?.tool_calls?.length) { + this.hasTools = true; + for (const call of choice.delta.tool_calls) { + if (Number.isSafeInteger(call.index) && typeof call.id === "string") this.toolIds.set(call.index, call.id); + } + } // 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/shared/diagnostic-sanitizer.ts b/packages/core/src/shared/diagnostic-sanitizer.ts index 0c995c239..2e4319918 100644 --- a/packages/core/src/shared/diagnostic-sanitizer.ts +++ b/packages/core/src/shared/diagnostic-sanitizer.ts @@ -1,3 +1,5 @@ +import { types } from "node:util"; + const secretKey = /^(authorization|proxy-authorization|cookie|set-cookie|(?:x-)?api[_-]?key|access[_-]?token|refresh[_-]?token|client[_-]?secret|password|secret|token)$/i; @@ -85,7 +87,64 @@ function collectCredentialValues(value: unknown, seen = new Set(), depth return result; } -/** Returns data only: custom JSON output is filtered, accessors are never invoked. */ +const nativeStackGetter = Object.getOwnPropertyDescriptor(new Error(), "stack")?.get; +const nativeCallSiteToString = (() => { + if (!nativeStackGetter) return; + const previous = Object.getOwnPropertyDescriptor(Error, "prepareStackTrace"); + try { + Object.defineProperty(Error, "prepareStackTrace", { + configurable: previous?.configurable ?? true, + writable: true, + value: (_error: Error, frames: NodeJS.CallSite[]) => + frames[0] && Object.getOwnPropertyDescriptor(Object.getPrototypeOf(frames[0]), "toString")?.value, + }); + const format = nativeStackGetter.call(new Error()); + return typeof format === "function" ? format : undefined; + } catch { + return; + } finally { + if (previous) Object.defineProperty(Error, "prepareStackTrace", previous); + else Reflect.deleteProperty(Error, "prepareStackTrace"); + } +})(); + +function errorTextField(error: Error, key: "name" | "message"): string | undefined { + let current: object | null = error; + while (current) { + const descriptor = Object.getOwnPropertyDescriptor(current, key); + if (descriptor) return "value" in descriptor && typeof descriptor.value === "string" ? descriptor.value : undefined; + current = Object.getPrototypeOf(current); + } + return ""; +} + +/** V8 lazy stacks are native accessors; format them without invoking user hooks. */ +function nativeErrorStack(error: Error, descriptor: PropertyDescriptor): string | undefined { + if (!nativeStackGetter || !nativeCallSiteToString || descriptor.get !== nativeStackGetter || !types.isNativeError(error)) return; + const name = errorTextField(error, "name"); + const message = errorTextField(error, "message"); + if (name === undefined || message === undefined) return; + const previous = Object.getOwnPropertyDescriptor(Error, "prepareStackTrace"); + try { + Object.defineProperty(Error, "prepareStackTrace", { + configurable: previous?.configurable ?? true, + writable: true, + value: (_error: Error, frames: NodeJS.CallSite[]) => { + const heading = !name ? message : !message ? name : `${name}: ${message}`; + return heading + frames.map((frame) => `\n at ${nativeCallSiteToString.call(frame)}`).join(""); + }, + }); + const stack = nativeStackGetter.call(error); + return typeof stack === "string" ? stack : undefined; + } catch { + return; + } finally { + if (previous) Object.defineProperty(Error, "prepareStackTrace", previous); + else Reflect.deleteProperty(Error, "prepareStackTrace"); + } +} + +/** Returns data only: custom JSON output is filtered and untrusted accessors are not invoked. */ export function sanitizeDiagnostic( value: unknown, secrets: readonly string[] = [], @@ -142,10 +201,11 @@ export function sanitizeDiagnostic( prototype = Object.getPrototypeOf(prototype); } } + const stack = error && key === "stack" && descriptor && !("value" in descriptor) ? nativeErrorStack(value, descriptor) : undefined; cleaned = - descriptor && !("value" in descriptor) + descriptor && !("value" in descriptor) && stack === undefined ? "[Accessor]" - : sanitizeDiagnostic(descriptor?.value, secrets, seen, depth + 1, redactDiagnosticText(key, secrets, options), options); + : sanitizeDiagnostic(stack ?? descriptor?.value, secrets, seen, depth + 1, redactDiagnosticText(key, secrets, options), options); } } catch { cleaned = "[Unreadable]"; diff --git a/packages/core/tests/decision-core.spec.ts b/packages/core/tests/decision-core.spec.ts index 6ef2b0093..059eb3706 100644 --- a/packages/core/tests/decision-core.spec.ts +++ b/packages/core/tests/decision-core.spec.ts @@ -129,6 +129,9 @@ it("records suppression and muting without scheduling a reply", async () => { await t.core.replyControl.set(t.target, ["all"], 1000); t.core.receiveStimulus({ type: "user_message", session: t.session }); expect(t.decisions.latest(t.target)?.reason).toBe("reply_suppressed"); + expect(t.logs.join("\n")).toContain('"blocked":["all"]'); + expect(t.logs.join("\n")).toContain('"expiresAt":'); + expect(t.logs.join("\n")).not.toContain("private-text-marker"); expect(t.core.willing.getCurrentWillingness(JSON.stringify(["qq", "bot", "g"]))).toBe(0); await t.core.replyControl.resume(t.target); t.core.worldState.isBotMuted = () => true; diff --git a/packages/core/tests/diagnostic-sanitizer.spec.ts b/packages/core/tests/diagnostic-sanitizer.spec.ts index b8f0f96ba..a2a6e3c97 100644 --- a/packages/core/tests/diagnostic-sanitizer.spec.ts +++ b/packages/core/tests/diagnostic-sanitizer.spec.ts @@ -1,8 +1,11 @@ import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { buildSync } from "esbuild"; import { test } from "vitest"; import { LocalLogWriter } from "../src/logger/local-writer"; @@ -151,3 +154,109 @@ test("custom JSON keeps the serialization key and Error hook diagnostics", () => assert.equal(cleaned.safe, "error-hook"); assert.equal(cleaned.Authorization, "[REDACTED]"); }); + +test("native lazy Error stacks remain readable and redact nested causes", () => { + const cause = new Error("failed configured-secret"); + const error = new Error("outer", { cause }); + cause.cause = error; + const cleaned = sanitizer.sanitizeDiagnostic(error, ["configured-secret"]); + assert.equal(typeof cleaned.stack, "string"); + assert.match(cleaned.stack, /Error: outer\n\s+at /); + assert.match(cleaned.cause.stack, /Error: failed \[REDACTED\]/); + assert.equal(cleaned.cause.cause, "[Circular]"); +}); + +test("reading native stacks never invokes custom formatters or field accessors", () => { + let invoked = 0; + const descriptor = Object.getOwnPropertyDescriptor(Error, "prepareStackTrace"); + const error = new Error("safe"); + const formatter = () => { + invoked++; + return "formatter-secret"; + }; + Object.defineProperty(Error, "prepareStackTrace", { configurable: true, value: formatter }); + Object.defineProperty(error, "name", { + configurable: true, + get() { + invoked++; + return "getter-secret"; + }, + }); + try { + const plain = sanitizer.sanitizeDiagnostic(new Error("ordinary")); + assert.match(plain.stack, /Error: ordinary\n\s+at /); + assert.equal(Error.prepareStackTrace, formatter); + const cleaned = sanitizer.sanitizeDiagnostic(error); + assert.equal(invoked, 0); + assert.ok(!JSON.stringify(cleaned).includes("secret")); + } finally { + if (descriptor) Object.defineProperty(Error, "prepareStackTrace", descriptor); + else Reflect.deleteProperty(Error, "prepareStackTrace"); + } +}); + +test("custom Error stack getters are not evaluated", () => { + let invoked = 0; + const error = new Error("safe"); + Object.defineProperty(error, "stack", { + get() { + invoked++; + return "stack-secret"; + }, + }); + const cleaned = sanitizer.sanitizeDiagnostic(error); + assert.equal(invoked, 0); + assert.equal(cleaned.stack, "[Accessor]"); +}); + +test("stack formatting does not read a captured function name getter", () => { + let invoked = 0; + const message = "safe"; + function capture() { + return new Error(message); + } + Object.defineProperty(capture, "name", { + get() { + invoked++; + return "function-secret"; + }, + }); + const cleaned = sanitizer.sanitizeDiagnostic(capture()); + assert.match(cleaned.stack, /Error: safe\n\s+at /); + assert.equal(invoked, 0); +}); + +test("locked stack formatter descriptors remain untouched and degrade safely", () => { + const source = buildSync({ + entryPoints: [fileURLToPath(new URL("../src/shared/diagnostic-sanitizer.ts", import.meta.url))], + bundle: true, + write: false, + platform: "node", + format: "cjs", + }).outputFiles[0].text; + for (const lockBeforeImport of [false, true]) { + assert.doesNotThrow(() => + execFileSync( + process.execPath, + [ + "-e", + ` + const assert = require("node:assert/strict"); + const source = require("node:fs").readFileSync(0, "utf8"); + const formatter = () => { throw new Error("formatter must not run"); }; + const lock = () => Object.defineProperty(Error, "prepareStackTrace", { value: formatter, configurable: false, writable: false }); + if (${lockBeforeImport}) lock(); + const target = { exports: {} }; + new Function("module", "exports", "require", source)(target, target.exports, require); + if (!${lockBeforeImport}) lock(); + const before = Object.getOwnPropertyDescriptor(Error, "prepareStackTrace"); + const cleaned = target.exports.sanitizeDiagnostic(new Error("safe")); + assert.equal(cleaned.stack, "[Accessor]"); + assert.deepEqual(Object.getOwnPropertyDescriptor(Error, "prepareStackTrace"), before); + `, + ], + { input: source }, + ), + ); + } +}); diff --git a/packages/core/tests/native-reasoning-continuation.spec.ts b/packages/core/tests/native-reasoning-continuation.spec.ts new file mode 100644 index 000000000..59de11f75 --- /dev/null +++ b/packages/core/tests/native-reasoning-continuation.spec.ts @@ -0,0 +1,204 @@ +import { expect, it } from "vitest"; + +import { ChatModel } from "../src/model/chat-model"; +import { ModelAbility } from "../src/model/config"; +import { loggingStub, stubCtx } from "./helpers/yesimbot"; + +const frame = (delta: any, finish_reason: string | null = null) => `data: ${JSON.stringify({ choices: [{ index: 0, delta, finish_reason }] })}\n\n`; +function fixture(body: string | (() => string), contentType = "text/event-stream", status = 200) { + const logs: string[] = []; + const requests: any[] = []; + const logger: any = Object.fromEntries( + ["debug", "info", "warn", "error", "success"].map((key) => [key, (...args: unknown[]) => logs.push(args.join(" "))]), + ); + logger.extend = () => logger; + const model = new ChatModel( + stubCtx({ logging: { getLogger: () => logger } }), + () => ({ baseURL: "https://test.invalid/v1/", apiKey: "test", model: "test" }), + { modelId: "test", providerName: "test", abilities: [ModelAbility.Chat], parameters: { stream: true, custom: [] } }, + (async (_url, init) => { + requests.push(JSON.parse(String(init?.body))); + return new Response(typeof body === "function" ? body() : body, { status, headers: { "content-type": contentType } }); + }) as typeof fetch, + loggingStub(logger), + ); + return { model, logs, requests }; +} +const options = { + messages: [{ role: "user", content: "hello" }] as any, + tools: [{ type: "function", function: { name: "lookup", description: "lookup", parameters: { type: "object" } }, execute: () => ({}) }] as any, + toolChoice: "required" as const, + maxSteps: 1, + singleStep: true, +}; +it("preserves native reasoning only on the matching completed assistant tool message", async () => { + const { model, logs, requests } = fixture( + frame({ reasoning_content: "PRIVATE_REASONING_" }) + + frame({ reasoning_content: "CONTINUATION" }) + + frame({ tool_calls: [{ index: 0, id: "opaque:call", type: "function", function: { name: "lookup", arguments: '{"action":' } }] }) + + frame({ tool_calls: [{ index: 0, function: { arguments: '"read"}' } }] }) + + frame({}, "tool_calls") + + "data: [DONE]\n\n", + ); + const result = await model.chat(options); + expect(requests[0].tool_choice).toBe("required"); + expect(requests[0].tools).toMatchObject([{ type: "function", function: { name: "lookup", parameters: { type: "object" } } }]); + const assistant = result.messages.find((message) => message.role === "assistant") as any; + expect(assistant?.reasoning_content).toBe("PRIVATE_REASONING_CONTINUATION"); + expect(assistant?.tool_calls.map((call) => call.id)).toEqual(result.toolCalls.map((call) => call.toolCallId)); + expect(assistant?.tool_calls[0].function.arguments).toBe('{"action":"read"}'); + expect(result.text).toBe(""); + expect(logs.join("\n")).not.toContain("PRIVATE_REASONING_"); +}); +it("does not expose reasoning as a successful continuation when the stream is truncated", async () => { + const { model } = fixture( + frame({ reasoning_content: "PRIVATE" }) + + frame({ tool_calls: [{ index: 0, id: "call", type: "function", function: { name: "lookup", arguments: "{}" } }] }), + ); + await expect(model.chat(options)).rejects.toMatchObject({ code: "LLM.REQUEST_FAILED" }); +}); + +it("keeps reasoning scoped to the completed tool step across multiple responses", async () => { + let requests = 0; + const { model } = fixture(() => { + requests++; + if (requests > 2) return frame({ content: "finished" }) + frame({}, "stop") + "data: [DONE]\n\n"; + return ( + frame({ reasoning_content: `step-${requests}` }) + + frame({ tool_calls: [{ index: 0, id: `call-${requests}`, type: "function", function: { name: "lookup", arguments: "{}" } }] }) + + frame({}, "tool_calls") + + "data: [DONE]\n\n" + ); + }); + const result = await model.chat({ ...options, maxSteps: 3, singleStep: false }); + expect(requests).toBe(3); + const assistants = result.messages.filter((message) => message.role === "assistant") as any[]; + expect(assistants.map((message) => message.reasoning_content)).toEqual(["step-1", "step-2"]); + expect(assistants.map((message) => message.tool_calls.map((call) => call.id))).toEqual([["call-1"], ["call-2"]]); +}); + +it("does not associate reasoning with an ambiguous call ID reused by multiple steps", async () => { + let requests = 0; + const { model } = fixture(() => { + requests++; + if (requests > 2) return frame({ content: "finished" }) + frame({}, "stop") + "data: [DONE]\n\n"; + return ( + frame({ reasoning_content: `step-${requests}` }) + + frame({ tool_calls: [{ index: 0, id: "reused", type: "function", function: { name: "lookup", arguments: JSON.stringify({ step: requests }) } }] }) + + frame({}, "tool_calls") + + "data: [DONE]\n\n" + ); + }); + const result = await model.chat({ ...options, maxSteps: 3, singleStep: false }); + expect(result.toolCalls).toHaveLength(2); + expect(result.messages).toEqual([]); +}); +it("preserves assistant content sharing a tool delta without using it as validated response text", async () => { + const { model } = fixture( + frame({ + content: "native-preface", + reasoning_content: "reason", + tool_calls: [{ index: 0, id: "call", type: "function", function: { name: "lookup", arguments: "{}" } }], + }) + + frame({}, "tool_calls") + + "data: [DONE]\n\n", + ); + const result = await model.chat(options); + expect(result.messages[0].content).toBe("native-preface"); + expect(result.text).toBe(""); +}); + +it("retains the original assistant reasoning when non-stream single-step completion stops the SDK", async () => { + let requests = 0; + const { model } = fixture(() => { + requests++; + return JSON.stringify({ + choices: [ + { + index: 0, + finish_reason: "tool_calls", + message: { + role: "assistant", + content: null, + reasoning_content: "nonstream-reason", + tool_calls: [{ index: 0, id: "nonstream:call", type: "function", function: { name: "lookup", arguments: "{}" } }], + }, + }, + ], + usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }, + }); + }, "application/json"); + const result = await model.chat({ ...options, stream: false }); + expect(requests).toBe(1); + expect((result.messages[0] as any)?.reasoning_content).toBe("nonstream-reason"); + expect((result.messages[0] as any)?.tool_calls[0].id).toBe(result.toolCalls[0].toolCallId); +}); + +it("does not execute tools or add requests when non-stream response fails", async () => { + let requests = 0; + let executions = 0; + const { model } = fixture( + () => { + requests++; + return JSON.stringify({ error: { message: "rate limited" } }); + }, + "application/json", + 429, + ); + await expect( + model.chat({ + ...options, + stream: false, + tools: [ + { + ...options.tools[0], + execute: () => { + executions++; + return {}; + }, + }, + ], + }), + ).rejects.toMatchObject({ code: "LLM.RATE_LIMIT_EXCEEDED" }); + expect(requests).toBe(1); + expect(executions).toBe(0); +}); +it("honors non-stream cancellation before returning captured metadata", async () => { + const controller = new AbortController(); + const reason = new DOMException("cancelled", "AbortError"); + let executions = 0; + const { model } = fixture(() => { + controller.abort(reason); + return JSON.stringify({ + choices: [ + { + index: 0, + finish_reason: "tool_calls", + message: { + role: "assistant", + content: null, + reasoning_content: "reason", + tool_calls: [{ index: 0, id: "call", type: "function", function: { name: "lookup", arguments: "{}" } }], + }, + }, + ], + }); + }, "application/json"); + await expect( + model.chat({ + ...options, + stream: false, + abortSignal: controller.signal, + tools: [ + { + ...options.tools[0], + execute: () => { + executions++; + return {}; + }, + }, + ], + }), + ).rejects.toBe(reason); + expect(executions).toBe(0); +}); diff --git a/packages/core/tests/native-tool-recovery.spec.ts b/packages/core/tests/native-tool-recovery.spec.ts new file mode 100644 index 000000000..af2d61653 --- /dev/null +++ b/packages/core/tests/native-tool-recovery.spec.ts @@ -0,0 +1,204 @@ +import { Schema } from "koishi"; +import { expect, it, vi } from "vitest"; + +import { AgentBehaviorConfigSchema } from "../src/agent/config"; +import { HeartbeatProcessor } from "../src/agent/heartbeat-processor"; +import { withReplyTurnGuard } from "../src/agent/reply-turn"; +import { loggingStub, stubCtx } from "./helpers/yesimbot"; + +const call = (toolName: string, args: unknown, toolCallId = "call") => ({ toolCallId, toolCallType: "function", toolName, args: JSON.stringify(args) }); +function setup(responses: any[], config: Record = {}) { + const logger = { + debug: vi.fn<(...args: any[]) => void>(), + info: vi.fn<(...args: any[]) => void>(), + warn: vi.fn<(...args: any[]) => void>(), + error: vi.fn<(...args: any[]) => void>(), + success: vi.fn<(...args: any[]) => void>(), + }; + const requests: any[] = []; + const invoke = vi.fn<(...args: any[]) => Promise>(async () => ({ status: "success" })); + const definitions = [ + { name: "send_message", description: "send", parameters: Schema.object({ message: Schema.string().required() }) }, + { name: "lookup", description: "lookup", parameters: Schema.object({ action: Schema.string().required() }) }, + ]; + const processor = new HeartbeatProcessor(stubCtx({ logging: { getLogger: () => logger } }), { heartbeat: 1, nativeToolCalling: true, ...config } as any, { + model: { + chat: async (options: any) => { + requests.push(structuredClone(options.messages)); + const response = responses[Math.min(requests.length - 1, responses.length - 1)]; + if (response instanceof Error) throw response; + if (typeof response === "function") return response(); + return response; + }, + } as any, + prompt: {} as any, + tool: { getAvailableTools: () => definitions, getTool: (name) => definitions.find((tool) => tool.name === name), invoke } as any, + l1: { recordThought: async () => {}, recordHeartbeat: async () => {}, recordAction: async () => "action", recordObservation: async () => {} } as any, + contextBuilder: {} as any, + logging: loggingStub(logger), + world: {} as any, + }); + (processor as any)._prepareLlmRequest = async () => ({ messages: [] }); + const run = () => processor.runCycle({ session: { platform: "qq", channelId: "g", cid: "qq:g" } } as any); + return { requests, invoke, logger, run }; +} +it("feeds invalid argument paths back as paired tool responses before any batch action executes", async () => { + const f = setup([ + { toolCalls: [call("send_message", { message: "discard" }, "send"), call("lookup", {}, "lookup")] }, + { toolCalls: [call("send_message", { message: "accepted" }, "corrected")] }, + ]); + expect(await f.run()).toBe(true); + expect(f.invoke.mock.calls).toEqual([["send_message", { message: "accepted" }, expect.anything()]]); + const repair = f.requests[1]; + expect(repair.find((message) => message.role === "assistant").tool_calls).toHaveLength(2); + const results = repair.filter((message) => message.role === "tool"); + expect(results.map((message) => message.tool_call_id)).toEqual(["send", "lookup"]); + expect(results[1].content).toContain("action"); + expect(f.logger.error).not.toHaveBeenCalled(); +}); +it("does not execute tool tags written into plain text and asks for a native correction", async () => { + const f = setup([ + { text: '{"function":"send_message","params":{"message":"discard"}}' }, + { toolCalls: [call("send_message", { message: "accepted" })] }, + ]); + expect(await f.run()).toBe(true); + expect(f.requests).toHaveLength(2); + expect(f.invoke.mock.calls[0][1]).toEqual({ message: "accepted" }); + expect(f.logger.error).not.toHaveBeenCalled(); +}); +it("bounds malformed response correction and reports the classified failure only once", async () => { + const f = setup([{ toolCalls: [call("lookup", { secret: "DO_NOT_LOG" })] }]); + expect(await f.run()).toBe(false); + expect(f.requests).toHaveLength(2); + expect(f.invoke).not.toHaveBeenCalled(); + const errors = f.logger.error.mock.calls.flat().join("\n"); + expect(errors.match(/错误报告/g)).toHaveLength(1); + expect(errors).toContain("LLM.OUTPUT_PARSING_FAILED"); + expect(JSON.stringify(f.logger.error.mock.calls)).not.toContain("DO_NOT_LOG"); +}); +it("does not retry or replay a batch after actual execution has started", async () => { + const f = setup([{ toolCalls: [call("send_message", { message: "once" }), call("lookup", { action: "read" }, "lookup")] }]); + f.invoke.mockImplementationOnce(async () => ({ status: "success" })).mockImplementationOnce(async () => ({ status: "error" })); + expect(await f.run()).toBe(true); + expect(f.requests).toHaveLength(1); + expect(f.invoke).toHaveBeenCalledTimes(2); +}); +it("preserves successful legacy JSON responses without a native retry", async () => { + const f = setup([ + { text: JSON.stringify({ thoughts: {}, actions: [{ function: "send_message", params: { message: "legacy" } }], request_heartbeat: false }) }, + ]); + expect(await f.run()).toBe(true); + expect(f.requests).toHaveLength(1); +}); + +it("does not retry transport errors as model argument corrections", async () => { + const f = setup([new Error("transport failed")]); + expect(await f.run()).toBe(false); + expect(f.requests).toHaveLength(1); + expect(f.invoke).not.toHaveBeenCalled(); +}); +it.each(["invalid-json", "conflicting-id"])("corrects %s without executing the original batch", async (scenario) => { + const original = + scenario === "invalid-json" + ? [{ ...call("lookup", {}), args: "{invalid" }] + : [call("send_message", { message: "discard" }), call("lookup", { action: "read" })]; + const f = setup([{ toolCalls: original }, { toolCalls: [call("send_message", { message: "accepted" }, "fixed")] }]); + expect(await f.run()).toBe(true); + expect(f.invoke).toHaveBeenCalledTimes(1); + expect(f.invoke.mock.calls[0][1]).toEqual({ message: "accepted" }); +}); + +it("preserves opaque tool identifiers and assistant reasoning metadata during correction", async () => { + const id = "yib-qwen:opaque/+==:continuation"; + const f = setup([ + { + toolCalls: [call("lookup", {}, id)], + messages: [ + { + role: "assistant", + content: "", + reasoning_content: "retained provider reasoning", + tool_calls: [{ id, type: "function", function: { name: "lookup", arguments: "{}" } }], + }, + ], + }, + { toolCalls: [call("send_message", { message: "accepted" })] }, + ]); + expect(await f.run()).toBe(true); + expect(f.requests[1].find((message) => message.role === "assistant").reasoning_content).toBe("retained provider reasoning"); + expect(f.requests[1].find((message) => message.role === "tool").tool_call_id).toBe(id); +}); + +it("does not issue correction requests after the reply turn is cancelled", async () => { + const controller = new AbortController(); + const f = setup([ + () => { + controller.abort(); + return { toolCalls: [call("lookup", {})] }; + }, + ]); + expect(await withReplyTurnGuard(() => !controller.signal.aborted, f.run, controller.signal)).toBe(false); + expect(f.requests).toHaveLength(1); + expect(f.invoke).not.toHaveBeenCalled(); + expect(f.logger.error).not.toHaveBeenCalled(); +}); + +it("does not unwrap tool markup into an otherwise valid legacy action batch", async () => { + const legacy = JSON.stringify({ thoughts: {}, actions: [{ function: "send_message", params: { message: "discard" } }], request_heartbeat: false }); + const f = setup([{ text: `${legacy}` }, { toolCalls: [call("send_message", { message: "accepted" })] }]); + expect(await f.run()).toBe(true); + expect(f.requests).toHaveLength(2); + expect(f.invoke.mock.calls[0][1]).toEqual({ message: "accepted" }); +}); + +it("allows literal tool tag text inside a valid legacy JSON message", async () => { + const f = setup([ + { + text: JSON.stringify({ + thoughts: {}, + actions: [{ function: "send_message", params: { message: "literal text" } }], + request_heartbeat: false, + }), + }, + ]); + expect(await f.run()).toBe(true); + expect(f.requests).toHaveLength(1); + expect(f.invoke.mock.calls[0][1]).toEqual({ message: "literal text" }); +}); + +it.each([0, 2, 4])("stops after the configured %i additional argument corrections", async (retries) => { + const f = setup([{ toolCalls: [call("lookup", {})] }], { nativeToolCorrectionRetries: retries }); + expect(await f.run()).toBe(false); + expect(f.requests).toHaveLength(retries + 1); + expect(f.invoke).not.toHaveBeenCalled(); +}); + +it.each([0, 2])("stops after the configured %i additional plain-text corrections", async (retries) => { + const f = setup([{ text: "invalid plain text" }], { nativeToolCorrectionRetries: retries }); + expect(await f.run()).toBe(false); + expect(f.requests).toHaveLength(retries + 1); + expect(f.invoke).not.toHaveBeenCalled(); +}); + +it("executes only the successful batch after multiple corrections", async () => { + const f = setup( + [ + { toolCalls: [call("lookup", {}, "first")] }, + { toolCalls: [call("lookup", {}, "second")] }, + { toolCalls: [call("send_message", { message: "accepted" }, "third")] }, + ], + { nativeToolCorrectionRetries: 2 }, + ); + expect(await f.run()).toBe(true); + expect(f.requests).toHaveLength(3); + expect(f.invoke.mock.calls).toEqual([["send_message", { message: "accepted" }, expect.anything()]]); + expect(f.requests[2].filter((message) => message.role === "tool").map((message) => message.tool_call_id)).toEqual(["first", "second"]); +}); + +it("defaults correction retries to one and accepts only non-negative safe integers", () => { + expect(AgentBehaviorConfigSchema({}).nativeToolCorrectionRetries).toBe(1); + for (const value of [0, 2, 20]) expect(AgentBehaviorConfigSchema({ nativeToolCorrectionRetries: value }).nativeToolCorrectionRetries).toBe(value); + for (const value of [-1, 0.5, Infinity, NaN, Number.MAX_SAFE_INTEGER + 1]) { + expect(() => AgentBehaviorConfigSchema({ nativeToolCorrectionRetries: value })).toThrow(); + } +});