From 13a6355ad9e696efffb335594849d56d6577a557 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=AE=B8=E4=BB=99xhcz?= Date: Thu, 29 Oct 2026 19:22:05 +0800 Subject: [PATCH] =?UTF-8?q?feat(v3-dev):=20=E5=AE=8C=E5=96=84=E5=85=AC?= =?UTF-8?q?=E5=85=B1=E9=94=99=E8=AF=AF=E6=8E=A5=E5=8F=A3=E4=B8=8E=E4=BA=BA?= =?UTF-8?q?=E7=89=A9=E8=AE=B0=E5=BF=86=E5=86=B2=E7=AA=81=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/core/src/extension/service.ts | 8 +- packages/core/src/extension/types.ts | 6 + .../core/src/shared/errors/definitions.ts | 48 ++++++++ packages/core/src/shared/errors/index.ts | 104 ++++++++++++++---- .../tests/tool-error-normalization.spec.ts | 90 +++++++++++++++ packages/person-memory/src/index.ts | 8 +- packages/person-memory/src/store.ts | 12 +- .../person-memory/tests/profile-tools.spec.ts | 53 +++++++++ 8 files changed, 299 insertions(+), 30 deletions(-) create mode 100644 packages/core/tests/tool-error-normalization.spec.ts diff --git a/packages/core/src/extension/service.ts b/packages/core/src/extension/service.ts index 73a8f35e3..e80f43479 100644 --- a/packages/core/src/extension/service.ts +++ b/packages/core/src/extension/service.ts @@ -7,6 +7,7 @@ import { Config } from "../config"; import type { LoggerService } from "../logger"; import { PromptService } from "../prompt"; import { sanitizeDiagnostic } from "../shared/diagnostic-sanitizer"; +import { normalizeAppError, fromAppError } from "../shared/errors"; import { getInstanceDirectory, getInstanceScope } from "../shared/instance-scope"; import { YesImBotService } from "../shared/service"; import { isEmpty, stringify, truncate } from "../shared/utils"; @@ -794,9 +795,10 @@ export class ToolService extends YesImBotService { } } catch (error) { assertReplyTurn(); - this._logger.error(`💥 异常 | 调用 ${functionName} 时出错`, error.message); - this._logger.debug(error.stack); - lastResult = Failed(`Exception: ${error.message}`); + const normalized = normalizeAppError(error); + this._logger.error(`💥 异常 | 调用 ${functionName} 时出错`, { code: normalized.code, errorId: normalized.errorId }); + this._logger.debug(sanitizeDiagnostic(normalized)); + lastResult = Failed(fromAppError(normalized)); return lastResult; } } diff --git a/packages/core/src/extension/types.ts b/packages/core/src/extension/types.ts index 00677492c..5b538227d 100644 --- a/packages/core/src/extension/types.ts +++ b/packages/core/src/extension/types.ts @@ -2,6 +2,8 @@ import { Context, Schema, Session } from "koishi"; +import type { ErrorCategory } from "../shared/errors/definitions"; + export interface Param { type: string; description?: string; @@ -77,6 +79,10 @@ export interface ToolError { message: string; /** 错误是否可重试 */ retryable?: boolean; + code?: string; + errorId?: string; + category?: ErrorCategory; + suggestion?: string; } /** diff --git a/packages/core/src/shared/errors/definitions.ts b/packages/core/src/shared/errors/definitions.ts index cc027e319..ef8730a61 100644 --- a/packages/core/src/shared/errors/definitions.ts +++ b/packages/core/src/shared/errors/definitions.ts @@ -1,3 +1,18 @@ +/** Coarse public classification; it does not authorize retries. */ +export type ErrorCategory = + | "invalid_input" + | "configuration" + | "permission_denied" + | "not_found" + | "conflict" + | "source_invalid" + | "cancelled" + | "timeout" + | "rate_limited" + | "upstream_failure" + | "internal" + | "outcome_unknown"; + /** * @description 应用程序的统一错误定义 * 每个定义都包含 code (错误码)、message (错误信息) 和给用户的 suggestion (建议) @@ -8,48 +23,56 @@ export const ErrorDefinitions = { LLM: { BAD_REQUEST: { code: "LLM.BAD_REQUEST", + category: "invalid_input", message: "LLM API 请求因格式错误而失败", suggestion: "请检查您的请求参数,确保它们符合 API 的要求并已正确格式化", }, INVALID_API_KEY: { code: "LLM.INVALID_API_KEY", + category: "configuration", message: "提供了无效的 LLM API 密钥", suggestion: "请仔细检查您的 API 密钥,确保其在插件配置中已正确设置。如果您使用的是云服务,请确保您有权访问指定的模型", }, RATE_LIMIT_EXCEEDED: { code: "LLM.RATE_LIMIT_EXCEEDED", + category: "rate_limited", message: "LLM API 的请求频率超限", suggestion: "请稍等片刻再发起请求。如果您使用的是云服务,请考虑升级您的套餐或将请求分散在更长的时间段内", }, PROVIDER_ERROR: { code: "LLM.PROVIDER_ERROR", + category: "upstream_failure", message: "LLM 服务提供商内部发生错误", suggestion: "请检查服务商的文档以确保其设置正确。如果问题仍然存在,请考虑报告此问题", }, REQUEST_FAILED: { code: "LLM.REQUEST_FAILED", + category: "upstream_failure", message: (details: string) => `LLM API 请求失败:${details}`, suggestion: "请检查您的网络、API 密钥以及模型提供商的状态页面。这可能是由于频率限制、密钥无效或暂时的服务中断所致", }, OUTPUT_PARSING_FAILED: { code: "LLM.OUTPUT_PARSING_FAILED", + category: "upstream_failure", message: "解析 LLM 响应失败,输出不是有效的 JSON 格式", suggestion: "这通常是暂时的模型问题,请重试。如果问题持续存在,可能是模型不稳定或系统提示词需要调整以确保生成有效的 JSON", }, OUTPUT_EMPTY_CONTENT: { code: "LLM.OUTPUT_EMPTY_CONTENT", + category: "upstream_failure", message: "LLM 响应为空", suggestion: "这可能是上游API故障导致,建议联系API提供商检查服务状态", }, TIMEOUT: { code: "LLM.TIMEOUT", + category: "timeout", message: (duration?: number) => typeof duration === "number" && Number.isFinite(duration) && duration > 0 ? `对 LLM 的请求在 ${duration} 秒后超时` @@ -61,21 +84,25 @@ export const ErrorDefinitions = { CONFIG: { MISSING: { code: "CONFIG.MISSING", + category: "configuration", message: (service: string, component: string) => `服务 '${service}' 中缺少 '${component}' 的配置`, suggestion: (component: string) => `请确保在插件设置中已正确配置 '${component}'`, }, MISSING_MODEL_GROUP: { code: "CONFIG.MISSING_MODEL_GROUP", + category: "configuration", message: "未给 '聊天 (Chat)' 任务类型配置任何模型组", suggestion: "代理需要一个聊天模型才能运作。请前往“模型服务”设置,并为 '聊天' 任务类型至少配置一个模型", }, INVALID: { code: "CONFIG.INVALID", + category: "configuration", message: (details: string) => `发现无效配置:${details}`, suggestion: "请检查插件配置并更正指定的字段。有关有效值,请参阅文档", }, PROVIDER_INIT_FAILED: { code: "CONFIG.PROVIDER_INIT_FAILED", + category: "configuration", message: (providerId: string) => `初始化提供商失败:${providerId}`, suggestion: "请确保提供商的配置(如 API 密钥和基础 URL)正确无误,并检查日志中是否有相关的错误信息", }, @@ -84,6 +111,7 @@ export const ErrorDefinitions = { TASK: { EXECUTION_FAILED: { code: "TASK.EXECUTION_FAILED", + category: "internal", message: "执行计划任务时发生错误", suggestion: "这表明代理的处理周期内存在内部错误。请检查详细日志以获取更多信息", }, @@ -92,14 +120,25 @@ export const ErrorDefinitions = { WILLINGNESS: { CALCULATION_FAILED: { code: "WILLINGNESS.CALCULATION_FAILED", + category: "internal", message: "意愿计算失败", suggestion: "在决定是否回复时发生内部错误。请检查日志以获取更多详情", }, }, + PERSON_MEMORY: { + VERSION_CONFLICT: { + code: "PERSON_MEMORY.VERSION_CONFLICT", + category: "conflict", + retryable: false, + message: (details = "身份或画像版本已变化") => details, + suggestion: "请重新读取人物及账号关联版本,核对后重新提交候选", + }, + }, // --- 系统未知错误 --- SYSTEM: { UNKNOWN: { code: "SYSTEM.UNKNOWN", + category: "internal", message: "发生未知错误", suggestion: "捕获到意外错误。请检查日志并考虑报告此问题", }, @@ -108,26 +147,31 @@ export const ErrorDefinitions = { MODEL: { UNAVAILABLE: { code: "MODEL.UNAVAILABLE", + category: "configuration", message: (modelId: string) => `无法找到或加载请求的模型 '${modelId}'`, suggestion: "请验证模型 ID 是否正确,以及对应的提供商是否已启用并正确配置", }, GROUP_INIT_FAILED: { code: "MODEL.GROUP_INIT_FAILED", + category: "configuration", message: (groupName: string) => `模型组 '${groupName}' 初始化失败,因为它不包含任何可用的模型`, suggestion: "请检查模型组的配置。确保所列模型存在、其提供商已启用,并且它们具备所需的能力(例如 '聊天')", }, ALL_FAILED_IN_GROUP: { code: "MODEL.ALL_FAILED_IN_GROUP", + category: "upstream_failure", message: (groupName: string) => `模型组 '${groupName}' 中的所有模型都未能处理请求`, suggestion: "这表明存在普遍性问题。请检查错误报告中的 'cause' 以了解单个模型的失败原因。这可能是网络问题或影响组内所有模型的问题", }, RETRY_EXHAUSTED: { code: "MODEL.RETRY_EXHAUSTED", + category: "upstream_failure", message: (modelId: string) => `模型 '${modelId}' 的所有重试次数已用尽`, suggestion: "该模型反复失败。请检查错误日志以找出根本原因(例如,网络问题、持续的 API 错误)", }, NO_SUITABLE_MODEL: { code: "MODEL.NO_SUITABLE_MODEL", + category: "configuration", message: (groupName: string) => `在模型组 '${groupName}' 中未找到合适的模型`, suggestion: "请检查模型组的配置。确保所列模型存在、其提供商已启用,并且它们具备所需的能力(例如 '聊天')", }, @@ -136,6 +180,7 @@ export const ErrorDefinitions = { NETWORK: { REQUEST_FAILED: { code: "NETWORK.REQUEST_FAILED", + category: "upstream_failure", message: "网络请求失败", suggestion: "请检查您服务器的互联网连接和 DNS 设置。如果您正在使用代理,请确保其配置正确且正在运行", }, @@ -144,16 +189,19 @@ export const ErrorDefinitions = { MEMORY: { PROVIDER_ERROR: { code: "MEMORY.PROVIDER_ERROR", + category: "upstream_failure", message: "记忆提供商发生错误", suggestion: "请检查记忆提供商的配置并确保其设置正确。如果问题仍然存在,请考虑报告此问题", }, SEARCH_FAILED: { code: "MEMORY.SEARCH_FAILED", + category: "internal", message: "搜索记忆失败", suggestion: "这可能是由于内部错误。请检查日志以获取更多详情。如果问题仍然存在,请考虑报告此问题", }, EMBEDDING_FAILED: { code: "MEMORY.EMBEDDING_FAILED", + category: "upstream_failure", message: "为记忆生成嵌入向量失败", suggestion: "这可能是由于内部错误。请检查日志以获取更多详情。如果问题仍然存在,请考虑报告此问题", }, diff --git a/packages/core/src/shared/errors/index.ts b/packages/core/src/shared/errors/index.ts index 00a29785e..cabd8cf2c 100644 --- a/packages/core/src/shared/errors/index.ts +++ b/packages/core/src/shared/errors/index.ts @@ -1,9 +1,10 @@ import { Logger, Schema } from "koishi"; import { v4 as uuidv4 } from "uuid"; +import type { ToolError } from "../../extension/types"; import { sanitizeDiagnostic, redactDiagnosticText } from "../../shared/diagnostic-sanitizer"; import { truncate } from "../../shared/utils"; -import { ErrorDefinitions } from "./definitions"; +import { ErrorDefinitions, type ErrorCategory } from "./definitions"; import { diagnosticId, diagnosticCode, summarizeContext, summarizeError } from "./report-summary"; // --- 错误上报模块 --- @@ -120,7 +121,7 @@ export class ErrorReporter { } private formatErrorDump(context: ReportContext): string { - const error = context.error instanceof AppError ? context.error : new AppError(ErrorDefinitions.SYSTEM.UNKNOWN, { cause: context.error }); + const error = normalizeAppError(context.error); // Credential filtering includes nested Error fields and additionalInfo before // applying the stricter outbound content policy. Neither step mutates inputs. const detailed = !!this.config.includeSensitiveInfo; @@ -178,16 +179,20 @@ export function initializeErrorReporter( globalErrorReporter = new ErrorReporter(config, logger, saveLocal, knownSecrets); } -type ErrorDomains = keyof typeof ErrorDefinitions; - -export type ErrorDefinitionValue = { - [K in ErrorDomains]: (typeof ErrorDefinitions)[K][keyof (typeof ErrorDefinitions)[K]]; -}[ErrorDomains]; +export interface ErrorDefinitionValue { + code: string; + message: string | ((...args: any[]) => string); + suggestion: string | ((...args: any[]) => string); + category?: ErrorCategory; + retryable?: boolean; +} export class AppError extends Error { public readonly code: string; public readonly suggestion: string; public readonly errorId: string; + public readonly category: ErrorCategory; + public readonly retryable: boolean; public context?: Record; @@ -195,7 +200,8 @@ export class AppError extends Error { definition: ErrorDefinitionValue, options?: { context?: Record; - cause?: Error; + cause?: unknown; + errorId?: string; args?: any[]; }, ) { @@ -220,7 +226,9 @@ export class AppError extends Error { this.code = definition.code; this.suggestion = suggestion; this.context = options?.context; - this.errorId = uuidv4(); + this.errorId = options?.errorId ?? uuidv4(); + this.category = definition.category ?? "internal"; + this.retryable = definition.retryable ?? false; Object.setPrototypeOf(this, AppError.prototype); } @@ -239,20 +247,7 @@ export class AppError extends Error { * @returns 返回生成的唯一错误 ID */ export function handleError(logger: Logger, error: unknown, contextDescription: string): string { - let appError: AppError; - - // 步骤 1: 确保错误是 AppError 类型 - // 如果捕获到的不是 AppError,则将其包装成一个通用的系统未知错误,以便统一处理 - if (error instanceof AppError) { - appError = error; - } else { - // 保留原始错误信息作为排查线索 - const cause = error instanceof Error ? error : undefined; - appError = new AppError(ErrorDefinitions.SYSTEM.UNKNOWN, { - cause, - context: { capturedValue: error }, - }); - } + const appError = normalizeAppError(error); const { errorId, message, suggestion, context, stack } = appError; @@ -301,3 +296,66 @@ export function handleError(logger: Logger, error: unknown, contextDescription: } export * from "./definitions"; + +const errorCatalog = new Map( + Object.values(ErrorDefinitions).flatMap((domain) => Object.values(domain).map((definition) => [definition.code, definition] as const)), +); +const boundedText = (value: unknown, limit: number): value is string => typeof value === "string" && value.length > 0 && value.length <= limit; + +/** The validated fields available across package copies or serialized transport. */ +export interface AppErrorEnvelope { + name: "AppError"; + code: string; + message: string; + suggestion: string; + errorId: string; + category?: ErrorCategory; + retryable?: boolean; +} + +/** Validates a transported/duplicate-package AppError envelope, never a bare code. */ +export function isAppError(value: unknown): value is AppError | AppErrorEnvelope { + if (value instanceof AppError) return true; + if (!value || typeof value !== "object") return false; + const error = value as Record; + const definition = typeof error.code === "string" ? errorCatalog.get(error.code) : undefined; + return ( + !!definition && + error.name === "AppError" && + boundedText(error.message, 4096) && + boundedText(error.suggestion, 4096) && + typeof error.errorId === "string" && + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(error.errorId) && + (error.category === undefined || error.category === definition.category) && + (error.retryable === undefined || error.retryable === ("retryable" in definition ? definition.retryable : false)) + ); +} + +/** Internal normalization retains the original thrown value as cause. */ +export function normalizeAppError(error: unknown): AppError { + if (isAppError(error)) { + if (error instanceof AppError) return error; + return new AppError(errorCatalog.get(error.code)!, { errorId: error.errorId, cause: error }); + } + return new AppError(ErrorDefinitions.SYSTEM.UNKNOWN, { cause: error }); +} + +/** Public allowlist projection. Dynamic diagnostic arguments never cross this boundary. */ +export function fromAppError(error: AppError): ToolError { + const normalized = normalizeAppError(error); + const definition = errorCatalog.get(normalized.code) ?? ErrorDefinitions.SYSTEM.UNKNOWN; + return { + name: "AppError", + code: definition.code, + message: typeof definition.message === "string" ? definition.message : `操作失败(${definition.code})`, + suggestion: typeof definition.suggestion === "string" ? definition.suggestion : "请检查配置与日志后重试", + errorId: normalized.errorId, + category: definition.category, + retryable: "retryable" in definition ? definition.retryable : false, + }; +} + +/** Normalize a thrown value; explicit legacy ToolError results continue through Failed unchanged. */ +export function toToolError(error: unknown): ToolError { + return fromAppError(normalizeAppError(error)); +} diff --git a/packages/core/tests/tool-error-normalization.spec.ts b/packages/core/tests/tool-error-normalization.spec.ts new file mode 100644 index 000000000..a2dd5a026 --- /dev/null +++ b/packages/core/tests/tool-error-normalization.spec.ts @@ -0,0 +1,90 @@ +import { Schema } from "koishi"; +import { describe, expect, it } from "vitest"; + +import { Failed, Success } from "../src/extension/helpers"; +import { ToolService } from "../src/extension/service"; +import { AppError, ErrorDefinitions, fromAppError, normalizeAppError, toToolError } from "../src/shared/errors"; + +describe("public tool error boundary", () => { + it("keeps successful and legacy structured/string failures compatible", () => { + expect(Success([])).toMatchObject({ status: "success", result: [] }); + expect(Failed("old message").error).toEqual({ name: "ToolError", message: "old message" }); + const legacy = { name: "OldError", message: "old", retryable: true }; + expect(Failed(legacy).error).toBe(legacy); + }); + it("projects known fields with one ID and omits cause/context/stack", () => { + const error = new AppError(ErrorDefinitions.LLM.TIMEOUT, { cause: new Error("secret"), context: { token: "secret" } }); + expect(fromAppError(error)).toMatchObject({ code: "LLM.TIMEOUT", category: "timeout", errorId: error.errorId, retryable: false }); + expect(JSON.stringify(fromAppError(error))).not.toMatch(/secret|cause|context|stack/); + expect(toToolError(error)).toEqual(fromAppError(error)); + }); + it("retains unknown causes internally while redacting their public text", () => { + const cause = new Error("Bearer sensitive-token\n at private/path"); + const normalized = normalizeAppError(cause); + expect(normalized.cause).toBe(cause); + expect(toToolError(cause)).toMatchObject({ code: "SYSTEM.UNKNOWN", category: "internal", retryable: false }); + expect(JSON.stringify(toToolError(cause))).not.toMatch(/sensitive-token|private\/path/); + }); + it("validates cross-package envelopes instead of trusting arbitrary codes", () => { + const error = new AppError(ErrorDefinitions.LLM.TIMEOUT); + const envelope = { name: error.name, code: error.code, errorId: error.errorId, message: error.message, suggestion: error.suggestion }; + expect(toToolError(envelope).errorId).toBe(error.errorId); + expect(toToolError({ code: error.code, message: "secret" }).code).toBe("SYSTEM.UNKNOWN"); + expect(toToolError({ ...envelope, errorId: "bad\nsecret" }).code).toBe("SYSTEM.UNKNOWN"); + }); + it.each([new Error("secret"), null, new AppError(ErrorDefinitions.LLM.TIMEOUT)])("normalizes thrown values without adding retries (%s)", async (error) => { + let calls = 0; + const tool = { + parameters: Schema.object({}), + execute: async () => { + calls++; + throw error; + }, + }; + const service = { + getTool: () => tool, + _logger: { info() {}, warn() {}, error() {}, debug() {}, success() {} }, + config: { advanced: { maxRetry: 2 } }, + executeInvocation: ToolService.prototype["executeInvocation"], + deps: {}, + } as unknown as ToolService; + const result = await ToolService.prototype.invoke.call(service, "test", {}, {} as any); + expect(result.status).toBe("error"); + expect(result.error?.code).toBe(error instanceof AppError ? error.code : "SYSTEM.UNKNOWN"); + expect(result.error?.message).not.toContain("secret"); + expect(calls).toBe(1); + }); +}); + +it("retains explicit legacy structured retry eligibility and attempt limits", async () => { + for (const retryable of [false, true]) { + let calls = 0; + const legacy = Failed({ name: "Legacy", message: "original text", retryable }); + const tool = { + parameters: Schema.object({}), + execute: async () => { + calls++; + return legacy; + }, + }; + const service = { + getTool: () => tool, + _logger: { info() {}, warn() {}, error() {}, debug() {}, success() {} }, + config: { advanced: { maxRetry: 2 } }, + executeInvocation: ToolService.prototype["executeInvocation"], + deps: {}, + } as unknown as ToolService; + const result = await ToolService.prototype.invoke.call(service, "legacy", {}, {} as any); + expect(result).toBe(legacy); + expect(calls).toBe(retryable ? 3 : 1); + } +}); + +it("keeps local custom AppError identity and cause while projecting safe unknown public fields", () => { + const cause = new Error("private-token"); + const error = new AppError({ code: "PLUGIN.LOCAL", message: "private-token", suggestion: "private-token" }, { cause }); + expect(normalizeAppError(error)).toBe(error); + expect(normalizeAppError(error).cause).toBe(cause); + expect(toToolError(error)).toMatchObject({ code: "SYSTEM.UNKNOWN", errorId: error.errorId, category: "internal", retryable: false }); + expect(JSON.stringify(toToolError(error))).not.toContain("private-token"); +}); diff --git a/packages/person-memory/src/index.ts b/packages/person-memory/src/index.ts index 17ef65716..8e8b062f3 100644 --- a/packages/person-memory/src/index.ts +++ b/packages/person-memory/src/index.ts @@ -136,7 +136,13 @@ export interface Dependencies { }; } const Success = (result: unknown) => ({ status: "success", result }); -const Failed = (error: unknown) => ({ status: "error", error: { name: "PersonMemoryError", message: error instanceof Error ? error.message : String(error) } }); +const Failed = (error: unknown) => ({ + status: "error", + error: + typeof core.isAppError === "function" && typeof core.toToolError === "function" && core.isAppError(error) + ? core.toToolError(error) + : { name: "PersonMemoryError", message: error instanceof Error ? error.message : String(error) }, +}); const key = (session: Session) => sceneKey(session as unknown as SceneInput); function profileView(p: Person) { return { diff --git a/packages/person-memory/src/store.ts b/packages/person-memory/src/store.ts index b2b048c0a..61e2709d1 100644 --- a/packages/person-memory/src/store.ts +++ b/packages/person-memory/src/store.ts @@ -1,11 +1,17 @@ import { createHash, randomUUID } from "node:crypto"; import type { Context } from "koishi"; -import { conversationChannelId } from "koishi-plugin-yesimbot"; +import { AppError, ErrorDefinitions, conversationChannelId } from "koishi-plugin-yesimbot"; import { applyClaimChanges, projectClaims, retireClaims, claimEvidence as allClaimEvidence, type Claim, type ClaimChange } from "./claims"; import { validateProfileDocument, renderProfileDocument, type ProfileDocument } from "./profile"; +/** Keep version guards usable with cores predating the typed person error catalog. */ +function versionConflict(message: string): Error { + const definition = ErrorDefinitions.PERSON_MEMORY?.VERSION_CONFLICT; + return definition ? new AppError(definition, { args: [message] }) : new Error(message); +} + export type Mode = "off" | "review" | "auto"; export interface SceneInput { platform: string; @@ -831,7 +837,7 @@ export class PersonStore { if (p.locked) throw new Error("画像已被管理员锁定"); if (p.claims?.length) throw new Error("已有主张记录,请使用主张修订而非整篇覆写"); if (expected && (p.id !== expected.personId || p.revision !== expected.personRevision || a.revision !== expected.accountRevision)) - throw new Error("总结期间发生人工修改或身份变更,候选已过期"); + throw versionConflict("总结期间发生人工修改或身份变更,候选已过期"); const ids = new Set(messageIds); const sources = typeof input === "string" @@ -904,7 +910,7 @@ export class PersonStore { p = state.people[a.personId]; if (p.locked) throw new Error("画像已被管理员锁定"); if (!expected || p.id !== expected.personId || p.revision !== expected.personRevision || a.revision !== expected.accountRevision) - throw new Error("身份或画像版本已变化"); + throw versionConflict("身份或画像版本已变化"); const sources = await this.currentProfileSources(scope, state, userId, 0); const evidence = claimChanges.map((change) => { if (!Array.isArray(change.messageIds) || change.messageIds.length > 10 || (change.action !== "retire" && !change.messageIds.length)) diff --git a/packages/person-memory/tests/profile-tools.spec.ts b/packages/person-memory/tests/profile-tools.spec.ts index 28b30b4cb..9defd4c3d 100644 --- a/packages/person-memory/tests/profile-tools.spec.ts +++ b/packages/person-memory/tests/profile-tools.spec.ts @@ -1,3 +1,4 @@ +import { ErrorDefinitions } from "koishi-plugin-yesimbot"; import { expect, it } from "vitest"; import { apply } from "../src/index"; @@ -127,3 +128,55 @@ for (const shared of [false, true]) { expect(read.result.profile.endsWith(read.result.overview)).toBe(true); }); } + +for (const action of ["propose", "propose_claim"]) + it(`classifies stale ${action} candidates through the plugin failure boundary`, async (t) => { + const f = await setup(t, false); + const found = (await f.store.find(f.scope, "u"))!; + await f.store.setProfile(f.scope, "u", "管理员刚刚更新", "admin"); + await f.app.parallel("yesimbot/before-user-stimulus" as any, { + ...f.session, + author: { name: "u" }, + messageId: "fresh", + content: "我喜欢 Python", + timestamp: Date.now() + 1, + }); + const source = (await f.store.profileSources(f.scope, "u", 0))[0]; + const result = await f.tool.execute({ + session: f.session, + action, + account_id: "u", + profile: "旧候选", + message_ids: [source.id], + person_id: found.person.id, + person_revision: found.person.revision, + account_revision: found.accounts[0].revision, + changes: [{ action: "support", category: "preferences", statement: "旧候选", messageIds: [source.id] }], + }); + expect(result.status).toBe("error"); + expect(result.error).toMatchObject({ code: "PERSON_MEMORY.VERSION_CONFLICT", category: "conflict", retryable: false }); + expect(result.error.errorId).toMatch(/^[0-9a-f-]{36}$/); + expect(JSON.stringify(result)).not.toMatch(/stack|cause|context/); + expect((await f.store.find(f.scope, "u"))!.person.profile).toContain("管理员刚刚更新"); + }); + +it("preserves the conflict guard when an older core has no person error catalog", async (t) => { + const f = await setup(t, false); + const found = (await f.store.find(f.scope, "u"))!; + await f.store.setProfile(f.scope, "u", "管理员刚刚更新", "admin"); + const catalog = ErrorDefinitions as any; + const saved = catalog.PERSON_MEMORY; + try { + delete catalog.PERSON_MEMORY; + await expect( + f.store.propose(f.scope, "u", "旧候选", ["source"], "model", { + personId: found.person.id, + personRevision: found.person.revision, + accountRevision: found.accounts[0].revision, + }), + ).rejects.toThrow("总结期间发生人工修改或身份变更,候选已过期"); + expect((await f.store.find(f.scope, "u"))!.person.profile).toContain("管理员刚刚更新"); + } finally { + catalog.PERSON_MEMORY = saved; + } +});