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/3] =?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/3] =?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/3] 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"]'); +});