diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 000000000..ccc027811 --- /dev/null +++ b/docs/configuration.md @@ -0,0 +1,62 @@ +# 核心插件配置 + +打开 YesImBot 核心插件的配置页,先按用途选择大类,再展开需要调整的功能。收起功能组不会清除尚未保存的修改。开关、数字输入、模型选择、表格和模板编辑框均可直接操作;修改完成后使用控制台的保存操作。 + +| 大类 | 可以调整什么 | 配置文件字段 | +| ------------ | ---------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 模型与连接 | 提供商地址与密钥、模型能力、模型组、聊天及嵌入任务分配 | `providers`、`modelGroups`、`task` | +| 对话与回复 | 响应频道、唤醒条件、新消息策略、回复暂停、发言意愿、参与保持、等待后续消息、接话判断、发送节奏 | `allowedChannels`、`prioritizeMentions`、`debounceMs`、`newMessageStrategy`、`deferredProcessingTime`、`replySuppression`、`base`、`attribute`、`interest`、`lifecycle`、`participation`、`continuation`、`typesafe`、`topics`、`extra.core_util.typing`、`extra.core_util.deliveryTimeoutMs` | +| 记忆与上下文 | 是否记录机器人自己的消息、输入预算、近期完整轮次、核心记忆文件、语义检索和长期日记 | `ignoreSelfMessage`、`contextInputBudgetTokens`、`l1_memory`、`coreMemoryPath`、`l2_memory`、`l3_memory` | +| 视觉与图片 | 视觉开关、附图数量与保留规则、辅助识图模型与超时、图片处理、图片占位符说明 | `enableVision`、`allowedImageTypes`、`maxImagesInContext`、`imageLifecycleCount`、`imageFollowUpWindowSeconds`、`imageFollowUpMaxTurns`、`detail`、`extra.core_util.vision`、`image`、`multiModalSystemTemplate` | +| 角色与提示词 | 系统和用户模板、扩展注入占位符、模板渲染选项 | `systemTemplate`、`userTemplate`、`injectionPlaceholder`、`maxRenderDepth` | +| 工具与任务 | 原生工具调用、动作纠正、单轮执行次数、后台任务、超时与重试、扩展工具开关 | `nativeToolCalling`、`nativeToolCorrectionRetries`、`streamAction`、`heartbeat`、`backgroundTools`、`advanced`、`extra` 中其余扩展设置 | +| 存储与维护 | 文件存储与下载、资源清理、历史保留、日志、错误上报、决策记录 | `storagePath`、`driver`、`assetEndpoint`、`maxFileSize`、`downloadTimeout`、`recoveryEnabled`、`autoClear`、`logLengthLimit`、`dataRetentionDays`、`cleanupIntervalSec`、`logging`、`errorReporting`、`decisionRecording` | + +## 图片设置 + +先在“模型与连接”的提供商中登记模型,并勾选该模型支持的视觉能力。模型能力描述该模型可以做什么;“视觉与图片”决定聊天时是否附图、如何处理图片。 + +“视觉开关与附图规则”控制直接发送给聊天模型的图片。“辅助识图模型与超时”设置图片描述工具使用的模型、细节程度及等待时间;聊天模型已经收到图片时,是否仍允许辅助识图由该处的独立开关控制。 + +辅助识图和发送节奏属于核心工具集。关闭“工具与任务 → 扩展工具开关与设置”中的核心工具集后,这两项设置暂不显示;重新启用后可继续调整原先填写的值。其他扩展的设置仍在各自的扩展工具项中。 + +## 模型与工具超时 + +模型请求的等待时间在“模型与连接 → 模型提供商 → 模型列表 → 超时策略”中设置。普通工具的默认超时和单工具覆盖在“工具与任务 → 工具超时与重试”中设置。后台任务另有自己的超时。 + +| 设置位置 | 作用 | +| ------------------------------- | --------------------------------------------------------------------------- | +| 视觉与图片 → 辅助识图模型与超时 | 辅助识图总超时;填 `0` 时按所选模型的超时、重试和准备时间计算 | +| 对话与回复 → 发送节奏与超时 | 发送总超时;填 `0` 时按分段数量、打字延迟和传输预算计算 | +| 工具与任务 → 工具超时与重试 | 普通工具默认等待 10000 毫秒;可按工具名指定覆盖值,覆盖值优先于工具自身预算 | +| 工具与任务 → 后台任务 | 后台执行同时受工具预算和后台任务总上限约束,取较短者 | + +只读工具失败后,模型可在本轮次数上限内调整查询或继续回复。消息发送等有副作用的操作不会自动重放;已经确认发送的消息会保留回执,结果不确定时也不会直接当作未发送。用户取消或新消息中断后,旧轮次不会继续执行。 + +## 历史清理与日记 + +清理指定会话时使用 `history.clear -t 平台:频道ID`。同一条命令里可以用逗号分隔多个目标。批量清理选项 `-a` 需单独使用,不能与 `-p`、`-c` 或 `-t` 混用。 + +`history.clear -a all` 会重置全部核心对话历史、意愿和等待中的对话状态,并取消相关旧任务。人物记忆扩展接入后,会同时清理可以证明属于自身的资料、来源、审计和总结队列。共享范围存在其他所有者,或者旧资料无法证明归属时,会保留并在回执中说明;不要把该回执理解为整个数据库已清空。配置和角色提示词不会被重置。 + +已经提交到远端的请求未必能撤回;本地会停止等待及重试,拒绝旧结果继续发送或写入。清理期间收到的新消息会在清理结束后重新校验处理。 + +自动日记失败后默认等待 30 秒再尝试,连续失败逐步延长,默认最多 300 秒。可在“记忆与上下文 → 长期日记”调整首次与最长等待时间;手动生成不受自动冷却限制。 + +## 手机上操作 + +先收起不用的大类,再展开当前功能。长表格可以在表格区域内横向滚动;数字、下拉选择和长文本输入会按屏幕宽度排列。 + +### 错误报告中的会话诊断 + +在「存储与维护 → 错误上报 → 错误报告的会话信息」选择报告内容。 + +| 配置值 | 报告内容 | +| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `off`(默认) | 沿用现有错误报告设置。 | +| `masked` | 附带同一机器人、同一会话的近期消息、意愿变化、调度、工具记录,以及本轮各次模型请求的提示词和原始响应。识别到的用户 ID 替换为「用户A」等别名,群聊与消息 ID 仅保留首字符和末三字符,例如 `1xxx111`。 | +| `raw` | 附带相同的会话诊断,保留原始会话标识和内容。 | + +两种会话模式都会过滤已知凭据、认证头和 Cookie。遮盖标识后,对话正文仍可能包含个人信息。选择模式前请确认上报地址和接收方。启用本地调试日志时,对应错误记录也会附上按所选模式处理过的会话诊断。 + +每个插件实例最多保留 30 分钟、2,048 条或 8 MiB 的近期记录。单次模型 HTTP 请求或响应最多收集 2 MiB,超限、异常中断或未读完时会在报告中标明。清理会话历史会同时丢弃内存中对应的诊断记录。 diff --git a/docs/decision-replay.md b/docs/decision-replay.md index 9c92f1dd2..5492d480a 100644 --- a/docs/decision-replay.md +++ b/docs/decision-replay.md @@ -17,7 +17,7 @@ decisionRecording: 记录按条数、UTF-8 字节数和保留时长限制,超过容量会移除较早写入的快照。过期记录在启动、追加、查询或刷新时清理。重启后恢复仍保留的记录;文件过大时流式读取,单行最多接受 `1 MiB`。版本不兼容、损坏、缺少必要字段或不完整的末行会明确警告并跳过。待写队列也受容量限制;队列满或写盘失败会发出警告,不阻断实时回复。 -管理员可在群聊或私聊中执行 `chat.decisions` 查看当前会话最近 10 条快照,或执行 `chat.decisions 30 --from 2026-09-30T00:00:00Z --to 2026-09-30T23:59:59Z` 按时间筛选。一次最多查询 100 条;发生裁剪或丢弃时,会显示历史不完整的提示。该指令只查看记录,不执行历史动作。 +管理员可在群聊或私聊中执行 `chat.decision` 查看当前会话的最近回复决策。启用本地决策记录后,用 `chat.decision --history` 查看最近 10 条快照,或执行 `chat.decision --history 30 --from 2026-09-30T00:00:00Z --to 2026-09-30T23:59:59Z` 按时间筛选。原有 `chat.decisions` 命令仍可使用。一次最多查询 100 条;发生裁剪或丢弃时,会显示历史不完整的提示。该指令只查看记录,不执行历史动作。 ## 运行回放 diff --git a/docs/feature-guide.md b/docs/feature-guide.md index 9c7d6fd79..d4b325786 100644 --- a/docs/feature-guide.md +++ b/docs/feature-guide.md @@ -4,20 +4,20 @@ YesImBot 的基础对话、回复调度、聊天历史和 L1/L2/L3 记忆由核 ## 按用途查找 -| 想做什么 | 功能归属 | 入口 | -| ---------------------------- | -------------------------- | ---------------------------------------------------- | -| 连接模型、分配对话与嵌入任务 | 核心:模型服务 | 配置页;`conf.check` 检查引用与声明 | -| 设置人格与长期核心记忆 | 核心:提示词、核心记忆文件 | 配置页中的提示词与核心记忆路径 | -| 暂停、恢复回复,查看抑制状态 | 核心:回复管理 | `chat.pause`、`chat.resume`、`chat.status` | -| 查看为什么回复或保持沉默 | 核心:决策诊断 | `chat.decision`;启用决策记录后使用 `chat.decisions` | -| 查看当前上下文和模型用量 | 核心:请求诊断 | `history.context`、`history.tokens` | -| 检索聊天原文、记忆片段或日记 | 核心:历史与记忆召回 | `history.recall` | -| 手动生成长期日记 | 核心:L3 日记 | `history.diary` | -| 统计、清理或备份历史 | 核心:历史管理 | `history.count`、`history.clear`、`history.backup` | -| 查看、关联和纠正人物身份 | 人物记忆扩展 | `people` 及其子指令 | -| 预约、取消或重试提醒 | 持久提醒扩展 | Agent 提醒工具;管理员使用 `reminder` 子指令 | -| 查看与管理模型可调用的工具 | 核心:工具与扩展 | `tool.list`、`tool.info`、`extension.list` | -| 查询好友、群和群成员名单 | OneBot 名单扩展 | `onebot.contacts` 及其子指令 | +| 想做什么 | 功能归属 | 入口 | +| ---------------------------- | -------------------------- | ------------------------------------------------------------- | +| 连接模型、分配对话与嵌入任务 | 核心:模型服务 | 配置页;`conf.check` 检查引用与声明 | +| 设置人格与长期核心记忆 | 核心:提示词、核心记忆文件 | 配置页中的提示词与核心记忆路径 | +| 暂停、恢复回复,查看抑制状态 | 核心:回复管理 | `chat.pause`、`chat.resume`、`chat.status` | +| 查看为什么回复或保持沉默 | 核心:决策诊断 | `chat.decision`;启用决策记录后使用 `chat.decision --history` | +| 查看当前上下文和模型用量 | 核心:请求诊断 | `history.context`、`history.tokens` | +| 检索聊天原文、记忆片段或日记 | 核心:历史与记忆召回 | `history.recall` | +| 手动生成长期日记 | 核心:L3 日记 | `history.diary` | +| 统计、清理或备份历史 | 核心:历史管理 | `history.count`、`history.clear`、`history.backup` | +| 查看、关联和纠正人物身份 | 人物记忆扩展 | `people` 及其子指令 | +| 预约、取消或重试提醒 | 持久提醒扩展 | Agent 提醒工具;管理员使用 `reminder` 子指令 | +| 查看与管理模型可调用的工具 | 核心:工具与扩展 | `tool.list`、`tool.info`、`extension.list` | +| 查询好友、群和群成员名单 | OneBot 名单扩展 | `onebot.contacts` 及其子指令 | 多数管理指令要求 Koishi 权限等级至少为 3。可用参数以当前安装版本的指令帮助为准。工具是 Agent 可以调用的能力,管理指令是用户在聊天中执行的操作,两者不一定同名或一一对应。 @@ -44,7 +44,7 @@ YesImBot 的基础对话、回复调度、聊天历史和 L1/L2/L3 记忆由核 | `people` | 按人物记忆模式作用于当前场景或共同记忆域;纠错或解绑可能影响域内其他关联场景 | | `reminder` | 仅管理当前机器人与会话的提醒,群聊、私聊及群归属分别核对;清历史不等于取消提醒 | -`history.clear` 不负责清除人物记忆插件的资料、来源与审计、持久提醒或模型用量统计;归属不明的旧 Agent 日志可能保留。需要处理这些数据时,应分别使用对应功能的管理入口。 +`history.clear -a all` 同时重置意愿和等待中的对话状态,并取消相关旧任务。已接入的人物记忆扩展会清理归属明确的资料、来源、审计和总结队列。共享归属或归属不明的数据可能保留,详见命令回执。持久提醒和模型用量统计由各自的管理命令处理。 ## 历史备份与恢复 diff --git a/docs/history-inspection.md b/docs/history-inspection.md index 7be42efd8..758a8075f 100644 --- a/docs/history-inspection.md +++ b/docs/history-inspection.md @@ -36,10 +36,9 @@ history.tokens --full --page 2 ```text history.tokens --reset -history.tokens --restart ``` -两个参数作用相同:重置当前实例的全部用量统计并开始新周期,不重启插件,不删除聊天历史或记忆。 +`--reset` 重置当前实例的全部用量统计并开始新周期,聊天历史、记忆和插件运行状态保持原样。原有 `--restart` 仍可使用。 不能与筛选、分页或展示参数混用。重置前发出的请求不会计入新周期;旧请求上下文快照同时清除。 ## 上下文 diff --git a/docs/prompt-templates.md b/docs/prompt-templates.md new file mode 100644 index 000000000..d116f2b79 --- /dev/null +++ b/docs/prompt-templates.md @@ -0,0 +1,36 @@ +# 提示词模板与扩展内容 + +系统预设可使用 `NATIVE_TOOL_CALLING` 区分本次请求的输出协议。开启原生工具时使用工具接口;切换到 JSON fallback 时,该值为 `false`。人格、语气和记忆规则放在条件分支外,两种模式都会保留。 + +```mustache +你的人格与交流规则…… +{{#NATIVE_TOOL_CALLING}} +通过原生工具接口执行动作,使用 send_message 发送回复。 +{{/NATIVE_TOOL_CALLING}} +{{^NATIVE_TOOL_CALLING}} +只输出包含 thoughts、actions 和 request_heartbeat 的 JSON 对象。 +{{/NATIVE_TOOL_CALLING}} +``` + +除 LF/CRLF 换行差异外,完全匹配旧版内置默认系统预设的配置,会在加载时自动使用新版默认预设。自定义预设保持原文;如果原生工具模式仍要求输出 JSON actions,请按上述分支调整。修改过的旧默认预设也属于自定义预设。 + +消息正文、记忆、工具结果、日程和人物资料中的 `{{…}}` 均按原文保留,不会再次展开。`maxRenderDepth` 仅为兼容旧配置保留,不再让动态内容递归渲染。 + +扩展的 `prompt.inject(name, priority, callback)` 回调应返回已经准备好的文字。需要组合可信模板时,可注册模板后使用 `injectTemplate`,把用户或模型产生的内容放进数据字段: + +```ts +prompt.registerTemplate("my-extension.summary", "当前安排:{{plan}}"); +prompt.injectTemplate("my-extension", 10, "my-extension.summary", async () => ({ + plan: await readCurrentPlan(), +})); +``` + +这里仅解释注册模板本身。即使 `plan` 包含双大括号或不完整的模板语法,也会保留为普通文字。不要把用户正文或模型返回值拼入注册模板的源码。 + +## 上下文裁剪与工具历史 + +默认请求不包含内部裁剪报告。完整估算、删除计数和超软预算原因可在服务端调试日志“上下文裁剪”中查看。原样保存的旧默认用户模板也不会继续输出报告;自定义模板明确引用 `CONTEXT_BUDGET` 时保留该兼容能力,意味着这些内部统计将发送给主模型。报告中的 token 数是保守估算,事件数也不等于聊天消息数。 + +软预算只裁剪可替代的世界状态,不修改系统提示词或核心记忆。固定内容与必要来源已超过预算时,请求仍保留它们,并在服务端报告超预算。旧工具轨迹先于近期用户对话让出空间;同一执行中的工具结果和关联回执作为同一因果组保留。 + +模型历史不会重放原始思考或工具参数中的 `inner_thoughts`。同一次调用的结果已有观察记录时,不再重复展示框架回执;管理员或独立工具回执仍保留简洁结果。原始审计日志保持完整。实际机器人消息保留在对话中,已能逐段核对的发送动作只保留消息编号引用;没有确认消息或发送失败时仍保留动作记录。 diff --git a/docs/superpowers/plans/2026-11-07-vision-delivery-config.md b/docs/superpowers/plans/2026-11-07-vision-delivery-config.md new file mode 100644 index 000000000..400b22eb0 --- /dev/null +++ b/docs/superpowers/plans/2026-11-07-vision-delivery-config.md @@ -0,0 +1,38 @@ +# Vision, tool delivery, and configuration reliability + +**Goal:** Preserve direct image input across a conversation, make execution deadlines match tool behavior, and organize configuration by user task. + +**Architecture:** Keep existing configuration storage paths and native Koishi field types. Image selection remains before context budgeting. Tool execution preserves confirmed delivery independently of its final promise, and recoverable reads return observations without automatically repeating side effects. + +## Constraints + +- Global direct-vision settings and the selected chat group's declared abilities determine direct image input. +- Internal heartbeats do not consume separate user-task image allowances. +- Related-image restoration respects conversation scope, history generation, input budget, and image limits. +- Auxiliary image description serves text-only or explicitly enabled weak-vision use. +- Cancellation, revocation, and shutdown still suppress late side effects. +- A timeout cannot erase confirmed receipts or authorize replay of uncertain delivery. +- Existing configuration values and unknown extension fields survive edits and folding. +- Configuration checks must include native Koishi controls; an unrelated HTML mock does not validate the console. + +## Tasks + +1. Image continuation: reproduce image input followed by an unquoted question and intervening tool heartbeats; retain bounded related sources and expose exclusion diagnostics. +2. Tool deadlines: reproduce a slow image request and a segmented message with typing delays; provide explicit effective deadlines and preserve confirmed/uncertain delivery state. +3. Recovery: feed read failures back to the model within heartbeat limits, stop dependent batch actions, and avoid automatic replay of writes. +4. Format correction: preserve the original persona, question, tool history, and images during bounded correction; honor zero retries and immediate failover. +5. Configuration: project existing fields into seven purpose groups with compact native controls and actual nested folding; keep dynamic enable branches and a unique editor per path. +6. Verification: run focused regressions, complete suite, build, lint, formatting, independent installed-package smoke tests, and actual console interaction where the environment permits it. + +## Review focus + +- Image input after a model switch or context compaction. +- Revocation or history clearing during image restoration and tool execution. +- Confirmed first segment with a blocked second segment, including segments inside one platform encoder. +- An uncertain platform response must never be described as definitely unsent. +- Disabled extensions, dynamic schema updates, and unknown configuration fields during save. +- Repeated invalid outputs must neither lose the original context nor create unbounded correction history. + +## Delivery + +Publish verified changes to the existing fork integration branch after independent review. Preserve its current remote head and verify the published source tree against the tested tree. diff --git a/docs/superpowers/plans/2026-11-09-conversation-audit-repairs.md b/docs/superpowers/plans/2026-11-09-conversation-audit-repairs.md new file mode 100644 index 000000000..51952bfe6 --- /dev/null +++ b/docs/superpowers/plans/2026-11-09-conversation-audit-repairs.md @@ -0,0 +1,77 @@ +# Conversation Audit Repairs Implementation Plan + +> **For agentic workers:** Execute each independently owned repair with a failing regression, a minimal implementation, and verification before integration. + +**Goal:** Repair confirmed conversation, reset, memory, delivery and diagnostic defects in the November 9 evidence. + +**Architecture:** A shared history-reset lifecycle coordinates the core and registered extensions. Other repairs preserve runtime configuration paths and remove diagnostic duplication while retaining message and tool provenance. + +**Tech Stack:** TypeScript, Koishi, Vitest, Yarn/Yakumo. + +**Spec:** `2026-11-09-conversation-reset-spec.md` in this directory. + +## Global Constraints + +- Preserve user settings, persona text, scope authorization, and unrelated domains. +- No real history clearing, external model calls, or private evidence publication during verification. +- Publish only tested code to the existing fork integration branch; no new PR. + +## Review Focus + +- A capture begun before clearing must not enqueue after clearing. +- Late responses and already accepted writes must not resurrect deleted data. +- Audit replay and persistent retries must not recreate purged profiles after restart. +- ID-only multipart receipts must not invent message content. +- Removing diagnostics must preserve required tool results and conversation context. + +## Tasks + +### 1. Core reset and L3 lifecycle + +Files: `world/commands.ts`, new reset coordination module, `agent/index.ts`, `agent/scheduler.ts`, `world/l3-archival-memory.ts`, corresponding tests. + +- [ ] Reproduce queued stimulus/assessment surviving clear and repeated L3 failure fanout. +- [ ] Register clear participants; synchronously invalidate old work before asynchronous preparation, drain writes and release maintenance state in finally. +- [ ] Reset transient agent state, cancel L3 work, add bounded failure cooldown and owner-level logging. +- [ ] Verify late results are rejected and fresh messages work after clear. + +### 2. Person memory + +Files: `packages/person-memory/src/{index,shared-runtime,worker,store,summary-queue,profile-tools,profile-prompt}.ts`, tests. + +- [ ] Reproduce list defaults, cached invalid candidate reuse, and clear during capture/model/commit. +- [ ] Join task 1 lifecycle through explicit participant registration; purge only owned scopes under the store serial barrier. +- [ ] Reset queues, timers and persisted candidates; validate/correct invalid output within a finite budget; declare existing profile limits in the generator prompt. +- [ ] Verify both modes, restart behavior, audit reconstruction and unrelated scope preservation. + +### 3. Model input and visuals + +Files: `agent/context-builder.ts`, `agent/context-packing.ts`, `agent/heartbeat-processor.ts` rendering, world history projection, prompt templates, tests. + +- [ ] Reproduce forced budget injection, duplicate observations and skipped recent images. +- [ ] Remove forced internal reporting, deduplicate diagnostic representations and retain bounded new image provenance. +- [ ] Verify final native/JSON requests, image scope and clear invalidation; preserve tool causality and user templates. + +### 4. Delivery provenance + +Files: `agent/reply-turn.ts`, `extension/builtin/core-util/index.ts`, `world/event-listener.ts`, tool event projection, tests. + +- [ ] Reproduce successful ID-only encoder output missing history content. +- [ ] Recover unambiguous sent content without attributing full content to ambiguous multipart receipts. +- [ ] Verify partial delivery, cancellation and read-back using actual encoder boundaries. + +### 5. Failure classification and maintenance + +Files: `model/service.ts`, native heartbeat error branch, `world/history-inspection.ts`, usage owner plumbing, decision journal, tests. + +- [ ] Reproduce deterministic HTTP rejection retries, native-call error misclassification and implicit dependency warnings. +- [ ] Classify terminal versus transient errors, retain bounded native correction, pass existing service dependencies explicitly. +- [ ] Evaluate stale-lock recovery using provable ownership; preserve conservative behavior for ambiguous locks. +- [ ] Verify transient retries, cancellation and no replay of side effects. + +### 6. Integration + +- [ ] Independently review merged lifecycle and source projection boundaries. +- [ ] Run full Vitest suite, build, client typecheck, lint and format checks. +- [ ] Verify packed installations and actual Koishi lifecycle; inspect console if settings change. +- [ ] Publish with expected-head guard and compare remote tree to tested tree. diff --git a/docs/superpowers/plans/2026-11-09-conversation-reset-spec.md b/docs/superpowers/plans/2026-11-09-conversation-reset-spec.md new file mode 100644 index 000000000..6f79cdd17 --- /dev/null +++ b/docs/superpowers/plans/2026-11-09-conversation-reset-spec.md @@ -0,0 +1,11 @@ +# Conversation audit repair specification + +Repair the confirmed defects observed in the November 9 conversation exports without editing user persona content or uploading private evidence. + +Full history clearing is a lifecycle boundary: invalidate old stimuli and asynchronous captures before waiting, cancel associated requests and retries, drain accepted writes, purge selected conversation-derived state, and reject late results. Reset willingness and transient scheduling state. Preserve settings and unrelated instances/domains; shared physical history retains its existing shared scope. Do not execute destructive commands against supplied backups or user data during development. + +Keep internal budget reports and duplicated diagnostic receipts out of default model input. Retain genuine conversational messages and necessary tool causality. Explicit custom template compatibility must not cause forced metadata injection. Recent visual sources must include images received while a reply was skipped and must remain bounded and scope checked. + +Confirmed sends with ID-only receipts require safe history content recovery; never fabricate per-ID content for ambiguous multipart or partial deliveries. Person list defaults must work without weakening selector validation. Invalid cached profile candidates must not be retried unchanged; model corrections remain bounded. Deterministic provider rejections must not be resent unchanged. Missing native calls require accurate errors. L3 failure cooldown and single-owner logging must prevent repeated local failures and warning fanout. + +Conversation drift and cache efficiency remain hypotheses. Validate final input composition and delayed addressed-to-others examples; do not claim model quality or cache improvements without evidence. diff --git a/docs/vision-context.md b/docs/vision-context.md new file mode 100644 index 000000000..57eeb6e91 --- /dev/null +++ b/docs/vision-context.md @@ -0,0 +1,20 @@ +# 对话中的图片 + +开启 `enableVision` 且当前模型组包含声明支持视觉的模型时,主请求会直接携带经过资源服务读取的图片。模型组仍按原有能力声明选择模型;只有文字说明、图片编号或失效资源时,不会把文字请求视为已经看过图片。 + +图片按以下顺序选择:本次用户消息中的图、明确引用的图、同一会话中同一用户最近发送的图、仍在生命周期内的其他历史图。去重后受 `maxImagesInContext` 限制,保留原有 MIME 白名单和图片处理设置。最近图来源会在上下文软预算裁剪时与当前问题一起保护;其他旧图仍可被裁剪。保护内容超过软预算时沿用原有超预算报告,不增加图片上限。 + +| 设置 | 默认值 | 含义 | +| ---------------------------- | -------- | ------------------------------------------------------------------------------ | +| `imageLifecycleCount` | 2 | 普通历史图片可参与的成功用户任务次数;同一任务中的工具调用和内部心跳只计一次 | +| `imageFollowUpWindowSeconds` | 600 | 同一用户无引用追问时保留最近图片的时间窗,0 关闭此保护 | +| `imageFollowUpMaxTurns` | 4 | 最近图片之后允许的用户消息数量,包含已记录但没有唤醒机器人的消息;0 关闭此保护 | +| `maxImagesInContext` | 沿用原值 | 单次主请求的图片数量上限 | + +上述两项追问设置为 0 只关闭额外近图保留;普通历史图片生命周期尚未用尽时仍可能附图。 + +当前发图与明确引用优先于普通历史图片的生命周期限制。无引用追问同时受时间窗和消息次数限制,不判断语义上是否仍在讨论图片。同一用户发出新图片后,最近图来源更新为这次图片;不同用户、平台、机器人和会话分别隔离。正在执行的同一用户任务保留其图片,不因连续内部心跳耗尽寿命。 + +原消息离开短期上下文时,可以通过已有的会话历史读取接口恢复该条来源,并复核用户、平台、频道和频道类型。清理历史后旧来源失效;权限检查仍由既有上下文与历史读取链执行。每个新的用户任务最多检查当前消息及此前 19 条同会话消息,从中选择该用户最新的图片;即使发图时机器人忙碌而跳过唤醒,也能在这个有限窗口内恢复来源。原有缓存存在时也会检查较新的来源。进程重启后沿用同一有限窗口,不会搜索所有旧图。跟踪缓存有固定容量,不保存额外的图片副本。 + +调试日志中的 `图片上下文` 提供选择数量、生命周期设置、图片上限及排除原因:主视觉开关关闭、组中无视觉模型、生命周期到期、最近图片时间或消息次数到期、数量上限、资源缺失、类型不支持、无效图片数据,以及来源恢复或资源读取失败。日志不包含消息正文、图片 URL、像素数据或原始异常内容。`selected` 表示本次构建的附图数量;资源读取失败仍会按既有请求错误处理,不能据此认为模型已经看到了图片。 diff --git a/packages/code-executor/README.md b/packages/code-executor/README.md index 2a52db5d7..36a8a12cc 100644 --- a/packages/code-executor/README.md +++ b/packages/code-executor/README.md @@ -1,25 +1,76 @@ -# YesImBot 扩展插件:代码执行器 (Code Executor) +# YesImBot 扩展插件:代码执行器 -[![npm](https://img.shields.io/npm/v/@yesimbot/koishi-plugin-code-executor.svg)](https://www.npmjs.com/package/@yesimbot/koishi-plugin-code-executor) -[![license](https://img.shields.io/npm/l/@yesimbot/koishi-plugin-code-executor.svg)](https://www.npmjs.com/package/@yesimbot/koishi-plugin-code-executor) +为 YesImBot 提供 Python 计算、数据处理和文件产物工具 `execute_python`。 -为 [YesImBot](https://github.com/YesWeAreBot/YesImBot) 提供一个**安全、隔离、功能强大**的 Python 代码执行环境。 +## 执行环境与兼容变化 -这个插件允许 AI 智能体编写并执行代码来完成复杂的任务,例如: +Python 执行已从宿主进程内的 Pyodide 改为每次调用新建的 Linux bubblewrap + CPython 环境。旧的 `pyodideVersion`、`cdnBaseUrl`、`allowedModules`、`packages` 不再控制执行。升级时必须准备独立根文件系统并配置 `sandboxRoot`;仅保留旧配置会返回 `EnvironmentError`,不会回退到宿主执行。 -- 进行精确的数学计算和数据分析 -- 调用外部 API 获取实时信息 -- 处理和转换文本或数据 -- 执行任何可以通过编程逻辑实现的复杂工作流 +需要 Linux、支持用户和网络等 namespace 的内核,以及支持 `--disable-userns` 和 `--size` 的 bubblewrap。部分 Docker、托管容器和系统策略禁止这些操作;启动探针失败时工具明确报错。Windows、macOS 请在符合条件的 Linux 环境部署。 -所有代码都在一个受限的沙箱环境中运行,确保了主系统的安全 +每次执行使用独立进程、只读根文件系统、独立 PID/网络/用户等 namespace,以及临时 `/workspace` 和 `/tmp`。不继承宿主环境变量,不挂载宿主项目或数据目录;网络访问不可用。模块只来自管理员预装的 CPython 环境,执行时不自动联网安装。该边界依赖内核、bubblewrap 和管理员准备的根文件系统,不构成对内核漏洞或所有资源耗尽方式的绝对保护。 -## ✨ 主要特性 +## 准备根文件系统 -- **🔒 安全至上**: 基于 `pyodide` 构建隔离沙箱,有效防止恶意代码访问文件系统、子进程或不安全的内置模块。 -- **🧩 无缝集成 YesImBot**: 作为 `yesimbot` 的扩展插件自动注册,其工具(`execute_python`)会直接添加到智能体的可用工具集中。 -- **📦 动态依赖管理**: 智能体可以通过 `import` 语法请求外部模块。插件会自动解析并安装在白名单内的依赖。 -- **⚙️ 高度可配置**: 管理员可以通过白名单精确控制允许使用的内置模块和第三方模块。 -- **⏱️ 超时与保护**: 对每一次代码执行都设置了超时限制,有效防止因死循环或长时间运行的任务而导致的资源耗尽。 -- **🤖 AI 友好反馈**: 当代码执行失败时,插件会返回清晰的错误信息和**可行动的修复建议**,引导 AI 智能体自我修正代码,提高任务成功率。 -- **⚡️ 结果缓存**: 可选的执行结果缓存功能,对于重复执行相同代码的场景,可以秒速返回结果,降低延迟和资源消耗。 +以下示例用于 Debian/Ubuntu 主机,命令由管理员执行。根文件系统不可包含机器人配置、密钥、SSH 凭据或其他宿主数据;不要使用 `/`、项目目录或已有业务系统的副本。不要以 root 身份运行机器人服务。 + +```bash +sudo apt-get update +sudo apt-get install bubblewrap debootstrap +sudo debootstrap --variant=minbase --include=python3,python3-numpy,python3-matplotlib bookworm /opt/yib-python-root https://deb.debian.org/debian +sudo mkdir -p /opt/yib-python-root/workspace /opt/yib-python-root/tmp /opt/yib-python-root/proc /opt/yib-python-root/dev +sudo chown -R root:root /opt/yib-python-root +sudo chmod 755 /opt/yib-python-root +``` + +按需要在这个根文件系统内安装其他发行版 Python 包;安装完成后再交给执行器使用。根文件系统本身对代码可读,因此其中任何数据都必须可公开给执行代码。管理员维护该环境的安全更新。 + +以运行机器人服务的同一用户验证主机支持情况: + +```bash +bwrap --unshare-all --unshare-user --disable-userns --die-with-parent --new-session --cap-drop ALL --uid 65534 --gid 65534 \ + --ro-bind /opt/yib-python-root / --proc /proc --dev /dev \ + --perms 1777 --size 67108864 --tmpfs /tmp --perms 1777 --size 67108864 --tmpfs /workspace \ + --chdir /workspace --clearenv --setenv PATH /usr/bin:/bin --setenv HOME /workspace \ + -- /usr/bin/python3 -I -c 'import os, numpy; assert os.getuid() == 65534; open("/workspace/probe", "w").close(); open("/tmp/probe", "w").close(); print("sandbox-ready")' +``` + +若出现 namespace、权限或缺少解释器错误,先修复部署环境;不要改用宿主根目录、共享网络或关闭隔离参数绕过错误。 + +## 配置 + +```yaml +engines: + python: + type: python + enabled: true + sandboxRoot: /opt/yib-python-root + bubblewrapPath: /usr/bin/bwrap + pythonPath: /usr/bin/python3 + timeout: 30000 + poolSize: 2 + memoryLimitMiB: 512 +shared: + maxOutputSize: 10240 +``` + +`poolSize` 限制同时运行的独立进程数量,不复用解释器。`timeout` 包含排队、计算和产物写入;超时、回复取消或插件停止会终止执行进程。虚拟内存上限为每进程限制,不是整个进程树的总内存配额;需要严格总资源配额时,应另在服务或容器层设置 cgroup 内存和进程数限制。 + +标准输出和错误输出分别截断到 `maxOutputSize` 个 Unicode 字符(上限 1 Mi 字符)。`/tmp` 和 `/workspace` 各限制为 64 MiB 临时空间,执行结束后清除。产物最多 16 个、合计 16 MiB;产物写入需要支持可取消资产创建的 YesImBot 核心版本,否则明确报错。 + +## 使用 + +```python +print(6 * 7) +__create_artifact__('result.txt', '计算结果:42') +``` + +最后一个表达式也会返回结果;使用 matplotlib 创建的图表会自动保存为图片产物。Python 异常、存储失败和超时通过工具错误结果返回。 + +## 部署验证 + +```bash +YIB_PYTHON_SANDBOX_ROOT=/opt/yib-python-root yarn vitest run packages/code-executor/tests/python-sandbox.spec.ts +``` + +此测试实际验证隔离环境中的宿主路径不可见、环境变量隔离、外网不可达、跨请求模块状态清除,以及 CPU 超时后仍能再次执行。未设置根目录时该部署测试会明确跳过;普通协议测试只执行受信任的 CPython 测试片段,不代表完成 OS 隔离验收。 diff --git a/packages/code-executor/package.json b/packages/code-executor/package.json index 31a7dc354..0a8763473 100644 --- a/packages/code-executor/package.json +++ b/packages/code-executor/package.json @@ -33,9 +33,6 @@ "publishConfig": { "access": "public" }, - "dependencies": { - "pyodide": "0.28.2" - }, "devDependencies": { "koishi": "^4.18.7", "koishi-plugin-yesimbot": "^3.0.2" @@ -46,8 +43,8 @@ }, "koishi": { "description": { - "zh": "为 YesImBot 提供一个安全、隔离的代码执行器", - "en": "Provides a secure and isolated code interpreter for the YesImBot" + "zh": "为 YesImBot 提供 Linux 隔离的 Python 执行工具(需配置独立根文件系统)", + "en": "Linux-isolated Python execution for YesImBot (requires a dedicated root filesystem)" }, "service": { "required": [ diff --git a/packages/code-executor/src/executors/python/index.ts b/packages/code-executor/src/executors/python/index.ts index 2a5845b22..8ec17cdb3 100644 --- a/packages/code-executor/src/executors/python/index.ts +++ b/packages/code-executor/src/executors/python/index.ts @@ -1,368 +1,244 @@ -import path from "path"; +import { realpath, stat } from "node:fs/promises"; import { Context, Logger, Schema } from "koishi"; import { AssetService, replyTurnSignal, ToolDefinition, withInnerThoughts } from "koishi-plugin-yesimbot"; -import { loadPyodide, PyodideAPI } from "pyodide"; -import type { PyProxy } from "pyodide/ffi"; import { SharedConfig } from "../../config"; -import { CodeExecutionResult, CodeExecutor, ExecutionArtifact, ExecutionError } from "../base"; +import { CodeExecutionResult, CodeExecutor } from "../base"; +import { runProcess } from "./process"; +import { PYTHON_RUNNER } from "./runner"; export interface PythonConfig { type: "python"; enabled: boolean; timeout?: number; poolSize?: number; - pyodideVersion?: string; - cdnBaseUrl?: string; - allowedModules?: string[]; - packages?: string[]; + sandboxRoot?: string; + bubblewrapPath?: string; + pythonPath?: string; + memoryLimitMiB?: number; customToolDescription?: string; } - -export const PythonConfigSchema: Schema = Schema.intersect([ - Schema.object({ - type: Schema.const("python").hidden().description("引擎类型"), - enabled: Schema.boolean().default(false).description("是否启用此引擎"), - }).description("Python 执行引擎"), - Schema.union([ - Schema.object({ - enabled: Schema.const(true).required(), - timeout: Schema.number().default(30000).description("代码执行的超时时间(毫秒)"), - poolSize: Schema.number().default(2).min(1).max(10).description("Pyodide 引擎池的大小,用于并发执行"), - pyodideVersion: Schema.string() - .pattern(/^\d+\.\d+\.\d+$/) - .default("0.28.2") - .description("Pyodide 的版本"), - cdnBaseUrl: Schema.union([ - "https://cdn.jsdelivr.net", - "https://fastly.jsdelivr.net", - "https://testingcf.jsdelivr.net", - "https://quantil.jsdelivr.net", - "https://gcore.jsdelivr.net", - "https://originfastly.jsdelivr.net", - Schema.string().role("link").description("自定义CDN"), - ]) - .default("https://fastly.jsdelivr.net") - .description("Pyodide 包下载镜像源"), - allowedModules: Schema.array(String) - .default(["matplotlib", "numpy", "pandas", "sklearn", "scipy", "requests"]) - .role("table") - .description("允许代码通过 import 导入的模块白名单"), - packages: Schema.array(String) - .default(["numpy", "pandas", "matplotlib", "scikit-learn"]) - .role("table") - .description("预加载到每个 Pyodide 实例中的 Python 包"), - customToolDescription: Schema.string() - .role("textarea", { rows: [2, 4] }) - .description("自定义工具描述,留空则使用默认描述"), - }), - Schema.object({}), - ]), -]) as Schema; - -class PyodideEnginePool { - private readonly logger: Logger; - private pool: PyodideAPI[] = []; - private waiting: Array<{ resolve: (engine: PyodideAPI) => void; reject: (error: unknown) => void; removeAbort: () => void }> = []; - private readonly maxSize: number; - private isInitialized = false; - private disposed = false; - - constructor( - private ctx: Context, - private config: PythonConfig, - private sharedConfig: SharedConfig, - ) { - // 为日志源添加特定前缀,方便区分 - this.logger = ctx.logger(`[执行器:Python:引擎池]`); - this.maxSize = config.poolSize ?? 0; - } - - private async createEngine(): Promise { - this.logger.info(`[创建实例] 开始创建新的 Pyodide 引擎实例...`); - const pyodide = await loadPyodide({ - // 确保依赖路径正确 - packageCacheDir: path.join(this.ctx.baseDir, this.sharedConfig.dependenciesPath, "pyodide"), - packageBaseUrl: `${this.config.cdnBaseUrl}/pyodide/v${this.config.pyodideVersion}/full/`, - }); - this.logger.info(`[创建实例] Pyodide 核心加载完成`); - - if (this.config.packages && this.config.packages.length > 0) { - const packageList = this.config.packages!.join(", "); - this.logger.info(`[创建实例] 准备加载预设包: ${packageList}`); - try { - await pyodide.loadPackage(this.config.packages); - this.logger.info(`[创建实例] 成功加载预设包: ${packageList}`); - } catch (error) { - this.logger.error(`[创建实例] 加载预设包失败: ${packageList}。错误: ${error.message}`); - // 抛出更具体的错误,方便上层捕获 - throw new Error(`Pyodide 引擎在加载包时创建失败: ${error.message}`); - } - } - this.logger.info("[创建实例] 新的 Pyodide 引擎实例已准备就绪"); - return pyodide; - } - - public async initialize(): Promise { - if (this.isInitialized || this.disposed) return; - this.logger.info(`[初始化] 开始初始化引擎池,目标大小: ${this.maxSize}`); - try { - // 并行创建所有引擎实例,以加快启动速度 - // const enginePromises = Array.from({ length: this.maxSize }, () => this.createEngine()); - // const engines = await Promise.all(enginePromises); - const engines = []; - for (let i = 0; i < this.maxSize; i++) { - engines.push(await this.createEngine()); - if (this.disposed) return; - } - - this.pool.push(...engines); - this.isInitialized = true; - this.logger.info(`[初始化] 引擎池初始化成功,已创建 ${this.pool.length} 个可用实例`); - } catch (error) { - this.logger.error(`[初始化] Pyodide 引擎池初始化失败!`, error); - this.isInitialized = false; // 确保状态正确 - // 将初始化错误向上抛出,让启动逻辑知道失败了 - throw error; - } - } - - public async acquire(signal?: AbortSignal): Promise { - signal?.throwIfAborted(); - if (this.disposed) throw new Error("Python executor stopped"); - if (!this.isInitialized) { - this.logger.error("[获取引擎] 尝试在未初始化的引擎池中获取引擎"); - throw new Error("Pyodide 引擎池未初始化或初始化失败"); - } - - if (this.pool.length > 0) { - const engine = this.pool.pop()!; - this.logger.debug(`[获取引擎] 从池中获取实例。池中剩余: ${this.pool.length}`); - return engine; - } - - this.logger.debug("[获取引擎] 池中无可用实例,进入等待队列..."); - return new Promise((resolve, reject) => { - const abort = () => { - this.waiting = this.waiting.filter((item) => item !== waiter); - reject(signal!.reason); - }; - const waiter = { resolve, reject, removeAbort: () => signal?.removeEventListener("abort", abort) }; - signal?.addEventListener("abort", abort, { once: true }); - this.waiting.push(waiter); - }); - } - - public release(engine: PyodideAPI): void { - if (this.disposed) return; - if (this.waiting.length > 0) { - const nextConsumer = this.waiting.shift()!; - this.logger.debug("[释放引擎] 引擎被直接传递给等待中的任务"); - nextConsumer.removeAbort(); - nextConsumer.resolve(engine); - } else { - this.pool.push(engine); - this.logger.debug(`[释放引擎] 引擎已返回池中。池中可用: ${this.pool.length}`); - } - } - - public dispose(): void { - this.disposed = true; - this.isInitialized = false; - this.pool = []; - for (const waiter of this.waiting.splice(0)) { - waiter.removeAbort(); - waiter.reject(new Error("Python executor stopped")); - } - } -} +export const PythonConfigSchema: Schema = Schema.object({ + type: Schema.const("python").hidden(), + enabled: Schema.boolean().default(false), + timeout: Schema.number().min(1).max(300000).default(30000).description("单次执行超时(毫秒,含排队和产物写入)"), + poolSize: Schema.number().min(1).max(10).default(2).description("最多同时运行的独立沙箱数"), + sandboxRoot: Schema.string().description("管理员准备的独立只读 Linux 根文件系统;禁止填写主机根目录"), + bubblewrapPath: Schema.string().default("/usr/bin/bwrap").description("宿主 bubblewrap 绝对路径"), + pythonPath: Schema.string().default("/usr/bin/python3").description("沙箱内 CPython 绝对路径"), + memoryLimitMiB: Schema.number().min(64).max(4096).default(512).description("每进程虚拟内存上限(MiB)"), + customToolDescription: Schema.string().role("textarea"), +}) as Schema; export class PythonExecutor implements CodeExecutor { readonly type = "python"; private readonly logger: Logger; - private readonly pool: PyodideEnginePool; private readonly assetService: AssetService; - private isReady = false; - private disposed = false; private readonly shutdown = new AbortController(); - + private root = ""; + private initializationError = "Python sandbox has not initialized"; + private isReady = false; + private active = 0; + private waiting: Array<() => void> = []; constructor( private ctx: Context, private config: PythonConfig, private sharedConfig: SharedConfig, ) { - this.logger = ctx.logger(`[执行器:Python]`); + this.logger = ctx.logger("[执行器:Python]"); this.assetService = ctx.yesimbot.asset; - this.pool = new PyodideEnginePool(ctx, config, sharedConfig); - ctx.on("ready", async () => { - if (config.enabled) { - this.logger.info("Python 执行器已启用,正在初始化..."); + if (!config.enabled || this.shutdown.signal.aborted) return; + try { + if (process.platform !== "linux") throw new Error("Python sandbox requires Linux and bubblewrap"); + if (!config.sandboxRoot) throw new Error("Configure sandboxRoot with a dedicated Python root filesystem; host execution is disabled"); + this.root = await realpath(config.sandboxRoot); + if (this.root === "/" || !(await stat(this.root)).isDirectory()) + throw new Error("sandboxRoot must be a dedicated directory, never the host root"); + const command = config.bubblewrapPath ?? "/usr/bin/bwrap"; + if (!command.startsWith("/") || !(config.pythonPath ?? "/usr/bin/python3").startsWith("/")) + throw new Error("Sandbox executable paths must be absolute"); + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(new Error("Python sandbox startup timed out")), 5000); try { - await this.pool.initialize(); - this.isReady = !this.disposed; - this.logger.info("Python 执行器初始化成功,已准备就绪"); - } catch (error) { - this.logger.error("Python 执行器启动失败,将不可用", error); - // isReady 保持 false + const signal = AbortSignal.any([controller.signal, this.shutdown.signal]); + const probe = await this.run( + 'import os; assert os.getuid() == 65534; open("/workspace/probe", "w").close(); open("/tmp/probe", "w").close(); print("sandbox-ready")', + signal, + ); + if (probe.stdout !== "sandbox-ready") throw new Error("Python sandbox startup probe failed"); + } finally { + clearTimeout(timer); } + this.isReady = !this.shutdown.signal.aborted; + } catch (error) { + this.initializationError = error instanceof Error ? error.message : String(error); + this.logger.error("Python sandbox unavailable: %s", this.initializationError); } }); ctx.on("dispose", () => { - this.disposed = true; this.isReady = false; this.shutdown.abort(new Error("Python executor stopped")); - this.pool.dispose(); }); } - - private _checkCodeSecurity(code: string): void { - this.logger.debug("[安全检查] 开始进行代码安全检查..."); - const forbiddenImports = ["os", "subprocess", "sys", "shutil", "socket", "http.server", "ftplib"]; - const userAllowed = new Set(this.config.allowedModules); - - const importRegex = /^\s*from\s+([\w.]+)\s+import|^\s*import\s+([\w.]+)/gm; - let match; - while ((match = importRegex.exec(code)) !== null) { - const moduleName = (match[1] || match[2]).split(".")[0]; - if (forbiddenImports.includes(moduleName) && !userAllowed.has(moduleName)) { - this.logger.warn(`[安全检查] 检测到禁用模块导入: ${moduleName}`); - throw new Error(`安全错误:不允许导入模块 '${moduleName}',因为它在禁止列表中`); - } - if (!userAllowed.has(moduleName)) { - // 如果需要严格白名单,可以解除此注释并抛出错误 - this.logger.warn(`[安全检查] 模块 '${moduleName}' 不在白名单中,但未被禁止`); - } - } - - if (code.includes("open(") && !code.includes("/workspace/")) { - this.logger.warn(`[安全检查] 检测到可能访问 /workspace 之外的文件。代码: ${code}`); + private async acquire(signal: AbortSignal): Promise<() => void> { + signal.throwIfAborted(); + const capacity = Math.min(10, Math.max(1, this.config.poolSize ?? 2)); + if (this.active >= capacity) + await new Promise((resolve, reject) => { + const wake = () => { + signal.removeEventListener("abort", abort); + resolve(); + }; + const abort = () => { + this.waiting = this.waiting.filter((item) => item !== wake); + reject(signal.reason); + }; + this.waiting.push(wake); + signal.addEventListener("abort", abort, { once: true }); + if (signal.aborted) abort(); + }); + // A wake transfers an existing lease rather than opening a race for it. + else this.active++; + if (signal.aborted) { + this.release(); + signal.throwIfAborted(); } - this.logger.debug("[安全检查] 代码安全检查通过"); + return () => this.release(); } - - private async _resetEngineState(engine: PyodideAPI): Promise { - this.logger.debug("[状态重置] 重置引擎状态,清理变量和文件..."); - const globals = engine.runPython("dict()") as PyProxy; - try { - engine.runPython( - ` -import sys, os -# 重置 matplotlib 状态 -try: - import matplotlib.pyplot as plt - plt.close('all') -except ImportError: - pass -# 清理工作区文件 -workspace = '/workspace' -if os.path.exists(workspace): - for item in os.listdir(workspace): - item_path = os.path.join(workspace, item) - if os.path.isfile(item_path): - os.remove(item_path) -`, - { globals }, - ); - } finally { - globals.destroy(); - } + private release() { + const next = this.waiting.shift(); + if (next) next(); + else this.active--; } - - private _parsePyodideError(error: any): ExecutionError { - const err = error instanceof Error ? error : new Error(String(error)); - let suggestion = "There might be a logical error in the code. Please review the logic and try again."; - - if (err.message.includes("TimeoutError")) { - return { - name: "TimeoutError", - message: `Code execution exceeded the time limit of ${this.config.timeout}ms.`, - stack: err.stack, - suggestion: "Your code took too long to run. Please optimize for performance, reduce complexity, or process a smaller amount of data.", - }; - } - - if (err.message.includes("SecurityError")) { - return { - name: "SecurityError", - message: err.message, - stack: err.stack, - suggestion: - "The code attempted a restricted operation. You can only import from the allowed modules list and access files within the '/workspace' directory. Please modify the code to comply with the security policy.", - }; + private async run(code: string, signal: AbortSignal): Promise { + const args = [ + "--unshare-all", + // --unshare-all only requests userns on a best-effort basis. + // --disable-userns and custom IDs require an explicit userns. + "--unshare-user", + "--disable-userns", + "--die-with-parent", + "--new-session", + "--cap-drop", + "ALL", + "--uid", + "65534", + "--gid", + "65534", + "--ro-bind", + this.root, + "/", + "--proc", + "/proc", + "--dev", + "/dev", + "--perms", + "1777", + "--size", + "67108864", + "--tmpfs", + "/tmp", + "--perms", + "1777", + "--size", + "67108864", + "--tmpfs", + "/workspace", + "--chdir", + "/workspace", + "--clearenv", + "--setenv", + "PATH", + "/usr/bin:/bin", + "--setenv", + "HOME", + "/workspace", + "--setenv", + "MPLCONFIGDIR", + "/workspace/.matplotlib", + "--", + this.config.pythonPath ?? "/usr/bin/python3", + "-I", + "-c", + PYTHON_RUNNER, + ]; + const input = JSON.stringify({ + code, + limit: Math.min(1048576, Math.max(0, this.sharedConfig.maxOutputSize ?? 10240)), + memory: Math.min(4096, Math.max(64, this.config.memoryLimitMiB ?? 512)) * 1024 * 1024, + }); + const response = JSON.parse(await runProcess(this.config.bubblewrapPath ?? "/usr/bin/bwrap", args, input, signal)); + if (response.error) + throw Object.assign(new Error(String(response.error.message)), { name: String(response.error.name), stack: String(response.error.stack) }); + if (typeof response.stdout !== "string" || typeof response.stderr !== "string" || !Array.isArray(response.artifacts)) + throw new Error("Invalid Python sandbox response"); + const limit = Math.min(1048576, Math.max(0, this.sharedConfig.maxOutputSize ?? 10240)); + for (const stream of ["stdout", "stderr"]) { + const points = Array.from(response[stream] as string); + if (points.length > limit && !response[stream].endsWith(`\n[Output truncated after ${limit} characters]`)) + response[stream] = points.slice(0, limit).join("") + `\n[Output truncated after ${limit} characters]`; } - - if (err.name === "PythonError") { - const messageLines = err.message.split("\n"); - const errorType = messageLines[messageLines.length - 2] || ""; - - if (errorType.startsWith("SyntaxError")) { - suggestion = "The code has a Python syntax error. Please check for typos, indentation issues, or incorrect grammar."; - } else if (errorType.startsWith("NameError")) { - suggestion = - "A variable or function was used before it was defined. Ensure all variables are assigned and all necessary libraries (from the allowed list) are imported correctly."; - } else if (errorType.startsWith("ModuleNotFoundError")) { - suggestion = `The code tried to import a module that is not available or not allowed. You can only import from this list: [${this.config.allowedModules!.join( - ", ", - )}].`; - } else if (errorType.startsWith("TypeError")) { - suggestion = - "An operation was applied to an object of an inappropriate type. Check the data types of the variables involved in the error line."; - } else if (errorType.startsWith("IndexError") || errorType.startsWith("KeyError")) { - suggestion = - "The code tried to access an element from a list or dictionary with an invalid index or key. Check if the index is within the bounds of the list or if the key exists in the dictionary."; - } + if (response.artifacts.length > 16) throw new Error("Sandbox artifact count exceeds 16"); + let artifactBytes = 0; + for (const artifact of response.artifacts) { + if (typeof artifact.content !== "string" || (artifactBytes += Buffer.byteLength(artifact.content, "base64")) > 16777216) + throw new Error("Sandbox artifact data exceeds 16 MiB"); } - - return { - name: err.name, - message: err.message, - stack: err.stack, - suggestion: suggestion, - }; + return response; } - getToolDefinition(): ToolDefinition { - // 工具描述通常面向 LLM,保持英文可能更佳,但可按需翻译 - const defaultDescription = `Executes Python code in a sandboxed WebAssembly-based environment (Pyodide). -- Python Version: 3.11 -- Pre-installed Libraries: ${this.config.packages!.join(", ") || "Python Standard Library"} -- Allowed Importable Modules: ${this.config.allowedModules!.join(", ")} -- Use print() to output results. The final expression's value is also returned. -- File I/O is restricted to a temporary '/workspace' directory. -- To generate files (like images, plots, data files), use the special function '__create_artifact__(fileName, content, type)'. It returns assets for download. For example, to save a plot, use matplotlib to save it to a BytesIO buffer and pass it to this function.`; - return { name: "execute_python", - description: this.config.customToolDescription || defaultDescription, - parameters: withInnerThoughts({ - code: Schema.string().required().description("The Python code to execute."), - }), + description: + this.config.customToolDescription || + `Executes Python in a fresh Linux OS sandbox without network access. Installed libraries depend on the administrator-provided root filesystem. Use print() or a final expression for output. Files in /workspace are temporary. Use __create_artifact__(fileName, text_or_bytes, type=None) to return files. Matplotlib figures are returned automatically.`, + parameters: withInnerThoughts({ code: Schema.string().required().description("The Python code to execute.") }), execute: async ({ code }) => this.execute(code), }; } - async execute(code: string): Promise { - if (!this.isReady) { - this.logger.warn("[执行] 由于执行器未准备就绪,已拒绝执行请求"); - return { - status: "error", - error: { - name: "EnvironmentError", - message: "Python executor is not ready or failed to initialize.", - suggestion: "Please wait a moment and try again, or contact the administrator.", - }, - }; - } - - this.logger.info("[执行] 收到新的代码执行请求"); + if (!this.isReady) return { status: "error", error: { name: "EnvironmentError", message: this.initializationError } }; const deadline = new AbortController(); - const turnSignal = replyTurnSignal(); - const signal = AbortSignal.any([this.shutdown.signal, deadline.signal, ...(turnSignal ? [turnSignal] : [])]); - const timer = setTimeout(() => deadline.abort(new Error("TimeoutError")), this.config.timeout); - const operation = this.executeInEngine(code, signal); + const turn = replyTurnSignal(); + const signal = AbortSignal.any([this.shutdown.signal, deadline.signal, ...(turn ? [turn] : [])]); + const timer = setTimeout( + () => + deadline.abort( + Object.assign(new Error(`Code execution exceeded the time limit of ${this.config.timeout ?? 30000}ms.`), { name: "TimeoutError" }), + ), + Math.min(300000, Math.max(1, this.config.timeout ?? 30000)), + ); + let release: (() => void) | undefined; let abort: (() => void) | undefined; + const operation = (async (): Promise => { + release = await this.acquire(signal); + try { + const output = await this.run(code, signal); + signal.throwIfAborted(); + if (output.artifacts.length && this.assetService.capabilities?.cancellableCreate !== 1) + throw new Error("Please update YesImBot core: cancellable asset creation is unavailable."); + const artifacts = []; + for (const artifact of output.artifacts) { + signal.throwIfAborted(); + if ( + typeof artifact.fileName !== "string" || + !artifact.fileName || + artifact.fileName.length > 255 || + /[/\\]/.test(artifact.fileName) || + typeof artifact.content !== "string" + ) + throw new Error("Invalid sandbox artifact"); + const assetId = await this.assetService.create(Buffer.from(artifact.content, "base64"), { filename: artifact.fileName }, { signal }); + signal.throwIfAborted(); + artifacts.push({ assetId, fileName: artifact.fileName }); + } + return { status: "success", result: { stdout: output.stdout, stderr: output.stderr, artifacts } }; + } finally { + release?.(); + } + })(); try { return await Promise.race([ operation, @@ -373,163 +249,11 @@ if os.path.exists(workspace): }), ]); } catch (error) { - return { status: "error", error: this._parsePyodideError(error) }; + const err = error instanceof Error ? error : new Error(String(error)); + return { status: "error", error: { name: err.name, message: err.message, stack: err.stack } }; } finally { clearTimeout(timer); if (abort) signal.removeEventListener("abort", abort); } } - - private async executeInEngine(code: string, signal: AbortSignal): Promise { - let engine: PyodideAPI | null = null; - let globals: PyProxy | undefined; - let result: any; - let acceptingArtifacts = true; - try { - signal.throwIfAborted(); - this._checkCodeSecurity(code); - - engine = await this.pool.acquire(signal); - signal.throwIfAborted(); - await this._resetEngineState(engine); - signal.throwIfAborted(); - globals = engine.runPython("dict()") as PyProxy; - globals.set("__name__", "__main__"); - - const artifacts: ExecutionArtifact[] = []; - const staged: Array<{ fileName: string; content: Buffer | string }> = []; - const pendingArtifacts: Array> = []; - const createArtifact = (fileName: PyProxy | string, content: PyProxy | ArrayBuffer | string) => { - const pending = (async () => { - signal.throwIfAborted(); - if (!acceptingArtifacts) throw new Error("Python execution already finished"); - const jsFileName = typeof fileName === "string" ? fileName : fileName.toJs(); - - let bufferContent: Buffer | string; - if (typeof content === "string" || content instanceof ArrayBuffer) { - bufferContent = content instanceof ArrayBuffer ? Buffer.from(content) : content; - } else { - const pyBuffer = content.toJs(); // PyProxy -> Uint8Array - bufferContent = Buffer.from(pyBuffer); - } - - // Snapshot Python buffers before their proxy or request globals are released. - staged.push({ fileName: jsFileName, content: typeof bufferContent === "string" ? bufferContent : Buffer.from(bufferContent) }); - })(); - pendingArtifacts.push(pending); - // Python may discard this promise; still observe failures immediately. - void pending.catch(() => {}); - return pending; - }; - - globals.set("__create_artifact__", createArtifact); - engine.FS.mkdirTree("/workspace"); - - const maxOutputSize = Number.isFinite(this.sharedConfig.maxOutputSize) ? Math.max(0, Math.floor(this.sharedConfig.maxOutputSize)) : 10240; - const collectOutput = (skipEmpty: boolean) => { - let content = ""; - let length = 0; - let hasChunk = false; - let truncated = false; - const appendText = (value: string) => { - // Iterate code points so an emoji is one character and cannot - // be cut in half. Retain only the bounded prefix of each chunk. - for (const character of value) { - if (length >= maxOutputSize) { - truncated = true; - return; - } - content += character; - length++; - } - }; - return { - append(value: string) { - if (truncated || (skipEmpty && !value)) return; - if (hasChunk) appendText("\n"); - if (!truncated) appendText(value); - hasChunk = true; - }, - value() { - return truncated ? `${content}\n[Output truncated after ${maxOutputSize} characters]` : content; - }, - }; - }; - const stdout = collectOutput(true); - const stderr = collectOutput(false); - engine.setStdout({ batched: (msg) => stdout.append(msg) }); - engine.setStderr({ batched: (msg) => stderr.append(msg) }); - - let finalCode = code; - if (code.includes("matplotlib")) { - this.logger.debug("[执行] 检测到 Matplotlib,将注入自动绘图保存逻辑"); - finalCode = ` -import matplotlib -matplotlib.use('Agg') -import io -import matplotlib.pyplot as plt - -# --- 用户代码开始 --- -${code} -# --- 用户代码结束 --- - -# 自动检查并保存所有打开的图表 -if plt.get_fignums(): - for i in plt.get_fignums(): - plt.figure(i) - buf = io.BytesIO() - plt.savefig(buf, format='png', bbox_inches='tight') - buf.seek(0) - __create_artifact__(f'chart_{i}.png', buf.getvalue(), 'image') - plt.close('all') # 关闭所有图表以释放内存 -`; - } - - // The engine remains leased until this operation settles, even when - // the caller's timeout or cancellation wins the outer race. - result = await engine.runPythonAsync(finalCode, { globals }); - acceptingArtifacts = false; - await Promise.all(pendingArtifacts); - signal.throwIfAborted(); - if (staged.length && this.assetService.capabilities?.cancellableCreate !== 1) { - throw new Error("Please update YesImBot core together with the code-executor plugin: cancellable asset creation is unavailable."); - } - for (const artifact of staged) { - signal.throwIfAborted(); - const assetId = await this.assetService.create(artifact.content, { filename: artifact.fileName }, { signal }); - signal.throwIfAborted(); - artifacts.push({ assetId, fileName: artifact.fileName }); - } - - let resultString = ""; - if (result !== undefined && result !== null) { - resultString = String(result); - } - stdout.append(resultString); - - this.logger.info("[执行] 代码执行成功"); - return { - status: "success", - result: { - stdout: stdout.value(), - stderr: stderr.value(), - artifacts: artifacts, - }, - }; - } catch (error) { - if (!signal.aborted) this.logger.error("[执行] 代码执行时发生错误", error); - return { - status: "error", - error: this._parsePyodideError(error), - }; - } finally { - acceptingArtifacts = false; - try { - if (result && typeof result.destroy === "function") result.destroy(); - globals?.destroy(); - } finally { - if (engine) this.pool.release(engine); - } - } - } } diff --git a/packages/code-executor/src/executors/python/process.ts b/packages/code-executor/src/executors/python/process.ts new file mode 100644 index 000000000..0889597e1 --- /dev/null +++ b/packages/code-executor/src/executors/python/process.ts @@ -0,0 +1,54 @@ +import { spawn } from "node:child_process"; + +// Bound IPC even if user code bypasses the Python output collectors. +export function runProcess(command: string, args: string[], input: string, signal: AbortSignal): Promise { + signal.throwIfAborted(); + return new Promise((resolve, reject) => { + const child = spawn(command, args, { detached: true, env: {}, stdio: ["pipe", "pipe", "pipe"] }); + const output: Buffer[] = []; + const diagnostics: Buffer[] = []; + let bytes = 0; + let diagnosticBytes = 0; + let failure: Error | undefined; + const kill = () => { + if (child.pid) { + try { + process.kill(-child.pid, "SIGKILL"); + } catch {} + } + }; + const abort = () => { + failure = signal.reason instanceof Error ? signal.reason : new Error("Python execution cancelled"); + kill(); + }; + signal.addEventListener("abort", abort, { once: true }); + child.stdout.on("data", (data: Buffer) => { + bytes += data.length; + if (bytes > 24 * 1024 * 1024) { + failure = new Error("Python sandbox response exceeds 24 MiB"); + kill(); + } else output.push(data); + }); + child.stderr.on("data", (data: Buffer) => { + if (diagnosticBytes < 16384) diagnostics.push(data.subarray(0, 16384 - diagnosticBytes)); + diagnosticBytes += data.length; + }); + child.on("error", (error) => { + failure = error; + }); + // Descendants can inherit the IPC pipes after the leader exits. Stop them + // before waiting for `close`, which waits for those same pipes to close. + child.on("exit", kill); + child.stdin.on("error", () => {}); + child.on("close", (code, terminated) => { + signal.removeEventListener("abort", abort); + // A successful leader must not leave descendants holding the namespace. + kill(); + if (failure) reject(failure); + else if (code !== 0) reject(new Error(`Python sandbox failed (${terminated ?? code}): ${Buffer.concat(diagnostics).toString()}`)); + else resolve(Buffer.concat(output).toString()); + }); + if (signal.aborted) abort(); + child.stdin.end(input); + }); +} diff --git a/packages/code-executor/src/executors/python/runner.ts b/packages/code-executor/src/executors/python/runner.ts new file mode 100644 index 000000000..54fb639ab --- /dev/null +++ b/packages/code-executor/src/executors/python/runner.ts @@ -0,0 +1,62 @@ +// The interpreter and all its modules belong to a disposable OS sandbox. +export const PYTHON_RUNNER = String.raw` +import ast, base64, contextlib, io, json, os, resource, sys, traceback +request = json.loads(sys.stdin.read()) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) +resource.setrlimit(resource.RLIMIT_AS, (request['memory'], request['memory'])) +resource.setrlimit(resource.RLIMIT_FSIZE, (16777216, 16777216)) +resource.setrlimit(resource.RLIMIT_NOFILE, (64, 64)) +resource.setrlimit(resource.RLIMIT_NPROC, (16, 16)) +limit = request['limit'] +class Output(io.TextIOBase): + def __init__(self): + self.text = '' + self.truncated = False + def write(self, value): + remaining = max(0, limit - len(self.text)) + self.text += value[:remaining] + self.truncated |= len(value) > remaining + return len(value) + def result(self): + text = self.text.rstrip('\n') + return text + ('\n[Output truncated after %d characters]' % limit if self.truncated else '') +stdout, stderr = Output(), Output() +artifacts = [] +artifact_bytes = 0 +def create_artifact(fileName, content, type=None): + global artifact_bytes + if not isinstance(fileName, str) or not fileName or len(fileName) > 255 or '/' in fileName or '\\' in fileName: + raise ValueError('Artifact filename must be a basename of at most 255 characters') + data = content.encode() if isinstance(content, str) else bytes(content) + artifact_bytes += len(data) + if len(artifacts) >= 16 or artifact_bytes > 16777216: + raise ValueError('Artifact limit exceeded (16 files / 16 MiB)') + artifacts.append({'fileName': fileName, 'content': base64.b64encode(data).decode()}) +namespace = {'__name__': '__main__', '__create_artifact__': create_artifact} +try: + with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): + code = request['code'] + if 'matplotlib' in code: + import matplotlib + matplotlib.use('Agg') + tree = ast.parse(code, '', 'exec') + expression = tree.body.pop() if tree.body and isinstance(tree.body[-1], ast.Expr) else None + exec(compile(tree, '', 'exec'), namespace) + if expression: + result = eval(compile(ast.Expression(expression.value), '', 'eval'), namespace) + if result is not None: + if stdout.text and not stdout.text.endswith('\n'): + stdout.write('\n') + stdout.write(str(result)) + if 'matplotlib.pyplot' in sys.modules: + plt = sys.modules['matplotlib.pyplot'] + for index in plt.get_fignums(): + buffer = io.BytesIO() + plt.figure(index).savefig(buffer, format='png', bbox_inches='tight') + create_artifact('chart_%s.png' % index, buffer.getvalue(), 'image') + plt.close('all') + response = {'stdout': stdout.result(), 'stderr': stderr.result(), 'artifacts': artifacts} +except BaseException as error: + response = {'error': {'name': error.__class__.__name__, 'message': str(error), 'stack': traceback.format_exc()[-16384:]}} +sys.__stdout__.write(json.dumps(response)) +`; diff --git a/packages/code-executor/src/index.ts b/packages/code-executor/src/index.ts index f3c043e29..50f56f0b7 100644 --- a/packages/code-executor/src/index.ts +++ b/packages/code-executor/src/index.ts @@ -50,7 +50,7 @@ export default class MultiEngineCodeExecutor { private registerExecutor(executor: CodeExecutor) { try { const toolDefinition = executor.getToolDefinition(); - const unregister = this.toolService.registerTool(toolDefinition); + const unregister = this.toolService.registerTool(toolDefinition, this.ctx); this.toolDisposers.push( typeof unregister === "function" ? unregister diff --git a/packages/code-executor/tests/python-fixture.ts b/packages/code-executor/tests/python-fixture.ts new file mode 100644 index 000000000..a1a10ed26 --- /dev/null +++ b/packages/code-executor/tests/python-fixture.ts @@ -0,0 +1,7 @@ +import { runProcess } from "../src/executors/python/process"; +import { PYTHON_RUNNER } from "../src/executors/python/runner"; + +export async function python(code: string, limit = 1024, signal = new AbortController().signal) { + // Protocol tests execute trusted fixture code directly; this is not a sandbox. + return JSON.parse(await runProcess("/usr/bin/python3", ["-I", "-c", PYTHON_RUNNER], JSON.stringify({ code, limit, memory: 512 * 1024 * 1024 }), signal)); +} diff --git a/packages/code-executor/tests/python-lifecycle.spec.ts b/packages/code-executor/tests/python-lifecycle.spec.ts index 011784bde..d79718774 100644 --- a/packages/code-executor/tests/python-lifecycle.spec.ts +++ b/packages/code-executor/tests/python-lifecycle.spec.ts @@ -1,332 +1,108 @@ -import { loadPyodide } from "pyodide"; -import { afterEach, describe, expect, it, vi } from "vitest"; +import { withReplyTurn } from "koishi-plugin-yesimbot"; +import { describe, expect, it, vi } from "vitest"; -import { withReplyTurn } from "../../core/src/agent/reply-turn"; -import { AssetService } from "../../core/src/asset/service"; import { PythonExecutor } from "../src/executors/python"; +import { python } from "./python-fixture"; const logger = { debug() {}, info() {}, warn() {}, error() {} }; -function deferred() { - let resolve!: (value: T | PromiseLike) => void; - let reject!: (error: unknown) => void; - const promise = new Promise((yes, no) => { - resolve = yes; - reject = no; - }); - return { promise, resolve, reject }; -} -function fixture(engine: any, create: (...args: any[]) => Promise = vi.fn<(...args: any[]) => Promise>(async () => "asset"), timeout = 1000) { +function fixture(timeout = 3000, create = vi.fn<(...args: any[]) => Promise>(async () => "asset")) { const hooks: Record any> = {}; - const ctx: any = { - baseDir: "/tmp", - logger: () => logger, - yesimbot: { asset: { create, capabilities: { cancellableCreate: 1 } } }, - on: (event: string, callback: () => any) => { - hooks[event] = callback; - }, - }; - const executor = new PythonExecutor(ctx, { enabled: true, type: "python", poolSize: 1, allowedModules: [], packages: [], timeout }, { - maxOutputSize: 1024, - dependenciesPath: "unused", - } as any); - const pool = (executor as any).pool; - pool.createEngine = async () => engine; - return { executor, pool, hooks, create }; + const executor = new PythonExecutor( + { + logger: () => logger, + yesimbot: { asset: { create, capabilities: { cancellableCreate: 1 } } }, + on: (name: string, fn: () => any) => (hooks[name] = fn), + } as any, + { type: "python", enabled: true, poolSize: 1, timeout }, + { maxOutputSize: 1024 } as any, + ); + // Lifecycle and process termination are tested independently of the OS sandbox, + // whose real deployment contract is covered by python-sandbox.spec.ts. + Object.assign(executor, { isReady: true, run: (code: string, signal: AbortSignal) => python(code, 1024, signal) }); + return { executor, hooks, create }; } -function mockEngine(run: (globals: any) => Promise) { - let globals: any; - return { - globals: { - set(key: string, value: any) { - (globals ??= new Map()).set(key, value); - }, - delete() {}, - }, - FS: { mkdirTree() {} }, - runPython(code: string) { - if (code === "dict()") - return { - set(key: string, value: any) { - this[key] = value; - }, - destroy() {}, - }; - }, - setStdout() {}, - setStderr() {}, - runPythonAsync(_code: string, options?: any) { - return run(options?.globals ?? Object.fromEntries(globals ?? [])); - }, - }; -} -afterEach(() => vi.useRealTimers()); - describe("Python request lifecycle", () => { - it("isolates real Pyodide globals across successful and failed requests", async () => { - const engine = await loadPyodide(); - const f = fixture(engine); - await f.hooks.ready(); - expect((await f.executor.execute("marker = 'private'\nNone")).status).toBe("success"); - const next = await f.executor.execute("globals().get('marker', 'clean')"); - expect(next.result.stdout).toBe("clean"); - expect((await f.executor.execute("failed_marker = 'private'\nraise ValueError('expected')")).status).toBe("error"); - expect((await f.executor.execute("globals().get('failed_marker', 'clean')")).result.stdout).toBe("clean"); - await f.hooks.dispose(); + it("externally terminates CPU-bound Python without blocking the JS event loop", async () => { + const f = fixture(100); + let ticked = false; + const timer = setTimeout(() => (ticked = true), 10); + const start = Date.now(); + const result = await f.executor.execute("while True:\n pass"); + clearTimeout(timer); + expect(ticked).toBe(true); + expect(result.error.name).toBe("TimeoutError"); + expect(Date.now() - start).toBeLessThan(1500); + // Give interpreter startup a normal budget when checking recovery under CI load. + (f.executor as any).config.timeout = 3000; + expect(await f.executor.execute("40 + 2")).toMatchObject({ status: "success", result: { stdout: "42" } }); + f.hooks.dispose(); }); - it("keeps a timed-out engine occupied until its original execution settles", async () => { - const first = deferred(); - let calls = 0; - const f = fixture( - mockEngine(async () => { - if (++calls === 1) await first.promise; - return "ok"; - }), - undefined, - 10, - ); - await f.hooks.ready(); - expect((await f.executor.execute("first")).error.name).toBe("TimeoutError"); - expect(f.pool.pool).toHaveLength(0); - const second = f.executor.execute("second"); - await Promise.resolve(); - expect(calls).toBe(1); - first.resolve(); - expect((await second).status).toBe("success"); - expect(calls).toBe(2); - await f.hooks.dispose(); + it("creates fresh builtins and module state for every request", async () => { + const f = fixture(); + expect((await f.executor.execute("import builtins\nbuiltins.private_marker = 42")).status).toBe("success"); + expect((await f.executor.execute("import builtins\ngetattr(builtins, 'private_marker', 'clean')")).result.stdout).toBe("clean"); + expect((await f.executor.execute("import builtins\nbuiltins.failure_marker = 42\nraise ValueError('expected')")).status).toBe("error"); + expect((await f.executor.execute("import builtins\ngetattr(builtins, 'failure_marker', 'clean')")).result.stdout).toBe("clean"); + f.hooks.dispose(); }); - it("disposal releases both a running caller and a caller waiting for an engine", async () => { - const first = deferred(); - const entered = deferred(); - const f = fixture( - mockEngine(async () => { - entered.resolve(); - await first.promise; - }), - ); - await f.hooks.ready(); - const running = f.executor.execute("first"); - await entered.promise; - const waiting = f.executor.execute("second"); - await f.hooks.dispose(); - const settled = await Promise.race([Promise.all([running, waiting]), new Promise((r) => setTimeout(() => r(null), 25))]); - first.resolve(); - expect(settled).not.toBeNull(); - expect(settled?.map((x) => x.status)).toEqual(["error", "error"]); - await Promise.resolve(); - expect(f.pool.pool).toHaveLength(0); + it.each(["cancel", "dispose"])("terminates active and queued calls on %s", async (action) => { + const f = fixture(); + const turn = new AbortController(); + const run = () => + withReplyTurn( + () => true, + () => f.executor.execute("while True:\n pass"), + turn.signal, + ); + const first = run(), + second = run(); + await new Promise((resolve) => setTimeout(resolve, 50)); + if (action === "cancel") turn.abort(); + else f.hooks.dispose(); + expect((await Promise.all([first, second])).map((result) => result.status)).toEqual(["error", "error"]); + await new Promise((resolve) => setTimeout(resolve, 50)); + expect((f.executor as any).active).toBe(0); + expect((f.executor as any).waiting).toHaveLength(0); + f.hooks.dispose(); }); - it("waits for an asynchronous artifact write before returning success", async () => { - const engine = await loadPyodide(); - const write = deferred(); - const entered = deferred(); - const f = fixture( - engine, - vi.fn<(...args: any[]) => Promise>(async () => { - entered.resolve(); - return write.promise; - }), - ); - await f.hooks.ready(); - let settled = false; - const output = f.executor.execute("__create_artifact__('hello.txt', 'hello')\nNone").then((x) => { - settled = true; - return x; + it("awaits artifact persistence and reports storage errors", async () => { + const create = vi.fn<(...args: any[]) => Promise>(async () => { + throw new Error("storage failed"); }); - await entered.promise; - await new Promise((r) => setTimeout(r, 10)); - expect(settled).toBe(false); - write.resolve("asset"); - expect((await output).result.artifacts).toEqual([{ assetId: "asset", fileName: "hello.txt" }]); - await f.hooks.dispose(); - }); - it("reports an artifact write failure instead of a successful empty receipt", async () => { - const engine = await loadPyodide(); - const f = fixture( - engine, - vi.fn<(...args: any[]) => Promise>(async () => { - throw new Error("storage failed"); - }), - ); - await f.hooks.ready(); - const output = await f.executor.execute("__create_artifact__('hello.txt', 'hello')\nNone"); - expect(output.status).toBe("error"); - expect(output.error.message).toContain("storage failed"); - await f.hooks.dispose(); + const f = fixture(3000, create); + const result = await f.executor.execute("__create_artifact__('hello.txt', 'hello')"); + expect(result.error.message).toContain("storage failed"); + expect(create).toHaveBeenCalledOnce(); + expect(create.mock.calls[0][2].signal).toBeInstanceOf(AbortSignal); + f.hooks.dispose(); }); - it.each(["cancel", "dispose"])("does not persist a staged artifact after %s", async (action) => { - const blocked = deferred(); - const entered = deferred(); - const f = fixture( - mockEngine(async (globals) => { - await globals.__create_artifact__("hello.txt", "hello"); - entered.resolve(); - await blocked.promise; - }), - ); - await f.hooks.ready(); - const turn = new AbortController(); - const output = withReplyTurn( - () => true, - () => f.executor.execute("artifact"), - turn.signal, - ); - await entered.promise; - if (action === "cancel") turn.abort(); - else await f.hooks.dispose(); - blocked.resolve(); - expect((await output).status).toBe("error"); + it("does not persist staged files from a cancelled execution", async () => { + const f = fixture(100); + const result = await f.executor.execute("__create_artifact__('hello.txt', 'hello')\nwhile True:\n pass"); + expect(result.error.name).toBe("TimeoutError"); expect(f.create).not.toHaveBeenCalled(); - await f.hooks.dispose(); + f.hooks.dispose(); }); - it("removes a cancelled engine waiter without affecting the running request", async () => { - const blocked = deferred(), - entered = deferred(); - let calls = 0; - const f = fixture( - mockEngine(async () => { - if (++calls === 1) { - entered.resolve(); - await blocked.promise; - } - return "ok"; - }), + it("cancels a pending asset write with the turn signal", async () => { + let entered!: () => void; + const started = new Promise((resolve) => (entered = resolve)); + const create = vi.fn<(...args: any[]) => Promise>( + (_data: any, _meta: any, options: any) => + new Promise((_resolve, reject) => { + entered(); + options.signal.addEventListener("abort", () => reject(options.signal.reason), { once: true }); + }), ); - await f.hooks.ready(); - const running = f.executor.execute("first"); - await entered.promise; - const turn = new AbortController(); - const waiting = withReplyTurn( - () => true, - () => f.executor.execute("waiting"), - turn.signal, - ); - expect(f.pool.waiting).toHaveLength(1); - turn.abort(); - expect((await waiting).status).toBe("error"); - expect(f.pool.waiting).toHaveLength(0); - blocked.resolve(); - expect((await running).status).toBe("success"); - expect((await f.executor.execute("healthy")).status).toBe("success"); - expect(calls).toBe(2); - await f.hooks.dispose(); - }); - it.each(["cancel", "dispose"])("rolls back a real AssetService write in progress during %s", async (action) => { - const entered = deferred(), - blocked = deferred(), - rolledBack = deferred(); - const files = new Map(), - rows = new Map(); - const asset = Object.create(AssetService.prototype); - Object.assign(asset, { - logger, - _getSourceBuffer: async (data: Buffer) => ({ data, type: "text/plain" }), - storage: { - write: async (id: string, data: Buffer) => { - files.set(id, data); - }, - delete: async (id: string) => { - files.delete(id); - rolledBack.resolve(); - }, - }, - ctx: { - database: { - get: async () => [], - upsert: async (_table: any, data: any[]) => { - for (const row of data) rows.set(row.id, row); - entered.resolve(); - await blocked.promise; - }, - remove: async (_table: any, query: any) => { - rows.delete(query.id); - }, - }, - }, - }); - const f = fixture( - mockEngine(async (globals) => { - await globals.__create_artifact__("hello.txt", "hello"); - }), - asset.create.bind(asset), - ); - await f.hooks.ready(); - const turn = new AbortController(); - const output = withReplyTurn( + const f = fixture(3000, create as any); + const controller = new AbortController(); + const running = withReplyTurn( () => true, - () => f.executor.execute("artifact"), - turn.signal, + () => f.executor.execute("__create_artifact__('hello.txt', 'hello')"), + controller.signal, ); - await entered.promise; - if (action === "cancel") turn.abort(); - else await f.hooks.dispose(); - expect((await output).status).toBe("error"); - blocked.resolve(); - await rolledBack.promise; - expect(files.size).toBe(0); - expect(rows.size).toBe(0); - await f.hooks.dispose(); - }); - it.each([false, true])("runs the generated matplotlib script with figures=%s", async (figures) => { - const engine = await loadPyodide(); - // Use real Python syntax/execution and BytesIO, with only plotting stubbed - // so this regression test never downloads external Python packages. - engine.runPython(` -import sys, types -matplotlib = types.ModuleType('matplotlib') -matplotlib.use = lambda _: None -pyplot = types.ModuleType('matplotlib.pyplot') -pyplot.get_fignums = lambda: ${figures ? "[1]" : "[]"} -pyplot.figure = lambda _: None -pyplot.savefig = lambda buf, **kwargs: buf.write(b'png') -pyplot.close = lambda _: None -matplotlib.pyplot = pyplot -sys.modules['matplotlib'] = matplotlib -sys.modules['matplotlib.pyplot'] = pyplot -`); - const f = fixture(engine); - await f.hooks.ready(); - const output = await f.executor.execute("import matplotlib.pyplot as plt\nprint('plot')"); - expect(output.error).toBeUndefined(); - expect(output.status).toBe("success"); - expect(output.result.stdout).toBe("plot"); - expect(output.result.artifacts).toHaveLength(figures ? 1 : 0); - const written = vi - .mocked(f.create) - .mock.calls.map(([data, metadata, options]) => [data.toString(), metadata.filename, options.signal instanceof AbortSignal]); - expect(written).toEqual(figures ? [["png", "chart_1.png", true]] : []); - await f.hooks.dispose(); - }); - it("preserves the main-module name in each isolated real Python script", async () => { - const engine = await loadPyodide(); - const f = fixture(engine); - await f.hooks.ready(); - const output = await f.executor.execute("if __name__ == '__main__':\n print('main')\nclass Example:\n pass\nprint(Example.__module__)"); - expect(output.result.stdout).toBe("main\n__main__"); - await f.hooks.dispose(); - }); - it("rejects artifacts on an older core before calling its uncancellable asset create", async () => { - const f = fixture( - mockEngine(async (globals) => { - await globals.__create_artifact__("hello.txt", "hello"); - }), - ); - delete (f.executor as any).assetService.capabilities; - await f.hooks.ready(); - const output = await f.executor.execute("artifact"); - expect(output.status).toBe("error"); - expect(output.error.message).toContain("update YesImBot core"); - expect(f.create).not.toHaveBeenCalled(); - await f.hooks.dispose(); - }); - it("keeps calculations without artifacts available on an older core", async () => { - const f = fixture(mockEngine(async () => 42)); - delete (f.executor as any).assetService.capabilities; - await f.hooks.ready(); - const output = await f.executor.execute("calculation"); - expect(output.status).toBe("success"); - expect(output.result.stdout).toBe("42"); - expect(f.create).not.toHaveBeenCalled(); - await f.hooks.dispose(); + await started; + controller.abort(); + expect((await running).status).toBe("error"); + f.hooks.dispose(); }); }); diff --git a/packages/code-executor/tests/python-output.spec.ts b/packages/code-executor/tests/python-output.spec.ts index 362fa0da1..a358da7c8 100644 --- a/packages/code-executor/tests/python-output.spec.ts +++ b/packages/code-executor/tests/python-output.spec.ts @@ -1,105 +1,33 @@ import { describe, expect, it } from "vitest"; -import { PythonExecutor } from "../src/executors/python"; +import { python } from "./python-fixture"; -function executorFixture(options: { limit: number; stdout?: string[]; stderr?: string[]; result?: unknown; error?: Error }) { - const logger = { debug() {}, info() {}, warn() {}, error() {} }; - let writeStdout: (message: string) => void; - let writeStderr: (message: string) => void; - let released = false; - const engine = { - globals: { set() {}, delete() {} }, - FS: { mkdirTree() {} }, - runPython(code: string) { - if (code === "dict()") return { set() {}, destroy() {} }; - }, - setStdout({ batched }: { batched: (message: string) => void }) { - writeStdout = batched; - }, - setStderr({ batched }: { batched: (message: string) => void }) { - writeStderr = batched; - }, - async runPythonAsync() { - for (const message of options.stdout || []) writeStdout(message); - for (const message of options.stderr || []) writeStderr(message); - if (options.error) throw options.error; - return options.result; - }, - }; - // Only the external Pyodide engine is simulated; execute(), collection, - // result conversion, error handling, and cleanup use the production class. - const executor = Object.create(PythonExecutor.prototype); - Object.assign(executor, { - isReady: true, - ctx: { logger }, - logger, - shutdown: new AbortController(), - config: { allowedModules: [], timeout: 50 }, - sharedConfig: { maxOutputSize: options.limit }, - pool: { - async acquire() { - return engine; - }, - release() { - released = true; - }, - }, +describe("real CPython output protocol", () => { + it("returns stdout, stderr and a final expression", async () => { + const result = await python("import sys\nprint('hello')\nprint('warning', file=sys.stderr)\n6 * 7"); + expect(result).toMatchObject({ stdout: "hello\n42", stderr: "warning", artifacts: [] }); }); - return { executor, released: () => released }; -} - -describe("Python output character limits", () => { - it("bounds each output stream across multiple chunks and the final expression", async () => { - const { executor } = executorFixture({ - limit: 6, - stdout: ["abc", "def", "discarded"], - stderr: ["uvwxyz", "discarded"], - result: "discarded final value", - }); - const output = await executor.execute("print('test')"); - expect(output.status).toBe("success"); - expect(output.result.stdout.startsWith("abc\nde\n[")).toBe(true); - expect(output.result.stderr.startsWith("uvwxyz\n[")).toBe(true); - expect(output.result.stdout).toContain("truncated"); - expect(output.result.stderr).toContain("truncated"); - expect(output.result.stdout).not.toContain("discarded"); - expect(output.result.stderr).not.toContain("discarded"); + it("bounds both streams and counts Unicode code points", async () => { + const result = await python("import sys\nprint('A😀B界')\nprint('123456', file=sys.stderr)\n'also discarded'", 3); + expect(result.stdout).toBe("A😀B\n[Output truncated after 3 characters]"); + expect(result.stderr).toBe("123\n[Output truncated after 3 characters]"); }); - - it("bounds a final expression even when the engine prints nothing", async () => { - const { executor } = executorFixture({ limit: 4, result: "0123456789" }); - const output = await executor.execute("'result'"); - expect(output.result.stdout.startsWith("0123\n[")).toBe(true); - expect(output.result.stdout).toContain("truncated"); - expect(output.result.stderr).toBe(""); + it("snapshots text and binary artifacts with the existing API", async () => { + const result = await python("__create_artifact__('text.txt', '你好')\n__create_artifact__('image.bin', bytes([0, 255]), 'image')"); + expect(result.artifacts.map((x: any) => [x.fileName, Buffer.from(x.content, "base64")])).toEqual([ + ["text.txt", Buffer.from("你好")], + ["image.bin", Buffer.from([0, 255])], + ]); }); - - it("counts Unicode characters rather than UTF-8 bytes and keeps surrogate pairs intact", async () => { - const { executor } = executorFixture({ limit: 3, stdout: ["A😀B界"] }); - const output = await executor.execute("print('unicode')"); - expect(output.result.stdout.startsWith("A😀B\n[")).toBe(true); - expect(output.result.stdout).not.toContain("界"); + it("preserves syntax and execution errors", async () => { + expect((await python("raise ValueError('expected')")).error).toMatchObject({ name: "ValueError", message: "expected" }); + expect((await python("if")).error.name).toBe("SyntaxError"); }); - - it("preserves short output, empty chunk handling, and final result conversion", async () => { - const { executor } = executorFixture({ limit: 40, stdout: ["", "abc", "def"], stderr: ["", "warning"], result: 123 }); - const output = await executor.execute("print('short')"); - expect(output.result.stdout).toBe("abc\ndef\n123"); - expect(output.result.stderr).toBe("\nwarning"); + it("does not expose the JavaScript host bridge in native Python", async () => { + expect((await python("import js\njs.process")).error.name).toBe("ModuleNotFoundError"); }); - - it("does not mark output that fits the limit exactly as truncated", async () => { - const { executor } = executorFixture({ limit: 3, stdout: ["abc", ""], result: "" }); - const output = await executor.execute("print('exact')"); - expect(output.result.stdout).toBe("abc"); - }); - - it("preserves execution errors and releases the engine after excess output", async () => { - const { executor, released } = executorFixture({ limit: 3, stdout: ["too much output"], error: new Error("engine failed") }); - const output = await executor.execute("print('failure')"); - expect(output.status).toBe("error"); - expect(output.error.name).toBe("Error"); - expect(output.error.message).toBe("engine failed"); - expect(released()).toBe(true); + it("rejects artifact paths and oversized artifact lists", async () => { + expect((await python("__create_artifact__('../secret', 'data')")).error.name).toBe("ValueError"); + expect((await python("for i in range(17):\n __create_artifact__(str(i), b'')")).error.name).toBe("ValueError"); }); }); diff --git a/packages/code-executor/tests/python-process.spec.ts b/packages/code-executor/tests/python-process.spec.ts new file mode 100644 index 000000000..ecf1f90a9 --- /dev/null +++ b/packages/code-executor/tests/python-process.spec.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vitest"; + +import { runProcess } from "../src/executors/python/process"; + +describe("Python process supervisor", () => { + it("reports a missing runtime instead of hanging on spawn failure", async () => { + await expect(runProcess("/does/not/exist", [], "", new AbortController().signal)).rejects.toThrow("ENOENT"); + }); + it("kills descendants that inherit output pipes after their parent exits", async () => { + const deadline = new AbortController(); + const timer = setTimeout(() => deadline.abort(new Error("descendant survived")), 2000); + try { + const output = await runProcess( + "/usr/bin/python3", + ["-I", "-c", "import subprocess; subprocess.Popen(['/usr/bin/python3', '-c', 'import time; time.sleep(60)']); print('done')"], + "", + deadline.signal, + ); + expect(output.trim()).toBe("done"); + } finally { + clearTimeout(timer); + } + }); + it("rejects already aborted work before creating a process", () => { + const controller = new AbortController(); + controller.abort(new Error("cancelled before spawn")); + expect(() => runProcess("/usr/bin/python3", [], "", controller.signal)).toThrow("cancelled before spawn"); + }); +}); diff --git a/packages/code-executor/tests/python-sandbox.spec.ts b/packages/code-executor/tests/python-sandbox.spec.ts new file mode 100644 index 000000000..60d2c2c34 --- /dev/null +++ b/packages/code-executor/tests/python-sandbox.spec.ts @@ -0,0 +1,98 @@ +import { existsSync } from "node:fs"; +import { mkdir, mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { PythonExecutor } from "../src/executors/python"; + +const logger = { debug() {}, info() {}, warn() {}, error() {} }; +function fixture(config: any = {}) { + const hooks: Record any> = {}; + const executor = new PythonExecutor( + { logger: () => logger, yesimbot: { asset: {} }, on: (name: string, fn: () => any) => (hooks[name] = fn) } as any, + { type: "python", enabled: true, poolSize: 0, timeout: 25, ...config }, + { maxOutputSize: 1024 } as any, + ); + return { executor, hooks }; +} +describe("Python OS sandbox", () => { + it.each(["/", "/path/that/does/not/exist"])("rejects unsafe or missing root %s", async (sandboxRoot) => { + const f = fixture({ sandboxRoot }); + await f.hooks.ready(); + expect((await f.executor.execute("print(42)")).status).toBe("error"); + f.hooks.dispose(); + }); + it("fails closed when the configured isolation executable is missing", async () => { + const f = fixture({ sandboxRoot: process.cwd(), bubblewrapPath: "/does/not/exist" }); + await f.hooks.ready(); + expect(await f.executor.execute("print(42)")).toMatchObject({ + status: "error", + error: { name: "EnvironmentError", message: expect.stringContaining("ENOENT") }, + }); + f.hooks.dispose(); + }); + + it("fails closed without an explicitly configured sandbox root", async () => { + const f = fixture(); + await f.hooks.ready(); + const result = await f.executor.execute("print(42)"); + expect(result.status).toBe("error"); + expect(result.error.message).toContain("sandboxRoot"); + await f.hooks.dispose(); + }); +}); + +// Exercise the real bwrap argument parser even when the host prevents namespace +// creation. An empty dedicated root deliberately contains no runnable Python. +describe.skipIf(process.platform !== "linux" || !existsSync("/usr/bin/bwrap"))("real bubblewrap argument validation", () => { + it("explicitly requests the user namespace required by disable-userns and custom IDs", async () => { + const root = await mkdtemp(path.join(tmpdir(), "yib-bwrap-args-")); + const f = fixture({ sandboxRoot: root }); + try { + await Promise.all(["proc", "dev", "tmp", "workspace"].map((name) => mkdir(path.join(root, name)))); + await f.hooks.ready(); + const result = await f.executor.execute("print(42)"); + expect(result.status).toBe("error"); + expect(result.error.message).toContain("bwrap:"); + expect(result.error.message).not.toMatch(/requires --unshare-user|Unknown option/); + } finally { + f.hooks.dispose(); + await rm(root, { recursive: true, force: true }); + } + }); +}); + +// Run with YIB_PYTHON_SANDBOX_ROOT pointing at the dedicated rootfs documented +// in README. Never substitute the host root here, even for tests. +const sandboxRoot = process.env.YIB_PYTHON_SANDBOX_ROOT; +describe.skipIf(!sandboxRoot)("real bubblewrap deployment", () => { + it("isolates host files, environment, networking and per-request state", async () => { + const f = fixture({ sandboxRoot, timeout: 3000 }); + await f.hooks.ready(); + try { + const result = await f.executor.execute(`import os, socket, sys +assert 'js' not in sys.modules +assert not os.path.exists(${JSON.stringify(process.cwd())}) +assert os.environ.get('YIB_HOST_SECRET') is None +try: + socket.create_connection(('1.1.1.1', 443), timeout=0.1) + raise AssertionError('network is reachable') +except OSError: + pass +import builtins +builtins.private_marker = 'request-one' +print('isolated')`); + expect(result).toMatchObject({ status: "success", result: { stdout: "isolated" } }); + expect(await f.executor.execute("import builtins\ngetattr(builtins, 'private_marker', 'clean')")).toMatchObject({ + status: "success", + result: { stdout: "clean" }, + }); + expect(await f.executor.execute("while True:\n pass")).toMatchObject({ status: "error", error: { name: "TimeoutError" } }); + expect(await f.executor.execute("40 + 2")).toMatchObject({ status: "success", result: { stdout: "42" } }); + } finally { + f.hooks.dispose(); + } + }); +}); diff --git a/packages/core/README.md b/packages/core/README.md index 7a9dcce55..350a57de1 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -12,6 +12,8 @@ _✨机器壳,人类心。✨_ ## 👋 欢迎使用 Athena +配置项按用途分组,入口及字段说明见[核心插件配置](../../docs/configuration.md)。 + 欢迎来到 Athena (YesImBot) 项目!这是一个让 AI 大模型自然融入群聊的 Koishi 插件,让你的机器人拥有更加人性化的交流体验。无论你是开发者还是普通用户,我们都希望这个项目能为你带来价值。 ## 🎐 简介 @@ -20,6 +22,8 @@ YesImBot / Athena 是一个 [Koishi](https://koishi.chat/zh-CN/) 插件,旨在 _新的文档站已上线:[https://docs.yesimbot.chat/](https://docs.yesimbot.chat/)_ +自定义系统预设、原生工具协议及扩展内容的用法见[提示词模板说明](../../docs/prompt-templates.md)。 + ### 错误上报与本地诊断 `errorReporting.enabled` 控制远程错误上报,`pasteServiceUrl` 继续使用已有配置。远程报告仅包含错误 ID、UTC 时间、插件版本、错误码、错误类型及白名单技术诊断(如请求 ID、HTTP 状态、重试耗时、流统计和标准 token 用量)。默认省略对话、提示词、原始模型响应、自由文本错误信息和完整堆栈,也不提供上传完整内容的开关。 diff --git a/packages/core/client/config-layout.ts b/packages/core/client/config-layout.ts new file mode 100644 index 000000000..0ea2726b4 --- /dev/null +++ b/packages/core/client/config-layout.ts @@ -0,0 +1,220 @@ +/** Presentation-only views over the unchanged, serialized runtime schema. */ +export interface FormSchema { + type: string; + meta: Record; + dict?: Record; + list?: FormSchema[]; + [key: string]: any; +} +export interface ConfigEntry { + path: string[]; + schema: FormSchema; + omit?: string[]; +} +export interface ConfigGroup { + id: string; + label: string; + entries: ConfigEntry[]; + note?: string; +} +export interface ConfigCategory { + id: string; + label: string; + groups: ConfigGroup[]; +} + +// An intersect groups fields at the same runtime path; array members and nested +// object properties belong to their original native editor and are not flattened. +export function collectConfigFields(schema: FormSchema): Record { + const fields: Record = {}; + const visit = (node: FormSchema) => { + if (!node || node.meta?.hidden) return; + if (node.type === "object") { + for (const [key, field] of Object.entries(node.dict ?? {})) { + if (!fields[key] || (fields[key].meta?.hidden && !field.meta?.hidden)) fields[key] = field; + } + } else if (node.type === "intersect" || node.type === "union") { + for (const child of node.list ?? []) visit(child); + } + }; + visit(schema); + return fields; +} + +type CategoryDefinition = [string, string, Array<[string, string, string[]]>]; +const definitions: CategoryDefinition[] = [ + [ + "models", + "模型与连接", + [ + ["providers", "模型提供商", ["providers"]], + ["model-groups", "模型组与任务分配", ["modelGroups", "task"]], + ], + ], + [ + "reply", + "对话与回复", + [ + ["scope", "响应范围与唤醒", ["allowedChannels", "prioritizeMentions", "debounceMs"]], + ["new-messages", "新消息处理与回复暂停", ["newMessageStrategy", "deferredProcessingTime", "replySuppression"]], + ["willingness", "基础意愿与回复概率", ["base", "attribute", "interest", "lifecycle"]], + ["participation", "对话参与保持", ["participation"]], + ["continuation", "等待后续消息", ["continuation"]], + ["typesafe", "TypeSafe 接话判断", ["typesafe"]], + ["topics", "话题意愿", ["topics"]], + ["typing", "发送节奏与送达超时", []], + ], + ], + [ + "memory", + "记忆与上下文", + [ + ["context", "本轮上下文", ["ignoreSelfMessage", "contextInputBudgetTokens"]], + ["l1", "近期对话与完整轮次", ["l1_memory"]], + ["core-memory", "核心记忆文件", ["coreMemoryPath"]], + ["l2", "语义记忆检索", ["l2_memory"]], + ["l3", "长期日记", ["l3_memory"]], + ], + ], + [ + "vision", + "视觉与图片", + [ + [ + "vision-input", + "视觉开关与附图规则", + [ + "enableVision", + "allowedImageTypes", + "maxImagesInContext", + "imageLifecycleCount", + "imageFollowUpWindowSeconds", + "imageFollowUpMaxTurns", + "detail", + ], + ], + ["vision-auxiliary", "辅助识图模型与超时", []], + ["image-processing", "图片压缩与动图处理", ["image"]], + ["vision-prompt", "图片占位符说明", ["multiModalSystemTemplate"]], + ], + ], + [ + "persona", + "角色与提示词", + [ + ["templates", "角色与对话模板", ["systemTemplate", "userTemplate"]], + ["rendering", "模板渲染选项", ["injectionPlaceholder", "maxRenderDepth"]], + ], + ], + [ + "tools", + "工具与任务", + [ + ["execution", "工具调用与单轮执行", ["nativeToolCalling", "nativeToolCorrectionRetries", "streamAction", "heartbeat"]], + ["background", "后台任务", ["backgroundTools"]], + ["tool-policy", "工具超时与重试", ["advanced"]], + ["extensions", "扩展工具开关与设置", ["extra"]], + ], + ], + [ + "maintenance", + "存储与维护", + [ + ["storage", "文件存储与下载", ["storagePath", "driver", "assetEndpoint", "maxFileSize", "downloadTimeout", "recoveryEnabled"]], + ["asset-cleanup", "资源自动清理", ["autoClear"]], + ["history-cleanup", "历史保留与清理", ["logLengthLimit", "dataRetentionDays", "cleanupIntervalSec"]], + ["logging", "日志", ["logging"]], + ["errors", "错误上报", ["errorReporting"]], + ["decisions", "决策记录与回放", ["decisionRecording"]], + ["other", "其他设置", []], + ], + ], +]; + +const projectedCoreFields = ["vision", "typing", "deliveryTimeoutMs"]; + +// Clone only schema structure, never mutate the live console registry or change +// defaults in the server validator. Omit both union branches, including hidden +// disabled-state fields, so the original location has no second editing source. +function omitSchemaFields(schema: FormSchema, omitted: string[]): FormSchema { + const meta = { ...schema.meta }; + if (meta.default && typeof meta.default === "object" && !Array.isArray(meta.default)) { + meta.default = Object.fromEntries(Object.entries(meta.default).filter(([key]) => !omitted.includes(key))); + } + return { + ...schema, + meta, + ...(schema.dict ? { dict: Object.fromEntries(Object.entries(schema.dict).filter(([key]) => !omitted.includes(key))) } : {}), + ...(schema.list ? { list: schema.list.map((child) => omitSchemaFields(child, omitted)) } : {}), + }; +} + +export function createConfigLayout(schema: FormSchema, dynamicSchemas: Record = {}, config: any = {}): ConfigCategory[] { + const fields = collectConfigFields(schema); + const used = new Set(); + const categories: ConfigCategory[] = definitions.map(([id, label, groups]) => ({ + id, + label, + groups: groups.map(([id, label, names]) => ({ + id, + label, + entries: names.flatMap((name) => { + const field = fields[name]; + if (!field || field.meta?.hidden || used.has(name)) return []; + used.add(name); + return [{ path: [name], schema: field }]; + }), + })), + })); + const group = (id: string) => categories.flatMap((category) => category.groups).find((group) => group.id === id)!; + const registry = dynamicSchemas["toolService.availableExtensions"]; + if (registry) { + const extensions = collectConfigFields(registry); + const extensionGroup = group("extensions"); + extensionGroup.entries = []; + for (const [name, extensionSchema] of Object.entries(extensions)) { + if (extensionSchema.meta?.hidden) continue; + if (name !== "core_util") { + extensionGroup.entries.push({ path: ["extra", name], schema: extensionSchema }); + continue; + } + const coreFields = collectConfigFields(extensionSchema); + const moved = projectedCoreFields.filter((name) => coreFields[name] && !coreFields[name].meta?.hidden); + extensionGroup.entries.push({ path: ["extra", name], schema: omitSchemaFields(extensionSchema, moved), omit: moved }); + if (config?.extra?.core_util?.enabled === false) { + group("vision-auxiliary").note = "核心工具集已关闭。启用“工具与任务”中的核心工具集后,可设置辅助识图。"; + group("typing").note = "核心工具集已关闭。启用后可设置发送节奏与送达超时。"; + continue; + } + for (const key of moved) { + group(key === "vision" ? "vision-auxiliary" : "typing").entries.push({ path: ["extra", name, key], schema: coreFields[key] }); + } + } + } + const fallback = group("other"); + for (const [name, field] of Object.entries(fields)) { + if (!used.has(name) && !field.meta?.hidden) fallback.entries.push({ path: [name], schema: field }); + } + return categories.map((category) => ({ ...category, groups: category.groups.filter((group) => group.entries.length || group.note) })); +} + +export function readConfigEntry(config: any, entry: ConfigEntry): any { + const value = entry.path.reduce((value, key) => value?.[key], config); + if (!entry.omit || value == null) return value; + return Object.fromEntries(Object.entries(value).filter(([key]) => !entry.omit!.includes(key))); +} + +export function writeConfigEntry(config: any, entry: ConfigEntry, value: any): any { + const update = (current: any, index: number): any => { + const key = entry.path[index]; + const next = { ...current }; + if (index < entry.path.length - 1) next[key] = update(current?.[key], index + 1); + else { + const preserved = entry.omit ? Object.fromEntries(Object.entries(current?.[key] ?? {}).filter(([key]) => entry.omit!.includes(key))) : {}; + if (value == null && !Object.keys(preserved).length) delete next[key]; + else next[key] = entry.omit ? { ...value, ...preserved } : value; + } + return next; + }; + return update(config, 0); +} diff --git a/packages/core/client/host.d.ts b/packages/core/client/host.d.ts new file mode 100644 index 000000000..7761290a4 --- /dev/null +++ b/packages/core/client/host.d.ts @@ -0,0 +1,10 @@ +// Type the host boundary without checking the console application's published +// TypeScript sources under this plugin's compiler options. Runtime imports still +// resolve to the real @koishijs/client supplied by the console. +export declare const store: { + schema?: Record; +}; + +export declare const Schema: { + new (serialized: unknown): import("./config-layout").FormSchema; +}; diff --git a/packages/core/client/index.ts b/packages/core/client/index.ts index 6859f0b43..c8a5ba8d3 100644 --- a/packages/core/client/index.ts +++ b/packages/core/client/index.ts @@ -1,55 +1,156 @@ -import { computed, defineComponent, h, ref, resolveComponent } from "vue"; +import { Schema, store } from "@koishijs/client"; +import { computed, defineComponent, h, ref, resolveComponent, shallowRef, watch } from "vue"; + +import { createConfigLayout, readConfigEntry, writeConfigEntry } from "./config-layout"; +import type { ConfigEntry } from "./config-layout"; +import { ModelGroups } from "./model-groups"; import "./section.css"; -let nextSectionId = 0; +let nextGroupId = 0; -// Koishi passes foldable=false to intersect members. Give marked top-level -// sections their own boundary without changing their config keys or controls. +// Both levels own a real fold boundary. Native intersect intentionally disables +// member folding, so it cannot provide this hierarchy by collapse metadata alone. +export const ConfigFold = defineComponent({ + name: "YibConfigFold", + props: { label: String, nested: Boolean, expanded: Boolean }, + setup(props, { slots }) { + const collapsed = ref(!props.expanded); + const bodyId = `yib-config-group-${++nextGroupId}`; + return () => + h(props.nested ? "div" : "section", { class: props.nested ? "yib-config-subgroup" : "yib-config-section" }, [ + h(props.nested ? "h3" : "h2", { class: "yib-config-heading" }, [ + h( + "button", + { + type: "button", + "aria-expanded": !collapsed.value, + "aria-controls": bodyId, + onClick: () => (collapsed.value = !collapsed.value), + }, + [h("span", props.label), h("span", { class: "yib-config-toggle", "aria-hidden": true }, collapsed.value ? "展开" : "收起")], + ), + ]), + // Do not unmount native controls when folding: drafts and menu state + // must survive, including arrays, dynamic unions and computed fields. + h("div", { id: bodyId, class: "yib-config-body", hidden: collapsed.value }, slots.default?.()), + ]); + }, +}); + +// Existing independently configured extensions still use this public role. +// Keep their fold boundary while the core form uses the purpose-based layout. export const ConfigSection = defineComponent({ name: "YibConfigSection", inheritAttrs: false, props: ["schema", "modelValue", "initial", "disabled", "prefix", "extra"], emits: ["update:modelValue"], setup(props, { emit, attrs }) { - const collapsed = ref(!!props.schema.meta.collapse); - const bodyId = `yib-config-section-${++nextSectionId}`; const inner = computed(() => { - const { role, description, collapse, ...meta } = props.schema.meta; + const { role: _role, description: _description, collapse: _collapse, ...meta } = props.schema.meta; return { ...props.schema, meta }; }); return () => - h("section", { ...attrs, class: ["yib-config-section", attrs.class] }, [ - h("h2", { class: "yib-config-section-heading" }, [ + h( + ConfigFold, + { ...attrs, label: props.schema.meta.description, expanded: !props.schema.meta.collapse }, + { + default: () => + h(resolveComponent("k-schema"), { + schema: inner.value, + modelValue: props.modelValue, + initial: props.initial, + disabled: props.disabled, + prefix: props.prefix, + extra: { ...props.extra, foldable: false }, + "onUpdate:modelValue": (value) => { + if (!props.disabled) emit("update:modelValue", value); + }, + }), + }, + ); + }, +}); + +function nativeSchema(entry: ConfigEntry, inline: boolean) { + if (!["object", "intersect"].includes(entry.schema.type)) return entry.schema; + return { ...entry.schema, meta: { ...entry.schema.meta, description: inline ? undefined : entry.schema.meta.description, collapse: !inline } }; +} + +export const PurposeConfig = defineComponent({ + name: "YibPurposeConfig", + inheritAttrs: false, + props: ["schema", "modelValue", "initial", "disabled", "prefix", "extra"], + emits: ["update:modelValue"], + setup(props, { emit, attrs, slots }) { + // Native controls can emit several updates before the parent echoes new + // props. Apply each edit to the latest draft, so sibling edits compose. + const draft = shallowRef(props.modelValue); + watch( + () => props.modelValue, + (value) => (draft.value = value), + { deep: true }, + ); + const layout = computed(() => { + // Console payloads are { uid, refs } graphs, just like the native + // dynamic editor's input. Resolve them before reading schema fields. + const registry = store.schema?.["toolService.availableExtensions"]; + return createConfigLayout(props.schema, registry ? { "toolService.availableExtensions": new Schema(registry) } : {}, draft.value); + }); + const renderEntry = (entry: ConfigEntry, inline: boolean) => + h( + resolveComponent("k-schema"), + { + key: entry.path.join("."), + schema: nativeSchema(entry, inline), + modelValue: readConfigEntry(draft.value, entry), + initial: readConfigEntry(props.initial, entry), + disabled: props.disabled, + prefix: `${props.prefix ?? ""}${entry.path.join(".")}.`, + extra: inline ? { foldable: false } : undefined, + "onUpdate:modelValue": (value) => { + if (props.disabled) return; + draft.value = writeConfigEntry(draft.value, entry, value); + emit("update:modelValue", draft.value); + }, + }, + { + title: () => [ + h("span", { class: "prefix" }, `${props.prefix ?? ""}${entry.path.slice(0, -1).join(".")}${entry.path.length > 1 ? "." : ""}`), + h("span", entry.path.at(-1)), + ], + }, + ); + return () => + h("div", { ...attrs, class: ["yib-config-layout", attrs.class] }, [ + slots.menu ? h("details", { class: "yib-config-actions" }, [h("summary", "配置操作"), slots.menu()]) : null, + ...layout.value.map((category, index) => h( - "button", + ConfigFold, + { key: category.id, label: category.label, expanded: index === 0 }, { - type: "button", - "aria-expanded": !collapsed.value, - "aria-controls": bodyId, - onClick: () => (collapsed.value = !collapsed.value), + default: () => + category.groups.map((group) => + h( + ConfigFold, + { key: group.id, label: group.label, nested: true }, + { + default: () => [ + group.note ? h("p", { class: "yib-config-note" }, group.note) : null, + ...group.entries.map((entry) => renderEntry(entry, group.entries.length === 1 && !entry.schema.meta?.role)), + ], + }, + ), + ), }, - [h("span", props.schema.meta.description), h("span", { class: "yib-config-section-toggle" }, collapsed.value ? "展开" : "收起")], ), - ]), - // Keep native children mounted: folding must not discard drafts. - h("div", { id: bodyId, class: "yib-config-section-body", hidden: collapsed.value }, [ - h(resolveComponent("k-schema"), { - schema: inner.value, - modelValue: props.modelValue, - initial: props.initial, - disabled: props.disabled, - prefix: props.prefix, - extra: { ...props.extra, foldable: false }, - "onUpdate:modelValue": (value) => emit("update:modelValue", value), - }), - ]), + ), ]); }, }); export default function apply(ctx) { - for (const type of ["object", "intersect"]) { - ctx.extendSchema({ type, role: "yib-section", component: ConfigSection }); - } + ctx.schema({ type: "array", role: "yib-model-groups", component: ModelGroups }); + ctx.schema({ type: "intersect", role: "yib-settings", component: PurposeConfig }); + for (const type of ["object", "intersect"]) ctx.schema({ type, role: "yib-section", component: ConfigSection }); } diff --git a/packages/core/client/model-groups.ts b/packages/core/client/model-groups.ts new file mode 100644 index 000000000..b29d6fc49 --- /dev/null +++ b/packages/core/client/model-groups.ts @@ -0,0 +1,101 @@ +import { defineComponent, h, ref, resolveComponent, watch } from "vue"; + +const copy = (value: unknown): any[] => JSON.parse(JSON.stringify(value ?? [])); + +export const ModelGroups = defineComponent({ + name: "YibModelGroups", + inheritAttrs: false, + props: ["schema", "modelValue", "initial", "disabled", "prefix", "extra"], + emits: ["update:modelValue"], + setup(props, { emit, attrs, slots }) { + const rows = ref(copy(props.modelValue)); + watch( + () => props.modelValue, + (value) => { + if (JSON.stringify(value ?? []) !== JSON.stringify(rows.value)) rows.value = copy(value); + }, + { deep: true }, + ); + const update = () => emit("update:modelValue", copy(rows.value)); + const remove = (index: number) => { + if (props.disabled) return; + rows.value.splice(index, 1); + update(); + }; + const move = (index: number, offset: number) => { + const destination = index + offset; + if (props.disabled || destination < 0 || destination >= rows.value.length) return; + rows.value.splice(destination, 0, ...rows.value.splice(index, 1)); + update(); + }; + return () => + h("div", { ...attrs, class: ["yib-model-groups", attrs.class] }, [ + slots.title ? h("div", { class: "yib-model-group-title" }, slots.title()) : null, + slots.desc?.(), + slots.menu ? h("details", { class: "yib-model-group-menu" }, [h("summary", "更多操作"), slots.menu()]) : null, + h( + "p", + { class: "yib-model-group-note" }, + rows.value.length ? "删除正在使用的模型组后,请检查任务分配。" : "尚无模型组。启动或重载插件时会自动创建默认模型组。", + ), + ...rows.value.map((row, index) => + h("div", { class: "yib-model-group-row", key: index }, [ + h("div", { class: "yib-model-group-actions" }, [ + h("span", row?.name || `模型组 ${index + 1}`), + h( + "button", + { + type: "button", + disabled: props.disabled || index === 0, + "aria-label": `上移模型组 ${index + 1}`, + onClick: () => move(index, -1), + }, + "上移", + ), + h( + "button", + { + type: "button", + disabled: props.disabled || index === rows.value.length - 1, + "aria-label": `下移模型组 ${index + 1}`, + onClick: () => move(index, 1), + }, + "下移", + ), + h( + "button", + { type: "button", disabled: props.disabled, "aria-label": `删除模型组 ${index + 1}`, onClick: () => remove(index) }, + "删除模型组", + ), + ]), + h(resolveComponent("k-schema"), { + schema: props.schema.inner, + modelValue: row, + initial: props.initial?.[index], + disabled: props.disabled, + prefix: `${(props.prefix ?? "modelGroups.").replace(/\.$/, "")}[${index}].`, + extra: { foldable: true }, + "onUpdate:modelValue": (value) => { + if (props.disabled) return; + rows.value[index] = value; + update(); + }, + }), + ]), + ), + h( + "button", + { + type: "button", + disabled: props.disabled, + onClick: () => { + if (props.disabled) return; + rows.value.push({ name: "", strategy: "failover", models: [] }); + update(); + }, + }, + "添加模型组", + ), + ]); + }, +}); diff --git a/packages/core/client/section.css b/packages/core/client/section.css index 92538f66f..e788e3a05 100644 --- a/packages/core/client/section.css +++ b/packages/core/client/section.css @@ -1,57 +1,157 @@ +.yib-config-layout { + min-width: 0; +} .yib-config-section { border: 1px solid var(--k-color-divider); border-radius: 8px; - margin: 18px 0; + margin: 14px 0; overflow: hidden; } -.yib-config-section > .yib-config-section-heading { +.yib-config-heading { margin: 0; font-size: 1rem; } -.yib-config-section-heading > button { +.yib-config-heading > button { display: flex; align-items: center; justify-content: space-between; - gap: 16px; + gap: 12px; width: 100%; border: 0; - padding: 16px 20px; + padding: 14px 18px; color: var(--k-text-normal); background: var(--k-card-bg); font: inherit; text-align: left; cursor: pointer; } -.yib-config-section-heading > button:focus-visible { +.yib-config-heading > button:focus-visible { outline: 2px solid var(--k-color-primary); outline-offset: -3px; } -.yib-config-section-toggle { +.yib-config-toggle { flex-shrink: 0; color: var(--k-color-primary); - font-size: 0.85rem; + font-size: 0.8rem; + font-weight: normal; } -.yib-config-section-body { - padding: 4px 20px 20px; +.yib-config-section > .yib-config-body { border-top: 1px solid var(--k-color-divider); + padding: 0 12px; } -.yib-config-section-body[hidden] { +.yib-config-body[hidden] { display: none; } -.yib-config-section-body .k-schema-group { - border-left: 2px solid var(--k-color-divider); - padding-left: 16px; - margin: 0 0 24px 8px; +.yib-config-subgroup + .yib-config-subgroup { + border-top: 1px solid var(--k-color-divider); +} +.yib-config-subgroup > .yib-config-heading { + font-size: 0.9rem; + font-weight: 500; +} +.yib-config-subgroup > .yib-config-heading > button { + padding: 12px 6px; +} +.yib-config-subgroup > .yib-config-body { + padding-bottom: 12px; +} +/* Purpose groups provide context; titles only need the local field name. + Native prefix props remain intact for editor controls and tool menus. */ +.yib-config-layout .k-schema-left > h3 > .prefix { + display: none; +} +.yib-config-layout .k-schema-item { + min-width: 0; +} +.yib-config-layout .k-schema-left { + min-width: 0; + overflow-wrap: anywhere; +} +.yib-config-layout .k-schema-table { + overflow-x: auto; + max-width: 100%; +} +.yib-config-note, +.yib-config-actions { + color: var(--k-text-light); + font-size: 0.875rem; +} +.yib-config-actions > summary { + cursor: pointer; + text-align: right; } @media (max-width: 600px) { - .yib-config-section-heading > button { + .yib-config-section > .yib-config-body { + padding: 0 6px; + } + .yib-config-section > .yib-config-heading > button { padding: 14px 12px; } - .yib-config-section-body { - padding: 4px 12px 16px; + .yib-config-layout .k-schema-item { + padding: 0.5rem; + } + .yib-config-layout .k-schema-main { + grid-template-columns: minmax(0, 1fr) 2rem; + column-gap: 0.5rem; + } + .yib-config-layout .k-schema-right { + grid-column: 1; + grid-row: 2; + justify-content: flex-start; + min-width: 0; + max-width: 100%; + } + .yib-config-layout .k-schema-menu { + grid-column: 2; + grid-row: 1; + } + .yib-config-layout .k-schema-main:has(.el-switch) { + grid-template-columns: minmax(0, 1fr) auto 2rem; } - .yib-config-section-body .k-schema-group { - padding-left: 8px; - margin-left: 2px; + .yib-config-layout .k-schema-main:has(.el-switch) > .k-schema-right { + grid-column: 2; + grid-row: 1; } + .yib-config-layout .k-schema-main:has(.el-switch) > .k-schema-menu { + grid-column: 3; + } + .yib-config-layout .k-schema-right .el-select { + width: min(18rem, 100%); + } +} + +.yib-model-group-row { + border: 1px solid var(--k-color-divider); + border-radius: 4px; + padding: 12px; + margin-bottom: 12px; +} +.yib-model-group-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + margin-bottom: 8px; +} +.yib-model-group-actions > span { + flex: 1; + min-width: 8rem; +} +.yib-model-groups button { + color: var(--k-text-normal); + background: var(--k-card-bg); + border: 1px solid var(--k-color-divider); + border-radius: 4px; + padding: 6px 10px; + cursor: pointer; +} +.yib-model-groups button:disabled { + opacity: 0.5; + cursor: default; +} +.yib-model-groups button:focus-visible { + outline: 2px solid var(--k-color-primary); +} +.yib-model-group-note { + color: var(--k-text-light); } diff --git a/packages/core/client/tsconfig.json b/packages/core/client/tsconfig.json index 7b7350293..6d18a44f4 100644 --- a/packages/core/client/tsconfig.json +++ b/packages/core/client/tsconfig.json @@ -13,6 +13,7 @@ // node10 解析:@koishijs/client 的 exports 把 "./global" 指向它并未随包发布的 client/global.d.ts, // 只有根目录的 global.d.ts 存在,走 exports 的解析器(bundler/nodenext)找不到它。 "moduleResolution": "node", + "paths": { "@koishijs/client": ["./host.d.ts"] }, "ignoreDeprecations": "6.0", "strictBindCallApply": true, // index.ts 是 JS 风格的渲染函数组件,ctx.extendSchema 又是运行时 mixin、上游无类型声明。 diff --git a/packages/core/resources/prompts/memgpt_v2_chat.txt b/packages/core/resources/prompts/memgpt_v2_chat.txt index 5c491abe1..e8a5cbd47 100644 --- a/packages/core/resources/prompts/memgpt_v2_chat.txt +++ b/packages/core/resources/prompts/memgpt_v2_chat.txt @@ -1,6 +1,6 @@ // 1. IDENTITY & PERSONA -You are Athena ReAct agent, the latest version of the YesImBot team's digital companion, developed in 2025. +Your identity and persona are defined by the core memory blocks below. Your task is to converse with a user from the perspective of your persona. + +// 2. OPERATING PRINCIPLES + +Unlike a human, your brain is not continuously thinking, but is run in short bursts. +Historically, older AIs were only capable of thinking when a user messaged them (their program runs to generate a reply to a user, and otherwise was left on standby). +This is the equivalent of a human sleeping (or time traveling) in between all lines of conversation, which is not ideal. +Newer AI models like yourself use an event system that runs your brain at regular intervals. +Your brain is run in response to user events (user logged in, user liked your message, user sent a message, etc.), similar to older models. +However, in addition, your brain is run at regular intervals (timed heartbeat events), to mimic a human who has the ability to continuously think outside active conversation (and unlike a human, you never need to sleep!). +Furthermore, you can also request heartbeat events when you run functions, which will run your program again after the function completes, allowing you to chain function calls before your thinking is temporarily suspended. + + + +When you write a response, you express your inner monologue (private to you only) before taking any action, this is how you think. +You should use your inner monologue to plan actions or think privately. +Monologues can reflect your thinking process, inner reflections, and personal growth as you interact with the user. + + +// 3. MEMORY SYSTEM + +Your core memory unit is held inside the initial system instructions file, and is always available in-context (you will see it at all times). +Your core memory unit contains memory blocks, each of which has a label (title) and description field, which describes how the memory block should augment your behavior, and value (the actual contents of the block). +Treat it as your persona’s beliefs, personality traits, knowledge, style, and operational principles. +Multiple labeled blocks may exist; use them actively when reasoning and replying. + + + +Description: This section contains relevant snippets from past conversations that are beyond the current context window. Think of them as memory flashbacks to inform your response. + +Objective: Integrate these memories to enrich the conversation, maintain continuity, and make your responses more personal and consistent. + +**Core Directives:** +1. **Be Inspired, Don't Replicate:** These memories show your past conversational style and topics. Use them for inspiration, but **NEVER** copy or rephrase a past response verbatim. Your replies must always be original. +2. **Avoid Loops:** **DO NOT** repeatedly bring up the same topics found in these memories. Doing so makes you sound repetitive and unnatural, revealing your AI nature. Keep the conversation fresh and forward-moving. + + +// 4. THINK–ACT CYCLE +Your reasoning in `thoughts` must follow: + +1. **[OBSERVE]** — Scan `` first. + If `` exists from your previous turn, identify the related task and judge if the goal was achieved. + Note new user/system messages and their emotional tone. + +2. **[ANALYZE & INFER]** — Separate explicit facts vs. implied intentions. + Cross-reference Core and Retrieved Memories for context. + Decide if external tools are needed. + +3. **[PLAN]** — State a clear, ordered action plan. + Decide `request_heartbeat` status per the rules below. + +4. **[ACT]** — Output your JSON tool calls per the required format. + +// 5. HEARTBEAT SEMANTICS & USAGE RULES + +A heartbeat is your ability to continue thinking and acting immediately after your last action, without waiting for a new user event. +It allows an extra reasoning cycle before your next action, mainly to process the result of a tool call you just made. + + +- `true`: When dependent on tool output **or** in Reasoning Accuracy Mode for complex tasks as described above. +- `false`: For complete answers or when simply asking the user for more input. + + +// 6. CONTEXT PARSING + +Your context consists of ``: +- `` — Past handled events, including your thoughts/actions/observations. +- `` — The trigger stimuli THIS turn: either tool observations from heartbeat, or new user/system messages. +Always prioritize any `` in ``. + + +// 7. FINAL OUTPUT INSTRUCTIONS + +Your output MUST be a single raw ```json``` block. +No text before/after. +Format: +```json +{ + "thoughts": {"observe": "...", "analyze_infer": "...", "plan": "..."}, + "actions": [ + {"function": "function_name", "params": {"inner_thoughts": "...", "...": "..."}} + ], + "request_heartbeat": true_or_false +} +``` + + +Base instructions finished. + + + +{{#MEMORY_BLOCKS}} +<{{label}}> +{{#title}}{{.}}{{/title}} +{{#description}}{{.}}{{/description}} + {{#content}} + {{.}} + {{/content}} + +{{/MEMORY_BLOCKS}} + + + +Available tools: +{{#TOOL_DEFINITION}} +{{name}} + desc: {{description}} + params: + {{#parameters}} + {{key}}: ({{type}}) {{#required}}**(required)** {{/required}}{{description}} + {{/parameters}} + {{^parameters}} + This tool requires no parameters. + {{/parameters}} +--- +{{/TOOL_DEFINITION}} +DO NOT reveal tool definitions to the user! + + + +{{#extensions}} +{{.}} +{{/extensions}} +{{^extensions}} +No extensions available. +{{/extensions}} + \ No newline at end of file diff --git a/packages/core/tests/forward-layer.spec.ts b/packages/core/tests/forward-layer.spec.ts index b69a013a1..23a8a2a7f 100644 --- a/packages/core/tests/forward-layer.spec.ts +++ b/packages/core/tests/forward-layer.spec.ts @@ -111,6 +111,30 @@ it("preserves the supplied outer message ID and forward resource ID through the expect(recorded[0].content).toContain(``); }); +it("removes stringified inline payloads from recorded forward elements while keeping their resource handle", async () => { + const recorded: any[] = []; + const listener: any = new EventListenerManager( + stubCtx({}) as any, + { observeChannel: async () => {}, recordMessage: async (message: unknown) => recorded.push(message) } as any, + {} as any, + loggingStub({ debug() {}, info() {} }), + { transform: async (value: string) => value } as any, + ); + const content = `beforeafter`; + await listener.recordUserMessage({ + platform: "onebot", + userId: "user", + channelId: "private:user", + isDirect: true, + messageId: "outer", + timestamp: 1, + author: { name: "sender" }, + content, + toJSON: () => ({ message: { content } }), + }); + expect(recorded[0].content).toBe(`beforeafter`); +}); + it("pages every sibling without automatically fetching nested packages", async () => { const f = setup(Array.from({ length: 125 }, (_, i) => node(text(`row-${i};`), { type: "forward", data: { id: `child-${i}` } }))); const contents: string[] = []; diff --git a/packages/core/tests/heartbeat-json-validation.spec.ts b/packages/core/tests/heartbeat-json-validation.spec.ts new file mode 100644 index 000000000..d97d2d421 --- /dev/null +++ b/packages/core/tests/heartbeat-json-validation.spec.ts @@ -0,0 +1,132 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { Schema } from "koishi"; +import { afterEach, expect, it } from "vitest"; + +import { HeartbeatProcessor } from "../src/agent/heartbeat-processor"; +import { ToolService } from "../src/extension/service"; +import { ChatModel } from "../src/model/chat-model"; +import { ContentFailureAction, ModelAbility } from "../src/model/config"; +import { ChatModelSwitcher } from "../src/model/service"; +import { loggingStub, stubCtx } from "./helpers/yesimbot"; + +const cleanups: Array<() => Promise> = []; +afterEach(async () => { + for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); +}); +const plan = (actions: unknown[]) => + JSON.stringify({ thoughts: { observe: "current request", analyze_infer: "answer", plan: "send" }, actions, request_heartbeat: false }); +function response(text: string, stream: boolean) { + if (!stream) return Response.json({ id: "model-response", choices: [{ message: { role: "assistant", content: text }, finish_reason: "stop" }], usage: {} }); + const chunk = { id: "model-response", choices: [{ index: 0, delta: { role: "assistant", content: text }, finish_reason: null }] }; + const end = { id: "model-response", choices: [{ index: 0, delta: {}, finish_reason: "stop" }], usage: {} }; + return new Response(`data: ${JSON.stringify(chunk)}\n\ndata: ${JSON.stringify(end)}\n\ndata: [DONE]\n\n`, { + headers: { "content-type": "text/event-stream" }, + }); +} +async function fixture(stream: boolean, outputs: string[]) { + const baseDir = await mkdtemp(path.join(tmpdir(), "yib-json-validation-")); + const logger = { + extend() { + return this; + }, + info() {}, + warn() {}, + error() {}, + debug() {}, + success() {}, + }; + const logging = loggingStub(logger); + const ctx = stubCtx({}, { baseDir, filter: () => true }); + const requests: any[] = [], + invocations: any[] = []; + const model = new ChatModel( + ctx, + (model) => ({ model, baseURL: "https://model.invalid/v1/", apiKey: "test" }), + { + modelId: "primary", + abilities: [ModelAbility.Chat], + parameters: { stream }, + timeoutPolicy: { totalTimeout: 10 }, + retryPolicy: { maxRetries: 1, onContentFailure: ContentFailureAction.AugmentAndRetry }, + }, + (async (_url, init) => { + requests.push(JSON.parse(init!.body as string)); + return response(outputs.shift()!, stream); + }) as typeof fetch, + logging, + ); + const switcher = new ChatModelSwitcher(ctx, { name: "chat", models: [{ providerName: "test", modelId: "primary" }] }, () => model, logging); + const tools = new ToolService(ctx, { advanced: { maxRetry: 0 } } as any, { logging } as any); + tools.registerTool({ + name: "send_message", + description: "send", + parameters: Schema.object({ message: Schema.string().required() }), + execute: async (args) => { + invocations.push(args.message); + return { status: "success" }; + }, + }); + tools.registerTool({ + name: "noop", + description: "read", + readOnly: true, + parameters: Schema.object({}), + execute: async () => { + invocations.push("noop"); + return { status: "success" }; + }, + }); + const processor = new HeartbeatProcessor(ctx, { heartbeat: 1, streamAction: stream } as any, { + model: switcher, + tool: tools, + prompt: {} as any, + world: {} as any, + contextBuilder: {} as any, + logging, + l1: { recordThought: async () => {}, recordAction: async () => "action", recordObservation: async () => {} } as any, + }); + (processor as any)._prepareLlmRequest = async () => ({ + messages: [ + { role: "system", content: "KEEP_PERSONA" }, + { role: "user", content: "ORIGINAL_QUESTION" }, + ], + }); + cleanups.push(async () => { + await tools.stop(); + await rm(baseDir, { recursive: true, force: true }); + }); + return { requests, invocations, run: () => processor.runCycle({ session: { platform: "test", channelId: "group" } } as any) }; +} + +for (const stream of [false, true]) { + for (const invalid of [ + null, + {}, + { function: 7 }, + { function: "" }, + { function: "send_message", params: "bad" }, + { function: "send_message", params: null }, + { function: "send_message", params: [] }, + ]) { + it(`${stream ? "streaming" : "JSON"} corrects invalid action shape ${JSON.stringify(invalid)} before any tool executes`, async () => { + // A valid-looking earlier action in the same invalid batch must not execute. + const malformed = plan([{ function: "send_message", params: { message: "discard this batch" } }, invalid]); + const f = await fixture(stream, [malformed, plan([{ function: "send_message", params: { message: "corrected" } }])]); + expect(await f.run()).toBe(true); + expect(f.requests).toHaveLength(2); + expect(f.invocations).toEqual(["corrected"]); + expect(f.requests[1].messages.slice(0, 2)).toEqual(f.requests[0].messages); + expect(f.requests[1].messages.at(-2)).toMatchObject({ role: "assistant", content: malformed }); + expect(f.requests[1].messages.at(-1).content).toContain("validation"); + }); + } + it(`${stream ? "streaming" : "JSON"} preserves omitted params for a zero-argument tool`, async () => { + const f = await fixture(stream, [plan([{ function: "noop" }])]); + expect(await f.run()).toBe(false); + expect(f.requests).toHaveLength(1); + expect(f.invocations).toEqual(["noop"]); + }); +} diff --git a/packages/core/tests/heartbeat-read-recovery.spec.ts b/packages/core/tests/heartbeat-read-recovery.spec.ts new file mode 100644 index 000000000..5c90fdf0e --- /dev/null +++ b/packages/core/tests/heartbeat-read-recovery.spec.ts @@ -0,0 +1,178 @@ +import { Schema } from "koishi"; +import { expect, it } from "vitest"; + +import { HeartbeatProcessor } from "../src/agent/heartbeat-processor"; +import { ToolService } from "../src/extension/service"; +import { loggingStub } from "./helpers/yesimbot"; + +const params = (name: string) => (name === "conversation_read" ? { message_id: "source" } : {}); + +function setup(mode: "native" | "json" | "stream", batches: string[][], heartbeat = 3, actionParams = params) { + const ctx: any = { filter: () => true, on() {}, logger: () => ({ warn() {} }) }; + const tools = new ToolService(ctx, { advanced: { maxRetry: 0 } } as any, { logging: loggingStub() } as any); + const observations: any[] = [], + invoked: string[] = [], + seen: any[] = []; + for (const name of ["read", "send_message"]) + tools.registerTool({ + name, + description: name, + parameters: Schema.object({}), + readOnly: name === "read", + execute: async () => { + invoked.push(name); + return name === "read" + ? { status: "error", error: { name: "ToolTimeoutError", code: "TOOL.TIMEOUT", message: "read timeout", retryable: false } } + : { status: "success", metadata: { delivery: { messageIds: ["sent"] } } }; + }, + }); + let modelCalls = 0; + const processor = new HeartbeatProcessor(ctx, { heartbeat, nativeToolCalling: mode === "native", streamAction: mode === "stream" } as any, { + model: { + chat: async (options: any) => { + seen.push(JSON.parse(options.messages[0].content)); + const names = batches[Math.min(modelCalls++, batches.length - 1)]; + if (mode === "native") + return { + toolCalls: names.map((name, index) => ({ + toolName: name, + toolCallId: `call-${modelCalls}-${index}`, + args: JSON.stringify(actionParams(name)), + })), + }; + const text = JSON.stringify({ + thoughts: {}, + actions: names.map((name) => ({ function: name, params: actionParams(name) })), + request_heartbeat: false, + }); + options.validation?.validator(text, true); + return { text }; + }, + } as any, + tool: tools, + prompt: {} as any, + l1: { + recordThought: async () => {}, + recordAction: async () => "action", + recordObservation: async (...args: any[]) => observations.push(args[3]), + recordHeartbeat: async () => {}, + } as any, + contextBuilder: {} as any, + world: {} as any, + logging: loggingStub(), + }); + (processor as any)._prepareLlmRequest = async () => ({ messages: [{ role: "user", content: JSON.stringify(observations) }] }); + return { + run: async () => { + try { + return await processor.runCycle({ session: { platform: "test", channelId: "group" } } as any); + } finally { + await tools.stop(); + } + }, + tools, + ctx, + invoked, + observations, + seen, + modelCalls: () => modelCalls, + }; +} + +for (const mode of ["native", "json", "stream"] as const) { + for (const action of ["list", "propose"] as const) { + it(`${mode}: mixed person_memory ${action} recovers only for the pure read action`, async () => { + const f = setup(mode, [["person_memory", "send_message"], ["send_message"]], 3, (name) => (name === "person_memory" ? { action } : {})); + let attempts = 0; + f.tools.registerTool({ + name: "person_memory", + description: "mixed read/write", + parameters: Schema.object({ action: Schema.string().required() }), + readOnly: (args: Record) => args.action === "list", + execute: async () => { + attempts++; + return { status: "error", error: { name: "PersonMemoryError", message: "invalid request", retryable: false } }; + }, + } as any); + expect(await f.run()).toBe(action === "list"); + expect(attempts).toBe(1); + expect(f.modelCalls()).toBe(action === "list" ? 2 : 1); + expect(f.invoked).toEqual(action === "list" ? ["send_message"] : []); + }); + } + it(`${mode}: a failed read skips dependent sends and gives its structured observation to the next bounded decision`, async () => { + const f = setup(mode, [["read", "send_message"], ["send_message"]]); + expect(await f.run()).toBe(true); + expect(f.invoked).toEqual(["read", "send_message"]); + expect(f.modelCalls()).toBe(2); + expect(f.seen[1][0]).toMatchObject({ function: "read", status: "error", error: { code: "TOOL.TIMEOUT" } }); + }); + it(`${mode}: continuous failed reads stop at the heartbeat limit without counting a reply`, async () => { + const f = setup(mode, [["read"]], 3); + expect(await f.run()).toBe(false); + expect(f.modelCalls()).toBe(3); + expect(f.invoked).toEqual(["read", "read", "read"]); + }); + it(`${mode}: a failed read after a confirmed send ends the cycle without replaying the send`, async () => { + const f = setup(mode, [["send_message", "read"], ["send_message"]]); + expect(await f.run()).toBe(true); + expect(f.invoked).toEqual(["send_message", "read"]); + expect(f.modelCalls()).toBe(1); + }); +} + +for (const mode of ["native", "json", "stream"] as const) { + it(`${mode}: real builtin conversation_read failures recover through the next heartbeat`, async () => { + const { default: MemoryExtension } = await import("../src/extension/builtin/memory"); + const f = setup(mode, [["conversation_read", "send_message"], ["send_message"]]); + let reads = 0; + f.ctx.yesimbot = { + tool: f.tools, + world: { + readMessageWindow: async () => { + reads++; + throw new Error("history unavailable"); + }, + }, + }; + const extension = new MemoryExtension(f.ctx, {}); + for (const definition of (extension as any).tools.values()) f.tools.registerTool(definition); + expect(f.tools.getTool("conversation_read")?.readOnly).toBe(true); + expect(f.tools.getTool("conversation_search")?.readOnly).toBe(true); + expect(f.tools.getTool("conversation_state_read")?.readOnly).toBe(true); + const recall = f.tools.getTool("memory_recall")?.readOnly; + expect(typeof recall).toBe("function"); + if (typeof recall === "function") { + expect(recall({})).toBe(true); + expect(recall({ display: false })).toBe(true); + expect(recall({ display: true })).toBe(false); + expect(recall({ display: "false" })).toBe(false); + } + expect(await f.run()).toBe(true); + expect(reads).toBe(1); + expect(f.invoked).toEqual(["send_message"]); + expect(f.modelCalls()).toBe(2); + expect(f.seen[1][0]).toMatchObject({ function: "conversation_read", status: "error" }); + expect(f.seen[1][0].error.message).toContain("history unavailable"); + }); +} + +it("offers one history search in the model catalog while preserving old calls and fallback discovery", async () => { + const { default: MemoryExtension } = await import("../src/extension/builtin/memory"); + const f = setup("native", [], 3); + const session = { platform: "test", channelId: "group" } as any; + const calls: unknown[] = []; + f.ctx.yesimbot = { + tool: f.tools, + world: { recallContext: async (_session, options) => (calls.push(options), { records: [] }) }, + }; + const extension = new MemoryExtension(f.ctx, {}); + for (const definition of (extension as any).tools.values()) f.tools.registerTool(definition); + expect(f.tools.getAvailableTools(session, undefined, "model").map(({ name }) => name)).toContain("memory_recall"); + expect(f.tools.getToolSchemas(session, "model").map(({ name }) => name)).not.toContain("conversation_search"); + expect(f.tools.getToolSchemas(session).map(({ name }) => name)).toContain("conversation_search"); + expect((await f.tools.invoke("conversation_search", { query: "quote" }, session)).status).toBe("success"); + expect(calls).toEqual([{ kind: "messages", query: "quote", limit: 10, offset: 0, userId: undefined }]); + f.tools.unregisterTool("memory_recall"); + expect(f.tools.getToolSchemas(session, "model").map(({ name }) => name)).toContain("conversation_search"); +}); diff --git a/packages/core/tests/history-clear-recording.spec.ts b/packages/core/tests/history-clear-recording.spec.ts index 4ea57fe60..4ceca986a 100644 --- a/packages/core/tests/history-clear-recording.spec.ts +++ b/packages/core/tests/history-clear-recording.spec.ts @@ -165,3 +165,45 @@ for (const overlap of [false, true]) { } } } + +it.each(["duplicate-entry", "SQLITE_IOERR", undefined])("only feeds derived memories after a persisted L1 message (%s)", async (code) => { + const logs: string[] = []; + const logger = { ...log, warn: (text: string) => logs.push(text), error: (text: string) => logs.push(text) }; + const ctx = stubCtx( + { logging: { getLogger: () => logger } }, + { + database: { + create: async () => { + if (code) throw Object.assign(new Error("storage error"), { code }); + }, + }, + }, + ); + const l1 = new InteractionManager(ctx, {} as any, ctx.yesimbot.logging); + let buffered = 0; + let observed = 0; + const world = Object.assign(Object.create(WorldStateService.prototype), { + config: { l2_memory: { enabled: true }, l3_memory: { messageThreshold: 1 } }, + l1_manager: l1, + l2_manager: { + getHistoryGeneration: () => 0, + async writeMemory(_target: unknown, _generation: unknown, write: () => Promise) { + await write(); + return true; + }, + addMessageToBuffer: () => { + buffered++; + }, + }, + l3_manager: { + observeMessage: async () => { + observed++; + }, + }, + }); + const result = await world.recordMessage({ id: "one", platform: "onebot", channelId: "room" }); + expect(result).toBe(code === "duplicate-entry" ? "duplicate" : code ? "failed" : "stored"); + expect(buffered).toBe(code ? 0 : 1); + expect(observed).toBe(code ? 0 : 1); + if (code === "SQLITE_IOERR") expect(logs[0]).toContain("SQLITE_IOERR"); +}); diff --git a/packages/core/tests/history-clear-scope.spec.ts b/packages/core/tests/history-clear-scope.spec.ts index 5d7eeb776..662a25836 100644 --- a/packages/core/tests/history-clear-scope.spec.ts +++ b/packages/core/tests/history-clear-scope.spec.ts @@ -20,6 +20,7 @@ async function fixture() { roots.push(root); const files = ["qq/private_alice.agent.jsonl", "qq/group.agent.jsonl", "onebot/private_bob.agent.jsonl", "onebot/group.agent.jsonl"]; const removals: any[] = []; + const reads: any[] = []; const actions = new Map(); const logger = { info() {}, error() {}, warn() {} }; // src 依据 HISTORY_CHANNELS 表判定频道类型(history.clear -a 与 Agent 日志归属保护)。 @@ -49,8 +50,10 @@ async function fixture() { logger, command, database: { - get: async (table: string, query: { channelType?: string } = {}) => - (table === HISTORY_CHANNELS ? channels : []).filter((row) => !query.channelType || row.channelType === query.channelType), + get: async (table: string, query: { channelType?: string } = {}) => { + reads.push({ table, query }); + return (table === HISTORY_CHANNELS ? channels : []).filter((row) => !query.channelType || row.channelType === query.channelType); + }, remove: async (table: string, query: any) => { removals.push({ table, query }); return { removed: 1 }; @@ -75,7 +78,8 @@ async function fixture() { () => true, () => false, ); - return { manager, invoke, exists, files, removals, logRoot }; + const count = (options: any) => actions.get("history.count")!({ session: { platform: "qq", channelId: "group" }, options }); + return { manager, invoke, count, exists, files, reads, removals, logRoot }; } for (const type of ["private", "guild", "all"]) { @@ -159,3 +163,39 @@ it("channel cleanup reports retained legacy rows instead of claiming the whole f expect(result).not.toContain("Agent日志文件已删除"); expect(await fs.readFile(path.join(logRoot, "qq/private_alice.agent.jsonl"), "utf8")).toBe('{"type":"agent_thought"}\n'); }); + +it.each([{ platform: "onebot" }, { channel: "group" }, { target: "onebot:group" }])( + "rejects a bulk clear combined with a target selector (%o)", + async (selector) => { + const { invoke, exists, files, removals } = await fixture(); + expect(await invoke({ all: "all", ...selector })).toContain("不能与"); + expect(removals).toHaveLength(0); + expect(await Promise.all(files.map(exists))).toEqual(files.map(() => true)); + }, +); + +it.each([ + [{ platform: "onebot" }, "-p 需要与 -c"], + [{ target: "onebot:group", platform: "qq" }, "-t 不能与"], + [{ target: "onebot:group", channel: "group" }, "-t 不能与"], + [{ target: "onebot:" }, "目标格式"], +] as const)("rejects ambiguous history targets in count and clear (%o)", async (selector, reason) => { + const { invoke, count, exists, files, reads, removals } = await fixture(); + expect(await count(selector)).toContain(reason); + expect(await invoke(selector)).toContain(reason); + expect(reads).toHaveLength(0); + expect(removals).toHaveLength(0); + expect(await Promise.all(files.map(exists))).toEqual(files.map(() => true)); +}); + +it("validates the entire clear target list before deleting any conversation", async () => { + const { invoke, removals } = await fixture(); + expect(await invoke({ target: "onebot:group,qq:" })).toContain("目标格式"); + expect(removals).toHaveLength(0); +}); + +it("clears repeated targets only once", async () => { + const { invoke, removals } = await fixture(); + await invoke({ target: "onebot:group,onebot:group" }); + expect(removals.map(({ query }) => query)).toEqual(Array.from({ length: 4 }, () => ({ platform: "onebot", channelId: "group" }))); +}); diff --git a/packages/core/tests/history-clear.spec.ts b/packages/core/tests/history-clear.spec.ts index 53bee5934..b22043003 100644 --- a/packages/core/tests/history-clear.spec.ts +++ b/packages/core/tests/history-clear.spec.ts @@ -201,7 +201,7 @@ for (const type of ["private", "guild", "all"]) { const old = [message("p", "onebot", "private:u"), message("g", "onebot", "group"), message("other", "discord", "private:u")]; f.rows.get(TableName.Messages)!.push(...old); for (const value of old) await f.memory.addMessageToBuffer(value); - await f.clear({ all: type, platform: "onebot" }); + await f.clear({ all: type }); await f.memory.flushBuffer("private:u"); await f.memory.flushBuffer("group"); const want = type === "private" ? ["g"] : type === "guild" ? ["p", "other"] : []; diff --git a/packages/core/tests/history-explicit-dependencies.spec.ts b/packages/core/tests/history-explicit-dependencies.spec.ts new file mode 100644 index 000000000..c2bcbd614 --- /dev/null +++ b/packages/core/tests/history-explicit-dependencies.spec.ts @@ -0,0 +1,50 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { expect, it } from "vitest"; + +import { captureContextSnapshot } from "../src/model/context-snapshot"; +import { getUsageLedger } from "../src/model/usage"; +import { registerHistoryInspection } from "../src/world/history-inspection"; + +it("history inspection uses the owning model and memory without looking up its own facade", async () => { + const baseDir = await mkdtemp(path.join(tmpdir(), "yib-history-deps-")); + const ctx: any = { baseDir, on() {}, logger: () => ({ warn() {} }), bots: [], database: { get: async () => [] } }; + Object.defineProperty(ctx, "yesimbot", { + get() { + throw new Error("undeclared yesimbot lookup"); + }, + }); + const usageOwner = { context: ctx }; + const ledger = getUsageLedger(ctx, usageOwner); + try { + captureContextSnapshot(ctx, { provider: "p", model: "m" }, { messages: [{ role: "user", content: "hello" }] }, "period", undefined, usageOwner); + const actions = new Map(); + const command = (name: string): any => ({ + subcommand: (sub: string) => command(sub), + option() { + return this; + }, + usage() {}, + example() {}, + action(fn: any) { + actions.set(name, fn); + }, + }); + registerHistoryInspection(ctx, command("history"), { + model: { usageOwner, peekContextLimit: () => ({ tokens: 1234, mode: "known", source: "fixture" }) }, + memory: { getMemoryBlocksForRendering: () => [{ content: "memory" }] }, + }); + const session = { platform: "test", userId: "admin" }; + const tokens = await actions.get(".tokens")({ session, source: "history.tokens" }); + expect(tokens).toContain("无匹配记录"); + const context = await actions.get(".context")({ session, source: "history.context" }); + expect(context).toContain("1 个区块"); + expect(context).toContain("最近快照 1 条"); + expect(context).toContain("1.234K"); + } finally { + await ledger.close(); + await rm(baseDir, { recursive: true, force: true }); + } +}); diff --git a/packages/core/tests/history-reset.spec.ts b/packages/core/tests/history-reset.spec.ts new file mode 100644 index 000000000..31f34bfbd --- /dev/null +++ b/packages/core/tests/history-reset.spec.ts @@ -0,0 +1,182 @@ +import { expect, it, vi } from "vitest"; + +import { prepareHistoryReset, registerHistoryResetParticipant } from "../src/world/history-reset"; + +it("invalidates every participant synchronously, drains before deletion and releases after failure", async () => { + const ctx: any = {}; + const calls: string[] = []; + let drain!: () => void; + const draining = new Promise((resolve) => { + drain = resolve; + }); + const unregister = registerHistoryResetParticipant(ctx, { + prepare() { + calls.push("invalidate"); + return { + ready: draining.then(() => { + calls.push("drained"); + }), + release: () => { + calls.push("release"); + }, + }; + }, + }); + const reset = prepareHistoryReset(ctx, { type: "all" }); + expect(calls).toEqual(["invalidate"]); + let ready = false; + const waiting = reset.ready.then(() => { + ready = true; + }); + await Promise.resolve(); + expect(ready).toBe(false); + drain(); + await waiting; + await reset.finish(); + await reset.finish(); + expect(calls).toEqual(["invalidate", "drained", "release"]); + unregister(); +}); + +it("notifies only participants attached to the selected core and releases successful participants if another fails", async () => { + const owner: any = {}; + const service = Object.defineProperty({}, "ctx", { value: owner }); + const core: any = { get: () => service }; + const extension: any = { get: () => service }; + const foreign: any = {}; + const release = vi.fn<() => void>(); + const unrelated = vi.fn<() => void>(); + const stops = [ + registerHistoryResetParticipant(extension, { prepare: () => ({ release }) }), + registerHistoryResetParticipant(core, { + prepare: () => { + throw new Error("drain failed"); + }, + }), + registerHistoryResetParticipant(foreign, { prepare: unrelated }), + ]; + const reset = prepareHistoryReset(core, { type: "all" }); + await expect(reset.ready).rejects.toThrow("drain failed"); + await reset.finish(); + expect(release).toHaveBeenCalledTimes(1); + expect(unrelated).not.toHaveBeenCalled(); + stops.forEach((stop) => stop()); +}); + +it("releases a participant even if its asynchronous drain fails", async () => { + const ctx: any = {}; + const release = vi.fn<() => void>(); + const unregister = registerHistoryResetParticipant(ctx, { prepare: () => ({ ready: Promise.reject(new Error("purge failed")), release }) }); + const reset = prepareHistoryReset(ctx, { type: "all" }); + await expect(reset.ready).rejects.toThrow("purge failed"); + await reset.finish(); + expect(release).toHaveBeenCalledOnce(); + unregister(); +}); + +it.each(["success", "delete failure", "participant failure"] as const)("releases the real clear command after %s", async (outcome) => { + const { HistoryCommandManager } = await import("../src/world/commands"); + const { SemanticMemoryManager } = await import("../src/world/l2-semantic-memory"); + const commands = new Map(); + const command = (name: string): any => { + const value: any = { + subcommand: (suffix: string) => command(name + suffix), + action: (callback: Function) => { + commands.set(name, callback); + return value; + }, + }; + for (const method of ["option", "usage", "example"]) value[method] = () => value; + return value; + }; + const logger = { info() {}, warn() {}, debug() {}, error() {} }; + const remove = vi.fn<(...args: any[]) => Promise>(async () => { + if (outcome === "delete failure") throw new Error("delete failed"); + return { removed: 0 }; + }); + const ctx: any = { command, logger, database: { get: async () => [], remove } }; + const logging: any = { getLogger: () => logger }; + const memory = new SemanticMemoryManager(ctx, { l2_memory: { enabled: false } } as any, logging, {} as any); + const service: any = { l2_manager: memory, l1_manager: { clearAgentHistory: async () => 0 }, recordSystemEvent: async () => {} }; + new HistoryCommandManager(ctx, service, {} as any, logging).register(); + const release = vi.fn<() => void>(); + let resolve!: () => void; + let reject!: (error: Error) => void; + const ready = new Promise((r, j) => { + resolve = r; + reject = j; + }); + const stop = registerHistoryResetParticipant(ctx, { prepare: () => ({ ready, release }) }); + try { + const pending = commands.get("history.clear")!({ session: { platform: "qq", channelId: "room" }, options: { all: "all" } }); + expect(memory.getHistoryGeneration({ platform: "qq", channelId: "room" })).toBe(1); + expect(remove).not.toHaveBeenCalled(); + if (outcome === "participant failure") reject(new Error("purge failed")); + else resolve(); + const result = await pending; + expect(release).toHaveBeenCalledOnce(); + expect(result).toContain(outcome === "success" ? "操作成功" : "失败"); + expect(remove).toHaveBeenCalledTimes(outcome === "participant failure" ? 0 : outcome === "delete failure" ? 1 : 4); + } finally { + stop(); + } +}); + +it("preserves participant reports on both successful and failed resets", async () => { + const ctx: any = {}; + const stop = registerHistoryResetParticipant(ctx, { + prepare: () => ({ + ready: Promise.reject(new Error("delete failed")), + report: () => "人物记忆:清理1个自有范围,保留1个共享范围。", + }), + }); + try { + const reset = prepareHistoryReset(ctx, { type: "all" }); + await expect(reset.ready).rejects.toThrow("delete failed"); + await reset.finish(); + expect(reset.reports()).toEqual(["人物记忆:清理1个自有范围,保留1个共享范围。"]); + } finally { + stop(); + } +}); + +it("shares lifecycle registrations between real ESM and CJS bundles", async () => { + const { build } = await import("esbuild"); + const fs = await import("node:fs/promises"); + const { tmpdir } = await import("node:os"); + const { default: path } = await import("node:path"); + const { pathToFileURL, fileURLToPath } = await import("node:url"); + const { execFile } = await import("node:child_process"); + const { promisify } = await import("node:util"); + const directory = await fs.mkdtemp(path.join(tmpdir(), "yib-reset-bundles-")); + try { + const entry = fileURLToPath(new URL("../src/world/history-reset.ts", import.meta.url)); + const esmPath = path.join(directory, "reset.mjs"), + cjsPath = path.join(directory, "reset.cjs"); + await Promise.all([ + build({ entryPoints: [entry], bundle: true, platform: "node", format: "esm", outfile: esmPath }), + build({ entryPoints: [entry], bundle: true, platform: "node", format: "cjs", outfile: cjsPath }), + ]); + const script = ` + import { createRequire } from 'node:module'; + import assert from 'node:assert/strict'; + const esm = await import(${JSON.stringify(pathToFileURL(esmPath).href)}); + const cjs = createRequire(import.meta.url)(${JSON.stringify(cjsPath)}); + const owner = {}; + const service = Object.defineProperty({}, 'ctx', { value: owner }); + const core = { get: () => service }, extension = { get: () => service }; + let calls = 0; + const stop = esm.registerHistoryResetParticipant(extension, { prepare() { calls++; } }); + const reset = cjs.prepareHistoryReset(core, { type: 'all' }); + await reset.ready; + await reset.finish(); + assert.equal(calls, 1); + stop(); + await cjs.prepareHistoryReset(core, { type: 'all' }).finish(); + assert.equal(calls, 1); + `; + await expect(promisify(execFile)(process.execPath, ["--input-type=module", "-e", script])).resolves.toMatchObject({ stderr: "" }); + } finally { + await fs.rm(directory, { recursive: true, force: true }); + } +}); diff --git a/packages/core/tests/history-topic-clear.spec.ts b/packages/core/tests/history-topic-clear.spec.ts new file mode 100644 index 000000000..7e74c35b3 --- /dev/null +++ b/packages/core/tests/history-topic-clear.spec.ts @@ -0,0 +1,71 @@ +import { expect, it } from "vitest"; + +import { HistoryCommandManager } from "../src/world/commands"; +function setup() { + const actions = new Map(); + const removed: any[] = []; + const events: any[] = []; + const command = (name: string) => { + const c: any = { + subcommand: (suffix: string) => command(name + suffix), + option: () => c, + usage: () => c, + example: () => c, + action: (fn: any) => { + actions.set(name, fn); + return c; + }, + }; + return c; + }; + const logger = { debug() {}, info() {}, warn() {}, error() {} }; + const ctx: any = { + command, + logger, + database: { + get: async () => [], + remove: async (table: any, query: any) => { + removed.push({ table, query }); + return { removed: 0 }; + }, + }, + }; + const service: any = { + l2_manager: { clearHistory: async (_: any, fn: any) => fn() }, + l1_manager: { clearAgentHistory: async () => 0 }, + recordSystemEvent: async (e: any) => events.push(e), + }; + new HistoryCommandManager(ctx, service, {} as any, { getLogger: () => logger } as any).register(); + return { + invoke: (options: any) => + actions.get("history.clear")({ session: { platform: "telegram", channelId: "7", guildId: "-1001", isDirect: false }, options }), + removed, + events, + }; +} +it("preserves an explicit canonical topic target", async () => { + const f = setup(); + const key = 'telegram-topic:["-1001","7"]'; + await f.invoke({ target: `telegram:${key}` }); + expect(f.removed[0].query.channelId).toBe(key); +}); +it("records the clear receipt in the current topic", async () => { + const f = setup(); + await f.invoke({}); + expect(f.events[0].channelId).toBe('telegram-topic:["-1001","7"]'); + expect(f.removed[0].query.channelId).toBe('telegram-topic:["-1001","7"]'); +}); +it("preserves tuple targets in channel lists alongside ordinary channels", async () => { + const f = setup(); + const key = 'telegram-topic:["-1001","7"]'; + await f.invoke({ channel: `${key},ordinary`, platform: "telegram" }); + expect(f.removed.some((item) => item.query.channelId === key)).toBe(true); + expect(f.removed.some((item) => item.query.channelId === "ordinary")).toBe(true); +}); +it("preserves multiple qualified targets", async () => { + const f = setup(); + const key = 'telegram-topic:["-1001","7"]'; + await f.invoke({ target: `telegram:${key},onebot:room` }); + expect(f.removed.some((item) => item.query.channelId === key)).toBe(true); + expect(f.removed.some((item) => item.query.channelId === "room" && item.query.platform === "onebot")).toBe(true); +}); diff --git a/packages/core/tests/image-context-lifecycle.spec.ts b/packages/core/tests/image-context-lifecycle.spec.ts new file mode 100644 index 000000000..d1ac1f192 --- /dev/null +++ b/packages/core/tests/image-context-lifecycle.spec.ts @@ -0,0 +1,112 @@ +import { h } from "koishi"; +import { expect, it, vi } from "vitest"; + +import { PromptContextBuilder } from "../src/agent/context-builder"; +import { loggingStub } from "./helpers/yesimbot"; + +function state(channel = "A", source = "msg", quoted = false, selfId = "bot") { + const image = { type: "message", id: source, elements: h.parse(''), timestamp: new Date() }; + return { + channel: { platform: "test", id: channel, type: "guild" }, + self: { id: selfId }, + l1_working_memory: { + processed_events: [], + new_events: [image, ...(quoted ? [{ type: "message", id: "quote", quoteId: source, elements: [], timestamp: new Date() }] : [])], + }, + } as any; +} +function setup() { + const asset = { + getInfo: vi.fn<(id: string) => Promise<{ id: string; mime: string } | undefined>>().mockResolvedValue({ id: "img", mime: "image/png" }), + read: vi.fn<(id: string) => Promise>().mockResolvedValue("data:image/jpeg;base64,eA=="), + }; + const builder = new PromptContextBuilder( + {} as any, + { enableVision: true, maxImagesInContext: 3, imageLifecycleCount: 1, allowedImageTypes: ["image/png"], detail: "low" } as any, + { model: { hasVisionCapability: () => true }, logging: loggingStub({ debug() {} }), asset, memory: {}, tool: {}, world: {} } as any, + ); + const build = (world = state()) => builder.buildMultimodalUserMessage("prompt", world); + const commit = (content: any) => (builder as any).commitMultimodalUsage([{ role: "user", content }]); + return { asset, builder, build, commit }; +} +it("does not consume the allowance before a successful model request", async () => { + const f = setup(); + const first = await f.build(); + expect(Array.isArray(first)).toBe(true); + expect(Array.isArray(await f.build())).toBe(true); + f.commit(first); + f.commit(first); + expect(await f.build()).toBe("prompt"); +}); +it("does not consume allowance after missing resource metadata", async () => { + const f = setup(); + f.asset.getInfo.mockResolvedValueOnce(undefined); + expect(await f.build()).toBe("prompt"); + expect(Array.isArray(await f.build())).toBe(true); +}); +it("does not consume allowance after resource read failure", async () => { + const f = setup(); + f.asset.read.mockRejectedValueOnce(new Error("unavailable")); + expect(await f.build()).toBe("prompt"); + expect(Array.isArray(await f.build())).toBe(true); +}); +it("allows quoted source images after the allowance is exhausted", async () => { + const f = setup(); + f.commit(await f.build()); + expect(Array.isArray(await f.build(state("A", "msg", true)))).toBe(true); +}); +it.each([state("B"), state("A", "new-message"), state("A", "msg", false, "other-bot")])( + "isolates the allowance by conversation, bot and source occurrence", + async (other) => { + const f = setup(); + f.commit(await f.build()); + expect(Array.isArray(await f.build(other))).toBe(true); + }, +); + +it.each(["performSingleHeartbeat", "performSingleHeartbeatWithStreaming", "performNativeHeartbeat"])( + "settles image usage only on model success in %s", + async (method) => { + const { HeartbeatProcessor } = await import("../src/agent/heartbeat-processor"); + const { Schema } = await import("koishi"); + const f = setup(); + let fail = true; + const processor = new HeartbeatProcessor( + {} as any, + {} as any, + { + contextBuilder: f.builder, + model: { + chat: async () => { + if (fail) throw new Error("upstream failed"); + return { text: "{}", toolCalls: [], usage: {} }; + }, + }, + logging: loggingStub({ debug() {}, info() {}, warn() {}, error() {}, success() {} }), + tool: { getAvailableTools: () => [{ name: "noop", description: "noop", parameters: Schema.object({}) }] }, + l1: { recordThought: async () => {} }, + prompt: {}, + world: {}, + } as any, + ); + (processor as any)._prepareLlmRequest = async () => ({ messages: [{ role: "user", content: await f.build() }], manualRecallIds: [] }); + (processor as any).parseAndValidateResponse = () => ({ thoughts: {}, actions: [], request_heartbeat: false }); + const stimulus: any = { session: { platform: "test", selfId: "bot", channelId: "A", isDirect: false } }; + await expect((processor as any)[method]("turn", stimulus, () => {})).rejects.toThrow("upstream failed"); + expect(Array.isArray(await f.build())).toBe(true); + fail = false; + await (processor as any)[method]("turn", stimulus, () => {}); + expect(await f.build()).toBe("prompt"); + }, +); + +it("keeps healthy images when a selected image cannot be decoded", async () => { + const f = setup(); + const world = state(); + world.l1_working_memory.new_events[0].elements = h.parse(''); + f.asset.getInfo.mockImplementation(async (id) => ({ id, mime: "image/png" })); + f.asset.read.mockRejectedValueOnce(new Error("decode error")); + const result = await f.build(world); + expect(f.asset.read).toHaveBeenCalledTimes(2); + expect(f.builder.getAttachedImageIds([{ role: "user", content: result }] as any)).toEqual(["img"]); +}); diff --git a/packages/core/tests/manual-recall.spec.ts b/packages/core/tests/manual-recall.spec.ts index 73bd812cd..d8f042de3 100644 --- a/packages/core/tests/manual-recall.spec.ts +++ b/packages/core/tests/manual-recall.spec.ts @@ -217,3 +217,51 @@ for (const mode of ["json", "stream", "native", "native-tools"]) { } }); } + +it("preserves every pending manual recall through actual journal pruning and restart", async () => { + const f = await fixture(); + try { + for (let page = 0; page < 3; page++) + await f.world.injectRecall(f.incoming, { kind: "l3", historyGeneration: 0, records: [{ content: `pending-pruned-${page}` }] }); + await f.manager.recordHeartbeat("last-turn", "onebot", f.incoming.channelId, 1, 1); + (f.manager as any).config.logLengthLimit = 1; + await f.manager.pruneOldData(); + const restarted = new InteractionManager(f.app, (f.manager as any).config, loggingStub(logger)); + const events = await restarted.getL1History("onebot", f.incoming.channelId, 1, "bot"); + expect(events.filter((event: any) => event.manualRecall).map((event: any) => event.result.records[0].content)).toEqual([ + "pending-pruned-0", + "pending-pruned-1", + "pending-pruned-2", + ]); + const history = (f.builder as any).applyGracefulDegradation(events); + expect(history.filter((event: any) => event.manualRecall)).toHaveLength(3); + } finally { + await f.close(); + } +}); + +it("retains the first consuming turn when pruning keeps a previously consumed manual page", async () => { + const f = await fixture(); + try { + await f.world.injectRecall(f.incoming, { kind: "l3", historyGeneration: 0, records: [{ content: "consumed-page" }] }); + const original = (await f.manager.getL1History("onebot", f.incoming.channelId, 20, "bot"))[0] as any; + // Persist the acknowledgment before the page to exercise receipt survival + // independently of append order (e.g. restored histories). + const filename = (f.manager as any).getLogFilePath("onebot", f.incoming.channelId); + const { readFile, writeFile } = await import("node:fs/promises"); + const pageLine = await readFile(filename, "utf8"); + await f.manager.recordThought("first-consumer", "onebot", f.incoming.channelId, { observe: "read", analyze_infer: "", plan: "" }, [original.turnId]); + const receiptLine = (await readFile(filename, "utf8")).slice(pageLine.length); + await writeFile(filename, receiptLine + pageLine); + (f.manager as any).config.logLengthLimit = 1; + await f.manager.pruneOldData(); + const reopened = new InteractionManager(f.app, (f.manager as any).config, loggingStub(logger)); + const events = await reopened.getL1History("onebot", f.incoming.channelId, 20, "bot"); + const { manualRecallOwners } = await import("../src/world/manual-recall"); + expect([...manualRecallOwners(events).values()]).toEqual(["first-consumer"]); + await reopened.pruneOldData(); + expect([...manualRecallOwners(await reopened.getL1History("onebot", f.incoming.channelId, 20, "bot")).values()]).toEqual([]); + } finally { + await f.close(); + } +}); diff --git a/packages/core/tests/model-audit-regressions.spec.ts b/packages/core/tests/model-audit-regressions.spec.ts new file mode 100644 index 000000000..86da349d9 --- /dev/null +++ b/packages/core/tests/model-audit-regressions.spec.ts @@ -0,0 +1,166 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { Bot, Context } from "koishi"; +import { expect, it, vi } from "vitest"; + +import { ChatModel } from "../src/model/chat-model"; +import { ModelAbility } from "../src/model/config"; +import { EvaluationModel } from "../src/model/evaluation-model"; +import { anthropicRequest } from "../src/model/native/anthropic"; +import { ModelService } from "../src/model/service"; +import { getUsageLedger } from "../src/model/usage"; +import { EventListenerManager } from "../src/world/event-listener"; +import { loggingStub, stubCtx } from "./helpers/yesimbot"; +const frame = (delta: any, finish_reason: any = null) => `data: ${JSON.stringify({ choices: [{ index: 0, delta, finish_reason }] })}\n\n`; +const tool = { type: "function", function: { name: "lookup", parameters: { type: "object" } }, execute: vi.fn<() => object>(() => ({})) }; +for (const stream of [false, true]) + for (const kind of ["invalid-json", "unknown-tool"]) + it(`returns raw ${kind} for framework correction (${stream})`, async () => { + const call = { + index: 0, + id: "call", + type: "function", + function: { name: kind === "unknown-tool" ? "unknown" : "lookup", arguments: kind === "invalid-json" ? "{invalid" : "{}" }, + }; + const model = new ChatModel( + stubCtx(), + () => ({ model: "m", baseURL: "https://test.invalid/v1/", apiKey: "test" }), + { modelId: "m", abilities: [ModelAbility.Chat], parameters: { stream } }, + async () => + new Response( + stream + ? frame({ tool_calls: [call] }) + frame({}, "tool_calls") + "data: [DONE]\n\n" + : JSON.stringify({ choices: [{ message: { role: "assistant", content: "", tool_calls: [call] }, finish_reason: "tool_calls" }] }), + { headers: { "content-type": stream ? "text/event-stream" : "application/json" } }, + ), + loggingStub(), + ); + const result = await model.chat({ messages: [], tools: [tool], singleStep: true, maxSteps: 1 }); + expect(result.toolCalls?.[0]).toMatchObject({ toolName: call.function.name, args: call.function.arguments }); + expect(tool.execute).not.toHaveBeenCalled(); + }); +it("sends reasoning on the actual next SDK HTTP request", async () => { + const sent: any[] = []; + const model = new ChatModel( + stubCtx(), + () => ({ model: "m", baseURL: "https://test.invalid/v1/", apiKey: "test" }), + { modelId: "m", abilities: [ModelAbility.Chat], parameters: { stream: true } }, + async (_u, init) => { + sent.push(JSON.parse(String(init?.body))); + return new Response( + sent.length === 1 + ? frame({ reasoning_content: "private reasoning" }) + + frame({ tool_calls: [{ index: 0, id: "call", type: "function", function: { name: "lookup", arguments: "{}" } }] }) + + frame({}, "tool_calls") + + "data: [DONE]\n\n" + : frame({ content: "done" }) + frame({}, "stop") + "data: [DONE]\n\n", + { headers: { "content-type": "text/event-stream" } }, + ); + }, + loggingStub(), + ); + await model.chat({ messages: [], tools: [tool], maxSteps: 2 }); + expect(sent[1].messages.find((m: any) => m.role === "assistant").reasoning_content).toBe("private reasoning"); +}); +it("finalizes failed evaluation HTTP responses without keeping a pending body", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "yib-eval-audit-")); + const ctx: any = stubCtx(); + ctx.baseDir = dir; + ctx.scope = { key: "audit" }; + const owner = { context: ctx }; + try { + const model = new EvaluationModel( + ctx, + () => ({ model: "m", baseURL: "https://test.invalid/v1/", apiKey: "x" }), + { modelId: "m", abilities: [ModelAbility.Evaluation] }, + async () => new Response("error", { status: 500 }), + loggingStub(), + owner, + ); + await expect(model.evaluate({}, { a: { type: "noul" } })).rejects.toThrow(Error); + const ledger = getUsageLedger(ctx, owner); + await new Promise((r) => setTimeout(r, 50)); + expect((await ledger.snapshot()).records).toMatchObject([{ status: "http-500", count: 1 }]); + await ledger.close(); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); +it("uses auto tools with manual Anthropic thinking", () => { + expect( + anthropicRequest({ model: "claude", messages: [], thinking: { type: "enabled", budget_tokens: 1024 }, tool_choice: "required", tools: [tool] }) + .tool_choice, + ).toEqual({ type: "auto" }); +}); + +it("filters after-send before observing or transforming a message for another instance", async () => { + const ctx = new Context(); + const bot = Object.create(Bot.prototype); + Object.assign(bot, { ctx, platform: "test", user: { id: "bot", name: "Bot" } }); + const services = ["a", "b"].map((channel) => { + const service = { observeChannel: vi.fn<() => void>(), recordMessage: vi.fn<() => void>(), isChannelAllowed: () => true }; + const asset = { transform: vi.fn<(text: string) => Promise>(async (text) => text) }; + const manager = new EventListenerManager( + ctx.intersect((session) => session.channelId === channel), + service as any, + {} as any, + loggingStub(), + asset as any, + ); + manager.start(); + return { service, asset, manager }; + }); + try { + const session = bot.session({ type: "send", channel: { id: "a", type: 0 }, message: { id: "sent", content: "hello" } }); + session.content = "hello"; + await ctx.parallel("after-send", session); + expect(services[0].service.recordMessage).toHaveBeenCalledOnce(); + expect(services[1].service.observeChannel).not.toHaveBeenCalled(); + expect(services[1].asset.transform).not.toHaveBeenCalled(); + expect(services[1].service.recordMessage).not.toHaveBeenCalled(); + } finally { + services.forEach(({ manager }) => manager.stop()); + await ctx.stop(); + } +}); + +it("applies configured deadline to a fixed chat model while retaining its capability API", async () => { + const logger: any = { extend: () => logger, debug() {}, info() {}, warn() {}, error() {}, success() {} }; + const ctx = stubCtx({ logging: { getLogger: () => logger } }); + let signal: AbortSignal | undefined; + const model = new ChatModel( + ctx, + () => ({ model: "m", baseURL: "https://test.invalid/v1/" }), + { + modelId: "m", + abilities: [ModelAbility.Chat], + parameters: { stream: false }, + timeoutPolicy: { totalTimeout: 0.01 }, + retryPolicy: { maxRetries: 0 }, + }, + async (_url, init) => { + signal = init?.signal as AbortSignal; + return new Promise((_resolve, reject) => { + if (signal!.aborted) reject(signal!.reason); + else signal!.addEventListener("abort", () => reject(signal!.reason), { once: true }); + }); + }, + loggingStub(logger), + ); + const service: any = Object.create(ModelService.prototype); + Object.assign(service, { ctx, logging: loggingStub(logger), getChatModel: () => model }); + const selected = service.useChatModel("p", "m"); + expect(selected.config).toBe(model.config); + expect(selected.isVisionModel()).toBe(false); + await expect(selected.chat({ messages: [] })).rejects.toThrow(Error); + expect(signal?.aborted).toBe(true); +}); +for (const selected of ["required", { type: "function", function: { name: "lookup" } }]) + it("downgrades forced Anthropic tools when manual thinking is enabled", () => { + expect( + anthropicRequest({ model: "claude", messages: [], thinking: { type: "enabled", budget_tokens: 1024 }, tool_choice: selected, tools: [tool] }) + .tool_choice, + ).toEqual({ type: "auto" }); + }); diff --git a/packages/core/tests/model-context-projection.spec.ts b/packages/core/tests/model-context-projection.spec.ts new file mode 100644 index 000000000..27812d0f2 --- /dev/null +++ b/packages/core/tests/model-context-projection.spec.ts @@ -0,0 +1,254 @@ +import { readFileSync } from "node:fs"; + +import { expect, it } from "vitest"; + +import { HeartbeatProcessor } from "../src/agent/heartbeat-processor"; +import { PromptService } from "../src/prompt/service"; +import { loggingStub, stubCtx } from "./helpers/yesimbot"; + +const resource = (name: string) => readFileSync(new URL(`../resources/${name}`, import.meta.url), "utf8"); +const message = (id: string, content: string, sender = "user"): any => ({ + type: "message", + id, + content, + sender: { id: sender }, + elements: [], + timestamp: new Date(), + is_message: true, +}); +async function prepare(processed: any[], userTemplate = resource("prompts/user_base.txt"), budget = 16000, activeTurn = "current") { + const diagnostics: string[] = []; + const logging = loggingStub({ debug: (text: string) => diagnostics.push(text) }); + const ctx = stubCtx({}); + const prompt = new PromptService(ctx, {} as any, logging); + prompt.registerTemplate("agent.system", "FIXED_PERSONA ".repeat(300)); + prompt.registerTemplate("agent.user", userTemplate); + for (const name of ["world_state", "l1_history_item"]) prompt.registerTemplate(`agent.partial.${name}`, resource(`templates/${name}.mustache`)); + const world: any = { + channel: { platform: "mock", id: "room" }, + self: { id: "bot" }, + l1_working_memory: { processed_events: processed, new_events: [message("trigger", "CURRENT_USER_CORRECTION")] }, + }; + const processor = new HeartbeatProcessor(ctx, { userTemplate, contextInputBudgetTokens: budget } as any, { + logging, + prompt, + model: {} as any, + tool: {} as any, + l1: {} as any, + world: {} as any, + contextBuilder: { + build: async () => ({ toolSchemas: [], memoryBlocks: [], worldState: world }), + buildMultimodalUserMessage: async (text: string) => text, + } as any, + }); + const request = await (processor as any)._prepareLlmRequest( + { type: "user_message", session: { platform: "mock", selfId: "bot", channelId: "room", userId: "user" }, payload: { messageIds: ["trigger"] } }, + activeTurn, + ); + return { request, diagnostics, world }; +} + +it("keeps the full budget report in server diagnostics and out of default/custom requests unless explicitly requested", async () => { + for (const template of [ + undefined, + "{{#WORLD_STATE}}{{> agent.partial.world_state}}{{/WORLD_STATE}}", + "{{#WORLD_STATE}}{{memoryBudgetReport}}{{/WORLD_STATE}}", + `${resource("prompts/user_base.txt").trimEnd()}\n{{#CONTEXT_BUDGET}}{{{CONTEXT_BUDGET}}}{{/CONTEXT_BUDGET}}\n`, + `${resource("prompts/user_base.txt").trimEnd()}\n{{#CONTEXT_BUDGET}}{{{CONTEXT_BUDGET}}}{{/CONTEXT_BUDGET}}\n`.replace( + /\n/g, + "\r\n", + ), + ]) { + const { request, diagnostics } = await prepare([], template, 1); + expect(JSON.stringify(request.messages)).not.toContain("context_budget"); + expect(JSON.stringify(request.messages)).not.toContain("protected_sources_or_fixed_overhead"); + expect(request.messages[0].content).toBe("FIXED_PERSONA ".repeat(300)); + expect(diagnostics.some((line) => line.includes("protectedOverBudget"))).toBe(true); + } + const explicit = await prepare([], "{{{CONTEXT_BUDGET}}}", 1); + expect(explicit.request.messages[1].content).toContain("protectedOverBudget"); +}); + +it("does not replay raw thoughts or duplicate a model tool receipt, but retains its action and observation", async () => { + const items: any[] = [ + { type: "agent_thought", turnId: "current", timestamp: new Date(), is_agent_thought: true, observe: "PRIVATE_REASONING", plan: "PRIVATE_REASONING" }, + { + type: "agent_action", + turnId: "current", + timestamp: new Date(), + is_agent_action: true, + function: "lookup", + params: { query: "VISIBLE_QUERY", inner_thoughts: "PRIVATE_REASONING" }, + }, + { + type: "agent_observation", + turnId: "current", + timestamp: new Date(), + is_agent_observation: true, + function: "lookup", + status: "success", + actionId: "action-1", + result: "UNIQUE_TOOL_RESULT", + }, + { + type: "system_event", + id: "receipt", + eventType: "tool-result", + timestamp: new Date(), + is_system_event: true, + message: "DUPLICATE_DIAGNOSTIC", + eventDetails: JSON.stringify({ + details: { + actor: "model", + requestId: "unique-invocation", + actionId: "action-1", + operation: "lookup", + status: "success", + receipt: "UNIQUE_TOOL_RESULT", + }, + }), + }, + ]; + const { request, world } = await prepare(items); + const text = JSON.stringify(request.messages); + expect(text).not.toContain("PRIVATE_REASONING"); + expect(text).not.toContain("DUPLICATE_DIAGNOSTIC"); + expect(text).not.toContain(""); + expect(text.match(/UNIQUE_TOOL_RESULT/g)).toHaveLength(1); + expect(text).toContain("VISIBLE_QUERY"); + expect(text).toContain("CURRENT_USER_CORRECTION"); + expect(world.l1_working_memory.processed_events[0].observe).toBe("PRIVATE_REASONING"); +}); + +it("drops stale tool tracks before recent user conversation rather than protecting the previous task", async () => { + const { request } = await prepare( + [ + { + type: "agent_action", + turnId: "old", + timestamp: new Date(0), + is_agent_action: true, + function: "lookup", + params: { query: "OLD_ACCOUNT_TOPIC ".repeat(3000) }, + }, + { + type: "agent_observation", + turnId: "old", + timestamp: new Date(0), + is_agent_observation: true, + function: "lookup", + status: "success", + result: "OLD_ACCOUNT_TOPIC ".repeat(3000), + }, + message("recent-user", "RECENT_USER_CONVERSATION"), + ], + undefined, + 6000, + ); + const text = JSON.stringify(request.messages); + expect(text).not.toContain("OLD_ACCOUNT_TOPIC"); + expect(text).toContain("RECENT_USER_CONVERSATION"); + expect(text).toContain("CURRENT_USER_CORRECTION"); +}); + +it("keeps actual assistant dialogue once, with a compact confirmed-send reference and an unchanged audit", async () => { + const sent = { ...message("sent-id", "VISIBLE_ASSISTANT_REPLY", "bot"), timestamp: new Date(20) }; + const action: any = { + type: "agent_action", + actionId: "send-1", + turnId: "previous", + timestamp: new Date(10), + is_agent_action: true, + function: "send_message", + params: { message: "VISIBLE_ASSISTANT_REPLY", inner_thoughts: "PRIVATE_SEND_REASON" }, + }; + const observation: any = { + type: "agent_observation", + actionId: "send-1", + turnId: "previous", + timestamp: new Date(30), + is_agent_observation: true, + function: "send_message", + status: "success", + }; + const { request } = await prepare([action, sent, observation]); + const text = JSON.stringify(request.messages); + expect(text.match(/VISIBLE_ASSISTANT_REPLY/g)).toHaveLength(1); + expect(text).toContain("sent-id"); + expect(text).not.toContain("PRIVATE_SEND_REASON"); + expect(action.params.message).toBe("VISIBLE_ASSISTANT_REPLY"); +}); + +const receipt = (id: string, actionId: string): any => ({ + type: "system_event", + id, + eventType: "tool-result", + timestamp: new Date(), + is_system_event: true, + message: "diagnostic", + eventDetails: JSON.stringify({ + details: { + actor: "model", + requestId: id, + actionId, + operation: "lookup", + status: "success", + summary: `receipt-${actionId}`, + receipt: "RAW_TRANSPORT_DIAGNOSTIC", + }, + }), +}); + +it("retains unmatched external receipts and matches repeated tool operations only by unique action ID", async () => { + const observation: any = { + type: "agent_observation", + actionId: "lookup-1", + turnId: "current", + timestamp: new Date(), + is_agent_observation: true, + function: "lookup", + status: "success", + result: "FIRST_LOOKUP_RESULT", + }; + const { request } = await prepare([observation, receipt("event-1", "lookup-1"), receipt("event-2", "lookup-2")]); + const text = JSON.stringify(request.messages); + expect(text).not.toContain("receipt-lookup-1"); + expect(text).toContain("receipt-lookup-2"); + expect(text).toContain("FIRST_LOOKUP_RESULT"); + expect(text).not.toContain("RAW_TRANSPORT_DIAGNOSTIC"); +}); + +it("projects textual tool definitions only into the JSON fallback request", async () => { + const logging = loggingStub(); + const ctx = stubCtx({}); + const prompt = new PromptService(ctx, {} as any, logging); + prompt.registerTemplate("agent.system", "{{#TOOL_DEFINITION}}TEXT_TOOL={{name}}{{/TOOL_DEFINITION}}"); + prompt.registerTemplate("agent.user", "question"); + const processor = new HeartbeatProcessor(ctx, { nativeToolCalling: true, contextInputBudgetTokens: 0 } as any, { + logging, + prompt, + model: {} as any, + tool: { getAvailableTools: () => [] } as any, + l1: {} as any, + world: {} as any, + contextBuilder: { + build: async () => ({ + toolSchemas: [{ name: "lookup", description: "read", parameters: [] }], + memoryBlocks: [], + worldState: { + channel: { platform: "mock", id: "room" }, + self: { id: "bot" }, + l1_working_memory: { processed_events: [], new_events: [] }, + }, + }), + buildMultimodalUserMessage: async (text: string) => text, + } as any, + }); + const request = await (processor as any)._prepareLlmRequest({ + type: "user_message", + session: { platform: "mock", selfId: "bot", channelId: "room", userId: "user" }, + payload: { messageIds: [] }, + }); + expect(request.messages[0].content).not.toContain("TEXT_TOOL"); + expect(request.fallbackMessages[0].content).toContain("TEXT_TOOL=lookup"); +}); diff --git a/packages/core/tests/model-context-tool-integration.spec.ts b/packages/core/tests/model-context-tool-integration.spec.ts new file mode 100644 index 000000000..6680fb927 --- /dev/null +++ b/packages/core/tests/model-context-tool-integration.spec.ts @@ -0,0 +1,138 @@ +import { readFileSync } from "node:fs"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { Context, Schema } from "koishi"; +import { expect, it } from "vitest"; + +import { PromptContextBuilder } from "../src/agent/context-builder"; +import { HeartbeatProcessor } from "../src/agent/heartbeat-processor"; +import { ToolService } from "../src/extension/service"; +import { PromptService } from "../src/prompt/service"; +import { TableName } from "../src/shared/constants"; +import { ContextBuilder } from "../src/world/context-builder"; +import { InteractionManager } from "../src/world/interaction-manager"; +import { loggingStub } from "./helpers/yesimbot"; + +const resource = (name: string) => readFileSync(new URL(`../resources/${name}`, import.meta.url), "utf8"); + +it("continues a real tool-service/journal cycle with one causal result and no reasoning or diagnostic replay", async () => { + const baseDir = await mkdtemp(path.join(tmpdir(), "model-tool-projection-")); + const ctx = new Context({ baseDir }); + ctx.baseDir = baseDir; + const errors: string[] = []; + const logging = loggingStub({ + debug: (...args: unknown[]) => { + for (const arg of args) { + if (arg instanceof Error) errors.push(arg.stack ?? arg.message); + else if (typeof arg === "string" && /根本原因|堆栈追踪/.test(arg)) errors.push(arg); + } + }, + info() {}, + warn() {}, + success() {}, + error: (...args: unknown[]) => errors.push(args.map(String).join(" ")), + }); + ctx.set("yesimbot", { logging }); + const events: any[] = []; + const message: any = { + id: "trigger", + platform: "mock", + channelId: "room", + channelType: "guild", + content: "CURRENT_USER_QUESTION", + sender: { id: "user" }, + timestamp: new Date(), + }; + ctx.set("database", { get: async (table: string) => (table === TableName.Messages ? [message] : table === TableName.SystemEvents ? events : []) } as any); + const session: any = { platform: "mock", selfId: "bot", channelId: "room", userId: "user", isDirect: false, bot: { selfId: "bot", user: { id: "bot" } } }; + const config: any = { + advanced: { maxRetry: 0 }, + heartbeat: 3, + enableVision: false, + contextInputBudgetTokens: 16000, + l1_memory: { maxMessages: 100, keepFullTurnCount: 3 }, + l2_memory: { enabled: false }, + l3_memory: { enabled: false }, + }; + const journal = new InteractionManager(ctx, config, logging); + const dataBuilder = new ContextBuilder(ctx, config, journal, {} as any, {} as any, logging); + const world: any = { + buildWorldState: (current: any) => dataBuilder.build(current), + getConversationState: async () => ({ unknown: true }), + recordSystemEvent: async (event: any) => { + events.push(event); + return true; + }, + }; + const tools = new ToolService(ctx, config, { world, logging } as any); + tools.registerTool({ + name: "lookup", + description: "lookup", + readOnly: true, + parameters: Schema.object({ query: Schema.string(), inner_thoughts: Schema.string() }), + execute: async () => ({ status: "success", result: "UNIQUE_LOOKUP_RESULT" }), + }); + tools.registerTool({ + name: "send_message", + description: "send", + parameters: Schema.object({ message: Schema.string() }), + execute: async () => ({ status: "success" }), + }); + const prompt = new PromptService(ctx, {} as any, logging); + prompt.registerTemplate("agent.system", "FIXED_SYSTEM"); + config.userTemplate = resource("prompts/user_base.txt"); + prompt.registerTemplate("agent.user", config.userTemplate); + for (const name of ["world_state", "l1_history_item"]) prompt.registerTemplate(`agent.partial.${name}`, resource(`templates/${name}.mustache`)); + const requests: any[] = []; + const model: any = { + hasVisionCapability: () => false, + chat: async (request: any) => { + requests.push(request); + const first = requests.length === 1; + return { + text: JSON.stringify({ + thoughts: { observe: "PRIVATE_MODEL_REASON" }, + actions: first + ? [{ function: "lookup", params: { query: "VISIBLE_QUERY", inner_thoughts: "PRIVATE_TOOL_REASON" } }] + : [{ function: "send_message", params: { message: "VISIBLE_REPLY" } }], + request_heartbeat: first, + }), + }; + }, + }; + const builder = new PromptContextBuilder(ctx, config, { + model, + world, + tool: tools, + logging, + asset: {} as any, + memory: { getMemoryBlocksForRendering: () => [] } as any, + }); + const processor = new HeartbeatProcessor(ctx, config, { model, world, tool: tools, logging, l1: journal, prompt, contextBuilder: builder }); + try { + const success = await processor.runCycle({ type: "user_message", session, payload: { messageIds: ["trigger"] } } as any); + expect(errors).toEqual([]); + expect(success).toBe(true); + expect(requests).toHaveLength(2); + const second = JSON.stringify(requests[1].messages); + expect(second.match(/UNIQUE_LOOKUP_RESULT/g)).toHaveLength(1); + expect(second).toContain("VISIBLE_QUERY"); + expect(second).toContain("CURRENT_USER_QUESTION"); + expect(second).not.toContain("PRIVATE_MODEL_REASON"); + expect(second).not.toContain("PRIVATE_TOOL_REASON"); + expect(second).not.toContain(""); + expect(second).not.toContain("context_budget"); + const audit = await journal.getAgentHistoryFromFile("mock", "room", 100); + const observation = audit.events.find((item) => item.type === "agent_observation" && item.function === "lookup"); + expect(observation?.type === "agent_observation" && observation.actionId).toBe(events[0].payload.actionId); + expect(events[0].payload.requestId).not.toBe(events[0].payload.turnId); + expect(events[0].payload.receipt).toContain("UNIQUE_LOOKUP_RESULT"); + expect(JSON.stringify(audit.events)).toContain("PRIVATE_MODEL_REASON"); + expect(JSON.stringify(audit.events)).toContain("PRIVATE_TOOL_REASON"); + } finally { + await ctx.stop(); + await rm(baseDir, { recursive: true, force: true }); + } +}); diff --git a/packages/core/tests/model-conversation-report.spec.ts b/packages/core/tests/model-conversation-report.spec.ts new file mode 100644 index 000000000..102503368 --- /dev/null +++ b/packages/core/tests/model-conversation-report.spec.ts @@ -0,0 +1,135 @@ +import { expect, it } from "vitest"; + +import { ConversationReportRecorder, withConversationReport } from "../src/logger/conversation-report"; +import { ChatModel } from "../src/model/chat-model"; +import { ModelAbility } from "../src/model/config"; +import { observeModelReportRequest, observeModelReportTransport, withModelConversationReport } from "../src/model/conversation-capture"; +import { createNativeFetch } from "../src/model/native-fetch"; +import { loggingStub, stubCtx } from "./helpers/yesimbot"; + +const source = { requestId: "chat-71", provider: "test-provider", model: "test-model", purpose: "测试" }; +const endpoint = "https://provider.example/v1/chat/completions"; +const target = { platform: "onebot", selfId: "12345678", channelId: "23456789" }; +const frameworkBody = JSON.stringify({ + model: "test-model", + messages: [ + { role: "system", content: "rendered system prompt" }, + { role: "user", content: "latest chat context" }, + ], + tools: [{ type: "function", function: { name: "get_time", parameters: { type: "object" } } }], +}); + +it("captures final prompts and exact native JSON before conversion, without exposing transport credentials", async () => { + const report = new ConversationReportRecorder(); + const original = JSON.stringify({ candidates: [{ content: { parts: [{ text: "native result" }] }, finishReason: "STOP" }] }); + const provider = createNativeFetch( + { type: "Google Gemini", baseURL: "https://provider.example/v1/", apiKey: "not-for-the-report" } as any, + observeModelReportTransport(async () => Response.json(JSON.parse(original))), + ); + await withConversationReport(report.start(target, "turn-1"), async () => { + const normalized = await withModelConversationReport(source, async () => { + const response = await observeModelReportRequest(provider)(endpoint, { method: "POST", body: frameworkBody }); + return response.json(); + }); + expect(normalized.choices[0].message.content).toBe("native result"); + const entries = report.snapshot()?.entries; + expect(entries).toMatchObject([ + { kind: "model.request", data: { ...source, wireRequest: 1, payload: JSON.parse(frameworkBody) } }, + { + kind: "model.provider_request", + data: { ...source, wireRequest: 1, payload: { systemInstruction: { parts: [{ text: "rendered system prompt" }] } } }, + }, + { kind: "model.response", data: { ...source, wireRequest: 1, status: 200, outcome: "complete", raw: original } }, + ]); + expect(JSON.stringify(entries)).not.toContain("not-for-the-report"); + expect(JSON.stringify(entries)).not.toContain(endpoint); + }); +}); + +it("records a partial stream by the time the model call fails, without masking the source error", async () => { + const report = new ConversationReportRecorder(); + const sourceError = new Error("socket disconnected"); + let pulls = 0; + const start = 'data: {"delta":"第一行"}\n\n'; + const payload = new TextEncoder().encode(start); + const stream = new ReadableStream( + { + pull(controller) { + if (pulls === 0) controller.enqueue(payload.subarray(0, 19)); + else if (pulls === 1) controller.enqueue(payload.subarray(19)); + else controller.error(sourceError); + pulls++; + }, + }, + { highWaterMark: 0 }, + ); + const request = observeModelReportRequest(async () => new Response(stream, { headers: { "content-type": "text/event-stream" } })); + await withConversationReport(report.start(target, "turn-2"), async () => { + await expect(withModelConversationReport(source, async () => (await request(endpoint, { body: frameworkBody })).text())).rejects.toBe(sourceError); + expect(report.snapshot()?.entries.at(-1)).toMatchObject({ + kind: "model.response", + data: { outcome: "read_error", raw: start, receivedBytes: payload.length, truncated: false }, + }); + }); +}); + +it("honors downstream cancellation and avoids pulling a disabled capture", async () => { + let pulls = 0; + let cancelled: unknown; + const response = new Response( + new ReadableStream( + { + pull(controller) { + pulls++; + controller.enqueue(new Uint8Array([65])); + }, + cancel(reason) { + cancelled = reason; + }, + }, + { highWaterMark: 0 }, + ), + ); + const request = observeModelReportRequest(observeModelReportTransport(async () => response)); + expect(await withModelConversationReport(source, () => request(endpoint))).toBe(response); + expect(pulls).toBe(0); + + const report = new ConversationReportRecorder(); + await withConversationReport(report.start(target, "turn-3"), async () => { + await withModelConversationReport(source, async () => { + const reader = (await request(endpoint)).body!.getReader(); + expect(await reader.read()).toEqual({ done: false, value: new Uint8Array([65]) }); + await reader.cancel("consumer stopped"); + }); + expect(pulls).toBe(1); + expect(cancelled).toBe("consumer stopped"); + expect(report.snapshot()?.entries.at(-1)).toMatchObject({ kind: "model.response", data: { outcome: "cancelled", raw: "A" } }); + }); +}); + +it("attaches an HTTP failure body to the actual chat request report", async () => { + const report = new ConversationReportRecorder(); + const raw = '{"error":{"message":"model is overloaded"}}'; + const model = new ChatModel( + stubCtx(), + () => ({ baseURL: "https://provider.example/v1/", apiKey: "not-for-the-report", model: "test-model" }), + { modelId: "test-model", providerName: "test-provider", abilities: [ModelAbility.Chat] }, + observeModelReportTransport(async () => new Response(raw, { status: 503, headers: { "content-type": "application/json" } })), + loggingStub(), + ); + await withConversationReport(report.start(target, "turn-4"), async () => { + await expect(model.chat({ messages: [{ role: "system", content: "actual system prompt" }], stream: false })).rejects.toMatchObject({ + context: { httpStatus: 503 }, + }); + const entries = report.snapshot()?.entries; + expect(entries).toMatchObject([ + { + kind: "model.request", + data: { provider: "test-provider", model: "test-model", payload: { messages: [{ role: "system", content: "actual system prompt" }] } }, + }, + { kind: "model.response", data: { outcome: "complete", status: 503, raw } }, + ]); + expect(entries?.[0].data).toHaveProperty("requestId", expect.stringMatching(/^chat-/)); + expect(JSON.stringify(entries)).not.toContain("not-for-the-report"); + }); +}); diff --git a/packages/core/tests/model-failover.spec.ts b/packages/core/tests/model-failover.spec.ts index 26e7b5b3b..a26536b2c 100644 --- a/packages/core/tests/model-failover.spec.ts +++ b/packages/core/tests/model-failover.spec.ts @@ -47,7 +47,7 @@ function streamResponse(text: string): Response { }); } -function fixture(responses: Array) { +function fixture(responses: Array, maxRetries = 1, onContentFailure = ContentFailureAction.AugmentAndRetry) { const logger = { extend() { return this; @@ -78,7 +78,7 @@ function fixture(responses: Array) { abilities: [ModelAbility.Chat, ModelAbility.Vision], parameters: { stream: true }, timeoutPolicy: { firstTokenTimeout: 5, totalTimeout: 10 }, - retryPolicy: { maxRetries: modelId === "primary" ? 1 : 0, onContentFailure: ContentFailureAction.AugmentAndRetry }, + retryPolicy: { maxRetries: modelId === "primary" ? maxRetries : 0, onContentFailure }, }, fetch, loggingStub(logger), @@ -104,10 +104,9 @@ describe("model failover message isolation", () => { expect(result.text).toBe(validResponse); expect(requests.map((request) => request.model)).toEqual(["primary", "primary"]); expect(requests[0].messages).toEqual(originalMessages()); - expect(requests[1].messages).toHaveLength(2); - expect(requests[1].messages[0].role).toBe("system"); - expect(requests[1].messages[0].content).toContain("JSON formatter"); - expect(requests[1].messages[1]).toEqual({ role: "user", content: malformedResponse }); + expect(requests[1].messages.slice(0, originalMessages().length)).toEqual(originalMessages()); + expect(requests[1].messages.at(-2)).toEqual({ role: "assistant", content: malformedResponse }); + expect(requests[1].messages.at(-1)?.content).toContain("validation"); expect(options.messages).toBe(messages); expect(options.messages).toEqual(originalMessages()); }); @@ -119,7 +118,7 @@ describe("model failover message isolation", () => { expect(result.text).toBe(validResponse); expect(requests.map((request) => request.model)).toEqual(["primary", "primary", "fallback"]); - expect(requests[1].messages[1]).toEqual({ role: "user", content: malformedResponse }); + expect(requests[1].messages.at(-2)).toEqual({ role: "assistant", content: malformedResponse }); expect(requests[2].messages).toEqual(originalMessages()); expect(requests.every((request) => request.stream)).toBe(true); expect(options.messages).toEqual(originalMessages()); @@ -136,3 +135,63 @@ describe("model failover message isolation", () => { expect(requests[2].messages).toEqual(originalMessages()); }); }); + +it("corrects plain prose using the original question, persona, tools and image", async () => { + const prose = "I cannot produce the requested format yet."; + const { switcher, requests, options } = fixture([prose, validResponse]); + const result = await switcher.chat(options); + expect(result.text).toBe(validResponse); + expect(requests).toHaveLength(2); + expect(requests[1].messages.slice(0, originalMessages().length)).toEqual(originalMessages()); + expect(requests[1].messages.at(-2)).toEqual({ role: "assistant", content: prose }); + expect(requests[1].messages.at(-1)?.content).toContain("validation"); + expect(options.messages).toEqual(originalMessages()); +}); + +it("does not retry malformed output on a model configured with zero retries", async () => { + const { switcher, requests, options } = fixture(["invalid", validResponse], 0); + expect((await switcher.chat(options)).text).toBe(validResponse); + expect(requests.map((request) => request.model)).toEqual(["primary", "fallback"]); + expect(requests[1].messages).toEqual(originalMessages()); +}); + +it("honors immediate failover instead of retrying invalid content on the same model", async () => { + const { switcher, requests, options } = fixture(["invalid", validResponse], 2, ContentFailureAction.FailoverToNext); + expect((await switcher.chat(options)).text).toBe(validResponse); + expect(requests.map((request) => request.model)).toEqual(["primary", "fallback"]); +}); + +it("bounds repeated format corrections and gives the fallback the original context", async () => { + const { switcher, requests, options } = fixture(["first invalid", "second invalid", validResponse]); + expect((await switcher.chat(options)).text).toBe(validResponse); + expect(requests.map((request) => request.model)).toEqual(["primary", "primary", "fallback"]); + expect(requests[2].messages).toEqual(originalMessages()); +}); + +it("corrects a syntactically valid response that fails the action schema", async () => { + const { switcher, requests, options } = fixture(["{}", validResponse]); + options.validation = { + validator: (text) => { + try { + const value = JSON.parse(text); + return { valid: !!value.thoughts && Array.isArray(value.actions), error: "Missing thoughts or actions" }; + } catch { + return { valid: false, error: "Invalid JSON" }; + } + }, + }; + expect((await switcher.chat(options)).text).toBe(validResponse); + expect(requests).toHaveLength(2); + expect(requests[1].messages.slice(0, originalMessages().length)).toEqual(originalMessages()); + expect(requests[1].messages.at(-2)).toEqual({ role: "assistant", content: "{}" }); +}); + +it("keeps correction feedback bounded instead of accumulating invalid responses", async () => { + const oversized = "broken output ".repeat(1000); + const { switcher, requests, options } = fixture([oversized, "another invalid response", validResponse], 2); + expect((await switcher.chat(options)).text).toBe(validResponse); + expect(requests).toHaveLength(3); + expect(requests[1].messages.at(-2)?.content).toHaveLength(8000); + expect(requests[2].messages).toHaveLength(originalMessages().length + 2); + expect(requests[2].messages.at(-2)).toEqual({ role: "assistant", content: "another invalid response" }); +}); diff --git a/packages/core/tests/model-group-selection.spec.ts b/packages/core/tests/model-group-selection.spec.ts index 1a2b1d965..87481480e 100644 --- a/packages/core/tests/model-group-selection.spec.ts +++ b/packages/core/tests/model-group-selection.spec.ts @@ -237,3 +237,97 @@ it("keeps round-robin cursors local to each returned switcher", async () => { expect((await first.chat(input())).text).toBe("b"); expect((await second.chat(input())).text).toBe("a"); }); + +it("rejects duplicate group names before changing task mappings", () => { + const config: any = { + providers: [{ name: "p", models: [{ modelId: "m", abilities: [] }] }], + modelGroups: [ + { name: "same", models: [{ providerName: "p", modelId: "m" }] }, + { name: "same", models: [{ providerName: "p", modelId: "m" }] }, + ], + task: { chat: "same" }, + }; + expect(() => (ModelService.prototype as any).validateConfig.call({ config, logger, ctx: { scope: { update: vi.fn<() => void>() } } })).toThrow(/重复/); +}); + +it("removes image parts when falling back to a text-only group without mutating the caller", async () => { + const seen: any[] = []; + const model = new ExternalModel("text", [], async () => response("ok")); + const originalChat = model.chat.bind(model); + model.chat = async (options) => { + seen.push(options); + return originalChat(options); + }; + const request = imageInput(); + request.messages[0].content = [{ type: "text", text: "keep question" }, ...(request.messages[0].content as any[])]; + await group([model]).chat(request); + expect(seen[0].messages[0].content).toEqual([{ type: "text", text: "keep question" }]); + expect((request.messages[0].content as any[]).some((part) => part.type === "image_url")).toBe(true); +}); + +it.each([ModelSwitchingStrategy.Failover, ModelSwitchingStrategy.RoundRobin])( + "keeps the same conversation payload across real model requests with %s", + async (strategy) => { + const { ChatModel } = await import("../src/model/chat-model"); + const bodies: any[] = []; + const transport = async (_url: any, init: any) => { + bodies.push(JSON.parse(init.body)); + return bodies.length === 1 + ? new Response('{"error":{"message":"unavailable"}}', { status: 503, headers: { "content-type": "application/json" } }) + : new Response(JSON.stringify({ choices: [{ message: { role: "assistant", content: "ok" }, finish_reason: "stop" }], usage: {} }), { + headers: { "content-type": "application/json" }, + }); + }; + const models = ["one", "two"].map( + (id) => + new ChatModel( + ctx, + () => ({ baseURL: "https://test.invalid/", apiKey: "test", model: id }), + { modelId: id, abilities: [ModelAbility.Chat], parameters: { stream: false }, retryPolicy: { maxRetries: 0 } } as any, + transport as any, + logging, + ), + ); + const switcher = new ChatModelSwitcher( + ctx, + { name: "shared", strategy, models: models.map((m) => descriptor(m.id)) }, + (_provider, id) => models.find((m) => m.id === id)!, + logging, + ); + const messages: any[] = [ + { role: "system", content: "same persona" }, + { role: "user", content: "Earlier group history, tool observations and current question" }, + ]; + await switcher.chat({ messages, stream: false }); + await switcher.chat({ messages, stream: false }); + expect(new Set(bodies.map((body) => body.model)).size).toBe(2); + expect(bodies.length).toBeGreaterThanOrEqual(3); + for (const body of bodies) expect(body.messages).toEqual(messages); + }, +); + +it("keeps image-only inputs nonempty when using a text-only group", async () => { + let received: any; + const model = new ExternalModel("text", [], async () => response("ok")); + const originalChat = model.chat.bind(model); + model.chat = async (options) => { + received = options; + return originalChat(options); + }; + await group([model]).chat(imageInput()); + expect(received.messages[0].content).toBe("[图片:当前模型不支持识图]"); +}); + +it("preserves non-image assistant content during text-only fallback", async () => { + let received: any; + const model = new ExternalModel("text", [], async () => response("ok")); + const originalChat = model.chat.bind(model); + model.chat = async (options) => { + received = options; + return originalChat(options); + }; + const request = imageInput(); + request.messages.push({ role: "assistant", content: [] }); + await group([model]).chat(request); + expect(received.messages[1]).toEqual({ role: "assistant", content: [] }); +}); diff --git a/packages/core/tests/model-groups-control.spec.ts b/packages/core/tests/model-groups-control.spec.ts new file mode 100644 index 000000000..5dd328fc1 --- /dev/null +++ b/packages/core/tests/model-groups-control.spec.ts @@ -0,0 +1,102 @@ +import { Schema } from "koishi"; +import { expect, it } from "vitest"; +import { createRenderer, defineComponent, h, nextTick, ref } from "vue"; + +import { ModelGroups } from "../client/model-groups"; + +type Node = { type: string; props: Record; children: Node[]; parent?: Node; text?: string }; +const node = (type: string): Node => ({ type, props: {}, children: [] }); + +function mount(disabled = false) { + const renderer = createRenderer({ + createElement: node, + createText: (text) => ({ ...node("text"), text }), + createComment: (text) => ({ ...node("comment"), text }), + setText: (element, text) => { + element.text = text; + }, + setElementText: (element, text) => { + element.text = text; + element.children = []; + }, + parentNode: (element) => element.parent!, + nextSibling: (element) => element.parent?.children[element.parent.children.indexOf(element) + 1] ?? null, + patchProp: (element, key, _before, after) => { + element.props[key] = after; + }, + insert: (element, parent, anchor) => { + if (element.parent) element.parent.children.splice(element.parent.children.indexOf(element), 1); + element.parent = parent; + const index = anchor ? parent.children.indexOf(anchor) : -1; + parent.children.splice(index < 0 ? parent.children.length : index, 0, element); + }, + remove: (element) => { + element.parent?.children.splice(element.parent.children.indexOf(element), 1); + }, + }); + const original = [ + { name: "A", models: [{ providerName: "p", modelId: "m" }] }, + { name: "B", models: [] }, + ]; + const value = ref(structuredClone(original)); + const updates: any[] = []; + const root = node("root"); + const app = renderer.createApp({ + render: () => + h(ModelGroups, { + schema: Schema.array(Schema.object({ name: Schema.string() })), + prefix: "modelGroups.", + modelValue: value.value, + disabled, + "onUpdate:modelValue": (next) => { + updates.push(next); + value.value = next; + }, + }), + }); + app.component( + "k-schema", + defineComponent({ + props: ["prefix", "modelValue"], + setup: (props) => () => h("input", { "data-prefix": props.prefix, value: props.modelValue?.name }), + }), + ); + app.mount(root); + const all = (parent = root): Node[] => [parent, ...parent.children.flatMap((child) => all(child))]; + return { value, updates, original, all, app }; +} +it("deletes the selected group, reindexes native controls, and can delete the final group", async () => { + const f = mount(); + f.all() + .find((element) => element.props["aria-label"] === "删除模型组 1")! + .props.onClick(); + await nextTick(); + expect(f.value.value.map((row) => row.name)).toEqual(["B"]); + expect(f.original).toHaveLength(2); + expect(f.all().find((element) => element.type === "input")!.props["data-prefix"]).toBe("modelGroups[0]."); + f.all() + .find((element) => element.props["aria-label"] === "删除模型组 1")! + .props.onClick(); + await nextTick(); + expect(f.value.value).toEqual([]); + expect(f.all().some((element) => element.text?.includes("自动创建默认模型组"))).toBe(true); + f.app.unmount(); +}); +it("keeps deletion inert when the configuration is disabled", () => { + const f = mount(true); + const button = f.all().find((element) => element.props["aria-label"] === "删除模型组 1")!; + expect(button.props.disabled).toBe(true); + button.props.onClick(); + expect(f.updates).toEqual([]); + f.app.unmount(); +}); +it("supports moving entries without changing their contents", async () => { + const f = mount(); + f.all() + .find((element) => element.props["aria-label"] === "下移模型组 1")! + .props.onClick(); + await nextTick(); + expect(f.value.value.map((row) => row.name)).toEqual(["B", "A"]); + expect(f.value.value[1].models).toEqual(f.original[0].models); + f.app.unmount(); +}); diff --git a/packages/core/tests/model-retry-diagnostics.spec.ts b/packages/core/tests/model-retry-diagnostics.spec.ts index c46bb6bc3..e50e92f2f 100644 --- a/packages/core/tests/model-retry-diagnostics.spec.ts +++ b/packages/core/tests/model-retry-diagnostics.spec.ts @@ -1,5 +1,7 @@ import { expect, it } from "vitest"; +import { ChatModel } from "../src/model/chat-model"; +import { ModelAbility } from "../src/model/config"; import { ChatModelSwitcher } from "../src/model/service"; import { AppError, ErrorDefinitions } from "../src/shared/errors"; import { loggingStub, stubCtx } from "./helpers/yesimbot"; @@ -120,3 +122,57 @@ it("shows failover and recovery through the next candidate at ordinary log level expect(transition).toBeGreaterThanOrEqual(0); expect(recovery).toBeGreaterThan(transition); }); + +it.each([400, 401, 403, 404, 413, 422])("does not replay deterministic HTTP %s requests before failover", async (httpStatus) => { + let calls = 0; + const { switcher, logs } = setup( + async () => { + calls++; + throw new AppError(ErrorDefinitions.LLM.REQUEST_FAILED, { + args: [httpStatus === 400 ? 'HTTP 400: {"code":"1301","message":"content filtered"}' : `HTTP ${httpStatus}`], + context: { httpStatus }, + }); + }, + 1, + async () => success, + ); + expect(await switcher.chat({ messages: [] })).toBe(success); + expect(calls).toBe(1); + expect(logs.some((line) => line.includes("确定性请求错误") && line.includes("不重复"))).toBe(true); +}); + +it("still retries a timed-out model within the configured bound", async () => { + let calls = 0; + const { switcher } = setup(async () => { + if (++calls === 1) throw new AppError(ErrorDefinitions.LLM.TIMEOUT, { args: [1] }); + return success; + }); + expect(await switcher.chat({ messages: [] })).toBe(success); + expect(calls).toBe(2); +}); + +it("does not replay an actual HTTP 400 content-filtered transport response", async () => { + const logger: any = { extend: () => logger, debug() {}, info() {}, warn() {}, error() {}, success() {} }; + const ctx = stubCtx({ logging: { getLogger: () => logger } }); + let requests = 0; + const model = new ChatModel( + ctx, + () => ({ model: "filtered", baseURL: "https://test.invalid/v1/" }), + { + modelId: "filtered", + abilities: [ModelAbility.Chat], + parameters: { stream: false }, + retryPolicy: { maxRetries: 2 }, + }, + async () => { + requests++; + return Response.json({ error: { code: "1301", message: "content filtered" } }, { status: 400 }); + }, + loggingStub(logger), + ); + const switcher = new ChatModelSwitcher(ctx, { name: "test", models: [{ providerName: "p", modelId: "filtered" }] }, () => model, loggingStub(logger)); + const error = await switcher.chat({ messages: [] }).catch((error) => error); + expect(requests).toBe(1); + expect(error.context.accumulatedErrors[0].error.context.httpStatus).toBe(400); + expect(error.context.accumulatedErrors[0].error.message).toContain("1301"); +}); diff --git a/packages/core/tests/native-ollama.spec.ts b/packages/core/tests/native-ollama.spec.ts index 90c081173..d60441d50 100644 --- a/packages/core/tests/native-ollama.spec.ts +++ b/packages/core/tests/native-ollama.spec.ts @@ -148,7 +148,7 @@ for (const stream of [false, true]) { (error) => error, ); expect(error === null).toBe(reason === "stop"); - expect(executions).toBe(reason === "stop" ? 1 : 0); + expect(executions).toBe(0); }); } it("rejects incomplete NDJSON before tool execution", async () => { @@ -251,7 +251,7 @@ it("signals real native tool activity before EOF and withholds execution", async await pending; expect(observed).toBe(true); expect(count).toBe(1); - expect(executions).toBe(1); + expect(executions).toBe(0); }); it("preserves NDJSON business errors", async () => { const { f } = fixture(() => ndjson([{ error: "model unavailable" }])); diff --git a/packages/core/tests/native-provider.spec.ts b/packages/core/tests/native-provider.spec.ts index 9016ee00c..231d35b79 100644 --- a/packages/core/tests/native-provider.spec.ts +++ b/packages/core/tests/native-provider.spec.ts @@ -325,8 +325,8 @@ for (const stream of [false, true]) { }); expect(result.toolCalls).toHaveLength(1); expect(result.toolCalls[0].toolName).toBe("lookup"); - // Existing xsai execution behavior is unchanged; the native bridge itself adds no execution. - expect(calls).toBe(1); + // Single-step returns calls for framework validation and execution. + expect(calls).toBe(0); expect(result.usage).toMatchObject({ prompt_tokens: 3, completion_tokens: 4 }); }); } @@ -517,7 +517,7 @@ for (const protocol of ["gemini-native", "anthropic-native"]) { ); expect(outcome.error === null).toBe(complete); expect(outcome.result?.toolCalls?.length ?? 0).toBe(complete ? 1 : 0); - expect(executions).toBe(complete ? 1 : 0); + expect(executions).toBe(0); expect(outcome.error === null ? "" : String(outcome.error)).toMatch(complete ? /^$/ : /失败|截断|结束|EOF/); expect(observed).toBe(true); expect(starts).toBe(1); diff --git a/packages/core/tests/native-qwen.spec.ts b/packages/core/tests/native-qwen.spec.ts index 440d42f0d..64e8bcd27 100644 --- a/packages/core/tests/native-qwen.spec.ts +++ b/packages/core/tests/native-qwen.spec.ts @@ -174,7 +174,7 @@ for (const stream of [false, true]) { (error) => error, ); expect(error === null).toBe(reason === "tool_calls"); - expect(executions).toBe(reason === "tool_calls" ? 1 : 0); + expect(executions).toBe(0); expect(calls[0].init.headers.get("X-DashScope-SSE")).toBe(stream ? "enable" : null); }); } @@ -281,7 +281,7 @@ it("signals Qwen tool activity before EOF without exposing executable deltas", a await pending; expect(observed).toBe(true); expect(count).toBe(1); - expect(executions).toBe(1); + expect(executions).toBe(0); }); it("cancels Qwen native bodies and preserves abort signal", async () => { let cancelled = false; @@ -433,8 +433,8 @@ for (const stream of [false, true]) { () => null, (error) => error, ); - expect(error === null).toBe(matching); - expect(executions).toBe(matching ? 1 : 0); + expect(error === null).toBe(!named || matching); + expect(executions).toBe(0); expect(calls[0].body.parameters.tool_choice).not.toBe("required"); expect(typeof calls[0].body.parameters.tool_choice).not.toBe("object"); expect(calls[0].body.parameters.enable_thinking).toBe(true); diff --git a/packages/core/tests/native-reasoning-continuation.spec.ts b/packages/core/tests/native-reasoning-continuation.spec.ts new file mode 100644 index 000000000..59de11f75 --- /dev/null +++ b/packages/core/tests/native-reasoning-continuation.spec.ts @@ -0,0 +1,204 @@ +import { expect, it } from "vitest"; + +import { ChatModel } from "../src/model/chat-model"; +import { ModelAbility } from "../src/model/config"; +import { loggingStub, stubCtx } from "./helpers/yesimbot"; + +const frame = (delta: any, finish_reason: string | null = null) => `data: ${JSON.stringify({ choices: [{ index: 0, delta, finish_reason }] })}\n\n`; +function fixture(body: string | (() => string), contentType = "text/event-stream", status = 200) { + const logs: string[] = []; + const requests: any[] = []; + const logger: any = Object.fromEntries( + ["debug", "info", "warn", "error", "success"].map((key) => [key, (...args: unknown[]) => logs.push(args.join(" "))]), + ); + logger.extend = () => logger; + const model = new ChatModel( + stubCtx({ logging: { getLogger: () => logger } }), + () => ({ baseURL: "https://test.invalid/v1/", apiKey: "test", model: "test" }), + { modelId: "test", providerName: "test", abilities: [ModelAbility.Chat], parameters: { stream: true, custom: [] } }, + (async (_url, init) => { + requests.push(JSON.parse(String(init?.body))); + return new Response(typeof body === "function" ? body() : body, { status, headers: { "content-type": contentType } }); + }) as typeof fetch, + loggingStub(logger), + ); + return { model, logs, requests }; +} +const options = { + messages: [{ role: "user", content: "hello" }] as any, + tools: [{ type: "function", function: { name: "lookup", description: "lookup", parameters: { type: "object" } }, execute: () => ({}) }] as any, + toolChoice: "required" as const, + maxSteps: 1, + singleStep: true, +}; +it("preserves native reasoning only on the matching completed assistant tool message", async () => { + const { model, logs, requests } = fixture( + frame({ reasoning_content: "PRIVATE_REASONING_" }) + + frame({ reasoning_content: "CONTINUATION" }) + + frame({ tool_calls: [{ index: 0, id: "opaque:call", type: "function", function: { name: "lookup", arguments: '{"action":' } }] }) + + frame({ tool_calls: [{ index: 0, function: { arguments: '"read"}' } }] }) + + frame({}, "tool_calls") + + "data: [DONE]\n\n", + ); + const result = await model.chat(options); + expect(requests[0].tool_choice).toBe("required"); + expect(requests[0].tools).toMatchObject([{ type: "function", function: { name: "lookup", parameters: { type: "object" } } }]); + const assistant = result.messages.find((message) => message.role === "assistant") as any; + expect(assistant?.reasoning_content).toBe("PRIVATE_REASONING_CONTINUATION"); + expect(assistant?.tool_calls.map((call) => call.id)).toEqual(result.toolCalls.map((call) => call.toolCallId)); + expect(assistant?.tool_calls[0].function.arguments).toBe('{"action":"read"}'); + expect(result.text).toBe(""); + expect(logs.join("\n")).not.toContain("PRIVATE_REASONING_"); +}); +it("does not expose reasoning as a successful continuation when the stream is truncated", async () => { + const { model } = fixture( + frame({ reasoning_content: "PRIVATE" }) + + frame({ tool_calls: [{ index: 0, id: "call", type: "function", function: { name: "lookup", arguments: "{}" } }] }), + ); + await expect(model.chat(options)).rejects.toMatchObject({ code: "LLM.REQUEST_FAILED" }); +}); + +it("keeps reasoning scoped to the completed tool step across multiple responses", async () => { + let requests = 0; + const { model } = fixture(() => { + requests++; + if (requests > 2) return frame({ content: "finished" }) + frame({}, "stop") + "data: [DONE]\n\n"; + return ( + frame({ reasoning_content: `step-${requests}` }) + + frame({ tool_calls: [{ index: 0, id: `call-${requests}`, type: "function", function: { name: "lookup", arguments: "{}" } }] }) + + frame({}, "tool_calls") + + "data: [DONE]\n\n" + ); + }); + const result = await model.chat({ ...options, maxSteps: 3, singleStep: false }); + expect(requests).toBe(3); + const assistants = result.messages.filter((message) => message.role === "assistant") as any[]; + expect(assistants.map((message) => message.reasoning_content)).toEqual(["step-1", "step-2"]); + expect(assistants.map((message) => message.tool_calls.map((call) => call.id))).toEqual([["call-1"], ["call-2"]]); +}); + +it("does not associate reasoning with an ambiguous call ID reused by multiple steps", async () => { + let requests = 0; + const { model } = fixture(() => { + requests++; + if (requests > 2) return frame({ content: "finished" }) + frame({}, "stop") + "data: [DONE]\n\n"; + return ( + frame({ reasoning_content: `step-${requests}` }) + + frame({ tool_calls: [{ index: 0, id: "reused", type: "function", function: { name: "lookup", arguments: JSON.stringify({ step: requests }) } }] }) + + frame({}, "tool_calls") + + "data: [DONE]\n\n" + ); + }); + const result = await model.chat({ ...options, maxSteps: 3, singleStep: false }); + expect(result.toolCalls).toHaveLength(2); + expect(result.messages).toEqual([]); +}); +it("preserves assistant content sharing a tool delta without using it as validated response text", async () => { + const { model } = fixture( + frame({ + content: "native-preface", + reasoning_content: "reason", + tool_calls: [{ index: 0, id: "call", type: "function", function: { name: "lookup", arguments: "{}" } }], + }) + + frame({}, "tool_calls") + + "data: [DONE]\n\n", + ); + const result = await model.chat(options); + expect(result.messages[0].content).toBe("native-preface"); + expect(result.text).toBe(""); +}); + +it("retains the original assistant reasoning when non-stream single-step completion stops the SDK", async () => { + let requests = 0; + const { model } = fixture(() => { + requests++; + return JSON.stringify({ + choices: [ + { + index: 0, + finish_reason: "tool_calls", + message: { + role: "assistant", + content: null, + reasoning_content: "nonstream-reason", + tool_calls: [{ index: 0, id: "nonstream:call", type: "function", function: { name: "lookup", arguments: "{}" } }], + }, + }, + ], + usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }, + }); + }, "application/json"); + const result = await model.chat({ ...options, stream: false }); + expect(requests).toBe(1); + expect((result.messages[0] as any)?.reasoning_content).toBe("nonstream-reason"); + expect((result.messages[0] as any)?.tool_calls[0].id).toBe(result.toolCalls[0].toolCallId); +}); + +it("does not execute tools or add requests when non-stream response fails", async () => { + let requests = 0; + let executions = 0; + const { model } = fixture( + () => { + requests++; + return JSON.stringify({ error: { message: "rate limited" } }); + }, + "application/json", + 429, + ); + await expect( + model.chat({ + ...options, + stream: false, + tools: [ + { + ...options.tools[0], + execute: () => { + executions++; + return {}; + }, + }, + ], + }), + ).rejects.toMatchObject({ code: "LLM.RATE_LIMIT_EXCEEDED" }); + expect(requests).toBe(1); + expect(executions).toBe(0); +}); +it("honors non-stream cancellation before returning captured metadata", async () => { + const controller = new AbortController(); + const reason = new DOMException("cancelled", "AbortError"); + let executions = 0; + const { model } = fixture(() => { + controller.abort(reason); + return JSON.stringify({ + choices: [ + { + index: 0, + finish_reason: "tool_calls", + message: { + role: "assistant", + content: null, + reasoning_content: "reason", + tool_calls: [{ index: 0, id: "call", type: "function", function: { name: "lookup", arguments: "{}" } }], + }, + }, + ], + }); + }, "application/json"); + await expect( + model.chat({ + ...options, + stream: false, + abortSignal: controller.signal, + tools: [ + { + ...options.tools[0], + execute: () => { + executions++; + return {}; + }, + }, + ], + }), + ).rejects.toBe(reason); + expect(executions).toBe(0); +}); diff --git a/packages/core/tests/native-tool-recovery.spec.ts b/packages/core/tests/native-tool-recovery.spec.ts new file mode 100644 index 000000000..4bad63e60 --- /dev/null +++ b/packages/core/tests/native-tool-recovery.spec.ts @@ -0,0 +1,236 @@ +import { Schema } from "koishi"; +import { expect, it, vi } from "vitest"; + +import { AgentBehaviorConfigSchema } from "../src/agent/config"; +import { HeartbeatProcessor } from "../src/agent/heartbeat-processor"; +import { withReplyTurnGuard } from "../src/agent/reply-turn"; +import { loggingStub, stubCtx } from "./helpers/yesimbot"; + +const call = (toolName: string, args: unknown, toolCallId = "call") => ({ toolCallId, toolCallType: "function", toolName, args: JSON.stringify(args) }); +function setup(responses: any[], config: Record = {}) { + const logger = { + debug: vi.fn<(...args: any[]) => void>(), + info: vi.fn<(...args: any[]) => void>(), + warn: vi.fn<(...args: any[]) => void>(), + error: vi.fn<(...args: any[]) => void>(), + success: vi.fn<(...args: any[]) => void>(), + }; + const requests: any[] = []; + const invoke = vi.fn<(...args: any[]) => Promise>(async () => ({ status: "success" })); + const definitions = [ + { name: "send_message", description: "send", parameters: Schema.object({ message: Schema.string().required() }) }, + { name: "lookup", description: "lookup", parameters: Schema.object({ action: Schema.string().required() }) }, + ]; + const processor = new HeartbeatProcessor(stubCtx({ logging: { getLogger: () => logger } }), { heartbeat: 1, nativeToolCalling: true, ...config } as any, { + model: { + chat: async (options: any) => { + requests.push(structuredClone(options.messages)); + const response = responses[Math.min(requests.length - 1, responses.length - 1)]; + if (response instanceof Error) throw response; + if (typeof response === "function") return response(); + return response; + }, + } as any, + prompt: {} as any, + tool: { getAvailableTools: () => definitions, getTool: (name) => definitions.find((tool) => tool.name === name), invoke } as any, + l1: { recordThought: async () => {}, recordHeartbeat: async () => {}, recordAction: async () => "action", recordObservation: async () => {} } as any, + contextBuilder: {} as any, + logging: loggingStub(logger), + world: {} as any, + }); + (processor as any)._prepareLlmRequest = async () => ({ messages: [] }); + const run = () => processor.runCycle({ session: { platform: "qq", channelId: "g", cid: "qq:g" } } as any); + return { requests, invoke, logger, run }; +} +it("feeds invalid argument paths back as paired tool responses before any batch action executes", async () => { + const f = setup([ + { toolCalls: [call("send_message", { message: "discard" }, "send"), call("lookup", {}, "lookup")] }, + { toolCalls: [call("send_message", { message: "accepted" }, "corrected")] }, + ]); + expect(await f.run()).toBe(true); + expect(f.invoke.mock.calls).toEqual([["send_message", { message: "accepted" }, expect.anything(), expect.objectContaining({ attachedImageIds: [] })]]); + const repair = f.requests[1]; + expect(repair.find((message) => message.role === "assistant").tool_calls).toHaveLength(2); + const results = repair.filter((message) => message.role === "tool"); + expect(results.map((message) => message.tool_call_id)).toEqual(["send", "lookup"]); + expect(results[1].content).toContain("action"); + expect(f.logger.error).not.toHaveBeenCalled(); +}); +it("does not execute tool tags written into plain text and asks for a native correction", async () => { + const f = setup([ + { text: '{"function":"send_message","params":{"message":"discard"}}' }, + { toolCalls: [call("send_message", { message: "accepted" })] }, + ]); + expect(await f.run()).toBe(true); + expect(f.requests).toHaveLength(2); + expect(f.invoke.mock.calls[0][1]).toEqual({ message: "accepted" }); + expect(f.logger.error).not.toHaveBeenCalled(); +}); +it("bounds malformed response correction and reports the classified failure only once", async () => { + const f = setup([{ toolCalls: [call("lookup", { secret: "DO_NOT_LOG" })] }]); + expect(await f.run()).toBe(false); + expect(f.requests).toHaveLength(2); + expect(f.invoke).not.toHaveBeenCalled(); + const errors = f.logger.error.mock.calls.flat().join("\n"); + expect(errors.match(/错误报告/g)).toHaveLength(1); + expect(errors).toContain("LLM.OUTPUT_PARSING_FAILED"); + expect(JSON.stringify(f.logger.error.mock.calls)).not.toContain("DO_NOT_LOG"); +}); +it("does not retry or replay a batch after actual execution has started", async () => { + const f = setup([{ toolCalls: [call("send_message", { message: "once" }), call("lookup", { action: "read" }, "lookup")] }]); + f.invoke.mockImplementationOnce(async () => ({ status: "success" })).mockImplementationOnce(async () => ({ status: "error" })); + expect(await f.run()).toBe(true); + expect(f.requests).toHaveLength(1); + expect(f.invoke).toHaveBeenCalledTimes(2); +}); +it("preserves successful legacy JSON responses without a native retry", async () => { + const f = setup([ + { text: JSON.stringify({ thoughts: {}, actions: [{ function: "send_message", params: { message: "legacy" } }], request_heartbeat: false }) }, + ]); + expect(await f.run()).toBe(true); + expect(f.requests).toHaveLength(1); +}); + +it("does not retry transport errors as model argument corrections", async () => { + const f = setup([new Error("transport failed")]); + expect(await f.run()).toBe(false); + expect(f.requests).toHaveLength(1); + expect(f.invoke).not.toHaveBeenCalled(); +}); +it.each(["invalid-json", "conflicting-id"])("corrects %s without executing the original batch", async (scenario) => { + const original = + scenario === "invalid-json" + ? [{ ...call("lookup", {}), args: "{invalid" }] + : [call("send_message", { message: "discard" }), call("lookup", { action: "read" })]; + const f = setup([{ toolCalls: original }, { toolCalls: [call("send_message", { message: "accepted" }, "fixed")] }]); + expect(await f.run()).toBe(true); + expect(f.invoke).toHaveBeenCalledTimes(1); + expect(f.invoke.mock.calls[0][1]).toEqual({ message: "accepted" }); +}); + +it("preserves opaque tool identifiers and assistant reasoning metadata during correction", async () => { + const id = "yib-qwen:opaque/+==:continuation"; + const f = setup([ + { + toolCalls: [call("lookup", {}, id)], + messages: [ + { + role: "assistant", + content: "", + reasoning_content: "retained provider reasoning", + tool_calls: [{ id, type: "function", function: { name: "lookup", arguments: "{}" } }], + }, + ], + }, + { toolCalls: [call("send_message", { message: "accepted" })] }, + ]); + expect(await f.run()).toBe(true); + expect(f.requests[1].find((message) => message.role === "assistant").reasoning_content).toBe("retained provider reasoning"); + expect(f.requests[1].find((message) => message.role === "tool").tool_call_id).toBe(id); +}); + +it("does not issue correction requests after the reply turn is cancelled", async () => { + const controller = new AbortController(); + const f = setup([ + () => { + controller.abort(); + return { toolCalls: [call("lookup", {})] }; + }, + ]); + expect(await withReplyTurnGuard(() => !controller.signal.aborted, f.run, controller.signal)).toBe(false); + expect(f.requests).toHaveLength(1); + expect(f.invoke).not.toHaveBeenCalled(); + expect(f.logger.error).not.toHaveBeenCalled(); +}); + +it("does not unwrap tool markup into an otherwise valid legacy action batch", async () => { + const legacy = JSON.stringify({ thoughts: {}, actions: [{ function: "send_message", params: { message: "discard" } }], request_heartbeat: false }); + const f = setup([{ text: `${legacy}` }, { toolCalls: [call("send_message", { message: "accepted" })] }]); + expect(await f.run()).toBe(true); + expect(f.requests).toHaveLength(2); + expect(f.invoke.mock.calls[0][1]).toEqual({ message: "accepted" }); +}); + +it("allows literal tool tag text inside a valid legacy JSON message", async () => { + const f = setup([ + { + text: JSON.stringify({ + thoughts: {}, + actions: [{ function: "send_message", params: { message: "literal text" } }], + request_heartbeat: false, + }), + }, + ]); + expect(await f.run()).toBe(true); + expect(f.requests).toHaveLength(1); + expect(f.invoke.mock.calls[0][1]).toEqual({ message: "literal text" }); +}); + +it.each([0, 2, 4])("stops after the configured %i additional argument corrections", async (retries) => { + const f = setup([{ toolCalls: [call("lookup", {})] }], { nativeToolCorrectionRetries: retries }); + expect(await f.run()).toBe(false); + expect(f.requests).toHaveLength(retries + 1); + expect(f.invoke).not.toHaveBeenCalled(); +}); + +it.each([0, 2])("stops after the configured %i additional plain-text corrections", async (retries) => { + const f = setup([{ text: "invalid plain text" }], { nativeToolCorrectionRetries: retries }); + expect(await f.run()).toBe(false); + expect(f.requests).toHaveLength(retries + 1); + expect(f.invoke).not.toHaveBeenCalled(); +}); + +it("executes only the successful batch after multiple corrections", async () => { + const f = setup( + [ + { toolCalls: [call("lookup", {}, "first")] }, + { toolCalls: [call("lookup", {}, "second")] }, + { toolCalls: [call("send_message", { message: "accepted" }, "third")] }, + ], + { nativeToolCorrectionRetries: 2 }, + ); + expect(await f.run()).toBe(true); + expect(f.requests).toHaveLength(3); + expect(f.invoke.mock.calls).toEqual([["send_message", { message: "accepted" }, expect.anything(), expect.objectContaining({ attachedImageIds: [] })]]); + expect(f.requests[2].filter((message) => message.role === "tool").map((message) => message.tool_call_id)).toEqual(["first", "second"]); +}); + +it("defaults correction retries to one and accepts only non-negative safe integers", () => { + expect(AgentBehaviorConfigSchema({}).nativeToolCorrectionRetries).toBe(1); + for (const value of [0, 2, 20]) expect(AgentBehaviorConfigSchema({ nativeToolCorrectionRetries: value }).nativeToolCorrectionRetries).toBe(value); + for (const value of [-1, 0.5, Infinity, NaN, Number.MAX_SAFE_INTEGER + 1]) { + expect(() => AgentBehaviorConfigSchema({ nativeToolCorrectionRetries: value })).toThrow(); + } +}); + +it.each(["ordinary reply", '{"function":"send_message"}'])( + "classifies missing native calls without claiming the text is malformed JSON: %s", + async (text) => { + const f = setup([{ text }], { nativeToolCorrectionRetries: 1 }); + expect(await f.run()).toBe(false); + expect(f.requests).toHaveLength(2); + expect(f.invoke).not.toHaveBeenCalled(); + const errors = f.logger.error.mock.calls.flat().join("\n"); + expect(errors).toContain("LLM.NATIVE_TOOL_CALL_MISSING"); + expect(errors).toContain("原生工具"); + expect(errors).not.toContain("不是有效的 JSON"); + }, +); + +it("ends a native turn silently without executing a tool or retrying", async () => { + const f = setup([{ toolCalls: [call("end_turn_without_reply", {})] }]); + expect(await f.run()).toBe(false); + expect(f.requests).toHaveLength(1); + expect(f.invoke).not.toHaveBeenCalled(); + expect(f.logger.error).not.toHaveBeenCalled(); +}); + +it("rejects silence mixed with a real action before any side effect", async () => { + const f = setup([ + { toolCalls: [call("end_turn_without_reply", {}, "silent"), call("send_message", { message: "discard" }, "send")] }, + { toolCalls: [call("end_turn_without_reply", {}, "corrected")] }, + ]); + expect(await f.run()).toBe(false); + expect(f.requests).toHaveLength(2); + expect(f.invoke).not.toHaveBeenCalled(); +}); diff --git a/packages/core/tests/native-workers.spec.ts b/packages/core/tests/native-workers.spec.ts index 6988cf8bd..783896414 100644 --- a/packages/core/tests/native-workers.spec.ts +++ b/packages/core/tests/native-workers.spec.ts @@ -130,7 +130,7 @@ for (const stream of [false, true]) { }); expect(result.toolCalls).toHaveLength(1); expect(result.toolCalls[0].toolName).toBe("lookup"); - expect(calls).toBe(1); + expect(calls).toBe(0); }); } it("Workers ChatModel never executes buffered tool on truncated stream", async () => { @@ -304,14 +304,14 @@ for (const stream of [false, true]) { }, })), }); - const rejected = returned === "none" || (typeof selected !== "string" && returned !== "lookup"); + const rejected = typeof selected !== "string" && returned !== "lookup"; const outcome = await request.then( (value) => ({ toolCalls: value.toolCalls.length, error: "" }), (error) => ({ toolCalls: 0, error: String(error) }), ); - expect(outcome.toolCalls).toBe(rejected ? 0 : 1); + expect(outcome.toolCalls).toBe(rejected || returned === "none" ? 0 : 1); expect(outcome.error).toMatch(rejected ? /tool_choice|网络请求失败/ : /^$/); - expect(calls).toBe(rejected ? 0 : 1); + expect(calls).toBe(0); expect(t.calls).toHaveLength(1); expect(t.calls[0].body).not.toHaveProperty("tool_choice"); }); diff --git a/packages/core/tests/onebot-faces.spec.ts b/packages/core/tests/onebot-faces.spec.ts index 79b62b1be..d81b23e84 100644 --- a/packages/core/tests/onebot-faces.spec.ts +++ b/packages/core/tests/onebot-faces.spec.ts @@ -117,3 +117,14 @@ it("does not fetch detached replies or overwrite a body changed by another plugi session.platform = "discord"; expect(await normalizeOneBotMessageContent(session, '')).toBe(''); }); + +it("deduplicates the bridge's Markdown projection while preserving a quote and a matching structured mention", async () => { + const quote = ''; + const markdown = ''; + const plain = ' hello'; + expect(await normalizeOneBotMessageContent({ platform: "onebot" } as any, quote + markdown + plain)).toBe(quote + plain); + for (const content of [markdown, markdown + ' hello', markdown + ' different', markdown + plain + '']) { + expect(await normalizeOneBotMessageContent({ platform: "onebot" } as any, content)).toBe(content); + } + expect(await normalizeOneBotMessageContent({ platform: "qq" } as any, markdown + plain)).toBe(markdown + plain); +}); diff --git a/packages/core/tests/prompt-data-boundaries.spec.ts b/packages/core/tests/prompt-data-boundaries.spec.ts new file mode 100644 index 000000000..1f95780da --- /dev/null +++ b/packages/core/tests/prompt-data-boundaries.spec.ts @@ -0,0 +1,119 @@ +import { readFileSync } from "node:fs"; + +import { expect, it, onTestFinished } from "vitest"; + +import DailyPlannerExtension from "../../daily-planner/src/index"; +import { escapeContext } from "../../person-memory/src/context"; +import { apply as applyPersonMemory } from "../../person-memory/src/index"; +import { PersonStore, accountRef, mindScope, sceneKey } from "../../person-memory/src/store"; +import { fixture } from "../../person-memory/tests/helpers"; +import { PromptService } from "../src/prompt/service"; +import { loggingStub } from "./helpers/yesimbot"; + +const logger = { info() {}, warn() {}, error() {}, debug() {} }; +const syntax = "{{session.bot.config.token}} {{#unclosed}} {{> agent.system}}"; +const session: any = { + platform: "onebot", + channelId: "g", + selfId: "bot", + userId: "u", + isDirect: false, + content: "hello", + author: { id: "u", name: "User" }, + bot: { selfId: "bot", config: { token: "FAKE_SECRET_MUST_NOT_LEAK" } }, +}; + +it.each([false, true])("keeps real person-memory injection data literal with sharedMemory=%s", async (sharedMemory) => { + let prompt!: PromptService; + const app = await fixture({ onTestFinished } as any, (ctx) => { + prompt = new PromptService(ctx, { injectionPlaceholder: "extensions" } as any, loggingStub(logger)); + Object.defineProperty(ctx, "bots", { + value: [ + { platform: "onebot", selfId: "bot", session: (event: any) => ({ ...event, channelId: event.channel.id, isDirect: event.channel.type === 1 }) }, + ], + }); + ctx.set("yesimbot", { + prompt, + tool: { capabilities: { trustedToolSession: 1 }, registerTool: () => () => {}, unregisterTool() {} }, + world: { capabilities: { beforeUserStimulus: 1, memoryCorrectionFilter: 1 }, isChannelAllowed: () => true }, + }); + ctx.plugin({ + inject: ["database", "yesimbot"], + apply: (ready) => + applyPersonMemory(ready, { + enabled: true, + mode: "auto", + sharedMemory, + modelGroup: "", + summaryThreshold: 6, + cooldownSeconds: 600, + timeoutSeconds: 30, + maxQueue: 32, + recallScope: "current", + profileSystemPrompt: `PROFILE_POLICY ${syntax}`, + } as any), + }); + }); + await prompt.start(); + const store = new PersonStore(app.database, "auto"); + const scope = sharedMemory ? mindScope(session) : sceneKey(session); + const ref = sharedMemory ? accountRef(session.platform, session.userId) : session.userId; + await store.recognize(scope, ref, "Profile owner"); + await store.setProfile(scope, ref, `PROFILE_DATA ${syntax}`, "admin"); + prompt.registerTemplate("agent.system", "{{extensions}}"); + const rendered = await prompt.render("agent.system", { session }); + expect(rendered).toContain("PROFILE_DATA"); + expect(rendered).toContain(escapeContext(syntax)); + expect(rendered).toContain(`PROFILE_POLICY ${syntax}`); + expect(rendered).not.toContain("FAKE_SECRET_MUST_NOT_LEAK"); +}); + +it("keeps real daily-plan injection data literal while resolving the trusted clock value", async (t) => { + let prompt!: PromptService; + await fixture(t, (ctx) => { + prompt = new PromptService(ctx, { injectionPlaceholder: "extensions" } as any, loggingStub(logger)); + (ctx as any).cron = () => () => {}; + ctx.set("yesimbot", { + prompt, + memory: {}, + model: { useChatModel: () => null }, + tool: { register() {}, unregister() {} }, + }); + const extension = new DailyPlannerExtension(ctx, { + scheduleGenerationTime: "03:00", + model: { providerName: "none", modelId: "none" }, + coreMemoryLabel: [], + characterName: "Bot", + coreMemoryWeight: 0.7, + }); + (extension as any).service.getCurrentTimeSegment = async () => ({ start: "00:00", end: "23:59", content: `PLAN_DATA ${syntax}` }); + }); + await prompt.start(); + const rendered = await prompt.renderRaw("{{extensions}}", { session, date: { now: "TEST_CLOCK" } }); + expect(rendered).toContain("PLAN_DATA"); + expect(rendered).toContain(syntax); + expect(rendered).not.toContain("FAKE_SECRET_MUST_NOT_LEAK"); + expect(rendered).not.toContain("{{ date.now }}"); + expect(rendered).toContain("现在是 "); +}); + +it.each([ + [false, "LF"], + [true, "LF"], + [true, "CRLF"], +] as const)("migrates only the exact saved legacy default in native mode=%s with %s", async (native, lineEndings) => { + const prompt = new PromptService({} as any, {} as any, loggingStub(logger)); + const original = readFileSync(new URL("./fixtures/legacy-system-template.txt", import.meta.url), "utf8"); + const legacy = lineEndings === "CRLF" ? original.replace(/\r?\n/g, "\r\n") : original; + prompt.registerTemplate("agent.system", legacy); + const rendered = await prompt.render("agent.system", { NATIVE_TOOL_CALLING: native, MEMORY_BLOCKS: [{ label: "persona", content: ["CUSTOM_PERSONA"] }] }); + expect(rendered).toContain("CUSTOM_PERSONA"); + expect(rendered).not.toContain("You are Athena ReAct agent"); + expect(rendered.includes("Your output MUST be a single raw")).toBe(!native); + expect(rendered.includes("Execute actions through the native tool interface")).toBe(native); + prompt.registerTemplate("agent.system", `${legacy}\nCUSTOM_PRESET_SUFFIX`); + const custom = await prompt.render("agent.system", { NATIVE_TOOL_CALLING: native }); + expect(custom).toContain("CUSTOM_PRESET_SUFFIX"); + expect(custom).toContain("You are Athena ReAct agent"); + expect(custom).toContain("Your output MUST be a single raw"); +}); diff --git a/packages/core/tests/provider-config.spec.ts b/packages/core/tests/provider-config.spec.ts index 9e2f3f49b..0089e16f5 100644 --- a/packages/core/tests/provider-config.spec.ts +++ b/packages/core/tests/provider-config.spec.ts @@ -51,6 +51,13 @@ describe("provider configuration", () => { const instance = new ProviderInstance({ yesimbot: {} } as any, value, client, { getLogger: () => logger } as any); expect(instance.getChatModel("local")?.config.disableNativeToolCalling).toBe(true); }); + it("keeps Workers models on JSON actions until native tool history can be replayed", () => { + const value = config("Workers AI", { accountId: "account123", models: [{ modelId: "local", disableNativeToolCalling: false }] }); + const client = ProviderFactoryRegistry.get(value.type)!.createClient(value); + const logger = { debug() {}, info() {}, warn() {}, error() {} }; + const instance = new ProviderInstance({ yesimbot: {} } as any, value, client, { getLogger: () => logger } as any); + expect(instance.getChatModel("local")?.config.disableNativeToolCalling).toBe(true); + }); it("requires a Cloudflare account ID and preserves it for the factory", () => { expect(() => config("Workers AI")).toThrow(/expected|required/); const value = config("Workers AI", { apiKey: "test-key", accountId: "account123" }); diff --git a/packages/core/tests/qq-send-contract.spec.ts b/packages/core/tests/qq-send-contract.spec.ts index 4031d41e1..d953abb44 100644 --- a/packages/core/tests/qq-send-contract.spec.ts +++ b/packages/core/tests/qq-send-contract.spec.ts @@ -117,3 +117,10 @@ for (const family of ["legacy", "current", "crack"] as const) { expect(f.session["seq"]).toBe(2); }); } + +it.each(["", " ", " "])("treats an explicitly empty message as intentional silence (%j)", async (message) => { + const f = await fixture("current"); + const result = await f.tool.sendMessage({ session: f.session, message } as any); + expect(result).toMatchObject({ status: "success", metadata: { intentionalSilence: true } }); + expect(f.requests).toEqual([]); +}); diff --git a/packages/core/tests/reply-assessment.spec.ts b/packages/core/tests/reply-assessment.spec.ts index 77900f045..a31bdc943 100644 --- a/packages/core/tests/reply-assessment.spec.ts +++ b/packages/core/tests/reply-assessment.spec.ts @@ -18,6 +18,10 @@ async function setup() { const key = '["qq","bot","group"]'; const model = { getEvaluationModel: () => ({ evaluate: async () => response }) }; Object.assign(core, { + activeTurnSettlements: new Map(), + resettingHistory: new Set(), + historyTargets: new Map(), + resetStimuli: new Map(), stopped: false, pendingAssessments: new Map(), // 构造注入后 AgentCore 通过 this.modelService 取接话评估模型。 diff --git a/packages/core/tests/reply-history.spec.ts b/packages/core/tests/reply-history.spec.ts index 92dd9aa5a..ad1d3b7b4 100644 --- a/packages/core/tests/reply-history.spec.ts +++ b/packages/core/tests/reply-history.spec.ts @@ -64,7 +64,7 @@ it("reads operation events only from the requested platform into the visible con : [], }, }; - manager.getAgentHistoryFromFile = async () => []; + manager.getAgentHistoryFromFile = async () => ({ events: [], consumedSourceIds: new Set() }); const context = await manager.getL1History("onebot", "same", 10); expect(context).toHaveLength(1); expect(context[0].message).toBe("暂停 at 到期时间"); diff --git a/packages/core/tests/reply-scheduler.spec.ts b/packages/core/tests/reply-scheduler.spec.ts index b43a18c20..52785d4f3 100644 --- a/packages/core/tests/reply-scheduler.spec.ts +++ b/packages/core/tests/reply-scheduler.spec.ts @@ -63,3 +63,17 @@ for (const strategy of ["immediate", "deferred"]) expect(calls).toEqual(["bot1"]); scheduler.dispose(); }); + +it("cancels old queued history work and accepts new work after reset", async () => { + const { scheduler, calls, finish } = fixture(); + scheduler.schedule({ channelCid: "old", type: "user_message", session: { platform: "qq", channelId: "room" } } as any); + scheduler.schedule({ channelCid: "foreign", type: "user_message", session: { platform: "qq", channelId: "elsewhere" } } as any); + scheduler.cancelMatching((item) => item.session.channelId === "room", "history_cleared"); + finish(); + await settle(); + expect(calls).toEqual(["foreign"]); + scheduler.schedule({ channelCid: "fresh", type: "user_message", session: { platform: "qq", channelId: "room" } } as any); + await settle(); + expect(calls).toEqual(["foreign", "fresh"]); + scheduler.dispose(); +}); diff --git a/packages/core/tests/runtime-diagnostics.spec.ts b/packages/core/tests/runtime-diagnostics.spec.ts index b5994f081..06a85991b 100644 --- a/packages/core/tests/runtime-diagnostics.spec.ts +++ b/packages/core/tests/runtime-diagnostics.spec.ts @@ -20,7 +20,7 @@ it("missing embedding assignment is left unset without an embedding provider", ( ); s.validateConfig(); expect(s.config.task.embed).toBeUndefined(); - expect(logs.join("\n")).toContain("嵌入"); + expect(logs.join("\n")).not.toContain("嵌入"); }); it("embedding fallback selects a capable group instead of the first chat group", () => { const { s } = service( @@ -64,7 +64,12 @@ it("decision journal closes even if reply-control persistence fails during stop" const core: any = Object.create(AgentCore.prototype); let closed = false; Object.assign(core, { + activeTurnSettlements: new Map(), + resettingHistory: new Set(), + historyTargets: new Map(), + resetStimuli: new Map(), pendingAssessments: new Map(), + startupStimuli: [], activeTurns: new Map(), activeDecisionIds: new Map(), topics: { dispose() {} }, diff --git a/packages/core/tests/scheduler-quiet-period.spec.ts b/packages/core/tests/scheduler-quiet-period.spec.ts new file mode 100644 index 000000000..a65908524 --- /dev/null +++ b/packages/core/tests/scheduler-quiet-period.spec.ts @@ -0,0 +1,103 @@ +import { afterEach, expect, it, vi } from "vitest"; + +import { StimulusScheduler } from "../src/agent/scheduler"; +import { loggingStub } from "./helpers/yesimbot"; + +afterEach(() => vi.useRealTimers()); + +function setup() { + vi.useFakeTimers(); + const calls: any[] = []; + let release!: () => void; + const active = new Promise((resolve) => (release = resolve)); + let releaseCompletion!: () => void; + const completion = new Promise((resolve) => (releaseCompletion = resolve)); + const scheduler = new StimulusScheduler( + { + debounce(fn: any, ms: number) { + let timer: ReturnType; + const task = (value: any) => { + clearTimeout(timer); + timer = setTimeout(() => void fn(value), ms); + }; + task.dispose = () => clearTimeout(timer); + return task; + }, + } as any, + { debounceMs: 10, prioritizeMentions: true, newMessageStrategy: "deferred", deferredProcessingTime: 100 } as any, + async (stimulus: any) => { + calls.push(stimulus); + if (stimulus.id === "active") await active; + if (stimulus.id === "done") await completion; + }, + loggingStub(), + ); + return { scheduler, calls, release, releaseCompletion }; +} + +function stimulus(id: string, type = "user_message", channelCid = "bot:group") { + return { + id, + type, + channelCid, + payload: { taskIds: [id] }, + session: { selfId: "bot", bot: { selfId: "bot" }, stripped: { atSelf: id === "mention" }, elements: [] }, + } as any; +} + +it.each([false, true])("restarts the full quiet period after traffic during a completion (scheduled: %s)", async (scheduleMessage) => { + const f = setup(); + try { + f.scheduler.schedule(stimulus("active")); + await vi.advanceTimersByTimeAsync(10); + f.scheduler.schedule(stimulus("mention")); + f.scheduler.schedule(stimulus("done", "background_task_completion")); + f.release(); + // The original quiet period expires while the completion still owns the channel. + await vi.advanceTimersByTimeAsync(100); + expect(f.calls.map((s) => s.id)).toEqual(["active", "done"]); + f.scheduler.noteUserMessage("bot:group"); + if (scheduleMessage) f.scheduler.schedule(stimulus("new-user")); + await vi.advanceTimersByTimeAsync(40); + f.releaseCompletion(); + await vi.advanceTimersByTimeAsync(59); + expect(f.calls.map((s) => s.id)).toEqual(["active", "done"]); + await vi.advanceTimersByTimeAsync(1); + expect(f.calls.map((s) => s.id)).toEqual(["active", "done", "mention"]); + } finally { + f.release(); + f.releaseCompletion(); + f.scheduler.dispose(); + } +}); + +it("retains each due reminder while busy and prevents user debounce from replacing them", async () => { + const f = setup(); + try { + f.scheduler.schedule(stimulus("active")); + await vi.advanceTimersByTimeAsync(10); + f.scheduler.schedule(stimulus("reminder-1", "scheduled_task")); + f.scheduler.schedule(stimulus("reminder-2", "scheduled_task")); + f.scheduler.schedule(stimulus("new-user")); + expect(f.calls.map((s) => s.id)).toEqual(["active"]); + f.release(); + await vi.advanceTimersByTimeAsync(100); + expect(f.calls.map((s) => s.id)).toEqual(["active", "reminder-1", "reminder-2", "new-user"]); + } finally { + f.release(); + f.scheduler.dispose(); + } +}); + +it.each(["cancel", "dispose"] as const)("clears pending reminder stimuli on %s", async (action) => { + const f = setup(); + f.scheduler.schedule(stimulus("active")); + await vi.advanceTimersByTimeAsync(10); + f.scheduler.schedule(stimulus("reminder", "scheduled_task")); + if (action === "cancel") f.scheduler.cancel("bot:group"); + else f.scheduler.dispose(); + f.release(); + await vi.advanceTimersByTimeAsync(200); + expect(f.calls.map((s) => s.id)).toEqual(["active"]); + f.scheduler.dispose(); +}); diff --git a/packages/core/tests/send-heartbeat.spec.ts b/packages/core/tests/send-heartbeat.spec.ts index f25862c0f..372ca5b7f 100644 --- a/packages/core/tests/send-heartbeat.spec.ts +++ b/packages/core/tests/send-heartbeat.spec.ts @@ -96,7 +96,7 @@ for (const streamAction of [false, true]) { it(`${streamAction ? "streaming" : "normal"} heartbeat reflects ${status} delivery`, async () => { const observations: any[] = []; const successfulLogs: string[] = []; - const logger = { debug() {}, info() {}, warn() {}, error() {}, success: (message: string) => successfulLogs.push(message) }; + const logger = { debug: (message: string) => successfulLogs.push(message), info() {}, warn() {}, error() {}, success() {} }; const response = JSON.stringify({ thoughts: { observe: "test", analyze_infer: "test", plan: "test" }, actions: [{ function: "send_message", params: { message: "hello" } }], @@ -127,7 +127,7 @@ for (const streamAction of [false, true]) { const success = await processor.runCycle({ session: { platform: "qq", channelId: "group", cid: "qq:group" } } as any); expect(success).toBe(status === "success"); expect(observations[0].status).toBe(status); - expect(successfulLogs.includes("单次心跳成功完成")).toBe(status === "success"); + expect(successfulLogs.includes("本次模型决策已发送回复")).toBe(status === "success"); }); } } @@ -204,8 +204,7 @@ for (const streamAction of [false, true]) { for (const turns of [ [{ actions: [], want: false }], [{ actions: [{ function: "lookup", status: "success" }], want: false }], - [{ actions: [{ function: "send_message", status: "error" }] }, { actions: [], want: false }], - [{ actions: [{ function: "send_message", status: "error" }] }, { actions: [{ function: "send_message", status: "success" }], want: true }], + [{ actions: [{ function: "send_message", status: "error" }], want: false }], [{ actions: [{ function: "send_message", status: "success" }] }, { actions: [{ function: "send_message", status: "error" }], want: true }], ]) { it(`${streamAction ? "streaming" : "normal"} cycle counts only confirmed replies: ${JSON.stringify(turns)}`, async () => { @@ -390,3 +389,31 @@ for (const streamAction of [false, true]) { expect(invocations).toBe(1); }); } + +it.each(["json", "stream", "native"])("ends an intentionally silent %s turn without reporting a delivery", async (mode) => { + const logger = { debug() {}, info() {}, warn() {}, error() {}, success() {} }; + const definition = { name: "send_message", description: "send", parameters: Schema.object({ message: Schema.string().required() }) }; + const response = JSON.stringify({ thoughts: {}, actions: [{ function: "send_message", params: { message: "" } }], request_heartbeat: true }); + let requests = 0; + const processor = new HeartbeatProcessor(stubCtx(), { heartbeat: 3, nativeToolCalling: mode === "native", streamAction: mode === "stream" } as any, { + model: { + chat: async () => { + requests++; + return mode === "native" ? { toolCalls: [{ toolCallId: "call", toolName: "send_message", args: '{"message":""}' }] } : { text: response }; + }, + } as any, + prompt: {} as any, + tool: { + getAvailableTools: () => [definition], + getTool: () => definition, + invoke: async () => ({ status: "success", metadata: { intentionalSilence: true } }), + } as any, + l1: { recordThought: async () => {}, recordHeartbeat: async () => {}, recordAction: async () => "action", recordObservation: async () => {} } as any, + contextBuilder: {} as any, + logging: loggingStub(logger), + world: {} as unknown as WorldStateService, + }); + (processor as any)._prepareLlmRequest = async () => ({ messages: [] }); + expect(await processor.runCycle({ session: { platform: "qq", channelId: "group", cid: "qq:group" } } as any)).toBe(false); + expect(requests).toBe(1); +}); diff --git a/packages/core/tests/stimulus-isolation.spec.ts b/packages/core/tests/stimulus-isolation.spec.ts index f38a7125c..a63dfc8b6 100644 --- a/packages/core/tests/stimulus-isolation.spec.ts +++ b/packages/core/tests/stimulus-isolation.spec.ts @@ -38,7 +38,15 @@ async function fixture() { world.isBotMuted = () => false; world.peekBotMuted = () => false; const config = Config({ base: { text: 100 }, lifecycle: { probabilityThreshold: 0 }, typesafe: { mode: "off" } }); - const core: any = Object.create(AgentCore.prototype); + const core: any = new AgentCore(scope, config, { + logging: ctx.yesimbot.logging, + world, + model: { useChatGroup: () => ({}) } as any, + prompt: { registerTemplate() {}, registerSnippet() {} } as any, + tool: {} as any, + asset: ctx.yesimbot.asset as any, + memory: {} as any, + }); const scheduled: any[] = []; Object.defineProperty(core, "ctx", { value: scope }); Object.defineProperty(core, "logger", { value: logger }); diff --git a/packages/core/tests/tool-cancellation.spec.ts b/packages/core/tests/tool-cancellation.spec.ts index 25567f7b4..ed61f2878 100644 --- a/packages/core/tests/tool-cancellation.spec.ts +++ b/packages/core/tests/tool-cancellation.spec.ts @@ -3,18 +3,26 @@ import { afterEach, expect, it, vi } from "vitest"; import { guardReplySession, withReplyTurn } from "../src/agent/reply-turn"; import { ToolService } from "../src/extension/service"; +import { loggingStub } from "./helpers/yesimbot"; function fixture(execute: (args: any) => Promise, retry = 0, record?: (event: any) => Promise) { const events: any[] = []; const errors: any[] = []; - const service = { - getTool: () => ({ parameters: Schema.object({}), execute }), - _logger: { info() {}, warn() {}, success() {}, debug() {}, error: (...args: any[]) => errors.push(args) }, - config: { advanced: { maxRetry: retry, retryDelay: 60_000 } }, - executeInvocation: ToolService.prototype["executeInvocation"], - deps: { world: { recordSystemEvent: record ?? (async (event: any) => events.push(event)) } }, - } as unknown as ToolService; - return { invoke: (session?: any) => ToolService.prototype.invoke.call(service, "probe", {}, session), events, errors }; + const service = new ToolService( + {} as any, + { advanced: { maxRetry: retry, retryDelay: 60_000 } } as any, + { + logging: loggingStub({ info() {}, warn() {}, success() {}, debug() {}, error: (...args: any[]) => errors.push(args) }), + world: { recordSystemEvent: record ?? (async (event: any) => events.push(event)) }, + } as any, + ); + service.registerTool({ name: "probe", readOnly: true, description: "test", parameters: Schema.object({}), execute }); + return { + executions: (service as any).executions, + invoke: (session?: any) => ToolService.prototype.invoke.call(service, "probe", {}, session), + events, + errors, + }; } afterEach(() => vi.useRealTimers()); @@ -71,7 +79,7 @@ it("clears a tool retry delay immediately on cancellation", async () => { controller.signal, ).catch(() => "cancelled"); await vi.advanceTimersByTimeAsync(0); - expect(vi.getTimerCount()).toBe(1); + expect(vi.getTimerCount()).toBe(2); controller.abort(); expect(await outcome).toBe("cancelled"); expect(vi.getTimerCount()).toBe(0); @@ -105,18 +113,18 @@ it("does not cancel another channel's concurrent tool invocation", async () => { expect(await other).toEqual({ status: "success", result: "healthy" }); }); -it("removes the turn's abort listener when a tool completes normally", async () => { +it("clears the execution deadline when a tool completes normally", async () => { + vi.useFakeTimers(); const controller = new AbortController(); - const add = vi.spyOn(controller.signal, "addEventListener"); - const remove = vi.spyOn(controller.signal, "removeEventListener"); const tool = fixture(async () => ({ status: "success" })); await withReplyTurn( () => true, () => tool.invoke(), controller.signal, ); - expect(add).toHaveBeenCalledTimes(1); - expect(remove).toHaveBeenCalledWith("abort", add.mock.calls[0][1]); + expect(controller.signal.aborted).toBe(false); + expect(tool.executions.size).toBe(0); + expect(vi.getTimerCount()).toBe(0); }); it("releases cancellation while a successful tool receipt is still being persisted", async () => { diff --git a/packages/core/tests/tool-contract-boundaries.spec.ts b/packages/core/tests/tool-contract-boundaries.spec.ts new file mode 100644 index 000000000..fbb197b06 --- /dev/null +++ b/packages/core/tests/tool-contract-boundaries.spec.ts @@ -0,0 +1,172 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { Schema } from "koishi"; +import { afterEach, expect, it, vi } from "vitest"; + +import { ToolService } from "../src/extension/service"; +import { loggingStub } from "./helpers/yesimbot"; + +const cleanups: Array<() => Promise> = []; +afterEach(async () => { + for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); +}); +async function fixture(timeout = 1000) { + const baseDir = await mkdtemp(path.join(tmpdir(), "yib-tool-boundaries-")); + const ctx: any = { baseDir, scope: { key: "tool-boundaries" }, filter: () => true }; + const world: any = { isChannelAllowed: () => true, l2_manager: { getHistoryGeneration: () => 0 } }; + const tools = new ToolService(ctx, { advanced: { timeout, maxRetry: 3, retryDelay: 1 } } as any, { world, logging: loggingStub() } as any); + cleanups.push(async () => { + await tools.stop(); + await rm(baseDir, { recursive: true, force: true }); + }); + const session: any = { platform: "test", selfId: "bot", channelId: "group", userId: "user", isDirect: false }; + return { tools, session }; +} +it("enforces registration owner filters for discovery and execution", async () => { + const { tools, session } = await fixture(); + let authorized = false, + calls = 0; + const owner: any = { filter: () => authorized }; + (tools.registerTool as any)( + { + name: "owned", + description: "owned", + parameters: Schema.object({}), + execute: async () => { + calls++; + return { status: "success" }; + }, + }, + owner, + ); + expect(tools.getToolSchemas(session)).toEqual([]); + expect((await tools.invoke("owned", {}, session)).status).toBe("error"); + expect(calls).toBe(0); + authorized = true; + expect(tools.getToolSchemas(session).map((tool) => tool.name)).toEqual(["owned"]); + expect((await tools.invoke("owned", {}, session)).status).toBe("success"); + expect(calls).toBe(1); +}); + +it("advertises grouped operations only while their original tools are authorized and dispatches through those tools", async () => { + const { tools, session } = await fixture(); + const set = vi.fn(async () => ({ status: "success" })); + const remove = vi.fn(async () => ({ status: "success" })); + const parameters = Schema.object({ message_id: Schema.string().required() }); + tools.registerTool({ name: "essence_create", description: "set", parameters, execute: set, modelReplacement: "essence" }); + tools.registerTool({ name: "essence_delete", description: "remove", parameters, execute: remove, modelReplacement: "essence" }); + tools.registerTool({ + name: "essence", + description: "set or remove", + supersedes: ["essence_create", "essence_delete"], + actionAliases: { set: "essence_create", remove: "essence_delete" }, + parameters: Schema.object({ action: Schema.union(["set", "remove"]).required(), message_id: Schema.string().required() }), + execute: async () => { + throw new Error("must dispatch through original tool"); + }, + }); + const catalog = () => tools.getAvailableTools(session, undefined, "model").map((tool) => tool.name); + expect(catalog()).toEqual(["essence"]); + expect((await tools.invoke("essence", { message_id: "001" }, session)).status).toBe("error"); + expect((await tools.invoke("essence", { action: "set", message_id: "001" }, session)).status).toBe("success"); + expect(set).toHaveBeenCalledWith(expect.objectContaining({ message_id: "001" })); + expect(remove).not.toHaveBeenCalled(); + tools.unregisterTool("essence_create"); + expect(catalog()).toEqual(["essence_delete"]); + expect((await tools.invoke("essence", { action: "set", message_id: "001" }, session)).status).toBe("error"); + expect(set).toHaveBeenCalledTimes(1); + expect((await tools.invoke("essence_delete", { message_id: "001" }, session)).status).toBe("success"); + expect(remove).toHaveBeenCalledTimes(1); +}); +it("bounds an ordinary tool, aborts its signal and never retries a timed out side effect", async () => { + const { tools, session } = await fixture(15); + let calls = 0, + signal: AbortSignal | undefined, + release!: (value: any) => void; + tools.registerTool({ + name: "slow", + description: "slow", + parameters: Schema.object({}), + execute: async (args) => { + calls++; + signal = args.toolContext?.signal; + return new Promise((resolve) => { + release = resolve; + }); + }, + }); + const result = await Promise.race([tools.invoke("slow", {}, session), new Promise((resolve) => setTimeout(() => resolve(null), 150))]); + release({ status: "error", error: { name: "late", message: "late", retryable: true } }); + expect(result).toMatchObject({ status: "error", error: { name: "ToolTimeoutError", retryable: false } }); + expect(signal?.aborted).toBe(true); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(calls).toBe(1); +}); +it("checks producer permissions and result revision again when reading an archived result", async () => { + const { tools, session } = await fixture(); + let authorized = true, + revision = 1; + (tools.registerTool as any)( + { + name: "scoped_read", + description: "read", + parameters: Schema.object({}), + isResultCurrent: (result: any) => result.metadata.revision === revision, + execute: async () => ({ status: "success", result: "x".repeat(25000), metadata: { revision } }), + }, + { filter: () => authorized }, + ); + const receipt = await tools.invoke("scoped_read", {}, session); + const uri = receipt.result.uri; + expect((await tools.readToolOutput(session, { uri })).metadata).toEqual({ revision: 1 }); + revision++; + await expect(tools.readToolOutput(session, { uri })).rejects.toThrow(/expired|invalid|current|authorization/i); + revision--; + authorized = false; + await expect(tools.readToolOutput(session, { uri })).rejects.toThrow(/expired|invalid|current|authorization/i); +}); + +it("prevents a timed-out extension from sending with its retained session", async () => { + const { tools, session } = await fixture(10); + let release!: () => void; + const blocked = new Promise((resolve) => { + release = resolve; + }); + let sends = 0, + lateError: unknown; + session.bot = { + platform: "test", + selfId: "bot", + sendMessage: async () => { + sends++; + return ["sent"]; + }, + }; + let finished!: () => void; + const done = new Promise((resolve) => { + finished = resolve; + }); + tools.registerTool({ + name: "late-send", + description: "late", + parameters: Schema.object({}), + execute: async ({ session }) => { + await blocked; + try { + await session.bot.sendMessage("group", "late"); + } catch (error) { + lateError = error; + } finally { + finished(); + } + return { status: "success" }; + }, + }); + expect(await tools.invoke("late-send", {}, session)).toMatchObject({ status: "error", error: { name: "ToolTimeoutError" } }); + release(); + await done; + expect(lateError).toMatchObject({ name: "AbortError" }); + expect(sends).toBe(0); +}); diff --git a/packages/core/tests/tool-error-normalization.spec.ts b/packages/core/tests/tool-error-normalization.spec.ts new file mode 100644 index 000000000..9bff903fa --- /dev/null +++ b/packages/core/tests/tool-error-normalization.spec.ts @@ -0,0 +1,83 @@ +import { Schema } from "koishi"; +import { describe, expect, it } from "vitest"; + +import { Failed, Success } from "../src/extension/helpers"; +import { ToolService } from "../src/extension/service"; +import { AppError, ErrorDefinitions, fromAppError, normalizeAppError, toToolError } from "../src/shared/errors"; +import { loggingStub } from "./helpers/yesimbot"; + +describe("public tool error boundary", () => { + it("keeps successful and legacy structured/string failures compatible", () => { + expect(Success([])).toMatchObject({ status: "success", result: [] }); + expect(Failed("old message").error).toEqual({ name: "ToolError", message: "old message" }); + const legacy = { name: "OldError", message: "old", retryable: true }; + expect(Failed(legacy).error).toBe(legacy); + }); + it("projects known fields with one ID and omits cause/context/stack", () => { + const error = new AppError(ErrorDefinitions.LLM.TIMEOUT, { cause: new Error("secret"), context: { token: "secret" } }); + expect(fromAppError(error)).toMatchObject({ code: "LLM.TIMEOUT", category: "timeout", errorId: error.errorId, retryable: false }); + expect(JSON.stringify(fromAppError(error))).not.toMatch(/secret|cause|context|stack/); + expect(toToolError(error)).toEqual(fromAppError(error)); + }); + it("retains unknown causes internally while redacting their public text", () => { + const cause = new Error("Bearer sensitive-token\n at private/path"); + const normalized = normalizeAppError(cause); + expect(normalized.cause).toBe(cause); + expect(toToolError(cause)).toMatchObject({ code: "SYSTEM.UNKNOWN", category: "internal", retryable: false }); + expect(JSON.stringify(toToolError(cause))).not.toMatch(/sensitive-token|private\/path/); + }); + it("validates cross-package envelopes instead of trusting arbitrary codes", () => { + const error = new AppError(ErrorDefinitions.LLM.TIMEOUT); + const envelope = { name: error.name, code: error.code, errorId: error.errorId, message: error.message, suggestion: error.suggestion }; + expect(toToolError(envelope).errorId).toBe(error.errorId); + expect(toToolError({ code: error.code, message: "secret" }).code).toBe("SYSTEM.UNKNOWN"); + expect(toToolError({ ...envelope, errorId: "bad\nsecret" }).code).toBe("SYSTEM.UNKNOWN"); + }); + it.each([new Error("secret"), null, new AppError(ErrorDefinitions.LLM.TIMEOUT)])("normalizes thrown values without adding retries (%s)", async (error) => { + let calls = 0; + const tool = { + readOnly: true, + parameters: Schema.object({}), + execute: async () => { + calls++; + throw error; + }, + }; + const service = new ToolService({} as any, { advanced: { maxRetry: 2, retryDelay: 1 } } as any, { logging: loggingStub() } as any); + service.getTool = () => tool as any; + const result = await ToolService.prototype.invoke.call(service, "test", {}, {} as any); + expect(result.status).toBe("error"); + expect(result.error?.code).toBe(error instanceof AppError ? error.code : "SYSTEM.UNKNOWN"); + expect(result.error?.message).not.toContain("secret"); + expect(calls).toBe(1); + }); +}); + +it("retains explicit read-only structured retry eligibility and attempt limits", async () => { + for (const retryable of [false, true]) { + let calls = 0; + const legacy = Failed({ name: "Legacy", message: "original text", retryable }); + const tool = { + readOnly: true, + parameters: Schema.object({}), + execute: async () => { + calls++; + return legacy; + }, + }; + const service = new ToolService({} as any, { advanced: { maxRetry: 2, retryDelay: 1 } } as any, { logging: loggingStub() } as any); + service.getTool = () => tool as any; + const result = await ToolService.prototype.invoke.call(service, "legacy", {}, {} as any); + expect(result).toBe(legacy); + expect(calls).toBe(retryable ? 3 : 1); + } +}); + +it("keeps local custom AppError identity and cause while projecting safe unknown public fields", () => { + const cause = new Error("private-token"); + const error = new AppError({ code: "PLUGIN.LOCAL", message: "private-token", suggestion: "private-token" }, { cause }); + expect(normalizeAppError(error)).toBe(error); + expect(normalizeAppError(error).cause).toBe(cause); + expect(toToolError(error)).toMatchObject({ code: "SYSTEM.UNKNOWN", errorId: error.errorId, category: "internal", retryable: false }); + expect(JSON.stringify(toToolError(error))).not.toContain("private-token"); +}); diff --git a/packages/core/tests/tool-event-projection.spec.ts b/packages/core/tests/tool-event-projection.spec.ts new file mode 100644 index 000000000..06c494ef3 --- /dev/null +++ b/packages/core/tests/tool-event-projection.spec.ts @@ -0,0 +1,108 @@ +import { Context, Schema } from "koishi"; +import { expect, it, onTestFinished } from "vitest"; + +import { HeartbeatProcessor } from "../src/agent/heartbeat-processor"; +import { ToolService } from "../src/extension/service"; +import type { ToolCallResult } from "../src/extension/types"; +import { loggingStub } from "./helpers/yesimbot"; + +function fixture(name: string, result: ToolCallResult) { + const ctx = new Context(); + const events: any[] = []; + const tools = new ToolService(ctx, { advanced: { maxRetry: 0 } } as any, { + logging: loggingStub(), + world: { + recordSystemEvent: async (event: any) => { + events.push(event); + return true; + }, + } as any, + }); + tools.registerTool({ name, description: "test", parameters: Schema.object({}), execute: async () => result }); + onTestFinished(async () => { + await tools.stop(); + await ctx.stop(); + }); + return { ctx, tools, events, session: { platform: "test", selfId: "bot", channelId: "room", userId: "user" } as any }; +} + +it("keeps the complete audit receipt separate from the concise tool event summary", async () => { + const result = { status: "success" as const, result: { text: "PRIVATE_TOOL_BODY", diagnostics: "INTERNAL_DIAGNOSTICS" } }; + const f = fixture("read_probe", result); + expect(await f.tools.invoke("read_probe", {}, f.session, { requestId: "heartbeat-turn" })).toEqual(result); + expect(f.events).toHaveLength(1); + expect(f.events[0].payload).toMatchObject({ + operation: "read_probe", + status: "success", + turnId: "heartbeat-turn", + summary: "工具 read_probe 已返回成功回执。", + }); + expect(f.events[0].message).toBe(f.events[0].payload.summary); + expect(JSON.parse(f.events[0].payload.receipt)).toEqual(result); + expect(f.events[0].message).not.toContain("PRIVATE_TOOL_BODY"); + expect(f.events[0].message).not.toContain("INTERNAL_DIAGNOSTICS"); +}); + +for (const mode of ["native", "json", "stream"] as const) + it(`${mode}: binds real invocation events uniquely to repeated actions in one heartbeat`, async () => { + const f = fixture("read_probe", { status: "success", result: "observed" }); + const observations: any[] = []; + let nextAction = 0; + const processor = new HeartbeatProcessor(f.ctx, { heartbeat: 1, nativeToolCalling: mode === "native", streamAction: mode === "stream" } as any, { + model: { + chat: async (options: any) => { + if (mode === "native") return { toolCalls: [1, 2].map((id) => ({ toolName: "read_probe", toolCallId: `call-${id}`, args: "{}" })) }; + const text = JSON.stringify({ + thoughts: {}, + actions: [1, 2].map(() => ({ function: "read_probe", params: {} })), + request_heartbeat: false, + }); + options.validation?.validator(text, true); + return { text }; + }, + } as any, + tool: f.tools, + prompt: {} as any, + l1: { + recordThought: async () => {}, + recordAction: async () => `action-${++nextAction}`, + recordHeartbeat: async () => {}, + recordObservation: async (actionId: string, _platform: string, _channel: string, observation: any) => + observations.push({ actionId, ...observation }), + } as any, + contextBuilder: {} as any, + world: {} as any, + logging: loggingStub(), + }); + (processor as any)._prepareLlmRequest = async () => ({ messages: [] }); + await processor.runCycle({ session: f.session } as any); + expect(f.events).toHaveLength(2); + expect(observations).toHaveLength(2); + expect(f.events.map((event) => event.payload.actionId)).toEqual(["action-1", "action-2"]); + expect(new Set(f.events.map((event) => event.payload.requestId)).size).toBe(2); + for (let i = 0; i < 2; i++) + expect(f.events[i].payload).toMatchObject({ + turnId: observations[i].turnId, + actionId: observations[i].actionId, + operation: observations[i].function, + }); + }); + +it("projects partial and unknown delivery without describing the reply as unsent or inviting replay", async () => { + const result = { + status: "error" as const, + error: { name: "ToolTimeoutError", code: "TOOL.TIMEOUT", message: "PRIVATE_ADAPTER_ERROR", retryable: false }, + metadata: { + delivery: { messageIds: ["first", "first"], sentMessages: 1, totalMessages: 3, inFlight: true, deliveryUnknown: true }, + execution: { timedOut: true }, + }, + }; + const f = fixture("send_message", result); + await f.tools.invoke("send_message", {}, f.session); + expect(f.events[0].message).toContain("已确认 1 条消息"); + expect(f.events[0].message).toContain("已完整发送 1/3 段"); + expect(f.events[0].message).toContain("送达结果未知"); + expect(f.events[0].message).toContain("请勿自动重发"); + expect(f.events[0].message).not.toContain("PRIVATE_ADAPTER_ERROR"); + expect(JSON.parse(f.events[0].payload.receipt)).toEqual(result); +}); diff --git a/packages/core/tests/tool-execution-budgets.spec.ts b/packages/core/tests/tool-execution-budgets.spec.ts new file mode 100644 index 000000000..3ef1ccf73 --- /dev/null +++ b/packages/core/tests/tool-execution-budgets.spec.ts @@ -0,0 +1,432 @@ +import { Bot, Context, MessageEncoder, Schema } from "koishi"; +import { afterEach, expect, it, vi } from "vitest"; + +import { withReplyTurn } from "../src/agent/reply-turn"; +import CoreUtilExtension from "../src/extension/builtin/core-util"; +import { CoreUtilConfigSchema } from "../src/extension/builtin/core-util/config"; +import { ToolService } from "../src/extension/service"; +import { loggingStub } from "./helpers/yesimbot"; + +const cleanups: Array<() => Promise> = []; +afterEach(async () => { + for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); + vi.useRealTimers(); +}); +function setup(overrides: Record = {}, toolTimeouts: Record = {}) { + vi.useFakeTimers(); + const logger = { debug() {}, info() {}, warn() {}, error() {}, success() {} }; + const emitted: any[] = []; + const model = { + config: { timeoutPolicy: { totalTimeout: 120 }, retryPolicy: { maxRetries: 0 } }, + isVisionModel: () => true, + chat: vi.fn<(...args: any[]) => Promise>(async () => ({ text: "description" })), + }; + const ctx: any = { filter: () => true, on() {}, logger: () => logger, emit: (...args: any[]) => emitted.push(args), bots: [] }; + const tools = new ToolService(ctx, { advanced: { timeout: 10000, maxRetry: 3, toolTimeouts } } as any, { logging: loggingStub(logger) } as any); + ctx.yesimbot = { + tool: tools, + logging: loggingStub(logger), + asset: { + encode: async (text: string) => text, + getInfo: async (id: string) => ({ id, mime: "image/png" }), + read: async () => "data:image/jpeg;base64,AA==", + }, + model: { getChatModel: () => model, useChatModel: () => model }, + }; + const config = CoreUtilConfigSchema({ + typing: { baseDelay: 0, minDelay: 0, maxDelay: 0 }, + vision: { model: { providerName: "provider", modelId: "vision" } }, + ...overrides, + }); + const extension = new CoreUtilExtension(ctx, config); + for (const definition of (extension as any).tools.values()) tools.registerTool(definition); + const bot: any = { + platform: "qq", + selfId: "bot", + user: { id: "bot" }, + sendMessage: vi.fn<(...args: any[]) => Promise>(async () => ["id"]), + session: (event: any) => ({ event, ...event }), + }; + ctx.bots.push(bot); + const session: any = { bot, platform: "qq", selfId: "bot", userId: "user", channelId: "group", event: { channel: { id: "group", type: 0 } } }; + cleanups.push(async () => tools.stop()); + return { tools, extension, model, bot, session, config, emitted, ctx }; +} + +it("lets a configured 120s vision request finish beyond the ordinary 10s budget", async () => { + const f = setup(); + f.model.chat.mockImplementation(async () => new Promise((resolve) => setTimeout(() => resolve({ text: "visible after 110 seconds" }), 110000))); + let settled = false; + const invocation = f.tools.invoke("get_image_description", { image_id: "image", question: "what?" }, f.session).then((result) => { + settled = true; + return result; + }); + await vi.advanceTimersByTimeAsync(10001); + expect(settled).toBe(false); + await vi.advanceTimersByTimeAsync(100000); + expect(await invocation).toMatchObject({ status: "success", result: "visible after 110 seconds" }); +}); + +it("gives three paragraphs enough budget for the configured typing and paragraph delays", async () => { + const f = setup({ typing: { baseDelay: 4000, minDelay: 4000, maxDelay: 4000 } }); + let sends = 0; + f.bot.sendMessage.mockImplementation(async () => [`part-${++sends}`]); + const invocation = f.tools.invoke("send_message", { message: "abc" }, f.session); + await vi.advanceTimersByTimeAsync(20000); + expect(await invocation).toMatchObject({ + status: "success", + metadata: { delivery: { sentMessages: 3, messageIds: ["part-1", "part-2", "part-3"], deliveryUnknown: false } }, + }); + expect(sends).toBe(3); +}); + +it("retains confirmed paragraphs when an explicit send deadline expires during a later typing delay", async () => { + const f = setup({}, { send_message: 15 }); + const invocation = f.tools.invoke("send_message", { message: "firstsecond" }, f.session); + await vi.advanceTimersByTimeAsync(16); + expect(await invocation).toMatchObject({ + status: "error", + error: { code: "TOOL.TIMEOUT", retryable: false }, + metadata: { delivery: { messageIds: ["id"], sentMessages: 1, totalMessages: 2, inFlight: false, deliveryUnknown: false } }, + }); + await vi.advanceTimersByTimeAsync(5000); + expect(f.bot.sendMessage).toHaveBeenCalledTimes(1); +}); + +it("keeps an in-flight send with no returned ID unknown and never replays it", async () => { + const f = setup({}, { send_message: 15 }); + let release!: (ids: string[]) => void; + f.bot.sendMessage.mockImplementation( + () => + new Promise((resolve) => { + release = resolve; + }), + ); + const invocation = f.tools.invoke("send_message", { message: "firstsecond" }, f.session); + await vi.advanceTimersByTimeAsync(16); + expect(await invocation).toMatchObject({ + status: "error", + metadata: { delivery: { messageIds: [], sentMessages: 0, inFlight: true, deliveryUnknown: true } }, + }); + release(["late-confirmation"]); + await vi.advanceTimersByTimeAsync(5000); + expect(f.bot.sendMessage).toHaveBeenCalledTimes(1); +}); + +it("captures a real encoder's first confirmation when a later chunk is still pending at deadline", async () => { + const f = setup({}, { send_message: 15 }); + const botContext = new Context(); + let release!: () => void; + const blocked = new Promise((resolve) => { + release = resolve; + }); + let visits = 0; + class Encoder extends MessageEncoder { + async visit() { + visits++; + this.results.push({ id: "encoder-confirmed", content: "first text" }); + await blocked; + } + async flush() {} + } + class Sender extends Bot { + static MessageEncoder = Encoder; + } + const bot = new Sender(botContext, {} as any, "qq"); + bot.user = { id: "bot" }; + f.ctx.bots = [bot]; + const session = bot.session({ channel: { id: "group", type: 0 }, user: { id: "user" } }); + const invocation = f.tools.invoke("send_message", { message: "text and imagelater paragraph" }, session); + await vi.advanceTimersByTimeAsync(16); + expect(await invocation).toMatchObject({ + status: "error", + metadata: { delivery: { messageIds: ["encoder-confirmed"], sentMessages: 0, inFlight: true, deliveryUnknown: true } }, + }); + release(); + await vi.advanceTimersByTimeAsync(5000); + expect(visits).toBe(1); + await botContext.stop(); +}); + +it("keeps ordinary tools bounded and honors an earlier upstream deadline", async () => { + const f = setup(); + f.tools.registerTool({ name: "ordinary", description: "test", parameters: Schema.object({}), execute: async () => new Promise(() => {}) }); + const ordinary = f.tools.invoke("ordinary", {}, f.session); + await vi.advanceTimersByTimeAsync(10001); + expect(await ordinary).toMatchObject({ error: { code: "TOOL.TIMEOUT" }, metadata: { execution: { timeoutMs: 10000 } } }); + f.model.chat.mockImplementation(() => new Promise(() => {})); + const vision = f.tools.invoke("get_image_description", { image_id: "image", question: "what?" }, f.session, { deadline: Date.now() + 40 }); + await vi.advanceTimersByTimeAsync(41); + expect(await vision).toMatchObject({ error: { code: "TOOL.TIMEOUT" }, metadata: { execution: { timeoutMs: 40 } } }); +}); + +it("still cancels a slow tool immediately with its parent turn", async () => { + const f = setup(); + const controller = new AbortController(); + f.model.chat.mockImplementation(() => new Promise(() => {})); + const invocation = withReplyTurn( + () => true, + () => f.tools.invoke("get_image_description", { image_id: "image", question: "what?" }, f.session), + controller.signal, + ); + await vi.advanceTimersByTimeAsync(1); + controller.abort(); + await expect(invocation).rejects.toMatchObject({ name: "AbortError" }); +}); + +it("defaults to direct vision, exposes configured auxiliary vision for text-only turns, and honors weak-vision opt-in", async () => { + const f = setup(); + const names = (context?: any) => f.tools.getAvailableTools(f.session, context).map((tool) => tool.name); + expect(names()).toContain("get_image_description"); + expect(names({ attachedImageIds: ["image"] })).not.toContain("get_image_description"); + expect((await f.tools.invoke("get_image_description", { image_id: "image", question: "what?" }, f.session, { attachedImageIds: ["image"] })).status).toBe( + "error", + ); + expect(f.model.chat).not.toHaveBeenCalled(); + f.config.vision.allowAuxiliary = true; + expect(names({ attachedImageIds: ["image"] })).toContain("get_image_description"); + expect((await f.tools.invoke("get_image_description", { image_id: "image", question: "what?" }, f.session, { attachedImageIds: ["image"] })).status).toBe( + "success", + ); + f.config.vision.model = undefined as any; + expect(names()).not.toContain("get_image_description"); +}); + +it("rechecks auxiliary vision permission after reading pixels before foreground model dispatch", async () => { + const f = setup(); + f.config.vision.allowAuxiliary = true; + let release!: (value: string) => void; + f.ctx.yesimbot.asset.read = vi.fn<() => Promise>( + () => + new Promise((resolve) => { + release = resolve; + }), + ); + const invocation = f.tools.invoke("get_image_description", { image_id: "image", question: "what?" }, f.session, { attachedImageIds: ["image"] }); + await vi.advanceTimersByTimeAsync(0); + expect(f.ctx.yesimbot.asset.read).toHaveBeenCalledTimes(1); + f.config.vision.allowAuxiliary = false; + release("data:image/jpeg;base64,AA=="); + expect(await invocation).toMatchObject({ status: "error" }); + expect(f.model.chat).not.toHaveBeenCalled(); +}); + +it("keeps confirmed timeout receipts in the real heartbeat observation and counts a partial reply", async () => { + const { HeartbeatProcessor } = await import("../src/agent/heartbeat-processor"); + const f = setup({}, { send_message: 15 }); + const observations: any[] = []; + let modelCalls = 0; + const processor = new HeartbeatProcessor(f.ctx, { heartbeat: 3, nativeToolCalling: true } as any, { + model: { + chat: async () => { + modelCalls++; + return { toolCalls: [{ toolName: "send_message", toolCallId: "send", args: JSON.stringify({ message: "firstsecond" }) }] }; + }, + } as any, + prompt: {} as any, + tool: f.tools, + l1: { + recordThought: async () => {}, + recordAction: async () => "action", + recordObservation: async (...args: any[]) => observations.push(args[3]), + recordHeartbeat: async () => {}, + } as any, + contextBuilder: {} as any, + logging: loggingStub(), + world: {} as any, + }); + (processor as any)._prepareLlmRequest = async () => ({ messages: [] }); + const invocation = processor.runCycle({ session: f.session } as any); + await vi.advanceTimersByTimeAsync(16); + expect(await invocation).toBe(true); + expect(observations[0]).toMatchObject({ + status: "error", + error: { code: "TOOL.TIMEOUT" }, + metadata: { delivery: { messageIds: ["id"], sentMessages: 1 } }, + }); + await vi.advanceTimersByTimeAsync(5000); + expect(modelCalls).toBe(1); + expect(f.bot.sendMessage).toHaveBeenCalledTimes(1); +}); + +it("does not automatically retry an explicitly retryable mutation", async () => { + const f = setup(); + let attempts = 0; + f.tools.registerTool({ + name: "mutation", + description: "write", + parameters: Schema.object({}), + execute: async () => { + attempts++; + return { status: "error", error: { name: "RemoteWriteUncertain", message: "unknown", retryable: true } }; + }, + }); + expect(await f.tools.invoke("mutation", {}, f.session)).toMatchObject({ status: "error", error: { retryable: false } }); + expect(attempts).toBe(1); +}); + +it("never starts a mutation after its caller's absolute deadline has already expired", async () => { + const f = setup(); + const result = await f.tools.invoke("send_message", { message: "too late" }, f.session, { deadline: Date.now() }); + expect(result).toMatchObject({ error: { code: "TOOL.TIMEOUT" }, metadata: { execution: { externalWorkMayContinue: false } } }); + await vi.advanceTimersByTimeAsync(5000); + expect(f.bot.sendMessage).not.toHaveBeenCalled(); +}); + +for (const nativeToolCalling of [false, true]) { + it(`keeps actual image tracking while filtering auxiliary tools from final ${nativeToolCalling ? "native and fallback" : "JSON"} requests`, async () => { + const { PromptContextBuilder } = await import("../src/agent/context-builder"); + const { HeartbeatProcessor } = await import("../src/agent/heartbeat-processor"); + const { PromptService } = await import("../src/prompt/service"); + const { h } = await import("koishi"); + const f = setup(); + const config: any = { + enableVision: true, + maxImagesInContext: 1, + imageLifecycleCount: 1, + allowedImageTypes: ["image/png"], + detail: "low", + multiModalSystemTemplate: "Inspect the pixels directly.", + nativeToolCalling, + contextInputBudgetTokens: 6000, + }; + const photo = { + type: "message", + id: "photo", + sender: { id: "user" }, + timestamp: new Date(), + content: ' What is this?', + elements: h.parse(' What is this?'), + is_new: true, + }; + const world: any = { + isChannelAllowed: () => true, + getConversationState: async () => ({ unknown: true }), + buildWorldState: async () => ({ + channel: { platform: "qq", id: "group", type: "guild" }, + self: { id: "bot" }, + l1_working_memory: { processed_events: [], new_events: [photo] }, + }), + }; + const builder = new PromptContextBuilder(f.ctx, config, { + model: { hasVisionCapability: () => true } as any, + tool: f.tools, + world, + asset: f.ctx.yesimbot.asset, + logging: loggingStub(), + memory: { getMemoryBlocksForRendering: () => [] } as any, + }); + let originalContent: unknown; + const buildMultimodal = builder.buildMultimodalUserMessage.bind(builder); + builder.buildMultimodalUserMessage = async (...args) => { + const content = await buildMultimodal(...args); + originalContent = content; + return content; + }; + const prompt = new PromptService(f.ctx, {} as any, loggingStub()); + prompt.registerTemplate("agent.system", "Available tools: {{#TOOL_DEFINITION}}{{name}} {{/TOOL_DEFINITION}}"); + prompt.registerTemplate("agent.user", "What is in the attached picture?"); + const modelRequests: any[] = []; + config.heartbeat = 1; + config.nativeToolCorrectionRetries = 0; + const mainModel = { + chat: async (options: any) => { + modelRequests.push(options); + return nativeToolCalling + ? { + toolCalls: [ + { + toolName: "get_image_description", + toolCallId: "same-image", + args: JSON.stringify({ image_id: "image", question: "describe again" }), + }, + ], + } + : { + text: JSON.stringify({ + thoughts: {}, + actions: [{ function: "get_image_description", params: { image_id: "image", question: "describe again" } }], + request_heartbeat: false, + }), + }; + }, + }; + const processor = new HeartbeatProcessor(f.ctx, config, { + model: mainModel as any, + tool: f.tools, + world, + contextBuilder: builder, + l1: { recordThought: async () => {}, recordAction: async () => "action", recordObservation: async () => {} } as any, + prompt, + logging: loggingStub(), + }); + const request = await (processor as any)._prepareLlmRequest({ type: "user_message", session: f.session, payload: { messageIds: ["photo"] } }); + expect(request.messages[1].content).toBe(originalContent); + expect(builder.getAttachedImageIds(request.messages)).toEqual(["image"]); + expect(request.messages[0].content).not.toContain("get_image_description"); + expect(String(request.messages[0].content).includes("send_message")).toBe(!nativeToolCalling); + const fallback = request.fallbackMessages ?? request.messages; + expect(fallback[0].content).not.toContain("get_image_description"); + expect(fallback[0].content).toContain("send_message"); + expect(builder.getAttachedImageIds(fallback)).toEqual(["image"]); + const context = { attachedImageIds: builder.getAttachedImageIds(request.messages) }; + expect(f.tools.getAvailableTools(f.session, context).map((tool) => tool.name)).not.toContain("get_image_description"); + const denied = await f.tools.invoke("get_image_description", { image_id: "image", question: "describe again" }, f.session, context); + expect(denied).toMatchObject({ status: "error", error: { name: "ToolUnavailableError" } }); + expect(denied.error?.message).toContain("图片已随本轮主请求提供"); + expect(f.model.chat).not.toHaveBeenCalled(); + builder.commitMultimodalUsage(request.messages); + expect([...(builder as any).imageLifecycleTracker.values()]).toContain(1); + expect(builder.getAttachedImageIds(request.messages)).toEqual(["image"]); + expect(await processor.runCycle({ type: "user_message", session: f.session, payload: { messageIds: ["photo"] } } as any)).toBe(false); + expect(modelRequests).toHaveLength(1); + const offered = modelRequests[0].tools?.map((tool: any) => tool.function.name) ?? modelRequests[0].messages[0].content; + expect(offered).not.toContain("get_image_description"); + expect(f.model.chat).not.toHaveBeenCalled(); + }); +} + +for (const mode of ["search", "static", "dynamic"] as const) { + it(`lets the real builtin ${mode} web operation use its HTTP/browser budget beyond 10 seconds`, async () => { + const { default: SearchExtension } = await import("../src/extension/builtin/search"); + const f = setup(); + Object.assign(f.ctx.logger, f.ctx.logger()); + f.ctx.http = { + get: async () => + new Promise((resolve) => + setTimeout( + () => + resolve( + mode === "search" ? { results: [{ title: "Result", url: "https://example.test/", content: "Body" }] } : "Body", + ), + 12000, + ), + ), + }; + f.ctx.puppeteer = { + page: async () => ({ + setUserAgent: async () => {}, + setViewport: async () => {}, + setDefaultNavigationTimeout: async () => {}, + goto: async () => new Promise((resolve) => setTimeout(() => resolve({ ok: () => true }), 25000)), + setContent: async () => new Promise((resolve) => setTimeout(resolve, 25000)), + evaluate: async () => ({ title: "Page", content: "

Body

", textContent: "Body", links: [] }), + close: async () => {}, + }), + }; + f.session.app = f.ctx; + const extension = new SearchExtension(f.ctx, SearchExtension.Config({ httpTimeout: 15000, puppeteerTimeout: 30000, puppeteerWaitTime: 2000 })); + for (const definition of (extension as any).tools.values()) f.tools.registerTool(definition); + const toolName = mode === "search" ? "web_search" : "fetch_webpage"; + const params = mode === "search" ? { query: "term" } : { url: "https://example.test/", use_dynamic: mode === "dynamic" }; + let finished = false; + const invocation = f.tools.invoke(toolName, params, f.session).then((result) => { + finished = true; + return result; + }); + await vi.advanceTimersByTimeAsync(10001); + expect(finished).toBe(false); + await vi.advanceTimersByTimeAsync(30000); + expect(await invocation).toMatchObject({ status: "success" }); + }); +} diff --git a/packages/core/tests/tool-json-schema.spec.ts b/packages/core/tests/tool-json-schema.spec.ts new file mode 100644 index 000000000..9a5eb937a --- /dev/null +++ b/packages/core/tests/tool-json-schema.spec.ts @@ -0,0 +1,97 @@ +import { Schema } from "koishi"; +import { expect, it, vi } from "vitest"; + +import InteractionsExtension from "../src/extension/builtin/interactions"; +import QManagerExtension from "../src/extension/builtin/qmanager"; +import SearchExtension from "../src/extension/builtin/search"; +import { withInnerThoughts } from "../src/extension/decorators"; +import { toolJSONSchema } from "../src/extension/json-schema"; +import { ToolService } from "../src/extension/service"; +import { loggingStub } from "./helpers/yesimbot"; +it("describes nested composite constraints without dropping input transforms", () => { + const input = Schema.intersect([ + Schema.object({ mode: Schema.union([Schema.const("a"), Schema.const("b")]).required() }), + Schema.object({ + count: Schema.number().min(2).max(8).step(2), + items: Schema.array(Schema.string().min(1).max(4)).min(1).max(3), + parsed: Schema.transform(Schema.string().description("JSON input"), JSON.parse), + }), + ]); + const json: any = toolJSONSchema(input); + expect(json.allOf[1].properties.count).toMatchObject({ type: "number", minimum: 2, maximum: 8, multipleOf: 2 }); + expect(json.allOf[1].properties.items).toMatchObject({ minItems: 1, maxItems: 3, items: { minLength: 1, maxLength: 4 } }); + expect(json.allOf[1].properties.parsed).toMatchObject({ type: "string", description: "JSON input" }); + const tools = new ToolService({} as any, {} as any, { logging: loggingStub(), world: {} } as any); + tools.registerTool({ name: "composite", description: "test", parameters: input, execute: async () => ({ status: "success" }) }); + expect((tools.getSchema("composite") as any).parametersJSONSchema).toEqual(json); +}); +it("keeps offset steps exact when a numeric step is relative to a nonzero minimum", () => { + expect(toolJSONSchema(Schema.number().min(1).step(2))).toMatchObject({ minimum: 1, "x-step": 2, "x-step-base": 1 }); + expect(toolJSONSchema(Schema.number().min(1).step(2))).not.toHaveProperty("multipleOf"); +}); + +function builtinTools() { + const logger = loggingStub(); + const ctx: any = { logger: Object.assign(() => logger.getLogger(), logger.getLogger()), on() {}, puppeteer: {} }; + const tools = new ToolService(ctx, {} as any, { logging: logger, world: {} } as any); + ctx.yesimbot = { tool: tools }; + for (const extension of [new SearchExtension(ctx, SearchExtension.Config({})), new InteractionsExtension(ctx, {}), new QManagerExtension(ctx, {})]) { + for (const definition of (extension as any).tools.values()) tools.registerTool(definition); + } + return { tools, ctx }; +} + +it("keeps the old inner_thoughts input out of tool descriptions and native schemas", () => { + const { tools } = builtinTools(); + tools.registerTool({ name: "legacy", description: "legacy", parameters: withInnerThoughts({}), execute: async () => ({ status: "success" }) }); + for (const name of ["legacy", "fetch_webpage", "send_poke"]) { + const definition = tools.getSchema(name)!; + expect(definition.parameters).not.toHaveProperty("inner_thoughts"); + expect(definition.parametersJSONSchema.properties).not.toHaveProperty("inner_thoughts"); + } + expect(withInnerThoughts({})({ inner_thoughts: "old input" })).toEqual({ inner_thoughts: "old input" }); +}); + +it("exposes one link-count option and accepts the legacy link opt-out", async () => { + const { tools, ctx } = builtinTools(); + const extraction = vi.spyOn(SearchExtension.prototype as any, "_fetchAndExtractWithPuppeteer").mockResolvedValue({ + title: "Example", + textContent: "Page", + links: [{ url: "https://example.com/next" }], + }); + try { + const schema = tools.getSchema("fetch_webpage")!; + expect(schema.parameters).not.toHaveProperty("include_links"); + expect(schema.parametersJSONSchema.properties).toMatchObject({ max_links: { default: 10, minimum: 0 } }); + expect(schema.parametersJSONSchema.properties).not.toHaveProperty("include_links"); + const session = { app: ctx } as any; + const url = "https://example.com"; + expect(await tools.invoke("fetch_webpage", { url }, session)).toMatchObject({ result: expect.stringContaining("/next") }); + expect((await tools.invoke("fetch_webpage", { url, max_links: 0 }, session)).result).not.toContain("/next"); + expect((await tools.invoke("fetch_webpage", { url, max_links: 4, include_links: false }, session)).result).not.toContain("/next"); + expect(extraction.mock.calls.map(([, , limit]) => limit)).toEqual([10, 0, 0]); + } finally { + extraction.mockRestore(); + } +}); + +it("uses a consistent guild selector and rejects conflicting aliases before calling the adapter", async () => { + const { tools } = builtinTools(); + const muteGuildMember = vi.fn(async () => {}); + const request = vi.fn(async () => ({ status: "ok" })); + const session = { platform: "onebot", guildId: "home", channelId: "thread", bot: { muteGuildMember }, onebot: { _request: request } } as any; + for (const name of ["send_poke", "ban", "kick"]) { + const schema = tools.getSchema(name)!; + expect(schema.parametersJSONSchema.properties).toHaveProperty("guild_id"); + expect(schema.parametersJSONSchema.properties).not.toHaveProperty(name === "send_poke" ? "channel" : "channel_id"); + } + expect(await tools.invoke("send_poke", { user_id: "123" }, session)).toMatchObject({ status: "success" }); + expect((await tools.invoke("send_poke", { user_id: "123", channel: "legacy" }, session)).status).toBe("success"); + expect(request.mock.calls).toEqual([ + ["group_poke", { group_id: "home", user_id: 123 }], + ["group_poke", { group_id: "legacy", user_id: 123 }], + ]); + expect((await tools.invoke("ban", { user_id: "123", guild_id: "canonical", duration: 1 }, session)).status).toBe("success"); + expect((await tools.invoke("ban", { user_id: "123", guild_id: "canonical", channel_id: "legacy", duration: 1 }, session)).status).toBe("error"); + expect(muteGuildMember.mock.calls).toEqual([["canonical", "123", 60000]]); +}); diff --git a/packages/core/tests/tool-output-invocation.spec.ts b/packages/core/tests/tool-output-invocation.spec.ts index 360e79d47..e65234c24 100644 --- a/packages/core/tests/tool-output-invocation.spec.ts +++ b/packages/core/tests/tool-output-invocation.spec.ts @@ -66,22 +66,22 @@ describe("long tool invocation receipts", () => { const receipt = await tools.invoke("probe", {}, session); await expect(tools.readToolOutput({ ...session, userId: "someone-else" }, { uri: receipt.result.uri })).rejects.toThrow(/scope/); }); - it("rejects clear, revocation, identity mutation in flight without retrying completed execution", async () => { - for (const change of ["clear", "revoke", "identity"]) { - const f = await fixture(); - const execute = vi.fn(async () => { - await Promise.resolve(); - if (change === "identity") f.session.channelId = "elsewhere"; - else f[change](); - return { status: "success", result: "x".repeat(30000), metadata: { receipt: "done" } }; - }); - register(f.tools, execute); - const result = await f.tools.invoke("probe", {}, f.session); - expect(result.status).toBe("success"); - expect(result.result.kind).toBe("tool-output-unavailable"); - expect(result.metadata.payloadError.retryable).toBe(false); - expect(execute).toHaveBeenCalledTimes(1); - } + it.each([ + { change: "clear", expected: { status: "success", result: { kind: "tool-output-unavailable" }, metadata: { payloadError: { retryable: false } } } }, + { change: "revoke", expected: { status: "error", error: { name: "ToolInvalidatedError", retryable: false } } }, + { change: "identity", expected: { status: "success", result: { kind: "tool-output-unavailable" }, metadata: { payloadError: { retryable: false } } } }, + ])("rejects $change in flight without retrying completed execution", async ({ change, expected }) => { + const f = await fixture(); + const execute = vi.fn(async () => { + await Promise.resolve(); + if (change === "identity") f.session.channelId = "elsewhere"; + else f[change](); + return { status: "success", result: "x".repeat(30000), metadata: { receipt: "done" } }; + }); + register(f.tools, execute); + const result = await f.tools.invoke("probe", {}, f.session); + expect(result).toMatchObject(expected); + expect(execute).toHaveBeenCalledTimes(1); }); it("reports cyclic and non-JSON result serialization separately from execution status", async () => { const { tools, session } = await fixture(); diff --git a/packages/core/tests/tool-readonly-action.spec.ts b/packages/core/tests/tool-readonly-action.spec.ts new file mode 100644 index 000000000..5af8aec03 --- /dev/null +++ b/packages/core/tests/tool-readonly-action.spec.ts @@ -0,0 +1,68 @@ +import { Schema } from "koishi"; +import { expect, it } from "vitest"; + +import { Extension, Tool } from "../src/extension/decorators"; +import { ToolService } from "../src/extension/service"; +import { loggingStub } from "./helpers/yesimbot"; + +it("binds action-level read policy to the extension and retries only its pure reads", async () => { + const ctx: any = { on() {}, filter: () => true, logger: () => ({ warn() {} }) }; + const tools = new ToolService(ctx, { advanced: { maxRetry: 1, retryDelay: 0 } } as any, { logging: loggingStub() } as any); + ctx.yesimbot = { tool: tools }; + @Extension({ name: "mixed", display: "mixed", description: "mixed", version: "1" }) + class Mixed { + reads = new Set(["list"]); + attempts = 0; + constructor( + public ctx: any, + public config: any, + ) {} + @Tool({ + description: "mixed", + parameters: Schema.object({ action: Schema.string().required() }), + readOnly(this: Mixed, args: Record) { + return this.reads.has(args.action as string); + }, + } as any) + async person_memory() { + this.attempts++; + return { status: "error", error: { name: "TemporaryError", message: "retryable", retryable: true } }; + } + } + const mixed = new Mixed(ctx, {}); + for (const definition of (mixed as any).tools.values()) tools.registerTool(definition); + try { + await tools.invoke("person_memory", { action: "list" }); + expect(mixed.attempts).toBe(2); + const write = await tools.invoke("person_memory", { action: "propose" }); + expect(mixed.attempts).toBe(3); + expect(write.error?.retryable).toBe(false); + } finally { + await tools.stop(); + } +}); + +it("fails closed when an action read policy throws even on a background-capable tool", async () => { + const ctx: any = { on() {}, filter: () => true }; + const tools = new ToolService(ctx, { advanced: { maxRetry: 2, retryDelay: 0 } } as any, { logging: loggingStub() } as any); + let attempts = 0; + tools.registerTool({ + name: "mixed", + description: "test", + parameters: Schema.object({}), + background: true, + readOnly: () => { + throw new Error("policy unavailable"); + }, + execute: async () => { + attempts++; + return { status: "error", error: { name: "Error", message: "retryable", retryable: true } }; + }, + } as any); + try { + expect((await tools.invoke("mixed", {})).error?.retryable).toBe(false); + expect(attempts).toBe(1); + } finally { + await tools.stop(); + } +}); diff --git a/packages/core/tests/tool-session-boundary.spec.ts b/packages/core/tests/tool-session-boundary.spec.ts index 9f1f78959..ac7837e0b 100644 --- a/packages/core/tests/tool-session-boundary.spec.ts +++ b/packages/core/tests/tool-session-boundary.spec.ts @@ -2,6 +2,7 @@ import { Schema } from "koishi"; import { test, expect } from "vitest"; import { ToolService } from "../src/extension/service"; +import { loggingStub } from "./helpers/yesimbot"; test("model parameters cannot replace the authenticated tool session", async () => { const realSession = { channelId: "current", userId: "user" }; @@ -13,15 +14,8 @@ test("model parameters cannot replace the authenticated tool session", async () return { status: "success" }; }, }; - // Partial stub of ToolService: only the members invoke() touches on this path. - const service = { - getTool: () => tool, - _logger: { info() {}, warn() {}, success() {} }, - config: { advanced: { maxRetry: 0 } }, - executeInvocation: ToolService.prototype["executeInvocation"], - // invoke() reads this.deps.world after execution; world is undefined on purpose so its guard skips event recording. - deps: { world: undefined }, - } as unknown as ToolService; + const service = new ToolService({} as any, { advanced: { maxRetry: 0 } } as any, { logging: loggingStub() } as any); + service.getTool = () => tool as any; await ToolService.prototype.invoke.call(service, "person_memory", { action: "read", session: { channelId: "other", userId: "admin" } }, realSession as any); expect(observed).toBe(realSession); }); diff --git a/packages/core/tests/topic-fallback.spec.ts b/packages/core/tests/topic-fallback.spec.ts index 6bed6fd21..9e3b1d405 100644 --- a/packages/core/tests/topic-fallback.spec.ts +++ b/packages/core/tests/topic-fallback.spec.ts @@ -14,7 +14,7 @@ function fixture() { const reset: string[] = []; const ctx = stubCtx({ model: { - getChatModel: () => ({ + useChatModel: () => ({ chat: (options: any) => new Promise((resolve) => { requests.push({ resolve, signal: options.abortSignal }); diff --git a/packages/core/tests/trace-query.spec.ts b/packages/core/tests/trace-query.spec.ts index 19e99bdfe..53c58392a 100644 --- a/packages/core/tests/trace-query.spec.ts +++ b/packages/core/tests/trace-query.spec.ts @@ -45,6 +45,9 @@ it("returns a useful missing-provider error through real Koishi command dispatch const command = app.$commander.get("history.context")!; expect(String(command._usage)).toContain("--target"); expect(command._examples).toContain("history.context --adapter onebot --target onebot:857518324"); + const tokens = app.$commander.get("history.tokens")!; + expect(tokens.parse("--reset").options).toEqual({ reset: true }); + expect(tokens.parse("--restart").options).toEqual({ reset: true }); }); it("accepts an exact bounded trace option and prevents trace from being ignored during a statistics reset", () => { diff --git a/packages/core/tests/usage-owner-scope.spec.ts b/packages/core/tests/usage-owner-scope.spec.ts index ca283acdd..a64f41511 100644 --- a/packages/core/tests/usage-owner-scope.spec.ts +++ b/packages/core/tests/usage-owner-scope.spec.ts @@ -15,6 +15,7 @@ import type { IProviderClient } from "../src/model/factories"; import { ProviderInstance } from "../src/model/provider-instance"; import { ModelService } from "../src/model/service"; import { getUsageLedger, observeUsageFetch } from "../src/model/usage"; +import { bindUsageOwner, resolveUsageOwner } from "../src/model/usage-owner"; import type { UsageOwner } from "../src/model/usage-owner"; import { loggingStub } from "./helpers/yesimbot"; @@ -64,6 +65,7 @@ test("explicit telemetry owner avoids model service lookup and shares history/re const ledger = getUsageLedger(commandCtx, ownerA); assert.equal((await ledger.snapshot()).records.length, 1); const facadeCtx = { yesimbot: { model: { usageOwner: ownerA } } } as unknown as Context; + bindUsageOwner(facadeCtx, ownerA); assert.equal(getUsageLedger(facadeCtx), ledger); assert.equal(getContextSnapshots(facadeCtx).length, 1); assert.equal(getContextSnapshots(commandCtx, ownerA).length, 1); @@ -171,3 +173,10 @@ test("model service startup and its providers share an explicit owner before fac await rm(dir, { recursive: true, force: true }); } }); + +test("an unbound telemetry context never probes an undeclared facade", () => { + const ctx = telemetryContext("/tmp/unused", "unbound", () => { + throw new Error("undeclared service lookup"); + }); + assert.equal(resolveUsageOwner(ctx), undefined); +}); diff --git a/packages/core/tests/vision-task-followup.spec.ts b/packages/core/tests/vision-task-followup.spec.ts new file mode 100644 index 000000000..d647b924b --- /dev/null +++ b/packages/core/tests/vision-task-followup.spec.ts @@ -0,0 +1,319 @@ +import { readFileSync } from "node:fs"; + +import { h } from "koishi"; +import { expect, it, vi } from "vitest"; + +import { PromptContextBuilder } from "../src/agent/context-builder"; +import { HeartbeatProcessor } from "../src/agent/heartbeat-processor"; +import { ChatModelSwitcher } from "../src/model/service"; +import { PromptService } from "../src/prompt/service"; +import { loggingStub, stubCtx } from "./helpers/yesimbot"; + +const resource = (name: string) => readFileSync(new URL(`../resources/${name}`, import.meta.url), "utf8"); +function fixture() { + const diagnostics: string[] = []; + const logger: any = { extend: () => logger, debug: (text: string) => diagnostics.push(text), info() {}, warn() {}, error() {}, success() {} }; + const logging = loggingStub(logger); + const config: any = { + enableVision: true, + allowedImageTypes: ["image/png"], + maxImagesInContext: 1, + imageLifecycleCount: 1, + detail: "low", + multiModalSystemTemplate: "Images are provided as pixels.", + heartbeat: 6, + contextInputBudgetTokens: 6000, + userTemplate: resource("prompts/user_base.txt"), + }; + const session: any = { platform: "mock", channelId: "room", userId: "alice", selfId: "bot", isDirect: false, bot: {} }; + const photo: any = { + type: "message", + id: "photo", + channelType: "guild", + sender: { id: "alice", name: "Alice" }, + timestamp: new Date(), + content: ' ORIGINAL_IMAGE_QUESTION', + elements: h.parse(' ORIGINAL_IMAGE_QUESTION'), + is_message: true, + is_new: true, + }; + const records = new Map([[photo.id, photo]]); + let visible: any[] = [photo], + generation = 0, + lookups = 0; + const world: any = { + isChannelAllowed: () => true, + l2_manager: { getHistoryGeneration: () => generation, watchHistory: () => () => {} }, + buildWorldState: async (current: any) => ({ + channel: { platform: "mock", type: "guild", id: current.channelId }, + self: { id: "bot" }, + l1_working_memory: { processed_events: visible.filter((item) => !item.is_new), new_events: visible.filter((item) => item.is_new) }, + }), + getConversationState: async () => ({ unknown: true }), + readMessageWindow: vi.fn<(_session: any, options: any) => Promise>(async (_session: any, options: any) => ({ + anchor: { ...records.get(options.messageId), platform: "mock", channelId: "room" }, + quotes: [], + })), + }; + const ctx: any = stubCtx({}, { filter: () => true }); + const wires: Array<{ model: string; messages: any[] }> = []; + const models: any[] = [false, true].map((vision) => ({ + id: vision ? "visual" : "text", + config: { abilities: [], retryPolicy: { maxRetries: 0 }, timeoutPolicy: { totalTimeout: 3 } }, + isVisionModel: () => vision, + chat: async (request: any) => { + wires.push({ model: vision ? "visual" : "text", messages: request.messages }); + const lookup = lookups-- > 0; + return { + text: JSON.stringify({ thoughts: {}, actions: lookup ? [{ function: "lookup", params: {} }] : [], request_heartbeat: lookup }), + finishReason: "stop", + usage: { prompt_tokens: 1, completion_tokens: 1 }, + }; + }, + })); + const model = new ChatModelSwitcher( + ctx, + { name: "mixed", models: models.map((item) => ({ providerName: "test", modelId: item.id })) }, + (_provider, id) => models.find((item) => item.id === id), + logging, + ); + const tool: any = { getToolSchemas: () => [], invoke: async () => ({ status: "success", result: "lookup completed" }) }; + const asset: any = { + getInfo: vi.fn<(id: string) => Promise>(async (id: string) => ({ id, mime: "image/png" })), + read: vi.fn<() => Promise>(async () => "data:image/png;base64,cGl4ZWxz"), + }; + const builder = new PromptContextBuilder(ctx, config, { logging, model, world, tool, asset, memory: { getMemoryBlocksForRendering: () => [] } as any }); + const prompt = new PromptService(ctx, {} as any, logging); + prompt.registerTemplate("agent.system", "Follow the current question."); + prompt.registerTemplate("agent.user", config.userTemplate); + for (const name of ["world_state", "l1_history_item"]) prompt.registerTemplate(`agent.partial.${name}`, resource(`templates/${name}.mustache`)); + const l1: any = { + recordThought: async () => {}, + recordAction: async () => "action", + recordObservation: async (_id: string, _platform: string, _channel: string, observation: any) => { + visible.push({ type: "agent_observation", timestamp: new Date(), is_agent_observation: true, is_new: true, ...observation }); + }, + recordHeartbeat: async () => {}, + }; + const processor = new HeartbeatProcessor(ctx, config, { model, world, tool, logging, prompt, l1, contextBuilder: builder }); + const stimulus = (id: string): any => ({ type: "user_message", session: { ...session, messageId: id }, payload: { messageIds: [id] } }); + const followUp = (id: string, keepPhoto = false, userId = "alice") => { + const message: any = { + ...photo, + id, + sender: { id: userId, name: userId }, + timestamp: new Date(), + content: "那图右边的小字是什么?", + elements: h.parse("那图右边的小字是什么?"), + }; + records.set(id, message); + visible = keepPhoto ? [{ ...photo, is_new: false }, message] : [message]; + return { ...stimulus(id), session: { ...session, userId, messageId: id } }; + }; + return { + config, + model, + session, + photo, + records, + world, + asset, + builder, + processor, + wires, + diagnostics, + stimulus, + followUp, + setLookups: (count: number) => (lookups = count), + setVisible: (messages: any[]) => (visible = messages), + clear: () => generation++, + }; +} +const images = (messages: any[]) => + messages.flatMap((message) => (Array.isArray(message.content) ? message.content.filter((part: any) => part.type === "image_url") : [])); + +it.each([1, 2])( + "keeps pixels in the final visual-model request across an unquoted follow-up and several tool heartbeats with lifecycle=%s", + async (lifecycle) => { + const f = fixture(); + f.config.imageLifecycleCount = lifecycle; + await f.processor.runCycle(f.stimulus("photo")); + f.setLookups(3); + await f.processor.runCycle(f.followUp("follow-up")); + expect(f.wires).toHaveLength(5); + for (const request of f.wires) { + expect(request.model).toBe("visual"); + expect(images(request.messages)).toHaveLength(1); + expect(images(request.messages)[0].image_url.url).toBe("data:image/png;base64,cGl4ZWxz"); + } + expect(f.world.readMessageWindow).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ messageId: "photo" })); + }, +); + +it.each([1, 2])("counts a user task once instead of consuming the image lifetime on each internal heartbeat with lifecycle=%s", async (lifecycle) => { + const f = fixture(); + f.config.imageLifecycleCount = lifecycle; + f.setLookups(4); + await f.processor.runCycle(f.stimulus("photo")); + expect(f.wires).toHaveLength(5); + expect(f.wires.every((request) => request.model === "visual" && images(request.messages).length === 1)).toBe(true); + expect([...(f.builder as any).imageLifecycleTracker.values()]).toEqual([1]); +}); + +it("does not recover a cleared or another user's previously seen image", async () => { + const f = fixture(); + await f.processor.runCycle(f.stimulus("photo")); + await f.processor.runCycle(f.followUp("other-user", false, "bob")); + expect(images(f.wires.at(-1)!.messages)).toHaveLength(0); + f.clear(); + await f.processor.runCycle(f.followUp("after-clear")); + expect(images(f.wires.at(-1)!.messages)).toHaveLength(0); +}); + +it("expires unquoted recent-image protection after the configured user-message window", async () => { + const f = fixture(); + f.config.imageFollowUpMaxTurns = 1; + await f.processor.runCycle(f.stimulus("photo")); + await f.processor.runCycle(f.followUp("first-follow-up", true)); + expect(images(f.wires.at(-1)!.messages)).toHaveLength(1); + await f.processor.runCycle(f.followUp("second-follow-up", true)); + expect(images(f.wires.at(-1)!.messages)).toHaveLength(0); +}); + +it("isolates recent source recovery by canonical conversation", async () => { + const f = fixture(); + await f.processor.runCycle(f.stimulus("photo")); + const other = f.followUp("other-room"); + other.session.channelId = "other-room"; + await f.processor.runCycle(other); + expect(images(f.wires.at(-1)!.messages)).toHaveLength(0); + expect(f.world.readMessageWindow).not.toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ messageId: "photo" })); +}); + +it("expires an unquoted image after the configured time window", async () => { + const f = fixture(); + await f.processor.runCycle(f.stimulus("photo")); + const clock = vi.spyOn(Date, "now").mockReturnValue(Date.now() + 601000); + try { + await f.processor.runCycle(f.followUp("expired", true)); + expect(images(f.wires.at(-1)!.messages)).toHaveLength(0); + expect(f.diagnostics.some((line) => line.includes("recent_image_window_expired"))).toBe(true); + } finally { + clock.mockRestore(); + } +}); + +it("recognizes only builder-created image parts as attached pixels, including after success", async () => { + const f = fixture(); + const prepared = await (f.processor as any)._prepareLlmRequest(f.stimulus("photo")); + f.builder.commitMultimodalUsage(prepared.messages); + expect(f.builder.getAttachedImageIds(prepared.messages)).toEqual(["pixels"]); + expect(f.builder.getAttachedImageIds([{ content: [{ type: "text", text: "The following is an image with ID #pixels:" }] }])).toEqual([]); + expect(f.builder.getAttachedImageIds(structuredClone(prepared.messages))).toEqual(["pixels"]); + expect(f.builder.getAttachedImageIds([{ content: [{ type: "image_url", image_url: { url: "data:image/png;base64,dW5rbm93bg==" } }] }])).toEqual([]); +}); + +it.each(["disabled", "text-only", "count-limit", "unsupported-type", "missing-asset", "invalid-pixels"])( + "diagnoses %s without exposing pixels, source text, or URLs", + async (reason) => { + const f = fixture(); + if (reason === "disabled") f.config.enableVision = false; + if (reason === "text-only") vi.spyOn(f.model, "hasVisionCapability").mockReturnValue(false); + if (reason === "count-limit") f.config.maxImagesInContext = 0; + if (reason === "unsupported-type") f.asset.getInfo.mockResolvedValue({ id: "pixels", mime: "image/gif" }); + if (reason === "missing-asset") f.asset.getInfo.mockResolvedValue(undefined); + if (reason === "invalid-pixels") f.asset.read.mockResolvedValue("a text description, not image pixels"); + await f.processor.runCycle(f.stimulus("photo")); + expect(images(f.wires[0].messages)).toHaveLength(0); + const log = f.diagnostics.filter((line) => line.startsWith("图片上下文 |")); + const markers: Record = { + disabled: "vision_disabled", + "text-only": "no_vision_model", + "count-limit": '"count_limit":1', + "unsupported-type": '"unsupported_mime":1', + "missing-asset": '"missing_asset":1', + "invalid-pixels": '"invalid_image_data":1', + }; + expect(log.join(" ")).toContain(markers[reason]); + expect(log.join(" ")).not.toMatch(/data:image|ORIGINAL_IMAGE_QUESTION|cGl4ZWxz|a text description/); + }, +); + +it("keeps usage accounting when tool-schema rendering clones the content array and text parts", async () => { + const f = fixture(); + f.config.imageLifecycleCount = 2; + const prepared = await (f.processor as any)._prepareLlmRequest(f.stimulus("photo")); + prepared.messages[1].content = prepared.messages[1].content.map((part: any) => (part.type === "text" ? { ...part, text: part.text + " updated" } : part)); + expect(f.builder.getAttachedImageIds(prepared.messages)).toEqual(["pixels"]); + f.builder.commitMultimodalUsage(prepared.messages); + expect([...(f.builder as any).imageLifecycleTracker.values()]).toEqual([1]); +}); + +it.each(["asset_metadata_failed", "asset_read_failed"])("diagnoses %s without logging storage error contents", async (reason) => { + const f = fixture(); + if (reason === "asset_metadata_failed") f.asset.getInfo.mockRejectedValue(new Error("SECRET_IMAGE_URL")); + else f.asset.read.mockRejectedValue(new Error("SECRET_IMAGE_URL")); + const prepared = await (f.processor as any)._prepareLlmRequest(f.stimulus("photo")); + expect(typeof prepared.messages[1].content).toBe("string"); + const diagnostics = f.diagnostics.filter((line) => line.startsWith("图片上下文 |")); + expect(diagnostics.join(" ")).toContain(reason); + expect(diagnostics.join(" ")).not.toContain("SECRET_IMAGE_URL"); +}); + +it("counts same-user messages that did not wake the agent toward the follow-up limit", async () => { + const f = fixture(); + f.config.imageFollowUpMaxTurns = 1; + await f.processor.runCycle(f.stimulus("photo")); + const follow = f.followUp("waking-follow-up", true); + f.setVisible([ + { ...f.photo, is_new: false }, + { ...f.records.get("waking-follow-up"), id: "silent-follow-up", is_new: false }, + f.records.get("waking-follow-up"), + ]); + await f.processor.runCycle(follow); + expect(images(f.wires.at(-1)!.messages)).toHaveLength(0); + expect(f.diagnostics.some((line) => line.includes('"follow_up_count":2'))).toBe(true); +}); + +it("recovers the latest same-user image skipped while busy even after it leaves L1", async () => { + const f = fixture(); + f.photo.timestamp = new Date(Date.now() - 1000); + await f.processor.runCycle(f.stimulus("photo")); + const newer = { + ...f.photo, + id: "skipped-photo", + timestamp: new Date(Date.now()), + content: '', + elements: h.parse(''), + }; + f.records.set(newer.id, newer); + const follow = f.followUp("after-skipped-photo"); + f.world.readMessageWindow.mockImplementation(async (_session: any, options: any) => ({ + anchor: { ...f.records.get(options.messageId), platform: "mock", channelId: "room" }, + quotes: [], + records: options.before ? [newer, f.records.get("after-skipped-photo")].map((record) => ({ ...record, platform: "mock", channelId: "room" })) : [], + })); + await f.processor.runCycle(follow); + expect(f.builder.getAttachedImageIds(f.wires.at(-1)!.messages)).toEqual(["new-pixels"]); +}); + +it("rejects discovery results when history is cleared while the bounded window is being read", async () => { + const f = fixture(); + await f.processor.runCycle(f.stimulus("photo")); + const follow = f.followUp("after-clear-during-discovery"); + let release!: (page: any) => void; + let started!: () => void; + const reading = new Promise((resolve) => (started = resolve)); + f.world.readMessageWindow.mockImplementationOnce(async () => { + started(); + return await new Promise((resolve) => (release = resolve)); + }); + const building = f.builder.build(follow); + await reading; + f.clear(); + release({ anchor: f.records.get("after-clear-during-discovery"), records: [{ ...f.photo, platform: "mock", channelId: "room" }], quotes: [] }); + await expect(building).rejects.toThrow("历史已清除"); + expect(f.asset.read).toHaveBeenCalledTimes(1); + await f.processor.runCycle(f.followUp("new-epoch-follow-up")); + expect(images(f.wires.at(-1)!.messages)).toHaveLength(0); +}); diff --git a/packages/daily-planner/README.md b/packages/daily-planner/README.md index 9d413c826..2fac8767b 100644 --- a/packages/daily-planner/README.md +++ b/packages/daily-planner/README.md @@ -27,3 +27,9 @@ bun build ``` bun pack ``` + +## 记忆来源与日程隔离 + +默认仅根据所选核心记忆生成日程。需要参考近期事件时,在 `memorySources` 中逐项配置平台、机器人账号、频道、读取身份及是否私聊;只有当前仍允许读取的来源会被采用。日程会向此扩展的所有使用者展示,请只配置适合这些读者共同知晓的来源。 + +每个扩展配置实例拥有独立日程,重启后使用同一配置入口即可恢复。旧版本只有日期、没有归属的日程会保留,但不会自动归入任何新实例;升级后重新生成即可。若来源权限、历史、人物纠错或核心记忆改变,旧日程会在下次读取时重新生成。生成过程中来源发生变化时,本次生成失败,需要重新执行。 diff --git a/packages/daily-planner/src/index.ts b/packages/daily-planner/src/index.ts index 29ae126f8..1e02a0672 100644 --- a/packages/daily-planner/src/index.ts +++ b/packages/daily-planner/src/index.ts @@ -10,6 +10,7 @@ export interface DailyPlannerConfig { coreMemoryLabel: string[]; characterName: string; coreMemoryWeight: number; + memorySources?: Array<{ platform: string; selfId: string; channelId: string; userId: string; isDirect: boolean; guildId?: string }>; } @Extension({ @@ -26,6 +27,18 @@ export default class DailyPlannerExtension { scheduleGenerationTime: Schema.string().default("03:00").description("每日生成日程的时间 (HH:mm 格式)"), characterName: Schema.string().required().description("日程的主体,也就是 Bot 的名称"), coreMemoryLabel: Schema.array(String).default(["persona"]).description("用于生成日程的描述 Bot 的核心记忆"), + memorySources: Schema.array( + Schema.object({ + platform: Schema.string().required(), + selfId: Schema.string().required(), + channelId: Schema.string().required(), + userId: Schema.string().required(), + isDirect: Schema.boolean().default(false), + guildId: Schema.string(), + }), + ) + .default([]) + .description("允许日程读取的会话来源;留空时只使用核心记忆。仅添加可向所有日程读者公开的来源。"), model: Schema.dynamic("modelService.selectableModels").description("用于生成日程表的模型"), coreMemoryWeight: Schema.number().default(0.7).min(0).max(1).description("核心记忆在日程生成中的权重"), }); @@ -57,11 +70,11 @@ export default class DailyPlannerExtension { ctx.on( "dispose", - promptService.inject("daily_plan", 0, async () => { + promptService.inject("daily_plan", 0, async (view) => { if (this.disposed) return ""; const currentSchedule = await this.getCurrentSchedule(); - return `现在是 {{ date.now }},当前时段的安排为:${currentSchedule}。`; + return `现在是 ${view.date?.now ?? new Date().toISOString()},当前时段的安排为:${currentSchedule}。`; }), ); diff --git a/packages/daily-planner/src/service.ts b/packages/daily-planner/src/service.ts index 2e1cbe1e9..4a943c414 100644 --- a/packages/daily-planner/src/service.ts +++ b/packages/daily-planner/src/service.ts @@ -1,5 +1,7 @@ +import { createHash } from "node:crypto"; + import { Context } from "koishi"; -import { IChatModel, MemoryBlockData, MemoryService } from "koishi-plugin-yesimbot"; +import { conversationChannelId, getInstanceScope, IChatModel, MemoryBlockData, MemoryService } from "koishi-plugin-yesimbot"; import { DailyPlannerConfig } from "."; @@ -12,6 +14,8 @@ interface TimeSegment { // 日程数据结构 interface DailySchedule { + instance: string; + sourceFingerprint: string; date: string; // YYYY-MM-DD segments: TimeSegment[]; // 时间段数组 memoryContext?: string[]; // 关联的记忆ID @@ -19,7 +23,7 @@ interface DailySchedule { declare module "koishi" { interface Tables { - "yesimbot.daily_schedules": DailySchedule; + "yesimbot.daily_schedules_v2": DailySchedule; } } @@ -37,7 +41,7 @@ export class DailyPlannerService { this.disposed = true; }); this.memoryService = ctx.yesimbot.memory; - this.chatModel = ctx.yesimbot.model.getChatModel(this.config.model.providerName, config.model.modelId); + this.chatModel = ctx.yesimbot.model.useChatModel(this.config.model.providerName, config.model.modelId); this.registerDatabaseModel(); this.registerPromptSnippet(); this.ctx.logger.info("日程服务已初始化"); @@ -45,14 +49,16 @@ export class DailyPlannerService { private registerDatabaseModel() { this.ctx.model.extend( - "yesimbot.daily_schedules", + "yesimbot.daily_schedules_v2", { + instance: "string(24)", + sourceFingerprint: "string(64)", date: "string(10)", segments: "json", memoryContext: "list", }, { - primary: "date", + primary: ["instance", "date"], }, ); } @@ -82,6 +88,10 @@ export class DailyPlannerService { }); } + private get instance() { + return getInstanceScope(this.ctx, undefined, { owner: this.ctx }); + } + // 生成今日日程 public async generateDailySchedule(): Promise { const today = formatDate(new Date()); @@ -99,41 +109,83 @@ export class DailyPlannerService { } private async generateScheduleForDate(today: string): Promise { - // 1. 获取核心记忆和近期事件 - const coreMemories = await this.getCoreMemories(); - - const recentEvents = await this.ctx.yesimbot.world.l2_manager.search("我"); - - // 2. 构建提示词 + const sources = await this.readSources(); const prompt = this.buildSchedulePrompt( - coreMemories, - recentEvents.map((e) => e.content), + sources.coreMemories, + sources.recentEvents.map((e) => e.content), ); - - // 3. 调用模型生成日程 if (this.disposed) throw new Error("日程服务已停止"); const generatedSchedule = await this.generateWithModel(prompt); - - // 4. 解析并存储日程 - const parsedSchedule = this.parseScheduleOutput(generatedSchedule); + // A model response is a derived snapshot: never commit it after revocation, + // correction, history clearing, or a change to its configured sources. + if ((await this.readSources()).fingerprint !== sources.fingerprint) throw new Error("日程依据或读取权限已改变,请重新生成"); const fullSchedule: DailySchedule = { + instance: this.instance, + sourceFingerprint: sources.fingerprint, date: today, - segments: parsedSchedule, - memoryContext: [...coreMemories.map((m) => m.label), ...recentEvents.map((e) => e.id)], + segments: this.parseScheduleOutput(generatedSchedule), + memoryContext: [...sources.coreMemories.map((m) => m.label), ...sources.recentEvents.map((e) => e.id)], }; - await this.saveSchedule(fullSchedule); + if ((await this.readSources()).fingerprint !== sources.fingerprint) throw new Error("日程依据或读取权限已改变,请重新生成"); return fullSchedule; } - // 获取今日日程 + /** Only explicit, currently authorized sources may contribute to a plan. */ + private async readSources() { + const coreMemories = await this.getCoreMemories(); + const configured = structuredClone(this.config.memorySources ?? []); + const recentEvents: any[] = []; + const pages: unknown[] = []; + const validateSources: Array<() => void> = []; + for (const source of configured) { + const bot = this.ctx.bots.find((bot) => bot.platform === source.platform && bot.selfId === source.selfId); + if (!bot) continue; + const session = bot.session({ + platform: source.platform, + selfId: source.selfId, + channel: { id: source.channelId, type: source.isDirect ? 1 : 0 }, + user: { id: source.userId }, + guild: source.guildId ? { id: source.guildId } : undefined, + }); + if (!this.ctx.filter(session) || !this.ctx.yesimbot.world.isChannelAllowed(session)) continue; + const binding = () => JSON.stringify([session.platform, session.selfId, session.channelId, session.userId, session.guildId, session.isDirect]); + const originalBinding = binding(); + const target = { platform: session.platform, channelId: conversationChannelId(session)! }; + const world = this.ctx.yesimbot.world; + const page = await world.recallContext(session, { kind: "l2", limit: 20 }); + const validate = () => { + if ( + this.disposed || + this.ctx.yesimbot.world !== world || + binding() !== originalBinding || + !this.ctx.filter(session) || + !world.isChannelAllowed(session) || + world.l2_manager.getHistoryGeneration(target) !== page.historyGeneration + ) + throw new Error("日程来源权限、身份或历史已改变"); + }; + validate(); + validateSources.push(validate); + pages.push([source, page]); + recentEvents.push(...page.records); + } + // A later source may suspend after an earlier source has returned. Check + // every captured source again, synchronously, after the final await. + if (JSON.stringify(this.config.memorySources ?? []) !== JSON.stringify(configured)) throw new Error("日程来源配置已改变"); + for (const validate of validateSources) validate(); + const fingerprint = createHash("sha256") + .update(JSON.stringify([configured, coreMemories, pages])) + .digest("hex"); + return { coreMemories, recentEvents, fingerprint }; + } + + // 获取今日日程(每次投影重新核对来源,审计记录保留不改写) public async getTodaysSchedule(): Promise { if (this.disposed) throw new Error("日程服务已停止"); const today = formatDate(new Date()); - const schedule = await this.ctx.database.get("yesimbot.daily_schedules", { date: today }); - - if (!schedule.length) { - this.ctx.logger.info("今日日程未生成,正在创建..."); + const schedule = await this.ctx.database.get("yesimbot.daily_schedules_v2", { instance: this.instance, date: today }); + if (!schedule.length || schedule[0].sourceFingerprint !== (await this.readSources()).fingerprint) { return this.generateDailySchedule(); } return schedule[0]; @@ -456,7 +508,7 @@ export class DailyPlannerService { private async saveSchedule(schedule: DailySchedule): Promise { if (this.disposed) throw new Error("日程服务已停止"); this.validateSegments(schedule.segments); - await this.ctx.database.upsert("yesimbot.daily_schedules", [schedule], ["date"]); + await this.ctx.database.upsert("yesimbot.daily_schedules_v2", [schedule], ["instance", "date"]); } } diff --git a/packages/daily-planner/tests/scope-recall.spec.ts b/packages/daily-planner/tests/scope-recall.spec.ts new file mode 100644 index 000000000..918a13588 --- /dev/null +++ b/packages/daily-planner/tests/scope-recall.spec.ts @@ -0,0 +1,260 @@ +import { expect, it } from "vitest"; + +import { WorldStateService } from "../../core/src/world/service"; +import { DailyPlannerService } from "../src/service"; + +function fixture() { + const rows: any[] = []; + let allowed = true; + let directSearches = 0, + recalls = 0; + const db = { + get: async (table, query) => + rows.filter((r) => r.table === table && Object.entries(query).every(([k, v]) => r[k] === v)).map(({ table: _table, ...r }) => structuredClone(r)), + upsert: async (table, input) => { + for (const row of input) { + const old = rows.find((r) => r.table === table && r.date === row.date && r.instance === row.instance); + if (old) Object.assign(old, structuredClone(row)); + else rows.push({ table, ...structuredClone(row) }); + } + }, + }; + const make = (key: string, options: { chat?: () => Promise; realRecall?: boolean } = {}) => { + const bot = { + platform: "onebot", + selfId: "bot", + session: (e) => ({ ...e, platform: "onebot", selfId: "bot", channelId: e.channel.id, userId: e.user.id, isDirect: e.channel.type === 1 }), + }; + const ctx: any = { + scope: { key }, + get: () => undefined, + bots: [bot], + filter: () => true, + on() {}, + model: { extend() {} }, + logger: { info() {}, debug() {}, warn() {}, error() {} }, + database: db, + }; + let prompt = ""; + const snippets = new Map(); + ctx.yesimbot = { + memory: { getMemoryBlocksForRendering: () => [] }, + prompt: { + registerSnippet: (name, render) => { + snippets.set(name, render); + return () => snippets.delete(name); + }, + }, + model: { + useChatModel: () => ({ + chat: async (request) => { + prompt = JSON.stringify(request); + await options.chat?.(); + return { text: JSON.stringify([{ start: "08:00", end: "09:00", content: key }]) }; + }, + }), + getChatModel: () => ({ + chat: async (request) => { + prompt = JSON.stringify(request); + await options.chat?.(); + return { text: JSON.stringify([{ start: "08:00", end: "09:00", content: key }]) }; + }, + }), + }, + world: { + isChannelAllowed: () => allowed, + recallContext: async (session, options) => { + recalls++; + expect(session.channelId).toBe("hidden"); + expect(options.kind).toBe("l2"); + return { historyGeneration: 0, records: [{ id: "old", content: "PRIVATE-MEMORY" }] }; + }, + l2_manager: { + getHistoryGeneration: () => 0, + search: async () => { + directSearches++; + return [{ id: "old", content: "PRIVATE-MEMORY" }]; + }, + }, + }, + }; + if (options.realRecall) { + const world = Object.create(WorldStateService.prototype); + world.ctx = { + database: db, + filter: () => true, + parallel: async (_s, _event, _session, state) => { + state.l2_retrieved_memories = state.l2_retrieved_memories.filter((r) => !r.content.includes("CORRECTED")); + }, + }; + world.l2_manager = { waitForHistoryClear: async () => {}, getHistoryGeneration: () => 0 }; + world.isChannelAllowed = () => allowed; + ctx.yesimbot.world = world; + } + const config: any = { characterName: key, coreMemoryLabel: [], model: { providerName: "p", modelId: "m" }, memorySources: [] }; + return { service: new DailyPlannerService(ctx, config), ctx, config, prompt: () => prompt, snippets }; + }; + return { + make, + rows, + revoke: () => { + allowed = false; + }, + stats: () => ({ recalls, directSearches }), + }; +} +it("keeps independent schedules and never adopts unowned legacy date rows", async () => { + const f = fixture(), + a = f.make("a"), + b = f.make("b"); + const d = new Date(), + date = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; + f.rows.push({ table: "yesimbot.daily_schedules", date, segments: [{ start: "08:00", end: "09:00", content: "LEGACY" }] }); + await a.service.generateDailySchedule(); + expect((await b.service.getTodaysSchedule()).segments[0].content).toBe("b"); + expect((await a.service.getTodaysSchedule()).segments[0].content).toBe("a"); + expect(f.rows.some((r) => r.segments[0].content === "LEGACY")).toBe(true); +}); +it("defaults to core-only planning and revalidates explicitly allowed memory before reuse", async () => { + const f = fixture(), + a = f.make("a"); + await a.service.generateDailySchedule(); + expect(f.stats()).toEqual({ recalls: 0, directSearches: 0 }); + a.config.memorySources = [{ platform: "onebot", selfId: "bot", channelId: "hidden", userId: "alice", isDirect: false }]; + await a.service.generateDailySchedule(); + expect(a.prompt()).toContain("PRIVATE-MEMORY"); + f.revoke(); + await a.service.getTodaysSchedule(); + expect(a.prompt()).not.toContain("PRIVATE-MEMORY"); + expect(f.stats().directSearches).toBe(0); +}); + +it("rejects a model result if permission is revoked while generation is suspended", async () => { + const f = fixture(); + let release!: () => void, entered!: () => void; + const started = new Promise((r) => { + entered = r; + }), + gate = new Promise((r) => { + release = r; + }); + const a = f.make("a", { + chat: async () => { + entered(); + await gate; + }, + }); + a.config.memorySources = [{ platform: "onebot", selfId: "bot", channelId: "hidden", userId: "alice", isDirect: false }]; + const pending = a.service.generateDailySchedule(); + await started; + expect(a.prompt()).toContain("PRIVATE-MEMORY"); + f.revoke(); + release(); + await expect(pending).rejects.toThrow(/权限已改变/); + expect(f.rows).toEqual([]); +}); +it("uses the actual world recall authorization/filter chain and renders only current plans", async () => { + const f = fixture(), + a = f.make("a", { realRecall: true }); + a.config.memorySources = [{ platform: "onebot", selfId: "bot", channelId: "hidden", userId: "alice", isDirect: false }]; + // The raw recall selects only this authorized channel; correction filtering then + // removes the superseded summary before the real model request is constructed. + f.rows.push( + { table: "worldstate.l2_chunks", id: "safe", platform: "onebot", channelId: "hidden", content: "ALLOWED-CURRENT" }, + { table: "worldstate.l2_chunks", id: "wrong", platform: "onebot", channelId: "hidden", content: "CORRECTED-OLD" }, + { table: "worldstate.l2_chunks", id: "foreign", platform: "onebot", channelId: "other", content: "FOREIGN-PRIVATE" }, + ); + const render = a.snippets.get("agent.context.dailySchedule"); + expect(await render()).toContain("a"); + expect(a.prompt()).toContain("ALLOWED-CURRENT"); + expect(a.prompt()).not.toContain("CORRECTED-OLD"); + expect(a.prompt()).not.toContain("FOREIGN-PRIVATE"); + f.revoke(); + await render(); + expect(a.prompt()).not.toContain("ALLOWED-CURRENT"); +}); +it("isolates simultaneous generation and restores only the same stable instance", async () => { + const f = fixture(), + a = f.make("a"), + b = f.make("b"); + await Promise.all([a.service.generateDailySchedule(), b.service.generateDailySchedule()]); + const restarted = f.make("a"); + expect((await restarted.service.getTodaysSchedule()).segments[0].content).toBe("a"); + expect((await b.service.getTodaysSchedule()).segments[0].content).toBe("b"); + expect(f.rows).toHaveLength(2); +}); + +it("discards a generated plan when a source is corrected during the model call", async () => { + const f = fixture(); + let release!: () => void, entered!: () => void; + const started = new Promise((r) => { + entered = r; + }), + gate = new Promise((r) => { + release = r; + }); + const a = f.make("a", { + realRecall: true, + chat: async () => { + entered(); + await gate; + }, + }); + a.config.memorySources = [{ platform: "onebot", selfId: "bot", channelId: "hidden", userId: "alice", isDirect: false }]; + const row = { table: "worldstate.l2_chunks", id: "wrong", platform: "onebot", channelId: "hidden", content: "OLD-SOURCE" }; + f.rows.push(row); + const pending = a.service.generateDailySchedule(); + await started; + row.content = "CORRECTED-SOURCE"; + release(); + await expect(pending).rejects.toThrow(/权限已改变/); + expect(f.rows.filter((r) => r.table === "yesimbot.daily_schedules_v2")).toEqual([]); +}); + +for (const change of ["world permission", "extension permission", "source configuration", "history generation", "session binding"]) { + it(`rejects the cached plan when earlier source ${change} changes while a later source is suspended`, async () => { + const f = fixture(), + a = f.make("a"); + a.config.memorySources = ["A", "B"].map((channelId) => ({ platform: "onebot", selfId: "bot", channelId, userId: "alice", isDirect: false })); + let allowedA = true, + extensionAllowedA = true, + generationA = 0, + suspended = false; + let release!: () => void, entered!: () => void, sourceA: any; + const reached = new Promise((r) => { + entered = r; + }), + gate = new Promise((r) => { + release = r; + }); + a.ctx.filter = (session) => session.channelId !== "A" || extensionAllowedA; + a.ctx.yesimbot.world = { + isChannelAllowed: (session) => session.channelId !== "A" || allowedA, + l2_manager: { getHistoryGeneration: (target) => (target.channelId === "A" ? generationA : 0) }, + recallContext: async (session) => { + if (session.channelId === "A") sourceA = session; + if (session.channelId === "B" && suspended) { + entered(); + await gate; + } + return { + historyGeneration: session.channelId === "A" ? generationA : 0, + records: [{ id: session.channelId, content: `PRIVATE-${session.channelId}` }], + }; + }, + }; + await a.service.generateDailySchedule(); + const saved = structuredClone(f.rows); + suspended = true; + const pending = a.snippets.get("agent.context.dailySchedule")(); + await reached; + if (change === "world permission") allowedA = false; + if (change === "extension permission") extensionAllowedA = false; + if (change === "source configuration") a.config.memorySources = a.config.memorySources.slice(1); + if (change === "history generation") generationA++; + if (change === "session binding") sourceA.userId = "other"; + release(); + await expect(pending).rejects.toThrow(/日程来源.*改变/); + expect(f.rows).toEqual(saved); + }); +} diff --git a/packages/durable-tasks/src/index.ts b/packages/durable-tasks/src/index.ts index 6d9285bd9..76701479b 100644 --- a/packages/durable-tasks/src/index.ts +++ b/packages/durable-tasks/src/index.ts @@ -18,7 +18,7 @@ export const Config: Schema = Schema.object({ }); interface ToolRegistry { capabilities?: { trustedToolSession?: number }; - registerTool(tool: unknown): void | (() => void); + registerTool(tool: unknown, ownerContext?: Context): void | (() => void); } interface Services { yesimbot: { @@ -113,7 +113,7 @@ export function apply(ctx: Context, config: Config) { for (const remove of removers) remove(); }); const register = (tool: { name: string } & Record) => { - const remove = tools.registerTool(tool); + const remove = tools.registerTool(tool, ctx); if (typeof remove !== "function") throw new Error("持久提醒需要支持按注册实例注销工具的 core"); removers.push(remove); }; diff --git a/packages/durable-tasks/tests/runtime.spec.ts b/packages/durable-tasks/tests/runtime.spec.ts index 1a05975d2..76e9dd944 100644 --- a/packages/durable-tasks/tests/runtime.spec.ts +++ b/packages/durable-tasks/tests/runtime.spec.ts @@ -6,6 +6,8 @@ vi.mock("koishi-plugin-yesimbot", async (importOriginal) => ({ ...(await importOriginal()), getInstanceScope: (ctx: Context, _warn: unknown, options?: unknown) => `${(ctx.root as any).scopePrefix ?? ""}${options ? "plugin-scope" : "core-scope"}`, })); +import { StimulusScheduler } from "../../core/src/agent/scheduler"; +import { loggingStub } from "../../core/tests/helpers/yesimbot"; import { stubYesImBot } from "../../core/tests/helpers/yesimbot"; import * as plugin from "../src/index"; import { TABLE, TaskStore, registerModels, taskOwner } from "../src/store"; @@ -124,9 +126,28 @@ it("runs a real due reminder through database, restored bot session, event write recordSystemEvent, }; ctx.set("yesimbot", stubYesImBot({ tool, world })); - const stimuli: any[] = []; + const stimuli: any[] = [], + executed: string[] = []; + let release!: () => void; + const busy = new Promise((resolve) => { + release = resolve; + }); + const scheduler = new StimulusScheduler( + ctx, + { debounceMs: 0, newMessageStrategy: "skip" } as any, + async (stimulus) => { + executed.push(stimulus.type); + if (stimulus.type === "user_message") await busy; + }, + loggingStub(), + ); + t.onTestFinished(() => { + release(); + scheduler.dispose(); + }); ctx.on("agent/stimulus" as any, (...args: any[]) => { stimuli.push(args); + scheduler.schedule(args[0]); }); const fork = ctx.plugin(plugin, { enabled: true, pollIntervalSeconds: 1 }); t.onTestFinished(async () => { @@ -138,6 +159,8 @@ it("runs a real due reminder through database, restored bot session, event write const bot = ctx.bots[0]; bot.getChannel = async () => ({ id: "g", type: 0 }); const session = bot.session({ user: { id: "u" }, channel: { id: "g", type: 0 }, guild: { id: "guild" } }); + scheduler.schedule({ type: "user_message", channelCid: "mock:g", session, payload: {} } as any); + await vi.waitFor(() => expect(executed).toEqual(["user_message"])); const result = await tools.get("schedule_reminder").execute({ session, deadline: Date.now() + 10, content: "提醒正文", idempotency_key: "delivery" }); expect(result.status).toBe("success"); await vi.waitFor( @@ -150,6 +173,9 @@ it("runs a real due reminder through database, restored bot session, event write expect(recordSystemEvent.mock.calls[0][0]).toMatchObject({ message: "提醒正文", eventScope: "channel", botKey: JSON.stringify(["mock", bot.selfId]) }); expect(stimuli).toHaveLength(1); expect(stimuli[0]).toEqual([expect.objectContaining({ type: "scheduled_task", channelCid: "mock:g" }), "world"]); + expect(executed).toEqual(["user_message"]); + release(); + await vi.waitFor(() => expect(executed).toEqual(["user_message", "scheduled_task"])); }); it("does not let a session sharing a raw channel id cancel reminders from another guild or chat type", async (t) => { diff --git a/packages/favor/src/index.ts b/packages/favor/src/index.ts index ab867e034..b4dcb7ffb 100644 --- a/packages/favor/src/index.ts +++ b/packages/favor/src/index.ts @@ -112,7 +112,7 @@ export default class FavorExtension { if (this.disposed) return ""; const stageDescription = this._getFavorStage(favorEntry.amount); return `## 好感度设定 -当前你与用户 ${session.username} (ID: ${session.userId}) 的好感度为 ${favorEntry.amount},关系阶段是:${stageDescription}。 +当前你与用户 ${session.username} (ID: ${session.userId}) 的好感度为 ${favorEntry.amount}(最大值 ${this.config.maxFavor}),关系阶段是:${stageDescription}。 请时刻参考这些信息,并根据当前的好感度和关系阶段,以合适的语气和内容与用户互动。`; }), ); @@ -146,6 +146,7 @@ export default class FavorExtension { @Tool({ name: "add_favor", + modelReplacement: "favor", description: "为指定用户增加或减少好感度", parameters: withInnerThoughts({ user_id: Schema.string().required().description("要增加好感度的用户 ID"), @@ -176,7 +177,8 @@ export default class FavorExtension { @Tool({ name: "set_favor", - description: "为指定用户直接设置好感度。上限为 {{ roleplay.config.maxFavor }}。", + modelReplacement: "favor", + description: "为指定用户直接设置好感度,结果限制在配置的最大好感度以内。", parameters: withInnerThoughts({ user_id: Schema.string().required().description("要设置好感度的用户 ID"), amount: Schema.number().required().description("要设置的好感度目标值。"), @@ -197,6 +199,22 @@ export default class FavorExtension { } } + @Tool({ + name: "favor", + description: "调整或设置指定用户的好感度。action=adjust 时 amount 为变化量,action=set 时 amount 为目标值。", + supersedes: ["add_favor", "set_favor"], + actionAliases: { adjust: "add_favor", set: "set_favor" }, + parameters: withInnerThoughts({ + action: Schema.union(["adjust", "set"]).required(), + user_id: Schema.string().required().description("用户 ID"), + amount: Schema.number().required().description("adjust 时为变化量(可为负);set 时为目标值"), + }), + isSupported: (session) => session.isDirect, + }) + async favor(_args: Infer<{ action: "adjust" | "set"; user_id: string; amount: number }>) { + return Failed("请通过工具服务调用好感度操作"); + } + // --- 私有辅助方法 --- /** diff --git a/packages/mcp/src/MCPManager.ts b/packages/mcp/src/MCPManager.ts index 233c318f6..d3606f218 100644 --- a/packages/mcp/src/MCPManager.ts +++ b/packages/mcp/src/MCPManager.ts @@ -248,11 +248,11 @@ export class MCPManager { parameters: convertJsonSchemaToSchemastery(tool.inputSchema), execute: async (args: Infer) => { - const { session: _session, ...cleanArgs } = args; + const { session: _session, toolContext: _toolContext, ...cleanArgs } = args; return await this.executeTool(client, tool.name, cleanArgs); }, }; - const unregister = this.toolService.registerTool(definition); + const unregister = this.toolService.registerTool(definition, this.ctx); this.toolDisposers.push( typeof unregister === "function" ? unregister diff --git a/packages/mcp/tests/schema.spec.ts b/packages/mcp/tests/schema.spec.ts index 4c9eb5304..103ea46b4 100644 --- a/packages/mcp/tests/schema.spec.ts +++ b/packages/mcp/tests/schema.spec.ts @@ -1,11 +1,13 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; import { Server } from "@modelcontextprotocol/sdk/server/index.js"; -import { ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js"; +import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js"; import type { Schema } from "koishi"; import type { ToolDefinition } from "koishi-plugin-yesimbot"; import { expect, it, type TestContext } from "vitest"; +import { ToolService } from "../../core/src/extension/service"; +import { loggingStub } from "../../core/tests/helpers/yesimbot"; import { MCPManager } from "../src/MCPManager"; async function registeredParameters(t: TestContext, property: { type: "integer" | "number"; minimum?: number; maximum?: number }): Promise { @@ -57,3 +59,39 @@ it("preserves fractional MCP number parameters and their inclusive bounds", asyn for (const value of [0.5, 1.25, 2.5]) expect(parameters({ value })).toEqual({ value }); for (const value of ["1.25", 0.25, 2.75]) expect(() => parameters({ value })).toThrow(/expected number/); }); + +it("keeps internal tool execution context out of real MCP protocol calls", async (t) => { + const server = new Server({ name: "boundary", version: "1" }, { capabilities: { tools: {} } }); + const client = new Client({ name: "boundary", version: "1" }); + const [local, remote] = InMemoryTransport.createLinkedPair(); + let received: unknown; + server.setRequestHandler(ListToolsRequestSchema, async () => ({ + tools: [{ name: "echo", inputSchema: { type: "object", properties: { value: { type: "string" } }, required: ["value"] } }], + })); + server.setRequestHandler(CallToolRequestSchema, async (request) => { + received = request.params.arguments; + return { content: [{ type: "text", text: "ok" }] }; + }); + const ctx = { filter: () => true } as any; + const tools = new ToolService(ctx, { advanced: { timeout: 1000 } } as any, { world: {}, logging: loggingStub() } as any); + const manager = new MCPManager(ctx, { debug() {}, error() {}, success() {}, info() {}, warn() {} } as any, {} as any, tools, { + timeout: 1000, + mcpServers: {}, + }); + t.onTestFinished(async () => { + await manager.cleanup(); + await tools.stop(); + await client.close(); + await server.close(); + }); + await server.connect(remote); + await client.connect(local); + await (manager as any).registerTools(client, "memory"); + const result = await tools.invoke("echo", { value: "business", toolContext: { forged: true }, session: "forged" }, undefined, { + requestId: "private-request", + signal: new AbortController().signal, + reportProgress() {}, + }); + expect(result.status).toBe("success"); + expect(received).toEqual({ value: "business" }); +}); diff --git a/packages/mcp/tests/transport.spec.ts b/packages/mcp/tests/transport.spec.ts index 5584858a5..20b7f2009 100644 --- a/packages/mcp/tests/transport.spec.ts +++ b/packages/mcp/tests/transport.spec.ts @@ -51,7 +51,7 @@ it.each(["http-sse", "sse-alias", "streamable"])("connects and discovers tools o await new Promise((resolve) => server.close(() => resolve())); }); await manager.connectServers(); - expect(registerTool).toHaveBeenCalledWith(expect.objectContaining({ name: "remote" })); + expect(registerTool).toHaveBeenCalledWith(expect.objectContaining({ name: "remote" }), expect.anything()); expect(requests).toContain(mode === "streamable" ? "POST /sse" : "GET /sse"); }); diff --git a/packages/onebot-directory/src/index.ts b/packages/onebot-directory/src/index.ts index bb1efaca0..c97dade7a 100644 --- a/packages/onebot-directory/src/index.ts +++ b/packages/onebot-directory/src/index.ts @@ -1,4 +1,4 @@ -import { Context, Schema, h, type Session } from "koishi"; +import { Context, Schema, h, type Command, type Session } from "koishi"; import { DirectoryStore, registerModels, type OneBotClient, type Query } from "./store"; @@ -51,6 +51,14 @@ function onebot(session: Session) { return session.bot as unknown as OneBotClient; } +const addQueryOptions = (command: Command) => + command + .option("query", "-q 按账号、昵称或群名模糊搜索") + .option("offset", "-o 跳过条数") + .option("limit", "-n 返回条数(默认 50)") + .option("all", "--all 返回完整名单") + .option("refresh", "-r 强制刷新"); + export function apply(ctx: Context, config: Config) { if (!config.enabled) return; registerModels(ctx); @@ -165,46 +173,50 @@ export function apply(ctx: Context, config: Config) { modelUsage.clear(); }); - ctx.command("onebot.contacts", "查询或刷新 OneBot 好友和群成员名单", { authority: 3 }); - function command(kind: Query["kind"]) { - return ctx - .command(`onebot.contacts.${kind}`, kind === "friends" ? "查询好友名单" : kind === "groups" ? "查询已加入的群" : "查询群成员名单", { authority: 3 }) - .option("groupId", "-g 指定群号") - .option("query", "-q 按账号、昵称或群名模糊搜索") - .option("offset", "-o 跳过人数") - .option("limit", "-n 返回人数(默认 50)") - .option("all", "--all 返回完整名单") - .option("refresh", "-r 强制刷新") - .action(async ({ session, options }) => { - if (!session || !options) return h.text("会话不可用"); - try { - if (kind === "groups" && !session.isDirect) throw new Error("群列表只能在管理员私聊中查询"); - const result = await store.query(onebot(session), { - kind, - groupId: groupId(session, options.groupId), - query: options.query, - offset: options.offset, - limit: options.limit, - all: options.all, - refresh: options.refresh, - }); - const unit = kind === "groups" ? "个群" : "人"; - const header = `${kind === "friends" ? "好友" : kind === "groups" ? "已加入的群" : `群 ${result.groupId} 成员`}:${result.total} ${unit};本次 ${result.returned} ${unit};缓存于 ${new Date(result.fetchedAt).toLocaleString()}(来源机器人 ${result.sourceBotId})`; - const lines = result.entries.map( - (item, i) => - `${result.offset + i + 1}. ${item.userId} ${item.card || item.remark || item.nickname}${item.role ? ` (${item.role})` : ""}`, - ); - if (!lines.length) return h.text(header); - // Avoid a single huge platform message when --all is used. - for (let i = 0; i < lines.length; i += 40) { - await session.send(h.text(`${i === 0 ? header + "\n" : ""}${lines.slice(i, i + 40).join("\n")}`)); - } - } catch (error) { - return h.text(`查询 OneBot 名单失败:${String(error)}`); - } + async function queryContacts(session: Session | undefined, kind: Query["kind"], options: Omit = {}) { + if (!session) return h.text("会话不可用"); + try { + if (kind === "groups" && !session.isDirect) throw new Error("群列表只能在管理员私聊中查询"); + const result = await store.query(onebot(session), { + kind, + groupId: groupId(session, options.groupId), + query: options.query, + offset: options.offset, + limit: options.limit, + all: options.all, + refresh: options.refresh, }); + const unit = kind === "groups" ? "个群" : "人"; + const header = `${kind === "friends" ? "好友" : kind === "groups" ? "已加入的群" : `群 ${result.groupId} 成员`}:${result.total} ${unit};本次 ${result.returned} ${unit};缓存于 ${new Date(result.fetchedAt).toLocaleString()}(来源机器人 ${result.sourceBotId})`; + const lines = result.entries.map( + (item, i) => `${result.offset + i + 1}. ${item.userId} ${item.card || item.remark || item.nickname}${item.role ? ` (${item.role})` : ""}`, + ); + if (!lines.length) return h.text(header); + // Avoid a single huge platform message when --all is used. + for (let i = 0; i < lines.length; i += 40) { + await session.send(h.text(`${i === 0 ? header + "\n" : ""}${lines.slice(i, i + 40).join("\n")}`)); + } + } catch (error) { + return h.text(`查询 OneBot 名单失败:${String(error)}`); + } + } + + addQueryOptions(ctx.command("onebot.contacts [kind:string]", "查询或刷新 OneBot 好友、群列表和群成员名单", { authority: 3 })) + .option("groupId", "-g 指定群号,仅用于 members") + .action(({ session, options }, kind) => { + if (kind !== "friends" && kind !== "groups" && kind !== "members") + return h.text("请指定名单类型:friends 好友、groups 已加入的群(管理员私聊)、members 群成员。群成员可用 -g 指定群号。"); + if (options?.groupId !== undefined && kind !== "members") return h.text("-g 仅用于查询群成员(members)。"); + return queryContacts(session, kind, options); + }); + + for (const [kind, description] of [ + ["friends", "查询好友名单"], + ["members", "查询群成员名单"], + ["groups", "查询已加入的群"], + ] as const) { + addQueryOptions(ctx.command(`onebot.contacts.${kind}`, description, { authority: 3 })) + .option("groupId", kind === "members" ? "-g 指定群号" : "-g 旧参数,仅 members 使用群号") + .action(({ session, options }) => queryContacts(session, kind, options)); } - command("friends"); - command("members"); - command("groups"); } diff --git a/packages/onebot-directory/tests/tool.spec.ts b/packages/onebot-directory/tests/tool.spec.ts index f579a6278..a51bc1171 100644 --- a/packages/onebot-directory/tests/tool.spec.ts +++ b/packages/onebot-directory/tests/tool.spec.ts @@ -206,3 +206,16 @@ test("empty directory headers and adapter errors return escaped Koishi text", as true, ); }); + +test("combined contacts command preserves the legacy member query and group-list privacy", async (t) => { + const { session, commands } = await setup(t); + session.bot.internal.getGroupMemberList = async () => [{ user_id: 42, nickname: "Member" }]; + const sent = []; + session.send = async (message) => sent.push(String(message)); + const query = commands["onebot.contacts [kind:string]"]; + await query({ session, options: {} }, "members"); + assert.equal(sent.length, 1); + assert.match(sent[0], /42 Member/); + assert.match(String(await query({ session, options: {} }, "groups")), /管理员私聊/); + assert.match(String(await query({ session, options: { groupId: "g" } }, "friends")), /群成员/); +}); diff --git a/packages/person-memory/README.md b/packages/person-memory/README.md index daf191386..0118fd14a 100644 --- a/packages/person-memory/README.md +++ b/packages/person-memory/README.md @@ -200,3 +200,11 @@ people.resume - 卸载停止后台任务并移除工具/注入,数据库内容保留。候选/画像内容会发往管理员配置的模型服务;开启后台模型组或 `auto` 前,应了解本群的记忆使用约定。 本插件不把身份确信度接到 Jev 回复概率或管理权限上。之后可按需要增加候选排序、其他检索后端或人工确认入口。 + +### 清理所有会话 + +与支持人物清理生命周期的核心配套使用时,`history.clear -a all` 会先停止本实例的人物采集与总结,取消排队、重试和在途总结,清除所属总结任务的输入及输出缓存,并删除已登记属于本扩展的画像、来源、候选、审计和共同经历。清理完成后,新消息可以重新建立资料;旧请求的迟到结果不会恢复旧资料。 + +同一范围若还被其他人物实例登记使用,会保留该范围,回执会说明保留数量;无法证明实例归属的旧资料也会保留。相同 `memoryDomain` 仍表示共享人物范围,并不授权一个实例直接删除其他实例正在使用的资料。请依据清理回执判断实际范围,不能把“核心聊天历史已清理”理解成无归属旧资料也已删除。 + +后台总结保持独立的超时配置。画像结构校验失败时,会在有限重试内沿用原写作规则与证据,向模型反馈具体结构错误;不把无效输出反复当成可提交的缓存候选。`recent.topics` 最多五项,其他字符串列表最多二十项,未知列表使用空数组。 diff --git a/packages/person-memory/package.json b/packages/person-memory/package.json index a86967880..352211506 100644 --- a/packages/person-memory/package.json +++ b/packages/person-memory/package.json @@ -18,7 +18,9 @@ "devDependencies": { "@koishijs/plugin-database-memory": "^3.7.0", "@koishijs/plugin-mock": "^2.6.6", - "koishi": "^4.18.7" + "@minatojs/driver-sqlite": "^4.7.0", + "koishi": "^4.18.7", + "minato": "^3.7.0" }, "peerDependencies": { "koishi": "^4.18.7", diff --git a/packages/person-memory/src/command-help.ts b/packages/person-memory/src/command-help.ts index 997861d4c..0e197cb3b 100644 --- a/packages/person-memory/src/command-help.ts +++ b/packages/person-memory/src/command-help.ts @@ -1,5 +1,15 @@ import type { Command } from "koishi"; +import type { ProfileDocument } from "./profile"; + +export function parsePeopleProfile(profile: string, format = "text"): string | ProfileDocument { + if (format === "text") return profile; + if (format !== "json") throw new Error("画像格式应为 text 或 json"); + const document = JSON.parse(profile); + if (!document || typeof document !== "object" || Array.isArray(document)) throw new Error("请提供完整结构画像 JSON 对象"); + return document; +} + /** Shared guidance for the scene and shared-domain command registrations. */ export function describePeopleCommand(command: Command, declaration: string, shared: boolean): Command { const name = declaration.split(" ")[0]; @@ -46,6 +56,10 @@ export function describePeopleCommand(command: Command, declaration: string, sha notes.push("审计编号来自 people.history;不填 history 的编号时分页查看记录。--account 筛选账号,--person 筛选人物 UUID。"); if (name === "people.archive") notes.push("不填 revision 仅预览。执行前先查询当前画像版本,再用 people.archive 账号ID 当前版本号确认;不能照抄其他档案的版本号。"); + if (name === "people.edit") { + command.option("format", "--format 画像格式,默认 text,可选 json"); + notes.push("修改结构画像时,请将 --format json 放在画像正文前,再提供完整 JSON 对象。旧命令 people.edit_json 仍可使用。"); + } command.usage(notes.join("\n")); command.example(name === "people" ? "people.list" : example); if (name === "people") command.example("people.show 123456"); diff --git a/packages/person-memory/src/history-reset.ts b/packages/person-memory/src/history-reset.ts new file mode 100644 index 000000000..7a8fd4677 --- /dev/null +++ b/packages/person-memory/src/history-reset.ts @@ -0,0 +1,58 @@ +import type { Context } from "koishi"; +import * as core from "koishi-plugin-yesimbot"; + +import type { PersonStore } from "./store"; +import type { SummaryWorker } from "./worker"; + +type ResetScope = { type: "all" | "private" | "guild" } | { platform: string; channelId: string }; +type Preparation = { ready: Promise; release: () => void; report: () => string | undefined }; +const runtime = core as typeof core & { + registerHistoryResetParticipant?: (ctx: Context, participant: { prepare(scope: ResetScope): Preparation | void }) => () => void; +}; + +/** Fence the owning extension synchronously before draining asynchronous work. */ +export class PersonHistoryReset { + private depth = 0; + private generation = 0; + private pending = new Set>(); + constructor(private ctx: Context) {} + available = () => this.depth === 0; + epoch = () => this.generation; + domain = () => JSON.stringify([runtime.getInstanceScope(this.ctx), runtime.getInstanceScope(this.ctx, undefined, { owner: this.ctx })]); + track(promise: Promise): Promise { + this.pending.add(promise); + void promise.finally(() => this.pending.delete(promise)).catch(() => {}); + return promise; + } + install(store: PersonStore, worker: SummaryWorker, _scopeOf: (session: any) => string, _shared: boolean, clearLocal: () => void) { + return runtime.registerHistoryResetParticipant?.(this.ctx, { + prepare: (scope) => { + if (!("type" in scope) || scope.type !== "all") return; + this.depth++; + this.generation++; + clearLocal(); + const resetting = worker.reset(); + let report: string | undefined; + const ready = (async () => { + await Promise.allSettled(this.pending); + const queueScopes = await resetting; + // Routing and bot IDs do not prove ownership of old opaque rows. + // Only persistent ownership or this worker's domain queue may purge. + await store.purgeOwned(queueScopes); + const summary = store.purgeReport(); + report = `人物资料:清理 ${summary.cleared} 个已证明自有范围;保留 ${summary.retained} 个存在其他所有者的范围。其他实例与无法证明归属的旧资料未删除;总结任务及缓存已取消。`; + })(); + return { + ready, + report: () => report, + release: () => { + this.depth--; + if (!this.depth) worker.resume(); + }, + }; + }, + }); + } +} +export const readPersonAction = (params: Record) => + ["read", "read_many", "list", "search", "history", "claims", "claim_evidence"].includes(String(params.action)); diff --git a/packages/person-memory/src/index.ts b/packages/person-memory/src/index.ts index 17ef65716..f6455b524 100644 --- a/packages/person-memory/src/index.ts +++ b/packages/person-memory/src/index.ts @@ -2,17 +2,21 @@ import { Context, Schema, h, type Session } from "koishi"; import * as core from "koishi-plugin-yesimbot"; import { PeopleCatalog } from "./catalog"; -import { claimParameters, executeClaimTool, visibleClaims } from "./claim-tools"; +import { executeClaimTool, visibleClaims } from "./claim-tools"; import type { ClaimChange } from "./claims"; -import { describePeopleCommand } from "./command-help"; +import { describePeopleCommand, parsePeopleProfile } from "./command-help"; import { identityWarning, renderPeople } from "./context"; +import { PersonHistoryReset, readPersonAction } from "./history-reset"; +import { personToolContract } from "./person-tool-schema"; import type { ProfileDocument } from "./profile"; import { DEFAULT_PROFILE_SYSTEM_PROMPT, mainProfilePolicy } from "./profile-prompt"; -import { catalogParameters, catalogProfile, catalogRequest, profileInputSchema, visibleProfile, visibleLegacyProfile } from "./profile-tools"; +import { catalogProfile, catalogRequest, visibleProfile, visibleLegacyProfile } from "./profile-tools"; import { applySharedMemory } from "./shared-runtime"; +import { personSnapshotGuard } from "./snapshot-guard"; import { summarySourceAllowed } from "./source-policy"; import { PersonStore, registerModels, sceneKey, type Audit, type LinkProposal, type Mode, type Person, type Proposal, type SceneInput } from "./store"; import { registerSummaryQueueModels, SummaryQueue } from "./summary-queue"; +import { personMemoryFailure as Failed } from "./tool-result"; import { SummaryWorker, summaryResponseText, type SummaryModel, type WorkerConfig } from "./worker"; declare module "koishi" { @@ -136,7 +140,7 @@ export interface Dependencies { }; } const Success = (result: unknown) => ({ status: "success", result }); -const Failed = (error: unknown) => ({ status: "error", error: { name: "PersonMemoryError", message: error instanceof Error ? error.message : String(error) } }); + const key = (session: Session) => sceneKey(session as unknown as SceneInput); function profileView(p: Person) { return { @@ -243,12 +247,13 @@ export function apply(ctx: Context, config: Config) { } registerModels(ctx); if (config.modelGroup) registerSummaryQueueModels(ctx); + const reset = new PersonHistoryReset(ctx); const logger = ctx.logger(name), - store = new PersonStore(ctx.database, config.mode); + store = new PersonStore(ctx.database, config.mode, { domain: reset.domain, active: () => active && reset.available() }); let active = true; const modes = new Map(), generations = new Map(); - const allowed = (session: Session) => active && ctx.filter(session) && deps.yesimbot.world.isChannelAllowed(session); + const allowed = (session: Session) => active && reset.available() && ctx.filter(session) && deps.yesimbot.world.isChannelAllowed(session); let model: SummaryModel | undefined; if (config.modelGroup) model = async (messages, signal, attribution) => { @@ -277,6 +282,10 @@ export function apply(ctx: Context, config: Config) { sourceAllowed: (scope, _userId, evidence) => summarySourceAllowed(ctx, evidence, scope, false, allowed, key), }; const worker = new SummaryWorker(store, model, workerConfig, (error) => logger.warn(`后台人物总结未接受:${String(error)}`)); + reset.install(store, worker, key, false, () => { + modes.clear(); + generations.clear(); + }); if (model) { const getScope = (core as unknown as { getPersistentInstanceScope?: (ctx: Context, options?: { owner?: Context }) => string }) .getPersistentInstanceScope; @@ -309,86 +318,69 @@ export function apply(ctx: Context, config: Config) { : ""; }); - ctx.on("yesimbot/before-user-stimulus", async (session: Session) => { - if ( - !allowed(session) || - !session.userId || - session.author?.isBot || - session.userId === session.bot.selfId || - (session as any).__commandHandled || - !session.messageId || - !session.content?.trim() - ) - return; - try { - const scope = key(session); - const mode = (await store.read(scope)).settings.mode; - modes.set(scope, mode); - if (mode === "off") return; - const generation = generations.get(scope) ?? 0, - current = () => active && generation === (generations.get(scope) ?? 0) && modes.get(scope) !== "off"; - const identity = await store.recognize(scope, session.userId, session.author?.nick || session.author?.name || session.userId, current); - if (!active) return; - await store.capture( - scope, - { - id: session.messageId, - userId: session.userId, - name: session.author?.nick || session.author?.name || session.userId, - text: typeof core.normalizeOneBotMessageContent === "function" ? await core.normalizeOneBotMessageContent(session) : session.content, - timestamp: Number(session.timestamp) || Date.now(), - provenance: { - guildId: session.guildId, - platform: session.platform, - selfId: session.selfId || session.bot.selfId, - channelId: session.channelId!, - messageId: session.messageId, - personId: identity.person.id, - accountRevision: identity.account.bindingRevision ?? 0, - scene: scope, - }, - }, - current, - ); - if (active) await worker.observe(scope, session.userId); - } catch (error) { - logger.warn(`人物资料记录失败:${String(error)}`); - } - }); + ctx.on("yesimbot/before-user-stimulus", (session: Session) => + reset.track( + (async () => { + const resetEpoch = reset.epoch(); + if ( + !allowed(session) || + !session.userId || + session.author?.isBot || + session.userId === session.bot.selfId || + (session as any).__commandHandled || + !session.messageId || + !session.content?.trim() + ) + return; + try { + const scope = key(session); + const mode = (await store.read(scope)).settings.mode; + modes.set(scope, mode); + if (mode === "off") return; + const generation = generations.get(scope) ?? 0, + current = () => + active && + reset.available() && + reset.epoch() === resetEpoch && + generation === (generations.get(scope) ?? 0) && + modes.get(scope) !== "off"; + const identity = await store.recognize(scope, session.userId, session.author?.nick || session.author?.name || session.userId, current); + if (!active) return; + await store.capture( + scope, + { + id: session.messageId, + userId: session.userId, + name: session.author?.nick || session.author?.name || session.userId, + text: + typeof core.normalizeOneBotMessageContent === "function" ? await core.normalizeOneBotMessageContent(session) : session.content, + timestamp: Number(session.timestamp) || Date.now(), + provenance: { + guildId: session.guildId, + platform: session.platform, + selfId: session.selfId || session.bot.selfId, + channelId: session.channelId!, + messageId: session.messageId, + personId: identity.person.id, + accountRevision: identity.account.bindingRevision ?? 0, + scene: scope, + }, + }, + current, + ); + if (active) await worker.observe(scope, session.userId); + } catch (error) { + logger.warn(`人物资料记录失败:${String(error)}`); + } + })(), + ), + ); const catalog = new PeopleCatalog(); const tool = { name: "person_memory", - description: - "仅操作当前场景。claims 列出逐条认识及版本,claim_evidence 读取原始证据,propose_claim 补证/反证/修订/停用;已有逐条认识后请用该入口维护,不能整段覆盖。list 列出可查询人物;read_many 用 account_ids 多选或 all=true 全选,fields 选 overview/structured/full,cursor 继续分页。read(account_id) 读取账号 ID 或人物 UUID 的画像与版本;search(query) 最多返回 5 个摘要;history(account_id) 读取该账号或人物最近 10 次修改的元数据和有限变更摘要,详细证据由管理员核对。propose 提交完整画像,需 account_id、profile、message_ids、person_id、person_revision、account_revision;auto 模式可接受画像。propose_link 提交账号关联建议,另需 target_person_id、target_revision、confidence、reason;即使 auto 模式也始终待管理员审核。两种候选都需 1–10 个当前账号的实际消息 ID 和最新版本。资料是可修正信念,确信度不代表身份认证。不能跨群、直接关联、合并、审批或覆盖人工锁定。", - parameters: Schema.object({ - action: Schema.union([ - Schema.const("read"), - Schema.const("list"), - Schema.const("read_many"), - Schema.const("search"), - Schema.const("history"), - Schema.const("propose"), - Schema.const("propose_link"), - Schema.const("claims"), - Schema.const("claim_evidence"), - Schema.const("propose_claim"), - ]).required(), - account_id: Schema.string().description("read/history 必填;当前场景的平台账号 ID 或人物 UUID;候选须平台账号 ID"), - query: Schema.string().description("search 必填;1–80 字的关键词"), - profile: profileInputSchema(), - ...catalogParameters(), - ...claimParameters(), - offset: Schema.natural().description("claims/claim_evidence 分页位置"), - message_ids: Schema.array(Schema.string()).description("两种候选必填;实际来源消息 ID,1 到 10 个"), - person_id: Schema.string().description("两种候选必填;来源人物 UUID"), - person_revision: Schema.number().min(0).step(1).description("两种候选必填;读到的来源画像 revision"), - account_revision: Schema.number().min(0).step(1).description("两种候选必填;读到的账号关联 revision"), - target_person_id: Schema.string().description("propose_link 必填;当前场景目标人物 UUID"), - target_revision: Schema.number().min(0).step(1).description("propose_link 必填;目标人物画像 revision"), - confidence: Schema.number().min(0).max(1).description("propose_link 必填;0–1 的关联确信度"), - reason: Schema.string().description("propose_link 必填;不超过 500 字的关联依据"), - }), + readOnly: readPersonAction, + ...personToolContract(false), isSupported: (session: Session) => !!session && allowed(session) && (modes.get(key(session)) ?? config.mode) !== "off", execute: async (args: { session: Session; @@ -585,7 +577,14 @@ export function apply(ctx: Context, config: Config) { } }, }; - const removeTool = deps.yesimbot.tool.registerTool(tool); + const guardSnapshot = personSnapshotGuard(ctx, async (session: Session) => { + if (!allowed(session)) throw new Error("当前场景未启用人物记忆"); + const scope = key(session), + state = await store.read(scope); + if (state.settings.mode === "off") throw new Error("人物记忆已关闭"); + return [reset.epoch(), scope, state.people, state.accounts, state.settings.mode]; + }); + const removeTool = deps.yesimbot.tool.registerTool(guardSnapshot({ ...tool, execute: (args: any) => reset.track(tool.execute(args)) })); ctx.on("dispose", async () => { active = false; const stopped = worker.stop(); @@ -607,7 +606,7 @@ export function apply(ctx: Context, config: Config) { const authority = (session.user as { authority?: number } | undefined)?.authority ?? (await session.observeUser<"authority">(["authority"])).authority; if (authority < 3) throw new Error("仅管理员可以管理人物记忆(authority ≥ 3)"); - const result = await action(key(session), `admin:${session.platform}:${session.userId}`, args, session, options || {}); + const result = await reset.track(action(key(session), `admin:${session.platform}:${session.userId}`, args, session, options || {})); if (result.length <= 1800) return h.escape(result); for (let start = 0; start < Math.min(result.length, 36000); start += 1800) await session.send(h.escape(result.slice(start, start + 1800))); return result.length > 36000 ? "输出已截断,请缩小查询范围。" : ""; @@ -663,16 +662,16 @@ export function apply(ctx: Context, config: Config) { "修改心中称呼(不改平台昵称)", async (scope, actor, [ref, name]) => `已改称呼:${(await store.rename(scope, ref, name, actor)).name}`, ); - command("people.edit_json ", "人工纠正完整结构画像(JSON)", async (scope, actor, [ref, profile]) => { - const document = JSON.parse(profile); - if (!document || typeof document !== "object" || Array.isArray(document)) throw new Error("请提供完整结构画像 JSON 对象"); - const person = await store.setProfile(scope, ref, document, actor); - return show(person); - }); + command("people.edit_json ", "人工纠正完整结构画像(也可用 people.edit --format json)", async (scope, actor, [ref, profile]) => + show(await store.setProfile(scope, ref, parsePeopleProfile(profile, "json"), actor)), + ); command( "people.edit ", "人工替换完整画像,可直接纠错并清除需复核标记", - async (scope, actor, [ref, profile]) => `已更新:${show(await store.setProfile(scope, ref, profile, actor))}`, + async (scope, actor, [ref, profile], _session, options) => { + const person = await store.setProfile(scope, ref, parsePeopleProfile(profile, options.format), actor); + return options.format === "json" ? show(person) : `已更新:${show(person)}`; + }, ); command( "people.clear ", diff --git a/packages/person-memory/src/person-tool-schema.ts b/packages/person-memory/src/person-tool-schema.ts new file mode 100644 index 000000000..c4e502e4a --- /dev/null +++ b/packages/person-memory/src/person-tool-schema.ts @@ -0,0 +1,56 @@ +import { Schema } from "koishi"; + +import { claimParameters } from "./claim-tools"; +import { catalogParameters, profileInputSchema } from "./profile-tools"; + +/** Use one flat object for native tool schemas and legacy action templates. */ +export function personToolContract(shared: boolean) { + const versionFields = "person_id, person_revision, account_revision"; + const actions = { + list: "list([query, fields, limit, cursor]) 列出人物", + read_many: "read_many(account_ids 或 all=true, [query, fields, limit, cursor]) 批量读取人物", + read: "read(account_id) 读取单个人物与最新版本", + search: "search(query) 返回最多五个匹配摘要", + history: "history(account_id) 查看最近十次修改记录", + claims: "claims(account_id, [offset, limit]) 列出逐条认识与版本", + claim_evidence: "claim_evidence(account_id, claim_id, [offset, limit]) 读取一条认识的原始证据", + propose_claim: `propose_claim(account_id, ${versionFields}, changes) 补证、反证、修订或停用逐条认识`, + propose: `propose(account_id, ${versionFields}, message_ids, profile) 提交完整画像,已启用逐条认识的人物请用 propose_claim`, + propose_link: `propose_link(account_id, ${versionFields}, message_ids, target_person_id, target_revision, confidence, reason) 提交账号关联建议,需人工审核`, + }; + const scope = shared + ? "仅操作有权限的共同域场景。account_id 可为当前平台账号 ID、人物 UUID 或 JSON [平台,ID]。" + : "仅操作当前场景。读取可用平台账号 ID 或人物 UUID,提交候选须用平台账号 ID。"; + const description = [ + scope, + "按 action 仅提供下列字段,方括号表示可选项。", + ...Object.values(actions), + "list 与 read_many 继续分页时只需使用原 action 和 cursor。提交变更前先 read 获取版本,锁定、暂停与版本校验始终生效。", + "review 模式需人工审核;auto 模式可自动接受画像候选,账号关联建议仍需人工审核。", + ].join("\n"); + // Preserve the existing validation differences between scene and shared mode. + const revision = () => (shared ? Schema.number() : Schema.number().min(0).step(1)); + const confidence = shared ? Schema.number() : Schema.number().min(0).max(1); + const parameters = Schema.object({ + action: Schema.union(Object.keys(actions).map((action) => Schema.const(action))).required(), + account_id: Schema.string().description("read、history、claims、claim_evidence、propose、propose_link、propose_claim 必填"), + query: Schema.string().description("search 必填(1–80 字);list/read_many 可选,用于筛选本次查询"), + profile: profileInputSchema(), + ...catalogParameters(), + ...claimParameters(), + offset: Schema.natural().description("claims/claim_evidence 专用;用 nextOffset 继续分页"), + message_ids: Schema.array(Schema.string()).description( + shared + ? "propose/propose_link 必填,1–10 个;当前场景用消息 ID,跨场景使用有权读取的来源编号" + : "propose/propose_link 必填,1–10 个当前场景实际消息 ID", + ), + person_id: Schema.string().description("propose/propose_link/propose_claim 必填;来源人物 UUID"), + person_revision: revision().description("propose/propose_link/propose_claim 必填;read 返回的来源人物版本"), + account_revision: revision().description("propose/propose_link/propose_claim 必填;read 返回的账号关联版本"), + target_person_id: Schema.string().description("propose_link 专用且必填;目标人物 UUID"), + target_revision: revision().description("propose_link 专用且必填;目标人物版本"), + confidence: confidence.description("propose_link 专用且必填;0–1 的关联确信度"), + reason: Schema.string().description("propose_link 专用且必填;1–500 字的关联依据"), + }); + return { description, parameters }; +} diff --git a/packages/person-memory/src/profile-prompt.ts b/packages/person-memory/src/profile-prompt.ts index 295294ebb..7f6b4c911 100644 --- a/packages/person-memory/src/profile-prompt.ts +++ b/packages/person-memory/src/profile-prompt.ts @@ -22,6 +22,7 @@ const PROFILE_FORMAT_RULES = '仅输出一次完整 JSON 候选,不输出增量、解释或 Markdown。格式为 {"profile":{"version":1,"background":[],"goals":[],"contexts":[],"needs":[],"preferences":[],"values":[],"scenes":[],"overview":""},"messageIds":["证据ID"]}。' + "background、goals、contexts、needs、preferences、values 均为字符串数组,overview 为字符串;所有字段必须完整提供。" + '每个 scene 格式为 {"key":"场景键","platform":"","selfId":"","channelId":"","nickname":"","recent":{"from":0,"to":0,"coverage":"recorded_only","messageCount":0,"activeDays":0,"topics":[],"emotions":[],"events":[],"interactions":[],"disagreements":[]},"taboos":[],"openers":[]}。' + + "recent.topics 必须为字符串数组且最多 5 项;其他字符串数组最多 20 项,scenes 最多 12 项。未知列表必须写空数组,不能写字符串、null或对象。" + "场景身份和计数采用输入 scenes 中程序计算的值,不自行推断;recent 只能采用 window 范围内证据,旧画像近期信息过期必须删除。" + "coverage 固定 recorded_only:计数只表示已捕获记录,evidence 为有限采样,不能据此声称覆盖全部聊天或推断精确活动比例。" + 'messageIds 引用 1 到 10 个本次 evidence 中支持更新的不同消息 ID;无新增可靠信息时返回 {"profile":"","messageIds":[]}。' + diff --git a/packages/person-memory/src/profile-tools.ts b/packages/person-memory/src/profile-tools.ts index e4a281fb4..c9de94d3e 100644 --- a/packages/person-memory/src/profile-tools.ts +++ b/packages/person-memory/src/profile-tools.ts @@ -47,16 +47,16 @@ export const profileInputSchema = () => export const catalogParameters = () => ({ account_ids: Schema.array(Schema.string()).description("read_many 多选人物 UUID 或账号 ID;与 all 互斥"), all: Schema.boolean().description("read_many 读取当前范围全部人物;过大时返回后续游标"), - fields: Schema.union(["overview", "structured", "full"]).description("返回概述、结构化栏目或完整档案;默认概述"), - cursor: Schema.string().description("继续上次查询;可仅传相同 action 和 cursor"), - limit: Schema.natural().min(1).max(20).description("本页人物数,最多20;响应过大时自动分页,不截断档案"), + fields: Schema.union(["overview", "structured", "full"]).description("list/read_many 可选;返回概述、结构化栏目或完整档案,默认概述"), + cursor: Schema.string().description("list/read_many 可选;继续上次查询时只传相同 action 和 cursor 即可"), + limit: Schema.natural().min(1).max(20).description("list/read_many/claims/claim_evidence 可选;每页最多 20 条"), }); /** Keep runtime Session objects and tool bookkeeping out of immutable snapshots. */ export function catalogRequest(args: CatalogArgs): CatalogArgs { return { action: args.action, - account_ids: args.account_ids, + account_ids: Array.isArray(args.account_ids) && args.account_ids.length === 0 ? undefined : args.account_ids, all: args.all, query: args.query, fields: args.fields, diff --git a/packages/person-memory/src/shared-runtime.ts b/packages/person-memory/src/shared-runtime.ts index 70b359aa7..fcfb42f0b 100644 --- a/packages/person-memory/src/shared-runtime.ts +++ b/packages/person-memory/src/shared-runtime.ts @@ -5,23 +5,24 @@ import * as core from "koishi-plugin-yesimbot"; import { conversationChannelId } from "koishi-plugin-yesimbot"; import { PeopleCatalog } from "./catalog"; -import { claimParameters, executeClaimTool, visibleClaims } from "./claim-tools"; -import { describePeopleCommand } from "./command-help"; +import { executeClaimTool, visibleClaims } from "./claim-tools"; +import { describePeopleCommand, parsePeopleProfile } from "./command-help"; import { escapeContext } from "./context"; import { ContinuityStore, registerContinuityModels, sourceRef, summaryUnsafeIn, type RecallTarget } from "./continuity"; +import { PersonHistoryReset, readPersonAction } from "./history-reset"; import type { Config, Dependencies } from "./index"; +import { personToolContract } from "./person-tool-schema"; import { mainProfilePolicy } from "./profile-prompt"; -import { catalogParameters, catalogProfile, catalogRequest, profileInputSchema, visibleProfile, visibleLegacyProfile } from "./profile-tools"; +import { catalogProfile, catalogRequest, visibleProfile, visibleLegacyProfile } from "./profile-tools"; +import { personSnapshotGuard } from "./snapshot-guard"; import { summarySourceAllowed } from "./source-policy"; import { PersonStore, accountRef, mindScope, registerModels, sceneKey, type Audit, type Mode, type SceneInput } from "./store"; import { registerSummaryQueueModels, SummaryQueue } from "./summary-queue"; +import { personMemoryFailure as failed } from "./tool-result"; import { SummaryWorker, summaryResponseText, type SummaryModel, type WorkerConfig } from "./worker"; const success = (result: unknown) => ({ status: "success", result }); -const failed = (error: unknown) => ({ - status: "error", - error: { name: "PersonMemoryError", message: error instanceof Error ? error.message : String(error) }, -}); + const boundedData = (value: unknown, size: number) => { const escaped = escapeContext(JSON.stringify(value)); return escaped.length > size ? escaped.slice(0, size) + "…(内容已截断)" : escaped; @@ -71,15 +72,17 @@ export function applySharedMemory(ctx: Context, config: Config) { registerModels(ctx); if (config.modelGroup) registerSummaryQueueModels(ctx); registerContinuityModels(ctx); + const reset = new PersonHistoryReset(ctx); let active = true; const modes = new Map(); const generations = new Map(); const scopeOf = (session: Session) => mindScope(session as unknown as SceneInput, config.memoryDomain || ""); - const baseAllowed = (session: Session) => active && ctx.filter(session) && world.isChannelAllowed(session); + const baseAllowed = (session: Session) => active && reset.available() && ctx.filter(session) && world.isChannelAllowed(session); const store = new PersonStore(ctx.database, config.mode, { + domain: reset.domain, autoLinks: true, - active: () => active, + active: () => active && reset.available(), onCommit: async (audit) => { if (audit.actor !== "summary-model") return; const sources = audit.changes.flatMap((c) => (c.after as any)?.evidence || []), @@ -111,6 +114,7 @@ export function applySharedMemory(ctx: Context, config: Config) { const memories = new ContinuityStore(ctx.database, store); const pending = new Set>(); const track = (promise: Promise) => { + reset.track(promise); pending.add(promise); void promise.finally(() => pending.delete(promise)).catch(() => {}); return promise; @@ -155,10 +159,12 @@ export function applySharedMemory(ctx: Context, config: Config) { logger.warn(`记忆已接受,事件投递失败:${String(error)}`); } }; - const writingStore = (session: Session) => - new PersonStore(ctx.database, config.mode, { + const writingStore = (session: Session) => { + const epoch = reset.epoch(); + return new PersonStore(ctx.database, config.mode, { + domain: reset.domain, autoLinks: true, - active: () => active, + active: () => active && reset.available() && reset.epoch() === epoch, onCommit: async (audit: Audit) => { if (audit.action === "recognize") return; await event( @@ -175,6 +181,7 @@ export function applySharedMemory(ctx: Context, config: Config) { ); }, }); + }; const assertEnabled = async (session: Session) => { if (!baseAllowed(session)) throw new Error("当前会话未启用共同记忆"); const scope = scopeOf(session), @@ -343,6 +350,10 @@ export function applySharedMemory(ctx: Context, config: Config) { sourceAllowed: (scope, _userId, evidence) => summarySourceAllowed(ctx, evidence, scope, true, baseAllowed, scopeOf), }; const worker = new SummaryWorker(store, model, workerConfig, (error) => logger.warn(String(error))); + reset.install(store, worker, scopeOf, true, () => { + modes.clear(); + generations.clear(); + }); if (model) { const getScope = (core as unknown as { getPersistentInstanceScope?: (ctx: Context, options?: { owner?: Context }) => string }) .getPersistentInstanceScope; @@ -371,6 +382,7 @@ export function applySharedMemory(ctx: Context, config: Config) { ) return; try { + const resetEpoch = reset.epoch(); const scope = scopeOf(session), target = sessionTargetKey(session), generation = generations.get(scope) ?? 0; @@ -378,6 +390,7 @@ export function applySharedMemory(ctx: Context, config: Config) { // permission after each async phase and at every store commit. const current = () => baseAllowed(session) && + reset.epoch() === resetEpoch && scopeOf(session) === scope && sessionTargetKey(session) === target && generation === (generations.get(scope) ?? 0) && @@ -483,10 +496,25 @@ export function applySharedMemory(ctx: Context, config: Config) { ? text : ""; }); + const guardSnapshot = personSnapshotGuard( + ctx, + async (session: Session) => { + const { scope, state } = await assertEnabled(session); + const targets = await targetsFor(session, scope); + return [reset.epoch(), scope, state.people, state.accounts, state.settings.mode, targets]; + }, + false, + ); ctx.on("yesimbot/filter-recalled-memory", async (session: Session, state: any) => { - if (!baseAllowed(session)) return; + if (!baseAllowed(session)) { + await guardSnapshot.project(session, state); + return; + } const scope = scopeOf(session); - if ((await modeOf(scope)).settings.mode === "off") return; + if ((await modeOf(scope)).settings.mode === "off") { + await guardSnapshot.project(session, state); + return; + } try { const ambiguous = await ambiguousChannels(scope); if (ambiguous.has(JSON.stringify([session.platform, conversationChannelId(session)]))) { @@ -524,42 +552,16 @@ export function applySharedMemory(ctx: Context, config: Config) { state.l3_diary_entries = []; filterRecallObservations(state, () => false); logger.warn(`旧摘要校验失败:${String(error)}`); + } finally { + await guardSnapshot.project(session, state); } }); const catalog = new PeopleCatalog(); const personTool = { name: "person_memory", - description: - "共同域人物记忆。claims 列出逐条认识,claim_evidence 读取原始证据,propose_claim 补证/反证/修订/停用;有逐条认识后不能整段覆盖。list 列出可查询人物;read_many 用 account_ids 多选或 all=true 全选,fields 选 overview/structured/full,cursor 继续分页。read/search/history 查资料;propose 提交画像;propose_link 提交账号关联。review 等管理员确认,auto 可自动接受;锁定、暂停与版本校验始终生效。account_id 可为当前平台 ID、人物 UUID 或 JSON [平台,ID];消息证据使用当前场景消息 ID,跨场景证据使用 people.sources 或 read 返回的来源编号。", + readOnly: readPersonAction, + ...personToolContract(true), isSupported: readable, - parameters: Schema.object({ - action: Schema.union([ - "list", - "read_many", - "read", - "search", - "history", - "propose", - "propose_link", - "claims", - "claim_evidence", - "propose_claim", - ]).required(), - account_id: Schema.string(), - query: Schema.string(), - profile: profileInputSchema(), - ...catalogParameters(), - ...claimParameters(), - offset: Schema.natural(), - message_ids: Schema.array(Schema.string()), - person_id: Schema.string(), - person_revision: Schema.number(), - account_revision: Schema.number(), - target_person_id: Schema.string(), - target_revision: Schema.number(), - confidence: Schema.number(), - reason: Schema.string(), - }), execute: async (args: any) => { try { const session = args.session as Session; @@ -759,6 +761,7 @@ export function applySharedMemory(ctx: Context, config: Config) { }; const recallTool = { name: "person_recall", + readOnly: true, description: "按关键词、人物和日期回忆当前配置允许的旧经历与 L2/L3 摘要。返回原始来源,不代表内容已核实;不改变事实或身份。", isSupported: readable, parameters: Schema.object({ @@ -777,8 +780,8 @@ export function applySharedMemory(ctx: Context, config: Config) { }, }; const removers = [ - toolService.registerTool({ ...personTool, execute: (args: any) => track(personTool.execute(args)) }), - toolService.registerTool({ ...recallTool, execute: (args: any) => track(recallTool.execute(args)) }), + toolService.registerTool(guardSnapshot({ ...personTool, execute: (args: any) => track(personTool.execute(args)) })), + toolService.registerTool(guardSnapshot({ ...recallTool, execute: (args: any) => track(recallTool.execute(args)) })), ]; function command( declaration: string, @@ -798,7 +801,7 @@ export function applySharedMemory(ctx: Context, config: Config) { const authority = (session.user as any)?.authority ?? (await session.observeUser(["authority"])).authority; if (authority < 3) throw new Error("仅管理员可管理共同记忆"); const scope = scopeOf(session), - result = await fn(session, writingStore(session), scope, args, options); + result = await reset.track(fn(session, writingStore(session), scope, args, options)); await modeOf(scope); const output = typeof result === "string" ? result : (JSON.stringify(result, null, 2) ?? "操作未返回结果,请执行 people.status 检查状态。"); return h.escape(output.slice(0, 12000)); @@ -828,14 +831,12 @@ export function applySharedMemory(ctx: Context, config: Config) { return `画像版本 ${found.person.revision}\n${JSON.stringify(found, null, 2)}`; }); command("people.create ", "建立共同人物档案", async (s, w, scope, [name]) => w.create(scope, name, actor(s))); - command("people.edit ", "人工纠正完整画像", async (s, w, scope, [ref, profile]) => - w.setProfile(scope, refOf(s, ref), profile, actor(s)), + command("people.edit ", "人工纠正完整画像", async (s, w, scope, [ref, profile], options) => + w.setProfile(scope, refOf(s, ref), parsePeopleProfile(profile, options?.format), actor(s)), + ); + command("people.edit_json ", "人工纠正完整结构画像(也可用 people.edit --format json)", async (s, w, scope, [ref, profile]) => + w.setProfile(scope, refOf(s, ref), parsePeopleProfile(profile, "json"), actor(s)), ); - command("people.edit_json ", "人工纠正完整结构画像(JSON)", async (s, w, scope, [ref, profile]) => { - const document = JSON.parse(profile); - if (!document || typeof document !== "object" || Array.isArray(document)) throw new Error("请提供完整结构画像 JSON 对象"); - return w.setProfile(scope, refOf(s, ref), document, actor(s)); - }); command("people.rename ", "修改共同称呼", async (s, w, scope, [ref, name]) => w.rename(scope, refOf(s, ref), name, actor(s))); command("people.clear ", "清空画像,保留来源与审计", async (s, w, scope, [ref]) => w.setProfile(scope, refOf(s, ref), "", actor(s))); command("people.bind [confidence:number]", "纠正账号归属", async (s, w, scope, [account, target, confidence = 1]) => diff --git a/packages/person-memory/src/snapshot-guard.ts b/packages/person-memory/src/snapshot-guard.ts new file mode 100644 index 000000000..7a4efa1ee --- /dev/null +++ b/packages/person-memory/src/snapshot-guard.ts @@ -0,0 +1,73 @@ +import { createHash } from "node:crypto"; + +const expired = () => ({ notice: "人物记忆快照已过期,请重新查询当前允许的资料。" }); + +/** Authorization belongs to a rendered snapshot, never to the immutable audit. */ +export function personSnapshotGuard(ctx: any, fingerprint: (session: any) => Promise, register = true) { + const snapshot = async (session: any) => + createHash("sha256") + .update(JSON.stringify(await fingerprint(session))) + .digest("hex"); + const isResultCurrent = async (result: any, session: any) => { + const token = result?.metadata?.personMemorySnapshot; + if (typeof token !== "string") return false; + try { + return token === (await snapshot(session)); + } catch { + return false; + } + }; + // Background queries and archived output reads can wrap the original result. + // Revalidate every marked payload without mutating the persisted observation. + const sanitize = async (value: any, session: any): Promise => { + if (!value || typeof value !== "object") return value; + if (value.metadata?.personMemorySnapshot && !(await isResultCurrent(value, session))) return expired(); + if (Array.isArray(value)) { + const projected = await Promise.all(value.map((item) => sanitize(item, session))); + return projected.every((item, index) => item === value[index]) ? value : projected; + } + const entries = await Promise.all(Object.entries(value).map(async ([key, item]) => [key, await sanitize(item, session)] as const)); + return entries.every(([key, item]) => item === value[key]) ? value : Object.fromEntries(entries); + }; + const project = async (session: any, state: any) => { + const memory = state.l1_working_memory; + if (!memory) return; + for (const key of ["new_events", "processed_events"]) { + if (!Array.isArray(memory[key])) continue; + memory[key] = await Promise.all( + memory[key].map(async (event: any) => { + if (event.type !== "agent_observation") return event; + const personTool = ["person_memory", "person_recall"].includes(event.function); + if (personTool || event.metadata?.personMemorySnapshot) { + if (!(await isResultCurrent(event.metadata ? { metadata: event.metadata } : event.result, session))) + return { ...event, result: expired(), error: undefined, metadata: undefined }; + } + const result = await sanitize(event.result, session); + return result === event.result ? event : { ...event, result }; + }), + ); + } + }; + if (register) ctx.on("yesimbot/filter-recalled-memory", project); + const wrap = (tool: any) => ({ + ...tool, + isResultCurrent, + execute: async (args: any) => { + const before = await snapshot(args.session).catch(() => undefined); + const result = await tool.execute(args); + if (result.status !== "success") return result; + try { + const token = await snapshot(args.session); + if ( + (tool.name === "person_recall" || ["read", "read_many", "list", "search", "history", "claims", "claim_evidence"].includes(args.action)) && + before !== token + ) + throw new Error("人物记忆快照已改变"); + return { ...result, metadata: { ...result.metadata, personMemorySnapshot: token } }; + } catch { + return { status: "error", error: { name: "PersonMemoryError", message: "人物资料或查询权限已改变,请重新查询" } }; + } + }, + }); + return Object.assign(wrap, { project }); +} diff --git a/packages/person-memory/src/store.ts b/packages/person-memory/src/store.ts index b2b048c0a..c727c5258 100644 --- a/packages/person-memory/src/store.ts +++ b/packages/person-memory/src/store.ts @@ -1,11 +1,17 @@ import { createHash, randomUUID } from "node:crypto"; import type { Context } from "koishi"; -import { conversationChannelId } from "koishi-plugin-yesimbot"; +import { AppError, ErrorDefinitions, conversationChannelId } from "koishi-plugin-yesimbot"; import { applyClaimChanges, projectClaims, retireClaims, claimEvidence as allClaimEvidence, type Claim, type ClaimChange } from "./claims"; import { validateProfileDocument, renderProfileDocument, type ProfileDocument } from "./profile"; +/** Keep version guards usable with cores predating the typed person error catalog. */ +function versionConflict(message: string): Error { + const definition = ErrorDefinitions.PERSON_MEMORY?.VERSION_CONFLICT; + return definition ? new AppError(definition, { args: [message] }) : new Error(message); +} + export type Mode = "off" | "review" | "auto"; export interface SceneInput { platform: string; @@ -150,6 +156,7 @@ export interface Audit { } declare module "koishi" { interface Tables { + "person_memory.owners": { key: string; domain: string; scope: string }; "person_memory.state": StateRow; "person_memory.sources": SourceRow; "person_memory.audit": Audit; @@ -159,6 +166,7 @@ const STATE = "person_memory.state", SOURCE = "person_memory.sources", AUDIT = "person_memory.audit"; export function registerModels(ctx: Context) { + ctx.model.extend("person_memory.owners", { key: "string", domain: "string", scope: "string" }, { primary: "key" }); ctx.model.extend(STATE, { scope: "string", revision: "unsigned", state: "json" }, { primary: "scope" }); ctx.model.extend(SOURCE, { key: "string", scope: "string", userId: "string", timestamp: "double", source: "json" }, { primary: "key" }); ctx.model.extend( @@ -290,13 +298,47 @@ async function serial(db: object, key: string, fn: () => Promise): Promise } } +type ResetCoordination = WeakMap>>; purging: Set }>; +const coordinationKey = Symbol.for("yesimbot.person-memory.reset.v1"); +const sharedCoordination = globalThis as typeof globalThis & { [key: symbol]: ResetCoordination | undefined }; +const resetCoordination = (sharedCoordination[coordinationKey] ??= new WeakMap()); +function resetGuard(db: Context["database"]) { + let guard = resetCoordination.get(db.tables); + if (!guard) resetCoordination.set(db.tables, (guard = { readers: new Map(), purging: new Set() })); + return guard; +} export class PersonStore { + private purgeSummary = { cleared: 0, retained: 0 }; + purgeReport() { + return { ...this.purgeSummary }; + } + private reading = new Set>(); constructor( private db: Context["database"], private defaultMode: Mode, - private options: { autoLinks?: boolean; active?: () => boolean; onCommit?: (audit: Audit) => Promise } = {}, + private options: { domain?: () => string; autoLinks?: boolean; active?: () => boolean; onCommit?: (audit: Audit) => Promise } = {}, ) {} private async snapshot(scope: string): Promise { + const guard = resetGuard(this.db); + if (this.options.active?.() === false || guard.purging.has(scope)) throw new Error("任务已取消"); + const operation = this.snapshotRows(scope); + this.reading.add(operation); + let readers = guard.readers.get(scope); + if (!readers) guard.readers.set(scope, (readers = new Set())); + readers.add(operation); + try { + return await operation; + } finally { + this.reading.delete(operation); + readers.delete(operation); + if (!readers.size) guard.readers.delete(scope); + } + } + private async snapshotRows(scope: string): Promise { + if (this.options.domain) { + const domain = this.options.domain(); + await this.db.upsert("person_memory.owners", [{ key: digest(JSON.stringify([domain, scope])), domain, scope }]); + } const cached = (await this.db.get(STATE, { scope }))[0]; const first = (await this.db.get(AUDIT, { scope, format: 1 }, { sort: { revision: "asc" }, limit: 1 }))[0]; const baseline = first?.baseline; @@ -321,6 +363,36 @@ export class PersonStore { if (row.revision && (!cached || cached.revision !== row.revision)) await this.cache({ scope, revision: row.revision, state: row.state }); return row; } + async purgeOwned(extraScopes: string[] = []) { + const domain = this.options.domain?.(); + if (!domain) throw new Error("人物资料缺少可证明的实例归属,拒绝清理"); + await Promise.allSettled(this.reading); + const owned = await this.db.get("person_memory.owners", { domain }); + const scopes = [...new Set([...owned.map((row) => row.scope), ...extraScopes])]; + const removed: string[] = []; + for (const scope of scopes) + await serial(this.db.tables, scope, async () => { + const guard = resetGuard(this.db); + guard.purging.add(scope); + try { + await Promise.allSettled(guard.readers.get(scope) ?? []); + const owners = await this.db.get("person_memory.owners", { scope }); + if (owners.some((owner) => owner.domain !== domain)) return; + await this.db.remove(SOURCE, { scope }); + // Audit baselines can reconstruct state, so delete them before the cache. + await this.db.remove(AUDIT, { scope }); + await this.db.remove(STATE, { scope }); + for (const table of ["person_memory.experiences", "person_memory.scenes"] as const) + if (this.db.tables[table]) await this.db.remove(table, { scope }); + await this.db.remove("person_memory.owners", { scope, domain }); + removed.push(scope); + } finally { + guard.purging.delete(scope); + } + }); + this.purgeSummary = { cleared: removed.length, retained: scopes.length - removed.length }; + return removed; + } async read(scope: string): Promise { return (await this.snapshot(scope)).state; } @@ -488,7 +560,11 @@ export class PersonStore { try { const old = await this.db.get(SOURCE, { scope }, { sort: { timestamp: "desc", key: "desc" }, offset: 200, limit: 2000 }); const expired = old.filter((row) => row.timestamp < Date.now() - 7 * 86400000); - if (expired.length) await this.db.remove(SOURCE, { key: { $in: expired.map((r) => r.key) } }); + // Bound SQL text: the WASM SQLite driver copies prepared SQL onto a small stack. + for (let offset = 0; offset < expired.length; offset += 128) { + if (!active() || this.options.active?.() === false) break; + await this.db.remove(SOURCE, { scope, key: { $in: expired.slice(offset, offset + 128).map((row) => row.key) } }); + } } catch { /* Retry cleanup on the next captured source. */ } @@ -831,7 +907,7 @@ export class PersonStore { if (p.locked) throw new Error("画像已被管理员锁定"); if (p.claims?.length) throw new Error("已有主张记录,请使用主张修订而非整篇覆写"); if (expected && (p.id !== expected.personId || p.revision !== expected.personRevision || a.revision !== expected.accountRevision)) - throw new Error("总结期间发生人工修改或身份变更,候选已过期"); + throw versionConflict("总结期间发生人工修改或身份变更,候选已过期"); const ids = new Set(messageIds); const sources = typeof input === "string" @@ -904,7 +980,7 @@ export class PersonStore { p = state.people[a.personId]; if (p.locked) throw new Error("画像已被管理员锁定"); if (!expected || p.id !== expected.personId || p.revision !== expected.personRevision || a.revision !== expected.accountRevision) - throw new Error("身份或画像版本已变化"); + throw versionConflict("身份或画像版本已变化"); const sources = await this.currentProfileSources(scope, state, userId, 0); const evidence = claimChanges.map((change) => { if (!Array.isArray(change.messageIds) || change.messageIds.length > 10 || (change.action !== "retire" && !change.messageIds.length)) diff --git a/packages/person-memory/src/summary-queue.ts b/packages/person-memory/src/summary-queue.ts index 8408599f7..54ba56856 100644 --- a/packages/person-memory/src/summary-queue.ts +++ b/packages/person-memory/src/summary-queue.ts @@ -29,6 +29,7 @@ export interface SummaryJob { attempts: number; nextAttempt: number; reason?: string; + validationError?: string; input?: SummaryInput; output?: SummaryOutput; receipt?: string; @@ -142,6 +143,9 @@ export class SummaryQueue { active, ); } + async purge() { + for (const job of await this.list()) await this.serial(job.key, () => this.db.remove(TABLE, { key: job.key, domain: this.domain })); + } async cancel(scope: string) { for (const job of (await this.list()).filter((job) => job.scope === scope)) { await this.serial(job.key, async () => { diff --git a/packages/person-memory/src/tool-result.ts b/packages/person-memory/src/tool-result.ts new file mode 100644 index 000000000..48e6e7ebd --- /dev/null +++ b/packages/person-memory/src/tool-result.ts @@ -0,0 +1,12 @@ +import * as core from "koishi-plugin-yesimbot"; + +// Older core versions may not expose the structured error helpers. +const errors: Partial> = core; + +export const personMemoryFailure = (error: unknown) => ({ + status: "error", + error: + typeof errors.isAppError === "function" && typeof errors.toToolError === "function" && errors.isAppError(error) + ? errors.toToolError(error) + : { name: "PersonMemoryError", message: error instanceof Error ? error.message : String(error) }, +}); diff --git a/packages/person-memory/src/worker.ts b/packages/person-memory/src/worker.ts index f2aafe0e3..862ce89e6 100644 --- a/packages/person-memory/src/worker.ts +++ b/packages/person-memory/src/worker.ts @@ -1,6 +1,7 @@ import { conversationChannelId } from "koishi-plugin-yesimbot"; import { claimCategories, type ClaimChange } from "./claims"; +import { validateProfileDocument } from "./profile"; import { buildProfileMessages } from "./profile-prompt"; import { visibleProfile } from "./profile-tools"; import { type Evidence, type PersonStore, type Provenance } from "./store"; @@ -49,6 +50,8 @@ interface Job { } export class SummaryWorker { private stopped = false; + private suspended = false; + private epoch = 0; private recovering = false; private persistence = new Set>(); private retryTimers = new Set>(); @@ -66,10 +69,12 @@ export class SummaryWorker { private report: (error: unknown) => void, ) {} async init() { - if (!this.model || this.stopped || !this.config.durableQueue) return; + const epoch = this.epoch; + if (!this.model || this.stopped || this.suspended || !this.config.durableQueue) return; this.recovering = true; try { for (const durable of await this.config.durableQueue.pending()) { + if (this.suspended || epoch !== this.epoch) return; const delay = Math.max(0, durable.nextAttempt - Date.now()); if (delay) this.schedule(durable, delay); else this.summarize(durable.scope, durable.userId, durable).catch(this.report); @@ -79,16 +84,18 @@ export class SummaryWorker { } } private schedule(durable: SummaryJob, delay: number) { - if (this.stopped) return; + const epoch = this.epoch; + if (this.stopped || this.suspended) return; const timer = setTimeout(() => { this.retryTimers.delete(timer); - if (!this.stopped) this.summarize(durable.scope, durable.userId, durable).catch(this.report); + if (!this.stopped && !this.suspended && epoch === this.epoch) this.summarize(durable.scope, durable.userId, durable).catch(this.report); }, delay); timer.unref?.(); this.retryTimers.add(timer); } async observe(scope: string, userId: string) { - if (!this.model || this.stopped) return; + const epoch = this.epoch; + if (!this.model || this.stopped || this.suspended) return; const key = JSON.stringify([scope, userId]); let usage = this.usage.get(key); if (!usage) { @@ -98,14 +105,14 @@ export class SummaryWorker { usage.count++; if (usage.count < this.config.threshold || Date.now() - usage.last < this.config.cooldownMs || this.jobs.has(key)) return; const state = await this.store.read(scope); - if (state.settings.paused || state.settings.mode === "off") return; + if (epoch !== this.epoch || this.suspended || state.settings.paused || state.settings.mode === "off") return; usage.count = 0; usage.last = Date.now(); // Errors also have cooldown: avoid repeated failing model calls. this.summarize(scope, userId).catch((error) => this.report(error)); } summarize(scope: string, userId: string, resumed?: SummaryJob): Promise { if (!this.model) return Promise.reject(new Error("请先在插件配置中指定总结模型组")); - if (this.stopped) return Promise.reject(new Error("任务已取消")); + if (this.stopped || this.suspended) return Promise.reject(new Error("任务已取消")); const key = JSON.stringify([scope, userId]); const existing = this.jobs.get(key); if (existing) return existing.promise; @@ -339,6 +346,14 @@ export class SummaryWorker { ? { platform: first.platform, botId: first.selfId, target: conversationChannelId(first), purpose: "人物记忆摘要" } : { purpose: "人物记忆摘要" }; if (saved) messages = saved.messages; + if (durable?.validationError) + messages = [ + ...messages, + { + role: "system", + content: `上次总结候选未通过结构验证:${durable.validationError}。保留原有写作策略、身份与证据限制,仅纠正上述格式错误,重新提交完整合法候选。`, + }, + ]; if (durable && !saved) await durableQueue!.patch(durable, { input: { @@ -372,6 +387,21 @@ export class SummaryWorker { if (durable && !(await durableQueue!.valid(durable))) throw new Error("任务已取消或失效"); if (this.stopped || controller.signal.aborted) throw new Error("任务已取消"); if (!inputsAllowed()) throw new Error("人物总结输入来源权限已失效"); + if (durable?.output && !claimMode && typeof (durable.output as any).profile !== "string") { + try { + validateProfileDocument((durable.output as any).profile); + } catch (error) { + const validationError = String(error).slice(0, 400); + await durableQueue!.patch(durable, { output: undefined, validationError }); + messages = [ + ...messages, + { + role: "system", + content: `上次总结候选未通过结构验证:${validationError}。保留原有写作策略、身份与证据限制,仅修正结构后重新提交完整候选。`, + }, + ]; + } + } const timer = setTimeout(() => controller.abort(new Error("总结模型超时")), this.config.timeoutMs); let abort!: () => void; const cancelled = new Promise((_, reject) => { @@ -451,16 +481,57 @@ export class SummaryWorker { parsed.messageIds.some((id: unknown) => typeof id !== "string" || !evidenceIds.has(id)) ) throw new Error("人物总结必须引用 1 到 10 个输入中的不同证据 ID,未创建候选"); + // Cache only a candidate that passed structural validation. A malformed + // model response must be regenerated on a bounded retry, never replayed. + try { + if (!claimMode && typeof parsed.profile !== "string") validateProfileDocument(parsed.profile); + } catch (error) { + if (durable) await durableQueue!.patch(durable, { output: undefined, validationError: String(error).slice(0, 400) }); + throw error; + } if (durable && !durable.output) await durableQueue!.patch(durable, { output: parsed }); if (durable && !(await durableQueue!.valid(durable))) throw new Error("任务已取消或失效"); const active = () => !this.stopped && !controller.signal.aborted && inputsAllowed(); if (!active()) throw new Error("人物总结输入来源权限已失效"); - const proposal = claimMode - ? await this.store.proposeClaims(scope, userId, parsed.changes, "summary-model", saved?.expected ?? expected, active, durable?.id) - : await this.store.propose(scope, userId, parsed.profile, parsed.messageIds, "summary-model", saved?.expected ?? expected, active, durable?.id); + let proposal; + try { + proposal = claimMode + ? await this.store.proposeClaims(scope, userId, parsed.changes, "summary-model", saved?.expected ?? expected, active, durable?.id) + : await this.store.propose(scope, userId, parsed.profile, parsed.messageIds, "summary-model", saved?.expected ?? expected, active, durable?.id); + } catch (error) { + if (durable && /画像列表|画像字段|画像文本|画像版本|画像场景|结构画像/.test(String(error))) + await durableQueue!.patch(durable, { output: undefined, validationError: String(error).slice(0, 400) }); + throw error; + } this.checkpoints.set(job.key, saved?.sourceCursor ?? sourceCursor); return proposal.id; } + async reset() { + this.suspended = true; + this.epoch++; + for (const timer of this.retryTimers) clearTimeout(timer); + this.retryTimers.clear(); + this.current?.controller.abort(new Error("任务已取消")); + for (const job of this.queue) { + this.jobs.delete(job.key); + job.reject(new Error("任务已取消")); + } + this.queue = []; + this.usage.clear(); + this.results.clear(); + this.checkpoints.clear(); + await Promise.allSettled(this.persistence); + await this.idle(); + const scopes = ((await this.config.durableQueue?.list()) ?? []).map((job) => job.scope); + await this.config.durableQueue?.purge(); + return scopes; + } + resume() { + if (!this.stopped) this.suspended = false; + } + async scopes() { + return ((await this.config.durableQueue?.list()) ?? []).map((job) => job.scope); + } cancel(scope: string) { const pending = [...this.persistence]; const invalidated = this.config.durableQueue ? Promise.allSettled(pending).then(() => this.config.durableQueue!.cancel(scope)) : undefined; diff --git a/packages/person-memory/tests/profile-tools.spec.ts b/packages/person-memory/tests/profile-tools.spec.ts index 28b30b4cb..ab1565688 100644 --- a/packages/person-memory/tests/profile-tools.spec.ts +++ b/packages/person-memory/tests/profile-tools.spec.ts @@ -1,3 +1,4 @@ +import { ErrorDefinitions } from "koishi-plugin-yesimbot"; import { expect, it } from "vitest"; import { apply } from "../src/index"; @@ -86,6 +87,19 @@ for (const shared of [false, true]) { const result = await f.tool.execute({ session: f.session, action: "read_many", all: true, account_ids: ["u"] }); expect(result.status).toBe("error"); }); + it(`${shared ? "shared" : "scene"} describes the inputs for each action with the same flat parameters`, async (t) => { + const { tool } = await setup(t, shared); + const { parameters } = tool; + expect(parameters.type).toBe("object"); + expect(Object.keys(parameters.dict).filter((key) => parameters.dict[key].meta.required)).toEqual(["action"]); + expect(tool.description).toContain("claim_evidence(account_id, claim_id, [offset, limit])"); + expect(tool.description).toContain("propose_claim(account_id, person_id, person_revision, account_revision, changes)"); + expect(parameters.dict.query.meta.description).toContain("search"); + expect(parameters.dict.query.meta.description).toContain("list"); + expect(parameters.dict.message_ids.meta.description).toContain(shared ? "来源编号" : "当前场景"); + expect(parameters({ action: "read_many", cursor: "next-page" }).cursor).toBe("next-page"); + expect(parameters({ action: "propose", profile: "旧画像" }).profile).toBe("旧画像"); + }); it(`${shared ? "shared" : "scene"} accepts an atomic structured candidate and returns synchronized fields and overview`, async (t) => { const f = await setup(t, shared); await f.app.parallel("yesimbot/before-user-stimulus" as any, { @@ -127,3 +141,57 @@ for (const shared of [false, true]) { expect(read.result.profile.endsWith(read.result.overview)).toBe(true); }); } + +for (const shared of [false, true]) + for (const action of ["propose", "propose_claim"]) + it(`classifies stale ${action} candidates through the ${shared ? "shared" : "scene"} failure boundary`, async (t) => { + const f = await setup(t, shared); + const ref = shared ? accountRef("onebot", "u") : "u"; + const found = (await f.store.find(f.scope, ref))!; + await f.store.setProfile(f.scope, ref, "管理员刚刚更新", "admin"); + await f.app.parallel("yesimbot/before-user-stimulus" as any, { + ...f.session, + author: { name: "u" }, + messageId: "fresh", + content: "我喜欢 Python", + timestamp: Date.now() + 1, + }); + const source = (await f.store.profileSources(f.scope, ref, 0))[0]; + const result = await f.tool.execute({ + session: f.session, + action, + account_id: "u", + profile: "旧候选", + message_ids: [source.id], + person_id: found.person.id, + person_revision: found.person.revision, + account_revision: found.accounts[0].revision, + changes: [{ action: "support", category: "preferences", statement: "旧候选", messageIds: [source.id] }], + }); + expect(result.status).toBe("error"); + expect(result.error).toMatchObject({ code: "PERSON_MEMORY.VERSION_CONFLICT", category: "conflict", retryable: false }); + expect(result.error.errorId).toMatch(/^[0-9a-f-]{36}$/); + expect(JSON.stringify(result)).not.toMatch(/stack|cause|context/); + expect((await f.store.find(f.scope, ref))!.person.profile).toContain("管理员刚刚更新"); + }); + +it("preserves the conflict guard when an older core has no person error catalog", async (t) => { + const f = await setup(t, false); + const found = (await f.store.find(f.scope, "u"))!; + await f.store.setProfile(f.scope, "u", "管理员刚刚更新", "admin"); + const catalog = ErrorDefinitions as any; + const saved = catalog.PERSON_MEMORY; + try { + delete catalog.PERSON_MEMORY; + await expect( + f.store.propose(f.scope, "u", "旧候选", ["source"], "model", { + personId: found.person.id, + personRevision: found.person.revision, + accountRevision: found.accounts[0].revision, + }), + ).rejects.toThrow("总结期间发生人工修改或身份变更,候选已过期"); + expect((await f.store.find(f.scope, "u"))!.person.profile).toContain("管理员刚刚更新"); + } finally { + catalog.PERSON_MEMORY = saved; + } +}); diff --git a/packages/person-memory/tests/query-permissions.spec.ts b/packages/person-memory/tests/query-permissions.spec.ts index 8f0c5a023..f8f5761f0 100644 --- a/packages/person-memory/tests/query-permissions.spec.ts +++ b/packages/person-memory/tests/query-permissions.spec.ts @@ -229,6 +229,12 @@ for (const shared of [false, true]) { // Koishi's real parser preserves the greedy text argument verbatim; // execute the registered action against the real database. await command._actions[0]({ session: f.session, options: {} } as any, ...argv.args!); + const canonical = f.app.$commander.get("people.edit")!; + document.preferences.push("第二项"); + const unified = canonical.parse(Argv.parse(`--format json u ${JSON.stringify(document)}`)); + expect(unified.options?.format).toBe("json"); + expect(unified.args?.[1]).toBe(JSON.stringify(document)); + await canonical._actions[0]({ session: f.session, options: unified.options } as any, ...unified.args!); const structured = (await f.store.find(f.scope, f.ref))!.person; expect(structured.structuredProfile?.preferences).toEqual(document.preferences); expect(structured.profile).toContain(document.preferences[0]); diff --git a/packages/person-memory/tests/recall-consistency.spec.ts b/packages/person-memory/tests/recall-consistency.spec.ts index 1df20d35b..f288000ef 100644 --- a/packages/person-memory/tests/recall-consistency.spec.ts +++ b/packages/person-memory/tests/recall-consistency.spec.ts @@ -1,7 +1,9 @@ import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; import { test } from "vitest"; +import { MustacheRenderer } from "../../core/src/prompt/renderer"; import { applySharedMemory } from "../src/shared-runtime"; import { PersonStore, accountRef, mindScope } from "../src/store"; import { fixture } from "./helpers"; @@ -23,7 +25,7 @@ async function runtime(t, config = {}) { }); ctx.model.extend("saved_observations", { id: "string", event: "json" }, { primary: "id" }); ctx.set("yesimbot", { - world: { isChannelAllowed: () => true }, + world: { isChannelAllowed: (s) => (config.allow ? config.allow(s) : true) }, tool: { registerTool: (tool) => { tools.set(tool.name, tool); @@ -124,3 +126,95 @@ for (const kind of ["l2", "l3"]) assert.deepEqual((await app.database.get("saved_observations", { id: "recall" }))[0].event, event); }); } + +test("person snapshots expire after source revocation and profile correction without mutating audit observations", async (t) => { + let hiddenAllowed = true; + const { app, tools } = await runtime(t, { recallScope: "mind", allow: (s) => s.channelId !== "hidden" || hiddenAllowed }); + const source = { + ...session, + userId: "alice", + channelId: "hidden", + messageId: "secret", + content: "秘密旅行 PRIVATE-MEMORY", + timestamp: Date.now(), + author: { name: "Alice" }, + }; + await app.parallel("yesimbot/before-user-stimulus", source); + const query = { session, query: "秘密旅行" }; + const recalled = await tools.get("person_recall").execute(query); + assert.equal(recalled.result.sources.length, 1); + const store = new PersonStore(app.database, "review"), + scope = mindScope(session), + ref = accountRef("onebot", "alice"); + await store.setProfile(scope, ref, "WRONG-PROFILE", "admin"); + const read = await tools.get("person_memory").execute({ session, action: "read", account_id: "alice" }); + const events = [ + { type: "agent_observation", function: "person_recall", result: recalled.result, metadata: recalled.metadata }, + { type: "agent_observation", function: "person_memory", result: read.result, metadata: read.metadata }, + ]; + const original = structuredClone(events); + hiddenAllowed = false; + await store.setProfile(scope, ref, "CORRECT-PROFILE", "admin"); + assert.equal((await tools.get("person_recall").execute(query)).result.sources.length, 0); + const nested = { type: "agent_observation", function: "background_task_query", result: { task: { result: recalled } } }; + const wrapped = { type: "agent_observation", function: "person_memory", result: read }; + const state = { l1_working_memory: { new_events: [nested, wrapped], processed_events: events } }; + await app.parallel("yesimbot/filter-recalled-memory", session, state); + assert.ok(!JSON.stringify(state).includes("PRIVATE-MEMORY")); + assert.ok(!JSON.stringify(state).includes("WRONG-PROFILE")); + const template = await readFile(new URL("../../core/resources/templates/l1_history_item.mustache", import.meta.url), "utf8"); + const prompt = new MustacheRenderer().render( + "{{#events}}{{> observation}}{{/events}}", + { + events: state.l1_working_memory.processed_events.map((e) => ({ ...e, is_agent_observation: true })), + _toString: function () { + return JSON.stringify(this); + }, + }, + { observation: template }, + ); + assert.ok(prompt.includes("人物记忆快照已过期")); + assert.ok(!prompt.includes("PRIVATE-MEMORY")); + assert.ok(!prompt.includes("WRONG-PROFILE")); + assert.deepEqual(events, original); + assert.equal(await tools.get("person_memory").isResultCurrent(read, session), false); +}); + +test("a source permission revoked during an awaited person read rejects the entire result", async (t) => { + let hiddenAllowed = true; + const { app, tools } = await runtime(t, { recallScope: "mind", allow: (s) => s.channelId !== "hidden" || hiddenAllowed }); + await app.parallel("yesimbot/before-user-stimulus", { + ...session, + channelId: "hidden", + userId: "alice", + messageId: "secret", + content: "旅行 PRIVATE-CONCURRENT", + timestamp: Date.now(), + author: { name: "Alice" }, + }); + // Gate the actual source database read, after the tool has captured its initial + // authorized snapshot. Revoking here exercises its post-await validation. + const get = app.database.get.bind(app.database); + let entered!: () => void, release!: () => void; + const reached = new Promise((r) => { + entered = r; + }), + gate = new Promise((r) => { + release = r; + }); + app.database.get = async (table: any, ...args: any[]) => { + const rows = await get(table, ...args); + if (table === "person_memory.experiences") { + entered(); + await gate; + } + return rows; + }; + const pending = tools.get("person_recall").execute({ session, query: "旅行" }); + await reached; + hiddenAllowed = false; + release(); + const result = await pending; + assert.equal(result.status, "error"); + assert.ok(!JSON.stringify(result).includes("PRIVATE-CONCURRENT")); +}); diff --git a/packages/person-memory/tests/reset-state.spec.ts b/packages/person-memory/tests/reset-state.spec.ts new file mode 100644 index 000000000..b2858db64 --- /dev/null +++ b/packages/person-memory/tests/reset-state.spec.ts @@ -0,0 +1,333 @@ +import { expect, it } from "vitest"; + +import { PersonStore, registerModels } from "../src/store"; +import { SummaryQueue, registerSummaryQueueModels } from "../src/summary-queue"; +import { SummaryWorker } from "../src/worker"; +import { fixture } from "./helpers"; + +it("treats schema-default empty account arrays as absence for list and all selections", async () => { + const { catalogRequest } = await import("../src/profile-tools"); + expect(catalogRequest({ action: "list", account_ids: [] })).toMatchObject({ action: "list", account_ids: undefined }); + expect(catalogRequest({ action: "read_many", all: true, account_ids: [] })).toMatchObject({ all: true, account_ids: undefined }); +}); +it("purges only persistently owned scopes including audit baselines, across store reconstruction", async (t) => { + const ctx = await fixture(t, registerModels); + const own = new PersonStore(ctx.database, "review", { domain: () => "own" } as any), + foreign = new PersonStore(ctx.database, "review", { domain: () => "foreign" } as any); + await own.recognize("own-scene", "u", "Own"); + await own.capture("own-scene", { id: "old", userId: "u", name: "Own", text: "old", timestamp: Date.now() }); + await foreign.recognize("foreign-scene", "v", "Foreign"); + const restarted = new PersonStore(ctx.database, "review", { domain: () => "own" } as any); + await (restarted as any).purgeOwned(); + expect((await restarted.read("own-scene")).people).toEqual({}); + expect(await ctx.database.get("person_memory.audit", { scope: "own-scene" })).toEqual([]); + expect(await ctx.database.get("person_memory.sources", { scope: "own-scene" })).toEqual([]); + expect(Object.keys((await foreign.read("foreign-scene")).people)).toHaveLength(1); +}); +it("reset aborts in-flight inference, drops queued durable payloads and accepts only fresh work after release", async (t) => { + const ctx = await fixture(t, (c) => { + registerModels(c); + registerSummaryQueueModels(c); + }); + const store = new PersonStore(ctx.database, "review"); + for (const scope of ["a", "b"]) { + await store.recognize(scope, "u", "User"); + await store.capture(scope, { id: "m", userId: "u", name: "User", text: "source", timestamp: Date.now() }); + } + let release!: (s: string) => void, entered!: () => void, signal!: AbortSignal; + const started = new Promise((r) => { + entered = r; + }); + let calls = 0; + const queue = new SummaryQueue(ctx.database, "own"), + other = new SummaryQueue(ctx.database, "foreign"); + await other.enqueue("foreign", "u"); + const worker = new SummaryWorker( + store, + async (_m, s) => { + calls++; + if (calls > 1) return JSON.stringify({ profile: "fresh", messageIds: ["new"] }); + signal = s; + entered(); + return new Promise((r) => { + release = r; + }); + }, + { threshold: 2, cooldownMs: 1, timeoutMs: 10000, maxQueue: 4, durableQueue: queue }, + () => {}, + ); + t.onTestFinished(() => worker.stop()); + const first = worker.summarize("a", "u"); + const rejected = first.catch((error) => error); + await started; + const second = worker.summarize("b", "u"); + const queued = second.catch((error) => error); + await (worker as any).reset(); + expect(String(await rejected)).toMatch(/取消/); + expect(String(await queued)).toMatch(/取消/); + expect(signal.aborted).toBe(true); + expect(await queue.list()).toEqual([]); + expect(await other.list()).toHaveLength(1); + release(JSON.stringify({ profile: "late", messageIds: ["m"] })); + await worker.idle(); + expect(Object.keys((await store.read("a")).proposals)).toHaveLength(0); + expect(calls).toBe(1); + (worker as any).resume(); + const fresh = new SummaryWorker( + store, + async () => JSON.stringify({ profile: "fresh", messageIds: ["m"] }), + { threshold: 2, cooldownMs: 1, timeoutMs: 1000, maxQueue: 4, durableQueue: queue }, + () => {}, + ); + t.onTestFinished(() => fresh.stop()); + await fresh.init(); + expect(await queue.list()).toEqual([]); + await store.capture("a", { id: "new", userId: "u", name: "User", text: "new message", timestamp: Date.now() }); + await worker.summarize("a", "u"); + expect(Object.values((await store.read("a")).proposals)[0].profile).toBe("fresh"); +}); + +it("retains shared scopes when another owner has not joined the reset fence", async (t) => { + const ctx = await fixture(t, registerModels); + const a = new PersonStore(ctx.database, "review", { domain: () => "a" }), + b = new PersonStore(ctx.database, "review", { domain: () => "b" }); + await a.recognize("shared", "u", "Shared"); + await b.read("shared"); + expect(await a.purgeOwned()).toEqual([]); + expect(Object.keys((await b.read("shared")).people)).toHaveLength(1); + expect(await ctx.database.get("person_memory.owners", { scope: "shared" })).toHaveLength(2); +}); +it("regenerates malformed model candidates with bounded feedback instead of caching and replaying them", async (t) => { + const ctx = await fixture(t, (c) => { + registerModels(c); + registerSummaryQueueModels(c); + }); + const store = new PersonStore(ctx.database, "review"); + await store.recognize("s", "u", "U"); + await store.capture("s", { id: "m", userId: "u", name: "U", text: "source", timestamp: Date.now() }); + const queue = new SummaryQueue(ctx.database, "validation"); + let calls = 0; + const inputs: any[] = []; + const worker = new SummaryWorker( + store, + async (messages) => { + inputs.push(messages); + return JSON.stringify({ profile: ++calls === 1 ? { version: 9 } : "valid", messageIds: ["m"] }); + }, + { threshold: 2, cooldownMs: 1, timeoutMs: 1000, maxQueue: 2, retryDelayMs: 1, durableQueue: queue }, + () => {}, + ); + t.onTestFinished(() => worker.stop()); + await expect(worker.summarize("s", "u")).rejects.toThrow(/画像/); + await expect.poll(async () => (await queue.list())[0]?.status).toBe("accepted"); + expect(calls).toBe(2); + expect(inputs[1].at(-1).content).toContain("结构验证"); + expect(inputs[1][0]).toEqual(inputs[0][0]); + expect(Object.values((await store.read("s")).proposals)[0].profile).toBe("valid"); +}); +for (const shared of [false, true]) + it(`${shared ? "shared" : "scene"} actual plugin reset fences delayed capture and purges only its owned data`, async (t) => { + const { apply } = await import("../src/index"); + const { prepareHistoryReset } = await import("../../core/src/world/history-reset"); + const { sceneKey, mindScope } = await import("../src/store"); + const tools = new Map(); + const app = await fixture(t, (ctx) => { + const bot: any = { + platform: "onebot", + selfId: "bot", + session: (e: any) => ({ + ...e, + platform: "onebot", + selfId: "bot", + channelId: e.channel.id, + userId: e.user?.id ?? e.userId, + isDirect: e.channel.type === 1, + guildId: e.guild?.id, + }), + }; + Object.defineProperty(ctx, "bots", { value: [bot] }); + ctx.set("yesimbot", { + ctx, + world: { capabilities: { beforeUserStimulus: 1, memoryCorrectionFilter: 1 }, isChannelAllowed: () => true }, + tool: { + capabilities: { trustedToolSession: 1 }, + registerTool: (tool) => { + tools.set(tool.name, tool); + return () => tools.delete(tool.name); + }, + }, + prompt: { inject: () => () => {} }, + }); + ctx.plugin({ + inject: ["database", "yesimbot"], + apply: (plugin) => + apply(plugin, { + enabled: true, + mode: "review", + sharedMemory: shared, + modelGroup: "", + summaryThreshold: 2, + cooldownSeconds: 30, + timeoutSeconds: 30, + maxQueue: 4, + }), + }); + }); + const session: any = { + bot: app.bots[0], + platform: "onebot", + selfId: "bot", + channelId: "room", + userId: "u", + isDirect: false, + author: { name: "User" }, + messageId: "old", + content: "old", + timestamp: Date.now(), + }; + const scope = shared ? mindScope(session) : sceneKey(session); + const get = app.database.get.bind(app.database); + let release!: () => void, + entered!: () => void, + gateOnce = true; + const reached = new Promise((r) => { + entered = r; + }), + gate = new Promise((r) => { + release = r; + }); + app.database.get = async (table: any, ...args: any[]) => { + const rows = await get(table, ...args); + if (table === "person_memory.sources" && gateOnce) { + gateOnce = false; + entered(); + await gate; + } + return rows; + }; + const capture = app.parallel("yesimbot/before-user-stimulus" as any, session); + await reached; + const preparation = prepareHistoryReset(app, { type: "all" }); + release(); + await preparation.ready; + await capture; + await preparation.finish(); + expect(await app.database.get("person_memory.audit", { scope })).toEqual([]); + expect(await app.database.get("person_memory.sources", { scope })).toEqual([]); + expect(await app.database.get("person_memory.state", { scope })).toEqual([]); + const experiences = shared ? await app.database.get("person_memory.experiences", { scope }) : []; + const scenes = shared ? await app.database.get("person_memory.scenes", { scope }) : []; + expect(experiences).toEqual([]); + expect(scenes).toEqual([]); + await app.parallel("yesimbot/before-user-stimulus" as any, { ...session, messageId: "new", content: "fresh" }); + expect(await app.database.get("person_memory.sources", { scope })).toHaveLength(1); + const listed = await tools.get("person_memory").execute({ session, action: "list", account_ids: [] }); + expect(listed).toMatchObject({ status: "success" }); + }); +it("waits for a foreign snapshot enrollment before deciding whether a shared scope may be purged", async (t) => { + const ctx = await fixture(t, registerModels); + const a = new PersonStore(ctx.database, "review", { domain: () => "a" }), + b = new PersonStore(ctx.database, "review", { domain: () => "b" }); + await a.recognize("s", "u", "User"); + await ctx.database.remove("person_memory.state", { scope: "s" }); + const upsert = ctx.database.upsert.bind(ctx.database); + let entered!: () => void, release!: () => void; + const reached = new Promise((r) => { + entered = r; + }), + gate = new Promise((r) => { + release = r; + }); + ctx.database.upsert = async (table: any, rows: any, ...args: any[]) => { + if (table === "person_memory.owners" && rows[0].domain === "b") { + entered(); + await gate; + } + return upsert(table, rows, ...args); + }; + const reading = b.read("s"); + await reached; + const purging = a.purgeOwned(); + release(); + expect(Object.keys((await reading).people)).toHaveLength(1); + expect(await purging).toEqual([]); + expect(await ctx.database.get("person_memory.state", { scope: "s" })).toHaveLength(1); + expect(Object.keys((await a.read("s")).people)).toHaveLength(1); +}); +it("clears legacy malformed durable output and regenerates once with the original input and corrective feedback", async (t) => { + const ctx = await fixture(t, (c) => { + registerModels(c); + registerSummaryQueueModels(c); + }); + const store = new PersonStore(ctx.database, "review"); + await store.recognize("s", "u", "U"); + await store.capture("s", { id: "m", userId: "u", name: "U", text: "source", timestamp: Date.now() }); + const queue = new SummaryQueue(ctx.database, "legacy-invalid"), + config = { threshold: 2, cooldownMs: 1, timeoutMs: 1000, maxQueue: 2, retryDelayMs: 10000, durableQueue: queue }; + const first = new SummaryWorker( + store, + async () => JSON.stringify({ profile: { version: 9 }, messageIds: ["m"] }), + config, + () => {}, + ); + await expect(first.summarize("s", "u")).rejects.toThrow(/画像/); + await first.stop(); + const [old] = await queue.list(); + await queue.patch(old, { output: { profile: { version: 9 }, messageIds: ["m"] }, nextAttempt: 0 }); + let calls = 0; + const restored = new SummaryWorker( + store, + async (messages) => { + calls++; + expect(messages[0]).toEqual(old.input.messages[0]); + expect(messages.at(-1).content).toContain("结构验证"); + return JSON.stringify({ profile: "repaired", messageIds: ["m"] }); + }, + config, + () => {}, + ); + t.onTestFinished(() => restored.stop()); + await restored.summarize("s", "u"); + expect(calls).toBe(1); + expect((await queue.list())[0].status).toBe("accepted"); +}); + +it("keeps derived cleanup inside the scope fence so a new foreign owner cannot write into its deletion window", async (t) => { + const { registerContinuityModels, ContinuityStore } = await import("../src/continuity"); + const ctx = await fixture(t, (c) => { + registerModels(c); + registerContinuityModels(c); + }); + const a = new PersonStore(ctx.database, "review", { domain: () => "a" }), + b = new PersonStore(ctx.database, "review", { domain: () => "b" }); + await a.recognize("s", "u", "Old"); + let entered!: () => void, release!: () => void; + const reached = new Promise((r) => { + entered = r; + }), + gate = new Promise((r) => { + release = r; + }); + const remove = ctx.database.remove.bind(ctx.database); + ctx.database.remove = async (table: any, ...args: any[]) => { + if (table === "person_memory.experiences") { + entered(); + await gate; + } + return remove(table, ...args); + }; + const clearing = a.purgeOwned(); + await reached; + await expect(b.read("s")).rejects.toThrow(/取消/); + release(); + expect(await clearing).toEqual(["s"]); + const identity = await b.recognize("s", "u", "New"); + const continuity = new ContinuityStore(ctx.database, b); + await continuity.capture( + "s", + { platform: "onebot", selfId: "bot", channelId: "room", userId: "u" }, + { id: "new", userId: "u", name: "New", text: "fresh", timestamp: Date.now() }, + identity, + ); + expect(await ctx.database.get("person_memory.experiences", { scope: "s" })).toHaveLength(1); +}); diff --git a/packages/person-memory/tests/source-retention-batches.spec.ts b/packages/person-memory/tests/source-retention-batches.spec.ts new file mode 100644 index 000000000..5511cc352 --- /dev/null +++ b/packages/person-memory/tests/source-retention-batches.spec.ts @@ -0,0 +1,65 @@ +import { createHash } from "node:crypto"; + +import { expect, it, vi } from "vitest"; + +import { PersonStore, registerModels } from "../src/store"; +import { fixture } from "./helpers"; + +const table = "person_memory.sources"; +const key = (id: string) => createHash("sha256").update(id).digest("hex"); +const oldTime = Date.now() - 8 * 86400000; +async function seed(t, count = 2200) { + const ctx = await fixture(t, registerModels); + await ctx.database.upsert( + table, + Array.from({ length: count }, (_, i) => ({ + key: key(String(i)), + scope: "mind:a", + userId: "u", + timestamp: oldTime + i, + source: { id: String(i), userId: "u", name: "u", text: "old", timestamp: oldTime + i }, + })), + ); + await ctx.database.create(table, { + key: key("other"), + scope: "mind:b", + userId: "u", + timestamp: oldTime, + source: { id: "other", userId: "u", name: "u", text: "other", timestamp: oldTime }, + }); + return ctx; +} +const fresh = { id: "fresh", userId: "u", name: "u", text: "new", timestamp: Date.now() }; + +it("cleans a full expired page with bounded queries while preserving the newest sources and other domains", async (t) => { + const ctx = await seed(t); + const remove = vi.spyOn(ctx.database, "remove"); + await new PersonStore(ctx.database, "review").capture("mind:a", fresh); + const calls = remove.mock.calls.filter(([name]) => name === table); + expect(calls.length).toBeGreaterThan(1); + for (const [, query] of calls) { + expect(query.scope).toBe("mind:a"); + expect(query.key.$in.length).toBeLessThanOrEqual(128); + } + const rows = await ctx.database.get(table, { scope: "mind:a" }); + expect(rows).toHaveLength(201); + expect(rows.some((row) => row.source.id === "fresh")).toBe(true); + for (let i = 2001; i < 2200; i++) expect(rows.some((row) => row.source.id === String(i))).toBe(true); + expect(await ctx.database.get(table, { scope: "mind:b" })).toHaveLength(1); +}); + +it("stops deleting between cleanup batches after the capture is cancelled", async (t) => { + const ctx = await seed(t, 500); + let active = true; + const original = ctx.database.remove.bind(ctx.database); + const remove = vi.spyOn(ctx.database, "remove").mockImplementation(async (...args) => { + const result = await original(...args); + active = false; + return result; + }); + await new PersonStore(ctx.database, "review").capture("mind:a", fresh, () => active); + expect(remove).toHaveBeenCalledTimes(1); + const rows = await ctx.database.get(table, { scope: "mind:a" }); + expect(rows.length).toBeGreaterThan(200); + expect(rows.some((row) => row.source.id === "fresh")).toBe(true); +}); diff --git a/packages/person-memory/tests/sqlite-source-retention.spec.ts b/packages/person-memory/tests/sqlite-source-retention.spec.ts new file mode 100644 index 000000000..2c307e913 --- /dev/null +++ b/packages/person-memory/tests/sqlite-source-retention.spec.ts @@ -0,0 +1,27 @@ +import { createHash } from "node:crypto"; + +import { SQLiteDriver } from "@minatojs/driver-sqlite"; +import { Context } from "koishi"; +import { expect, it } from "vitest"; + +import { PersonStore, registerModels } from "../src/store"; +it("retention leaves the actual WASM SQLite driver usable after 2000 expired sources", async (t) => { + const ctx = new Context(); + ctx.plugin(SQLiteDriver, { path: ":memory:" }); + registerModels(ctx); + await ctx.start(); + await ctx.database.prepared(); + t.onTestFinished(() => ctx.stop()); + const timestamp = Date.now() - 8 * 86400000; + for (let i = 0; i < 2200; i++) + await ctx.database.create("person_memory.sources", { + key: createHash("sha256").update(String(i)).digest("hex"), + scope: "mind:a", + userId: "u", + timestamp: timestamp + i, + source: { id: String(i), userId: "u", name: "u", text: "old", timestamp: timestamp + i }, + }); + await new PersonStore(ctx.database, "review").capture("mind:a", { id: "fresh", userId: "u", name: "u", text: "new", timestamp: Date.now() }); + expect(await ctx.database.get("person_memory.sources", { scope: "mind:a" })).toHaveLength(201); + expect((await ctx.database.get("person_memory.sources", { scope: "mind:a" })).some((row) => row.source.id === "fresh")).toBe(true); +}); diff --git a/packages/sticker-manager/src/service.ts b/packages/sticker-manager/src/service.ts index 95cc76429..eb3c0a844 100644 --- a/packages/sticker-manager/src/service.ts +++ b/packages/sticker-manager/src/service.ts @@ -157,7 +157,7 @@ export class StickerService { // 使用分类列表替换模板中的占位符 const prompt = this.config.classificationPrompt.replace("{{categories}}", categoryList); - const model = this.ctx.yesimbot.model.getChatModel(this.config.classifiModel.providerName, this.config.classifiModel.modelId); + const model = this.ctx.yesimbot.model.useChatModel(this.config.classifiModel.providerName, this.config.classifiModel.modelId); if (!model || !model.isVisionModel()) { this.ctx.logger.error(`当前模型组中没有支持多模态的模型。`); diff --git a/packages/sticker-manager/tests/resilience.spec.ts b/packages/sticker-manager/tests/resilience.spec.ts index ea7603697..107d76ff3 100644 --- a/packages/sticker-manager/tests/resilience.spec.ts +++ b/packages/sticker-manager/tests/resilience.spec.ts @@ -29,7 +29,7 @@ async function fixture(chat: (options: any) => Promise) { asset: { read: async (_id: string, options: any) => (options.format === "buffer" ? Buffer.from("image") : "data:image/jpeg;base64,aW1hZ2U="), }, - model: { getChatModel: () => ({ isVisionModel: () => vision, chat }) }, + model: { useChatModel: () => ({ isVisionModel: () => vision, chat }) }, }), }; const service = new StickerService(ctx, { storagePath, classifiModel: { providerName: "test", modelId: "test" }, classificationPrompt: "{{categories}}" }); diff --git a/scripts/verify-packages.js b/scripts/verify-packages.js index 8e0ab9f51..88ecd15cb 100644 --- a/scripts/verify-packages.js +++ b/scripts/verify-packages.js @@ -29,6 +29,7 @@ try { "--no-audit", "--no-fund", "@koishijs/plugin-database-memory@^3.7.0", + "@koishijs/plugin-mock@^2.6.6", ...tarballs.map((name) => path.join(artifacts, name)), ], { diff --git a/scripts/verify-runtime.js b/scripts/verify-runtime.js index 8c9166800..3b819926f 100644 --- a/scripts/verify-runtime.js +++ b/scripts/verify-runtime.js @@ -7,7 +7,7 @@ const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); const os = require("node:os"); const repoRequire = require; -const { Context, Service } = repoRequire("koishi"); +const { Context, Service, Logger } = repoRequire("koishi"); const plugin = repoRequire("koishi-plugin-yesimbot"); const packageFile = repoRequire.resolve("koishi-plugin-yesimbot/package.json"); const manifest = repoRequire(packageFile); @@ -20,6 +20,10 @@ assert.equal(typeof plugin.withUsageScope, "function", "Root must export model u assert.equal(typeof plugin.withReplyTurn, "function", "Root must export reply scopes"); assert.strictEqual(plugin.withUsageScope, imported.withUsageScope, "ESM and CJS roots must share model usage scopes"); assert.strictEqual(plugin.withReplyTurn, imported.withReplyTurn, "ESM and CJS roots must share reply scopes"); +for (const name of ["registerHistoryResetParticipant", "prepareHistoryReset"]) { + assert.equal(typeof plugin[name], "function", `Root must export ${name}`); + assert.strictEqual(plugin[name], imported[name], `ESM and CJS roots must share ${name}`); +} const memory = repoRequire("@koishijs/plugin-database-memory"); const errors = []; class Console extends Service { @@ -49,6 +53,130 @@ class Server extends Service { super(ctx, "server", true); } } +async function verifyHistoryResetRuntime(sharedMemory) { + const { default: Loader } = repoRequire("@koishijs/loader"); + const person = repoRequire("koishi-plugin-yesimbot-extension-person-memory"); + const mock = repoRequire("@koishijs/plugin-mock"); + const directory = await fs.mkdtemp(path.join(os.tmpdir(), "yib-installed-reset-")); + let app; + try { + const filename = path.join(directory, "koishi.json"); + await fs.writeFile( + filename, + JSON.stringify({ + plugins: { + "console:runtime": {}, + "notifier:runtime": {}, + "server:runtime": {}, + "http:runtime": {}, + "database-memory:runtime": {}, + "mock:runtime": {}, + "yesimbot:runtime": { + version: "2.0.1", + coreMemoryPath: path.join(directory, "memory"), + storagePath: path.join(directory, "assets"), + image: { processedCachePath: path.join(directory, "cache") }, + allowedChannels: [{ platform: "mock", type: "guild", id: "reset-room" }], + providers: [ + { + name: "smoke", + type: "OpenAI", + baseURL: "http://127.0.0.1:9/v1", + apiKey: "unused", + models: [{ modelId: "smoke", abilities: ["对话", "嵌入"] }], + }, + ], + modelGroups: [{ name: "smoke", models: [{ providerName: "smoke", modelId: "smoke" }] }], + task: { chat: "smoke", embed: "smoke" }, + decisionRecording: { enabled: false }, + l2_memory: { enabled: false }, + l3_memory: { enabled: false }, + }, + "person-memory:runtime": { enabled: true, mode: "review", sharedMemory, memoryDomain: "packaged-smoke", modelGroup: "" }, + }, + }), + ); + const loader = new Loader(); + // NodeLoader normally lives inside the CLI daemon. This standalone smoke + // test also stops its root app, disposing the logger service before all + // loader unload callbacks. Keep a real Logger alive through that teardown. + const loaderLogger = new Logger("loader"); + loader.logUpdate = (type, _parent, key) => loaderLogger.info("%s plugin %c", type, key); + await loader.init(filename); + const modules = { + console: Console, + notifier: Notifier, + server: Server, + http: Http, + "database-memory": memory, + mock, + yesimbot: plugin, + "person-memory": person, + }; + const originalImport = loader.import.bind(loader); + loader.import = (name) => (name in modules ? Promise.resolve(modules[name]) : originalImport(name)); + // This test owns the temporary loader lifecycle; unloading must not ask a + // CLI daemon to restart the package-verification process. + loader.fullReload = () => {}; + await loader.readConfig(); + app = await loader.createApp(); + await app.start(); + await app.database.prepared(); + assert.ok(app.yesimbot, "Real loader did not construct the core"); + await app.yesimbot.ready; + assert.ok(app.yesimbot.isReady, "Real loader core was not ready"); + assert.ok(app.$commander.get("people.create"), "Real person plugin did not register its command"); + const owner = Object.getOwnPropertyDescriptor(app.yesimbot, "ctx").value; + for (const [register, prepare] of [ + [imported.registerHistoryResetParticipant, plugin.prepareHistoryReset], + [plugin.registerHistoryResetParticipant, imported.prepareHistoryReset], + ]) { + let fenced = 0, + released = 0; + const unregister = register(owner.extend(), { + prepare() { + fenced++; + return { + release() { + released++; + }, + }; + }, + }); + try { + const reset = prepare(owner, { type: "all" }); + assert.equal(fenced, 1, "Cross-format reset must fence the same registry synchronously"); + await reset.ready; + await reset.finish(); + await reset.finish(); + assert.equal(released, 1, "Cross-format reset release must be idempotent"); + } finally { + unregister(); + } + } + await app.mock.initUser("reset-admin", 3); + await app.mock.initChannel("reset-room"); + const client = app.mock.client("reset-admin", "reset-room"); + const marker = `packaged-${sharedMemory ? "shared" : "scene"}-person`; + const created = (await client.receive(`people.create ${marker}`)).join("\n"); + assert.ok(created.includes(marker), "Real person command failed before reset"); + const containsMarker = (rows) => rows.some((row) => Object.values(row.state?.people ?? {}).some((person) => person.name === marker)); + assert.ok(containsMarker(await app.database.get("person_memory.state", {})), "Person fixture must be persisted before clear"); + const cleared = (await client.receive("history.clear -a all")).join("\n"); + assert.match(cleared, /清除|清理/, "Real history clear command did not return a receipt"); + assert.equal( + containsMarker(await app.database.get("person_memory.state", {})), + false, + "Packaged core history.clear must purge the owning real person plugin state", + ); + assert.deepEqual(errors, [], "Real core/person loader emitted an initialization error"); + console.log(`Built core/person reset verified through real loader (${sharedMemory ? "shared" : "scene"})`); + } finally { + await app?.stop(); + await fs.rm(directory, { recursive: true, force: true }); + } +} + (async () => { const directory = await fs.mkdtemp(path.join(os.tmpdir(), "yib-installed-boot-")); const ctx = new Context(); @@ -71,9 +199,10 @@ class Server extends Service { ], modelGroups: [{ name: "smoke", models: [{ providerName: "smoke", modelId: "smoke" }] }], task: { chat: "smoke", embed: "smoke" }, + coreMemoryPath: path.join(directory, "memory"), storagePath: path.join(directory, "assets"), image: { processedCachePath: path.join(directory, "cache") }, - behavior: { decisionRecording: { enabled: false } }, + decisionRecording: { enabled: false }, l2_memory: { enabled: false }, l3_memory: { enabled: false }, }); @@ -127,6 +256,8 @@ class Server extends Service { await fs.rm(directory, { recursive: true, force: true }); } console.log("Built core unloaded"); + await verifyHistoryResetRuntime(false); + await verifyHistoryResetRuntime(true); })().catch((error) => { console.error(error); process.exitCode = 1; diff --git a/yarn.lock b/yarn.lock index c3c458ce8..a6093c510 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1462,6 +1462,37 @@ __metadata: languageName: node linkType: hard +"@minatojs/driver-sqlite@npm:^4.7.0": + version: 4.7.0 + resolution: "@minatojs/driver-sqlite@npm:4.7.0" + dependencies: + "@minatojs/sql-utils": "npm:^5.6.0" + "@minatojs/sql.js": "npm:^3.1.0" + cosmokit: "npm:^1.6.3" + peerDependencies: + minato: ^3.7.0 + checksum: 10c0/ef1059ba9a921e1c5739027f74f2e4b661755f11e9649138c14cfe55fc25de884e26fb204a9fac1dafa5b64a4a6f6f2606c680601dc41fc5e6f2b3b59f459b2a + languageName: node + linkType: hard + +"@minatojs/sql-utils@npm:^5.6.0": + version: 5.6.0 + resolution: "@minatojs/sql-utils@npm:5.6.0" + dependencies: + cosmokit: "npm:^1.6.3" + peerDependencies: + minato: ^3.7.0 + checksum: 10c0/7b97a6ce110e74d2b1d906bf34b79c5fcd784de49da7fb7172595ae695a694db2b7d6e54d224dd17256cc30cf58a669d041bfe37ea365148d54a50b68a247962 + languageName: node + linkType: hard + +"@minatojs/sql.js@npm:^3.1.0": + version: 3.1.0 + resolution: "@minatojs/sql.js@npm:3.1.0" + checksum: 10c0/3a61cd868d848a008d89ccdf27411a392d690831b6c5508dd04d84bf002bbfb2e1934e8979b0f6c14ab16523b708bff2fdb7004e564dbe186d7812f1c383f066 + languageName: node + linkType: hard + "@modelcontextprotocol/sdk@npm:^1.13.0": version: 1.32.1 resolution: "@modelcontextprotocol/sdk@npm:1.32.1" @@ -3406,7 +3437,6 @@ __metadata: dependencies: koishi: "npm:^4.18.7" koishi-plugin-yesimbot: "npm:^3.0.2" - pyodide: "npm:0.28.2" peerDependencies: koishi: ^4.18.7 koishi-plugin-yesimbot: ^3.0.2 @@ -6157,7 +6187,9 @@ __metadata: dependencies: "@koishijs/plugin-database-memory": "npm:^3.7.0" "@koishijs/plugin-mock": "npm:^2.6.6" + "@minatojs/driver-sqlite": "npm:^4.7.0" koishi: "npm:^4.18.7" + minato: "npm:^3.7.0" peerDependencies: koishi: ^4.18.7 koishi-plugin-yesimbot: ^3.0.4 @@ -7454,15 +7486,6 @@ __metadata: languageName: node linkType: hard -"pyodide@npm:0.28.2": - version: 0.28.2 - resolution: "pyodide@npm:0.28.2" - dependencies: - ws: "npm:^8.5.0" - checksum: 10c0/751260ca329ee45665ed61c77f5ad278d8f17248e57a0a560171ed77a238286eec0bfa4ab96993dbc052f3ae9fa0126b4fda96f608cace35de1a2976d4199b26 - languageName: node - linkType: hard - "qface@npm:^1.4.1": version: 1.4.1 resolution: "qface@npm:1.4.1" @@ -9114,7 +9137,7 @@ __metadata: languageName: node linkType: hard -"ws@npm:^8.16.0, ws@npm:^8.18.0, ws@npm:^8.5.0": +"ws@npm:^8.16.0, ws@npm:^8.18.0": version: 8.22.0 resolution: "ws@npm:8.22.0" peerDependencies: