From fe4a40613a99a72325dbfcc5703ad3d0ca58ea85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=AE=B8=E4=BB=99xhcz?= Date: Sun, 25 Oct 2026 09:29:21 +0800 Subject: [PATCH 1/6] =?UTF-8?q?feat(v3-dev):=20=E6=B7=BB=E5=8A=A0=E5=8F=AF?= =?UTF-8?q?=E9=80=89=E4=BC=9A=E8=AF=9D=E7=BB=AD=E6=8E=A5=E5=B9=B6=E5=AE=8C?= =?UTF-8?q?=E5=96=84=E5=90=8E=E5=8F=B0=E5=B7=A5=E5=85=B7=E4=B8=8E=E4=B8=8A?= =?UTF-8?q?=E4=B8=8B=E6=96=87=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/background-tools.md | 21 +- docs/conversation-continuation.md | 45 ++++ packages/core/client/context-capacity.ts | 73 ------ packages/core/client/index.ts | 23 -- packages/core/client/section.css | 36 --- packages/core/src/agent/agent-core.ts | 114 ++++++++- packages/core/src/agent/config.ts | 47 +++- packages/core/src/agent/context-builder.ts | 96 +++++++- packages/core/src/agent/context-packing.ts | 7 +- packages/core/src/agent/continuation.ts | 37 +++ packages/core/src/agent/decision-journal.ts | 24 ++ packages/core/src/agent/decision-record.ts | 8 + packages/core/src/agent/willing.ts | 9 +- .../core/src/extension/background-tools.ts | 13 +- packages/core/src/extension/builtin/memory.ts | 10 +- packages/core/src/extension/service.ts | 42 +++- packages/core/src/model/config.ts | 23 +- packages/core/src/model/context-limit.ts | 48 +++- packages/core/src/world/conversation-state.ts | 74 +++++- packages/core/src/world/service.ts | 10 +- .../core/tests/background-commands.spec.ts | 2 +- packages/core/tests/background-policy.spec.ts | 16 ++ packages/core/tests/background-tools.spec.ts | 85 +++++++ .../core/tests/config-history-context.spec.ts | 14 +- .../core/tests/context-capacity-input.spec.ts | 158 ++++-------- .../context-working-state-failure.spec.ts | 65 +++++ .../tests/conversation-continuation.spec.ts | 91 +++++++ .../core/tests/conversation-state.spec.ts | 85 +++++++ packages/core/tests/decision-core.spec.ts | 108 +++++++++ .../tests/history-clear-recording.spec.ts | 227 +++++++++--------- 30 files changed, 1182 insertions(+), 429 deletions(-) create mode 100644 docs/conversation-continuation.md delete mode 100644 packages/core/client/context-capacity.ts create mode 100644 packages/core/src/agent/continuation.ts create mode 100644 packages/core/tests/conversation-continuation.spec.ts diff --git a/docs/background-tools.md b/docs/background-tools.md index fcdf515ba..aab9b2e12 100644 --- a/docs/background-tools.md +++ b/docs/background-tools.md @@ -6,15 +6,16 @@ 在“执行策略 → 后台工具任务”中配置: -| 配置 | 行为 | 默认值 | -| ------------------------ | -------------------------------------------------- | -------------- | -| 启用 | 允许模型提交后台任务 | 关闭 | -| 任务完成处理方式 | 下轮对话读取,或完成后进行正常回复意愿判断 | 下轮读取 | -| 完成意愿结算单位 | 每任务,或同轮对话提交的全部后台任务结束后统一结算 | 按对话轮次聚合 | -| 成功、失败、取消意愿增量 | 分别设置非负数,可为零和小数 | 均为 0 | -| 并发上限 | 当前插件实例最多同时执行多少后台任务 | 4 | -| 保留任务上限 | 包括执行中与已结束任务;优先淘汰可清理的旧结果 | 128 | -| 执行超时 | 到期请求取消 | 120 秒 | +| 配置 | 行为 | 默认值 | +| ------------------------ | -------------------------------------------------- | ------------------------ | +| 启用 | 允许模型提交后台任务 | 关闭 | +| 允许后台执行的工具 | 勾选模型可提交后台的工具;取消勾选不影响普通调用 | 搜索、网页读取、图片描述 | +| 任务完成处理方式 | 下轮对话读取,或完成后进行正常回复意愿判断 | 下轮读取 | +| 完成意愿结算单位 | 每任务,或同轮对话提交的全部后台任务结束后统一结算 | 按对话轮次聚合 | +| 成功、失败、取消意愿增量 | 分别设置非负数,可为零和小数 | 均为 0 | +| 并发上限 | 当前插件实例最多同时执行多少后台任务 | 4 | +| 保留任务上限 | 包括执行中与已结束任务;优先淘汰可清理的旧结果 | 128 | +| 执行超时 | 到期请求取消 | 120 秒 | “同轮对话”包括一次接话周期内的多次心跳,不是单次模型 HTTP 请求。聚合模式等待该周期不再提交任务且全部任务结束后结算一次;混合结果按失败优先、其次取消、否则成功分类。容量已满且没有可淘汰记录时,新提交会明确失败,不自动重试。 @@ -26,7 +27,7 @@ - `background_task_query`:提供 `id` 读取状态及结果;省略 `id` 列出最近任务与可提交后台的工具名称。 - `background_task_cancel`:指定 `id` 请求取消。模型结合当前用户要求和提示词决定是否调用。 -初始支持 `web_search`、`fetch_webpage`、`get_image_description`,以各工具当前可用条件为准。发送消息、修改配置及身份关联等工具不自动加入。第三方扩展可通过 `ToolMetadata.background` 或 `ToolDefinition.background` 显式声明支持;该声明仅适用于独立操作,不能替代每次调用的数据依赖判断。 +默认勾选 `web_search`、`fetch_webpage`、`get_image_description`,以各工具当前可用条件为准。可在复选列表中取消勾选或全部取消;新加载的第三方工具需要手动勾选。只有声明支持后台执行且已被勾选的工具才能提交后台。运行中撤销后台权限后,该任务不会再向会话提交结果或完成意愿。发送消息、修改配置及身份关联等工具不自动加入。第三方扩展可通过 `ToolMetadata.background` 或 `ToolDefinition.background` 显式声明支持;该声明仅适用于独立操作,不能替代每次调用的数据依赖判断。 每次构建模型上下文会提供当前会话最近 8 项任务快照。快照只含状态、工具名称、时间及有长度限制的真实进度,不包含完整结果;完整结果需查询,过长结果继续使用分页读取工具。自定义提示词模板也会收到转义后的任务快照。结果与进度属于观察数据,不能视为系统指令。 diff --git a/docs/conversation-continuation.md b/docs/conversation-continuation.md new file mode 100644 index 000000000..637b35f63 --- /dev/null +++ b/docs/conversation-continuation.md @@ -0,0 +1,45 @@ +# 会话续接 + +会话续接用于处理模型明确等待的后续消息。默认关闭;不需要 TypeSafe、JEV 或额外的判断模型。它复用当前会话的工作状态及原始消息来源。 + +开启后,模型可以通过 `conversation_state_update` 的可选 `followUp` 字段登记等待的用户 ID 和有效时间。非空等待必须引用当前会话中的原始消息,并提交当前 `expectedRevision`。此工具完整替换工作状态;省略 `followUp` 会移除原来的等待。 + +```json +{ + "expectedRevision": 0, + "topic": "待确认事项", + "openIssues": ["等待确认后继续"], + "sourceMessageIds": ["原始消息ID"], + "followUp": { "userIds": ["用户ID"], "durationSeconds": 120 } +} +``` + +用户 ID 应来自当前消息与上下文;登记等待不代表已经确认用户意图。收到指定用户的消息后,明显提及或引用其他人的消息不会命中续接。对于没有显式指向的消息,仍可能出现误接,应由提示词和模型结合上下文决定是否发言、是否移除或调整等待。 + +## 配置 + +`continuation` 位于 Agent 的意愿设置中。 + +| 字段 | 默认值 | 作用 | +| -------------------- | --------- | -------------------------------------------------------------- | +| `enabled` | `false` | 允许登记和使用会话等待 | +| `mode` | `trigger` | `trigger` 进入模型回合;`willingness` 只增加意愿后按原概率判断 | +| `willingnessGain` | `35` | 仅增加意愿模式的增益 | +| `maxDurationSeconds` | `300` | 单次登记等待的最长有效时间,范围 1–86400 秒 | + +进入模型回合后仍可保持沉默、调用工具或更新工作状态。会话忙碌时沿用原意愿与调度路径,不额外查询等待状态。续接不绕过频道权限、禁言、回复抑制和新消息处理策略。存在回复抑制规则时不应用续接;规则到期或解除后,仅对之后的新消息重新判断。 + +## 生命周期与上下文 + +- 同一实例、平台、机器人账号、频道及频道类型的工作状态分别保存。 +- 等待登记后使用固定截止时间;读取和收到消息不会延长等待。等待期间可能多次命中,模型应在等待完成或意图改变后移除或替换它。 +- 管理者调低最长等待时间后,已有等待也会受更短的上限约束。 +- 状态读取会验证原始来源。来源丢失、内容改变、历史清除或版本替换后,旧等待不能继续作为触发依据。 +- 排队后、准备模型上下文时会再次检查等待,仅依赖续接的直接触发模式获准处理的消息在等待到期或被替换后不再执行;本来就符合普通触发条件的消息继续处理。 +- 开启续接时,当前有效工作状态关联的原始消息会按需回到本轮上下文。它们是旧来源的临时投影,不写回历史,也不作为新消息或新证据。 +- 后台任务完成时,会尽量带回该任务来源消息及其引用。来源不可读取时保留缺失标记,模型可决定重新查询或结束。 +- 状态读取失败时回退到普通意愿判断。该功能增加本地状态和来源查询,不新增模型推理请求。 + +`conversation_focus` 包含有效的工作状态、续接配置及本次命中的来源信息。可以通过现有决策查询查看续接模式和工作状态版本;这些记录不保存原始消息正文。 + +仅增加意愿模式下,已获得的意愿沿用原有衰减与发言成本规则;等待到期不会收回已经获得的意愿,也不会取消由普通概率判断获准的处理。 diff --git a/packages/core/client/context-capacity.ts b/packages/core/client/context-capacity.ts deleted file mode 100644 index 8a517d4cf..000000000 --- a/packages/core/client/context-capacity.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { computed, defineComponent, h, ref, watch } from "vue"; - -import { parseContextLimit } from "../src/model/context-limit"; - -/** Keep the persisted string format so existing configs and runtime readers remain compatible. */ -export const ContextCapacityInput = defineComponent({ - name: "YibContextCapacityInput", - props: { modelValue: String, disabled: Boolean }, - emits: ["update:modelValue"], - setup(props, { emit }) { - const amount = ref(""); - const unit = ref("K"); - const serialized = () => (amount.value ? `${amount.value}${unit.value}` : ""); - watch( - () => props.modelValue, - (value) => { - // A parent echo must not reset the selected unit while clearing the number. - if (value === serialized()) return; - const match = /^\s*(\d+(?:\.\d+)?|\.\d+)\s*([km]?)\s*$/i.exec(value ?? ""); - amount.value = match?.[1] ?? value ?? ""; - unit.value = match ? match[2].toUpperCase() : value ? "" : "K"; - }, - { immediate: true }, - ); - const error = computed(() => { - try { - parseContextLimit(serialized()); - return ""; - } catch (error) { - return (error as Error).message; - } - }); - return () => - h("div", { class: "yib-context-capacity" }, [ - h("div", { class: "yib-context-capacity-row", role: "group", "aria-label": "最大上下文容量" }, [ - h("input", { - type: "text", - inputmode: "decimal", - "aria-label": "上下文数值", - "aria-invalid": !!error.value, - value: amount.value, - disabled: props.disabled, - placeholder: "例如 128 或 1.5", - onInput: (event: Event) => { - if (props.disabled) return; - const value = (event.target as HTMLInputElement).value; - // Also accept pasting an old capacity such as 1M into the number cell. - const match = /^\s*(\d+(?:\.\d+)?|\.\d+)\s*([km])\s*$/i.exec(value); - amount.value = match?.[1] ?? value; - if (match) unit.value = match[2].toUpperCase(); - emit("update:modelValue", serialized()); - }, - }), - h( - "select", - { - "aria-label": "上下文单位", - value: unit.value, - disabled: props.disabled, - onChange: (event: Event) => { - if (props.disabled) return; - unit.value = (event.target as HTMLSelectElement).value; - emit("update:modelValue", serialized()); - }, - }, - [h("option", { value: "" }, "token"), h("option", { value: "K" }, "K"), h("option", { value: "M" }, "M")], - ), - ]), - h("small", { class: "yib-context-capacity-hint" }, "1K = 1000 token;1M = 1000000 token"), - error.value ? h("small", { class: "yib-context-capacity-error", role: "alert" }, error.value) : null, - ]); - }, -}); diff --git a/packages/core/client/index.ts b/packages/core/client/index.ts index e5bf30fad..6859f0b43 100644 --- a/packages/core/client/index.ts +++ b/packages/core/client/index.ts @@ -1,8 +1,5 @@ -import { SchemaBase } from "@koishijs/client"; import { computed, defineComponent, h, ref, resolveComponent } from "vue"; -import { ContextCapacityInput } from "./context-capacity"; - import "./section.css"; let nextSectionId = 0; @@ -52,26 +49,6 @@ export const ConfigSection = defineComponent({ }); export default function apply(ctx) { - ctx.extendSchema({ - type: "string", - role: "yib-context-capacity", - component: defineComponent({ - props: ["schema", "modelValue", "initial", "disabled", "prefix", "extra"], - emits: ["update:modelValue"], - setup(props, { emit, slots }) { - return () => - h(SchemaBase, props, { - ...slots, - control: () => - h(ContextCapacityInput, { - modelValue: props.modelValue, - disabled: props.disabled, - "onUpdate:modelValue": (value) => emit("update:modelValue", value), - }), - }); - }, - }), - }); for (const type of ["object", "intersect"]) { ctx.extendSchema({ type, role: "yib-section", component: ConfigSection }); } diff --git a/packages/core/client/section.css b/packages/core/client/section.css index 66f155baf..92538f66f 100644 --- a/packages/core/client/section.css +++ b/packages/core/client/section.css @@ -1,39 +1,3 @@ -.yib-context-capacity-row { - display: grid; - grid-template-columns: minmax(0, 1fr) 5rem; - width: 18rem; - max-width: 100%; -} -.yib-context-capacity-row > input, -.yib-context-capacity-row > select { - min-width: 0; - box-sizing: border-box; - border: 1px solid var(--k-color-divider); - padding: 8px; - color: var(--k-text-normal); - background: var(--k-card-bg); - font: inherit; -} -.yib-context-capacity-row > input { - border-radius: 4px 0 0 4px; -} -.yib-context-capacity-row > select { - border-left: 0; - border-radius: 0 4px 4px 0; -} -.yib-context-capacity-row > :focus-visible { - outline: 2px solid var(--k-color-primary); - outline-offset: -2px; -} -.yib-context-capacity-hint, -.yib-context-capacity-error { - display: block; - margin-top: 6px; - font-size: 0.8rem; -} -.yib-context-capacity-error { - color: var(--k-color-danger); -} .yib-config-section { border: 1px solid var(--k-color-divider); border-radius: 8px; diff --git a/packages/core/src/agent/agent-core.ts b/packages/core/src/agent/agent-core.ts index 1565f790b..bffaa33c6 100644 --- a/packages/core/src/agent/agent-core.ts +++ b/packages/core/src/agent/agent-core.ts @@ -14,6 +14,7 @@ import { YesImBotService } from "../shared/service"; import { conversationChannelId, conversationCid } from "../shared/utils/conversation-scope"; import { AgentStimulus, WorldStateService } from "../world"; import { PromptContextBuilder } from "./context-builder"; +import { matchContinuation, sameContinuation, type ContinuationMatch } from "./continuation"; import { registerDecisionCommands } from "./decision-commands"; import { DecisionJournal } from "./decision-journal"; import { DecisionRecord, DecisionRecords, formatDecision, describeDecisionStage } from "./decision-record"; @@ -26,7 +27,7 @@ import { TopicManager, TopicSnapshot } from "./topics"; import { TypeSafeEvaluator } from "./typesafe"; import { WillingnessManager } from "./willing"; -type TracedStimulus = AgentStimulus & { decisionId?: string; topic?: TopicSnapshot }; +type TracedStimulus = AgentStimulus & { decisionId?: string; topic?: TopicSnapshot; continuation?: ContinuationMatch; continuationRequired?: boolean }; declare module "koishi" { interface Tables { @@ -58,6 +59,8 @@ export class AgentCore extends YesImBotService { private modelSwitcher: ChatModelSwitcher; private readonly pendingAssessments = new Map; token: number }>(); private stopped = false; + private continuationReads = new Map>(); + private continuationEpochs = new Map(); private decisionJournal?: DecisionJournal; private readonly decisions = new DecisionRecords(1000, Date.now, (record) => { this.initializeDecisionJournal(); @@ -329,6 +332,14 @@ export class AgentCore extends YesImBotService { this.toolService.background?.isCompletionCurrent(stimulus.session, stimulus.payload) === true); try { await this.replyControl.flush(); + const continuation = (stimulus as TracedStimulus).continuation; + if (continuation && (stimulus as TracedStimulus).continuationRequired) { + const current = await this.worldState.getConversationState(stimulus.session); + if (!valid() || !sameContinuation(continuation, matchContinuation(stimulus.session, this.config.continuation, current))) { + this.recordDecision(stimulus, { stage: "cancelled", reason: "continuation_expired", success: false }); + return; + } + } if (!valid() || !this.allowedCategories(stimulus).length) { this.recordDecision(stimulus, { stage: "cancelled", reason: "invalid_generation", success: false }); return; @@ -438,6 +449,75 @@ export class AgentCore extends YesImBotService { } private processStimulus(stimulus: TracedStimulus, assessmentMultiplier = 1, allowSchedule = true): void { + if (stimulus.type !== "user_message" || !this.config.continuation?.enabled) { + this.processResolvedStimulus(stimulus, assessmentMultiplier, allowSchedule); + return; + } + const session = stimulus.session; + const target = this.replyTarget(session), + key = replyKey(target); + if (this.scheduler.isBusy(key)) { + this.processResolvedStimulus(stimulus, assessmentMultiplier, allowSchedule); + return; + } + const token = this.replyControl.token(target); + const scope = { + platform: session.platform, + channelId: conversationChannelId(session)!, + channelType: session.isDirect ? ("private" as const) : ("guild" as const), + }; + const generation = this.worldState.l2_manager.getHistoryGeneration(scope); + this.continuationEpochs ??= new Map(); + const epoch = this.continuationEpochs.get(key) ?? {}; + this.continuationEpochs.set(key, epoch); + const binding = () => JSON.stringify([this.replyTarget(session), session.userId]); + const original = binding(); + const valid = () => + !this.stopped && + this.continuationEpochs.get(key) === epoch && + binding() === original && + this.replyControl.valid(target, token) && + this.ctx.filter(session) !== false && + this.worldState.isChannelAllowed(session) && + this.worldState.l2_manager.getHistoryGeneration(scope) === generation && + !this.worldState.isBotMuted(conversationCid(session), session.selfId); + this.continuationReads ??= new Map(); + const previous = this.continuationReads.get(key) ?? Promise.resolve(); + const task = previous + .catch(() => {}) + .then(async () => { + if (!valid()) { + this.recordDecision(stimulus, { stage: "cancelled", reason: "invalid_generation" }); + return; + } + let working; + try { + working = await this.worldState.getConversationState(session); + } catch (error) { + if (valid()) this.logger.warn(`续接状态读取失败,沿用普通意愿:${String(error)}`); + } + if (!valid()) { + this.recordDecision(stimulus, { stage: "cancelled", reason: "invalid_generation" }); + return; + } + const continuation = this.replyControl.get(target) ? undefined : matchContinuation(session, this.config.continuation, working); + // Explicit source anchors take precedence over a cached, model-inferred topic. + this.processResolvedStimulus(continuation ? { ...stimulus, topic: undefined, continuation } : stimulus, assessmentMultiplier, allowSchedule); + }) + .catch((error) => { + this.recordDecision(stimulus, { stage: "failed", reason: "exception" }); + this.logger.warn(`续接消息处理失败:${String(error)}`); + }) + .finally(() => { + if (this.continuationReads.get(key) === task) { + this.continuationReads.delete(key); + this.continuationEpochs.delete(key); + } + }); + this.continuationReads.set(key, task); + } + + private processResolvedStimulus(stimulus: TracedStimulus, assessmentMultiplier = 1, allowSchedule = true): void { const { type, session } = stimulus; const allowed = this.allowedCategories(stimulus); if (!allowed.length) { @@ -462,14 +542,22 @@ export class AgentCore extends YesImBotService { const willingnessBefore = this.willing.getCurrentWillingness(topic?.scoreKey ?? channelCid); const replyRule = this.replyControl.get(this.replyTarget(session)); const categories = replyRule ? allowed : undefined; - const result = topic - ? this.willing.shouldReply(session, channelCid, categories, assessmentMultiplier, { + const continuationGain = stimulus.continuation?.mode === "willingness" ? (this.config.continuation?.willingnessGain ?? 0) : 0; + const args = [session, channelCid, categories, assessmentMultiplier] as const; + const topicInput = topic + ? { currentScoreKey: topic.scoreKey, multiplier: topic.multiplier, candidates, latestTopicPreference: this.config.topics?.latestTopicPreference, - }) - : this.willing.shouldReply(session, channelCid, categories, assessmentMultiplier); + } + : undefined; + const result = + continuationGain > 0 + ? this.willing.shouldReply(...args, topicInput, continuationGain) + : topicInput + ? this.willing.shouldReply(...args, topicInput) + : this.willing.shouldReply(...args); const scoreKey = result.scoreKey ?? channelCid; const willingnessAfter = this.willing.getCurrentWillingness(scoreKey); if (topic) { @@ -480,18 +568,27 @@ export class AgentCore extends YesImBotService { } } const forcedMention = this.config.prioritizeMentions && !replyRule && isBotMention(session) && allowed.includes("at"); - decision = !!forcedMention || result.decision; + const continued = stimulus.continuation?.mode === "trigger"; + decision = !!forcedMention || continued || result.decision; + stimulus = { ...stimulus, continuationRequired: continued && !forcedMention && !result.decision }; this.recordDecision(stimulus, { stage: "calculated", allowed, decision, forcedReply: !!forcedMention, + continuation: stimulus.continuation, probability: result.probability, roll: result.roll, calculation: result.calculation, score: willingnessAfter, participation: this.willing.getParticipation?.(channelCid), - reason: forcedMention ? "forced_reply_by_mention" : result.probability === 0 ? "below_threshold" : "probability_roll", + reason: forcedMention + ? "forced_reply_by_mention" + : continued + ? "conversation_continuation" + : result.probability === 0 + ? "below_threshold" + : "probability_roll", }); if (result.calculation) { @@ -544,6 +641,8 @@ export class AgentCore extends YesImBotService { for (const id of this.activeDecisionIds.values()) this.decisions.update(id, { stage: "cancelled", reason: "stopped", success: false }); this.activeDecisionIds.clear(); this.topics?.dispose(); + this.continuationReads?.clear(); + this.continuationEpochs?.clear(); this.scheduler.dispose(); this.willing.stopDecayCycle(); try { @@ -559,6 +658,7 @@ export class AgentCore extends YesImBotService { } private resetWillingness(channelKey: string): void { + this.continuationEpochs?.delete(channelKey); this.topics?.reset(channelKey); this.clearTopicScores(channelKey); this.willing.reset(channelKey); diff --git a/packages/core/src/agent/config.ts b/packages/core/src/agent/config.ts index c1bf561d1..7954937be 100644 --- a/packages/core/src/agent/config.ts +++ b/packages/core/src/agent/config.ts @@ -57,7 +57,15 @@ export interface TypeSafeConfig { influence: number; } +export interface ContinuationConfig { + enabled: boolean; + mode: "trigger" | "willingness"; + willingnessGain: number; + maxDurationSeconds: number; +} + export interface WillingnessConfig { + continuation?: ContinuationConfig; topics?: TopicConfig; participation?: { enabled: boolean; @@ -107,6 +115,16 @@ export interface WillingnessConfig { } const WillingnessConfigSchema: Schema = Schema.object({ + continuation: Schema.object({ + enabled: Schema.boolean().default(false).description("允许模型登记等待后续消息;无需额外判断模型"), + mode: Schema.union([Schema.const("trigger").description("进入模型回合"), Schema.const("willingness").description("仅增加意愿")]) + .default("trigger") + .description("等待的用户发送后续消息时"), + willingnessGain: Schema.number().min(0).max(1000000).default(35).description("仅增加意愿模式的增益"), + maxDurationSeconds: Schema.number().min(1).max(86400).default(300).description("单次等待的最长有效时间(秒)"), + }) + .collapse() + .description("会话续接(模型显式登记,默认关闭;仍遵守回复控制与新消息处理策略)"), topics: Schema.object({ enabled: Schema.boolean().default(false).experimental().description("启用实验性话题意愿,默认关闭;识别可能滞后或不准确,请按实际聊天效果调整"), model: Schema.dynamic("modelService.selectableModels").description("话题总结模型(需具备对话能力;启用后会发送近期聊天内容)"), @@ -205,8 +223,11 @@ export const VisionConfigSchema: Schema = Schema.object({ detail: Schema.union(["low", "high", "auto"]).default("low").description("图片细节程度"), }); +export const DEFAULT_BACKGROUND_TOOLS = ["web_search", "fetch_webpage", "get_image_description"]; + export interface BackgroundToolsConfig { enabled: boolean; + allowedTools?: string[]; completion: "next_cycle" | "stimulus"; settlement: "task" | "request"; willingness: { succeeded: number; failed: number; cancelled: number }; @@ -215,15 +236,22 @@ export interface BackgroundToolsConfig { timeoutMs: number; } -const backgroundWillingnessSchema = () => +const backgroundWillingnessFields: Schema = Schema.object({ + succeeded: Schema.number().min(0).max(1000000).default(0).description("成功完成时增加的意愿值"), + failed: Schema.number().min(0).max(1000000).default(0).description("执行失败时增加的意愿值"), + cancelled: Schema.number().min(0).max(1000000).default(0).description("任务取消时增加的意愿值"), +}); +const backgroundWillingnessSchema = Schema.intersect([ + backgroundWillingnessFields, Schema.transform( - Schema.number().min(0).max(1000000), + backgroundWillingnessFields, (value) => { - if (!Number.isFinite(value)) throw new TypeError("后台任务意愿值必须为有限数值"); + if (Object.values(value).some((amount) => !Number.isFinite(amount))) throw new TypeError("后台任务意愿值必须为有限数值"); return value; }, true, - ).default(0); + ), +]); export type AgentBehaviorConfig = ArousalConfig & WillingnessConfig & @@ -250,6 +278,9 @@ export const AgentBehaviorConfigSchema: Schema = Schema.int Schema.object({ backgroundTools: Schema.object({ enabled: Schema.boolean().default(false).description("允许模型提交支持后台执行的工具任务"), + allowedTools: Schema.dynamic("toolService.backgroundEligibleTools") + .default([...DEFAULT_BACKGROUND_TOOLS]) + .description("允许后台执行的工具(取消勾选不影响普通调用)"), completion: Schema.union([ Schema.const("next_cycle").description("下轮对话读取结果"), Schema.const("stimulus").description("完成后进行回复意愿判断"), @@ -262,13 +293,7 @@ export const AgentBehaviorConfigSchema: Schema = Schema.int ]) .default("request") .description("完成意愿结算单位"), - willingness: Schema.object({ - succeeded: backgroundWillingnessSchema().description("成功完成时增加的意愿值"), - failed: backgroundWillingnessSchema().description("执行失败时增加的意愿值"), - cancelled: backgroundWillingnessSchema().description("任务取消时增加的意愿值"), - }) - .collapse() - .description("后台任务完成意愿"), + willingness: backgroundWillingnessSchema.description("后台任务完成意愿"), maxConcurrent: Schema.natural().min(1).max(32).default(4).description("同时执行的后台任务数上限"), maxRetained: Schema.natural().min(1).max(1024).default(128).description("保留的后台任务数上限"), timeoutMs: Schema.natural().min(1000).max(3600000).default(120000).description("后台任务执行超时(毫秒)"), diff --git a/packages/core/src/agent/context-builder.ts b/packages/core/src/agent/context-builder.ts index 5a70f0d56..0e5683aee 100644 --- a/packages/core/src/agent/context-builder.ts +++ b/packages/core/src/agent/context-builder.ts @@ -1,5 +1,5 @@ import { ImagePart, TextPart } from "@xsai/shared-chat"; -import { Context, Logger } from "koishi"; +import { Context, Logger, h } from "koishi"; import { AssetService } from "../asset"; import { Config } from "../config"; @@ -10,7 +10,9 @@ import { ChatModelSwitcher } from "../model"; import { conversationChannelId } from "../shared/utils/conversation-scope"; import { AgentStimulus, ContextualMessage, UserMessagePayload, WorldState, WorldStateService } from "../world"; import { sessionChannelType } from "../world/channel-metadata"; +import type { ConversationStateResult } from "../world/conversation-state"; import { deriveConversationFocus, FocusedWorldState } from "./context-packing"; +import { matchContinuation, sameContinuation, type ContinuationMatch } from "./continuation"; import { assertReplyTurn } from "./reply-turn"; interface ImageCandidate { @@ -79,25 +81,105 @@ export class PromptContextBuilder { throw new Error("上下文构建期间历史已清除"); }; assertContextCurrent(); - const sourceWorldState = await this.worldStateService.buildWorldState(session); + let sourceWorldState = await this.worldStateService.buildWorldState(session); assertContextCurrent(); + if (type === "background_task_completion" && session.messageId && this.worldStateService.readMessageWindow) { + const present = [...sourceWorldState.l1_working_memory.processed_events, ...sourceWorldState.l1_working_memory.new_events].some( + (item) => item.type === "message" && item.id === session.messageId, + ); + if (!present) { + try { + const page = await this.worldStateService.readMessageWindow(session, { messageId: session.messageId, before: 0, after: 0, limit: 1 }); + assertContextCurrent(); + const sources = [page.anchor, ...page.quotes.flatMap((quote) => (quote.record ? [quote.record] : []))]; + const currentIds = new Set( + [...sourceWorldState.l1_working_memory.processed_events, ...sourceWorldState.l1_working_memory.new_events] + .filter((item) => item.type === "message") + .map((item) => item.id), + ); + const messages = sources + .filter((record) => !currentIds.has(record.id)) + .map((record) => ({ + type: "message" as const, + id: record.id, + sender: record.sender, + content: record.content, + quoteId: record.quoteId, + timestamp: new Date(record.timestamp), + elements: h.parse(record.content), + is_new: false, + })); + sourceWorldState = { + ...sourceWorldState, + l1_working_memory: { + ...sourceWorldState.l1_working_memory, + processed_events: [...messages, ...sourceWorldState.l1_working_memory.processed_events] + .filter( + (item, index, items) => + item.type !== "message" || items.findIndex((other) => other.type === "message" && other.id === item.id) === index, + ) + .sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime()), + }, + }; + } catch (error) { + assertContextCurrent(); + if (error instanceof Error && error.name === "AbortError") throw error; + this.logger.warn(`后台任务来源读取失败,保留缺失标记:${String(error)}`); + } + } + } const focus = deriveConversationFocus(stimulus, sourceWorldState); + if (this.config.continuation?.enabled) + focus.continuationPolicy = { + mode: this.config.continuation.mode, + maxDurationSeconds: this.config.continuation.maxDurationSeconds, + }; // Optional for older service adapters. The service validates raw sources and current scope. const stateService = this.worldStateService as WorldStateService & { - getConversationState?: (session: AgentStimulus["session"]) => Promise<{ - unknown: boolean; - state?: { revision: number; topic?: string; openIssues: string[]; sourceMessageIds: string[]; createdAt: string; updatedAt: string }; - }>; + getConversationState?: (session: AgentStimulus["session"], options?: { includeSources?: boolean }) => Promise; }; let working: Awaited>> | undefined; try { - working = await stateService.getConversationState?.(session); + working = await stateService.getConversationState?.(session, { includeSources: this.config.continuation?.enabled === true }); } catch (error) { assertContextCurrent(); if (error instanceof Error && error.name === "AbortError") throw error; this.logger.warn(`工作状态读取失败,继续使用 unknown:${String(error)}`); } assertContextCurrent(); + const traced = stimulus as AgentStimulus & { continuation?: ContinuationMatch; continuationRequired?: boolean }; + const continuation = traced.continuation; + const currentContinuation = matchContinuation(session, this.config.continuation, working); + if (traced.continuationRequired && !sameContinuation(continuation, currentContinuation)) throw new DOMException("会话等待已到期或被替换", "AbortError"); + if (sameContinuation(continuation, currentContinuation)) focus.continuation = currentContinuation; + if (this.config.continuation?.enabled && working?.unknown === false && working.sourceMessages?.length) { + const present = new Set( + [...sourceWorldState.l1_working_memory.processed_events, ...sourceWorldState.l1_working_memory.new_events] + .filter((item) => item.type === "message") + .map((item) => item.id), + ); + const recalled = working.sourceMessages + .filter((record) => !present.has(record.id)) + .map((record) => ({ + type: "message" as const, + id: record.id, + sender: record.sender, + content: record.content, + quoteId: record.quoteId, + timestamp: new Date(record.timestamp), + elements: h.parse(record.content), + is_new: false, + })); + sourceWorldState = { + ...sourceWorldState, + l1_working_memory: { + ...sourceWorldState.l1_working_memory, + processed_events: [...recalled, ...sourceWorldState.l1_working_memory.processed_events].sort( + (a, b) => a.timestamp.getTime() - b.timestamp.getTime(), + ), + }, + }; + } focus.explicitWorkingState = { ...(working?.unknown === false ? working.state : undefined), unknown: working?.unknown ?? true, diff --git a/packages/core/src/agent/context-packing.ts b/packages/core/src/agent/context-packing.ts index 7ce39b744..d39206e19 100644 --- a/packages/core/src/agent/context-packing.ts +++ b/packages/core/src/agent/context-packing.ts @@ -7,6 +7,8 @@ export interface ConversationFocus { target: { platform: string; selfId: string; channelId: string }; targetUserId?: string; triggerType: string; + continuation?: import("./continuation").ContinuationMatch; + continuationPolicy?: { mode: "trigger" | "willingness"; maxDurationSeconds: number }; triggerMessageIds: string[]; quoteMessageIds: string[]; missingMessageIds: string[]; @@ -18,6 +20,7 @@ export interface ConversationFocus { topic?: string; openIssues?: string[]; sourceMessageIds?: string[]; + followUp?: import("../world/conversation-state").FollowUpState; createdAt?: string; updatedAt?: string; sourceProvenance: "explicit_scoped_tool_state_not_verified_fact"; @@ -41,7 +44,9 @@ export function deriveConversationFocus(stimulus: AgentStimulus, world: Wor const ids = stimulus.type === "user_message" && Array.isArray(stimulus.payload?.messageIds) ? [...new Set(stimulus.payload.messageIds.filter((id: unknown): id is string => typeof id === "string" && !!id))] - : []; + : stimulus.type === "background_task_completion" && session.messageId + ? [session.messageId] + : []; const messages = [...world.l1_working_memory.processed_events, ...world.l1_working_memory.new_events].filter((item) => item.type === "message"); const quotes = [...new Set(messages.filter((item) => ids.includes(item.id)).flatMap((item) => (item.quoteId ? [item.quoteId] : [])))]; const present = new Set(messages.map((item) => item.id)); diff --git a/packages/core/src/agent/continuation.ts b/packages/core/src/agent/continuation.ts new file mode 100644 index 000000000..33bb1467f --- /dev/null +++ b/packages/core/src/agent/continuation.ts @@ -0,0 +1,37 @@ +import type { Session } from "koishi"; + +import type { ConversationStateResult } from "../world/conversation-state"; +import type { ContinuationConfig } from "./config"; + +export interface ContinuationMatch { + mode: "trigger" | "willingness"; + revision: number; + registeredAt: string; + expiresAt: number; + sourceMessageIds: string[]; +} + +/** A model-authored invitation, not an inference about the user's intent. */ +export function matchContinuation( + session: Session, + config: ContinuationConfig | undefined, + result: ConversationStateResult | undefined, + now = Date.now(), +): ContinuationMatch | undefined { + const state = result?.unknown === false ? result.state : undefined; + const waiting = state?.followUp; + if (!config?.enabled || !state || !waiting || !waiting.userIds.includes(session.userId!)) return; + const registered = Date.parse(state.updatedAt); + const duration = config.maxDurationSeconds; + if (!Number.isFinite(registered) || !Number.isFinite(duration) || duration < 1) return; + const expiresAt = Math.min(waiting.expiresAt, registered + duration * 1000); + if (!Number.isFinite(expiresAt) || now < registered || now >= expiresAt || !state.sourceMessageIds.length) return; + const otherMention = session.elements?.some((element) => element.type === "at" && element.attrs.id !== session.selfId); + const otherQuote = session.quote?.user?.id && session.quote.user.id !== session.selfId; + if (otherMention || otherQuote) return; + return { mode: config.mode, revision: state.revision, registeredAt: state.updatedAt, expiresAt, sourceMessageIds: [...state.sourceMessageIds] }; +} + +export function sameContinuation(left: ContinuationMatch | undefined, right: ContinuationMatch | undefined): boolean { + return !!left && !!right && JSON.stringify(left) === JSON.stringify(right); +} diff --git a/packages/core/src/agent/decision-journal.ts b/packages/core/src/agent/decision-journal.ts index 42c915065..3ea0ad0c3 100644 --- a/packages/core/src/agent/decision-journal.ts +++ b/packages/core/src/agent/decision-journal.ts @@ -42,6 +42,8 @@ const reasons = new Set([ "permission_denied", "muted", "forced_reply_by_mention", + "conversation_continuation", + "continuation_expired", "mention_priority", "mention_pending", "probability_roll", @@ -69,6 +71,7 @@ const calculationFields = [ "assessmentMultiplier", "participationMultiplier", "effectiveGain", + "continuationGain", "maxWillingness", "threshold", "amplifier", @@ -145,6 +148,27 @@ export function sanitizeDecisionRecord(value: unknown): DecisionRecord | undefin } result.assessment = assessment; } + if (object(value.continuation)) { + const c = value.continuation; + if ( + ["trigger", "willingness"].includes(String(c.mode)) && + Number.isSafeInteger(c.revision) && + finite(c.expiresAt) && + typeof c.registeredAt === "string" && + Number.isFinite(Date.parse(c.registeredAt)) && + Array.isArray(c.sourceMessageIds) && + c.sourceMessageIds.length <= 10 && + c.sourceMessageIds.every(identifier) + ) { + result.continuation = { + mode: c.mode, + revision: c.revision, + expiresAt: c.expiresAt, + registeredAt: c.registeredAt, + sourceMessageIds: [...c.sourceMessageIds], + } as DecisionRecord["continuation"]; + } + } if (object(value.participation) && typeof value.participation.active === "boolean") { const participation: Record = { active: value.participation.active }; for (const field of ["lastReplyAt", "expiresAt"] as const) if (finite(value.participation[field])) participation[field] = value.participation[field]; diff --git a/packages/core/src/agent/decision-record.ts b/packages/core/src/agent/decision-record.ts index 23f8ecc78..01eaaf77e 100644 --- a/packages/core/src/agent/decision-record.ts +++ b/packages/core/src/agent/decision-record.ts @@ -14,6 +14,7 @@ export interface WillingnessCalculation { assessmentMultiplier: number; participationMultiplier: number; effectiveGain: number; + continuationGain?: number; maxWillingness: number; threshold: number; amplifier: number; @@ -34,6 +35,7 @@ export interface DecisionRecord { reason?: string; decision?: boolean; forcedReply?: boolean; + continuation?: import("./continuation").ContinuationMatch; calculation?: WillingnessCalculation; allowed?: string[]; assessment?: { @@ -133,6 +135,8 @@ const reasons: Record = { permission_denied: "会话未获许可", muted: "机器人被禁言", forced_reply_by_mention: "明确 @ 机器人,优先回复", + conversation_continuation: "命中模型登记的等待,进入模型回合", + continuation_expired: "会话等待已到期或被替换", mention_priority: "明确 @ 消息优先排队", mention_pending: "合并到待回复的 @ 消息", probability_roll: "随机判定", @@ -188,6 +192,10 @@ export function formatDecision(record: DecisionRecord | undefined, state: Decisi lines.push(`语义评分:面向机器人 ${a.addressed};兴趣匹配 ${a.interested};面向他人 ${a.others}`); } if (record.forcedReply) lines.push("明确 @ 优先回复:不依赖随机判定,仍遵守回复控制。"); + if (record.continuation) + lines.push( + `会话续接:${record.continuation.mode === "trigger" ? "进入模型回合" : "增加意愿"};工作状态版本 ${record.continuation.revision};有效至 ${new Date(record.continuation.expiresAt).toISOString()}`, + ); if (record.success !== undefined) lines.push(`成功发送回复:${record.success ? "是" : "否"}`); return lines.join("\n"); } diff --git a/packages/core/src/agent/willing.ts b/packages/core/src/agent/willing.ts index de510a4b8..691361f83 100644 --- a/packages/core/src/agent/willing.ts +++ b/packages/core/src/agent/willing.ts @@ -17,6 +17,7 @@ export interface MessageContext { isQuote: boolean; isDirect: boolean; allowedCategories?: ReplyCategory[]; + continuationGain?: number; } export interface TopicWillingnessInput { @@ -265,7 +266,8 @@ export class WillingnessManager { // --- 非线性增益 --- const gainMultiplier = getDynamicGainMultiplier(currentWillingness, resolvedMaxWillingness); - const effectiveGain = details.gain * gainMultiplier * assessmentMultiplier; + const continuationGain = Number.isFinite(context.continuationGain) ? Math.max(0, context.continuationGain!) : 0; + const effectiveGain = details.gain * gainMultiplier * assessmentMultiplier + continuationGain; currentWillingness += effectiveGain; // ------------------------- @@ -289,6 +291,7 @@ export class WillingnessManager { assessmentMultiplier, participationMultiplier: details.participationMultiplier, effectiveGain, + ...(continuationGain ? { continuationGain } : {}), maxWillingness: resolvedMaxWillingness, threshold: resolvedProbabilityThreshold, amplifier: resolvedProbabilityAmplifier, @@ -401,6 +404,7 @@ export class WillingnessManager { allowedCategories?: ReplyCategory[], assessmentMultiplier = 1, topic?: TopicWillingnessInput, + continuationGain = 0, ): { decision: boolean; probability: number; roll: number; calculation: WillingnessCalculation; scoreKey?: string } { const currentScoreKey = topic?.currentScoreKey ?? chatId; const credit = this.backgroundCredits.get(chatId) ?? 0; @@ -420,6 +424,7 @@ export class WillingnessManager { const context: MessageContext = { chatId: currentScoreKey, participationId: topic ? chatId : undefined, + continuationGain, allowedCategories, content: session.content ?? "", isMentioned: allowedCategories @@ -454,7 +459,7 @@ export class WillingnessManager { } if (scoreKey !== currentScoreKey) { this.sessions.set(scoreKey, session); - probability = this.calculateReplyProbability(session, { ...context, chatId: scoreKey }, 0, (value) => { + probability = this.calculateReplyProbability(session, { ...context, chatId: scoreKey, continuationGain: 0 }, 0, (value) => { calculation = value; }); } diff --git a/packages/core/src/extension/background-tools.ts b/packages/core/src/extension/background-tools.ts index 424c15119..515d89e68 100644 --- a/packages/core/src/extension/background-tools.ts +++ b/packages/core/src/extension/background-tools.ts @@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto"; import { Context, Schema, Session } from "koishi"; -import type { BackgroundToolsConfig } from "../agent/config"; +import { DEFAULT_BACKGROUND_TOOLS, type BackgroundToolsConfig } from "../agent/config"; import { guardReplySession, withReplyTurn } from "../agent/reply-turn"; import { conversationChannelId, conversationCid } from "../shared/utils/conversation-scope"; import type { WorldStateService } from "../world"; @@ -134,17 +134,22 @@ export class BackgroundTools { } } + private allows(toolName: string): boolean { + const selected = this.config.allowedTools ?? DEFAULT_BACKGROUND_TOOLS; + return !toolName.startsWith("background_task_") && Array.isArray(selected) && selected.includes(toolName); + } + public start(source: Session | undefined, toolName: string, params: Record, requestId?: string) { if (!source) throw new Error("缺少来源会话"); const context = this.capture(source), session = context.session; context.assertCurrent(); const definition = this.tools.getTool(toolName, session); - if (!definition?.background || toolName.startsWith("background_task_")) throw new Error("该工具不允许后台执行"); + if (!definition?.background || !this.allows(toolName)) throw new Error("该工具不允许后台执行"); const assertScope = context.assertCurrent; context.assertCurrent = () => { assertScope(); - if (this.tools.getTool(toolName, session) !== definition) throw new Error("后台任务工具已停用或权限已撤销"); + if (!this.allows(toolName) || this.tools.getTool(toolName, session) !== definition) throw new Error("后台任务工具已停用或权限已撤销"); }; const validated = structuredClone(definition.parameters(params)); this.pruneContexts(); @@ -210,7 +215,7 @@ export class BackgroundTools { tasks: this.registry.list(owner, 20), tools: this.tools .getAvailableTools(session) - .filter((tool) => tool.background) + .filter((tool) => tool.background && this.allows(tool.name)) .map((tool) => tool.name), }; } diff --git a/packages/core/src/extension/builtin/memory.ts b/packages/core/src/extension/builtin/memory.ts index 9a0e87e01..8db32988e 100644 --- a/packages/core/src/extension/builtin/memory.ts +++ b/packages/core/src/extension/builtin/memory.ts @@ -3,6 +3,7 @@ import { Context, h, Schema, Session } from "koishi"; import { Extension, Tool, withInnerThoughts } from "../../extension/decorators"; import { Failed, Success } from "../../extension/helpers"; import { Infer } from "../../extension/types"; +import type { ConversationStateInput } from "../../world/conversation-state"; @Extension({ name: "memory", @@ -178,15 +179,19 @@ export default class MemoryExtension { @Tool({ name: "conversation_state_update", description: - "显式完整替换当前会话工作话题/未决问题;不自动推断事实。非空状态须引用当前会话中 1–10 个现存原始消息 ID,并提交读取到的 expectedRevision(初始 0)。空 topic/issues 和空来源数组可清空;省略字段按空替换。", + "显式完整替换当前会话工作话题/未决问题;不自动推断事实。非空状态须引用当前会话中 1–10 个现存原始消息 ID,并提交读取到的 expectedRevision(初始 0)。空 topic/issues 和空来源数组可清空;省略字段按空替换。启用会话续接后,可用 followUp 登记等待指定用户的后续消息;这只申请处理机会,仍可选择沉默,发送给他人的消息不会命中。省略 followUp 会清除此前等待。", parameters: withInnerThoughts({ topic: Schema.string().max(1000), openIssues: Schema.array(Schema.string().max(500)).max(10), sourceMessageIds: Schema.array(Schema.string()).max(10).required(), expectedRevision: Schema.number().min(0).step(1).required(), + followUp: Schema.object({ + userIds: Schema.array(Schema.string().max(255)).min(1).max(10).required().description("等待的用户 ID"), + durationSeconds: Schema.number().min(1).max(86400).required().description("等待有效时间(秒),不超过管理者配置上限"), + }), }), }) - async conversationStateUpdate(args: Infer<{ topic?: string; openIssues?: string[]; sourceMessageIds: string[]; expectedRevision: number }>) { + async conversationStateUpdate(args: Infer) { if (!args.session) return Failed("session 不可用"); try { return Success( @@ -195,6 +200,7 @@ export default class MemoryExtension { openIssues: args.openIssues, sourceMessageIds: args.sourceMessageIds, expectedRevision: args.expectedRevision, + followUp: args.followUp, }), ); } catch (error) { diff --git a/packages/core/src/extension/service.ts b/packages/core/src/extension/service.ts index 73a8f35e3..90a7f9266 100644 --- a/packages/core/src/extension/service.ts +++ b/packages/core/src/extension/service.ts @@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto"; import { Context, ForkScope, h, Logger, Schema, Session } from "koishi"; +import { DEFAULT_BACKGROUND_TOOLS } from "../agent/config"; import { assertReplyTurn, awaitReplyTurn } from "../agent/reply-turn"; import { Config } from "../config"; import type { LoggerService } from "../logger"; @@ -24,6 +25,8 @@ import { extractMetaFromSchema, Failed } from "./helpers"; import { ToolOutputStore, TOOL_OUTPUT_THRESHOLD, ToolOutputOwner } from "./tool-output-store"; import { IExtension, Properties, ToolCallResult, ToolDefinition, ToolSchema, ToolExecutionContext } from "./types"; +const backgroundToolChoices = new WeakMap>(); + /** Keep JSON containers and quoted values intact before Koishi's tool-schema validation. */ function parseCommandParams(source: string): Record { const result: Record = Object.create(null); @@ -129,6 +132,7 @@ export class ToolService extends YesImBotService { private outputOwnerContext?: Context; private tools: Map = new Map(); + private schemaStopped = false; private extensions: Map = new Map(); // Disabled instances are also retained so their own plugin scope can be re-enabled. private knownExtensions: Map = new Map(); @@ -144,11 +148,14 @@ export class ToolService extends YesImBotService { super(ctx, config); this._logger = deps.logging.getLogger("[工具管理器]"); this.promptService = deps.prompt; + this.updateBackgroundToolSchema(); if (config.backgroundTools?.enabled) this.background = new BackgroundTools(ctx, config.backgroundTools, deps.world, this); } public async stop() { this.background?.dispose(); + this.schemaStopped = true; + this.updateBackgroundToolSchema(); } public async start() { @@ -480,6 +487,7 @@ export class ToolService extends YesImBotService { this._logger.debug(` -> 注册工具: "${tool.name}"`); this.tools.set(name, tool); } + this.updateBackgroundToolSchema(); } // this._logger.debug(`扩展 "${metadata.name}" 已加载`); @@ -497,21 +505,49 @@ export class ToolService extends YesImBotService { if (this.extensions.get(name) === ext) this.extensions.delete(name); for (const definition of ext.tools?.values() || []) { // Another extension (or registerTool) may have replaced a colliding name. - if (this.tools.get(definition.name) === definition) this.tools.delete(definition.name); + if (this.tools.get(definition.name) === definition) this.unregisterTool(definition.name); } this._logger.info(`已卸载扩展: "${name}"`); return true; } + private updateBackgroundToolSchema() { + // Root ownership keeps shared choices alive when an individual plugin is disposed. + const schema = this.ctx.root?.schema ?? this.ctx.schema; + if (!schema?.set) return; + const identity = schema._data ?? schema; + let instances = backgroundToolChoices.get(identity); + if (!instances) backgroundToolChoices.set(identity, (instances = new Map())); + if (this.schemaStopped) instances.delete(this); + else + instances.set( + this, + [...this.tools.values()].filter((tool) => tool.background && !tool.name.startsWith("background_task_")), + ); + const choices = new Map(DEFAULT_BACKGROUND_TOOLS.map((name) => [name, name])); + for (const tools of instances.values()) { + for (const tool of tools) choices.set(tool.name, `${tool.name}:${tool.description.split("\n")[0].slice(0, 80)}`); + } + schema.set( + "toolService.backgroundEligibleTools", + Schema.array(Schema.union([...choices].map(([name, label]) => Schema.const(name).description(label)))) + .role("checkbox") + .default([...DEFAULT_BACKGROUND_TOOLS]), + ); + } + public registerTool(definition: ToolDefinition) { this.tools.set(definition.name, definition); + this.updateBackgroundToolSchema(); return () => { - if (this.tools.get(definition.name) === definition) this.tools.delete(definition.name); + if (this.tools.get(definition.name) === definition) this.unregisterTool(definition.name); }; } public unregisterTool(name: string) { - return this.tools.delete(name); + const removed = this.tools.delete(name); + if (removed) this.updateBackgroundToolSchema(); + return removed; } private async recordFrameworkChange(session: Session, operation: string, name: string, status: string) { diff --git a/packages/core/src/model/config.ts b/packages/core/src/model/config.ts index 6aa620187..dff624b3b 100644 --- a/packages/core/src/model/config.ts +++ b/packages/core/src/model/config.ts @@ -1,6 +1,6 @@ import { Schema } from "koishi"; -import { ContextLimitConfig, parseContextLimit } from "./context-limit"; +import { ContextCapacityRow, ContextLimitConfig, contextCapacityRows, parseContextLimit } from "./context-limit"; /** 模型切换策略 */ export enum ModelSwitchingStrategy { @@ -95,6 +95,12 @@ export interface ModelConfig { circuitBreakerPolicy?: CircuitBreakerPolicy; } +// A fresh table row keeps its amount empty until the user supplies a valid capacity. +const contextCapacityRowSchema: Schema = Schema.object({ + amount: Schema.number().min(0).required().description("数值"), + unit: Schema.union(["token", "K", "M"]).default("K").description("单位"), +}); + export const ModelConfigSchema: Schema = Schema.object({ modelId: Schema.string().required().description("模型ID"), abilities: Schema.array( @@ -126,15 +132,20 @@ export const ModelConfigSchema: Schema = Schema.object({ Schema.object({ mode: Schema.const("unset").default("unset") }), Schema.object({ mode: Schema.const("custom").required(), - value: Schema.string() - .pattern(/^\s*(\d+(?:\.\d+)?|\.\d+)\s*([km]?)\s*$/i) - .role("yib-context-capacity") + value: Schema.union([ + Schema.array(contextCapacityRowSchema) + .min(1) + .max(1) + .role("table") + .default([{ unit: "K" }]), + Schema.transform(Schema.string(), contextCapacityRows, true), + ]) .required() - .description("上下文容量(数值与单位)"), + .description("上下文容量(1K = 1000 token;1M = 1000000 token)"), }), Schema.object({ mode: Schema.const("auto").required() }), ]), - // Keep validation separate from the primitive input: the console cannot render transform fields. + // Keep capacity validation separate from the visible table fields. Schema.transform(Schema.any(), parseContextLimit).hidden(), ]) .collapse() diff --git a/packages/core/src/model/context-limit.ts b/packages/core/src/model/context-limit.ts index 5656aeb74..84e45ccee 100644 --- a/packages/core/src/model/context-limit.ts +++ b/packages/core/src/model/context-limit.ts @@ -1,7 +1,12 @@ +export interface ContextCapacityRow { + amount?: number; + unit: "token" | "K" | "M"; +} + /** A declared capacity is independent of runtime context trimming. */ export interface ContextLimitConfig { mode: "unset" | "custom" | "auto"; - value?: string; + value?: string | ContextCapacityRow[]; } export interface ContextLimitResult { @@ -18,11 +23,28 @@ export interface ContextLimitResult { * Also validate declarations as a self-contained schema callback: Koishi serializes * callbacks for the console, so this function must not reference module helpers. */ -export function parseContextLimit(value: string): number; +export function parseContextLimit(value: string | ContextCapacityRow[]): number; export function parseContextLimit(value: ContextLimitConfig): ContextLimitConfig; -export function parseContextLimit(input: string | ContextLimitConfig): number | ContextLimitConfig { - if (typeof input !== "string" && input.mode !== "custom") return input; - const value = typeof input === "string" ? input : (input.value ?? ""); +export function parseContextLimit(input: string | ContextCapacityRow[] | ContextLimitConfig): number | ContextLimitConfig { + const config = typeof input === "object" && !Array.isArray(input); + if (config && input.mode !== "custom") return input; + const value = config ? (input.value ?? "") : input; + if (Array.isArray(value)) { + const row = value[0]; + if ( + value.length !== 1 || + !row || + typeof row !== "object" || + typeof row.amount !== "number" || + !Number.isFinite(row.amount) || + row.amount <= 0 || + !["token", "K", "M"].includes(row.unit) + ) + throw new Error("最大上下文需要一行有效数值与 token/K/M 单位"); + const tokens = row.amount * (row.unit === "K" ? 1000 : row.unit === "M" ? 1000000 : 1); + if (!Number.isFinite(tokens) || tokens <= 0 || tokens > Number.MAX_SAFE_INTEGER) throw new Error("最大上下文必须换算为安全范围内的有限正数 token 数"); + return config ? input : tokens; + } const match = /^\s*(\d+(?:\.\d+)?|\.\d+)\s*([km]?)\s*$/i.exec(value); if (!match) throw new Error("最大上下文必须是正数或带 K/M 的容量,例如 131072.5、128K、1M"); if (match[1].length > 4096) throw new Error("最大上下文数值过长"); @@ -34,7 +56,21 @@ export function parseContextLimit(input: string | ContextLimitConfig): number | if (!Number.isFinite(tokens) || tokens <= 0 || numerator > BigInt(Number.MAX_SAFE_INTEGER) * denominator) { throw new Error("最大上下文必须换算为安全范围内的有限正数 token 数"); } - return typeof input === "string" ? tokens : input; + return config ? input : tokens; +} + +/** Deserialize legacy capacities before the console selects the native table branch. */ +export function contextCapacityRows(value: string): ContextCapacityRow[] { + const match = /^\s*(\d+(?:\.\d+)?|\.\d+)\s*([km]?)\s*$/i.exec(value); + if (!match || match[1].length > 4096) throw new Error("最大上下文容量格式无效"); + const [whole, fraction = ""] = match[1].split("."); + const unit = (match[2].toUpperCase() || "token") as ContextCapacityRow["unit"]; + const multiplier = unit === "K" ? 1000n : unit === "M" ? 1000000n : 1n; + const amount = Number(match[1]); + const tokens = amount * Number(multiplier); + if (!Number.isFinite(tokens) || tokens <= 0 || BigInt(whole + fraction) * multiplier > BigInt(Number.MAX_SAFE_INTEGER) * 10n ** BigInt(fraction.length)) + throw new Error("最大上下文必须换算为安全范围内的有限正数 token 数"); + return [{ amount, unit }]; } /** Only explicit total context fields are accepted, never output limits or names. */ diff --git a/packages/core/src/world/conversation-state.ts b/packages/core/src/world/conversation-state.ts index 098f4de94..97d6799a6 100644 --- a/packages/core/src/world/conversation-state.ts +++ b/packages/core/src/world/conversation-state.ts @@ -10,7 +10,13 @@ import type { MessageData } from "./types"; const CONVERSATION_STATE = "worldstate.conversation_state"; +export interface FollowUpState { + userIds: string[]; + expiresAt: number; +} + export interface ConversationStateInput { + followUp?: { userIds: string[]; durationSeconds: number }; topic?: string; openIssues?: string[]; sourceMessageIds: string[]; @@ -18,6 +24,7 @@ export interface ConversationStateInput { } export interface ConversationState { + followUp?: FollowUpState; revision: number; topic: string; openIssues: string[]; @@ -29,6 +36,7 @@ export interface ConversationState { export interface ConversationStateResult { state?: ConversationState; unknown: boolean; + sourceMessages?: MessageData[]; } interface StatePayload extends ConversationState { @@ -140,6 +148,17 @@ function fingerprint(record: MessageData): string { .digest("hex"); } +function validateRecipients(ids: string[]) { + if ( + !Array.isArray(ids) || + ids.length < 1 || + ids.length > 10 || + new Set(ids).size !== ids.length || + ids.some((id) => typeof id !== "string" || !id.trim() || id.length > 255 || /\p{Cc}/u.test(id)) + ) + throw new Error("等待用户须为 1–10 个不同的用户 ID"); +} + function validateInput(input: ConversationStateInput) { if (!input || !Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 0) throw new Error("工作会话状态 expectedRevision 须为非负整数"); const topic = input.topic ?? "", @@ -150,8 +169,15 @@ function validateInput(input: ConversationStateInput) { const ids = input.sourceMessageIds; if (!Array.isArray(ids) || ids.length > 10 || ids.some((id) => typeof id !== "string" || !id.trim() || id.length > 255) || new Set(ids).size !== ids.length) throw new Error("来源消息 ID 须为最多 10 个不同的原始 ID"); - if ((topic.trim() || openIssues.length) && !ids.length) throw new Error("非空工作状态需要 1–10 个已验证来源消息 ID"); - return { topic, openIssues: [...openIssues], sourceMessageIds: [...ids] }; + if ((topic.trim() || openIssues.length || input.followUp) && !ids.length) throw new Error("非空工作状态需要 1–10 个已验证来源消息 ID"); + let followUp: FollowUpState | undefined; + if (input.followUp !== undefined) { + const { userIds, durationSeconds } = input.followUp; + validateRecipients(userIds); + if (!Number.isFinite(durationSeconds) || durationSeconds < 1 || durationSeconds > 86400) throw new Error("等待时长须为 1–86400 秒"); + followUp = { userIds: [...userIds], expiresAt: Date.now() + durationSeconds * 1000 }; + } + return { topic, openIssues: [...openIssues], sourceMessageIds: [...ids], ...(followUp ? { followUp } : {}) }; } /** Explicit working notes, not inferred facts. World service supplies barrier and live authorization. */ @@ -192,7 +218,7 @@ export class ConversationStateManager { } private async sourceFingerprints(target: MessageWindowTarget, ids: string[]) { - if (!ids.length) return { fingerprints: [], sourceOldestAt: undefined }; + if (!ids.length) return { fingerprints: [], sourceOldestAt: undefined, records: [] as MessageData[] }; const scope = { platform: target.platform, channelId: target.channelId, channelType: target.channelType }; const rows = await this.ctx.database.get(TableName.Messages, { ...scope, id: { $in: ids } }); if ( @@ -205,7 +231,7 @@ export class ConversationStateManager { if (matching.length !== 1) throw new SourceUnavailableError("工作状态的原始来源不唯一"); return fingerprint(matching[0]); }); - return { fingerprints, sourceOldestAt: new Date(Math.min(...rows.map((row) => new Date(row.timestamp).getTime()))).toISOString() }; + return { fingerprints, records: rows, sourceOldestAt: new Date(Math.min(...rows.map((row) => new Date(row.timestamp).getTime()))).toISOString() }; } private async readPayload(id: string, scope: string, target: MessageWindowTarget, assertCurrent: () => void): Promise { @@ -227,7 +253,17 @@ export class ConversationStateManager { valid = valid && Number.isFinite(Date.parse(state.createdAt)) && Number.isFinite(Date.parse(state.updatedAt)) && state.createdAt <= state.updatedAt; if (valid) { try { - validateInput({ ...state, expectedRevision: state.revision }); + validateInput({ ...state, followUp: undefined, expectedRevision: state.revision }); + if (state.followUp !== undefined) { + validateRecipients(state.followUp.userIds); + if ( + !state.sourceMessageIds.length || + !Number.isFinite(state.followUp.expiresAt) || + state.followUp.expiresAt <= Date.parse(state.updatedAt) || + state.followUp.expiresAt > Date.parse(state.updatedAt) + 86400_000 + ) + throw new Error("等待状态无效"); + } } catch { valid = false; } @@ -250,24 +286,41 @@ export class ConversationStateManager { return state; } - private result(payload?: StatePayload): ConversationStateResult { + private result(payload?: StatePayload, maxFollowUpDurationSeconds = 86400): ConversationStateResult { if (!payload) return { unknown: true }; const { scope: _scope, sourceFingerprints: _fingerprints, sourceOldestAt: _sourceOldestAt, ...state } = payload; - return { state, unknown: !state.topic.trim() && !state.openIssues.length }; + if (state.followUp) { + const expiresAt = Math.min(state.followUp.expiresAt, Date.parse(state.updatedAt) + maxFollowUpDurationSeconds * 1000); + if (Date.now() >= expiresAt) delete state.followUp; + else state.followUp = { userIds: [...state.followUp.userIds], expiresAt }; + } + return { state, unknown: !state.topic.trim() && !state.openIssues.length && !state.followUp }; } - public read(target: MessageWindowTarget, instance: string, assertCurrent: () => void) { + public read(target: MessageWindowTarget, instance: string, assertCurrent: () => void, includeSources = false, maxFollowUpDurationSeconds = 86400) { const { id, scope } = this.key(target, instance); return serialize(this.ctx.database, id, async () => { assertCurrent(); - return this.result(await this.readPayload(id, scope, target, assertCurrent)); + const payload = await this.readPayload(id, scope, target, assertCurrent); + if (!payload || !includeSources) return this.result(payload, maxFollowUpDurationSeconds); + try { + const sources = await this.sourceFingerprints(target, payload.sourceMessageIds); + assertCurrent(); + if (JSON.stringify(sources.fingerprints) !== JSON.stringify(payload.sourceFingerprints)) return { unknown: true }; + return { ...this.result(payload, maxFollowUpDurationSeconds), sourceMessages: sources.records }; + } catch (error) { + assertCurrent(); + if (error instanceof SourceUnavailableError) return { unknown: true }; + throw error; + } }); } public update(target: MessageWindowTarget, instance: string, input: ConversationStateInput, assertCurrent: () => void) { // Snapshot caller-owned arrays before any await; a changed input cannot bypass validation. const fields = validateInput(input), - expectedRevision = input.expectedRevision; + expectedRevision = input.expectedRevision, + durationSeconds = input.followUp?.durationSeconds; const { id, scope } = this.key(target, instance); return serialize(this.ctx.database, id, async () => { assertCurrent(); @@ -278,6 +331,7 @@ export class ConversationStateManager { const now = new Date().toISOString(); const payload: StatePayload = { ...fields, + ...(fields.followUp ? { followUp: { userIds: fields.followUp.userIds, expiresAt: Date.parse(now) + durationSeconds! * 1000 } } : {}), scope, sourceFingerprints, sourceOldestAt, diff --git a/packages/core/src/world/service.ts b/packages/core/src/world/service.ts index d07289dec..c111c99d5 100644 --- a/packages/core/src/world/service.ts +++ b/packages/core/src/world/service.ts @@ -206,11 +206,17 @@ export class WorldStateService extends YesImBotService { return { ...result, historyGeneration }; } - public getConversationState(session: Session) { - return this.withConversationState(session, (manager, target, instance, assertCurrent) => manager.read(target, instance, assertCurrent)); + public getConversationState(session: Session, options: { includeSources?: boolean } = {}) { + return this.withConversationState(session, (manager, target, instance, assertCurrent) => + manager.read(target, instance, assertCurrent, options.includeSources, this.config.continuation?.maxDurationSeconds), + ); } public updateConversationState(session: Session, input: ConversationStateInput) { + if (input.followUp && this.config.continuation) { + if (!this.config.continuation.enabled) throw new Error("会话续接未启用"); + if (input.followUp.durationSeconds > this.config.continuation.maxDurationSeconds) throw new Error("等待时长超过配置上限"); + } return this.withConversationState(session, (manager, target, instance, assertCurrent) => manager.update(target, instance, input, assertCurrent)); } diff --git a/packages/core/tests/background-commands.spec.ts b/packages/core/tests/background-commands.spec.ts index e400c6862..2677620a6 100644 --- a/packages/core/tests/background-commands.spec.ts +++ b/packages/core/tests/background-commands.spec.ts @@ -13,7 +13,7 @@ it("allows authority-3 cancellation while keeping ordinary members behind the co const fork = ctx.plugin((pluginMock as any).default ?? pluginMock); let release!: () => void; const external = new Promise((resolve) => (release = resolve)); - const config = Config({ backgroundTools: { enabled: true } }); + const config = Config({ backgroundTools: { enabled: true, allowedTools: ["lookup"] } }); const tools = new ToolService(ctx, config, { logging: loggingStub(), world: { diff --git a/packages/core/tests/background-policy.spec.ts b/packages/core/tests/background-policy.spec.ts index 5aca56591..5c65a205e 100644 --- a/packages/core/tests/background-policy.spec.ts +++ b/packages/core/tests/background-policy.spec.ts @@ -1,3 +1,4 @@ +import { Schema } from "koishi"; import { afterEach, expect, it, vi } from "vitest"; import { AgentBehaviorConfigSchema } from "../src/agent/config"; @@ -149,6 +150,7 @@ it("defaults background execution off and validates bounded configuration", () = const config = AgentBehaviorConfigSchema({}); expect(config.backgroundTools).toEqual({ enabled: false, + allowedTools: ["web_search", "fetch_webpage", "get_image_description"], completion: "next_cycle", settlement: "request", willingness: { succeeded: 0, failed: 0, cancelled: 0 }, @@ -251,3 +253,17 @@ it("decays pending topic credit and preserves it across stopping the decay timer expect(willing.getCurrentWillingness("topic-one")).toBeCloseTo(20 * Math.pow(0.5, 1 / 100)); expect(willing.getCurrentWillingness("chat")).toBe(0); }); + +it("exposes ordinary numeric willingness inputs in the serialized configuration", () => { + const schema = new Schema(JSON.parse(JSON.stringify(AgentBehaviorConfigSchema))); + const background = schema.list.find((branch: any) => branch.dict?.backgroundTools).dict.backgroundTools; + const willingness = background.dict.willingness; + const fields = willingness.dict ?? willingness.list?.find((branch: any) => branch.type === "object")?.dict; + for (const name of ["succeeded", "failed", "cancelled"]) { + expect({ type: fields?.[name]?.type, meta: fields?.[name]?.meta }).toMatchObject({ type: "number", meta: { default: 0, min: 0, max: 1000000 } }); + } + expect({ type: background.dict.allowedTools?.type, meta: background.dict.allowedTools?.meta }).toMatchObject({ + type: "any", + meta: { role: "dynamic", extra: { name: "toolService.backgroundEligibleTools" } }, + }); +}); diff --git a/packages/core/tests/background-tools.spec.ts b/packages/core/tests/background-tools.spec.ts index 25484b27d..b8c7c15c7 100644 --- a/packages/core/tests/background-tools.spec.ts +++ b/packages/core/tests/background-tools.spec.ts @@ -31,6 +31,7 @@ async function fixture(enabled = true) { const config: any = { backgroundTools: { enabled, + allowedTools: ["read_slow"], completion: "next_cycle", settlement: "request", willingness: { succeeded: 2, failed: 0, cancelled: 0 }, @@ -318,3 +319,87 @@ it("retains administrator attribution for a manually submitted background tool", await drain(); expect(f.receipts.find((receipt) => receipt.payload.operation === "read_slow").payload.actor).toBe("admin:telegram:u"); }); + +it("blocks unselected background tools without changing direct calls", async () => { + const f = await fixture(); + let calls = 0; + add(f, async () => { + calls++; + return { status: "success", result: "done" }; + }); + f.config.backgroundTools.allowedTools = []; + expect((f.tools.background!.query(f.session) as any).tools).toEqual([]); + expect(() => f.tools.background!.start(f.session, "read_slow", {})).toThrow("该工具不允许后台执行"); + expect(calls).toBe(0); + expect((await f.tools.invoke("read_slow", {}, f.session)).status).toBe("success"); + expect(calls).toBe(1); +}); +it("does not let selection authorize a tool without background support", async () => { + const f = await fixture(); + add(f, async () => ({ status: "success" }), false); + expect((f.tools.background!.query(f.session) as any).tools).toEqual([]); + expect(() => f.tools.background!.start(f.session, "read_slow", {})).toThrow("该工具不允许后台执行"); +}); +it("invalidates a running task result when its background permission is revoked", async () => { + const f = await fixture(), + d = deferred(); + add(f, async () => { + await d.promise; + return { status: "success", result: "stale" }; + }); + const task = f.tools.background!.start(f.session, "read_slow", {}); + await drain(); + f.config.backgroundTools.allowedTools = []; + d.resolve(); + await drain(); + expect(f.completions).toEqual([]); + expect(() => f.tools.background!.query(f.session, task.id)).toThrow("Background task not found"); +}); +it("refreshes selectable tools on registration, replacement and disposal", async () => { + const f = await fixture(false); + const definition = { + name: "extra_read", + description: "Extra read", + background: true, + parameters: Schema.object({}), + execute: async () => ({ status: "success" as const }), + }; + const removeOld = f.tools.registerTool(definition); + const names = () => f.tools.ctx.schema.get("toolService.backgroundEligibleTools")?.inner?.list?.map((choice: any) => choice.value) ?? []; + expect(names()).toContain("extra_read"); + const rendered = f.tools.ctx.schema.get("toolService.backgroundEligibleTools"); + expect(rendered.type).toBe("array"); + expect(rendered.meta.role).toBe("checkbox"); + expect(rendered.meta.default).toEqual(["web_search", "fetch_webpage", "get_image_description"]); + f.tools.registerTool({ ...definition, background: false }); + expect(names()).not.toContain("extra_read"); + const removeNew = f.tools.registerTool({ ...definition }); + removeOld(); + expect(names()).toContain("extra_read"); + removeNew(); + expect(names()).not.toContain("extra_read"); +}); + +it("keeps other instances' tool choices when a shared schema owner stops", async () => { + const f = await fixture(false); + let other!: ToolService; + const fork = f.tools.ctx.plugin((scope) => { + other = new ToolService(scope, { backgroundTools: { enabled: false } } as any, { logging: loggingStub() } as any); + scope.on("dispose", () => other.stop()); + }); + onTestFinished(() => fork.dispose()); + add(f, async () => ({ status: "success" })); + other.registerTool({ + name: "other_read", + description: "Other read", + background: true, + parameters: Schema.object({}), + execute: async () => ({ status: "success" }), + }); + const names = () => f.tools.ctx.schema.get("toolService.backgroundEligibleTools").inner!.list!.map((choice) => choice.value); + expect(names()).toContain("other_read"); + expect(names()).toContain("read_slow"); + await fork.dispose(); + expect(names()).not.toContain("other_read"); + expect(names()).toContain("read_slow"); +}); diff --git a/packages/core/tests/config-history-context.spec.ts b/packages/core/tests/config-history-context.spec.ts index c2fbf75f5..4f3efba47 100644 --- a/packages/core/tests/config-history-context.spec.ts +++ b/packages/core/tests/config-history-context.spec.ts @@ -6,6 +6,7 @@ import { test, vi } from "vitest"; import { AgentBehaviorConfigSchema } from "../src/agent/config"; import { TopicManager } from "../src/agent/topics"; import { ModelConfigSchema } from "../src/model/config"; +import { parseContextLimit } from "../src/model/context-limit"; import { loggingStub } from "./helpers/yesimbot"; test("context settings expose one collapsible section", () => { @@ -13,18 +14,21 @@ test("context settings expose one collapsible section", () => { assert.equal(context.meta.collapse, true); }); -test("custom context settings expose a primitive input", () => { +test("custom context settings expose a native capacity table", () => { const context = ModelConfigSchema.dict!.contextLimit; const branch = context.list![1].list!.find((item) => item.dict?.mode.value === "custom")!; - assert.equal(branch.dict!.value.type, "string"); + assert.equal(branch.dict!.value.type, "union"); assert.equal(branch.dict!.value.meta.required, true); - assert.equal(branch.dict!.value.meta.role, "yib-context-capacity"); + assert.equal(branch.dict!.value.list![0].meta.role, "table"); }); test("context schema preserves custom values and validates the declared capacity", () => { assert.equal(ModelConfigSchema({ modelId: "m" }).contextLimit?.mode, "unset"); for (const value of ["131072.5", "128K", "1M", "1m", " .5 k "]) { - assert.equal(ModelConfigSchema({ modelId: "m", contextLimit: { mode: "custom", value } }).contextLimit?.value, value); + assert.equal( + parseContextLimit(ModelConfigSchema({ modelId: "m", contextLimit: { mode: "custom", value } }).contextLimit!.value!), + parseContextLimit(value), + ); } for (const value of ["0", "-1", "NaN", "Infinity", "1G", "9007199254740992", "1".repeat(4097)]) { assert.throws(() => ModelConfigSchema({ modelId: "m", contextLimit: { mode: "custom", value } })); @@ -37,7 +41,7 @@ test("context schema preserves custom values and validates the declared capacity test("custom capacities validate after console schema serialization", () => { const consoleSchema = new Schema(JSON.parse(JSON.stringify(ModelConfigSchema))); - assert.equal(consoleSchema({ modelId: "m", contextLimit: { mode: "custom", value: "1M" } }).contextLimit?.value, "1M"); + assert.equal(parseContextLimit(consoleSchema({ modelId: "m", contextLimit: { mode: "custom", value: "1M" } }).contextLimit.value), 1000000); for (const value of ["0", "1G", "9007199254740992"]) { assert.throws(() => consoleSchema({ modelId: "m", contextLimit: { mode: "custom", value } })); } diff --git a/packages/core/tests/context-capacity-input.spec.ts b/packages/core/tests/context-capacity-input.spec.ts index 06e6f02b2..b85bbf14f 100644 --- a/packages/core/tests/context-capacity-input.spec.ts +++ b/packages/core/tests/context-capacity-input.spec.ts @@ -1,116 +1,62 @@ -import { expect, test } from "vitest"; -import { createRenderer, h, nextTick, ref } from "vue"; +import { Schema } from "koishi"; +import { expect, it } from "vitest"; -import { ContextCapacityInput } from "../client/context-capacity"; import { ModelConfigSchema } from "../src/model/config"; import { parseContextLimit } from "../src/model/context-limit"; -// Render the actual Vue input without a browser or Koishi server. -function mount(value?: string, disabled = false) { - const renderer = createRenderer({ - createElement: (type) => ({ type, props: {}, children: [] }), - createText: (text) => ({ text }), - createComment: (text) => ({ text }), - setText: (node, text) => (node.text = text), - setElementText: (node, text) => (node.text = text), - parentNode: (node) => node.parent, - nextSibling: () => null, - patchProp: (node, key, _previous, value) => (node.props[key] = value), - insert: (node, parent) => { - node.parent = parent; - parent.children.push(node); - }, - remove: (node) => { - node.parent.children = node.parent.children.filter((child) => child !== node); - }, - }); - const model = ref(value); - const root = { children: [] as any[] }; - const app = renderer.createApp({ - render: () => h(ContextCapacityInput, { modelValue: model.value, disabled, "onUpdate:modelValue": (next) => (model.value = next) }), - }); - app.mount(root); - return { - model, - input: () => root.children[0].children[0].children[0], - select: () => root.children[0].children[0].children[1], - errors: () => root.children[0].children.filter((node) => node.props?.role === "alert"), - dispose: () => app.unmount(), - }; +function capacityTable(schema = ModelConfigSchema) { + const custom = schema.dict!.contextLimit.list![1].list!.find((branch) => branch.dict?.mode.value === "custom")!; + return custom.dict!.value.list?.find((branch) => branch.type === "array"); } - -test("legacy capacities populate two cells without rewriting saved values", () => { - for (const [value, number, unit] of [ - ["1M", "1", "M"], - [" .5 k ", ".5", "K"], - ["131072.5", "131072.5", ""], - ]) { - const field = mount(value); - try { - expect(field.input().props.value).toBe(number); - expect(field.select().props.value).toBe(unit); - expect(field.model.value).toBe(value); - expect(field.errors()).toHaveLength(0); - } finally { - field.dispose(); - } - } +it("renders a native fixed-length table with exactly number and unit data columns", () => { + const schema = new Schema(JSON.parse(JSON.stringify(ModelConfigSchema))); + const table = capacityTable(schema); + expect(table?.meta.role).toBe("table"); + expect(table?.meta.min).toBe(1); + expect(table?.meta.max).toBe(1); + expect(Object.keys(table?.inner?.dict ?? {})).toEqual(["amount", "unit"]); + expect(table?.inner?.dict?.amount.type).toBe("number"); + expect(table?.inner?.dict?.unit.list?.map((choice) => choice.value)).toEqual(["token", "K", "M"]); +}); +it.each([ + [1.5, "M", 1500000], + [128, "K", 128000], + [131072.5, "token", 131072.5], + [1e-7, "M", 0.1], +])("converts a table capacity %s %s to tokens", (amount, unit, expected) => { + const schema = new Schema(JSON.parse(JSON.stringify(ModelConfigSchema))); + const config = schema({ modelId: "m", contextLimit: { mode: "custom", value: [{ amount, unit }] } }); + expect(parseContextLimit(config.contextLimit.value)).toBeCloseTo(expected, 12); +}); +it.each(["128K", "1m", " .5 k ", "131072.5"])("loads the legacy declaration %s into the table", (value) => { + const schema = new Schema(JSON.parse(JSON.stringify(ModelConfigSchema))); + const config = schema({ modelId: "m", contextLimit: { mode: "custom", value } }); + expect(Array.isArray(config.contextLimit.value)).toBe(true); + expect(parseContextLimit(config.contextLimit.value)).toBe(parseContextLimit(value)); +}); +it.for([ + [], + [ + { amount: 1, unit: "K" }, + { amount: 2, unit: "M" }, + ], + [{ amount: 0, unit: "K" }], + [{ amount: -1, unit: "M" }], + [{ amount: NaN, unit: "K" }], + [{ amount: Infinity, unit: "token" }], + [{ amount: 1, unit: "G" }], + [{ amount: 1e13, unit: "M" }], +])("rejects an invalid table declaration %j", (value) => { + expect(() => ModelConfigSchema({ modelId: "m", contextLimit: { mode: "custom", value } })).toThrow(/./); }); -test("number and unit edits survive parent echoes, clearing, and config validation", async () => { - const field = mount("1M"); - try { - field.input().props.onInput({ target: { value: "1.5" } }); - await nextTick(); - expect(field.model.value).toBe("1.5M"); - expect(parseContextLimit(ModelConfigSchema({ modelId: "m", contextLimit: { mode: "custom", value: field.model.value } }).contextLimit!.value!)).toBe( - 1500000, - ); - field.select().props.onChange({ target: { value: "K" } }); - await nextTick(); - expect(field.model.value).toBe("1.5K"); - field.input().props.onInput({ target: { value: "" } }); - await nextTick(); - expect(field.errors()).toHaveLength(1); - expect(field.select().props.value).toBe("K"); - field.input().props.onInput({ target: { value: "128" } }); - await nextTick(); - expect(field.model.value).toBe("128K"); - expect(field.errors()).toHaveLength(0); - field.model.value = "2M"; - await nextTick(); - expect(field.input().props.value).toBe("2"); - expect(field.select().props.value).toBe("M"); - } finally { - field.dispose(); - } +it.each(["9007199254740991.1", "9007199254740.9911K"])("rejects unsafe legacy capacity %s before numeric rounding", (value) => { + expect(() => ModelConfigSchema({ modelId: "m", contextLimit: { mode: "custom", value } })).toThrow(/./); }); -test("pasted units work, invalid drafts stay visible, and disabled controls cannot edit", async () => { - const field = mount(); - try { - field.input().props.onInput({ target: { value: "1M" } }); - await nextTick(); - expect(field.input().props.value).toBe("1"); - expect(field.select().props.value).toBe("M"); - for (const value of ["0", "-1", "Infinity", "1G", "9007199254740992"]) { - field.input().props.onInput({ target: { value } }); - await nextTick(); - expect(field.input().props.value).toBe(value); - expect(field.errors()).toHaveLength(1); - expect(() => ModelConfigSchema({ modelId: "m", contextLimit: { mode: "custom", value: field.model.value } })).toThrow(/contextLimit|最大上下文/); - } - } finally { - field.dispose(); - } - const locked = mount("1M", true); - try { - expect(locked.input().props.disabled).toBe(true); - expect(locked.select().props.disabled).toBe(true); - locked.input().props.onInput({ target: { value: "2" } }); - locked.select().props.onChange({ target: { value: "K" } }); - expect(locked.model.value).toBe("1M"); - } finally { - locked.dispose(); - } +it("offers an editable initial row without accepting a missing custom capacity", () => { + const table = capacityTable(); + expect(table?.meta.default).toEqual([{ unit: "K" }]); + expect(() => ModelConfigSchema({ modelId: "m", contextLimit: { mode: "custom" } })).toThrow(/./); + expect(() => ModelConfigSchema({ modelId: "m", contextLimit: { mode: "custom", value: [{ unit: "K" }] } })).toThrow(/./); }); diff --git a/packages/core/tests/context-working-state-failure.spec.ts b/packages/core/tests/context-working-state-failure.spec.ts index 158cd8fce..a6a5719f7 100644 --- a/packages/core/tests/context-working-state-failure.spec.ts +++ b/packages/core/tests/context-working-state-failure.spec.ts @@ -72,3 +72,68 @@ for (const change of ["context-filter", "channel-config", "identity", "history-g expect(f.warn).not.toHaveBeenCalled(); }); } + +it("projects validated working sources into context without writing history or treating them as new messages", async () => { + const source: any = { + id: "original", + platform: "test", + channelId: "room", + channelType: "guild", + sender: { id: "alice" }, + timestamp: new Date(0), + content: ' Original request', + }; + const f = fixture(async () => ({ + unknown: false, + state: { revision: 1, topic: "task", openIssues: [], sourceMessageIds: ["original"] }, + sourceMessages: [source], + })); + const builder = new PromptContextBuilder(f.ctx, { continuation: { enabled: true } } as any, { + model: {} as any, + logging: loggingStub(), + asset: {} as any, + memory: { getMemoryBlocksForRendering: () => [] } as any, + tool: { getToolSchemas: () => [] } as any, + world: f.world as any, + }); + const original = await f.world.buildWorldState(); + f.world.buildWorldState = async () => original; + const result = await builder.build(f.stimulus); + expect(result.worldState.l1_working_memory.processed_events).toMatchObject([{ id: "original", content: source.content, is_new: false }]); + expect(result.worldState.conversationFocus?.missingMessageIds).toEqual([]); + expect(original.l1_working_memory.processed_events).toEqual([]); +}); + +it("restores the original request for a background completion without counting it as a new message", async () => { + const f = fixture(async () => ({ unknown: true })); + f.stimulus.type = "background_task_completion"; + f.stimulus.session.messageId = "original"; + (f.world as any).readMessageWindow = async () => ({ + anchor: { id: "original", sender: { id: "alice" }, content: "Original request", timestamp: new Date(0) }, + quotes: [], + }); + const result = await f.build(); + expect(result.worldState.conversationFocus).toMatchObject({ triggerMessageIds: ["original"], missingMessageIds: [] }); + expect(result.worldState.l1_working_memory.processed_events).toMatchObject([{ id: "original", is_new: false }]); +}); + +it("refuses a queued continuation whose working state was replaced before context preparation", async () => { + const f = fixture(async () => ({ unknown: true })); + f.stimulus.continuationRequired = true; + f.stimulus.continuation = { + mode: "trigger", + revision: 1, + sourceMessageIds: ["original"], + expiresAt: Date.now() + 60000, + registeredAt: new Date().toISOString(), + }; + await expect(f.build()).rejects.toMatchObject({ name: "AbortError" }); +}); + +it("keeps independently admitted messages when their optional continuation expires", async () => { + const f = fixture(async () => ({ unknown: true })); + f.stimulus.continuationRequired = false; + f.stimulus.continuation = { mode: "trigger", revision: 1, sourceMessageIds: ["original"], expiresAt: 1, registeredAt: new Date(0).toISOString() }; + const result = await f.build(); + expect(result.worldState.conversationFocus?.continuation).toBeUndefined(); +}); diff --git a/packages/core/tests/conversation-continuation.spec.ts b/packages/core/tests/conversation-continuation.spec.ts new file mode 100644 index 000000000..2dea34526 --- /dev/null +++ b/packages/core/tests/conversation-continuation.spec.ts @@ -0,0 +1,91 @@ +import { expect, it } from "vitest"; + +import { matchContinuation } from "../src/agent/continuation"; + +const config = { enabled: true, mode: "trigger" as const, willingnessGain: 35, maxDurationSeconds: 300 }; +const session: any = { userId: "alice", selfId: "bot", elements: [], stripped: {} }; +const state: any = { + unknown: false, + state: { revision: 3, sourceMessageIds: ["source"], updatedAt: new Date(1000).toISOString(), followUp: { userIds: ["alice"], expiresAt: 61000 } }, +}; +it("matches only an explicitly registered recipient in the bounded waiting interval", () => { + expect(matchContinuation(session, config, state, 2000)).toMatchObject({ revision: 3, mode: "trigger", sourceMessageIds: ["source"] }); + for (const now of [0, 61000, 62000]) expect(matchContinuation(session, config, state, now)).toBeUndefined(); + expect(matchContinuation({ ...session, userId: "bob" }, config, state, 2000)).toBeUndefined(); + expect(matchContinuation(session, { ...config, enabled: false }, state, 2000)).toBeUndefined(); + expect(matchContinuation(session, config, { unknown: true }, 2000)).toBeUndefined(); + expect(matchContinuation(session, { ...config, maxDurationSeconds: 1 }, state, 2000)).toBeUndefined(); +}); +it("does not reinterpret messages addressed to someone else as continuation", () => { + for (const extra of [{ elements: [{ type: "at", attrs: { id: "bob" } }] }, { quote: { user: { id: "bob" } } }]) + expect(matchContinuation({ ...session, ...extra }, config, state, 2000)).toBeUndefined(); + expect(matchContinuation({ ...session, elements: [{ type: "at", attrs: { id: "bot" } }] }, config, state, 2000)).toBeDefined(); +}); +it("returns isolated anchor metadata and the administrator's selected mode", () => { + const result = matchContinuation(session, { ...config, mode: "willingness" }, state, 2000)!; + expect(result.mode).toBe("willingness"); + result.sourceMessageIds.push("mutated"); + expect(state.state.sourceMessageIds).toEqual(["source"]); +}); + +it("keeps continuation disabled for existing configurations and exposes native settings", async () => { + const { AgentBehaviorConfigSchema } = await import("../src/agent/config"); + const { Schema } = await import("koishi"); + const defaults = AgentBehaviorConfigSchema({}).continuation; + expect(defaults).toEqual({ enabled: false, mode: "trigger", willingnessGain: 35, maxDurationSeconds: 300 }); + const hydrated = new Schema(JSON.parse(JSON.stringify(AgentBehaviorConfigSchema))); + expect(hydrated({ continuation: { enabled: true, mode: "willingness" } }).continuation).toMatchObject({ + enabled: true, + mode: "willingness", + willingnessGain: 35, + }); + for (const continuation of [{ maxDurationSeconds: 0 }, { maxDurationSeconds: 86401 }, { willingnessGain: -1 }, { mode: "unknown" }]) + expect(() => AgentBehaviorConfigSchema({ continuation })).toThrow(/./); +}); + +it.each([true, false])("revalidates only continuation-dependent scheduled work (required=%s)", async (required) => { + const { vi } = await import("vitest"); + const { Context } = await import("koishi"); + const { AgentCore } = await import("../src/agent/agent-core"); + const { Config } = await import("../src/config"); + const { loggingStub } = await import("./helpers/yesimbot"); + vi.useFakeTimers(); + const ctx = new Context(); + let cycles = 0; + const core = new AgentCore(ctx, Config({ debounceMs: 1, continuation: config }), { + logging: loggingStub(), + world: { isBotMuted: () => false, getConversationState: async () => ({ unknown: true }) } as any, + model: { useChatGroup: () => ({}) } as any, + prompt: {} as any, + tool: {} as any, + asset: {} as any, + memory: {} as any, + }); + (core as any).processor = { + runCycle: async () => { + cycles++; + return false; + }, + }; + try { + (core as any).scheduler.schedule({ + type: "user_message", + channelCid: JSON.stringify(["qq", "bot", "room"]), + session: { platform: "qq", selfId: "bot", channelId: "room", userId: "alice", bot: { selfId: "bot" }, elements: [], stripped: {} }, + continuation: { + mode: "trigger", + revision: 1, + registeredAt: new Date().toISOString(), + expiresAt: Date.now() + 60000, + sourceMessageIds: ["original"], + }, + continuationRequired: required, + }); + await vi.advanceTimersByTimeAsync(10); + expect(cycles).toBe(required ? 0 : 1); + } finally { + await core.stop(); + await ctx.stop(); + vi.useRealTimers(); + } +}); diff --git a/packages/core/tests/conversation-state.spec.ts b/packages/core/tests/conversation-state.spec.ts index 3b87a7550..88b679e03 100644 --- a/packages/core/tests/conversation-state.spec.ts +++ b/packages/core/tests/conversation-state.spec.ts @@ -331,3 +331,88 @@ it("targeted clear preserves legacy notes in other channels until global migrati await restarted.l2_manager.clearHistory({ type: "all" }, async () => {}); expect(await f.app.database.get("worldstate.conversation_state", {})).toEqual([]); }); + +it("persists model-authored follow-up with fixed expiration and original-source validation", async () => { + const f = await fixture(); + await f.add(source("a")); + const before = Date.now(); + const result = await f.world.updateConversationState(f.session(), { + ...update, + topic: "", + openIssues: [], + followUp: { userIds: ["alice"], durationSeconds: 60 }, + }); + expect(result.unknown).toBe(false); + expect(result.state.followUp.userIds).toEqual(["alice"]); + expect(result.state.followUp.expiresAt).toBeGreaterThanOrEqual(before + 60_000); + expect(result.state.followUp.expiresAt).toBeLessThanOrEqual(Date.now() + 60_000); + expect(await f.restart().getConversationState(f.session())).toEqual(result); + await f.app.database.set(TableName.Messages, { ...target, id: "a" }, { content: "changed" }); + expect(await f.world.getConversationState(f.session())).toMatchObject({ unknown: true }); +}); + +it("rejects follow-up without sources or valid bounded recipients/duration", async () => { + const f = await fixture(); + await f.add(source("a")); + const invalid = [ + { userIds: [], durationSeconds: 60 }, + { userIds: ["alice", "alice"], durationSeconds: 60 }, + { userIds: [""], durationSeconds: 60 }, + { userIds: ["alice"], durationSeconds: 0 }, + { userIds: ["alice"], durationSeconds: Infinity }, + { userIds: ["alice"], durationSeconds: 86401 }, + ]; + for (const followUp of invalid) await expect(f.world.updateConversationState(f.session(), { ...update, followUp })).rejects.toThrow(/等待/); + await expect( + f.world.updateConversationState(f.session(), { + ...update, + topic: "", + openIssues: [], + sourceMessageIds: [], + followUp: { userIds: ["alice"], durationSeconds: 60 }, + }), + ).rejects.toThrow(/来源/); +}); + +it("returns original sources only when requested, without exposing fingerprints or storing source copies", async () => { + const f = await fixture(); + await f.add(source("a")); + await f.world.updateConversationState(f.session(), update); + const ordinary = await f.world.getConversationState(f.session()); + expect(ordinary).not.toHaveProperty("sourceMessages"); + const projected = await f.world.getConversationState(f.session(), { includeSources: true }); + expect(projected.sourceMessages).toMatchObject([{ id: "a", content: "a", sender: { id: "alice" } }]); + expect(projected.state).not.toHaveProperty("sourceFingerprints"); + expect(await f.restart().getConversationState(f.session())).not.toHaveProperty("sourceMessages"); +}); + +it("respects the administrator's continuation switch and duration ceiling", async () => { + const f = await fixture(); + await f.add(source("a")); + f.world.config.continuation = { enabled: false, maxDurationSeconds: 30 }; + const waiting = { ...update, followUp: { userIds: ["alice"], durationSeconds: 60 } }; + expect(() => f.world.updateConversationState(f.session(), waiting)).toThrow(/未启用/); + f.world.config.continuation.enabled = true; + expect(() => f.world.updateConversationState(f.session(), waiting)).toThrow(/上限/); +}); + +it("expires follow-up-only projections without renewing their fixed deadline", async () => { + const { vi } = await import("vitest"); + const f = await fixture(); + await f.add(source("a")); + await f.world.updateConversationState(f.session(), { + ...update, + topic: "", + openIssues: [], + followUp: { userIds: ["alice"], durationSeconds: 1 }, + }); + vi.spyOn(Date, "now").mockReturnValue(Date.now() + 2000); + try { + const result = await f.world.getConversationState(f.session(), { includeSources: true }); + expect(result.unknown).toBe(true); + expect(result.state.followUp).toBeUndefined(); + expect(result.state.revision).toBe(1); + } finally { + vi.restoreAllMocks(); + } +}); diff --git a/packages/core/tests/decision-core.spec.ts b/packages/core/tests/decision-core.spec.ts index 6ef2b0093..80657cd37 100644 --- a/packages/core/tests/decision-core.spec.ts +++ b/packages/core/tests/decision-core.spec.ts @@ -35,6 +35,7 @@ function setup() { stopped: false, decisions, pendingAssessments: new Map(), + topicScores: new Map(), activeTurns: new Map(), willing: new WillingnessManager(ctx, config, loggingStub(logger)), scheduler: { noteUserMessage() {}, isBusy: () => false, schedule: (s: any) => scheduled.push(s) }, @@ -164,3 +165,110 @@ it("separates Telegram topic decisions, scheduler keys, willingness and mute che Math.random = random; } }); + +function continuationSetup(mode = "trigger") { + const t = setup(); + t.ctx.filter = () => true; + t.core.config.lifecycle.probabilityThreshold = 99; + t.core.config.continuation = { enabled: true, mode, willingnessGain: 35, maxDurationSeconds: 300 }; + const state = { + unknown: false, + state: { + revision: 1, + topic: "", + openIssues: [], + sourceMessageIds: ["original"], + updatedAt: new Date().toISOString(), + followUp: { userIds: ["u"], expiresAt: Date.now() + 60000 }, + }, + }; + t.core.worldState.getConversationState = async () => state; + t.core.worldState.isChannelAllowed = () => true; + t.core.worldState.l2_manager = { getHistoryGeneration: () => 0 }; + return { ...t, state }; +} +const nextTick = () => new Promise((resolve) => setTimeout(resolve, 0)); +it("admits an explicit continuation despite low willingness without an extra model request", async () => { + const t = continuationSetup(); + t.core.receiveStimulus({ type: "user_message", session: t.session, payload: { messageIds: ["incoming"] } }); + await nextTick(); + expect(t.scheduled).toHaveLength(1); + expect(t.scheduled[0].continuation).toMatchObject({ revision: 1, sourceMessageIds: ["original"] }); + expect(t.decisions.latest(t.target)?.reason).toBe("conversation_continuation"); + expect(t.core.willing.getCurrentWillingness(t.decisions.latest(t.target)!.key)).toBe(12); +}); +it("can only add willingness and leaves the final probability decision in place", async () => { + const t = continuationSetup("willingness"); + t.core.receiveStimulus({ type: "user_message", session: t.session }); + await nextTick(); + expect(t.scheduled).toHaveLength(0); + expect(t.decisions.latest(t.target)?.calculation).toMatchObject({ before: 0, after: 47, continuationGain: 35 }); +}); +it("falls back to ordinary willingness if validated state cannot be read", async () => { + const t = continuationSetup(); + t.core.worldState.getConversationState = async () => { + throw new Error("database failure"); + }; + t.core.receiveStimulus({ type: "user_message", session: t.session }); + await nextTick(); + expect(t.scheduled).toHaveLength(0); + expect(t.decisions.latest(t.target)?.calculation?.after).toBe(12); +}); +it.each(["identity", "history", "permission", "pause", "stop", "mute"])("does not admit a pending continuation after %s changes", async (change) => { + const t = continuationSetup(); + let release!: (state: unknown) => void; + t.core.worldState.getConversationState = () => + new Promise((resolve) => { + release = resolve; + }); + t.core.receiveStimulus({ type: "user_message", session: t.session }); + await nextTick(); + if (change === "identity") t.session.channelId = "other"; + if (change === "history") t.core.worldState.l2_manager.getHistoryGeneration = () => 1; + if (change === "permission") t.core.worldState.isChannelAllowed = () => false; + if (change === "pause") await t.core.replyControl.set(t.target, ["all"], 1000); + if (change === "stop") t.core.stopped = true; + if (change === "mute") t.core.worldState.isBotMuted = () => true; + release(t.state); + await nextTick(); + expect(t.scheduled).toHaveLength(0); + expect(t.core.willing.getCurrentWillingness(t.decisions.latest(t.target)!.key)).toBe(0); +}); + +it("does not defer busy-message admission behind continuation database reads", () => { + const t = continuationSetup(); + t.core.scheduler.isBusy = () => true; + let reads = 0; + t.core.worldState.getConversationState = async () => { + reads++; + return t.state; + }; + t.core.receiveStimulus({ type: "user_message", session: t.session }); + expect(reads).toBe(0); + expect(t.decisions.latest(t.target)?.calculation?.after).toBe(12); +}); +it("marks only continuation-dependent admission for expiration cancellation", async () => { + const t = continuationSetup(); + t.core.config.prioritizeMentions = true; + t.session.elements = [{ type: "at", attrs: { id: "bot" } }]; + t.core.receiveStimulus({ type: "user_message", session: t.session }); + await nextTick(); + expect(t.scheduled).toHaveLength(1); + expect(t.scheduled[0].continuationRequired).toBe(false); +}); + +it("does not revive a read admitted before a mute and immediate unmute", async () => { + const t = continuationSetup(); + let release!: (state: unknown) => void; + t.core.worldState.getConversationState = () => + new Promise((resolve) => { + release = resolve; + }); + t.core.receiveStimulus({ type: "user_message", session: t.session }); + await nextTick(); + t.core.resetWillingness(t.decisions.latest(t.target)!.key); + release(t.state); + await nextTick(); + expect(t.scheduled).toHaveLength(0); + expect(t.decisions.latest(t.target)?.stage).toBe("cancelled"); +}); diff --git a/packages/core/tests/history-clear-recording.spec.ts b/packages/core/tests/history-clear-recording.spec.ts index 1585265fb..4ea57fe60 100644 --- a/packages/core/tests/history-clear-recording.spec.ts +++ b/packages/core/tests/history-clear-recording.spec.ts @@ -32,120 +32,9 @@ function matches(row: any, query: any): boolean { for (const overlap of [false, true]) { for (const commitFirst of [true, false]) { for (const type of [undefined, "private", "guild", "all"]) { - it(`clears accepted L1 writes before ${commitFirst ? "return" : "commit"} for ${type ?? "target"}, preserving later messages${overlap ? " across overlapping clears" : ""}`, async () => { + it(`clears accepted L1 writes before ${commitFirst ? "return" : "commit"} for ${type ?? "target"}, preserving later messages${overlap ? " across overlapping clears" : ""}`, async (t) => { const root = await fs.mkdtemp(path.join(os.tmpdir(), "yib-clear-recording-")); - try { - const rows = new Map( - [TableName.Messages, TableName.SystemEvents, TableName.L2Chunks, TableName.L3Diaries].map((name) => [name, []]), - ); - // -a private/guild 依赖 HISTORY_CHANNELS 判定频道类型。 - rows.set(HISTORY_CHANNELS, [ - { platform: "onebot", channelId: "private:user", channelType: "private" }, - { platform: "onebot", channelId: "same", channelType: "guild" }, - ]); - const entered = deferred(), - release = deferred(); - const actions = new Map(); - const command = (name: string): any => { - const cmd = { - option: () => cmd, - usage: () => cmd, - example: () => cmd, - subcommand: (suffix: string) => command(name + suffix), - action: (fn: Function) => { - actions.set(name, fn); - return cmd; - }, - }; - return cmd; - }; - const ctx = stubCtx( - { - logging: { getLogger: () => log }, - model: { useEmbeddingGroup: () => ({ getModels: () => [{ embed: async () => ({ embedding: [1] }) }] }) }, - }, - { - baseDir: root, - logger: log, - command, - database: { - get: async (table: string, query: any) => rows.get(table)!.filter((row) => matches(row, query)), - create: async (table: string, row: any) => { - if (row.id === "old") { - if (commitFirst) rows.get(table)!.push(row); - entered.resolve(); - await release.promise; - if (!commitFirst) rows.get(table)!.push(row); - } else rows.get(table)!.push(row); - return row; - }, - remove: async (table: string, query: any) => { - const old = rows.get(table)!; - const keep = old.filter((row) => !matches(row, query)); - rows.set(table, keep); - return { removed: old.length - keep.length }; - }, - }, - }, - ); - const config: any = { l2_memory: { enabled: true, messagesPerChunk: 1 }, l1_memory: { maxMessages: 10 } }; - const world: any = Object.create(WorldStateService.prototype); - world.config = config; - world.l1_manager = new InteractionManager(ctx, config, ctx.yesimbot.logging); - world.l2_manager = new SemanticMemoryManager(ctx, config, ctx.yesimbot.logging, ctx.yesimbot.model); - world.l2_manager.observeChannel({ platform: "onebot", channelId: "private:user" }, "private"); - world.l2_manager.observeChannel({ platform: "onebot", channelId: "same" }, "guild"); - world.l2_manager.start(); - new HistoryCommandManager(ctx, world, config, ctx.yesimbot.logging).register(); - const channelId = type === "private" ? "private:user" : "same"; - const message = (id: string, platform = "onebot") => ({ - id, - platform, - channelId, - content: id, - sender: { id: "user", name: "User" }, - timestamp: new Date(1000), - }); - const old = world.recordMessage(message("old")); - await entered.promise; - let cleared = false; - const clearing = actions.get("history.clear")!({ - session: { platform: "onebot", channelId }, - options: type ? { all: type } : {}, - }).then((value: string) => { - cleared = true; - return value; - }); - const fresh = world.recordMessage(message("fresh")); - const secondClear = overlap - ? actions.get("history.clear")!({ session: { platform: "onebot", channelId }, options: { all: "all" } }) - : undefined; - const newest = overlap ? world.recordMessage(message("newest")) : undefined; - // An explicit target must not hold another platform's L1 write. - const other = !type && !overlap ? world.recordMessage(message("other", "discord")) : undefined; - if (other) await other; - for (let i = 0; i < 25; i++) await Promise.resolve(); - const completedEarly = cleared; - release.resolve(); - const report = await clearing; - await Promise.all([old, fresh, secondClear, newest]); - await world.l2_manager.stop(); - expect(completedEarly).toBe(false); - expect(report).toContain("操作成功"); - const wanted = overlap ? ["newest"] : !type ? ["fresh", "other"] : ["fresh"]; - expect( - rows - .get(TableName.Messages)! - .map((row) => row.id) - .sort(), - ).toEqual(wanted); - expect( - rows - .get(TableName.L2Chunks)! - .map((row) => row.content) - .sort(), - ).toEqual(wanted.map((id) => `User: ${id}`)); - } finally { + t.onTestFinished(async () => { // Windows 下 antivirus/索引器会短暂锁住新目录,EBUSY 时稍候重试。 for (let attempt = 0; ; attempt++) { try { @@ -161,7 +50,117 @@ for (const overlap of [false, true]) { await promise; } } - } + }); + const rows = new Map( + [TableName.Messages, TableName.SystemEvents, TableName.L2Chunks, TableName.L3Diaries].map((name) => [name, []]), + ); + // -a private/guild 依赖 HISTORY_CHANNELS 判定频道类型。 + rows.set(HISTORY_CHANNELS, [ + { platform: "onebot", channelId: "private:user", channelType: "private" }, + { platform: "onebot", channelId: "same", channelType: "guild" }, + ]); + const entered = deferred(), + release = deferred(); + const actions = new Map(); + const command = (name: string): any => { + const cmd = { + option: () => cmd, + usage: () => cmd, + example: () => cmd, + subcommand: (suffix: string) => command(name + suffix), + action: (fn: Function) => { + actions.set(name, fn); + return cmd; + }, + }; + return cmd; + }; + const ctx = stubCtx( + { + logging: { getLogger: () => log }, + model: { useEmbeddingGroup: () => ({ getModels: () => [{ embed: async () => ({ embedding: [1] }) }] }) }, + }, + { + baseDir: root, + logger: log, + command, + database: { + get: async (table: string, query: any) => rows.get(table)!.filter((row) => matches(row, query)), + create: async (table: string, row: any) => { + if (row.id === "old") { + if (commitFirst) rows.get(table)!.push(row); + entered.resolve(); + await release.promise; + if (!commitFirst) rows.get(table)!.push(row); + } else rows.get(table)!.push(row); + return row; + }, + remove: async (table: string, query: any) => { + const old = rows.get(table)!; + const keep = old.filter((row) => !matches(row, query)); + rows.set(table, keep); + return { removed: old.length - keep.length }; + }, + }, + }, + ); + const config: any = { l2_memory: { enabled: true, messagesPerChunk: 1 }, l1_memory: { maxMessages: 10 } }; + const world: any = Object.create(WorldStateService.prototype); + world.config = config; + world.l1_manager = new InteractionManager(ctx, config, ctx.yesimbot.logging); + world.l2_manager = new SemanticMemoryManager(ctx, config, ctx.yesimbot.logging, ctx.yesimbot.model); + world.l2_manager.observeChannel({ platform: "onebot", channelId: "private:user" }, "private"); + world.l2_manager.observeChannel({ platform: "onebot", channelId: "same" }, "guild"); + world.l2_manager.start(); + new HistoryCommandManager(ctx, world, config, ctx.yesimbot.logging).register(); + const channelId = type === "private" ? "private:user" : "same"; + const message = (id: string, platform = "onebot") => ({ + id, + platform, + channelId, + content: id, + sender: { id: "user", name: "User" }, + timestamp: new Date(1000), + }); + const old = world.recordMessage(message("old")); + await entered.promise; + let cleared = false; + const clearing = actions.get("history.clear")!({ + session: { platform: "onebot", channelId }, + options: type ? { all: type } : {}, + }).then((value: string) => { + cleared = true; + return value; + }); + const fresh = world.recordMessage(message("fresh")); + const secondClear = overlap + ? actions.get("history.clear")!({ session: { platform: "onebot", channelId }, options: { all: "all" } }) + : undefined; + const newest = overlap ? world.recordMessage(message("newest")) : undefined; + // An explicit target must not hold another platform's L1 write. + const other = !type && !overlap ? world.recordMessage(message("other", "discord")) : undefined; + if (other) await other; + for (let i = 0; i < 25; i++) await Promise.resolve(); + const completedEarly = cleared; + release.resolve(); + const report = await clearing; + await Promise.all([old, fresh, secondClear, newest]); + await world.l2_manager.stop(); + expect(completedEarly).toBe(false); + expect(report).toContain("操作成功"); + const wanted = overlap ? ["newest"] : !type ? ["fresh", "other"] : ["fresh"]; + expect( + rows + .get(TableName.Messages)! + .map((row) => row.id) + .sort(), + ).toEqual(wanted); + expect( + rows + .get(TableName.L2Chunks)! + .map((row) => row.content) + .sort(), + ).toEqual(wanted.map((id) => `User: ${id}`)); }); } } From f5df20a05ce606c132e01dd29cffc6f0c52bec6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=AE=B8=E4=BB=99xhcz?= Date: Sun, 25 Oct 2026 14:05:46 +0800 Subject: [PATCH 2/6] =?UTF-8?q?feat(v3-dev):=20=E6=B7=BB=E5=8A=A0=E5=8F=AF?= =?UTF-8?q?=E9=80=89=E7=BE=A4=E8=81=8A=E5=B9=B3=E8=A1=A1=E6=84=8F=E6=84=BF?= =?UTF-8?q?=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/balanced-willingness.md | 42 ++++ docs/decision-replay.md | 4 + docs/feature-guide.md | 2 + packages/core/scripts/replay-decisions.cjs | 44 +++- packages/core/src/agent/config.ts | 44 ++++ packages/core/src/agent/decision-journal.ts | 33 ++- packages/core/src/agent/decision-record.ts | 11 +- packages/core/src/agent/willing.ts | 172 +++++++++++++-- packages/core/src/agent/willingness-policy.ts | 157 ++++++++++++++ .../core/tests/balanced-willingness.spec.ts | 202 ++++++++++++++++++ packages/core/tests/decision-journal.spec.ts | 51 +++++ .../core/tests/decision-replay-cli.spec.ts | 73 +++++++ 12 files changed, 816 insertions(+), 19 deletions(-) create mode 100644 docs/balanced-willingness.md create mode 100644 packages/core/src/agent/willingness-policy.ts create mode 100644 packages/core/tests/balanced-willingness.spec.ts diff --git a/docs/balanced-willingness.md b/docs/balanced-willingness.md new file mode 100644 index 000000000..9c35df8a4 --- /dev/null +++ b/docs/balanced-willingness.md @@ -0,0 +1,42 @@ +# 可选群聊平衡意愿算法 + +在「意愿算法选择」中,将 `willingnessPolicy.algorithm` 从 `legacy` 切换为 `balanced`。默认仍是原有算法;缺少这个配置的旧配置也继续使用原有算法。平衡算法为实验性功能,切换后按群聊实际效果调整参数。 + +它只改变意愿计算和普通消息的概率判定频率。权限、禁言、暂停、回复类别、忙时消息处理和工具调度仍由现有流程控制。不需要启用 JEV、话题分析或额外模型。 + +## 计算方式 + +- 沿用文本、兴趣、明确 @ 机器人、引用机器人、私聊、参与保持和可选语义评估提供的增益输入;取消原算法的动态与边际放大,概率按阈值和放大系数线性计算。 +- 普通消息使用逐渐回补的增益额度,同一会话的所有话题共享。默认初始额度 24,每 60 秒回补 24,密集消息不能立即补满。 +- 明确 @ 或引用他人的群消息不增加意愿,可对最终选中的话题减分。默认每次最多减 12,共享减分额度 24,每 60 秒回补。未知接收人、没有回复和沉默不会自动视作负反馈。配置减分为 0 可关闭。 +- 意愿按实际经过时间衰减,半衰期沿用生命周期配置。高分与群聊热度不再减慢衰减。 +- 普通消息存在正概率时,默认至少间隔 10 秒才抽取一次随机数。被间隔限制或概率为零时不抽取随机数。 +- 每个成功回复回合增加短期回复压力,默认产生 12 分概率折减,30 秒减半。压力不永久扣除意愿;原有成功回复成本仍会扣分。 + +符合启用类别的明确 @ 机器人、引用机器人和私聊,不受普通增益额度、判定间隔和短期回复压力限制。它们仍使用配置的增益和概率,不会因此强制回复。关闭对应回复类别后,不会通过该类别获得邀请加成。 + +后台任务及会话续接配置的意愿奖励单独计入,不消耗普通消息额度,仍保留原有完成回调行为。话题兴趣只给消息所属话题增加意愿;选择其他话题时不会再次增加普通消息增益。 + +## 配置 + +```yaml +willingnessPolicy: + algorithm: balanced + windowSeconds: 60 + ordinaryGainLimit: 24 + decisionIntervalSeconds: 10 + othersPenalty: 12 + negativeGainLimit: 24 + replyPenalty: 12 + replyPenaltyHalfLifeSeconds: 30 +``` + +`windowSeconds` 是额度从空到满的回补时间,不是固定窗口清零。`ordinaryGainLimit: 0` 关闭普通消息增益,`decisionIntervalSeconds: 0` 关闭判定间隔,`othersPenalty: 0` 或 `negativeGainLimit: 0` 关闭面向他人的减分,`replyPenalty: 0` 关闭短期回复压力。 + +意愿与额度是进程内状态,不在重启后恢复。建议切换后从新的观察期评估;切回 `legacy` 即恢复原有算法。 + +## 观察和回放 + +`chat.decision` 会显示平衡算法的时间衰减、增加、减少、额度限制和短期压力。启用决策记录后,离线回放能使用 `balanced-v1` 数值轨迹复算单条判定,间隔节流的记录允许没有随机数,且不会重新抽取。 + +这些记录能解释算法怎样算出结果,不能证明发言是否合适。新旧算法的忙群合成回放用于验证边界行为;真实效果仍应结合群聊中的实际反馈评估。单条快照回放不会重建完整会话,也不能推断换算法后群成员会怎样回应。 diff --git a/docs/decision-replay.md b/docs/decision-replay.md index 9c92f1dd2..3c5efec7f 100644 --- a/docs/decision-replay.md +++ b/docs/decision-replay.md @@ -83,3 +83,7 @@ node node_modules/koishi-plugin-yesimbot/scripts/replay-decisions.cjs decisions. 每条可复算记录增加 `scenario`,并保留原来的 `roll`。未指定的参数沿用原值。`recomputed` 和 `matches` 仍核对原始参数,`scenario` 单独展示假设参数下的概率和判定。调整参数不会重新抽样,也不会把新判定、回复成本或衰减传递给下一条记录;这是独立记录的情景比对,不是完整对话轨迹重演。 参数无效、文件不可读或输出失败时脚本以非零退出码结束;输入记录的不兼容、损坏和缺少数据则在汇总中计数,请检查这些数量后再解释结果。 + +## 群聊平衡算法记录 + +`calculation.policy.version` 为 `balanced-v1` 时,回放使用记录中的实际时间衰减、正负增益与短期回复压力计算分数和概率,不使用原算法的动态乘数。普通消息判定间隔限制会保留为零概率;此类记录和其他零概率记录可以没有 `roll`,回放不会重新抽取随机数。`--threshold` 和 `--amplifier` 仍只修改单条记录的参数,保留原有间隔限制,不能重新模拟完整的额度、间隔与回复轨迹。配置见 [可选群聊平衡意愿算法](balanced-willingness.md)。 diff --git a/docs/feature-guide.md b/docs/feature-guide.md index 9c7d6fd79..8b0cb9fe3 100644 --- a/docs/feature-guide.md +++ b/docs/feature-guide.md @@ -21,6 +21,8 @@ YesImBot 的基础对话、回复调度、聊天历史和 L1/L2/L3 记忆由核 多数管理指令要求 Koishi 权限等级至少为 3。可用参数以当前安装版本的指令帮助为准。工具是 Agent 可以调用的能力,管理指令是用户在聊天中执行的操作,两者不一定同名或一一对应。 +意愿算法默认沿用原有实现,可在配置中切换到实验性的 [群聊平衡算法](balanced-willingness.md),对密集普通消息增益、判定频率和近期回复压力分别设置限制。 + ## 几种记忆分别负责什么 | 类型 | 用途 | 设置位置 | diff --git a/packages/core/scripts/replay-decisions.cjs b/packages/core/scripts/replay-decisions.cjs index 3cc650efc..d64f77441 100644 --- a/packages/core/scripts/replay-decisions.cjs +++ b/packages/core/scripts/replay-decisions.cjs @@ -62,6 +62,13 @@ const fields = [ const finite = (value) => typeof value === "number" && Number.isFinite(value); const identifier = (value) => typeof value === "string" && value.length > 0 && value.length <= 512 && !/[\x00-\x1f\x7f]/.test(value); const object = (value) => value && typeof value === "object" && !Array.isArray(value); +const missingFields = (calculation) => + fields.filter( + (field) => + !object(calculation) || + (!(field === "roll" && calculation.policy?.version === "balanced-v1" && calculation.probability === 0 && calculation.roll === undefined) && + !finite(calculation[field])), + ); const usage = "Usage: node scripts/replay-decisions.cjs [--key KEY] [--from ISO] [--to ISO] [--threshold NUMBER] [--amplifier NUMBER]"; function parseOptions(args) { @@ -122,8 +129,26 @@ async function* lines(filename) { } function recompute(calculation, threshold = calculation.threshold, amplifier = calculation.amplifier) { + if (calculation.policy?.version === "balanced-v1") { + const p = calculation.policy; + const effectiveGain = p.positiveGain - p.negativeGain + (finite(calculation.continuationGain) ? Math.max(0, calculation.continuationGain) : 0); + const after = Math.max(0, Math.min(calculation.maxWillingness, calculation.before - p.decay + effectiveGain)); + const probability = p.gate === "opportunity_interval" ? 0 : Math.max(0, Math.min(1, (Math.max(0, after - p.fatiguePenalty) - threshold) * amplifier)); + return { + rawGain: p.requestedGain, + effectiveGain, + after, + threshold, + amplifier, + probability, + roll: calculation.roll, + decision: probability === 0 ? false : finite(calculation.roll) ? calculation.roll < probability : undefined, + }; + } const rawGain = calculation.baseScore * calculation.interestMultiplier * calculation.participationMultiplier * calculation.marginalMultiplier; - const effectiveGain = rawGain * calculation.dynamicMultiplier * calculation.assessmentMultiplier; + const effectiveGain = + rawGain * calculation.dynamicMultiplier * calculation.assessmentMultiplier + + (finite(calculation.continuationGain) ? Math.max(0, calculation.continuationGain) : 0); const after = Math.min(calculation.before + effectiveGain, calculation.maxWillingness); const probability = after > threshold ? Math.max(0, Math.min(1, (after - threshold) * amplifier)) : 0; return { @@ -170,7 +195,7 @@ async function replay(options) { (options.to !== undefined && record.time > options.to) ) continue; - if (!object(record.calculation) || fields.some((field) => !finite(record.calculation[field])) || typeof record.decision !== "boolean") continue; + if (!object(record.calculation) || missingFields(record.calculation).length || typeof record.decision !== "boolean") continue; if (!preferred.has(record.id)) { if (preferred.size >= 100000) throw Object.assign(new Error(), { code: "REPLAY_INDEX_LIMIT" }); preferred.set(record.id, { calculated: false, replayed: false }); @@ -245,7 +270,7 @@ async function replay(options) { if (reasons.has(record.reason)) event.reason = record.reason; if (typeof record.decision === "boolean") event.recordedDecision = record.decision; const calculation = record.calculation; - const missing = fields.filter((field) => !object(calculation) || !finite(calculation[field])); + const missing = missingFields(calculation); if (missing.length || typeof record.decision !== "boolean") { summary.missingCalculation++; event.status = !object(calculation) ? "no_calculation" : "missing_calculation_data"; @@ -260,6 +285,19 @@ async function replay(options) { await output(event); continue; } + const p = calculation.policy; + if ( + p !== undefined && + (!object(p) || + p.version !== "balanced-v1" || + !["decay", "requestedGain", "positiveGain", "negativeGain", "fatiguePenalty"].every((key) => finite(p[key]) && p[key] >= 0) || + !["none", "opportunity_interval", "recent_reply_pressure"].includes(p.gate)) + ) { + summary.corrupt++; + event.status = "invalid_calculation_data"; + await output(event); + continue; + } event.recomputed = recompute(calculation); if (record.forcedReply === true) event.recomputed.decision = true; if ( diff --git a/packages/core/src/agent/config.ts b/packages/core/src/agent/config.ts index 7954937be..72afeb907 100644 --- a/packages/core/src/agent/config.ts +++ b/packages/core/src/agent/config.ts @@ -6,6 +6,7 @@ import { Computed, Schema } from "koishi"; import { SystemConfig } from "../config"; import { PROMPTS_DIR } from "../shared/constants"; import type { TopicConfig } from "./topics"; +import { DEFAULT_WILLINGNESS_POLICY, type WillingnessPolicyConfig } from "./willingness-policy"; export const SystemBaseTemplate = readFileSync(path.resolve(PROMPTS_DIR, "memgpt_v2_chat.txt"), "utf-8"); export const UserBaseTemplate = readFileSync(path.resolve(PROMPTS_DIR, "user_base.txt"), "utf-8"); @@ -66,6 +67,7 @@ export interface ContinuationConfig { export interface WillingnessConfig { continuation?: ContinuationConfig; + willingnessPolicy?: WillingnessPolicyConfig; topics?: TopicConfig; participation?: { enabled: boolean; @@ -125,6 +127,48 @@ const WillingnessConfigSchema: Schema = Schema.object({ }) .collapse() .description("会话续接(模型显式登记,默认关闭;仍遵守回复控制与新消息处理策略)"), + willingnessPolicy: Schema.object({ + algorithm: Schema.union([Schema.const("legacy").description("原有算法"), Schema.const("balanced").description("群聊平衡算法(实验性)")]) + .default("legacy") + .description("意愿算法;默认保持原有行为"), + windowSeconds: Schema.number() + .min(1) + .max(86400) + .default(DEFAULT_WILLINGNESS_POLICY.windowSeconds) + .description("平衡算法:增减分额度完全回补所需时间(秒)"), + ordinaryGainLimit: Schema.number() + .min(0) + .max(1000000) + .default(DEFAULT_WILLINGNESS_POLICY.ordinaryGainLimit) + .description("平衡算法:普通消息增益额度,同一会话的话题共享"), + decisionIntervalSeconds: Schema.number() + .min(0) + .max(86400) + .default(DEFAULT_WILLINGNESS_POLICY.decisionIntervalSeconds) + .description("平衡算法:普通消息两次概率判定的最短间隔(秒),0 不限制"), + othersPenalty: Schema.number() + .min(0) + .max(1000000) + .default(DEFAULT_WILLINGNESS_POLICY.othersPenalty) + .description("平衡算法:明确提及或引用他人时的减分,0 关闭"), + negativeGainLimit: Schema.number() + .min(0) + .max(1000000) + .default(DEFAULT_WILLINGNESS_POLICY.negativeGainLimit) + .description("平衡算法:面向他人减分额度,逐渐回补,避免连续消息过度扣分"), + replyPenalty: Schema.number() + .min(0) + .max(1000000) + .default(DEFAULT_WILLINGNESS_POLICY.replyPenalty) + .description("平衡算法:每个成功回复回合产生的短期插话压力,0 关闭;只降低普通消息概率"), + replyPenaltyHalfLifeSeconds: Schema.number() + .min(1) + .max(86400) + .default(DEFAULT_WILLINGNESS_POLICY.replyPenaltyHalfLifeSeconds) + .description("平衡算法:短期插话压力半衰期(秒)"), + }) + .collapse() + .description("意愿算法选择(切换算法不会改变忙时处理策略)"), topics: Schema.object({ enabled: Schema.boolean().default(false).experimental().description("启用实验性话题意愿,默认关闭;识别可能滞后或不准确,请按实际聊天效果调整"), model: Schema.dynamic("modelService.selectableModels").description("话题总结模型(需具备对话能力;启用后会发送近期聊天内容)"), diff --git a/packages/core/src/agent/decision-journal.ts b/packages/core/src/agent/decision-journal.ts index 3ea0ad0c3..54cc6dc10 100644 --- a/packages/core/src/agent/decision-journal.ts +++ b/packages/core/src/agent/decision-journal.ts @@ -110,9 +110,29 @@ export function sanitizeDecisionRecord(value: unknown): DecisionRecord | undefin for (const field of ["decision", "success", "forcedReply"] as const) if (typeof value[field] === "boolean") result[field] = value[field]; for (const field of ["score", "probability", "roll"] as const) if (finite(value[field])) result[field] = value[field]; if (object(value.calculation)) { - const calculation: Record = {}; + const calculation: Record = {}; for (const field of calculationFields) if (finite(value.calculation[field])) calculation[field] = value.calculation[field]; result.calculation = calculation; + const policy = value.calculation.policy; + if (object(policy) && policy.version === "balanced-v1") { + const trace: Record = { version: "balanced-v1" }; + for (const field of ["invited", "addressesOthers", "preview"]) if (typeof policy[field] === "boolean") trace[field] = policy[field]; + for (const field of [ + "decay", + "requestedGain", + "positiveGain", + "negativeGain", + "limitedGain", + "ordinaryGainRemaining", + "negativeGainRemaining", + "fatiguePenalty", + "rawProbability", + ]) + if (finite(policy[field])) trace[field] = policy[field]; + if (typeof policy.gate === "string" && ["none", "opportunity_interval", "recent_reply_pressure"].includes(policy.gate)) trace.gate = policy.gate; + calculation.policy = trace; + } + if (object(value.calculation.gains)) { const gains: Record = {}; for (const field of ["text", "at", "quote", "direct"] as const) @@ -350,7 +370,16 @@ export class DecisionJournal { if ( object(value) && object((value as any).calculation) && - calculationFields.some((field) => !finite((value as any).calculation[field])) + calculationFields.some( + (field) => + field !== "continuationGain" && + !( + field === "roll" && + (value as any).calculation.policy?.version === "balanced-v1" && + (value as any).calculation.probability === 0 + ) && + !finite((value as any).calculation[field]), + ) ) this.warning("Decision journal calculation metadata is incomplete; offline replay will report missing fields."); const entry = this.add(record); diff --git a/packages/core/src/agent/decision-record.ts b/packages/core/src/agent/decision-record.ts index 01eaaf77e..fe1e64b05 100644 --- a/packages/core/src/agent/decision-record.ts +++ b/packages/core/src/agent/decision-record.ts @@ -4,6 +4,7 @@ import { replyKey, ReplyTarget } from "./reply-control"; /** 实际参与本条消息计算的值;不包含消息正文或模型配置中的凭据。 */ export interface WillingnessCalculation { + policy?: import("./willingness-policy").BalancedTrace; gains?: { text: number; at: number; quote: number; direct: number }; before: number; after: number; @@ -19,7 +20,7 @@ export interface WillingnessCalculation { threshold: number; amplifier: number; probability: number; - roll: number; + roll?: number; } export interface DecisionRecord { @@ -181,6 +182,14 @@ export function formatDecision(record: DecisionRecord | undefined, state: Decisi `语义乘数:${c.assessmentMultiplier.toFixed(3)};参与乘数:${c.participationMultiplier.toFixed(3)}`, ); } + if (c?.policy) { + const p = c.policy; + const gates = { none: "无", opportunity_interval: "普通消息判定间隔", recent_reply_pressure: "近期回复压力" }; + lines.push( + `算法:群聊平衡;时间衰减:${p.decay.toFixed(2)};增加:${p.positiveGain.toFixed(2)};减少:${p.negativeGain.toFixed(2)};限流增益:${p.limitedGain.toFixed(2)}`, + `近期回复压力:${p.fatiguePenalty.toFixed(2)};节流原因:${gates[p.gate]}`, + ); + } if (record.probability !== undefined || record.roll !== undefined) lines.push( `回复概率:${record.probability === undefined ? "未计算" : `${(record.probability * 100).toFixed(1)}%`};随机数:${record.roll ?? "未抽取"};判定:${record.decision === undefined ? "未判定" : record.decision ? "回复" : "不回复"}`, diff --git a/packages/core/src/agent/willing.ts b/packages/core/src/agent/willing.ts index 691361f83..1256b595b 100644 --- a/packages/core/src/agent/willing.ts +++ b/packages/core/src/agent/willing.ts @@ -6,6 +6,7 @@ import { conversationCid } from "../shared/utils/conversation-scope"; import { WillingnessConfig } from "./config"; import type { WillingnessCalculation } from "./decision-record"; import type { ReplyCategory } from "./reply-control"; +import { BalancedWillingnessPolicy, nonnegative, resolveWillingnessPolicy } from "./willingness-policy"; export interface MessageContext { chatId: string; @@ -18,6 +19,9 @@ export interface MessageContext { isDirect: boolean; allowedCategories?: ReplyCategory[]; continuationGain?: number; + preview?: boolean; + priorDecay?: number; + deferWithdrawal?: boolean; } export interface TopicWillingnessInput { @@ -74,9 +78,15 @@ export class WillingnessManager { private participation = new Map>>(); private backgroundCredits = new Map(); + private balanced = new BalancedWillingnessPolicy(); + private balancedUpdatedAt = new Map(); + private readonly now: () => number; + private readonly random: () => number; private decayInterval: NodeJS.Timeout | null = null; - constructor(ctx: Context, config: Config, logging: LoggerService) { + constructor(ctx: Context, config: Config, logging: LoggerService, runtime?: { now?: () => number; random?: () => number }) { + this.now = runtime?.now ?? (() => Date.now()); + this.random = runtime?.random ?? (() => Math.random()); this.ctx = ctx; this.baseConfig = config; this.logger = logging.getLogger("[意愿管理器]"); @@ -84,6 +94,8 @@ export class WillingnessManager { ctx.on("dispose", () => { this.stopDecayCycle(); this.backgroundCredits.clear(); + this.balanced.clear(); + this.balancedUpdatedAt.clear(); }); } @@ -136,11 +148,15 @@ export class WillingnessManager { } private _decay(): void { - const now = Date.now(); + const now = this.now(); for (const chatId of this.willingnessScores.keys()) { const session = this.sessions.get(chatId); if (!session) continue; + if (this.baseConfig.willingnessPolicy?.algorithm === "balanced") { + this.decayBalanced(session, chatId, now); + continue; + } const config = this._getResolvedConfig(session); const { decayHalfLifeSeconds, probabilityThreshold } = config.lifecycle; @@ -235,7 +251,7 @@ export class WillingnessManager { if (!invited && !(context.isDirect && allowed("direct")) && !(sameParticipant && allowed("text"))) return 1; const duration = state.expiresAt! - state.lastReplyAt!; - const remainingRatio = Math.max(0, Math.min(1, (state.expiresAt! - Date.now()) / duration)); + const remainingRatio = Math.max(0, Math.min(1, (state.expiresAt! - this.now()) / duration)); const configuredInfluence = this.baseConfig.participation?.influence ?? 0.5; const influence = Number.isFinite(configuredInfluence) ? Math.max(0, Math.min(1, configuredInfluence)) : 0.5; return 1 + influence * remainingRatio; @@ -252,6 +268,7 @@ export class WillingnessManager { assessmentMultiplier = 1, capture?: (calculation: Omit) => void, ): number { + if (this.baseConfig.willingnessPolicy?.algorithm === "balanced") return this.calculateBalanced(session, context, assessmentMultiplier, capture); const { chatId } = context; const config = this._getResolvedConfig(session); const { lifecycle } = config; @@ -300,6 +317,90 @@ export class WillingnessManager { return probability; } + private decayBalanced(session: Session, key: string, now: number): { before: number; score: number; decay: number } { + const before = nonnegative(this.willingnessScores.get(key) ?? 0); + const halfLife = this._getResolvedConfig(session).lifecycle.decayHalfLifeSeconds; + const previous = this.balancedUpdatedAt.get(key) ?? now; + const factor = 0.5 ** (Math.max(0, now - previous) / (Math.max(1, nonnegative(halfLife)) * 1000)); + const score = before * factor; + this.willingnessScores.set(key, score); + this.balancedUpdatedAt.set(key, Math.max(previous, now)); + const credit = this.backgroundCredits.get(key); + if (credit !== undefined) this.backgroundCredits.set(key, Math.min(score, credit * factor)); + return { before, score, decay: before - score }; + } + + private calculateBalanced( + session: Session, + context: MessageContext, + assessmentMultiplier: number, + capture?: (calculation: Omit) => void, + ): number { + const policy = resolveWillingnessPolicy(this.baseConfig.willingnessPolicy); + const config = this._getResolvedConfig(session); + const allowed = (category: ReplyCategory) => !context.allowedCategories || context.allowedCategories.includes(category); + const self = session.selfId || session.bot?.selfId; + const atSelf = !!session.stripped?.atSelf || (!!self && !!session.elements?.some((e) => e.type === "at" && e.attrs.id === self)); + const quoteSelf = !!self && session.quote?.user?.id === self; + const invited = (atSelf && allowed("at")) || (quoteSelf && allowed("quote")) || (!!session.isDirect && allowed("direct")); + const addressesOthers = + !invited && + !session.isDirect && + ((allowed("at") && !!session.elements?.some((e) => e.type === "at" && !!e.attrs.id && e.attrs.id !== self)) || + (allowed("quote") && !!session.quote?.user?.id && session.quote.user.id !== self)); + const gains = { + text: allowed("text") ? nonnegative(config.base.text) : 0, + at: atSelf && allowed("at") ? nonnegative(config.attribute.atMention) : 0, + quote: quoteSelf && allowed("quote") ? nonnegative(config.attribute.isQuote) : 0, + direct: session.isDirect && allowed("direct") ? nonnegative(config.attribute.isDirectMessage) : 0, + }; + const baseScore = gains.text + gains.at + gains.quote + gains.direct; + const interestMultiplier = nonnegative( + config.interest.keywords.some((word) => word && context.content.includes(word)) + ? config.interest.keywordMultiplier + : config.interest.defaultMultiplier, + ); + const participationMultiplier = this.getParticipationMultiplier(session, context); + const requestedGain = baseScore * interestMultiplier * participationMultiplier * nonnegative(assessmentMultiplier); + const now = this.now(); + const decayed = this.decayBalanced(session, context.chatId, now); + const { maxWillingness, probabilityThreshold, probabilityAmplifier } = config.lifecycle; + const continuationGain = context.preview ? 0 : nonnegative(context.continuationGain ?? 0); + const result = this.balanced.update(context.participationId ?? context.chatId, policy, { + now, + score: decayed.score + continuationGain, + decay: decayed.decay + (context.priorDecay ?? 0), + max: nonnegative(maxWillingness), + requestedGain, + invited, + addressesOthers, + preview: context.preview, + deferWithdrawal: context.deferWithdrawal, + threshold: probabilityThreshold, + amplifier: probabilityAmplifier, + }); + this.willingnessScores.set(context.chatId, result.after); + capture?.({ + before: decayed.before + (context.priorDecay ?? 0), + after: result.after, + gains, + baseScore, + interestMultiplier, + participationMultiplier, + marginalMultiplier: 1, + dynamicMultiplier: 1, + assessmentMultiplier, + effectiveGain: result.trace.positiveGain - result.trace.negativeGain + continuationGain, + ...(continuationGain ? { continuationGain } : {}), + maxWillingness: nonnegative(maxWillingness), + threshold: probabilityThreshold, + amplifier: probabilityAmplifier, + probability: result.probability, + policy: result.trace, + }); + return result.probability; + } + /** * 回复前处理:扣除发言成本 * @param chatId 聊天ID @@ -321,6 +422,10 @@ export class WillingnessManager { const { replyCost, maxWillingness } = config.lifecycle; const resolvedReplyCost = session.resolve(replyCost); + if (this.baseConfig.willingnessPolicy?.algorithm === "balanced") { + this.decayBalanced(session, chatId, this.now()); + this.balanced.replied(participationId, resolveWillingnessPolicy(this.baseConfig.willingnessPolicy), this.now()); + } // 策略1:直接大幅降低意愿值 // 这种做法模拟了"我说完这个话题了" @@ -331,7 +436,7 @@ export class WillingnessManager { if (this.baseConfig.participation?.enabled) { const durationSeconds = this.baseConfig.participation.durationSeconds ?? 60; if (Number.isFinite(durationSeconds) && durationSeconds >= 1 && durationSeconds <= 86400) { - const now = Date.now(); + const now = this.now(); this.participation.set(participationId, { lastReplyAt: now, expiresAt: now + durationSeconds * 1000, @@ -362,6 +467,8 @@ export class WillingnessManager { this.sessions.delete(chatId); this.participation.delete(chatId); this.backgroundCredits.delete(chatId); + this.balancedUpdatedAt.delete(chatId); + this.balanced.reset(chatId); } public getCurrentWillingness(chatId: string): number { @@ -373,6 +480,7 @@ export class WillingnessManager { const { maxWillingness, probabilityThreshold, probabilityAmplifier } = this._getResolvedConfig(session).lifecycle; this.sessions.set(chatId, session); const gain = Number.isFinite(amount) && amount > 0 ? amount : 0; + if (this.baseConfig.willingnessPolicy?.algorithm === "balanced") this.decayBalanced(session, chatId, this.now()); const before = this.getCurrentWillingness(chatId); const score = Math.max(0, Math.min(maxWillingness, before + gain)); this.willingnessScores.set(chatId, score); @@ -384,7 +492,7 @@ export class WillingnessManager { } /** 返回参与状态的副本;到期查询不会清除或刷新状态。 */ - public getParticipation(chatId: string, now = Date.now()): ParticipationSnapshot { + public getParticipation(chatId: string, now = this.now()): ParticipationSnapshot { const state = this.participation.get(chatId); if (!state) return { active: false }; return { @@ -405,8 +513,14 @@ export class WillingnessManager { assessmentMultiplier = 1, topic?: TopicWillingnessInput, continuationGain = 0, - ): { decision: boolean; probability: number; roll: number; calculation: WillingnessCalculation; scoreKey?: string } { + ): { decision: boolean; probability: number; roll?: number; calculation: WillingnessCalculation; scoreKey?: string } { const currentScoreKey = topic?.currentScoreKey ?? chatId; + const priorDecay = new Map(); + if (this.baseConfig.willingnessPolicy?.algorithm === "balanced") { + const now = this.now(); + for (const key of new Set([chatId, currentScoreKey, ...(topic?.candidates.map((candidate) => candidate.scoreKey) ?? [])])) + if (this.willingnessScores.has(key)) priorDecay.set(key, this.decayBalanced(session, key, now).decay); + } const credit = this.backgroundCredits.get(chatId) ?? 0; this.backgroundCredits.delete(chatId); if (credit > 0 && currentScoreKey !== chatId) { @@ -419,12 +533,14 @@ export class WillingnessManager { this.sessions.set(currentScoreKey, session); // Only the message's own topic receives activity, not a different topic // selected later from accumulated willingness. - this.lastMessageTimestamps.set(currentScoreKey, Date.now()); + this.lastMessageTimestamps.set(currentScoreKey, this.now()); const context: MessageContext = { chatId: currentScoreKey, - participationId: topic ? chatId : undefined, continuationGain, + priorDecay: priorDecay.get(currentScoreKey), + deferWithdrawal: !!topic, + participationId: topic || this.baseConfig.willingnessPolicy?.algorithm === "balanced" ? chatId : undefined, allowedCategories, content: session.content ?? "", isMentioned: allowedCategories @@ -459,14 +575,44 @@ export class WillingnessManager { } if (scoreKey !== currentScoreKey) { this.sessions.set(scoreKey, session); - probability = this.calculateReplyProbability(session, { ...context, chatId: scoreKey, continuationGain: 0 }, 0, (value) => { - calculation = value; - }); + probability = this.calculateReplyProbability( + session, + { ...context, chatId: scoreKey, priorDecay: priorDecay.get(scoreKey), preview: true, continuationGain: 0 }, + 0, + (value) => { + calculation = value; + }, + ); } } - const roll = Math.random(); - const decision = roll < probability; + // Other-directed withdrawal follows the selected topic and consumes its shared budget once. + if (topic && calculation?.policy?.addressesOthers) { + probability = this.calculateReplyProbability( + session, + { ...context, chatId: scoreKey, priorDecay: priorDecay.get(scoreKey), deferWithdrawal: false, continuationGain: 0 }, + assessmentMultiplier * topic.multiplier, + (value) => { + calculation = value; + }, + ); + } + if (calculation?.policy) { + const allowed = this.balanced.opportunity( + chatId, + resolveWillingnessPolicy(this.baseConfig.willingnessPolicy), + probability, + calculation.policy.invited, + this.now(), + ); + if (!allowed) { + probability = 0; + calculation.policy.gate = "opportunity_interval"; + } + calculation.probability = probability; + } + const roll = calculation?.policy && probability <= 0 ? undefined : this.random(); + const decision = roll !== undefined && roll < probability; return { decision, probability, roll, calculation: { ...calculation, roll } as WillingnessCalculation, ...(topic ? { scoreKey } : {}) }; } diff --git a/packages/core/src/agent/willingness-policy.ts b/packages/core/src/agent/willingness-policy.ts new file mode 100644 index 000000000..04843ce22 --- /dev/null +++ b/packages/core/src/agent/willingness-policy.ts @@ -0,0 +1,157 @@ +export interface WillingnessPolicyConfig { + algorithm: "legacy" | "balanced"; + windowSeconds: number; + ordinaryGainLimit: number; + decisionIntervalSeconds: number; + othersPenalty: number; + negativeGainLimit: number; + replyPenalty: number; + replyPenaltyHalfLifeSeconds: number; +} + +export const DEFAULT_WILLINGNESS_POLICY: WillingnessPolicyConfig = { + algorithm: "legacy", + windowSeconds: 60, + ordinaryGainLimit: 24, + decisionIntervalSeconds: 10, + othersPenalty: 12, + negativeGainLimit: 24, + replyPenalty: 12, + replyPenaltyHalfLifeSeconds: 30, +}; + +export interface BalancedTrace { + version: "balanced-v1"; + invited: boolean; + addressesOthers: boolean; + preview: boolean; + decay: number; + requestedGain: number; + positiveGain: number; + negativeGain: number; + limitedGain: number; + ordinaryGainRemaining: number; + negativeGainRemaining: number; + fatiguePenalty: number; + rawProbability: number; + gate: "none" | "opportunity_interval" | "recent_reply_pressure"; +} +interface ChannelState { + ordinaryRemaining: number; + negativeRemaining: number; + budgetAt: number; + pressure: number; + pressureAt: number; + opportunityAt?: number; +} + +/** Invalid raw runtime values fall back to finite defaults; old configurations stay legacy. */ +export function resolveWillingnessPolicy(input?: Partial): WillingnessPolicyConfig { + const config = { ...DEFAULT_WILLINGNESS_POLICY }; + config.algorithm = input?.algorithm === "balanced" ? "balanced" : "legacy"; + for (const field of [ + "windowSeconds", + "ordinaryGainLimit", + "decisionIntervalSeconds", + "othersPenalty", + "negativeGainLimit", + "replyPenalty", + "replyPenaltyHalfLifeSeconds", + ] as const) { + const value = input?.[field]; + const minimum = field === "windowSeconds" || field === "replyPenaltyHalfLifeSeconds" ? 1 : 0; + if (typeof value === "number" && Number.isFinite(value) && value >= minimum) config[field] = Math.min(value, 1_000_000); + } + return config; +} +export const nonnegative = (value: number) => (Number.isFinite(value) ? Math.max(0, value) : 0); +export const linearProbability = (score: number, threshold: number, amplifier: number) => + Math.max(0, Math.min(1, (score - nonnegative(threshold)) * nonnegative(amplifier))); + +/** O(1) per message: separate replenishing budgets and a decaying successful-reply pressure. */ +export class BalancedWillingnessPolicy { + private channels = new Map(); + private channel(key: string, config: WillingnessPolicyConfig, now: number): ChannelState { + let state = this.channels.get(key); + if (!state) { + state = { ordinaryRemaining: config.ordinaryGainLimit, negativeRemaining: config.negativeGainLimit, budgetAt: now, pressure: 0, pressureAt: now }; + this.channels.set(key, state); + } + const elapsed = Math.max(0, now - state.budgetAt) / (config.windowSeconds * 1000); + state.ordinaryRemaining = Math.min(config.ordinaryGainLimit, state.ordinaryRemaining + elapsed * config.ordinaryGainLimit); + state.negativeRemaining = Math.min(config.negativeGainLimit, state.negativeRemaining + elapsed * config.negativeGainLimit); + state.budgetAt = Math.max(state.budgetAt, now); + state.pressure *= 0.5 ** (Math.max(0, now - state.pressureAt) / (config.replyPenaltyHalfLifeSeconds * 1000)); + state.pressureAt = Math.max(state.pressureAt, now); + return state; + } + public update( + key: string, + config: WillingnessPolicyConfig, + input: { + now: number; + score: number; + decay: number; + max: number; + requestedGain: number; + invited: boolean; + addressesOthers: boolean; + preview?: boolean; + deferWithdrawal?: boolean; + threshold: number; + amplifier: number; + }, + ) { + const state = this.channel(key, config, input.now); + const requestedGain = nonnegative(input.requestedGain); + let positiveGain = 0, + negativeGain = 0; + if (!input.preview) { + if (input.addressesOthers) { + negativeGain = input.deferWithdrawal ? 0 : Math.min(config.othersPenalty, state.negativeRemaining); + state.negativeRemaining -= negativeGain; + } else { + positiveGain = input.invited ? requestedGain : Math.min(requestedGain, state.ordinaryRemaining); + if (!input.invited) state.ordinaryRemaining -= positiveGain; + } + } + const after = Math.max(0, Math.min(input.max, input.score + positiveGain - negativeGain)); + const fatiguePenalty = input.invited ? 0 : Math.min(input.max, state.pressure * config.replyPenalty); + const rawProbability = linearProbability(after, input.threshold, input.amplifier); + const probability = linearProbability(Math.max(0, after - fatiguePenalty), input.threshold, input.amplifier); + const trace: BalancedTrace = { + version: "balanced-v1", + invited: input.invited, + addressesOthers: input.addressesOthers, + preview: !!input.preview, + decay: input.decay, + requestedGain, + positiveGain, + negativeGain, + limitedGain: input.preview || input.addressesOthers ? 0 : Math.max(0, requestedGain - positiveGain), + ordinaryGainRemaining: state.ordinaryRemaining, + negativeGainRemaining: state.negativeRemaining, + fatiguePenalty, + rawProbability, + gate: rawProbability > 0 && probability === 0 ? "recent_reply_pressure" : "none", + }; + return { after, probability, trace }; + } + public opportunity(key: string, config: WillingnessPolicyConfig, probability: number, invited: boolean, now: number): boolean { + if (invited || probability <= 0) return true; + const state = this.channel(key, config, now); + if (state.opportunityAt !== undefined && now - state.opportunityAt < config.decisionIntervalSeconds * 1000) return false; + state.opportunityAt = Math.max(state.opportunityAt ?? now, now); + return true; + } + public replied(key: string, config: WillingnessPolicyConfig, now: number) { + const state = this.channel(key, config, now); + state.pressure = Math.min(100, state.pressure + 1); + } + public reset(key: string) { + this.channels.delete(key); + } + public clear() { + this.channels.clear(); + } +} diff --git a/packages/core/tests/balanced-willingness.spec.ts b/packages/core/tests/balanced-willingness.spec.ts new file mode 100644 index 000000000..8a0009a49 --- /dev/null +++ b/packages/core/tests/balanced-willingness.spec.ts @@ -0,0 +1,202 @@ +import { afterEach, expect, it, vi } from "vitest"; + +import { AgentBehaviorConfigSchema } from "../src/agent/config"; +import { WillingnessManager } from "../src/agent/willing"; +import { DEFAULT_WILLINGNESS_POLICY, resolveWillingnessPolicy } from "../src/agent/willingness-policy"; +import { loggingStub, stubCtx } from "./helpers/yesimbot"; + +const START = 1_000_000; +const topic = (key: string) => ({ currentScoreKey: key, multiplier: 1, candidates: [{ scoreKey: key, share: 1 }] }); +afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); +}); +function fixture(algorithm: "legacy" | "balanced" | undefined = "balanced", overrides: Record = {}) { + vi.useFakeTimers(); + vi.setSystemTime(START); + const config: any = { + willingnessPolicy: { algorithm, ...overrides }, + base: { text: 12 }, + attribute: { atMention: 100, isQuote: 100, isDirectMessage: 100 }, + interest: { keywords: [], keywordMultiplier: 1.2, defaultMultiplier: 1 }, + lifecycle: { maxWillingness: 100, probabilityThreshold: 55, probabilityAmplifier: 0.04, decayHalfLifeSeconds: 600, replyCost: 35 }, + }; + const manager = new WillingnessManager(stubCtx({}, { on() {} }), config, loggingStub()); + const session: any = { + platform: "qq", + channelId: "room", + selfId: "bot", + bot: { selfId: "bot" }, + userId: "alice", + content: "hello", + elements: [], + stripped: {}, + isDirect: false, + resolve: (value: unknown) => value, + }; + return { config, manager, session }; +} +it("keeps the legacy algorithm as the default and explicit choice", () => { + expect(AgentBehaviorConfigSchema({}).willingnessPolicy?.algorithm).toBe("legacy"); + const old = fixture("legacy"), + explicit = fixture("legacy"); + delete old.config.willingnessPolicy; + for (let i = 0; i < 5; i++) { + vi.spyOn(Math, "random").mockReturnValue(0.99); + expect(old.manager.shouldReply(old.session, "room")).toEqual(explicit.manager.shouldReply(explicit.session, "room")); + } + expect(old.manager.getCurrentWillingness("room")).toBeCloseTo(76.7815, 4); +}); +it("caps fast ordinary-message gain instead of amplifying a busy group", () => { + const f = fixture(); + for (let i = 0; i < 100; i++) f.manager.shouldReply(f.session, "room"); + expect(f.manager.getCurrentWillingness("room")).toBe(24); +}); +it("lets clear invitations bypass the ordinary budget and opportunity interval", () => { + const f = fixture(); + for (let i = 0; i < 10; i++) f.manager.shouldReply(f.session, "room"); + const result = f.manager.shouldReply({ ...f.session, elements: [{ type: "at", attrs: { id: "bot" } }] }, "room"); + expect(result.probability).toBe(1); + expect(result.calculation.policy?.invited).toBe(true); +}); +it("withdraws bounded willingness from clearly other-directed messages", () => { + const f = fixture(); + f.manager.addBackgroundWillingness(f.session, "room", 80); + const result = f.manager.shouldReply({ ...f.session, elements: [{ type: "at", attrs: { id: "bob" } }] }, "room"); + expect(result.calculation.policy).toMatchObject({ addressesOthers: true, negativeGain: 12, positiveGain: 0 }); + expect(result.calculation.after).toBe(68); + for (let i = 0; i < 100; i++) f.manager.shouldReply({ ...f.session, quote: { user: { id: "bob" } } }, "room"); + expect(f.manager.getCurrentWillingness("room")).toBe(56); +}); +it("does not repeatedly draw during the ordinary opportunity interval", () => { + const f = fixture(); + f.manager.addBackgroundWillingness(f.session, "room", 80); + const random = vi.spyOn(Math, "random").mockReturnValue(0.99); + const first = f.manager.shouldReply(f.session, "room"); + const next = f.manager.shouldReply(f.session, "room"); + expect(first.roll).toBe(0.99); + expect(next.probability).toBe(0); + expect(next.roll).toBeUndefined(); + expect(next.calculation.policy?.gate).toBe("opportunity_interval"); + expect(random).toHaveBeenCalledTimes(1); +}); +it("uses elapsed-time decay without heat or high-score slowdown", () => { + const f = fixture(); + f.manager.addBackgroundWillingness(f.session, "room", 80); + vi.setSystemTime(START + 600_000); + const result = f.manager.shouldReply(f.session, "room", undefined, 0); + expect(result.calculation).toMatchObject({ before: 80, after: 40 }); + expect(result.calculation.policy?.decay).toBe(40); +}); +it("temporarily reduces ordinary probability after a successful reply but preserves invitations", () => { + const f = fixture("balanced", { ordinaryGainLimit: 0 }); + f.config.lifecycle.replyCost = 0; + f.manager.addBackgroundWillingness(f.session, "room", 80); + f.manager.handlePostReply(f.session, "room"); + const result = f.manager.shouldReply(f.session, "room"); + expect(result.calculation.policy?.fatiguePenalty).toBe(12); + expect(result.probability).toBeCloseTo(0.52); + expect(f.manager.shouldReply({ ...f.session, isDirect: true }, "room").probability).toBe(1); +}); +it("replenishes ordinary and negative budgets gradually and resets them explicitly", () => { + const f = fixture(); + f.manager.shouldReply(f.session, "room"); + f.manager.shouldReply(f.session, "room"); + vi.setSystemTime(START + 30_000); + expect(f.manager.shouldReply(f.session, "room").calculation.policy?.positiveGain).toBe(12); + const other = { ...f.session, quote: { user: { id: "bob" } } }; + f.manager.shouldReply(other, "room"); + f.manager.shouldReply(other, "room"); + expect(f.manager.shouldReply(other, "room").calculation.policy?.negativeGain).toBe(0); + vi.setSystemTime(START + 60_000); + expect(f.manager.shouldReply(other, "room").calculation.policy?.negativeGain).toBe(12); + f.manager.reset("room"); + expect(f.manager.shouldReply(f.session, "room").calculation.after).toBe(12); +}); +it("shares the ordinary budget across topics and transfers background credit once", () => { + const f = fixture(); + f.manager.addBackgroundWillingness(f.session, "room", 50); + expect(f.manager.shouldReply(f.session, "room", undefined, 1, topic("a")).calculation.after).toBe(62); + expect(f.manager.getCurrentWillingness("room")).toBe(0); + expect(f.manager.shouldReply(f.session, "room", undefined, 1, topic("b")).calculation.after).toBe(12); + expect(f.manager.shouldReply(f.session, "room", undefined, 1, topic("c")).calculation.after).toBe(0); + expect(f.manager.shouldReply(f.session, "another-room").calculation.after).toBe(12); +}); +it("does not treat disabled mention categories or unknown recipients as invitations", () => { + const f = fixture("balanced", { ordinaryGainLimit: 0 }); + const at = { ...f.session, elements: [{ type: "at", attrs: { id: "bot" } }] }; + expect(f.manager.shouldReply(at, "room", ["text"]).calculation.policy?.invited).toBe(false); + expect(f.manager.shouldReply({ ...f.session, quote: {} }, "room").calculation.policy).toMatchObject({ invited: false, negativeGain: 0 }); + expect(f.manager.shouldReply({ ...f.session, quote: { user: { id: "bot" } } }, "room").calculation.policy?.invited).toBe(true); +}); +it("reopens ordinary opportunities after the configured interval", () => { + const f = fixture("balanced", { ordinaryGainLimit: 0 }); + f.manager.addBackgroundWillingness(f.session, "room", 80); + f.manager.shouldReply(f.session, "room"); + vi.setSystemTime(START + 9999); + expect(f.manager.shouldReply(f.session, "room").roll).toBeUndefined(); + vi.setSystemTime(START + 10000); + expect(f.manager.shouldReply(f.session, "room").roll).toEqual(expect.any(Number)); +}); +it("decays the same amount with a running timer and lazy evaluation", () => { + const lazy = fixture(), + timed = fixture(); + for (const f of [lazy, timed]) f.manager.addBackgroundWillingness(f.session, "room", 80); + timed.manager.startDecayCycle(); + vi.advanceTimersByTime(600_000); + const a = lazy.manager.shouldReply(lazy.session, "room", undefined, 0); + const b = timed.manager.shouldReply(timed.session, "room", undefined, 0); + timed.manager.stopDecayCycle(); + expect(a.calculation.after).toBeCloseTo(40); + expect(b.calculation.after).toBeCloseTo(a.calculation.after); +}); +it("replays the same busy-group messages against both algorithms without assuming reply quality", () => { + const legacy = fixture("legacy"), + balanced = fixture(); + const counts = { legacy: 0, balanced: 0 }; + vi.spyOn(Math, "random").mockReturnValue(0.5); + for (let i = 0; i < 100; i++) { + if (legacy.manager.shouldReply(legacy.session, "room").decision) counts.legacy++; + if (balanced.manager.shouldReply(balanced.session, "room").decision) counts.balanced++; + } + expect(counts).toEqual({ legacy: 96, balanced: 0 }); + expect(balanced.manager.shouldReply({ ...balanced.session, isDirect: true }, "room").decision).toBe(true); +}); +it("withdraws from the selected topic once when the message addresses somebody else", () => { + const f = fixture("balanced", { ordinaryGainLimit: 0 }); + f.manager.addBackgroundWillingness(f.session, "a", 80); + const result = f.manager.shouldReply({ ...f.session, quote: { user: { id: "bob" } } }, "room", undefined, 1, { + currentScoreKey: "b", + multiplier: 1, + candidates: [ + { scoreKey: "a", share: 0.8 }, + { scoreKey: "b", share: 0.2 }, + ], + }); + expect(result.scoreKey).toBe("a"); + expect(result.calculation.after).toBe(68); + expect(result.calculation.policy).toMatchObject({ negativeGain: 12, negativeGainRemaining: 12 }); + expect(result.probability).toBeCloseTo(0.52); +}); + +it("normalizes invalid raw policy values and prevents clock rollback from refilling budgets", () => { + expect(resolveWillingnessPolicy({ windowSeconds: NaN, ordinaryGainLimit: Infinity, replyPenalty: -1 })).toEqual(DEFAULT_WILLINGNESS_POLICY); + const f = fixture(); + f.manager.shouldReply(f.session, "room"); + f.manager.shouldReply(f.session, "room"); + vi.setSystemTime(START - 10000); + const result = f.manager.shouldReply(f.session, "room"); + expect(result.calculation.after).toBe(24); + expect(result.calculation.policy?.positiveGain).toBe(0); + expect(result.calculation.policy?.decay).toBe(0); +}); +it("keeps configured continuation gain separate from ordinary quotas without duplicate topic credit", () => { + const f = fixture("balanced", { ordinaryGainLimit: 0 }); + const first = f.manager.shouldReply(f.session, "room", undefined, 1, undefined, 35); + expect(first.calculation).toMatchObject({ after: 35, effectiveGain: 35, continuationGain: 35 }); + f.manager.reset("room"); + const other = { ...f.session, quote: { user: { id: "bob" } } }; + const result = f.manager.shouldReply(other, "room", undefined, 1, topic("a"), 35); + expect(result.calculation.after).toBe(23); + expect(f.manager.getCurrentWillingness("a")).toBe(23); +}); diff --git a/packages/core/tests/decision-journal.spec.ts b/packages/core/tests/decision-journal.spec.ts index 427017aa4..752677f77 100644 --- a/packages/core/tests/decision-journal.spec.ts +++ b/packages/core/tests/decision-journal.spec.ts @@ -305,3 +305,54 @@ describe("exclusion", () => { expect((await restored.list()).map((entry) => entry.id)).toStrictEqual(["before-crash"]); }); }); + +it("retains only approved balanced trace fields across persistence", async (t) => { + const dir = await temporary(t); + const journal = new DecisionJournal(dir, journalOptions); + t.onTestFinished(() => journal.close()); + await journal.append( + record("balanced", { + decision: false, + calculation: { + before: 80, + after: 68, + baseScore: 12, + interestMultiplier: 1, + marginalMultiplier: 1, + dynamicMultiplier: 1, + assessmentMultiplier: 1, + participationMultiplier: 1, + effectiveGain: -12, + maxWillingness: 100, + threshold: 55, + amplifier: 0.04, + probability: 0, + policy: { + version: "balanced-v1", + invited: false, + addressesOthers: true, + preview: false, + decay: 0, + positiveGain: 0, + negativeGain: 12, + fatiguePenalty: 0, + requestedGain: 12, + limitedGain: 0, + ordinaryGainRemaining: 24, + negativeGainRemaining: 12, + rawProbability: 0.52, + gate: "opportunity_interval", + content: "private text", + }, + }, + }), + ); + await journal.close(); + const log = warnings(); + const restored = new DecisionJournal(dir, journalOptions, log.warn); + t.onTestFinished(() => restored.close()); + const trace = (await restored.list({}))[0].calculation?.policy; + expect(trace).toMatchObject({ version: "balanced-v1", negativeGain: 12, gate: "opportunity_interval" }); + expect(trace).not.toHaveProperty("content"); + expect(log.collected).toEqual([]); +}); diff --git a/packages/core/tests/decision-replay-cli.spec.ts b/packages/core/tests/decision-replay-cli.spec.ts index 710dd978c..33705093b 100644 --- a/packages/core/tests/decision-replay-cli.spec.ts +++ b/packages/core/tests/decision-replay-cli.spec.ts @@ -172,3 +172,76 @@ describe("offline replay", () => { expect(event.recomputed.probability).toBe(precise.probability); }); }); + +it("replays balanced decay, penalties and gated records without a random draw", async (t) => { + const dir = await temporary(t), + filename = path.join(dir, "balanced.jsonl"); + const policy = { version: "balanced-v1", decay: 10, requestedGain: 12, positiveGain: 2, negativeGain: 0, fatiguePenalty: 5, gate: "none" }; + const balanced = { ...calculation, before: 80, after: 72, effectiveGain: 2, threshold: 55, amplifier: 0.04, probability: 0.48, policy }; + await writeLog(filename, [ + record("balanced", { calculation: balanced }), + record("gated", { + decision: false, + calculation: { ...balanced, probability: 0, roll: undefined, policy: { ...policy, gate: "opportunity_interval" } }, + }), + ]); + const result = replay(filename); + assertCleanExit(result); + const lines = parseJsonl(result.stdout); + expect(lines.filter((line) => line.status === "replayed").map((line) => line.matches)).toEqual([true, true]); + expect(lines.at(-1)!.summary.mismatches).toBe(0); +}); + +it("deduplicates balanced gated snapshots and leaves positive scenarios without a roll undecided", async (t) => { + const dir = await temporary(t), + filename = path.join(dir, "gated.jsonl"); + const balanced = { + ...calculation, + before: 50, + after: 50, + effectiveGain: 0, + threshold: 55, + amplifier: 0.04, + probability: 0, + roll: undefined, + policy: { version: "balanced-v1", decay: 0, requestedGain: 12, positiveGain: 0, negativeGain: 0, fatiguePenalty: 0, gate: "none" }, + }; + await writeLog(filename, [ + record("same", { stage: "completed", decision: false, calculation: balanced }), + record("same", { stage: "calculated", decision: false, calculation: balanced }), + ]); + const result = replay(filename, ["--threshold", "10"]); + assertCleanExit(result); + const lines = parseJsonl(result.stdout); + expect(lines.at(-1)!.summary).toMatchObject({ replayed: 1, duplicateCalculations: 1, mismatches: 0 }); + const event = lines.find((line) => line.status === "replayed")!; + expect(event.scenario.probability).toBe(1); + expect(event.scenario).not.toHaveProperty("decision"); +}); +it("replays explicit continuation bonuses with either algorithm", async (t) => { + const dir = await temporary(t), + filename = path.join(dir, "continuation.jsonl"); + await writeLog(filename, [ + record("legacy-bonus", { calculation: { ...calculation, continuationGain: 5, effectiveGain: 17, after: 27, probability: 0.7 } }), + record("balanced-bonus", { + calculation: { + ...calculation, + before: 80, + after: 77, + effectiveGain: 7, + continuationGain: 5, + threshold: 55, + amplifier: 0.04, + probability: 0.68, + policy: { version: "balanced-v1", decay: 10, requestedGain: 12, positiveGain: 2, negativeGain: 0, fatiguePenalty: 5, gate: "none" }, + }, + }), + ]); + const result = replay(filename); + assertCleanExit(result); + expect( + parseJsonl(result.stdout) + .filter((line) => line.status === "replayed") + .map((line) => line.matches), + ).toEqual([true, true]); +}); From 1acf3fd8fef05f5d1b88c2c5436b22b0ef5da33a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=AE=B8=E4=BB=99xhcz?= Date: Tue, 27 Oct 2026 11:13:42 +0800 Subject: [PATCH 3/6] fix(core): preserve topic willingness across fallback paths --- docs/balanced-willingness.md | 6 ++ packages/core/src/agent/agent-core.ts | 56 ++++++++++++----- packages/core/src/agent/decision-journal.ts | 1 + packages/core/src/agent/decision-record.ts | 2 + packages/core/tests/decision-core.spec.ts | 65 ++++++++++++++++++++ packages/core/tests/decision-journal.spec.ts | 10 +++ 6 files changed, 126 insertions(+), 14 deletions(-) diff --git a/docs/balanced-willingness.md b/docs/balanced-willingness.md index 9c35df8a4..658dccf49 100644 --- a/docs/balanced-willingness.md +++ b/docs/balanced-willingness.md @@ -40,3 +40,9 @@ willingnessPolicy: `chat.decision` 会显示平衡算法的时间衰减、增加、减少、额度限制和短期压力。启用决策记录后,离线回放能使用 `balanced-v1` 数值轨迹复算单条判定,间隔节流的记录允许没有随机数,且不会重新抽取。 这些记录能解释算法怎样算出结果,不能证明发言是否合适。新旧算法的忙群合成回放用于验证边界行为;真实效果仍应结合群聊中的实际反馈评估。单条快照回放不会重建完整会话,也不能推断换算法后群成员会怎样回应。 + +## 话题计分的连续性 + +启用话题意愿时,明确 @、临时话题评估失败以及会话续接会沿用当前保留焦点的意愿分数;没有焦点时使用仍保留的首个话题,没有可用话题时使用普通会话分数。回退只复用一个话题的计分归属,不合并不同话题分数,也不应用旧话题的兴趣倍率。这个计分归属不会作为新的话题判断注入续接上下文。成功回复后从同一份分数扣除回复成本。 + +这些连续性规则同样适用于原有算法。话题删除、到期及暂停、禁言导致的状态清理继续生效。计算日志与 `chat.decision` 会显示实际计分键;清理日志包含原因及清理前分数,便于区别换池、扣分和重置。 diff --git a/packages/core/src/agent/agent-core.ts b/packages/core/src/agent/agent-core.ts index bffaa33c6..0ca44f25d 100644 --- a/packages/core/src/agent/agent-core.ts +++ b/packages/core/src/agent/agent-core.ts @@ -27,7 +27,13 @@ import { TopicManager, TopicSnapshot } from "./topics"; import { TypeSafeEvaluator } from "./typesafe"; import { WillingnessManager } from "./willing"; -type TracedStimulus = AgentStimulus & { decisionId?: string; topic?: TopicSnapshot; continuation?: ContinuationMatch; continuationRequired?: boolean }; +type TracedStimulus = AgentStimulus & { + decisionId?: string; + topic?: TopicSnapshot; + scoringTopic?: TopicSnapshot; + continuation?: ContinuationMatch; + continuationRequired?: boolean; +}; declare module "koishi" { interface Tables { @@ -282,7 +288,7 @@ export class AgentCore extends YesImBotService { this.cancelAssessment(key, false); this.activeTurns.get(key)?.abort(new Error("聊天任务已取消")); this.decisions.update(this.activeDecisionIds.get(key), { stage: "cancelled", reason, success: false }); - this.resetWillingness(key); + this.resetWillingness(key, reason); this.scheduler?.cancel(key); }, async (target, reason, rule, actor) => { @@ -377,7 +383,7 @@ export class AgentCore extends YesImBotService { this.activeDecisionIds.delete(channelCid); } - const replyTopic = (stimulus as TracedStimulus).topic; + const replyTopic = (stimulus as TracedStimulus).scoringTopic ?? (stimulus as TracedStimulus).topic; if (success && valid() && (!replyTopic || this.topicScores.get(channelCid)?.has(replyTopic.scoreKey))) { const scoreKey = replyTopic?.scoreKey ?? channelCid; const willingnessBeforeReply = this.willing.getCurrentWillingness(scoreKey); @@ -385,14 +391,16 @@ 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, { stage: completed ? "completed" : "cancelled", reason: !completed ? "invalid_generation" : success ? undefined : "no_reply", success: success && completed, - score: this.willing.getCurrentWillingness((stimulus as TracedStimulus).topic?.scoreKey ?? channelCid), + score: this.willing.getCurrentWillingness( + (stimulus as TracedStimulus).scoringTopic?.scoreKey ?? (stimulus as TracedStimulus).topic?.scoreKey ?? channelCid, + ), participation: this.willing.getParticipation(channelCid), }); }, @@ -405,7 +413,7 @@ export class AgentCore extends YesImBotService { this.cancelAssessment(key, false, "muted"); this.activeTurns.get(key)?.abort(new Error("机器人已被禁言")); this.decisions.update(this.activeDecisionIds.get(key), { stage: "cancelled", reason: "muted", success: false }); - this.resetWillingness(key); + this.resetWillingness(key, "muted"); this.scheduler.cancel(key, "muted"); }); } @@ -536,9 +544,14 @@ export class AgentCore extends YesImBotService { if (type === "user_message") { try { - const topic = (stimulus as TracedStimulus).topic; - const candidates = topic ? (this.topics?.getTopics(channelCid) ?? []) : []; - if (topic) this.trackTopicScores(channelCid, candidates); + const inputTopic = stimulus.topic; + const retained = this.config.topics?.enabled ? (this.topics?.getTopics(channelCid) ?? []) : []; + const focusId = retained.length ? this.topics?.getFocus(channelCid)?.id : undefined; + const fallback = retained.find((item) => item.id === focusId) ?? retained[0]; + // Retain score ownership without injecting a stale inferred topic into source-anchored context. + const topic = inputTopic ?? (fallback ? { ...fallback, multiplier: 1 } : undefined); + const candidates = inputTopic ? retained : topic ? [topic] : []; + if (topic) this.trackTopicScores(channelCid, retained); const willingnessBefore = this.willing.getCurrentWillingness(topic?.scoreKey ?? channelCid); const replyRule = this.replyControl.get(this.replyTarget(session)); const categories = replyRule ? allowed : undefined; @@ -564,7 +577,7 @@ export class AgentCore extends YesImBotService { const focus = candidates.find((candidate) => candidate.scoreKey === scoreKey); if (focus) { this.topics?.chooseFocus(channelCid, focus.id); - stimulus = { ...stimulus, topic: focus } as TracedStimulus; + stimulus = { ...stimulus, scoringTopic: focus, ...(inputTopic ? { topic: focus } : {}) } as TracedStimulus; } } const forcedMention = this.config.prioritizeMentions && !replyRule && isBotMention(session) && allowed.includes("at"); @@ -581,6 +594,7 @@ export class AgentCore extends YesImBotService { roll: result.roll, calculation: result.calculation, score: willingnessAfter, + scoreKey, participation: this.willing.getParticipation?.(channelCid), reason: forcedMention ? "forced_reply_by_mention" @@ -598,7 +612,7 @@ export class AgentCore extends YesImBotService { ); } /* prettier-ignore */ - this.logger.debug(`[${channelCid}] 意愿计算: ${(result.calculation?.before ?? willingnessBefore).toFixed(2)} -> ${willingnessAfter.toFixed(2)} | 回复概率: ${(result.probability * 100).toFixed(1)}% | 初步决策: ${decision} | 处理: ${!allowSchedule ? "仅结算,不调度" : decision ? "准备提交调度" : "未达到回复条件"} | 消息ID: ${session.messageId ?? "未知"}`); + this.logger.debug(`[${channelCid}] 意愿计算 | 计分键: ${scoreKey} | ${(result.calculation?.before ?? willingnessBefore).toFixed(2)} -> ${willingnessAfter.toFixed(2)} | 回复概率: ${(result.probability * 100).toFixed(1)}% | 初步决策: ${decision} | 处理: ${!allowSchedule ? "仅结算,不调度" : decision ? "准备提交调度" : "未达到回复条件"} | 消息ID: ${session.messageId ?? "未知"}`); } catch (error) { this.recordDecision(stimulus, { stage: "failed", reason: "exception" }); handleError( @@ -653,11 +667,19 @@ export class AgentCore extends YesImBotService { } private clearTopicScores(channelKey: string): void { - for (const key of this.topicScores.get(channelKey) ?? []) this.willing.reset(key); + for (const key of this.topicScores.get(channelKey) ?? []) { + this.logger.debug( + `[${channelKey}] 清除话题意愿 | 计分键: ${key} | 原因: 话题重置或到期 | 清除前: ${this.willing.getCurrentWillingness(key).toFixed(2)}`, + ); + this.willing.reset(key); + } this.topicScores.delete(channelKey); } - private resetWillingness(channelKey: string): void { + private resetWillingness(channelKey: string, reason = "reset"): void { + this.logger.debug( + `[${channelKey}] 清除意愿状态 | 原因: ${reason} | 普通意愿: ${this.willing.getCurrentWillingness(channelKey).toFixed(2)} | 话题数: ${this.topicScores.get(channelKey)?.size ?? 0}`, + ); this.continuationEpochs?.delete(channelKey); this.topics?.reset(channelKey); this.clearTopicScores(channelKey); @@ -666,7 +688,13 @@ export class AgentCore extends YesImBotService { private trackTopicScores(channelKey: string, snapshots: TopicSnapshot[]): void { const keys = new Set(snapshots.map((topic) => topic.scoreKey)); - for (const old of this.topicScores.get(channelKey) ?? []) if (!keys.has(old)) this.willing.reset(old); + for (const old of this.topicScores.get(channelKey) ?? []) + if (!keys.has(old)) { + this.logger.debug( + `[${channelKey}] 清除话题意愿 | 计分键: ${old} | 原因: 话题移出候选 | 清除前: ${this.willing.getCurrentWillingness(old).toFixed(2)}`, + ); + this.willing.reset(old); + } this.topicScores.set(channelKey, keys); } diff --git a/packages/core/src/agent/decision-journal.ts b/packages/core/src/agent/decision-journal.ts index 54cc6dc10..307a32e71 100644 --- a/packages/core/src/agent/decision-journal.ts +++ b/packages/core/src/agent/decision-journal.ts @@ -105,6 +105,7 @@ export function sanitizeDecisionRecord(value: unknown): DecisionRecord | undefin stimulusType: stimuli.has(value.stimulusType) ? value.stimulusType : "unknown", startedAt: finite(value.startedAt) ? value.startedAt : value.time, }; + if (identifier(value.scoreKey)) result.scoreKey = value.scoreKey; if (identifier(value.messageId)) result.messageId = value.messageId; if (typeof value.reason === "string" && reasons.has(value.reason)) result.reason = value.reason; for (const field of ["decision", "success", "forcedReply"] as const) if (typeof value[field] === "boolean") result[field] = value[field]; diff --git a/packages/core/src/agent/decision-record.ts b/packages/core/src/agent/decision-record.ts index fe1e64b05..3ce5da289 100644 --- a/packages/core/src/agent/decision-record.ts +++ b/packages/core/src/agent/decision-record.ts @@ -24,6 +24,7 @@ export interface WillingnessCalculation { } export interface DecisionRecord { + scoreKey?: string; version: 1; id: string; messageId?: string; @@ -173,6 +174,7 @@ export function formatDecision(record: DecisionRecord | undefined, state: Decisi `状态:${stages[record.stage] || record.stage}${record.reason ? `;原因:${reasons[record.reason] || record.reason}` : ""}`, ); if (record.messageId) lines.push(`来源消息:${record.messageId}`); + if (record.scoreKey) lines.push(`计分键:${record.scoreKey}`); const c = record.calculation; if (c) { if (c.gains) lines.push(`增益来源:文本 ${c.gains.text};@ ${c.gains.at};引用 ${c.gains.quote};私聊 ${c.gains.direct}`); diff --git a/packages/core/tests/decision-core.spec.ts b/packages/core/tests/decision-core.spec.ts index 80657cd37..a9f4f9762 100644 --- a/packages/core/tests/decision-core.spec.ts +++ b/packages/core/tests/decision-core.spec.ts @@ -272,3 +272,68 @@ it("does not revive a read admitted before a mute and immediate unmute", async ( expect(t.scheduled).toHaveLength(0); expect(t.decisions.latest(t.target)?.stage).toBe("cancelled"); }); + +it.each(["legacy", "balanced"])("retains topic willingness across mentions and failed assessment in %s", async (algorithm) => { + const t = setup(); + t.core.config.willingnessPolicy = { algorithm }; + t.core.willing.now = () => 1000000; + t.core.config.topics = { enabled: true, model: { providerName: "test", modelId: "test" } }; + const topic = { id: "a", label: "A", scoreKey: "topic-A", share: 1, interest: 0.5, multiplier: 1 }; + t.core.topics = { + noteMessage() {}, + getCurrent: () => undefined, + getTopics: () => [topic], + getFocus: () => topic, + chooseFocus: () => topic, + assess: async () => undefined, + }; + t.core.willing.addBackgroundWillingness(t.session, topic.scoreKey, 80); + t.core.willing.handlePostReply(t.session, topic.scoreKey); + t.core.receiveStimulus({ type: "user_message", session: t.session }); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(t.decisions.latest(t.target)?.calculation?.before).toBe(45); + const remaining = t.core.willing.getCurrentWillingness(topic.scoreKey); + t.session.elements = [{ type: "at", attrs: { id: "bot" } }]; + t.session.stripped = { atSelf: true }; + t.core.receiveStimulus({ type: "user_message", session: t.session }); + expect(t.decisions.latest(t.target)?.calculation?.before).toBe(remaining); + expect(t.scheduled.at(-1).scoringTopic.scoreKey).toBe(topic.scoreKey); + expect(t.decisions.latest(t.target)?.scoreKey).toBe(topic.scoreKey); +}); +it("keeps continuation source context separate while retaining topic score", async () => { + const t = continuationSetup("willingness"); + t.core.config.lifecycle.probabilityThreshold = 10; + t.core.config.topics = { enabled: true, model: { providerName: "test", modelId: "test" } }; + const topic = { id: "a", label: "A", scoreKey: "topic-A", share: 1, interest: 0.5, multiplier: 1 }; + t.core.topics = { + noteMessage() {}, + getCurrent: () => topic, + getTopics: () => [topic], + getFocus: () => topic, + chooseFocus: () => topic, + assess: async () => topic, + }; + t.core.willing.addBackgroundWillingness(t.session, topic.scoreKey, 45); + t.core.receiveStimulus({ type: "user_message", session: t.session }); + await nextTick(); + expect(t.decisions.latest(t.target)?.calculation?.before).toBe(45); + expect(t.scheduled[0].topic).toBeUndefined(); + expect(t.scheduled[0].scoringTopic.scoreKey).toBe(topic.scoreKey); +}); +it("fallback preserves unrelated topic scores and disabled topics use the ordinary pool", () => { + const t = setup(); + t.core.config.topics = { enabled: true, model: { providerName: "test", modelId: "test" } }; + const topics = ["a", "b"].map((id) => ({ id, label: id, scoreKey: "topic-" + id, share: 0.5, interest: 0.5, multiplier: 1 })); + t.core.topics = { noteMessage() {}, getCurrent: () => undefined, getTopics: () => topics, getFocus: () => topics[0], chooseFocus() {} }; + const key = JSON.stringify(["qq", "bot", "g"]); + t.core.topicScores.set(key, new Set(topics.map((topic) => topic.scoreKey))); + for (const topic of topics) t.core.willing.addBackgroundWillingness(t.session, topic.scoreKey, 45); + t.session.stripped = { atSelf: true }; + t.core.receiveStimulus({ type: "user_message", session: t.session }); + expect(t.core.willing.getCurrentWillingness("topic-b")).toBe(45); + expect(t.decisions.latest(t.target)?.scoreKey).toBe("topic-a"); + t.core.config.topics.enabled = false; + t.core.receiveStimulus({ type: "user_message", session: t.session }); + expect(t.decisions.latest(t.target)?.scoreKey).toBe(key); + expect(t.decisions.latest(t.target)?.calculation?.before).toBe(0); +}); diff --git a/packages/core/tests/decision-journal.spec.ts b/packages/core/tests/decision-journal.spec.ts index 752677f77..8f092eaa6 100644 --- a/packages/core/tests/decision-journal.spec.ts +++ b/packages/core/tests/decision-journal.spec.ts @@ -356,3 +356,13 @@ it("retains only approved balanced trace fields across persistence", async (t) = expect(trace).not.toHaveProperty("content"); expect(log.collected).toEqual([]); }); +it("persists the actual score key independently of the conversation key", async (t) => { + const dir = await temporary(t); + const journal = new DecisionJournal(dir, journalOptions); + t.onTestFinished(() => journal.close()); + await journal.append(record("score-scope", { scoreKey: '["channel","topic","a"]' })); + await journal.close(); + const restored = new DecisionJournal(dir, journalOptions); + t.onTestFinished(() => restored.close()); + expect((await restored.list({}))[0].scoreKey).toBe('["channel","topic","a"]'); +}); From 841cbc4f1d9b2d66e0fcea16efb49ac8accb1c9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=AE=B8=E4=BB=99xhcz?= Date: Tue, 27 Oct 2026 15:49:57 +0800 Subject: [PATCH 4/6] =?UTF-8?q?feat(v3-dev):=20=E6=95=B4=E7=90=86=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E5=88=86=E7=BB=84=E5=B9=B6=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?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../config-and-error-standardization.md | 210 ++++++++++++++++++ packages/core/client/index.ts | 8 +- packages/core/client/section.css | 14 ++ packages/core/src/config/config.ts | 108 +++++++-- packages/core/src/extension/service.ts | 8 +- packages/core/src/extension/types.ts | 6 + packages/core/src/model/config.ts | 4 +- .../core/src/shared/errors/definitions.ts | 48 ++++ packages/core/src/shared/errors/index.ts | 104 +++++++-- packages/core/tests/config-navigation.spec.ts | 149 +++++++++++++ packages/core/tests/config-section.spec.ts | 38 ++++ .../core/tests/context-capacity-input.spec.ts | 12 + .../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 +++++ 16 files changed, 814 insertions(+), 58 deletions(-) create mode 100644 docs/design/config-and-error-standardization.md create mode 100644 packages/core/tests/config-navigation.spec.ts create mode 100644 packages/core/tests/config-section.spec.ts create mode 100644 packages/core/tests/tool-error-normalization.spec.ts diff --git a/docs/design/config-and-error-standardization.md b/docs/design/config-and-error-standardization.md new file mode 100644 index 000000000..76ec5a917 --- /dev/null +++ b/docs/design/config-and-error-standardization.md @@ -0,0 +1,210 @@ +# 配置组织与错误接口规范化设计草案 + +状态:首批核心配置导航及公共错误边界已实现;附加插件配置重排和其他错误抛出点的逐模块迁移仍属后续范围。重复标题局部修复已单独验证。 + +## 基线及限制 + +盘点基于 0038a9c,包含会话续接、群聊平衡算法及意愿连续性修复。模型提供商原生协议仍有独立的 #255 改动;实施模型配置整理前须结合其最终合入结果重新核对,不能覆盖或退回旧提供商配置。 + +本期设计不改变模型选择、回复策略、记忆作用域或默认启用状态。优先调整 Schema 的展示组合,不迁移配置字段。附加插件保留独立 Koishi 配置页和加载边界,通过一致的分类与文案形成统一体验,不要求所有插件配置复制进核心。 + +## 已核对的标题问题 + +`model/config.ts` 中 contextLimit 为带 description 的折叠 intersect。当前安装的 schemastery-vue 的 intersect 渲染器会在未设置 extra.foldable 时将父 meta 合并到内部块;内部 object 在 foldable=false 时将继承的 description 渲染成 h2。 + +局部修复在两个可见内部块上显式设置空 description,只阻止标题继承;外层说明、模式字段说明、数值/单位表格及隐藏校验继续存在。未修改 Vue 渲染器、配置路径、数据格式及容量解析。 + +## 配置归属与覆盖关系 + +下表是建议归属,尚不是已完成的移动清单。实际 Schema 合并前须确认每个字段只出现一次。 + +| 功能与现有路径 | 当前位置/关联项 | 建议主要入口 | 保留的行为关系 | +| ---------------------------------------------------------------------- | -------------------- | ---------------------------------- | --------------------------------------------------------------------------------------------------- | +| providers / modelGroups / task | 模型服务 | 模型连接与任务分配 | 提供商定义模型;模型组选择模型;任务选择组,不能合并成一个开关 | +| providers[].models[].contextLimit | 单模型配置 | 模型配置内的容量 | 表达模型硬容量,保留 unset/custom/auto | +| contextInputBudgetTokens | 执行策略 | 上下文与记忆 → 输入预算 | 软裁剪预算;0 关闭软裁剪,不关闭硬容量检查 | +| l1_memory / l2_memory / l3_memory | 历史与上下文 | 上下文与记忆 → 分层记忆 | 层级保留职责,不以一个“记忆开关”替代 | +| 核心记忆文件与人格模板 | 核心记忆、提示词区域 | 人格与提示词 | 文件长期提示与运行时检索不是同一功能 | +| 唤醒条件、base / attribute / interest / lifecycle | 唤醒条件、响应意愿 | 回复触发与参与 | 允许进入与概率判定分别说明,不能合并权限与意愿 | +| willingnessPolicy / topics / participation / typesafe / continuation | 响应意愿 | 回复触发与参与下的独立折叠子组 | 算法选择、辅助判断、话题与显式续接职责不同;无模型依赖的功能不绑定辅助模型开关 | +| newMessageStrategy / deferredProcessingTime / heartbeat | 执行策略 | 消息处理与调度 | 安静期只作用 deferred;最大心跳数不是消息条数 | +| backgroundTools.* | 执行策略 | 消息处理与调度 → 后台工具 | enabled 为总开关;allowedTools 决定可提交工具;completion 决定何时处理;settlement 决定奖励合并单位 | +| nativeToolCalling / 模型 disableNativeToolCalling / abilities | 执行策略、单模型能力 | 工具调用,并在模型配置明确关联说明 | 全局开启仍受模型支持限制;JSON 动作回退不是禁用工具 | +| extra / advanced.maxRetry / retryDelay / timeout | 工具与扩展 | 工具与扩展 → 执行限制 | 工具重试与模型重试分开,超时字段需核对真实调用方,不能仅按名字认定已生效 | +| replySuppression / decisionRecording | 回复控制与决策记录 | 暂停控制;日志与诊断 | 暂停行为与记录保存分组,不改变暂停的有效性保护 | +| logging / errorReporting | 系统设置 | 日志、诊断与错误上报 | 本地记录、诊断快照及外部上报分别开关,不相互暗示开启 | +| 人物插件 enabled / mode / sharedMemory / recallScope / automaticRecall | 人物插件独立配置页 | 人物维护;共享范围;召回;总结任务 | enabled 是插件功能门控;mode 是维护模式;共享认识与召回经历范围不是同一开关 | +| 持久提醒 enabled / pollIntervalSeconds | 持久提醒独立页 | 功能开关;执行检查 | 唤醒成功不等于平台发送成功 | +| OneBot 名单 enabled / concurrency / batchSize | 名单插件独立页 | 功能开关;查询与缓存 | 可用性和查询权限分别处理 | + +### 分组实施前需定稿 + +1. 顶层导航名称、顺序、默认折叠以及高级选项边界。 +2. 每项功能唯一主要入口;关联项使用简短说明,不复制可编辑字段。 +3. 保留公开配置路径与默认值,移动前后使用同一组旧配置验证。 +4. 能力声明、总开关、作用范围和执行策略分别命名,不将不同功能误删为重复。 +5. 每个附加插件的分组采用共同词汇,但不由核心强制加载或修改插件配置。 +6. 原生配置控件优先;隐藏或禁用无效组合前须确认配置保存与热更新行为。 + +## 错误体系现状 + +| 入口 | 现有结构 | 已确认的差异 | +| ------------ | ---------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| 核心内部 | AppError / ErrorDefinitions,含 code、message、suggestion、errorId、context、cause | 已有基础类与稳定码,不应重建另一套 | +| 核心公开导出 | 根入口导出 shared,shared 导出 errors | 错误类已有公开入口;问题是契约和使用覆盖,不是完全未导出 | +| 工具结果 | ToolCallResult / ToolError,错误含 name、message、可选 retryable | 未统一携带 code 与 errorId;Failed(string) 会丢失原始错误分类 | +| 工具异常捕获 | ToolService 捕获异常,日志后返回 Failed("Exception: ...") | 原始 code、cause 和关联关系不能可靠跨越边界;异常路径直接返回,结构化 retryable 路径才进入重试判断 | +| 人物插件 | 自建 Failed 包装为 PersonMemoryError,普通 Error 较多 | 权限、参数、版本和来源失效通常只剩说明文字 | +| OneBot 名单 | 本地 Failed 包装为 ToolError | 与核心 helper 形似,但不是统一转换入口 | +| 视觉工具 | 混合 Failed(string)、普通 Error 及服务错误文本 | 需要按边界转换,不应将第三方响应正文直接当成稳定错误码 | + +## 建议的最小公共约定 + +此处是设计候选,字段与命名须定稿后才进入实现。 + +- 内部沿用 AppError,保留 cause 与受控诊断上下文。 +- 外部错误结果沿用 ToolCallResult,增量兼容 code / errorId 等字段;旧 name / message / retryable 保留读取兼容。 +- 由统一转换入口从 unknown、AppError 或旧工具错误产生对应的公开结果。仅有相同 code 字符串不代表外部数据获得可信身份。 +- 用户提示提供可行动说明和必要的错误 ID;模型工具结果提供执行结果及可恢复建议;维护日志保留 cause;上报使用现有白名单与系统配置。 +- 不把无搜索结果或不存在可选记忆当成系统异常。 + +建议分类语义:输入无效、配置/能力缺失、权限拒绝、数据不存在、版本冲突、来源失效、取消、超时、限流、上游故障、内部故障、外部执行结果未知。先映射现有码,缺少的再按原有命名方式扩展;不批量重命名既有错误码。 + +重试资格由错误性质和具体操作共同决定。版本冲突通常需重读;权限、取消及确定失效不自动重试;发送或写入的结果未知不能因“网络错误”自动重做。声明 retryable 不代表绕过调用方的次数、幂等及取消限制。 + +## 接口边界验收候选 + +- 改变中文说明不会改变控制流。 +- 普通无结果与执行失败可区分。 +- 核心错误经过工具返回、日志和上报后仍能关联同一操作。 +- 字符串错误与旧扩展返回可继续处理,未知错误不丢失内部 cause。 +- 取消、版本冲突和权限拒绝不会被误判为可重试网络故障。 +- 副作用回执未知时不自动重复执行。 +- 对模型、用户及上报的结果不包含凭据、栈或未经批准的请求正文。 +- 附加插件无需依赖核心私有文件;同进程重复包加载或跨进程传输不单靠 instanceof 判断格式。 + +## 后续批次 + +A. 已验证的标题局部修复,可独立审查。 +B. 配置映射逐项定稿,再只调整展示分组并验证旧配置不变。 +C. 错误语义、字段和边界转换定稿;选一条真实链路从核心到一个附加插件贯通,再按模块扩展。 + +不得将 B/C 的讨论稿视为已实现,不将局部标题测试视为全配置页视觉验收。 + +## 配置导航具体方案(本批采用) + +将当前按实现模块拆开的区域收敛为七个顶层分组。模型服务和回复触发默认展开,其余默认折叠;子功能保留独立折叠。此处“默认折叠”仅影响展示,不改变功能开关与配置默认值。 + +| 顺序与显示名称 | 子组 | 现有根字段归属 | +| ------------------ | ------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1 模型服务 | 提供商与模型;模型组;任务分配 | providers、modelGroups、task | +| 2 人格与提示词 | 核心记忆文件;提示词模板;模板渲染(高级) | coreMemoryPath、systemTemplate、userTemplate、multiModalSystemTemplate、injectionPlaceholder、maxRenderDepth | +| 3 回复触发与意愿 | 响应范围;直接触发;意愿算法;基础增益;回复成本与衰减;参与保持;话题;辅助判断;会话续接;暂停 | allowedChannels、prioritizeMentions、willingnessPolicy、base、attribute、interest、lifecycle、participation、topics、typesafe、continuation、replySuppression | +| 4 消息处理与工具 | 消息调度;工具调用方式;后台工具;扩展启用;工具重试与限制 | debounceMs、newMessageStrategy、deferredProcessingTime、heartbeat、nativeToolCalling、streamAction、backgroundTools、extra、advanced | +| 5 上下文与记忆 | 输入预算;图片上下文;近期消息;语义召回;长期日记;历史保留与清理 | contextInputBudgetTokens、enableVision、allowedImageTypes、maxImagesInContext、imageLifecycleCount、detail、l1_memory、l2_memory、l3_memory、ignoreSelfMessage、logLengthLimit、dataRetentionDays、cleanupIntervalSec | +| 6 资源处理 | 保留现有资源服务字段,分存储与处理限制 | storagePath、driver、assetEndpoint、maxFileSize、downloadTimeout、autoClear、image、recoveryEnabled | +| 7 日志、诊断与上报 | 本地日志;决策记录;错误上报 | logging、decisionRecording、errorReporting | + +version 继续隐藏,不作为导航字段。模型的生成参数、请求超时、重试、熔断、能力声明及容量仍留在各自模型内,不重复出现在工具执行限制中。资源处理的 image 子组保留缓存路径、尺寸、体积及 GIF 策略,autoClear 保留启用、周期和保留天数。实施前仍须对 Schema 做机械路径清单核对,并补入 #255 最终新增字段,不能把人工映射表当作完整覆盖验收。 + +### 各组展示约定 + +- 显示标题与配置路径分别维护。移动展示位置不把 `contextInputBudgetTokens` 写成新的 `context.budget` 路径。 +- 保留 table、checkbox、computed 分支、动态模型/工具列表及高级参数的原生控件,不用文本框替换。 +- 意愿的通用基础参数放在算法选择之后;平衡算法专用字段仍属于 willingnessPolicy,明确仅作用于平衡算法,不通过隐藏而丢失未启用算法的已保存参数。 +- TypeSafe、话题分析和会话续接分别显示自己的启用条件及依赖;不增加一个会同时启用三者的总开关。 +- 完成意愿仍放在后台工具内,因为它依赖任务完成处理与结算单位;响应意愿组只说明该奖励的存在,不再放第二套编辑入口。 +- 图片上下文只负责模型本轮看到哪些图片;独立视觉工具负责图片查询与处理,其开关不假装是同一功能。 +- 删除“高级选项”这类无对象的泛称,改为“工具执行限制”“模板渲染(高级)”等明确对象名称。 +- 一个根字段只能在一处可编辑。跨组关联只用说明文字,不复制绑定同一字段的控件。 +- 条件未满足时保留已填写值;第一批仅补充生效说明,不自动清空、覆盖或强行启用相关选项。 + +### 易混淆控制关系的明确表达 + +| 管理者的问题 | 配置与解释 | +| ---------------------------- | ------------------------------------------------------------------------------------------ | +| 模型最多容纳多少 token? | 模型内 contextLimit;是容量声明,不是历史保留数量 | +| 每轮尽量给模型多少上下文? | contextInputBudgetTokens;软预算为 0 不取消模型容量约束 | +| 保存多少近期聊天? | l1_memory;与单次输入预算和数据库保留天数分开 | +| 是否使用原生工具调用? | nativeToolCalling 为全局偏好;模型能力及 disableNativeToolCalling 可使该模型回退 JSON 动作 | +| 工具能不能进入后台? | backgroundTools.enabled 与 allowedTools;不能据此推断普通工具被禁用 | +| 回复过程中来了新消息怎么办? | newMessageStrategy;与工具是否后台执行无从属关系 | +| 后台完成后是否主动处理? | backgroundTools.completion;是否最终发言仍由意愿、调度及回复控制决定 | +| 人物资料是否跨场景共享? | 人物插件 sharedMemory / memoryDomain;与 recallScope 控制的经历召回范围区分 | +| 是否自动总结人物? | 人物维护模式、总结模型组及任务条件共同决定;留空模型组不调用后台模型 | + +### 附加插件方案 + +人物记忆页保留“启用与维护模式 → 场景与共享范围 → 经历召回 → 后台总结 → 存储及维护限制”的顺序。已有字段保持原位置键,只重排展示。独立视觉、提醒、名单等插件统一采用“启用条件 → 功能参数 → 执行限制 → 存储/诊断(确有字段时)”;不存在的模块不添加空分组。 + +### 配置重排的验收门槛 + +1. 生成旧、新 Schema 根字段及完整路径清单:字段无丢失、无重复、无新增持久路径。 +2. 同一批旧配置经过旧、新 Schema 后,业务值与默认值一致;computed 分支、动态选择、隐藏迁移和未知字段处理分别验证。 +3. 在 Koishi 的真实配置渲染中检查折叠、保存、校验提示、未保存草稿、单行容量表和移动端窄屏;纯 schema 断言不替代视觉验收。 +4. 启用、禁用、切换算法与切换模型能力后,已保存的不活跃选项不被清空。 +5. 配置页实际载入的插件包与测试所用 schema 版本一致;先结合 #255 最终代码核对提供商相关控件。 + +## 公共错误接口具体方案(本批采用) + +### 结构与兼容 + +沿用 AppError 作为内部错误类,ErrorDefinitions 作为错误码目录,ToolCallResult 作为工具结果,不新增第二个基础异常类。 + +拟议的增量公共 ToolError 结构: + +```ts +interface ToolError { + name: string; // 兼容现有工具 + message: string; // 面向调用者的说明 + retryable?: boolean; // 现有字段:表示资格,不承诺调用方一定重试 + code?: string; // 稳定错误码,新转换入口产生,旧工具允许缺少 + errorId?: string; // 同一错误跨日志、结果及上报的关联标识 + category?: ErrorCategory; + suggestion?: string; +} +``` + +ErrorCategory 的候选固定值为 `invalid_input`、`configuration`、`permission_denied`、`not_found`、`conflict`、`source_invalid`、`cancelled`、`timeout`、`rate_limited`、`upstream_failure`、`internal`、`outcome_unknown`。category 是粗分类,code 是具体原因;不能通过 category 自动获得权限或触发重试。现有码保留,新目录条目再声明分类及可重试资格。 + +内部 AppError 保留 cause/context;这两个字段不加入公开 ToolError。ErrorDefinitions 中已有 code/message/suggestion 的条目继续可用,新增元信息应可选。普通 Error 规范化后以其为 cause,不直接将任意异常正文作为公开说明。 + +### 边界职责 + +| 边界 | 必须保留 | 不应直接传出 | +| ---------------------- | ----------------------------------------------- | ---------------------------------- | +| 内部服务到内部调用方 | AppError 的具体码、关联 ID、cause、受控上下文 | 不以中文文案做分支依据 | +| 内部错误到模型工具结果 | code、分类、可行动说明、重试资格和必要的关联 ID | 栈、凭据、原始请求及响应正文 | +| 管理指令到用户 | 简明原因、下一步操作、必要的错误 ID | 内部对象与完整调用栈 | +| 维护日志 | 同一 errorId、操作/工具标识、经处理的诊断详情 | 未处理的敏感请求内容 | +| 外部错误上报 | 沿用已配置的上报开关、过滤与字段白名单 | 不能因为错误被规范化就默认开启上报 | + +### 处理语义 + +- 成功但无查询结果:仍是成功结果,不能转换为内部异常;必需对象不存在才属于 not_found。 +- 来源删除、身份归属变化与暂时读取失败分开,暂时失败不能直接将数据判为永久失效。 +- 版本冲突先重新读取并重新决定操作,不能盲目重复旧提交。 +- 取消、权限拒绝、参数错误和明确来源失效不自动重试。 +- 超时、限流和上游故障仍受具体工具的幂等与次数约束;已执行但回执未知归 outcome_unknown,不自动重做副作用。 +- 对插件显式返回的旧 ToolError 保持 name/message/retryable 行为;逐步补齐新字段,而不是猜测中文文本对应的错误码。 +- 对来自普通对象的错误先验证字段类型与长度;不能只凭 `instanceof` 跨包判断,也不能仅凭外部 `code` 字符串将其当作可信 AppError。 +- 边界只进行一次有明确归属的规范化和记录,避免每层重新生成 errorId 或重复上报。 + +### 分阶段贯通与验收 + +首条贯通链建议选择人物记忆的“读取当前人物 → 提交带版本的候选 → 版本冲突返回”:既有真实普通 Error 和自建 Failed 包装,也已有版本保护,可验证分类而不改变人物认识算法。 + +第一步定稿错误类别、字段与转换入口签名;第二步补兼容测试及该条链路;第三步接入 ToolService 捕获与返回;第四步按插件扩展。取消/重试与副作用未知的用例应在工具服务接入时一并验证,不能仅在人物读取场景测试后宣称全链完成。 + +第一批不批量替换所有 throw,不修改既有工具成功结果,不增加自动重试次数,不将模型错误与工具错误的重试策略合并。配置展示与错误规范应分开提交与验收。 + +## 首批实施结果与验证边界 + +- 核心配置已按七组重排,原根字段仅出现一次,复用原生字段 schema;子分组使用独立 `yib-subsection` 角色与三级标题,折叠不卸载内部表单。 +- 原有配置、默认值、computed 分支、动态选择及上下文容量转换均与重排前组合对照验证。 +- AppError 增加分类及重试资格,旧构造方式继续可用;ToolError 增量增加可选 code/errorId/category/suggestion。共享 normalizeAppError、fromAppError、toToolError 提供内部规范化和公开白名单投影。 +- ToolService 异常捕获采用共享转换,保留取消检查与原重试次数;显式旧 ToolError 返回及 Failed(string) 继续兼容。 +- 人物候选与 claim 候选的版本冲突已贯通 `PERSON_MEMORY.VERSION_CONFLICT`;旧核心缺少该目录时回退原错误说明,版本保护仍执行。 +- 本地自定义 AppError 保留对象、cause 与关联 ID;未注册码对外回退安全的未知错误说明;跨包对象须通过受限结构检查。 +- 附加插件其他普通 Error 及独立配置页尚未全量改造,不应据此宣称所有插件已经统一错误分类。 +- 配置组件已验证服务端渲染的标题、展开状态、内部挂载与字段前缀传递;完整 Koishi 浏览器交互及真实主题下的窄屏视觉仍需部署验收,不能用 schema 或服务端渲染测试替代。 diff --git a/packages/core/client/index.ts b/packages/core/client/index.ts index 6859f0b43..0b91c2efb 100644 --- a/packages/core/client/index.ts +++ b/packages/core/client/index.ts @@ -19,8 +19,8 @@ export const ConfigSection = defineComponent({ return { ...props.schema, meta }; }); return () => - h("section", { ...attrs, class: ["yib-config-section", attrs.class] }, [ - h("h2", { class: "yib-config-section-heading" }, [ + h("section", { ...attrs, class: ["yib-config-section", props.schema.meta.role === "yib-subsection" && "yib-config-subsection", attrs.class] }, [ + h(props.schema.meta.role === "yib-subsection" ? "h3" : "h2", { class: "yib-config-section-heading" }, [ h( "button", { @@ -49,7 +49,7 @@ export const ConfigSection = defineComponent({ }); export default function apply(ctx) { - for (const type of ["object", "intersect"]) { - ctx.extendSchema({ type, role: "yib-section", component: ConfigSection }); + for (const role of ["yib-section", "yib-subsection"]) { + for (const type of ["object", "intersect"]) ctx.extendSchema({ type, role, component: ConfigSection }); } } diff --git a/packages/core/client/section.css b/packages/core/client/section.css index 92538f66f..4cf255808 100644 --- a/packages/core/client/section.css +++ b/packages/core/client/section.css @@ -55,3 +55,17 @@ margin-left: 2px; } } + +.yib-config-subsection { + margin: 10px 0; + border-radius: 4px; +} +.yib-config-subsection > .yib-config-section-heading { + font-size: 0.9rem; +} +.yib-config-subsection > .yib-config-section-heading > button { + padding: 10px 12px; +} +.yib-config-subsection > .yib-config-section-body { + padding: 4px 12px 12px; +} diff --git a/packages/core/src/config/config.ts b/packages/core/src/config/config.ts index 1d6fbeeb9..c192b81e6 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -35,30 +35,94 @@ export type Config = ModelServiceConfig & readonly version: string | number; }; -export const Config: Schema = Schema.intersect( - [ - Schema.object({ - version: Schema.union([Schema.string(), Schema.number()]).hidden(), - }), +// These module roots are presentation-only object/intersect containers. Reuse +// their field schemas whole: nested unions, transforms, computed branches and +// dynamic selectors must remain native and run exactly once. +const fields = new Map(); +for (const schema of [ + ModelServiceConfigSchema, + AgentBehaviorConfigSchema, + PromptServiceConfigSchema, + MemoryConfigSchema, + HistoryConfigSchema, + ToolServiceConfigSchema, + AssetServiceConfigSchema, + SystemConfigSchema, +]) { + collectFields(schema); +} - ModelServiceConfigSchema.description("模型服务"), - AgentBehaviorConfigSchema, - PromptServiceConfigSchema, +function collectFields(schema: Schema): void { + if (schema.type === "intersect") { + for (const child of schema.list ?? []) collectFields(child); + return; + } + // Do not silently flatten a future root union/transform: it may contain + // conditional or cross-field validation that needs an explicit redesign. + if (schema.type !== "object") throw new TypeError(`Unsupported configuration root: ${schema.type}`); + for (const [key, field] of Object.entries(schema.dict ?? {})) { + if (fields.has(key)) throw new TypeError(`Duplicate configuration field: ${key}`); + fields.set(key, field); + } +} - MemoryConfigSchema.description("核心记忆文件"), - HistoryConfigSchema, - ToolServiceConfigSchema.description("工具与扩展"), +function take(keys: ReadonlyArray): Schema { + const dict: Record = {}; + for (const key of keys) { + const field = fields.get(key); + if (!field) throw new TypeError(`Missing or repeated configuration field: ${key}`); + dict[key] = key === "advanced" ? field.description("工具执行限制") : field; + fields.delete(key); + } + return Schema.object(dict); +} - AssetServiceConfigSchema.collapse().description("资源存储与处理"), - //TelemetryConfigSchema, - SystemConfigSchema.collapse().description("系统设置"), - ].map(configSection), -); +function subgroup(title: string, keys: ReadonlyArray): Schema { + return take(keys).description(title).collapse().role("yib-subsection"); +} -// Preserve flat configuration fields. Only top-level presentation metadata changes. -function configSection(schema: Schema): Schema { - if (schema.type === "intersect" && !schema.meta.description) { - return Schema.intersect((schema.list ?? []).map(configSection)); - } - return schema.meta.description ? schema.role("yib-section") : schema; +function section(title: string, children: Schema[], collapsed = true): Schema { + return Schema.intersect(children).description(title).collapse(collapsed).role("yib-section"); } + +export const Config: Schema = Schema.intersect([ + Schema.object({ version: Schema.union([Schema.string(), Schema.number()]).hidden() }), + section("模型服务", [subgroup("提供商与模型", ["providers"]), subgroup("模型组", ["modelGroups"]), subgroup("任务分配", ["task"])], false), + section("人格与提示词", [ + subgroup("核心记忆文件", ["coreMemoryPath"]), + subgroup("提示词模板", ["systemTemplate", "userTemplate", "multiModalSystemTemplate"]), + subgroup("模板渲染(高级)", ["injectionPlaceholder", "maxRenderDepth"]), + ]), + section( + "回复触发与意愿", + [ + subgroup("响应范围", ["allowedChannels"]), + subgroup("直接触发", ["prioritizeMentions"]), + take(["willingnessPolicy"]), + subgroup("基础增益", ["base", "attribute", "interest"]), + take(["lifecycle", "participation", "topics", "typesafe", "continuation", "replySuppression"]), + ], + false, + ), + section("消息处理与工具", [ + subgroup("消息调度", ["debounceMs", "newMessageStrategy", "deferredProcessingTime", "heartbeat"]), + subgroup("工具调用方式", ["nativeToolCalling", "streamAction"]), + take(["backgroundTools"]), + subgroup("扩展启用", ["extra"]), + take(["advanced"]), + ]), + section("上下文与记忆", [ + subgroup("输入预算", ["contextInputBudgetTokens"]), + subgroup("图片上下文", ["enableVision", "allowedImageTypes", "maxImagesInContext", "imageLifecycleCount", "detail"]), + take(["l1_memory", "l2_memory", "l3_memory"]), + subgroup("历史保留与清理", ["ignoreSelfMessage", "logLengthLimit", "dataRetentionDays", "cleanupIntervalSec"]), + ]), + section("资源处理", [ + subgroup("资源存储", ["storagePath", "driver", "assetEndpoint"]), + subgroup("处理限制", ["maxFileSize", "downloadTimeout", "recoveryEnabled"]), + take(["autoClear", "image"]), + ]), + section("日志、诊断与上报", [take(["logging", "decisionRecording", "errorReporting"])]), +]); + +if (fields.size) throw new TypeError(`Configuration fields missing navigation: ${[...fields.keys()].join(", ")}`); diff --git a/packages/core/src/extension/service.ts b/packages/core/src/extension/service.ts index 90a7f9266..7befe4136 100644 --- a/packages/core/src/extension/service.ts +++ b/packages/core/src/extension/service.ts @@ -8,6 +8,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"; @@ -830,9 +831,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/model/config.ts b/packages/core/src/model/config.ts index dff624b3b..97dac8153 100644 --- a/packages/core/src/model/config.ts +++ b/packages/core/src/model/config.ts @@ -127,7 +127,7 @@ export const ModelConfigSchema: Schema = Schema.object({ ]) .default("unset") .description("最大上下文"), - }), + }).description(""), Schema.union([ Schema.object({ mode: Schema.const("unset").default("unset") }), Schema.object({ @@ -144,7 +144,7 @@ export const ModelConfigSchema: Schema = Schema.object({ .description("上下文容量(1K = 1000 token;1M = 1000000 token)"), }), Schema.object({ mode: Schema.const("auto").required() }), - ]), + ]).description(""), // Keep capacity validation separate from the visible table fields. Schema.transform(Schema.any(), parseContextLimit).hidden(), ]) 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/config-navigation.spec.ts b/packages/core/tests/config-navigation.spec.ts new file mode 100644 index 000000000..a0b4320f6 --- /dev/null +++ b/packages/core/tests/config-navigation.spec.ts @@ -0,0 +1,149 @@ +import assert from "node:assert/strict"; + +import { Schema } from "koishi"; +import { test } from "vitest"; + +import { AgentBehaviorConfigSchema } from "../src/agent/config"; +import { AssetServiceConfigSchema } from "../src/asset/config"; +import { Config, SystemConfigSchema } from "../src/config/config"; +import { ToolServiceConfigSchema } from "../src/extension/config"; +import { MemoryConfigSchema } from "../src/memory/config"; +import { ModelServiceConfigSchema } from "../src/model/config"; +import { PromptServiceConfigSchema } from "../src/prompt/config"; +import { HistoryConfigSchema } from "../src/world/config"; + +// The pre-navigation composition: keep the real module schemas, including their +// transforms and provider branches, as the normalization compatibility oracle. +const original = Schema.intersect([ + Schema.object({ version: Schema.union([Schema.string(), Schema.number()]).hidden() }), + ModelServiceConfigSchema, + AgentBehaviorConfigSchema, + PromptServiceConfigSchema, + MemoryConfigSchema, + HistoryConfigSchema, + ToolServiceConfigSchema, + AssetServiceConfigSchema, + SystemConfigSchema, +]); + +function rootEntries(schema: Schema): Array<[string, Schema]> { + if (schema.type === "object") return Object.entries(schema.dict!); + assert.equal(schema.type, "intersect", "navigation must not hide a second validation pass"); + return schema.list!.flatMap(rootEntries); +} + +const headings = ["模型服务", "人格与提示词", "回复触发与意愿", "消息处理与工具", "上下文与记忆", "资源处理", "日志、诊断与上报"]; + +test("core navigation has seven ordered sections with only model and reply expanded", () => { + const sections = Config.list!.filter((schema) => schema.meta.role === "yib-section"); + assert.deepEqual( + sections.map((schema) => schema.meta.description), + headings, + ); + assert.deepEqual( + sections.map((schema) => !!schema.meta.collapse), + [false, true, false, true, true, true, true], + ); + assert.equal(rootEntries(Config).find(([key]) => key === "version")![1].meta.hidden, true); +}); + +test("scalar subgroups have independently collapsible presentation boundaries", () => { + const sections = Config.list!.filter((schema) => schema.meta.role === "yib-section"); + const wrappers = sections.flatMap((schema) => schema.list!).filter((schema) => schema.meta.description); + assert.deepEqual( + wrappers.map((schema) => schema.meta.description), + [ + "提供商与模型", + "模型组", + "任务分配", + "核心记忆文件", + "提示词模板", + "模板渲染(高级)", + "响应范围", + "直接触发", + "基础增益", + "消息调度", + "工具调用方式", + "扩展启用", + "输入预算", + "图片上下文", + "历史保留与清理", + "资源存储", + "处理限制", + ], + ); + for (const wrapper of wrappers) { + assert.equal(wrapper.meta.role, "yib-subsection"); + assert.equal(wrapper.meta.collapse, true); + } +}); + +test("navigation preserves every root path exactly once and reuses native field schemas", () => { + const before = new Map(rootEntries(original)); + const after = rootEntries(Config); + assert.deepEqual(after.map(([key]) => key).sort(), [...before.keys()].sort()); + assert.equal(new Set(after.map(([key]) => key)).size, after.length); + for (const [key, field] of after) { + if (key === "version") continue; + if (key === "advanced") { + assert.equal(field.dict, before.get(key)!.dict); + assert.equal(field.meta.description, "工具执行限制"); + } else { + // Identity preserves every descendant path, transform, computed + // branch, dynamic reference and native control, not just its type. + assert.equal(field, before.get(key), key); + } + } +}); + +const fixtures = [ + {}, + { + version: "2.0.1", + unknownOption: { keep: true }, + base: { text: JSON.parse('{"$switch":{"branches":[{"case":{"platform":"onebot"},"then":27}],"default":12}}') }, + }, + { + providers: [ + { name: "default", models: [{ modelId: "a", contextLimit: { mode: "custom", value: "128K" } }] }, + { + name: "other", + type: "OpenAI Compatible", + baseURL: "https://example.invalid/v1", + models: [{ modelId: "b", contextLimit: { mode: "auto" }, disableNativeToolCalling: true }], + }, + ], + modelGroups: [{ name: "chat", models: [{ providerName: "default", modelId: "a" }] }], + task: { chat: "chat" }, + extra: { example: { enabled: true, retained: "value" } }, + }, + { + willingnessPolicy: { algorithm: "legacy", ordinaryGainLimit: 42, replyPenalty: 9 }, + topics: { enabled: false, model: { providerName: "p", modelId: "m" } }, + typesafe: { mode: "off", evaluationModel: { providerName: "p", modelId: "m" }, interests: "saved" }, + continuation: { enabled: false, mode: "willingness", willingnessGain: 18 }, + backgroundTools: { enabled: false, allowedTools: ["saved"], willingness: { succeeded: 3, failed: 2, cancelled: 1 } }, + newMessageStrategy: "skip", + deferredProcessingTime: 12345, + contextInputBudgetTokens: 0, + enableVision: false, + image: { gifProcessingStrategy: "firstFrame" }, + }, +]; + +test("old configurations normalize identically with defaults and inactive values retained", () => { + for (const fixture of fixtures) { + assert.deepEqual(Config(structuredClone(fixture)), original(structuredClone(fixture))); + } +}); + +test("navigation retains model capacity and background willingness validation", () => { + for (const fixture of [ + { providers: [{ name: "p", models: [{ modelId: "m", contextLimit: { mode: "custom", value: "1G" } }] }] }, + { backgroundTools: { willingness: { succeeded: Infinity } } }, + { participation: { influence: 1.1 } }, + ]) { + assert.throws(() => original(structuredClone(fixture))); + assert.throws(() => Config(structuredClone(fixture))); + } +}); diff --git a/packages/core/tests/config-section.spec.ts b/packages/core/tests/config-section.spec.ts new file mode 100644 index 000000000..ef4eb0300 --- /dev/null +++ b/packages/core/tests/config-section.spec.ts @@ -0,0 +1,38 @@ +import { renderToString } from "@vue/server-renderer"; +import { Schema } from "koishi"; +import { expect, it } from "vitest"; +import { createSSRApp, defineComponent, h } from "vue"; + +import apply, { ConfigSection } from "../client"; + +it("registers top-level sections and nested subsections independently", () => { + const extensions: any[] = []; + apply({ extendSchema: (extension: unknown) => extensions.push(extension) }); + expect(extensions.map(({ type, role }) => `${type}:${role}`)).toEqual([ + "object:yib-section", + "intersect:yib-section", + "object:yib-subsection", + "intersect:yib-subsection", + ]); +}); + +it.each([false, true])("renders a subsection without a duplicate top-level heading (folded=%s)", async (collapsed) => { + const schema = Schema.object({}).description("模型组").role("yib-subsection").collapse(collapsed); + const app = createSSRApp({ render: () => h(ConfigSection, { schema, modelValue: {}, prefix: "providers." }) }); + app.component( + "k-schema", + defineComponent({ + props: ["schema", "prefix"], + setup: (props) => () => h("input", { "data-prefix": props.prefix, "data-inner-title": props.schema.meta.description ?? "none" }), + }), + ); + const html = await renderToString(app); + expect(html).toContain('

