Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .github/workflows/dependency-audit.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: Review dependency advisories

on:
pull_request:
paths:
- "yarn.lock"
- "**/package.json"
- ".github/workflows/dependency-audit.yml"
schedule:
- cron: "21 3 * * 1"
workflow_dispatch:

permissions:
contents: read

jobs:
audit:
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
- run: corepack enable
- run: yarn install --immutable --mode=skip-build
- run: yarn npm audit --all --recursive --severity high
31 changes: 15 additions & 16 deletions docs/background-tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,30 +6,27 @@

在“执行策略 → 后台工具任务”中配置:

| 配置 | 行为 | 默认值 |
| ------------------------ | -------------------------------------------------- | ------------------------ |
| 启用 | 允许模型提交后台任务 | 关闭 |
| 允许后台执行的工具 | 勾选模型可提交后台的工具;取消勾选不影响普通调用 | 搜索、网页读取、图片描述 |
| 任务完成处理方式 | 下轮对话读取,或完成后进行正常回复意愿判断 | 下轮读取 |
| 完成意愿结算单位 | 每任务,或同轮对话提交的全部后台任务结束后统一结算 | 按对话轮次聚合 |
| 成功、失败、取消意愿增量 | 分别设置非负数,可为零和小数 | 均为 0 |
| 并发上限 | 当前插件实例最多同时执行多少后台任务 | 4 |
| 保留任务上限 | 包括执行中与已结束任务;优先淘汰可清理的旧结果 | 128 |
| 执行超时 | 到期请求取消 | 120 秒 |
| 配置 | 行为 | 默认值 |
| ------------------ | ------------------------------------------------ | ------------------------ |
| 启用 | 允许模型提交后台任务 | 关闭 |
| 允许后台执行的工具 | 勾选模型可提交后台的工具;取消勾选不影响普通调用 | 搜索、网页读取、图片描述 |
| 并发上限 | 当前插件实例最多同时执行多少后台任务 | 4 |
| 保留任务上限 | 包括执行中与已结束任务;优先淘汰可清理的旧结果 | 128 |
| 执行超时 | 到期请求取消 | 120 秒 |

“同轮对话”包括一次接话周期内的多次心跳,不是单次模型 HTTP 请求。聚合模式等待该周期不再提交任务且全部任务结束后结算一次;混合结果按失败优先、其次取消、否则成功分类。容量已满且没有可淘汰记录时,新提交会明确失败,不自动重试。
默认情况下,模型提交后台工具用于完成当前请求。同一接话周期内可能有多次模型调用;该周期结束并收到所需任务的结果后,插件安排一次续接,沿用原会话和原请求。完成续接仍受回复权限和禁言状态限制。成功、失败或取消均可作为结果交由模型处理。

意愿增量遵循既有上限与衰减,不重新计算来源消息的 @、引用、关键词或私聊加成。启用话题意愿时,会话增量只传递给下一次当前话题判断一次。完成后的回复仍受意愿判断、回复暂停、禁言和会话授权限制。
升级前保存的完成策略、结算单位和意愿增量设置不再参与调度。任务完成不会增加或消耗当前会话的回复意愿。

## 模型工具

- `background_task_start`:指定 `tool` 和 `params`,返回任务 ID;仅接受明确声明支持后台执行的工具。
- `background_task_start`:指定 `tool` 和 `params`,返回任务 ID。仅为后续对话预取资料时使用 `purpose: "prefetch"`,结果可查询,完成时保持静默;仅接受明确声明支持后台执行的工具。
- `background_task_query`:提供 `id` 读取状态及结果;省略 `id` 列出最近任务与可提交后台的工具名称。
- `background_task_cancel`:指定 `id` 请求取消。模型结合当前用户要求和提示词决定是否调用。

默认勾选 `web_search`、`fetch_webpage`、`get_image_description`,以各工具当前可用条件为准。可在复选列表中取消勾选或全部取消;新加载的第三方工具需要手动勾选。只有声明支持后台执行且已被勾选的工具才能提交后台。运行中撤销后台权限后,该任务不会再向会话提交结果或完成意愿。发送消息、修改配置及身份关联等工具不自动加入。第三方扩展可通过 `ToolMetadata.background` 或 `ToolDefinition.background` 显式声明支持;该声明仅适用于独立操作,不能替代每次调用的数据依赖判断。
默认勾选 `web_search`、`fetch_webpage`、`get_image_description`,以各工具当前可用条件为准。可在复选列表中取消勾选或全部取消;新加载的第三方工具需要手动勾选。只有声明支持后台执行且已被勾选的工具才能提交后台。运行中撤销后台权限后,该任务不会再向会话提交结果。发送消息、修改配置及身份关联等工具不自动加入。第三方扩展可通过 `ToolMetadata.background` 或 `ToolDefinition.background` 显式声明支持;该声明仅适用于独立操作,不能替代每次调用的数据依赖判断。

每次构建模型上下文会提供当前会话最近 8 项任务快照。快照只含状态、工具名称、时间及有长度限制的真实进度,不包含完整结果;完整结果需查询,过长结果继续使用分页读取工具。自定义提示词模板也会收到转义后的任务快照。结果与进度属于观察数据,不能视为系统指令。
普通对话构建模型上下文时会提供当前会话最近 8 项任务快照。快照只含状态、工具名称、时间及有长度限制的真实进度,不包含完整结果;完整结果需查询,过长结果继续使用分页读取工具。自定义提示词模板也会收到转义后的任务快照。结果与进度属于观察数据,不能视为系统指令。

## 管理与取消

