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/2] =?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 ff5ff4dca8569005d72ada734e1550bc98054c5b Mon Sep 17 00:00:00 2001 From: Xian Xu Date: Wed, 28 Oct 2026 16:20:12 +0000 Subject: [PATCH 2/2] =?UTF-8?q?fix(agent):=20=E4=BF=9D=E7=95=99=E5=B7=B2?= =?UTF-8?q?=E5=87=86=E5=85=A5=E7=BB=AD=E6=8E=A5=E8=BD=AE=E6=AC=A1=E7=9A=84?= =?UTF-8?q?=E5=90=8E=E7=BB=AD=E5=BF=83=E8=B7=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../core/src/agent/heartbeat-processor.ts | 12 +- .../core/tests/continuation-cycle.spec.ts | 161 ++++++++++++++++++ 2 files changed, 170 insertions(+), 3 deletions(-) create mode 100644 packages/core/tests/continuation-cycle.spec.ts diff --git a/packages/core/src/agent/heartbeat-processor.ts b/packages/core/src/agent/heartbeat-processor.ts index 0334ff1a0..6fcba0a43 100644 --- a/packages/core/src/agent/heartbeat-processor.ts +++ b/packages/core/src/agent/heartbeat-processor.ts @@ -96,6 +96,9 @@ export class HeartbeatProcessor { } private async runTracedCycle(turnId: string, stimulus: AgentStimulus): Promise { + // Admission belongs to this cycle, not to every heartbeat or to the caller's + // reusable stimulus. Keep the initial context check before any model call. + const cycleStimulus = { ...stimulus } as AgentStimulus & { continuationRequired?: boolean }; let shouldContinueHeartbeat = true; let heartbeatCount = 0; let success = false; @@ -109,13 +112,16 @@ export class HeartbeatProcessor { success = true; }; const result = this.config.nativeToolCalling - ? await this.performNativeHeartbeat(turnId, stimulus, onReplySent) + ? await this.performNativeHeartbeat(turnId, cycleStimulus, onReplySent) : this.config.streamAction - ? await this.performSingleHeartbeatWithStreaming(turnId, stimulus, onReplySent) - : await this.performSingleHeartbeat(turnId, stimulus, onReplySent); + ? await this.performSingleHeartbeatWithStreaming(turnId, cycleStimulus, onReplySent) + : await this.performSingleHeartbeat(turnId, cycleStimulus, onReplySent); assertReplyTurn(); if (result) { + // A successful heartbeat has passed context admission. Its tools + // may have replaced/cleared the wait, or the wait may now expire. + cycleStimulus.continuationRequired = false; shouldContinueHeartbeat = result.continue; success = success || result.replySent; } else { diff --git a/packages/core/tests/continuation-cycle.spec.ts b/packages/core/tests/continuation-cycle.spec.ts new file mode 100644 index 000000000..1c8dda06a --- /dev/null +++ b/packages/core/tests/continuation-cycle.spec.ts @@ -0,0 +1,161 @@ +import { afterEach, expect, it, vi } from "vitest"; + +import { PromptContextBuilder } from "../src/agent/context-builder"; +import { matchContinuation } from "../src/agent/continuation"; +import { HeartbeatProcessor } from "../src/agent/heartbeat-processor"; +import { withReplyTurnGuard } from "../src/agent/reply-turn"; +import { Config } from "../src/config"; +import { loggingStub } from "./helpers/yesimbot"; + +// Run the real context/model/action loop: clearing the wait is a normal first action, +// while sending the answer belongs to the next heartbeat. +function cycleFixture(afterUpdate: () => void = () => {}) { + const config = Config({ heartbeat: 3, streamAction: false, nativeToolCalling: false, continuation: { enabled: true, mode: "trigger" } }); + const session: any = { + platform: "qq", + selfId: "bot", + channelId: "room", + userId: "alice", + elements: [], + stripped: {}, + bot: { platform: "qq", selfId: "bot" }, + }; + let working: any = { + unknown: false, + state: { + revision: 1, + topic: "pending", + openIssues: [], + sourceMessageIds: ["old"], + updatedAt: new Date().toISOString(), + followUp: { userIds: ["alice"], expiresAt: Date.now() + 60000 }, + }, + }; + const stimulus: any = { + type: "user_message", + session, + payload: { messageIds: ["new"] }, + continuationRequired: true, + continuation: matchContinuation(session, config.continuation, working), + }; + const deliveries: string[] = []; + let modelCalls = 0; + const model: any = { + hasVisionCapability: () => false, + chat: async () => ({ + text: JSON.stringify({ + thoughts: {}, + actions: + ++modelCalls === 1 + ? [{ function: "conversation_state_update", params: {} }] + : [{ function: "send_message", params: { content: "answer" } }], + request_heartbeat: modelCalls === 1, + }), + }), + }; + const world: any = { + buildWorldState: async () => ({ l1_working_memory: { processed_events: [], new_events: [] } }), + getConversationState: async () => working, + }; + const tool: any = { + getToolSchemas: () => [], + invoke: async (name: string, params: any) => { + if (name === "conversation_state_update") afterUpdate(); + else deliveries.push(params.content); + return { status: "success", result: {} }; + }, + }; + const logging = loggingStub(); + const contextBuilder = new PromptContextBuilder({} as any, config, { + model, + world, + tool, + logging, + asset: {} as any, + memory: { getMemoryBlocksForRendering: () => [] } as any, + }); + const processor = new HeartbeatProcessor({} as any, config, { + model, + world, + tool, + logging, + contextBuilder, + prompt: { render: async () => "context" } as any, + l1: { recordHeartbeat: async () => {}, recordThought: async () => {}, recordAction: async () => "action", recordObservation: async () => {} } as any, + }); + return { + processor, + stimulus, + deliveries, + world, + modelCalls: () => modelCalls, + clearWait: () => { + working = { ...working, state: { ...working.state, revision: 2, followUp: undefined } }; + }, + }; +} + +afterEach(() => vi.useRealTimers()); + +it("admits continuation once per cycle when its own state update clears the wait", async () => { + const fixture = cycleFixture(() => fixture.clearWait()); + expect(await fixture.processor.runCycle(fixture.stimulus)).toBe(true); + expect(fixture.deliveries).toEqual(["answer"]); + expect(fixture.modelCalls()).toBe(2); + expect(fixture.stimulus.continuationRequired).toBe(true); + // Reusing even the same stimulus must perform fresh admission. + expect(await fixture.processor.runCycle(fixture.stimulus)).toBe(false); + expect(fixture.modelCalls()).toBe(2); +}); + +it("allows an admitted cycle to answer after its waiting interval expires", async () => { + vi.useFakeTimers(); + const fixture = cycleFixture(() => vi.setSystemTime(Date.now() + 61000)); + expect(await fixture.processor.runCycle(fixture.stimulus)).toBe(true); + expect(fixture.deliveries).toEqual(["answer"]); + expect(await fixture.processor.runCycle(fixture.stimulus)).toBe(false); + expect(fixture.modelCalls()).toBe(2); +}); + +it.each(["replaced", "expired"])("rejects %s continuation before the first model call", async (reason) => { + vi.useFakeTimers(); + const fixture = cycleFixture(); + if (reason === "replaced") fixture.clearWait(); + else vi.setSystemTime(Date.now() + 61000); + expect(await fixture.processor.runCycle(fixture.stimulus)).toBe(false); + expect(fixture.modelCalls()).toBe(0); + expect(fixture.deliveries).toEqual([]); +}); + +it("still cancels an admitted cycle before the next heartbeat", async () => { + const controller = new AbortController(); + const fixture = cycleFixture(() => controller.abort()); + expect( + await withReplyTurnGuard( + () => true, + () => fixture.processor.runCycle(fixture.stimulus), + controller.signal, + ), + ).toBe(false); + expect(fixture.modelCalls()).toBe(1); + expect(fixture.deliveries).toEqual([]); +}); + +it("still aborts an admitted cycle when channel history is cleared", async () => { + let generation = 0; + let onClear: (() => void) | undefined; + const fixture = cycleFixture(() => { + generation++; + onClear?.(); + }); + fixture.world.l2_manager = { + getHistoryGeneration: () => generation, + watchHistory: (_target: unknown, listener: () => void) => { + onClear = listener; + return () => {}; + }, + }; + expect(await fixture.processor.runCycle(fixture.stimulus)).toBe(false); + expect(fixture.modelCalls()).toBe(1); + expect(fixture.deliveries).toEqual([]); +});