'); + expect(html).not.toContain(" ModelConfigSchema({ modelId: "m", contextLimit: { mode: "custom" } })).toThrow(/./); expect(() => ModelConfigSchema({ modelId: "m", contextLimit: { mode: "custom", value: [{ unit: "K" }] } })).toThrow(/./); }); + +it("keeps the capacity title on its outer fold without inheriting it into native inner headers", () => { + const schema = new Schema(JSON.parse(JSON.stringify(ModelConfigSchema))).dict!.contextLimit; + expect(schema.meta.description).toContain("上下文容量"); + expect(schema.meta.collapse).toBe(true); + for (const child of schema.list!.filter((item) => !item.meta.hidden)) { + // Native intersect merges parent metadata into children rendered without a fold. + const renderedMeta = { ...schema.meta, ...child.meta }; + expect(renderedMeta.description).toBe(""); + } + expect(capacityTable()?.inner?.dict?.amount.type).toBe("number"); +}); 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; + } +}); From 8b2839057e2fd620784fe55647e6cc2688618e87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=AE=B8=E4=BB=99xhcz?= Date: Thu, 29 Oct 2026 01:12:44 +0800 Subject: [PATCH 5/6] fix(config): prevent native renderer from inheriting section headings --- packages/core/src/config/config.ts | 3 +- .../core/tests/config-native-headings.spec.ts | 67 +++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 packages/core/tests/config-native-headings.spec.ts diff --git a/packages/core/src/config/config.ts b/packages/core/src/config/config.ts index c192b81e6..deb9a39dd 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -74,7 +74,8 @@ function take(keys: ReadonlyArray): Schema { dict[key] = key === "advanced" ? field.description("工具执行限制") : field; fields.delete(key); } - return Schema.object(dict); + // Native intersect rendering inherits descriptions unless the child explicitly clears them. + return Schema.object(dict).description(""); } function subgroup(title: string, keys: ReadonlyArray): Schema { diff --git a/packages/core/tests/config-native-headings.spec.ts b/packages/core/tests/config-native-headings.spec.ts new file mode 100644 index 000000000..15ddac4d7 --- /dev/null +++ b/packages/core/tests/config-native-headings.spec.ts @@ -0,0 +1,67 @@ +import { createRequire } from "node:module"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import { renderToString } from "@vue/server-renderer"; +import { expect, it } from "vitest"; +import { createSSRApp, defineComponent, h } from "vue"; +import { createI18n } from "vue-i18n"; + +import { Config } from "../src/config/config"; + +it("renders each main heading once through the native Koishi fallback", async () => { + const require = createRequire(import.meta.url); + const clientRequire = createRequire(require.resolve("@koishijs/client/lib")); + const { createServer, normalizePath } = clientRequire("vite"); + const vue = clientRequire("@vitejs/plugin-vue"); + const yaml = clientRequire("@maikolib/vite-plugin-yaml"); + const root = fileURLToPath(new URL("../../..", import.meta.url)); + const server = await createServer({ + root, + configFile: false, + plugins: [(vue.default ?? vue)(), (yaml.default ?? yaml)()], + server: { middlewareMode: true }, + optimizeDeps: { noDiscovery: true }, + }); + try { + const schemaRoot = path.dirname(require.resolve("schemastery-vue")); + const object = (await server.ssrLoadModule(normalizePath(path.join(schemaRoot, "extensions/object.vue")))).default; + const intersect = (await server.ssrLoadModule(normalizePath(path.join(schemaRoot, "extensions/intersect.vue")))).default; + const NativeSchema = defineComponent({ + props: ["schema", "modelValue", "extra", "prefix", "initial", "disabled"], + setup: (props) => () => + ["object", "intersect"].includes(props.schema.type) + ? h(props.schema.type === "object" ? object : intersect, props) + : h("input", { "data-prefix": props.prefix }), + }); + const app = createSSRApp({ render: () => h(NativeSchema, { schema: Config, modelValue: {}, prefix: "", extra: { foldable: false } }) }); + app.use(createI18n({ legacy: false, locale: "zh-CN", messages: { "zh-CN": {} } })); + app.component("k-schema", NativeSchema); + app.component("k-badge", { + setup: + (_props, { slots }) => + () => + h("span", slots.default?.()), + }); + app.component("k-markdown", { + props: ["source"], + render() { + return h("p", this.source); + }, + }); + for (const name of ["el-button", "el-tooltip", "el-collapse-transition"]) + app.component(name, { + setup: + (_props, { slots }) => + () => + h("div", slots.default?.()), + }); + const html = await renderToString(app); + const headings = Config.list!.filter((section) => section.meta.role === "yib-section").map((section) => section.meta.description); + for (const title of headings) expect(html.split(String(title))).toHaveLength(2); + expect(html.split("日志设置")).toHaveLength(2); + expect(html).toContain('data-prefix="logging.local.enabled."'); + } finally { + await server.close(); + } +}); From 29b655b00cf53d4e5d3996ec139a707ff85b6177 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=AE=B8=E4=BB=99xhcz?= Date: Thu, 29 Oct 2026 11:00:35 +0800 Subject: [PATCH 6/6] fix(config): restore offline controls and configuration validation --- packages/core/client/dynamic-field.ts | 29 +++++ packages/core/client/index.ts | 100 +++++++++++++----- packages/core/client/section.css | 22 ++++ packages/core/client/tsconfig.json | 2 +- packages/core/client/validation.ts | 47 ++++++++ packages/core/src/agent/config.ts | 7 +- packages/core/src/extension/config.ts | 4 +- packages/core/src/model/config.ts | 16 ++- packages/core/src/shared/config-selectors.ts | 23 ++++ packages/core/tests/background-policy.spec.ts | 4 +- .../tests/config-lifecycle-rendering.spec.ts | 73 +++++++++++++ .../core/tests/config-native-headings.spec.ts | 98 +++++++++-------- packages/core/tests/config-section.spec.ts | 17 +-- 13 files changed, 354 insertions(+), 88 deletions(-) create mode 100644 packages/core/client/dynamic-field.ts create mode 100644 packages/core/client/validation.ts create mode 100644 packages/core/src/shared/config-selectors.ts create mode 100644 packages/core/tests/config-lifecycle-rendering.spec.ts diff --git a/packages/core/client/dynamic-field.ts b/packages/core/client/dynamic-field.ts new file mode 100644 index 000000000..ce0f4c0c3 --- /dev/null +++ b/packages/core/client/dynamic-field.ts @@ -0,0 +1,29 @@ +import { Schema } from "@koishijs/client"; +import { computed, defineComponent, h, resolveComponent } from "vue"; + +export function dynamicField(schemas: () => Record) { + return defineComponent({ + name: "YibDynamicField", + inheritAttrs: false, + props: ["schema", "modelValue", "initial", "disabled", "prefix", "extra"], + emits: ["update:modelValue"], + setup(props, { emit, attrs, slots }) { + const inner = computed(() => { + const live = schemas()?.[props.schema.meta.extra?.name]; + // Live schemas arrive serialized; k-schema reconstructs their reference table. + if (live) { + const hydrated = new Schema(live); + if (hydrated.type !== "intersect" || hydrated.list?.length) + return { ...hydrated, meta: { ...props.schema.meta, ...hydrated.meta, role: hydrated.meta.role, extra: hydrated.meta.extra } }; + } + return { ...props.schema, meta: { ...props.schema.meta, role: undefined, extra: undefined } }; + }); + return () => + h( + resolveComponent("k-schema"), + { ...attrs, ...props, schema: inner.value, "onUpdate:modelValue": (value) => emit("update:modelValue", value) }, + slots, + ); + }, + }); +} diff --git a/packages/core/client/index.ts b/packages/core/client/index.ts index 0b91c2efb..49f9375ae 100644 --- a/packages/core/client/index.ts +++ b/packages/core/client/index.ts @@ -1,6 +1,10 @@ +import { store } from "@koishijs/client"; import { computed, defineComponent, h, ref, resolveComponent } from "vue"; +import { dynamicField } from "./dynamic-field"; + import "./section.css"; +import { invalidConfig } from "./validation"; let nextSectionId = 0; @@ -15,41 +19,87 @@ export const ConfigSection = defineComponent({ const collapsed = ref(!!props.schema.meta.collapse); const bodyId = `yib-config-section-${++nextSectionId}`; const inner = computed(() => { - const { role, description, collapse, ...meta } = props.schema.meta; + const { role: _role, description: _description, collapse: _collapse, ...meta } = props.schema.meta; return { ...props.schema, meta }; }); + const invalid = computed(() => !!props.extra?.invalid || invalidConfig(inner.value, props.modelValue)); + return () => + h( + "section", + { + ...attrs, + class: [ + "yib-config-section", + props.schema.meta.role === "yib-subsection" && "yib-config-subsection", + attrs.class, + { invalid: invalid.value }, + ], + }, + [ + h(props.schema.meta.role === "yib-subsection" ? "h3" : "h2", { class: "yib-config-section-heading" }, [ + h( + "button", + { + type: "button", + "aria-expanded": !collapsed.value, + "aria-controls": bodyId, + "aria-invalid": invalid.value, + onClick: () => (collapsed.value = !collapsed.value), + }, + [ + h("span", props.schema.meta.description), + invalid.value ? h("span", { class: "yib-config-section-error" }, "配置未完成或无效") : null, + h("span", { class: "yib-config-section-toggle" }, collapsed.value ? "展开" : "收起"), + ], + ), + ]), + // Keep native children mounted: folding must not discard drafts. + h("div", { id: bodyId, class: "yib-config-section-body", hidden: collapsed.value }, [ + h(resolveComponent("k-schema"), { + schema: inner.value, + modelValue: props.modelValue, + initial: props.initial, + disabled: props.disabled, + prefix: props.prefix, + extra: { ...props.extra, foldable: false }, + "onUpdate:modelValue": (value) => emit("update:modelValue", value), + }), + ]), + ], + ); + }, +}); + +export const ConfigEntry = defineComponent({ + name: "YibConfigEntry", + inheritAttrs: false, + props: ["schema", "modelValue", "initial", "disabled", "prefix", "extra"], + emits: ["update:modelValue"], + setup(props, { emit, attrs, slots }) { + const inner = computed(() => ({ ...props.schema, meta: { ...props.schema.meta, role: undefined } })); + const invalid = computed(() => !!props.extra?.invalid || invalidConfig(inner.value, props.modelValue)); return () => - h("section", { ...attrs, class: ["yib-config-section", props.schema.meta.role === "yib-subsection" && "yib-config-subsection", attrs.class] }, [ - h(props.schema.meta.role === "yib-subsection" ? "h3" : "h2", { class: "yib-config-section-heading" }, [ - h( - "button", - { - type: "button", - "aria-expanded": !collapsed.value, - "aria-controls": bodyId, - onClick: () => (collapsed.value = !collapsed.value), - }, - [h("span", props.schema.meta.description), h("span", { class: "yib-config-section-toggle" }, collapsed.value ? "展开" : "收起")], - ), - ]), - // Keep native children mounted: folding must not discard drafts. - h("div", { id: bodyId, class: "yib-config-section-body", hidden: collapsed.value }, [ - h(resolveComponent("k-schema"), { + h("div", { ...attrs, class: ["yib-config-entry", attrs.class, { invalid: invalid.value }] }, [ + h( + resolveComponent("k-schema"), + { + ...props, schema: inner.value, - modelValue: props.modelValue, - initial: props.initial, - disabled: props.disabled, - prefix: props.prefix, - extra: { ...props.extra, foldable: false }, + extra: { ...props.extra, invalid: invalid.value }, "onUpdate:modelValue": (value) => emit("update:modelValue", value), - }), - ]), + }, + slots, + ), + invalid.value ? h("p", { class: "yib-config-entry-error", role: "status" }, "此项配置未完成或无效,请展开检查。") : null, ]); }, }); export default function apply(ctx) { + for (const type of ["object", "intersect"]) ctx.schema({ type, role: "yib-entry", component: ConfigEntry }); + const component = dynamicField(() => store.schema ?? {}); + for (const type of ["union", "string", "array", "dict"]) ctx.schema({ type, role: "yib-dynamic", component }); for (const role of ["yib-section", "yib-subsection"]) { - for (const type of ["object", "intersect"]) ctx.extendSchema({ type, role, component: ConfigSection }); + for (const type of ["object", "intersect"]) ctx.schema({ type, role, component: ConfigSection }); } } diff --git a/packages/core/client/section.css b/packages/core/client/section.css index 4cf255808..cc9e4d5ff 100644 --- a/packages/core/client/section.css +++ b/packages/core/client/section.css @@ -69,3 +69,25 @@ .yib-config-subsection > .yib-config-section-body { padding: 4px 12px 12px; } + +.yib-config-section.invalid { + border-color: var(--el-color-danger); +} +.yib-config-section.invalid > .yib-config-section-heading > button { + color: var(--el-color-danger); +} +.yib-config-section-error { + font-size: 0.85rem; + margin-left: auto; +} +.yib-config-entry.invalid { + border-left: 2px solid var(--el-color-danger); +} +.yib-config-entry.invalid > .k-schema-item > .k-schema-main > .k-schema-left > h3, +.yib-config-entry-error { + color: var(--el-color-danger); +} +.yib-config-entry-error { + padding: 0 1rem; + font-size: 0.85rem; +} diff --git a/packages/core/client/tsconfig.json b/packages/core/client/tsconfig.json index 7b7350293..726311ee2 100644 --- a/packages/core/client/tsconfig.json +++ b/packages/core/client/tsconfig.json @@ -15,7 +15,7 @@ "moduleResolution": "node", "ignoreDeprecations": "6.0", "strictBindCallApply": true, - // index.ts 是 JS 风格的渲染函数组件,ctx.extendSchema 又是运行时 mixin、上游无类型声明。 + // index.ts 是 JS 风格的渲染函数组件,ctx.schema 又是运行时 mixin、上游无类型声明。 "noImplicitAny": false, "types": ["@koishijs/client/global"] }, diff --git a/packages/core/client/validation.ts b/packages/core/client/validation.ts new file mode 100644 index 000000000..9c4704829 --- /dev/null +++ b/packages/core/client/validation.ts @@ -0,0 +1,47 @@ +import { Schema } from "@koishijs/client"; + +const copy = (value: unknown) => (value === undefined ? undefined : JSON.parse(JSON.stringify(value))); + +function missingRequired(schema, value): boolean { + if (schema.meta?.hidden) return false; + if (schema.meta?.required && (value == null || (typeof value === "string" && value.trim() === "") || (Array.isArray(value) && value.length === 0))) + return true; + if (schema.type === "object") { + if (Object.hasOwn(schema.dict ?? {}, "providers") && (!Array.isArray(value?.providers) || !value.providers.length)) return true; + const selectedModel = + schema.dict?.evaluationModel && value?.mode && value.mode !== "off" + ? value.evaluationModel + : schema.dict?.model && schema.dict?.enabled && value?.enabled === true + ? value.model + : undefined; + const needsModel = !!( + (schema.dict?.evaluationModel && value?.mode && value.mode !== "off") || + (schema.dict?.model && schema.dict?.enabled && value?.enabled === true) + ); + if (needsModel && (!selectedModel?.providerName?.trim() || !selectedModel?.modelId?.trim())) return true; + return Object.entries(schema.dict ?? {}).some(([key, child]) => missingRequired(child, value?.[key])); + } + if (schema.type === "array") return Array.isArray(value) && value.some((row) => missingRequired(schema.inner, row)); + if (schema.type === "intersect") return (schema.list ?? []).some((child) => missingRequired(child, value)); + if (schema.type === "union") { + const branch = schema.list?.find((child) => { + try { + new Schema(child)(copy(value)); + return true; + } catch { + return false; + } + }); + return branch ? missingRequired(branch, value) : false; + } + return false; +} + +export function invalidConfig(schema, value): boolean { + try { + new Schema(schema)(copy(value)); + return missingRequired(schema, value); + } catch { + return true; + } +} diff --git a/packages/core/src/agent/config.ts b/packages/core/src/agent/config.ts index 72afeb907..f04f713af 100644 --- a/packages/core/src/agent/config.ts +++ b/packages/core/src/agent/config.ts @@ -4,6 +4,7 @@ import path from "path"; import { Computed, Schema } from "koishi"; import { SystemConfig } from "../config"; +import { modelSelector, backgroundToolSelector } from "../shared/config-selectors"; import { PROMPTS_DIR } from "../shared/constants"; import type { TopicConfig } from "./topics"; import { DEFAULT_WILLINGNESS_POLICY, type WillingnessPolicyConfig } from "./willingness-policy"; @@ -171,7 +172,7 @@ const WillingnessConfigSchema: Schema = Schema.object({ .description("意愿算法选择(切换算法不会改变忙时处理策略)"), topics: Schema.object({ enabled: Schema.boolean().default(false).experimental().description("启用实验性话题意愿,默认关闭;识别可能滞后或不准确,请按实际聊天效果调整"), - model: Schema.dynamic("modelService.selectableModels").description("话题总结模型(需具备对话能力;启用后会发送近期聊天内容)"), + model: modelSelector("modelService.selectableModels").description("话题总结模型(需具备对话能力;启用后会发送近期聊天内容)"), minIntervalMs: Schema.number().min(1000).max(3600000).default(30000).description("两次话题分析的最短间隔(毫秒)"), messagesPerAnalysis: Schema.natural().min(1).max(100).default(6).description("再次分析前至少收到的新消息数"), historyLimit: Schema.natural().min(1).default(20).description("分析时参考的近期消息数"), @@ -199,7 +200,7 @@ const WillingnessConfigSchema: Schema = Schema.object({ .description("对话参与保持(不强制回复,沿用回复控制规则)"), typesafe: Schema.object({ mode: Schema.union(["off", "observe", "adjust"]).default("off").description("TypeSafe 接话判断:关闭 / 仅记录 / 调整意愿"), - evaluationModel: Schema.dynamic("modelService.evaluationModels").description("判断模型,请在模型服务中配置 TypeSafe 提供商和评估能力"), + evaluationModel: modelSelector("modelService.evaluationModels").description("判断模型,请在模型服务中配置 TypeSafe 提供商和评估能力"), timeoutMs: Schema.number().min(100).max(30000).default(3000).description("判断超时(毫秒),失败后沿用原意愿"), historyLimit: Schema.natural().default(8).description("判断时参考的近期消息数"), interests: Schema.string().role("textarea").default("").description("角色兴趣,留空使用高兴趣关键词"), @@ -322,7 +323,7 @@ export const AgentBehaviorConfigSchema: Schema = Schema.int Schema.object({ backgroundTools: Schema.object({ enabled: Schema.boolean().default(false).description("允许模型提交支持后台执行的工具任务"), - allowedTools: Schema.dynamic("toolService.backgroundEligibleTools") + allowedTools: backgroundToolSelector() .default([...DEFAULT_BACKGROUND_TOOLS]) .description("允许后台执行的工具(取消勾选不影响普通调用)"), completion: Schema.union([ diff --git a/packages/core/src/extension/config.ts b/packages/core/src/extension/config.ts index dceeb4327..6cbec1843 100644 --- a/packages/core/src/extension/config.ts +++ b/packages/core/src/extension/config.ts @@ -1,5 +1,7 @@ import { Schema } from "koishi"; +import { extensionSelector } from "../shared/config-selectors"; + export interface ToolServiceConfig { extra?: Record; /** 高级选项 */ @@ -11,7 +13,7 @@ export interface ToolServiceConfig { } export const ToolServiceConfigSchema = Schema.object({ - extra: Schema.dynamic("toolService.availableExtensions").default({}), + extra: extensionSelector().default({}), advanced: Schema.object({ maxRetry: Schema.number().default(3).description("最大重试次数"), diff --git a/packages/core/src/model/config.ts b/packages/core/src/model/config.ts index 97dac8153..c2b31ea15 100644 --- a/packages/core/src/model/config.ts +++ b/packages/core/src/model/config.ts @@ -1,5 +1,6 @@ import { Schema } from "koishi"; +import { modelSelector, groupSelector } from "../shared/config-selectors"; import { ContextCapacityRow, ContextLimitConfig, contextCapacityRows, parseContextLimit } from "./context-limit"; /** 模型切换策略 */ @@ -270,7 +271,8 @@ export const ProviderConfigSchema: Schema = Schema.intersect([ ), ]) .collapse() - .description("提供商配置"); + .description("提供商配置") + .role("yib-entry"); export interface ModelServiceConfig { providers: ProviderConfig[]; @@ -292,13 +294,17 @@ export const ModelServiceConfigSchema: Schema = Schema.objec ]) .default(ModelSwitchingStrategy.Failover) .description("模型切换策略"), - models: Schema.array(Schema.dynamic("modelService.selectableModels")).required().description("此模型组包含的模型"), + models: Schema.array(modelSelector("modelService.selectableModels", true)).required().description("此模型组包含的模型"), }) .collapse() - .description("模型组"), + .description("模型组") + .role("yib-entry"), ).description("模型组,用于故障转移或分类。修改提供商或模型后,先启动/重载插件以更新可选模型"), task: Schema.object({ - [TaskType.Chat]: Schema.dynamic("modelService.availableGroups").description("聊天任务使用的模型组"), - [TaskType.Embedding]: Schema.dynamic("modelService.availableGroups").description("语义记忆生成文本嵌入(Embedding)时使用的模型组"), + [TaskType.Chat]: groupSelector().description("聊天任务使用的模型组"), + [TaskType.Embedding]: groupSelector().description("语义记忆生成文本嵌入(Embedding)时使用的模型组"), }).description("任务与模型组映射"), }); + +// Provider arrays retain this shared schema reference. +ModelConfigSchema.meta.role = "yib-entry"; diff --git a/packages/core/src/shared/config-selectors.ts b/packages/core/src/shared/config-selectors.ts new file mode 100644 index 000000000..a6f597565 --- /dev/null +++ b/packages/core/src/shared/config-selectors.ts @@ -0,0 +1,23 @@ +import { Schema } from "koishi"; + +/** Static controls remain editable before the instance registers its live choices. */ +export function modelSelector(name: string, required = false): Schema { + return Schema.union([ + Schema.object({ + providerName: Schema.string().required(required).description("提供商名称"), + modelId: Schema.string().required(required).description("模型 ID"), + }).required(), + Schema.const(undefined).hidden(), + ]).role("yib-dynamic", { name }); +} +export function groupSelector(): Schema { + return Schema.string().role("yib-dynamic", { name: "modelService.availableGroups" }); +} +export function backgroundToolSelector(): Schema { + return Schema.array(Schema.string()).role("yib-dynamic", { name: "toolService.backgroundEligibleTools" }); +} +export function extensionSelector(): Schema { + return Schema.dict(Schema.object({ enabled: Schema.boolean().description("启用此扩展") })) + .role("yib-dynamic", { name: "toolService.availableExtensions" }) + .description("扩展配置(扩展加载后显示完整选项)"); +} diff --git a/packages/core/tests/background-policy.spec.ts b/packages/core/tests/background-policy.spec.ts index 5c65a205e..1a9661585 100644 --- a/packages/core/tests/background-policy.spec.ts +++ b/packages/core/tests/background-policy.spec.ts @@ -263,7 +263,7 @@ it("exposes ordinary numeric willingness inputs in the serialized configuration" expect({ type: fields?.[name]?.type, meta: fields?.[name]?.meta }).toMatchObject({ type: "number", meta: { default: 0, min: 0, max: 1000000 } }); } expect({ type: background.dict.allowedTools?.type, meta: background.dict.allowedTools?.meta }).toMatchObject({ - type: "any", - meta: { role: "dynamic", extra: { name: "toolService.backgroundEligibleTools" } }, + type: "array", + meta: { role: "yib-dynamic", extra: { name: "toolService.backgroundEligibleTools" } }, }); }); diff --git a/packages/core/tests/config-lifecycle-rendering.spec.ts b/packages/core/tests/config-lifecycle-rendering.spec.ts new file mode 100644 index 000000000..a420f0238 --- /dev/null +++ b/packages/core/tests/config-lifecycle-rendering.spec.ts @@ -0,0 +1,73 @@ +import { renderToString } from "@vue/server-renderer"; +import { Schema } from "koishi"; +import { expect, it, vi } from "vitest"; +import { createSSRApp, defineComponent, h } from "vue"; +vi.mock("@koishijs/client", async () => ({ store: { schema: {} }, Schema: (await import("koishi")).Schema })); +import { ConfigSection } from "../client"; +import { dynamicField } from "../client/dynamic-field"; +import { invalidConfig } from "../client/validation"; +import { modelSelector, groupSelector, backgroundToolSelector } from "../src/shared/config-selectors"; + +it("keeps static model, group and tool controls available without a running instance", () => { + const model = modelSelector("models"); + expect(model.list![0].dict!.providerName.type).toBe("string"); + expect(model.list![0].dict!.modelId.type).toBe("string"); + expect(model(undefined)).toBeUndefined(); + expect(model({ providerName: "p", modelId: "m" })).toEqual({ providerName: "p", modelId: "m" }); + expect(groupSelector().type).toBe("string"); + expect(backgroundToolSelector().inner!.type).toBe("string"); +}); +it("marks required entries in nested arrays without rejecting optional selectors", () => { + const schema = Schema.object({ + providers: Schema.array(Schema.object({ name: Schema.string().required(), models: Schema.array(Schema.string()).required() })), + optional: modelSelector("models"), + }); + expect(invalidConfig(schema, { providers: [{ name: "", models: [] }] })).toBe(true); + expect(invalidConfig(schema, { providers: [{ name: "p", models: ["m"] }] })).toBe(false); +}); +it("keeps collapsed parent and child sections marked invalid", async () => { + const child = Schema.object({ name: Schema.string().required() }).description("child").role("yib-subsection").collapse(); + const parent = Schema.intersect([child]).description("parent").role("yib-section").collapse(); + const app = createSSRApp({ render: () => h(ConfigSection, { schema: parent, modelValue: {} }) }); + app.component( + "k-schema", + defineComponent({ + props: ["schema", "modelValue"], + setup: (props) => () => (props.schema.type === "intersect" ? h(ConfigSection, { schema: child, modelValue: props.modelValue }) : h("input")), + }), + ); + const html = await renderToString(app); + expect(html.match(/aria-invalid="true"/g)).toHaveLength(2); + expect(html.match(/aria-expanded="false"/g)).toHaveLength(2); + expect(html.match(/配置未完成或无效/g)).toHaveLength(2); +}); +it.each([false, true])("renders static fallback or hydrated live controls (live=%s)", async (live) => { + const schema = groupSelector().description("选择模型组"); + const component = dynamicField(() => (live ? { "modelService.availableGroups": JSON.parse(JSON.stringify(Schema.union(["a", "b"]))) } : {})); + const app = createSSRApp({ render: () => h(component, { schema, modelValue: "a", prefix: "task.chat." }) }); + app.component( + "k-schema", + defineComponent({ + props: ["schema", "prefix"], + setup: (props) => () => h("input", { "data-type": props.schema.type, "data-role": props.schema.meta.role ?? "", "data-prefix": props.prefix }), + }), + ); + const html = await renderToString(app); + expect(html).toContain(`data-type="${live ? "union" : "string"}"`); + expect(html).not.toContain("yib-dynamic"); + expect(html).toContain('data-prefix="task.chat."'); +}); + +it("marks an unconfigured provider list without changing backend defaults", () => { + const schema = Schema.object({ providers: Schema.array(Schema.object({ name: Schema.string() })) }); + expect(invalidConfig(schema, {})).toBe(true); + expect(invalidConfig(schema, { providers: [] })).toBe(true); + expect(invalidConfig(schema, { providers: [{ name: "p" }] })).toBe(false); +}); + +it("only requires an optional evaluator after its feature is enabled", () => { + const schema = Schema.object({ mode: Schema.union(["off", "observe", "adjust"]).default("off"), evaluationModel: modelSelector("models") }); + expect(invalidConfig(schema, { mode: "off" })).toBe(false); + expect(invalidConfig(schema, { mode: "observe" })).toBe(true); + expect(invalidConfig(schema, { mode: "observe", evaluationModel: { providerName: "p", modelId: "m" } })).toBe(false); +}); diff --git a/packages/core/tests/config-native-headings.spec.ts b/packages/core/tests/config-native-headings.spec.ts index 15ddac4d7..30aff4d47 100644 --- a/packages/core/tests/config-native-headings.spec.ts +++ b/packages/core/tests/config-native-headings.spec.ts @@ -1,66 +1,78 @@ +import { readdirSync, readFileSync } from "node:fs"; import { createRequire } from "node:module"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { renderToString } from "@vue/server-renderer"; -import { expect, it } from "vitest"; -import { createSSRApp, defineComponent, h } from "vue"; +import { Schema } from "koishi"; +import { expect, it, vi } from "vitest"; +import { createSSRApp, h } from "vue"; import { createI18n } from "vue-i18n"; - +vi.mock("@koishijs/client", async () => ({ store: { schema: {} }, Schema: (await import("koishi")).Schema })); +import apply from "../client"; import { Config } from "../src/config/config"; +import { modelSelector } from "../src/shared/config-selectors"; + +const assertTitles = (html: string) => { + const headings = [...html.matchAll(/]*>([\s\S]*?)<\/h[23]>/g)].map((match) => match[1].replace(/<[^>]*>/g, "")); + for (const section of Config.list!.filter((item) => item.meta.role === "yib-section")) + expect(headings.filter((text) => text.startsWith(String(section.meta.description)))).toHaveLength(1); +}; -it("renders each main heading once through the native Koishi fallback", async () => { +it("renders serialized configuration before and after client extension registration without duplicate headings", async () => { const require = createRequire(import.meta.url); const clientRequire = createRequire(require.resolve("@koishijs/client/lib")); - const { createServer, normalizePath } = clientRequire("vite"); + const { createServer } = clientRequire("vite"); const vue = clientRequire("@vitejs/plugin-vue"); const yaml = clientRequire("@maikolib/vite-plugin-yaml"); - const root = fileURLToPath(new URL("../../..", import.meta.url)); const server = await createServer({ - root, + root: fileURLToPath(new URL("../../..", import.meta.url)), configFile: false, plugins: [(vue.default ?? vue)(), (yaml.default ?? yaml)()], - server: { middlewareMode: true }, + server: { middlewareMode: true, hmr: false }, optimizeDeps: { noDiscovery: true }, }); try { const schemaRoot = path.dirname(require.resolve("schemastery-vue")); - const object = (await server.ssrLoadModule(normalizePath(path.join(schemaRoot, "extensions/object.vue")))).default; - const intersect = (await server.ssrLoadModule(normalizePath(path.join(schemaRoot, "extensions/intersect.vue")))).default; - const NativeSchema = defineComponent({ - props: ["schema", "modelValue", "extra", "prefix", "initial", "disabled"], - setup: (props) => () => - ["object", "intersect"].includes(props.schema.type) - ? h(props.schema.type === "object" ? object : intersect, props) - : h("input", { "data-prefix": props.prefix }), - }); - const app = createSSRApp({ render: () => h(NativeSchema, { schema: Config, modelValue: {}, prefix: "", extra: { foldable: false } }) }); - app.use(createI18n({ legacy: false, locale: "zh-CN", messages: { "zh-CN": {} } })); - app.component("k-schema", NativeSchema); - app.component("k-badge", { - setup: - (_props, { slots }) => - () => - h("span", slots.default?.()), - }); - app.component("k-markdown", { - props: ["source"], - render() { - return h("p", this.source); - }, - }); - for (const name of ["el-button", "el-tooltip", "el-collapse-transition"]) - app.component(name, { - setup: - (_props, { slots }) => - () => - h("div", slots.default?.()), + const { form } = await server.ssrLoadModule(require.resolve("schemastery-vue")); + const files = [schemaRoot, path.join(schemaRoot, "extensions")].flatMap((dir) => + readdirSync(dir) + .filter((file) => file.endsWith(".vue")) + .map((file) => path.join(dir, file)), + ); + const tags = new Set(files.flatMap((file) => [...readFileSync(file, "utf8").matchAll(/<(el-[\w-]+)/g)].map((match) => match[1]))); + const render = async (schema, modelValue, full = true) => { + const app = createSSRApp({ + render: () => h(full ? form.Form : form.Schema, { schema: new Schema(JSON.parse(JSON.stringify(schema))), modelValue }), }); - const html = await renderToString(app); - const headings = Config.list!.filter((section) => section.meta.role === "yib-section").map((section) => section.meta.description); - for (const title of headings) expect(html.split(String(title))).toHaveLength(2); - expect(html.split("日志设置")).toHaveLength(2); - expect(html).toContain('data-prefix="logging.local.enabled."'); + app.use(form); + app.use(createI18n({ legacy: false, locale: "zh-CN", messages: { "zh-CN": {} } })); + app.component("k-markdown", { + props: ["source"], + render() { + return h("p", this.source); + }, + }); + for (const name of tags) + app.component(name, { + setup: + (_props, { slots }) => + () => + h("div", slots.default?.()), + }); + return renderToString(app); + }; + + assertTitles(await render(Config, {})); + const offline = await render(modelSelector("unregistered-models"), undefined, false); + expect(offline).toContain("providerName"); + expect(offline).toContain("modelId"); + apply({ schema: (extension) => form.extensions.add(extension) }); + const mounted = await render(Config, { providers: [{ name: "", models: [] }] }); + assertTitles(mounted); + expect(mounted).toContain('aria-invalid="true"'); + expect(mounted).toContain("配置未完成或无效"); + expect(mounted).toContain("此项配置未完成或无效"); } finally { await server.close(); } diff --git a/packages/core/tests/config-section.spec.ts b/packages/core/tests/config-section.spec.ts index ef4eb0300..f2efaa703 100644 --- a/packages/core/tests/config-section.spec.ts +++ b/packages/core/tests/config-section.spec.ts @@ -1,19 +1,20 @@ import { renderToString } from "@vue/server-renderer"; import { Schema } from "koishi"; -import { expect, it } from "vitest"; +import { expect, it, vi } from "vitest"; + +vi.mock("@koishijs/client", async () => ({ store: { schema: {} }, Schema: (await import("koishi")).Schema })); import { createSSRApp, defineComponent, h } from "vue"; import apply, { ConfigSection } from "../client"; it("registers top-level sections and nested subsections independently", () => { const extensions: any[] = []; - apply({ extendSchema: (extension: unknown) => extensions.push(extension) }); - expect(extensions.map(({ type, role }) => `${type}:${role}`)).toEqual([ - "object:yib-section", - "intersect:yib-section", - "object:yib-subsection", - "intersect:yib-subsection", - ]); + apply({ schema: (extension: unknown) => extensions.push(extension) }); + expect( + extensions + .filter(({ role }) => role !== "yib-model-groups" && role !== "yib-dynamic" && role !== "yib-entry") + .map(({ type, role }) => `${type}:${role}`), + ).toEqual(["object:yib-section", "intersect:yib-section", "object:yib-subsection", "intersect:yib-subsection"]); }); it.each([false, true])("renders a subsection without a duplicate top-level heading (folded=%s)", async (collapsed) => {