Expand All @@ -41,7 +38,9 @@ tool.tasks <任务ID>
tool.tasks.cancel <任务ID>
```

任务状态包括执行中、取消中、成功、失败、已取消。“取消中”表示取消请求已发出,外部操作尚未确认结束。支持取消信号的工具会尽快退出;无法中止的外部请求仍占用并发位置,直至实际结束,其迟到结果不会恢复已取消任务。取消不能撤销已经发生的外部操作。
续接当前请求时只携带该请求的逐项结果摘要、原消息和发起人。并发已满时按会话轮流取出等待任务,同一会话先到先执行。排队时间计入超时。

任务状态包括排队中、执行中、取消中、成功、失败、已取消。“取消中”表示取消请求已发出,外部操作尚未确认结束。支持取消信号的工具会尽快退出;无法中止的外部请求仍占用并发位置,直至实际结束,其迟到结果不会恢复已取消任务。取消不能撤销已经发生的外部操作。

后台工具使用独立于前台回复的取消状态,不直接发送会话消息。任务完成后由当前会话接收结果并决定后续回复。历史清除、会话授权撤销、工具停用与插件停止会使相关结果失效;其他会话、机器人或插件实例不能读取或取消这些任务。

Expand Down
8 changes: 8 additions & 0 deletions docs/feature-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,11 @@ YesImBot 的基础对话、回复调度、聊天历史和 L1/L2/L3 记忆由核
- [上下文与用量查询](history-inspection.md)
- [记忆召回](memory-recall.md)
- [人物记忆](../packages/person-memory/README.md)

## 媒体访问与历史保留

模型和会话工具使用的媒体 ID 绑定到来源平台、机器人账号及会话。升级前的资产缺少归属,旧消息里的资产需要在原会话重新收到后才能用于识图或发送。公开资产链接由当前进程签发,有效期五分钟,进程重启会使旧链接失效。

联网工具的本地网页提取只读取静态 HTML。它限制下载大小,并禁止 HTML 在浏览器中运行脚本或发出子请求。旧配置里的动态提取参数已停用,可改用支持网页提取的托管搜索引擎。

自动过期清理需显式启用 `allowGlobalRetention`。共用同一数据库服务的实例保留天数不一致时,自动清理暂停。清理间隔为 0 时停用定时任务。历史数据库在多个进程或账号之间仍可共享,要求物理隔离的部署需要独立数据库。L3 自动日记仅处理当前实例已经观察且仍允许访问的会话,进程重启后需要重新观察会话。
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,18 @@
"oxfmt": "^0.66.0",
"oxlint": "^1.77.0",
"typescript": "^6.0.3",
"vite": "7.3.6",
"vite": "7.3.8",
"vitest": "4.1.10",
"yakumo": "^3.2.1",
"yakumo-client": "workspace:*",
"yakumo-esbuild": "^3.0.2",
"yakumo-tsc": "^3.0.1",
"yakumo-vitest": "^1.3.3"
},
"resolutions": {
"js-yaml@npm:4.1.0": "npm:4.3.2",
"tinypool@npm:2.1.0": "npm:2.1.2"
},
"lint-staged": {
"*.{ts,tsx,mjs,cjs,js,jsx}": [
"oxlint --fix",
Expand Down
1 change: 1 addition & 0 deletions packages/code-executor/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export interface Config {

export const SharedConfig: Schema<SharedConfig> = Schema.object({
dependenciesPath: Schema.path({ filters: ["directory"], allowCreate: true })
.hidden()
.default("data/code-executor/deps")
.description("JS/Python等引擎动态安装依赖的存放路径"),
// artifactsPath: Schema.path({ filters: ["directory"], allowCreate: true })
Expand Down
12 changes: 8 additions & 4 deletions packages/code-executor/src/executors/python/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { realpath, stat } from "node:fs/promises";

import { Context, Logger, Schema } from "koishi";
import { Context, Logger, Schema, type Session } from "koishi";
import { AssetService, replyTurnSignal, ToolDefinition, withInnerThoughts } from "koishi-plugin-yesimbot";

import { SharedConfig } from "../../config";
Expand Down Expand Up @@ -195,10 +195,10 @@ export class PythonExecutor implements CodeExecutor {
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),
execute: async ({ code, session }) => this.execute(code, session),
};
}
async execute(code: string): Promise<CodeExecutionResult> {
async execute(code: string, session?: Session): Promise<CodeExecutionResult> {
if (!this.isReady) return { status: "error", error: { name: "EnvironmentError", message: this.initializationError } };
const deadline = new AbortController();
const turn = replyTurnSignal();
Expand Down Expand Up @@ -230,7 +230,11 @@ export class PythonExecutor implements CodeExecutor {
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 });
const assetId = await this.assetService.create(
Buffer.from(artifact.content, "base64"),
{ filename: artifact.fileName },
{ signal, session },
);
signal.throwIfAborted();
artifacts.push({ assetId, fileName: artifact.fileName });
}
Expand Down
8 changes: 8 additions & 0 deletions packages/code2image/src/css-safety.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/** Escape every Unicode code point in a quoted CSS string, including '<'. */
export function cssString(value: string): string {
return Array.from(value, (character) => `\\${character.codePointAt(0)!.toString(16)} `).join("");
}
export function boundedPixels(value: number, min: number, max: number): number {
if (!Number.isFinite(value) || value < min || value > max) throw new Error("Invalid rendering dimensions");
return value;
}
12 changes: 7 additions & 5 deletions packages/code2image/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import {} from "koishi-plugin-puppeteer";
import { Extension, Failed, Infer, Success, Tool, withInnerThoughts } from "koishi-plugin-yesimbot";
import type { BuiltinLanguage, BuiltinTheme, HighlighterCore } from "shiki";

import { cssString, boundedPixels } from "./css-safety";

// 使用 Logger 创建一个独立的日志记录器,便于区分插件日志
const logger = new Logger("code2image");

Expand Down Expand Up @@ -312,8 +314,8 @@ export default class CodeToImage {
const fontFaceStyles = Array.from(this.localFonts.entries())
.map(
([name, url]) => `@font-face {
font-family: "${name}";
src: url("file://${url}");
font-family: "${cssString(name)}";
src: url("${cssString(`file://${url}`)}");
}`,
)
.join("\n");
Expand All @@ -332,12 +334,12 @@ export default class CodeToImage {
height: fit-content;
}
.container {
padding: ${padding}px;
padding: ${boundedPixels(padding, 0, 512)}px;
}
pre {
margin: 0;
font-family: "${fontFamily}", monospace; /* 添加 monospace 作为备用 */
font-size: ${fontSize}px;
font-family: "${cssString(fontFamily)}", monospace; /* 添加 monospace 作为备用 */
font-size: ${boundedPixels(fontSize, 1, 256)}px;
line-height: 1.6;
}
</style>
Expand Down
13 changes: 13 additions & 0 deletions packages/code2image/tests/audit-css.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { expect, it } from "vitest";

import { cssString, boundedPixels } from "../src/css-safety";
it("cannot close a style tag or CSS string through font data", () => {
const encoded = cssString('font";}</style><script>fetch("file:///secret")</script>');
expect(encoded).not.toContain("<");
expect(encoded).not.toContain('"');
expect(encoded).not.toContain("}");
expect(encoded).toContain(String.fromCharCode(92) + "3c ");
});
it.each([NaN, Infinity, -1, 99999])("rejects nonfinite or excessive rendering dimensions %s", (value) => {
expect(() => boundedPixels(value, 1, 256)).toThrow("dimensions");
});
6 changes: 3 additions & 3 deletions packages/core/resources/templates/l1_history_item.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@
<observation>
<function>{{function}}</function>
<status>{{status}}</status>
{{#result}}
<result>{{#.}}{{_toString}}{{/.}}</result>
{{/result}}
{{#_hasToolResult}}
<result>{{_toolResultJson}}</result>
{{/_hasToolResult}}
{{#error}}
<error>{{.}}</error>
{{/error}}
Expand Down
22 changes: 13 additions & 9 deletions packages/core/src/agent/agent-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -424,8 +424,10 @@ export class AgentCore extends YesImBotService<Config> {
this.recordDecision(stimulus, { stage: "blocked", reason: "muted", success: false });
return;
}
this.cancelAssessment(channelCid);
this.willing.handlePreReply(channelCid);
if (stimulus.type !== "background_task_completion") {
this.cancelAssessment(channelCid);
this.willing.handlePreReply(channelCid);
}
success = await withReplyTurn(
valid,
async () => {
Expand Down Expand Up @@ -462,7 +464,12 @@ export class AgentCore extends YesImBotService<Config> {
}

const replyTopic = (stimulus as TracedStimulus).scoringTopic ?? (stimulus as TracedStimulus).topic;
if (success && valid() && (!replyTopic || this.topicScores.get(channelCid)?.has(replyTopic.scoreKey))) {
if (
stimulus.type !== "background_task_completion" &&
success &&
valid() &&
(!replyTopic || this.topicScores.get(channelCid)?.has(replyTopic.scoreKey))
) {
const scoreKey = replyTopic?.scoreKey ?? channelCid;
const willingnessBeforeReply = this.willing.getCurrentWillingness(scoreKey);
this.willing.handlePostReply(stimulus.session, scoreKey, 0, channelCid);
Expand Down Expand Up @@ -835,12 +842,9 @@ export class AgentCore extends YesImBotService<Config> {
return;
}
} else if (type === "background_task_completion") {
const completion = this.toolService?.background?.consumeCompletion(session, stimulus.payload);
if (!completion) return;
const result = this.willing.addBackgroundWillingness(session, channelCid, completion.gain);
const roll = completion.wake ? Math.random() : undefined;
decision = completion.wake && result.probability > (roll ?? 1);
this.recordDecision(stimulus, { stage: "calculated", decision, allowed, score: result.score, probability: result.probability, roll });
if (!this.toolService?.background?.consumeCompletion(session, stimulus.payload)) return;
decision = true;
this.recordDecision(stimulus, { stage: "calculated", decision, allowed, reason: "background_task_continuation" });
} else {
decision = true;
this.recordDecision(stimulus, { stage: "calculated", decision, allowed });
Expand Down
Loading
Loading