diff --git a/docs/design/agent-automation.md b/docs/design/agent-automation.md new file mode 100644 index 00000000..1b20550c --- /dev/null +++ b/docs/design/agent-automation.md @@ -0,0 +1,244 @@ +# Agent 自动化(定时任务) + +状态:设计稿,未实现。日期:2026-10-19。 + +权限部分建立在 [Agent 执行权限模型](agent-permission-model.md) 之上:自动化不定义自己的审批策略或白名单,只使用该模型的 `deferred` 运行模式、`automation` 作用域授权和 `ActingVia` 身份。权限模型的前三步是本需求的前置条件。 + +## 0. 已确认的决策 + +| 问题 | 决策 | +|---|---| +| 会话形态 | 两种都支持,由用户选择:每次运行新会话(默认),或一个自动化固定一个长期会话 | +| 需要确认的操作 | 运行模式为 `deferred`:挂起等待审批并通知;超过自动化配置的期限后放弃,本次运行记为失败 | +| 首版投递渠道 | 只做站内:运行历史 + 通知中心。IM 主动推送、出站 Webhook、邮件放到后续阶段 | +| 创建入口 | 设置页表单与助手对话创建都做,表单先行;助手创建复用同一服务接口和校验 | + +## 1. 目标与边界 + +用户定义一个“在什么时间、以谁的身份、让哪个 Agent 做什么”的自动化。到点后系统在后台无人值守地运行一轮 Agent 对话,结果持久化,并在站内通知创建者。运行中可以使用多 Agent 协作拆分任务,也可以在遇到需审批的写操作时挂起,等用户处理后继续。 + +第一版包含: + +- 触发方式为 cron 周期和一次性定时,支持时区;另提供手动“立即运行”。 +- 执行者为当前工作空间可用的 smart-reasoning Agent,或者内置助手。 +- 运行历史、运行详情(复用会话详情和子任务查看)、停止运行、暂停或恢复自动化。 +- 站内通知:运行成功、失败、等待审批、自动暂停。 +- 助手可通过 operations 创建和管理自动化,需要用户确认。 + +第一版不包含:事件触发(数据源同步完成、新文档、入站 Webhook 等)、IM 或 Webhook 或邮件投递、共享 Agent 跨租户执行、API Key 或 IM 用户作为自动化所有者、自动化之间的依赖编排(DAG)。 + +## 2. 现有能力与缺口 + +| 已有实现 | 复用方式 | 缺口 | +|---|---|---| +| `sessionService.AgentQA`,已被协作执行器、IM、MCP Server 在后台直接调用 | 作为一次运行的执行入口 | 各调用方重复实现“建消息对、挂事件流、监听完成、落库”,需要抽出统一的运行服务(见 §6) | +| 协作运行时 `internal/agent/collaboration`、`agent_collaborations` | 自动化的根 Agent 满足父任务条件时可直接 `spawn_agent`;持久化、租约、恢复、子审批转发不变 | 协作要求父任务具有 Web 用户身份,需要“以创建者身份运行”(§5.1) | +| `internal/datasource/scheduler.go`(`robfig/cron`,6 字段,含秒) | 复用表达式解析与校验 | 它在每个实例内存里注册 cron 并同时触发,依赖 Redis TaskID 去重;Lite 没有 Redis,也看不到重启期间错过的触发。自动化改用数据库驱动调度(§4) | +| HITL Broker:等待超时转为 `suspended` 并设置 `ExpiresAt`,reaper 回收过期 | 挂起等待审批 | 需要按自动化配置覆盖过期时间,并在挂起时发站内通知 | +| `Session.Kind`(`assistant`、`agent_delegated`) | 新增 `automation`,不进普通会话列表 | 会话列表和权限检查要识别新 kind | +| `types.WithPrincipal`、运行模式标记 | 构造后台运行身份和运行上下文 | 由权限模型合并为运行模式枚举并增加 `ActingVia`(权限模型 §2.3、§2.6) | +| 消息产物(artifact)与文件卡片 | 运行交付物 | 无 | +| `GlobalInvitationBell.vue` | 仅邀请通知 | 没有通用的站内通知中心,需要新建(§7) | +| 助手 operations 目录 | 新增 automation 系列操作 | 无 | + +## 3. 数据模型 + +### 3.1 `automations` + +| 字段 | 说明 | +|---|---| +| `id, tenant_id, owner_user_id` | 所有者是创建者的账户 ID,不保存任何凭据 | +| `name, description, enabled` | | +| `agent_id` | 为空表示使用内置助手;非空时引用 `CustomAgent`,跟随模板更新 | +| `instruction` | 任务提示词,支持运行时变量(§5.4) | +| `trigger` | JSON:`{type: cron, expr, timezone}` 或 `{type: once, at, timezone}` | +| `session_mode` | `per_run`(默认)或 `persistent` | +| `persistent_session_id` | `persistent` 模式下的固定会话,首次运行时创建 | +| `carry_last_result` | `per_run` 模式下是否注入上次成功运行的结果摘要 | +| `misfire_policy` | `skip`(默认)或 `run_once`:停机或暂停期间错过的触发,最多补跑一次 | +| `overlap_policy` | `skip`(默认)或 `queue`:上一次还在运行时如何处理本次触发;`queue` 最多排队一个 | +| `access_level` | 执行档位,语义见权限模型 §2.2;默认 `confirm`,`auto_write` 必须显式选择;运行时仍受 Agent 与工作空间上限约束 | +| `approval_timeout` | 挂起等待审批的最长时间,默认 24 小时 | +| `limits` | JSON:单次运行最长时间、最大迭代数、token 上限 | +| `next_run_at, last_run_at, last_success_at` | 调度状态 | +| `consecutive_failures, paused_reason` | 连续失败计数与自动暂停原因 | +| `version` | CAS 版本 | +| `created_at, updated_at, deleted_at` | | + +索引:`(enabled, next_run_at)` 供调度扫描;`(tenant_id, owner_user_id)` 供列表。 + +### 3.2 `automation_runs` + +| 字段 | 说明 | +|---|---| +| `id, automation_id, tenant_id` | | +| `scheduled_at` | 计划触发时间;手动运行为发起时间 | +| `trigger_kind` | `schedule` / `manual` / `misfire` | +| `status` | 见 §4.3 | +| `session_id, user_message_id, assistant_message_id` | 本次运行对应的会话与消息 | +| `owner, lease_until` | 执行所有权,与协作运行时同一套 CAS 加租约语义 | +| `pending_prompt_id` | 挂起等待审批时的 prompt | +| `effective_config` | JSON:本次实际使用的 Agent、模型、知识库范围、工具集合摘要,用于排查 | +| `usage, error, started_at, finished_at` | | + +唯一约束:`(automation_id, scheduled_at, trigger_kind)`。PostgreSQL 和 SQLite 同时提供迁移,不使用仅 PostgreSQL 支持的锁语法。 + +保留策略:每个自动化保留最近 N 条运行记录(可配置,默认 200)。清理运行记录时同时清理 `per_run` 模式的会话;`persistent` 会话随自动化删除。 + +## 4. 调度 + +### 4.1 数据库驱动的领取 + +调度器每个实例每隔 tick(默认 15 秒)执行: + +1. 查询 `enabled = true AND next_run_at <= now` 的自动化,限制批量大小。 +2. 对每条记录在一个事务内:用 `version` 做 CAS,把 `next_run_at` 推进到下一次触发时间;插入一条 `queued` 的运行记录(唯一键冲突说明其他实例已领取,直接跳过)。 +3. 提交后投递执行。有 Redis 时走 asynq 新队列 `automation`;Lite 时走进程内执行器。投递只负责唤起,真正的执行权由运行记录上的 CAS 和租约决定。 +4. 另有一个扫描任务处理 `queued` 但长时间未被领取的运行记录,避免投递丢失。 + +这样多副本、Lite、重启三种情况行为一致,不依赖进程内 cron 表,也不依赖 Redis 去重。 + +### 4.2 时间计算 + +- 使用 `robfig/cron` 与数据源一致的 6 字段解析器,额外支持 `CRON_TZ=` 前缀或独立的 `timezone` 字段,统一按 IANA 时区计算后存 UTC。 +- 校验时计算并返回未来 3 次触发时间,表单与助手都向用户回显。 +- 最小触发间隔可由系统设置控制(默认 5 分钟),过密的表达式拒绝。 +- 一次性触发运行后自动 `enabled = false`。 +- 错过的触发:`skip` 直接推进到未来;`run_once` 插入一条 `trigger_kind = misfire` 的运行,再推进到未来,不逐个补跑。 + +### 4.3 运行状态 + +```text +queued → running → succeeded | failed | cancelled + ↘ awaiting_approval → running + ↘ needs_attention (进程崩溃时执行结果未知) +queued → skipped (重叠策略或自动化已暂停) +``` + +- `overlap_policy = skip`:领取时发现同一自动化有 `running` 或 `awaiting_approval` 的运行,则新运行记为 `skipped` 并记录原因。 +- 进程崩溃恢复与协作一致:`queued` 可重新领取;`awaiting_approval` 由审批回答恢复;普通 `running` 转为 `needs_attention`,不自动重放副作用。 +- 单次运行超过 `limits` 中的最长时间,取消执行,记为 `failed`。挂起等待审批的时间不计入执行时长,单独受挂起期限约束。 + +## 5. 执行 + +### 5.1 运行身份 + +- 运行前加载所有者,重新校验:账户有效、仍是工作空间成员、`agent_id` 仍可用、知识库与 MCP 的授权范围仍成立。任一失败则本次 `failed`,并将自动化暂停、写入 `paused_reason`、发通知。 +- 校验通过后构造上下文:`Principal{web_user, owner_user_id, ActingVia: "automation:"}`,租户与工作空间取自自动化记录。路由层按所有者鉴权,因此 operations 可用;根 Agent 满足协作父任务条件,可以 `spawn_agent`。审计日志通过 `ActingVia` 区分代为执行。 +- 子任务按权限模型 §2.5 处理:档位不超过父任务,继承本次运行的授权。 + +### 5.2 运行模式与授权 + +- 运行模式为 `deferred`(权限模型 §2.3):不注册 `ask_user`;需要 OAuth 的 MCP 返回错误,模型在结果中说明;信息不足时由模型在交付物中写明缺失项。 +- 每次调用由权限模型的 `Decide` 判断,自动化只提供两项输入:执行档位 `access_level`,以及 `automation` 作用域的长期授权。 +- 长期授权在创建或编辑自动化时产生:用户勾选“运行时无需确认”的写类工具及资源范围,通过与对话中相同的审批卡批准,写入授权表(权限模型 §2.4)。destructive 工具可以预先授权,但必须指定具体资源范围(例如某个知识库),在审批卡上与写类授权分开列出并标明不可撤销;`Always` 工具不能预先授权(权限模型 §2.4)。 +- `Decide` 返回 ask 时:照常进入 HITL,挂起运行,过期时间取 `approval_timeout`;运行记为 `awaiting_approval`,发站内通知,用户在运行详情(即自动化会话)里处理。审批卡上选择“本会话允许”时写入会话授权;如需对以后的运行也生效,在自动化设置里添加长期授权。 +- 子任务的 ask 通过协作已有的审批转发展示在自动化会话中,规则相同。 +- 所有者撤销长期授权或降低档位后,下一次调用立即生效。 +- 系统提示词追加一段自动化运行说明:当前没有用户在线;触发时间与运行编号;必须产出完整交付物;不要询问用户;遇到阻塞时如实说明。该说明通过运行时通知注入,不写进 Agent 模板。 + +### 5.3 会话形态 + +- `per_run`:每次运行新建 `kind = automation` 的会话,标题为“自动化名 · 触发时间”。`carry_last_result = true` 时,把上次成功运行的最终回答(按长度上限截断并标注)作为背景材料放进本次用户消息。跨运行不继承协作子实例。 +- `persistent`:所有运行写入同一会话,每次追加一对消息,沿用现有多轮历史与上下文压缩;同一会话上的执行由现有会话级互斥保证不并发;如果用户正在这个会话里手动对话,本次触发按 `overlap_policy` 跳过或排队。适合“和上次对比”这类场景,但上下文会持续增长,表单上需提示。 +- 两种模式的会话都不进普通会话列表,从自动化详情进入。 + +### 5.4 运行时变量 + +`instruction` 支持以下变量,运行时替换后作为用户消息: + +- `{{now}}`:本次触发时间(自动化时区) +- `{{last_run_at}}`、`{{last_success_at}}`:上次运行、上次成功时间;首次运行为空并给出说明 +- `{{run_id}}`、`{{automation_name}}` + +变量只做文本替换,不执行表达式。 + +### 5.5 护栏 + +- 每租户自动化数量上限、全局并发执行上限(与协作子任务的全局并发上限分开计数)。 +- 单次运行的 token、迭代次数与时长上限;超出即结束并记录。 +- 连续失败达到阈值(默认 3 次)自动暂停并通知。 +- 删除自动化时先停止进行中的运行,再按保留规则清理。 + +## 6. 统一运行服务 + +协作执行器、IM、MCP Server 现在各自实现了“创建用户与助手消息、挂事件流和实时运行标记、监听完成与错误事件、落库、清理挂起快照”。自动化是第四个后台调用方。实现自动化时先抽出 `AgentRunService`: + +- `Start(ctx, RunSpec)`:RunSpec 包含会话、查询、Agent 快照、运行模式、执行档位、身份(含 `ActingVia`)、审批委托钩子、限制;返回运行结果(最终回答、产物、usage、是否挂起)。 +- `Resume(ctx, prompt)`:审批恢复。 +- `Interrupt(ctx, session, message)`:停止。 + +协作执行器先迁移到该服务,以现有协作回归测试作为不回退的依据;IM 与 MCP Server 的迁移不在本需求范围内,可以后续单独做。 + +## 7. 站内通知中心 + +新增通用通知模型,不和邀请混用: + +- `notifications`:`id, tenant_id, user_id, kind, title, body, link, source_type, source_id, read_at, created_at`。 +- 首批类型:`automation.succeeded`、`automation.failed`、`automation.awaiting_approval`、`automation.paused`。 +- 每个自动化可配置“成功是否通知”(默认关闭,仅失败、等待审批、暂停时通知),避免高频任务刷屏。 +- 前端在顶栏铃铛合并展示邀请与通知;实时推送可先用轮询,后续再接 SSE。 + +后续增加 IM、Webhook、邮件时,作为通知的其他投递方式扩展,不改动运行模型。IM 需要先给 Adapter 增加可选的主动发送接口,现有 `SendReply` 必须基于一条收到的消息。 + +## 8. 接口与前端 + +API(均校验所有者或空间管理员权限): + +- `GET/POST /automations`,`GET/PUT/DELETE /automations/:id` +- `POST /automations/:id/pause`、`/resume`、`/run`(立即运行) +- `POST /automations/validate-trigger`:返回是否合法及未来 3 次触发时间 +- `GET /automations/:id/runs`、`GET /automation-runs/:id`、`POST /automation-runs/:id/cancel` +- `GET /notifications`、`POST /notifications/read` + +前端: + +- 自动化列表:名称、执行 Agent、触发描述、下次运行、最近状态、启用开关。 +- 编辑表单:Agent 选择、任务提示词(含变量提示)、触发方式(预设项“每天/每周/每月”加高级 cron)、时区、会话形态、执行档位、长期授权(勾选运行时无需确认的写类与 destructive 工具及资源范围;destructive 项单独分组、必须选择具体资源,保存时弹审批卡)、审批等待期限、限制、通知选项。 +- 运行历史与详情:详情直接打开自动化会话,复用现有消息流、子任务卡片、审批卡和产物抽屉。 + +## 9. 助手集成 + +operations 新增:`automation.list`、`automation.get`、`automation.create`、`automation.update`、`automation.pause`、`automation.resume`、`automation.run_now`、`automation.delete`。 + +- 写操作走现有 confirm 审批,审批卡展示人类可读的触发描述、未来 3 次触发时间、执行 Agent、执行档位和将要创建的长期授权。长期授权由用户在审批卡上批准,模型不能代为授予。 +- 模型负责把自然语言转换为 cron 和时区,服务端负责校验;模型不能设置所有者,所有者固定为当前用户。 +- 助手只读档位下只能列出和查看。 + +## 10. 实施顺序 + +0. **前置**:权限模型第 1–4 步(`Decide` 收敛、规则修正、授权统一、`ActingVia` 与 `deferred` 模式)。 +1. **运行基础**:两张表与迁移、`AgentRunService` 抽取并迁移协作执行器、数据库调度器(Redis 与 Lite 两种投递)、运行身份、`automation` 会话 kind、两种会话形态。 +2. **管理与可见性**:API、列表/表单/运行历史页面、立即运行与停止、护栏与自动暂停。 +3. **通知与审批闭环**:通知中心、挂起审批的通知与过期处理。 +4. **助手集成**:operations 与审批卡展示。 +5. **后续**:事件触发、IM 主动推送、出站 Webhook、邮件。 + +## 11. 验收场景 + +- 两个实例同时扫描到同一到期自动化,只产生一条运行记录、执行一次。 +- Lite 重启后,停机期间错过的触发按 `misfire_policy` 处理;`run_once` 只补跑一次。 +- 时区为 `Asia/Shanghai` 的“每天 9:00”在 UTC 服务器上按北京时间触发;跨夏令时时区的触发时间正确。 +- `overlap_policy = skip` 时,上一次未结束则本次记为 `skipped`。 +- 所有者被移出工作空间后,下一次运行失败,自动化暂停并通知;不以旧权限执行。 +- Agent 模板被删除后运行失败并给出明确原因。 +- 命中长期授权的写类工具不弹审批;未命中的挂起并通知,审批后从原轮次继续,只执行一次;超过 `approval_timeout` 后运行失败,迟到的审批不会恢复。 +- destructive 工具未在设置中预先授权时,运行时每次挂起询问,审批卡不提供“以后都允许”;在设置中对知识库 X 预先授权后,删除 X 中的文档直接执行,删除其他知识库中的文档仍挂起询问。 +- `Always` 工具(管理员要求每次审批的 MCP、技能安装)在设置中不可勾选,运行时每次挂起询问。 +- 撤销长期授权后,下一次运行中同一调用重新挂起询问。 +- 自动化运行中 `spawn_agent` 创建子任务,子任务继承本次运行的授权,档位不超过父任务,结果汇总进本次运行。 +- 审计日志中自动化执行的写操作带 `ActingVia = automation:`。 +- 运行中进程崩溃,运行转为 `needs_attention`,不重放已发生的工具调用。 +- `ask_user` 不可用;需要 OAuth 的 MCP 返回错误而不是卡住。 +- 超过时长或 token 上限时运行结束并记为失败;连续失败 3 次自动暂停。 +- `per_run` 与 `carry_last_result` 正确注入上次结果;`persistent` 模式多次运行写入同一会话,历史连续。 +- 自动化会话不出现在普通会话列表,其他用户无法访问。 +- 助手创建自动化时展示的触发时间与服务端计算一致;只读档位下无法创建。 +- 协作执行器迁移到 `AgentRunService` 后,现有协作、恢复、审批回归测试全部通过。 + +## 12. 待定问题 + +- 共享空间里,空间管理员能否查看或停用成员创建的自动化。 +- `persistent` 会话长期运行后的上下文压缩策略是否需要比普通会话更激进。 +- 通知中心是否需要按工作空间隔离展示。 +- 每租户数量与并发上限的默认值,以及是否放进系统设置页。 diff --git a/docs/design/agent-permission-model.md b/docs/design/agent-permission-model.md new file mode 100644 index 00000000..4c5a84af --- /dev/null +++ b/docs/design/agent-permission-model.md @@ -0,0 +1,245 @@ +# Agent 执行权限模型 + +状态:后端第 1–4 步已实现;`automation` 作用域与 `ActingVia` 已就绪,等待自动化需求接入;MCP 风险管理界面暂缓(§6)。日期:2026-10-19。实现与原设计的差异见 §7。 + +本文统一 Agent 运行时“哪些动作可以直接执行、哪些要用户确认、哪些拒绝”的判断。助手、多 Agent 协作尚未上线,借此机会收敛规则;自动化(`agent-automation.md`)直接建立在本模型之上,不再自带权限概念。 + +## 0. 已确认的决策 + +| 问题 | 决策 | +|---|---| +| 档位适用范围 | 从仅内置助手扩展到所有 smart-reasoning Agent | +| 普通 Agent 默认档位 | 等价 `auto_write`:MCP 仍只按租户逐工具开关审批,保持 #1173 已上线行为 | +| 助手默认档位 | 保持 `confirm`,受工作空间上限约束 | +| 文档组织 | 本文独立维护;自动化文档引用本文 | + +## 1. 现状 + +“这个工具调用要不要等用户”目前由多处各自判断: + +| 位置 | 作用对象 | 判断依据 | +|---|---|---| +| `operations.Access.NeedsApprovalFor` | 助手 operations 目录 | 风险等级 + 助手档位 | +| `tools.ConfirmedTool` | 助手直接调用的 Wiki 写工具 | 同上;非交互运行时直接拒绝 | +| `approval.Gate.NeedsApproval` | MCP 工具 | 租户逐工具 `MCPToolApproval.RequireApproval`;协作委托时被覆盖 | +| `hitl.Delegation.RequireApproval` | 协作子任务 | `Access != auto_write` 时子任务所有 MCP 调用都要审批 | +| `AgentCollaboration` 的工具过滤(`agent_collaboration.go`) | 模板子任务的其他写工具 | 非 `auto_write` 时直接报错,提示“需要在父对话审批” | +| `Interactive`、`Suspendable`、`WithUnattendedRun`、`WithMCPOAuthNonInteractive` | 运行模式 | 四个独立标记,由各工具分别解读 | + +由此产生的问题: + +1. **档位只作用于内置助手。** `GrantsOperationCatalog` 仅对 `BuiltinWeKnoraAssistantID` 成立;普通 Agent 无档位概念。 +2. **只读档位不覆盖 MCP。** `read_only` 只清空 operations 写操作、Wiki 可写范围和 `fill_page`;MCP 写工具仍只看租户开关。 +3. **父子规则不一致。** 同一用户、同一档位、同一 MCP 工具,父任务可能直接执行,子任务每次都要审批,包括只读查询。 +4. **MCP 没有风险分级。** 只有布尔开关,`confirm` 与 `auto_write` 对 MCP 没有意义;MCP 规范中的 `readOnlyHint` / `destructiveHint` 注解未被使用(`mark3labs/mcp-go` 已解析 `Tool.Annotations`)。 +5. **授权记忆单一。** `AllowInSession` 仅用于带 Grant 的 Wiki 写工具;MCP 审批无法记忆,子任务不继承,也没有可长期保留的授权。 +6. **身份只认在线 Web 用户。** operations 依赖 `OperationIdentityFromContext`;后台运行只能构造一个看起来在线的 Web 用户,审计无法区分。 + +## 2. 模型 + +权限分三层,前两层保持现状,第三层统一: + +1. **能力面**:Agent 能看到哪些工具。`allowed_tools`、MCP 启用开关、Skills、内置助手专属能力。不变。 +2. **资源权限**:此用户能碰哪些资源。路由层 RBAC、知识库可写范围、共享 Agent 只读。不变,且每次运行和恢复时以真实用户重新校验。 +3. **执行策略**:可用且有资源权限的动作,此刻能否不经确认直接执行。由唯一的决策函数给出: + +```go +Decide(ctx, Action) Decision // allow | ask | deny,附原因与命中的授权 +``` + +所有工具入口(operations、内置写工具、MCP、委托子任务)都调用它;除它之外不再有分散的审批判断。 + +### 2.1 动作描述 + +```go +type Action struct { + Kind string // operation | builtin | mcp + ID string // operation ID、工具名,或 mcp:/ + Risk Risk // read | probe | write | destructive + Always bool // 每次都确认,授权不可豁免 + Resource string // 规范化的资源范围,例如 knowledge_base:;无则为空 + Summary string // 审批卡展示 +} +``` + +授权键 = `Kind + ID + Resource`,用于匹配已有授权。 + +风险来源: + +| 动作类型 | 风险 | `Always` | +|---|---|---| +| operations | 目录中的 `Risk` | 目录中的 `AlwaysConfirm` | +| 内置写工具 | 现有 `assistantWriteToolRisk`,扩展到所有 Agent 的写工具 | 否 | +| MCP 工具 | 管理员逐工具配置;未配置时取注解:`readOnlyHint=true` → read,其余 → write | `RequireApproval=true` 映射为 `Always` | + +MCP 注解来自外部服务,只用作默认值,规则如下: + +- 管理员的显式配置(`mcp_tool_approvals.risk`)优先,destructive 只能由管理员设置。`destructiveHint` 不被采用:write 已经需要按档位确认,外部服务声明 destructive 只会让审批更严格,却无法区分声明是否可信,因此交给管理员判断。 +- 未显式配置时,生效风险取“本次声明的风险”和“历史观察到的最高风险”(`observed_risk`)中较高者。`observed_risk` 只升不降:服务把注解从 read 改为 write 立即生效;从 write 改回 read 不生效,需要管理员显式设为 read。这取代了原设计中的“降级需管理员确认”流程,无需额外的待确认状态。 + +### 2.2 档位 + +`AssistantAccessLevel` 更名为执行档位(类型名可保留,避免无谓的改动),适用于所有 smart-reasoning Agent: + +| 档位 | read / probe | write | destructive 或 `Always` | +|---|---|---|---| +| `read_only` | allow | 不注册 | 不注册 | +| `confirm` | allow | 命中授权则 allow,否则 ask | ask | +| `auto_write` | allow | allow | ask | + +生效档位 = min(用户本次选择,Agent 上限,工作空间上限)。 + +- 内置助手:沿用用户在面板选择的档位,默认 `confirm`。 +- 普通 Agent:Agent 配置新增执行档位上限,默认 `auto_write`;用户未选择时取该上限。因此在未调整配置的情况下,普通 Agent 的 MCP 仍只在 `RequireApproval=true`(即 `Always`)时审批,与现状一致。 +- `read_only` 在注册阶段移除写工具,包括 MCP 写工具和 Wiki 写工具;仍到达 `Decide` 的写操作(例如注册后风险变化)返回 deny,不再 ask。 +- 每个 Agent 的上限保存在 `CustomAgentConfig.AccessLevel`(空值即 `auto_write`),编辑界面可配置;内置助手使用工作空间的 `MaxAccessLevel`。 + +### 2.3 运行模式 + +四个标记合并为一个枚举,放在运行上下文中,由运行入口设置: + +| 模式 | 来源 | `ask` 的处理 | `ask_user` | MCP OAuth | +|---|---|---|---|---| +| `attended` | Web 对话、助手面板 | 弹审批卡;可挂起,刷新后恢复 | 可用 | 弹授权卡 | +| `deferred` | 自动化 | 挂起运行,写通知;用户在会话中处理后恢复 | 不注册 | 失败并说明 | +| `unattended` | API、嵌入渠道、IM 等无法处理卡片的渠道 | deny,附原因 | 不注册 | 失败并说明 | + +现有 IM 渠道保持 `unattended`;后续若 IM 支持审批卡,再单独切换。 + +### 2.4 授权 + +统一为一张表,替代现在依赖 `agent_prompts` 中 `AllowInSession` 响应的隐式查询: + +| 字段 | 说明 | +|---|---| +| `id, tenant_id, user_id` | 授权属于用户本人;`user_id` 是 `Principal.StorageID()` | +| `grant_key` | 授权键,见下文 | +| `label` | 审批卡上展示的授权范围,用于查看与撤销界面 | +| `scope` | `session` / `automation` | +| `scope_id` | 根会话 ID 或自动化 ID | +| `prompt_id` | 产生该授权的审批 | +| `binding_hash` | 仅 `automation`:授权前提的哈希,见下文失效规则 | +| `expires_at, revoked_at, created_at, updated_at, last_used_at` | | + +表为 `agent_grants`,唯一键为(`tenant_id, user_id, scope, scope_id, grant_key`);再次批准同一授权时复用该行并清除 `revoked_at`。授权键: + +- MCP 写工具:`mcp:/#<输入 schema 的 sha256 前 6 字节>`。服务改变工具参数后键随之变化,旧授权自然不再匹配。 +- Wiki 等内置写工具:沿用工具原有的 Grant(工具名 + 规范化的知识库范围)。 + +规则: + +- 可豁免的范围按作用域区分,`Always` 在任何作用域都不可豁免: + + | 风险 | `session` | `automation` | + |---|---|---| + | write | 可,运行中在审批卡上勾选“本会话允许” | 可,创建或编辑自动化时预先授权 | + | destructive | 不可 | 可,仅限创建或编辑自动化时预先授权,见下文 | + | 任意风险且 `Always` | 不可 | 不可 | + +- destructive 的自动化授权用于“每晚清理过期文档”这类必然包含删除的任务;没有它,这类自动化每次运行都会挂起。约束如下(尚未实现,随自动化需求一起实现,见 §4): + - 只能在自动化的设置表单中逐项勾选并通过审批卡批准;运行中的审批卡不提供“以后都允许”,模型也不能代为授予。 + - 必须指定资源范围:带资源的动作(例如知识库文档删除)按具体知识库授权,不能对“所有知识库”授权;MCP 工具没有资源概念,按工具加参数 schema 授权。 + - 审批卡把 destructive 授权与 write 授权分开列出并标明“不可撤销”,需要单独确认。 + - 授权表增加 `risk` 列,记录批准时动作的风险。授权只覆盖不高于该风险的调用:write 授权不会因为工具被调高为 destructive 而继续生效。 + - 失效规则与其他 `automation` 授权相同(§2.4 下文);撤销、过期或失效后,下一次运行在该调用处挂起询问。 + - 决策日志与审计照常记录;命中 destructive 授权的调用另记 `agent_granted_destructive`,方便事后排查。 +- `session`:审批卡上的“本会话内允许”,扩展到 MCP 写工具。`scope_id` 始终是**根会话** ID:根任务和委派子任务上批准的授权都写到根会话名下,子任务判断时按根会话匹配。授权随根会话结束,用户删除会话时一并清理。不设单独的协作作用域,原因是每次用户发新消息都会创建新的协作组并继承上一组的空闲子实例;授权如果跟随协作组,同一对话中每一轮都会重复询问。 +- `automation`:创建或编辑自动化时,用户通过同一种审批卡批准一组长期授权;自动化运行时只认这一作用域和本次运行会话内新产生的授权。接入时需注意:目前审批网关只按运行上下文中的一个 `GrantScope` 查询和写入。自动化入口不能直接把作用域设为 `automation`,否则运行中勾选的“本会话允许”会被写成长期授权;需要让网关同时查询 `automation` 作用域与本次运行会话的 `session` 作用域,运行中产生的授权只写入后者,长期授权只由设置表单写入。 +- 匹配时同时校验用户、租户、作用域、未过期、未撤销;资源范围必须完全匹配,不做前缀推断。 +- 授权只决定“要不要问”,不扩大能力面或资源权限:工具未注册、资源无写权限时,授权不起作用。 +- 提供查看与撤销接口;撤销立即对后续调用生效,不影响已执行的调用。 + +`automation` 授权不按时间定期过期(创建时可选过期时间,默认不过期),而是在授权前提变化时失效: + +- 执行 Agent 模板的工具集合、MCP 服务或提示词发生变化。授权保存 `binding_hash`(这些关键配置的哈希),运行时哈希不一致即视为失效; +- MCP 工具风险被调高,或工具参数 schema hash 变化(复用快照恢复中的 schema hash); +- 所有者角色降低、档位上限调低,或授权涉及资源的写权限被收回; +- 自动化连续 90 天没有运行。 + +失效的授权不删除,审批改为 ask 并附原因,自动化运行挂起并通知;用户重新批准时更新 `binding_hash`。实现方式: + +- `binding_hash` 由 `types.AutomationBinding{AgentID, Tools, MCPServiceIDs, SystemPrompt, OwnerRole, Ceiling}.Hash()` 计算,工具与服务顺序无关。由自动化运行入口计算后放入运行上下文的 `GrantScope`。 +- `AgentGrant.LapseAt` 给出失效原因:`changed`(binding 不一致)、`expired`、`idle`(90 天未使用)、`revoked`。前三种通过审批请求的 `grant_lapsed` 字段带到审批卡并显示说明;用户主动撤销的不提示。 +- MCP 工具被设为 `Always` 后不再可授权;风险调高为 destructive 后,`session` 授权和按 write 批准的 `automation` 授权都不再生效(目前由“destructive 不可授权”保证;实现 destructive 自动化授权时改由授权的 `risk` 列保证)。schema 变化通过授权键失效。 +- 资源写权限收回不需要单独处理:授权只决定要不要问,路由层仍以真实用户校验写权限。 + +接口: + +- `GET /api/v1/agent/grants?session_id=<根会话 ID>`:列出当前用户在该会话中的有效授权。 +- `DELETE /api/v1/agent/grants/:id`:撤销当前用户的一条授权,仅本人可撤销。 +- 前端在会话标题的“更多”菜单中提供“已允许的操作”列表与撤销按钮。 +- 删除会话时,随会话清理其 `session` 作用域的授权。 + +### 2.5 委派 + +- 删除 `Delegation.RequireApproval` 的一刀切规则和协作工具过滤里的档位分支。子任务以父任务的生效档位和根会话的 `session` 授权调用同一个 `Decide`。 +- 模板子任务的档位 = min(父任务生效档位,模板 Agent 的档位上限)。由助手发起(`AssistantParent`)或继承了助手配置的子任务,再受工作空间助手上限约束。 +- 模板子任务的写工具同样用 `ConfirmedTool` 包装,因此只读档位下的写调用以工具结果形式返回拒绝原因,而不是报错中断子任务。 +- 授权作用域放在运行上下文中(`types.WithGrantScope`),子任务继承父任务的根会话作用域;顶层运行未设置时取请求的 `GrantSessionID`,否则取本会话。 +- 子任务的 `ask` 仍由现有机制转发到父会话展示,审批归属、恢复、取消不变。 +- 父任务对已委派工作的 MCP 防重复检查(`delegated_call_in_progress`)保留,与本模型无关。 + +### 2.6 身份 + +`Principal` 增加可选字段 `ActingVia`,例如 `automation:`: + +- 路由层仍按该 Web 用户鉴权,operations 可以使用; +- `StorageID()` 不包含 `ActingVia`,因此授权、会话归属和 HITL 的 `UserID` 都仍属于该用户,用户本人可以回答挂起的审批; +- operations 派发时 `AuditAgentAction.ActingVia` 随请求带过去(派发会重建身份,不能依赖原 `Principal`);`types.ActingViaFromContext` 先取 `AuditAgentAction`,再取 `Principal`; +- 知识库活动审计在 `details.agent_acting_via` 中记录它,区分本人操作与代为执行。 + +### 2.7 审计 + +每次 `Decide` 的非 read 结果由 `policy.Record` 写结构化日志(`agent policy decision`),字段为 `agent_action`、`agent_risk`、`agent_always`、`agent_level`、`agent_mode`、`agent_verdict`,代为执行时另有 `agent_acting_via`。命中授权与产生审批另由审批网关记录日志。执行写操作时按现有审计日志记录。 + +## 3. 兼容与迁移 + +| 现有数据或行为 | 迁移 | +|---|---| +| `mcp_tool_approvals.require_approval` | 保留列,语义为 `Always`;新增 `risk` 列,可空,空值按注解推断 | +| 普通 Agent 的 MCP 行为 | 默认档位上限 `auto_write`,行为不变 | +| 助手的 operations、Wiki 写工具 | 档位规则不变 | +| 助手 `read_only` 下的 MCP 写工具 | 行为变化:不再注册(修正) | +| 协作子任务的只读 MCP | 行为变化:不再强制审批(修正) | +| 协作子任务的写类 MCP | 规则与父任务一致;父任务已有会话授权时子任务可直接执行 | +| 已有 `AllowInSession` 审批 | 不兼容:功能尚未上线,旧的会话内授权不迁移,用户再次批准即可 | +| `WithUnattendedRun`、`Interactive` 等 | 已删除,运行入口直接设置运行模式(`types.WithRunMode`,`QARequest.Mode`);未设置时按 `unattended` 处理 | + +## 4. 实施顺序 + +1. **行为不变的收敛**(已完成,`b2719331e`):新增 `internal/agent/policy`,含 `Risk`(`operations.Risk` 改为其别名)、`Action`、`Rules`、`Decide`、`Offered`。operations 审批、`ConfirmedTool`、MCP `Gate.NeedsApproval`、协作委托的 `RequireApproval` 与子任务工具过滤都改为调用 `Decide`,规则完全复刻现状:MCP 暂按 `auto_write` 档位加 `Always`(租户开关)与 `ForceAsk`(委托)判断;`read_only` 下仍到达的写操作返回 ask 而非 deny。现有测试未改断言全部通过。 +2. **规则修正与运行模式**(已完成,运行模式 `e97cd5bfb`,其余 `a65b2fde6`):MCP 风险分级与注解默认值;`read_only` 覆盖 MCP(注册阶段移除,`Decide` 增加 deny);删除委派一刀切;普通 Agent 档位上限配置;合并运行模式。运行模式从第 1 步移到这里,因为合并必然改变现有行为:非交互运行中,operations 与 `ConfirmedTool` 直接拒绝,MCP 审批却发出审批卡并等待至超时(IM 渠道即如此);`WithUnattendedRun` 目前没有生产调用方。 +3. **授权统一**(已完成,`a249d8a2d`):授权表、按根会话匹配的 `session` 作用域、审批卡“本会话允许”扩展到 MCP、查看与撤销界面。 +4. **身份与自动化接入**(已完成,`2e875cca4`):`ActingVia`、决策日志、`automation` 作用域的 binding 与失效原因。`deferred` 模式在第 2 步已实现。自动化需求只需在运行入口设置模式、`GrantScope` 与 `Principal.ActingVia`。 +5. **自动化授权接入**:后端已完成——授权表 `risk` 列;`policy.Pregrantable`(write 与 destructive,非 `Always`)决定是否生成授权键,`policy.Grantable`(仅 write)决定审批卡是否提供“本会话允许”,`policy.Covers` 保证授权不覆盖风险更高的调用;网关先查运行的 `GrantScope`,再查 `types.WithStandingGrantScope` 设置的长期作用域,运行中的批准只写入前者。自动化设置表单写入长期授权的接口与界面随自动化需求实现。 + +## 5. 验收场景 + +- 第一步完成后,现有所有审批相关测试不改断言即通过。 +- 助手 `read_only`:MCP 写工具、Wiki 写工具、operations 写操作均不出现在工具列表中;MCP 只读工具可用。 +- 助手 `confirm`:写类 MCP 弹审批卡,选择“本会话允许”后同会话同一工具同一资源范围不再询问,换资源范围再次询问;destructive 每次询问。 +- 普通 Agent 未改配置:MCP 审批行为与改造前完全一致。 +- 协作:父任务批准“本会话允许”后,子任务调用同一工具同一范围不再弹卡;子任务上批准的授权对父任务和兄弟任务同样生效;用户发下一条消息后(新协作组)续跑的子任务仍沿用这些授权;子任务调用只读 MCP 不弹卡;模板子任务的档位不超过父任务。 +- 自动化授权:执行模板的工具列表被他人修改后,下一次运行在对应调用处挂起并说明失效原因;重新批准后恢复;所有者降级或资源写权限收回后同样失效。 +- `Always` 的工具(含 `RequireApproval=true` 的 MCP、技能安装)在任何档位和授权下都询问。 +- destructive:对话中每次询问,审批卡不提供“本会话允许”;自动化中只有在设置里针对具体资源预先批准过才直接执行,换一个知识库仍挂起询问;工具从 write 调高为 destructive 后,原有 write 授权不再生效。 +- MCP 服务把工具注解从 read 改为 write,下一次调用立即按 write 处理;反向变化不生效,需管理员显式设为 read。 +- `unattended` 模式下 ask 直接拒绝并告诉模型原因;`deferred` 模式下挂起并产生通知。 +- 撤销授权后下一次调用重新询问;已执行的调用不受影响。 +- 审计日志中能区分用户本人与 `ActingVia` 的执行。 +- 授权不能让未注册的工具出现,也不能让无写权限的知识库变为可写。 + +## 6. 待定问题 + +- MCP 工具风险的管理界面放在现有 MCP 服务的工具列表中(`McpToolsList.vue`),还是单独的策略页。暂缓:后端已支持,`PUT /api/v1/mcp-services/:id/tool-approvals/:tool_name` 接受 `risk`(空字符串表示改回按注解推断),`GET` 返回显式配置的 `risk` 与 `observed_risk`;界面后续再定。 + +已决定:不设协作作用域,授权按根会话匹配(§2.4);`automation` 授权按前提变化失效,不按时间定期重新确认(§2.4);不新增“全部直接通过”的档位,`auto_write` 是最高档,destructive 只能通过自动化作用域按具体资源预先授权,`Always` 永不豁免(§2.4)。理由:`Always` 是管理员对具体工具的决定,用户档位不应覆盖它;Agent 读取的知识库、网页和 MCP 结果都可能带有注入指令,全开档位会让这类内容直接触发不可撤销的操作;需要放宽的单个 MCP 工具,管理员可以把它的风险调为 write。 + +## 7. 实现与原设计的差异 + +- MCP 注解只采用 `readOnlyHint`;destructive 只能由管理员设置;降级确认改为 `observed_risk` 只升不降(§2.1)。 +- `read_only` 下仍到达的写操作返回 deny(§2.2)。 +- `Decide` 保持为纯函数 `Decide(Action, Rules) Verdict`,`Action` 只含 `Risk` 与 `Always`;授权键由各工具生成并在审批网关匹配,而不是放进 `Action`。授权在运行模式检查之前匹配,因此 `unattended` 与 `deferred` 运行同样认可已有授权。 +- 授权表字段命名为 `grant_key`、`prompt_id`,另有 `label`、`updated_at`(§2.4)。 +- 旧的 `AllowInSession` 数据不兼容(§3)。 +- 模板子任务的写工具改为包装执行,只读档位的拒绝以工具结果返回(§2.5)。 diff --git a/frontend/src/api/agent/index.ts b/frontend/src/api/agent/index.ts index 954dfb57..6377f9d3 100644 --- a/frontend/src/api/agent/index.ts +++ b/frontend/src/api/agent/index.ts @@ -1,4 +1,5 @@ import { get, post, put, del } from "../../utils/request"; +import type { AssistantAccessLevel } from "../assistant"; // 智能体配置 // 智能推理下的智能体类型预设 ID @@ -63,6 +64,8 @@ export interface CustomAgentConfig { // 对话中触发 OAuth 授权时的等待超时(秒):到点后自动跳过授权提示。 // <=0 时使用服务端默认超时。仅对使用 OAuth 的 MCP 服务生效。 mcp_auth_wait_timeout?: number; + // 执行权限上限:修改数据的工具能否不经确认直接执行。未设置等同 auto_write。 + access_level?: AssistantAccessLevel; // ===== Skills设置(仅Agent模式)===== // Skills选择模式:all=全部预装, selected=指定, none=不使用 diff --git a/frontend/src/api/mcp-service.ts b/frontend/src/api/mcp-service.ts index df88f137..1563bd03 100644 --- a/frontend/src/api/mcp-service.ts +++ b/frontend/src/api/mcp-service.ts @@ -299,6 +299,28 @@ export async function resolveToolApproval( return { resumed: Boolean(res?.resumed) } } +// A remembered "allow for this conversation" approval. +export interface AgentGrant { + id: string + scope: string + scope_id: string + grant_key: string + label: string + created_at: string + last_used_at?: string +} + +// The current user's grants in a conversation, including those approved in +// its delegated sub-tasks. +export async function listAgentGrants(sessionId: string): Promise { + const res: any = await get(`/api/v1/agent/grants?session_id=${encodeURIComponent(sessionId)}`) + return Array.isArray(res?.data) ? res.data : [] +} + +export async function revokeAgentGrant(id: string): Promise { + await del(`/api/v1/agent/grants/${encodeURIComponent(id)}`) +} + // Answer a prompt the agent raised (ask_user, tool approval) with the kind's // response object. export async function resolveAgentPrompt( diff --git a/frontend/src/components/ChatHeader.vue b/frontend/src/components/ChatHeader.vue index 18f9084c..47055342 100644 --- a/frontend/src/components/ChatHeader.vue +++ b/frontend/src/components/ChatHeader.vue @@ -58,6 +58,10 @@ {{ t('menu.renameSession') }} + +
+
{{ t('chatHeader.grants.menu') }}
+
{{ t('chatHeader.grants.description') }}
+ +
{{ t('chatHeader.grants.empty') }}
+
    +
  • + {{ grant.label }} + +
  • +
+ +
+
{{ t('chatHeader.deleteConfirmTitle') }} @@ -101,6 +126,7 @@ import { useI18n } from 'vue-i18n' import { MessagePlugin } from 'tdesign-vue-next' import { copyToClipboard } from '@/utils/clipboard' import { getMessageList } from '@/api/chat' +import { listAgentGrants, revokeAgentGrant, type AgentGrant } from '@/api/mcp-service' import { removeSession, renameSession, @@ -120,7 +146,7 @@ interface ChatHeaderSession { host_workspace_dir?: string } -type MenuMode = 'menu' | 'delete' +type MenuMode = 'menu' | 'delete' | 'grants' const props = defineProps<{ session: ChatHeaderSession | null @@ -157,6 +183,39 @@ function enterConfirmMode(mode: 'delete'): void { menuMode.value = mode } +const grants = ref([]) +const grantsLoading = ref(false) +const revokingId = ref('') + +async function enterGrantsMode(): Promise { + const session = props.session + if (!session) return + menuMode.value = 'grants' + grants.value = [] + grantsLoading.value = true + try { + grants.value = await listAgentGrants(session.id) + } catch { + MessagePlugin.error(t('chatHeader.grants.loadFailed')) + } finally { + grantsLoading.value = false + } +} + +async function revokeGrant(grant: AgentGrant): Promise { + if (revokingId.value) return + revokingId.value = grant.id + try { + await revokeAgentGrant(grant.id) + grants.value = grants.value.filter((g) => g.id !== grant.id) + MessagePlugin.success(t('chatHeader.grants.revoked')) + } catch { + MessagePlugin.error(t('chatHeader.grants.revokeFailed')) + } finally { + revokingId.value = '' + } +} + function backToMenu(): void { if (busyAction.value) return menuMode.value = 'menu' @@ -420,6 +479,38 @@ async function submitDeleteSession(): Promise { word-break: break-word; } +.chat-header-grants { + display: flex; + flex-direction: column; + gap: 6px; + max-height: 240px; + margin: 0; + padding: 0; + overflow-y: auto; + list-style: none; +} + +.chat-header-grants__item { + display: flex; + align-items: center; + gap: 8px; +} + +.chat-header-grants__label { + flex: 1 1 auto; + min-width: 0; + overflow: hidden; + color: var(--td-text-color-primary); + font-size: var(--app-text-sm); + text-overflow: ellipsis; + white-space: nowrap; +} + +.chat-header-grants__empty { + color: var(--td-text-color-placeholder); + font-size: var(--app-text-sm); +} + .chat-header-confirm__footer { display: flex; justify-content: flex-end; diff --git a/frontend/src/composables/useChatStreamHandler.ts b/frontend/src/composables/useChatStreamHandler.ts index 01cf6549..4c22f8d3 100644 --- a/frontend/src/composables/useChatStreamHandler.ts +++ b/frontend/src/composables/useChatStreamHandler.ts @@ -126,6 +126,7 @@ export function pendingPromptEvents(prompt: unknown): ChatMessage[] { ? JSON.stringify(response.modified_args) : request.args === undefined ? '' : JSON.stringify(request.args), grant_scope: request.grant_scope, + grant_lapsed: request.grant_lapsed, tool_call_id: p.tool_call_id, requested_at: requestedAt, suspendable: true, @@ -985,6 +986,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) { delegated_task: d.delegated_task, args_json: d.args_json, grant_scope: d.grant_scope, + grant_lapsed: d.grant_lapsed, timeout_seconds: d.timeout_seconds, hot_wait_seconds: d.hot_wait_seconds, suspendable: d.suspendable, diff --git a/frontend/src/composables/useModalShell.test.ts b/frontend/src/composables/useModalShell.test.ts index 86e79ab7..53ba8fba 100644 --- a/frontend/src/composables/useModalShell.test.ts +++ b/frontend/src/composables/useModalShell.test.ts @@ -53,6 +53,7 @@ function fixture() { useDeploymentCapabilitiesStore: () => ({ isSupported: () => true, async ensureLoaded() {} }), }, '@/api/agent': { listIMChannels: async () => ({ data: [] }) }, + '@/api/assistant': { ASSISTANT_ACCESS_LEVELS: ['read_only', 'confirm', 'auto_write'] }, '@/api/embed': { listEmbedChannels: async () => ({ data: [] }) }, '@/api/skill': {}, '@/api/system': { isNamedSandboxBackend: () => true }, diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index cdd8faa2..cf6b0ef0 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -353,6 +353,15 @@ export default { noSessions: 'No conversations yet' }, chatHeader: { + grants: { + menu: 'Allowed actions', + description: 'Actions allowed for this conversation without asking again. Revoke one to be asked next time.', + empty: 'No allowed actions yet', + revoke: 'Revoke', + revoked: 'Revoked', + revokeFailed: 'Failed to revoke', + loadFailed: 'Failed to load', + }, moreActions: 'More conversation actions', toggleSandboxPanel: 'Sandbox terminal', copySessionId: 'Copy Session ID', @@ -6477,6 +6486,11 @@ export default { argsLabel: 'Arguments', argsModified: 'Modified', allowInSession: 'Allow this for the rest of the conversation', + grantLapsed: { + changed: 'Your earlier approval no longer applies: the automation\'s agent setup, your role or the access ceiling changed.', + expired: 'Your earlier approval has expired.', + idle: 'Your earlier approval lapsed after a long time unused.', + }, countdownShort: '{seconds}s', approve: 'Approve & run', reject: 'Reject', @@ -7313,6 +7327,8 @@ export default { authWaitTimeout: 'Authentication Wait Timeout (s)', authWaitTimeoutDesc: 'Maximum seconds to wait for you to complete OAuth authentication when prompted during a conversation; the prompt is skipped after it elapses (only affects OAuth MCP services).', authWaitTimeoutPlaceholder: 'Default 600 seconds', + accessLevel: 'Access level', + accessLevelDesc: 'Whether tools that change data (MCP tools, Wiki writes) run without asking. Read-only leaves them out; confirm asks you each time. MCP tools marked as requiring approval always ask.', unavailableService: 'Unavailable service' }, llmCallTimeout: { diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts index 9019bc4e..44e0a409 100644 --- a/frontend/src/i18n/locales/ja-JP.ts +++ b/frontend/src/i18n/locales/ja-JP.ts @@ -353,6 +353,15 @@ export default { noSessions: '会話はまだありません' }, chatHeader: { + grants: { + menu: '許可済みの操作', + description: 'この会話で確認なしに許可された操作です。取り消すと次回また確認されます。', + empty: '許可済みの操作はありません', + revoke: '取り消す', + revoked: '取り消しました', + revokeFailed: '取り消しに失敗しました', + loadFailed: '読み込みに失敗しました', + }, moreActions: 'その他の会話操作', toggleSandboxPanel: 'サンドボックスターミナル', copySessionId: 'セッションIDをコピー', @@ -6477,6 +6486,11 @@ export default { argsLabel: '引数', argsModified: '変更あり', allowInSession: 'この会話では同様の操作をすべて許可', + grantLapsed: { + changed: '以前の許可は無効になりました。自動化の Agent 設定、ロール、または権限上限が変更されました。', + expired: '以前の許可は期限切れです。', + idle: '以前の許可は長期間使われなかったため無効になりました。', + }, countdownShort: '{seconds}秒', approve: '承認して実行', reject: '拒否', @@ -7313,6 +7327,8 @@ export default { authWaitTimeout: '認証待機タイムアウト(秒)', authWaitTimeoutDesc: '会話中にOAuth認証を求められた際、完了を待機する最大秒数です。この時間を過ぎると、認証の確認は自動的にスキップされます(OAuthを使用するMCPサービスのみに影響します)。', authWaitTimeoutPlaceholder: 'デフォルト600秒', + accessLevel: '実行権限の上限', + accessLevelDesc: 'データを変更するツール(MCP ツール、Wiki への書き込み)を確認なしで実行できるかどうか。読み取り専用ではこれらのツールを提供せず、変更前に確認では毎回確認します。承認が必要と設定された MCP ツールは常に確認します。', unavailableService: '利用できないサービス' }, llmCallTimeout: { diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 4a37c486..869578fd 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -1377,6 +1377,8 @@ export default { authWaitTimeout: '인증 대기 시간(초)', authWaitTimeoutDesc: '대화 중 OAuth 인증이 필요할 때 인증 완료를 기다리는 최대 시간(초)이며, 초과하면 인증 요청을 건너뜁니다(OAuth를 사용하는 MCP 서비스에만 적용).', authWaitTimeoutPlaceholder: '기본 600초', + accessLevel: '실행 권한 상한', + accessLevelDesc: '데이터를 변경하는 도구(MCP 도구, Wiki 쓰기)를 확인 없이 실행할지 여부입니다. 읽기 전용이면 이러한 도구를 제공하지 않고, 변경 전 확인이면 매번 확인을 요청합니다. 승인이 필요하도록 표시된 MCP 도구는 항상 확인합니다.', unavailableService: '사용할 수 없는 서비스' }, agentType: { @@ -2183,6 +2185,11 @@ export default { argsLabel: '인수', argsModified: '수정됨', allowInSession: '이 대화에서 같은 작업은 모두 허용', + grantLapsed: { + changed: '이전 허용이 더 이상 적용되지 않습니다. 자동화의 Agent 설정, 역할 또는 권한 상한이 변경되었습니다.', + expired: '이전 허용이 만료되었습니다.', + idle: '이전 허용이 오랫동안 사용되지 않아 만료되었습니다.', + }, countdownShort: '{seconds}초', approve: '승인 후 실행', reject: '거부', @@ -8301,6 +8308,15 @@ export default { } }, chatHeader: { + grants: { + menu: '허용된 작업', + description: '이 대화에서 다시 묻지 않도록 허용된 작업입니다. 취소하면 다음에 다시 묻습니다.', + empty: '허용된 작업이 없습니다', + revoke: '취소', + revoked: '취소되었습니다', + revokeFailed: '취소하지 못했습니다', + loadFailed: '불러오지 못했습니다', + }, moreActions: '대화 추가 작업', toggleSandboxPanel: '샌드박스 터미널', copySessionId: '세션 ID 복사', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 31d6d2f1..4aa8e18e 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -1377,6 +1377,8 @@ export default { authWaitTimeout: 'Тайм-аут ожидания аутентификации (с)', authWaitTimeoutDesc: 'Максимальное время ожидания (в секундах) завершения OAuth-аутентификации при запросе во время диалога; по его истечении запрос пропускается (влияет только на MCP-сервисы с OAuth).', authWaitTimeoutPlaceholder: 'Default 600 seconds', + accessLevel: 'Access level', + accessLevelDesc: 'Whether tools that change data (MCP tools, Wiki writes) run without asking. Read-only leaves them out; confirm asks you each time. MCP tools marked as requiring approval always ask.', unavailableService: 'Недоступный сервис' }, agentType: { @@ -2183,6 +2185,11 @@ export default { argsLabel: 'Аргументы', argsModified: 'Изменено', allowInSession: 'Разрешать такие действия до конца беседы', + grantLapsed: { + changed: 'Прежнее разрешение больше не действует: изменились настройки агента автоматизации, ваша роль или предел доступа.', + expired: 'Срок прежнего разрешения истёк.', + idle: 'Прежнее разрешение истекло: им долго не пользовались.', + }, countdownShort: '{seconds} с', approve: 'Подтвердить и выполнить', reject: 'Отклонить', @@ -8301,6 +8308,15 @@ export default { } }, chatHeader: { + grants: { + menu: 'Разрешённые действия', + description: 'Действия, разрешённые в этом диалоге без повторного запроса. После отзыва запрос появится снова.', + empty: 'Разрешённых действий пока нет', + revoke: 'Отозвать', + revoked: 'Отозвано', + revokeFailed: 'Не удалось отозвать', + loadFailed: 'Не удалось загрузить', + }, moreActions: 'Другие действия с диалогом', toggleSandboxPanel: 'Терминал песочницы', copySessionId: 'Копировать ID сессии', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 05361405..91bb0fc1 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -1379,6 +1379,8 @@ export default { authWaitTimeout: '授权等待超时(秒)', authWaitTimeoutDesc: '对话中触发 OAuth 授权时,等待你完成授权的最长秒数,超时后自动跳过授权提示(仅对使用 OAuth 的 MCP 服务生效)。', authWaitTimeoutPlaceholder: '默认 600 秒', + accessLevel: '执行权限上限', + accessLevelDesc: '修改数据的工具(MCP 工具、Wiki 写入)能否直接执行:只读时不提供这类工具,修改前确认时每次先征求你同意。被标记为需要审批的 MCP 工具始终需要确认。', unavailableService: '不可用服务' }, agentType: { @@ -2185,6 +2187,11 @@ export default { argsLabel: '调用参数', argsModified: '已修改', allowInSession: '本会话内同类操作都允许', + grantLapsed: { + changed: '之前的允许已失效:自动化的 Agent 配置、成员角色或权限上限已变化。', + expired: '之前的允许已过期。', + idle: '之前的允许因长期未使用已失效。', + }, countdownShort: '{seconds}s', approve: '通过并执行', reject: '拒绝', @@ -8302,6 +8309,15 @@ export default { } }, chatHeader: { + grants: { + menu: '已允许的操作', + description: '本对话中已允许、不再询问的操作。撤销后再次调用时会重新询问。', + empty: '暂无已允许的操作', + revoke: '撤销', + revoked: '已撤销', + revokeFailed: '撤销失败', + loadFailed: '加载失败', + }, moreActions: '更多对话操作', toggleSandboxPanel: '沙箱终端', copySessionId: '复制会话 ID', diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts index fef5be9c..bc9841a2 100644 --- a/frontend/src/i18n/locales/zh-TW.ts +++ b/frontend/src/i18n/locales/zh-TW.ts @@ -1379,6 +1379,8 @@ export default { authWaitTimeout: '授權等待超時(秒)', authWaitTimeoutDesc: '對話中觸發 OAuth 授權時,等待你完成授權的最長秒數,超時後自動跳過授權提示(僅對使用 OAuth 的 MCP 服務生效)。', authWaitTimeoutPlaceholder: '預設 600 秒', + accessLevel: '執行權限上限', + accessLevelDesc: '修改資料的工具(MCP 工具、Wiki 寫入)能否直接執行:唯讀時不提供這類工具,修改前確認時每次先徵求你同意。被標記為需要審批的 MCP 工具始終需要確認。', unavailableService: '不可用服務' }, agentType: { @@ -2185,6 +2187,11 @@ export default { argsLabel: '呼叫參數', argsModified: '已修改', allowInSession: '本會話內同類操作都允許', + grantLapsed: { + changed: '先前的允許已失效:自動化的 Agent 設定、成員角色或權限上限已變更。', + expired: '先前的允許已過期。', + idle: '先前的允許因長期未使用已失效。', + }, countdownShort: '{seconds}s', approve: '透過並執行', reject: '拒絕', @@ -8302,6 +8309,15 @@ export default { } }, chatHeader: { + grants: { + menu: '已允許的操作', + description: '本對話中已允許、不再詢問的操作。撤銷後再次呼叫時會重新詢問。', + empty: '暫無已允許的操作', + revoke: '撤銷', + revoked: '已撤銷', + revokeFailed: '撤銷失敗', + loadFailed: '載入失敗', + }, moreActions: '更多對話操作', toggleSandboxPanel: '沙箱終端', copySessionId: '複製會話 ID', diff --git a/frontend/src/views/agent/AgentEditorModal.vue b/frontend/src/views/agent/AgentEditorModal.vue index c5213aa9..c3b5c98a 100644 --- a/frontend/src/views/agent/AgentEditorModal.vue +++ b/frontend/src/views/agent/AgentEditorModal.vue @@ -1281,6 +1281,20 @@ theme="column" :placeholder="$t('agentEditor.mcp.authWaitTimeoutPlaceholder')" />
+ + +
+
+ +

{{ $t('agentEditor.mcp.accessLevelDesc') }}

+
+
+ + + +
+
@@ -1907,6 +1921,7 @@ import KBParserSettings, { type ParserEngineRule } from '@/views/knowledge/setti import AgentShareSettings from '@/components/AgentShareSettings.vue'; import { SKILL_ICON } from '@/types/mention'; import { listEmbedChannels } from '@/api/embed'; +import { ASSISTANT_ACCESS_LEVELS, type AssistantAccessLevel } from '@/api/assistant'; import { getRootZoom, rectToCssPx } from '@/utils/zoom'; import { integrationSectionKey } from '@/config/settingsRoute'; import { toolboxLocation } from '@/config/toolbox'; @@ -2892,6 +2907,8 @@ const defaultFormData = { mcp_services: [] as string[], // 对话中触发 OAuth 授权时的等待超时(秒),默认 600 mcp_auth_wait_timeout: 600, + // 执行权限上限,默认自动执行 + access_level: 'auto_write' as AssistantAccessLevel, // Skills 设置 skills_selection_mode: 'none' as 'all' | 'selected' | 'none', selected_skills: [] as string[], @@ -3634,6 +3651,7 @@ watch(() => props.visible, async (val) => { if (agentData.config.mcp_auth_wait_timeout == null || agentData.config.mcp_auth_wait_timeout <= 0) { agentData.config.mcp_auth_wait_timeout = 600; } + if (!agentData.config.access_level) agentData.config.access_level = 'auto_write'; if (!agentData.config.selected_skills) agentData.config.selected_skills = []; if (!agentData.config.supported_file_types) agentData.config.supported_file_types = []; if (!agentData.config.chat_parser_engine_rules) agentData.config.chat_parser_engine_rules = []; diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue index 23abf495..e7b69635 100644 --- a/frontend/src/views/chat/components/AgentStreamDisplay.vue +++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue @@ -124,7 +124,7 @@
diff --git a/frontend/src/views/chat/components/PendingPromptDock.vue b/frontend/src/views/chat/components/PendingPromptDock.vue index 223e8925..53190dec 100644 --- a/frontend/src/views/chat/components/PendingPromptDock.vue +++ b/frontend/src/views/chat/components/PendingPromptDock.vue @@ -32,7 +32,8 @@ + :delegated-task="prompt.delegated_task" :args-json="prompt.args_json" :grant-scope="prompt.grant_scope" + :grant-lapsed="prompt.grant_lapsed" />
+
{{ grantLapsedText }}
{{ $t('agentStream.toolApproval.allowInSession') }} {{ grantScope }} @@ -114,6 +115,8 @@ const props = defineProps<{ // grantScope, when set, offers to approve calls like this one for the // rest of the session and says which calls that covers. grantScope?: string + // grantLapsed is why an earlier "allow" for this call no longer applies. + grantLapsed?: string timeoutSeconds?: number requestedAt?: number resolved?: boolean @@ -159,6 +162,12 @@ const initialArgs = formatJson(props.argsJson || '{}') const argsText = ref(initialArgs) const argsExpanded = ref(false) const allowInSession = ref(false) +const GRANT_LAPSE_REASONS = ['changed', 'expired', 'idle'] +const grantLapsedText = computed(() => ( + props.grantLapsed && GRANT_LAPSE_REASONS.includes(props.grantLapsed) + ? t(`agentStream.toolApproval.grantLapsed.${props.grantLapsed}`) + : '' +)) const submitting = ref(false) const { parked, secondsLeft, timerClass, countdownText, parkedText } = usePromptCountdown(props) diff --git a/frontend/src/views/chat/components/agent-interaction-card.less b/frontend/src/views/chat/components/agent-interaction-card.less index 6929c2c4..ec510c27 100644 --- a/frontend/src/views/chat/components/agent-interaction-card.less +++ b/frontend/src/views/chat/components/agent-interaction-card.less @@ -451,6 +451,11 @@ color: var(--td-text-color-secondary); } +.prompt-grant-lapsed { + font-size: var(--agent-step-summary-size, 13px); + color: var(--td-warning-color); +} + .prompt-grant-scope { margin-left: 6px; color: var(--td-text-color-placeholder); diff --git a/internal/agent/act.go b/internal/agent/act.go index 26b6bfa9..ed02248c 100644 --- a/internal/agent/act.go +++ b/internal/agent/act.go @@ -613,7 +613,7 @@ func (e *AgentEngine) runToolCallAnswered( ExecTimeout: execTimeout, Snapshot: e.snapshotFunc(i, tc.Function.Name), Answered: answered, - Interactive: e.interactive, + Mode: e.mode, }) var result *types.ToolResult diff --git a/internal/agent/approval/gate.go b/internal/agent/approval/gate.go index 102ac5f2..0f1038e3 100644 --- a/internal/agent/approval/gate.go +++ b/internal/agent/approval/gate.go @@ -16,9 +16,9 @@ import ( "time" "github.com/Tencent/WeKnora/internal/agent/hitl" + "github.com/Tencent/WeKnora/internal/agent/policy" "github.com/Tencent/WeKnora/internal/config" "github.com/Tencent/WeKnora/internal/event" - "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/types" ) @@ -66,10 +66,13 @@ type PendingRequest struct { Description string Args json.RawMessage ToolCallID string - // Grant, when set, lets the user allow calls with the same grant for the - // rest of the session; see types.ToolApprovalPromptRequest. + // Grant, when set, names the kind of call for matching remembered + // grants; see types.ToolApprovalPromptRequest. GrantRisk is the call's + // risk, empty meaning write: only a write may be remembered from the + // card, while a standing grant may also cover a destructive call. Grant string GrantScope string + GrantRisk policy.Risk // Snapshot, when set, is the run state to resume from: the wait is cut // to the hot-wait window and then suspends instead of timing out. Snapshot []byte @@ -78,7 +81,9 @@ type PendingRequest struct { // MCPApproval is the surface used by MCPTool (mockable in tests). type MCPApproval interface { - NeedsApproval(ctx context.Context, tenantID uint64, serviceID, toolName string) bool + // Action is the policy action of calling tool; the caller decides it + // under the run's access level. + Action(ctx context.Context, tenantID uint64, serviceID string, tool *types.MCPTool) policy.Action IsEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) RequestAndWait(ctx context.Context, req PendingRequest) (Decision, error) // ResumeDecision is the decision carried by the answered prompt a resumed @@ -138,7 +143,8 @@ type Gate struct { timeout time.Duration hotWait time.Duration // in-memory wait before a suspendable approval suspends the run broker *hitl.Broker - failClose bool // when true, NeedsApproval errors block (require approval) instead of skip + failClose bool // when true, policy read errors require approval instead of skipping it + grants GrantStore } // Errors returned by Resolve; they alias the prompt broker's errors. @@ -151,9 +157,13 @@ var ( ) // UnattendedApprovalReason is the refusal of a tool approval raised in a run -// nobody watches (types.WithUnattendedRun). +// nobody can answer (types.RunModeUnattended). const UnattendedApprovalReason = "it needs the user's approval, which nobody can give in this run" +// DeferredApprovalReason is the refusal of a tool approval raised in a +// deferred run that cannot save its state to wait for the answer. +const DeferredApprovalReason = "it needs the user's approval, and this run cannot wait for it" + // NewGate builds a gate. checker may be nil (disables gating). cfg may be nil // (defaults apply). broker may be nil (process-local prompts, single replica). func NewGate(cfg *config.Config, checker Checker, broker *hitl.Broker) *Gate { @@ -178,25 +188,21 @@ func NewGate(cfg *config.Config, checker Checker, broker *hitl.Broker) *Gate { return &Gate{checker: checker, timeout: timeout, hotWait: hotWait, broker: broker, failClose: failClose} } -// NeedsApproval returns whether execution should pause for human confirmation. -func (g *Gate) NeedsApproval(ctx context.Context, tenantID uint64, serviceID, toolName string) bool { - if hitl.RequiresDelegatedApproval(ctx) { - return true - } - if g == nil || g.checker == nil || tenantID == 0 || serviceID == "" || toolName == "" { - return false - } +// Verdict decides a call of an MCP tool under the run's access level: the +// tool's risk comes from the workspace's policy and the service's +// annotations, and a tool the workspace marked as requiring approval +// always asks. +func (g *Gate) Verdict(ctx context.Context, tenantID uint64, serviceID string, tool *types.MCPTool) policy.Verdict { + rules := policy.Rules{Level: types.AccessLevelFromContext(ctx)} + return policy.Decide(g.Action(ctx, tenantID, serviceID, tool), rules) +} + +// requiredByPolicy reports whether the workspace marked the tool as always +// requiring approval, for checkers that know nothing about risk. +func (g *Gate) requiredByPolicy(ctx context.Context, tenantID uint64, serviceID, toolName string) bool { ok, err := g.checker.IsRequired(ctx, tenantID, serviceID, toolName) if err != nil { - // Default fail-close: a transient DB error must NOT silently allow a - // dangerous tool to run. Operators can opt into legacy behaviour via - // WEKNORA_AGENT_TOOL_APPROVAL_FAIL_OPEN=true. - if g.failClose { - logger.GetLogger(ctx).Warnf("mcp tool approval check failed (fail-close: requiring approval): %v", err) - return true - } - logger.GetLogger(ctx).Warnf("mcp tool approval check failed (fail-open: skip gate): %v", err) - return false + return g.failedAction(ctx, err).Always } return ok } @@ -220,9 +226,6 @@ func (g *Gate) RequestAndWait(ctx context.Context, req PendingRequest) (Decision if g == nil { return Decision{Approved: true}, nil } - if g.checker == nil && !hitl.RequiresDelegatedApproval(ctx) { - return Decision{Approved: true}, nil - } return g.awaitToolApproval(ctx, req) } @@ -234,57 +237,36 @@ func (g *Gate) RequestBuiltinApproval(ctx context.Context, req PendingRequest) ( if g == nil || g.broker == nil { return Decision{}, fmt.Errorf("tool approval is not available") } - if g.allowedInSession(ctx, req) { - return Decision{Approved: true, Granted: true}, nil - } return g.awaitToolApproval(ctx, req) } // offeredGrantScope is the scope the card offers to allow, which needs both // a grant to match later calls and a description for the user. func offeredGrantScope(req PendingRequest) string { - if req.Grant == "" { + if req.Grant == "" || req.grantRisk() != policy.RiskWrite { return "" } return req.GrantScope } -// grantedStatuses are the states of an approved prompt whose call ran or is -// running. -var grantedStatuses = []string{types.AgentPromptExecuting, types.AgentPromptDone} - -// allowedInSession reports whether the user already approved a call with -// req's grant in this session and chose to allow the rest. Only the same -// owner's approvals count, and any lookup failure asks again. -func (g *Gate) allowedInSession(ctx context.Context, req PendingRequest) bool { - if req.Grant == "" || req.SessionID == "" || req.UserID == "" || req.TenantID == 0 { - return false +func (req PendingRequest) grantRisk() policy.Risk { + if req.GrantRisk == "" { + return policy.RiskWrite } - prompts, err := g.broker.SessionPrompts(ctx, req.SessionID, grantedStatuses) - if err != nil { - logger.Warnf(ctx, "tool approval: read session grants: %v", err) - return false - } - for _, p := range prompts { - if p.Kind != types.AgentPromptKindToolApproval || p.TenantID != req.TenantID || p.UserID != req.UserID { - continue - } - var request types.ToolApprovalPromptRequest - var response types.ToolApprovalPromptResponse - if json.Unmarshal(p.Request, &request) != nil || request.Grant != req.Grant || - json.Unmarshal(p.Response, &response) != nil { - continue - } - if response.Approved && response.AllowInSession { - return true - } - } - return false + return req.GrantRisk } func (g *Gate) awaitToolApproval(ctx context.Context, req PendingRequest) (Decision, error) { - if types.IsUnattendedRun(ctx) { + granted, lapse := g.granted(ctx, req) + if granted { + return Decision{Approved: true, Granted: true}, nil + } + mode := types.RunModeFromContext(ctx) + switch { + case mode == types.RunModeUnattended: return Decision{Reason: UnattendedApprovalReason}, nil + case mode == types.RunModeDeferred && req.Snapshot == nil: + return Decision{Reason: DeferredApprovalReason}, nil } if req.EventBus == nil { return Decision{}, fmt.Errorf("tool approval: EventBus is nil") @@ -299,6 +281,7 @@ func (g *Gate) awaitToolApproval(ctx context.Context, req PendingRequest) (Decis Args: req.Args, Grant: req.Grant, GrantScope: offeredGrantScope(req), + GrantLapsed: lapse, }) if err != nil { return Decision{}, fmt.Errorf("encode tool approval: %w", err) @@ -307,15 +290,19 @@ func (g *Gate) awaitToolApproval(ctx context.Context, req PendingRequest) (Decis if len(req.Args) > 0 { _ = json.Unmarshal(req.Args, &argsObj) } - wait := g.timeout + wait, fallback := g.timeout, g.timeout var suspend *hitl.SuspendSpec if req.Snapshot != nil { wait = g.hotWait suspend = &hitl.SuspendSpec{Snapshot: req.Snapshot, SnapshotVersion: req.SnapshotVersion} } + if mode == types.RunModeDeferred { + // Nobody is watching: suspend at once, and never fall back to waiting. + wait, fallback = 0, 0 + } out, err := g.broker.Await(ctx, hitl.Spec{ Suspend: suspend, - FallbackTimeout: g.timeout, + FallbackTimeout: fallback, Prompt: &types.AgentPrompt{ TenantID: req.TenantID, UserID: req.UserID, @@ -347,6 +334,7 @@ func (g *Gate) awaitToolApproval(ctx context.Context, req PendingRequest) (Decis Args: argsObj, ArgsJSON: string(req.Args), GrantScope: offeredGrantScope(req), + GrantLapsed: lapse, TimeoutSeconds: timeoutSec, HotWaitSeconds: timeoutSec, Suspendable: p.Suspendable, @@ -379,7 +367,7 @@ func (g *Gate) awaitToolApproval(ctx context.Context, req PendingRequest) (Decis } d := toolApprovalDecision(out) - g.consumeDecision(ctx, &d, req.EventBus, req.SessionID, req.AssistantMessageID, req.RequestID) + g.consumeDecision(ctx, &d, req.EventBus, out.Prompt) return d, nil } @@ -397,13 +385,12 @@ func promptWaitSeconds(p *types.AgentPrompt, wait, fallback time.Duration) int { // returned it. func (g *Gate) ResumeDecision(ctx context.Context, prompt *types.AgentPrompt, bus *event.EventBus) Decision { d := toolApprovalDecision(hitl.Outcome{Prompt: prompt, Answered: true}) - g.consumeDecision(ctx, &d, bus, prompt.SessionID, prompt.AssistantMessageID, prompt.RequestID) + g.consumeDecision(ctx, &d, bus, prompt) return d } -func (g *Gate) consumeDecision( - ctx context.Context, d *Decision, bus *event.EventBus, sessionID, assistantMessageID, requestID string, -) { +func (g *Gate) consumeDecision(ctx context.Context, d *Decision, bus *event.EventBus, prompt *types.AgentPrompt) { + sessionID, assistantMessageID, requestID := prompt.SessionID, prompt.AssistantMessageID, prompt.RequestID // An approved call stays "executing" until MarkExecuted. consumeTo := types.AgentPromptDone if d.Approved { @@ -422,6 +409,9 @@ func (g *Gate) consumeDecision( } d.Reason = "could not confirm tool approval; tool was not executed" } + if consumed { + g.remember(ctx, *d, prompt) + } if bus == nil { return } @@ -714,10 +704,33 @@ type Adapter struct { Svc interface { IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) IsEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) + Policy(ctx context.Context, tenantID uint64, serviceID, toolName string) (*types.MCPToolApproval, error) + ObserveRisk(ctx context.Context, tenantID uint64, serviceID, toolName string, risk string) error } } -var _ Checker = (*Adapter)(nil) +var ( + _ Checker = (*Adapter)(nil) + _ RiskChecker = (*Adapter)(nil) +) + +// Policy implements RiskChecker. +func (a *Adapter) Policy( + ctx context.Context, tenantID uint64, serviceID, toolName string, +) (*types.MCPToolApproval, error) { + if a == nil || a.Svc == nil { + return nil, nil + } + return a.Svc.Policy(ctx, tenantID, serviceID, toolName) +} + +// ObserveRisk implements RiskChecker. +func (a *Adapter) ObserveRisk(ctx context.Context, tenantID uint64, serviceID, toolName string, risk string) error { + if a == nil || a.Svc == nil { + return nil + } + return a.Svc.ObserveRisk(ctx, tenantID, serviceID, toolName, risk) +} // IsRequired implements Checker. func (a *Adapter) IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) { diff --git a/internal/agent/approval/gate_test.go b/internal/agent/approval/gate_test.go index 242fa537..a9eeb0c7 100644 --- a/internal/agent/approval/gate_test.go +++ b/internal/agent/approval/gate_test.go @@ -6,6 +6,7 @@ import ( "testing" "time" + "github.com/Tencent/WeKnora/internal/agent/policy" "github.com/Tencent/WeKnora/internal/config" "github.com/Tencent/WeKnora/internal/event" "github.com/Tencent/WeKnora/internal/types" @@ -29,6 +30,12 @@ func (s *stubChecker) IsRequired(ctx context.Context, tenantID uint64, serviceID return s.required, s.err } +func (s *stubChecker) Policy(context.Context, uint64, string, string) (*types.MCPToolApproval, error) { + return &types.MCPToolApproval{RequireApproval: s.required}, s.err +} + +func (s *stubChecker) ObserveRisk(context.Context, uint64, string, string, string) error { return nil } + func (s *stubChecker) IsEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) { if s.enabledErr != nil { return false, s.enabledErr @@ -43,7 +50,7 @@ func TestGate_RequestAndWait_Approve(t *testing.T) { bus := event.NewEventBus() g := NewGate(&config.Config{Agent: &config.AgentConfig{ToolApprovalTimeoutSeconds: 2}}, &stubChecker{required: true}, nil) - ctx := context.Background() + ctx := attended() req := PendingRequest{ TenantID: 1, SessionID: "s1", @@ -76,7 +83,7 @@ func TestGate_RequestAndWait_Approve(t *testing.T) { func TestGate_RequestAndWait_Timeout(t *testing.T) { g := NewGate(&config.Config{Agent: &config.AgentConfig{ToolApprovalTimeoutSeconds: 1}}, &stubChecker{required: true}, nil) - ctx := context.Background() + ctx := attended() req := PendingRequest{ TenantID: 1, SessionID: "s1", @@ -108,7 +115,7 @@ func TestGate_UnattendedRunRefusesWithoutAsking(t *testing.T) { ServiceID: "svc", ServiceName: "svcname", MCPToolName: "t", RegisteredToolName: "mcp_svcname_t", Args: json.RawMessage(`{}`), } - ctx := types.WithUnattendedRun(context.Background()) + ctx := types.WithRunMode(context.Background(), types.RunModeUnattended) started := time.Now() d, err := g.RequestAndWait(ctx, req) @@ -131,9 +138,9 @@ func TestGate_UnattendedRunRefusesWithoutAsking(t *testing.T) { require.Empty(t, prompts, "no prompt is left pending") } -func TestGate_NeedsApproval_NoChecker(t *testing.T) { +func TestGate_Verdict_NoChecker(t *testing.T) { g := NewGate(nil, nil, nil) - require.False(t, g.NeedsApproval(context.Background(), 1, "x", "y")) + require.Equal(t, policy.Allow, g.Verdict(context.Background(), 1, "x", &types.MCPTool{Name: "y"})) } func TestGate_Resolve_NotFound(t *testing.T) { @@ -157,7 +164,7 @@ func TestGate_Resolve_TenantMismatch(t *testing.T) { }() return nil }) - d, err := g.RequestAndWait(context.Background(), req) + d, err := g.RequestAndWait(attended(), req) require.NoError(t, err) require.False(t, d.Approved) } @@ -178,7 +185,7 @@ func TestGate_Resolve_UserMismatch(t *testing.T) { }() return nil }) - d, err := g.RequestAndWait(context.Background(), req) + d, err := g.RequestAndWait(attended(), req) require.NoError(t, err) require.True(t, d.Approved) } @@ -202,7 +209,7 @@ func TestGate_Resolve_EmptyUserIDRejectedWhenWaiterHasUser(t *testing.T) { }() return nil }) - d, err := g.RequestAndWait(context.Background(), req) + d, err := g.RequestAndWait(attended(), req) require.NoError(t, err) require.False(t, d.Approved) } @@ -228,7 +235,7 @@ func TestGate_Resolve_AlreadyResolvedAfterTimeout(t *testing.T) { lateErr <- resolveFor(g, 1, "", pendingID, Decision{Approved: true}) }() - d, err := g.RequestAndWait(context.Background(), PendingRequest{ + d, err := g.RequestAndWait(attended(), PendingRequest{ TenantID: 1, EventBus: bus, SessionID: "s", ServiceID: "svc", MCPToolName: "t", Args: json.RawMessage(`{}`), }) @@ -260,7 +267,7 @@ func TestGate_ApprovedCallStaysExecutingUntilMarked(t *testing.T) { return nil }) - d, err := g.RequestAndWait(context.Background(), PendingRequest{ + d, err := g.RequestAndWait(attended(), PendingRequest{ TenantID: 1, EventBus: bus, SessionID: "s", ServiceID: "svc", MCPToolName: "t", Args: json.RawMessage(`{}`), }) @@ -300,7 +307,7 @@ func TestGate_Resolve_RaceWinsAlreadyResolved(t *testing.T) { return nil }) - d, err := g.RequestAndWait(context.Background(), PendingRequest{ + d, err := g.RequestAndWait(attended(), PendingRequest{ TenantID: 1, EventBus: bus, SessionID: "s", ServiceID: "svc", MCPToolName: "t", Args: json.RawMessage(`{}`), }) @@ -370,7 +377,7 @@ func TestGate_RequestAndWait_SuspendsAfterHotWait(t *testing.T) { return nil }) - d, err := g.RequestAndWait(context.Background(), PendingRequest{ + d, err := g.RequestAndWait(attended(), PendingRequest{ TenantID: 1, SessionID: "s1", AssistantMessageID: "m1", EventBus: bus, ServiceID: "svc", ServiceName: "svcname", MCPToolName: "t", RegisteredToolName: "mcp_svcname_t", Args: json.RawMessage(`{}`), ToolCallID: "tc1", @@ -389,12 +396,36 @@ func TestGate_RequestAndWait_SuspendsAfterHotWait(t *testing.T) { require.False(t, resolved, "a suspended approval is still open") } +func TestGate_DeferredRunSuspendsAtOnce(t *testing.T) { + g := NewGate(&config.Config{Agent: &config.AgentConfig{ + ToolApprovalTimeoutSeconds: 60, PromptHotWaitSeconds: 30, + }}, &stubChecker{required: true}, nil) + ctx := types.WithRunMode(context.Background(), types.RunModeDeferred) + req := PendingRequest{ + TenantID: 1, SessionID: "s1", AssistantMessageID: "m1", EventBus: event.NewEventBus(), + ServiceID: "svc", ServiceName: "svcname", MCPToolName: "t", RegisteredToolName: "mcp_svcname_t", + Args: json.RawMessage(`{}`), ToolCallID: "tc1", + } + + d, err := g.RequestAndWait(ctx, req) + require.NoError(t, err) + require.False(t, d.Approved) + require.Equal(t, DeferredApprovalReason, d.Reason, "without saved state the run cannot wait") + + req.Snapshot, req.SnapshotVersion = []byte(`{"version":1}`), 1 + started := time.Now() + d, err = g.RequestAndWait(ctx, req) + require.NoError(t, err) + require.NotNil(t, d.Suspended) + require.Less(t, time.Since(started), 5*time.Second, "a deferred run skips the hot wait") +} + func TestGate_ResolveSuspendedThenResumeDecision(t *testing.T) { bus := event.NewEventBus() g := NewGate(&config.Config{Agent: &config.AgentConfig{ ToolApprovalTimeoutSeconds: 60, PromptHotWaitSeconds: 1, }}, &stubChecker{required: true}, nil) - d, err := g.RequestAndWait(context.Background(), PendingRequest{ + d, err := g.RequestAndWait(attended(), PendingRequest{ TenantID: 1, SessionID: "s1", AssistantMessageID: "m1", EventBus: bus, ServiceID: "svc", ServiceName: "svcname", MCPToolName: "t", RegisteredToolName: "mcp_svcname_t", Args: json.RawMessage(`{"a":1}`), ToolCallID: "tc1", @@ -507,3 +538,7 @@ func TestAnsweredPromptOnlyCurrentOwnerCanContinue(t *testing.T) { } } } + +func attended() context.Context { + return types.WithRunMode(context.Background(), types.RunModeAttended) +} diff --git a/internal/agent/approval/grants.go b/internal/agent/approval/grants.go new file mode 100644 index 00000000..9dd13f76 --- /dev/null +++ b/internal/agent/approval/grants.go @@ -0,0 +1,124 @@ +package approval + +import ( + "context" + "encoding/json" + "time" + + "github.com/Tencent/WeKnora/internal/agent/policy" + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/types" +) + +// GrantStore keeps the approvals a user allowed to be remembered. +type GrantStore interface { + FindGrant(ctx context.Context, tenantID uint64, userID string, scope types.GrantScope, key string) ( + *types.AgentGrant, error) + SaveGrant(ctx context.Context, grant *types.AgentGrant) error + TouchGrant(ctx context.Context, id string, at time.Time) error +} + +// WithGrants makes the gate remember "allow for the rest" approvals in +// store. Without one, every call asks. +func (g *Gate) WithGrants(store GrantStore) *Gate { + g.grants = store + return g +} + +// grantScope is where grants of a run on ctx live: the scope the run set, +// else the session of the call. +func grantScope(ctx context.Context, sessionID string) (types.GrantScope, bool) { + if scope, ok := types.GrantScopeFromContext(ctx); ok { + return scope, true + } + if sessionID == "" { + return types.GrantScope{}, false + } + return types.GrantScope{Scope: types.AgentGrantScopeSession, ScopeID: sessionID}, true +} + +// granted reports whether the user already allowed calls with req's grant, +// in the run's own scope or its standing one. When they had but it no +// longer applies, lapse says why; a revoked grant is not reported, since the +// user withdrew it. Any lookup failure asks again. +func (g *Gate) granted(ctx context.Context, req PendingRequest) (ok bool, lapse string) { + if g.grants == nil || req.Grant == "" || req.UserID == "" || req.TenantID == 0 { + return false, "" + } + var scopes []types.GrantScope + if scope, ok := grantScope(ctx, req.SessionID); ok { + scopes = append(scopes, scope) + } + if scope, ok := types.StandingGrantScopeFromContext(ctx); ok { + scopes = append(scopes, scope) + } + for _, scope := range scopes { + ok, why := g.grantedIn(ctx, req, scope) + if ok { + return true, "" + } + if lapse == "" { + lapse = why + } + } + return false, lapse +} + +func (g *Gate) grantedIn(ctx context.Context, req PendingRequest, scope types.GrantScope) (bool, string) { + grant, err := g.grants.FindGrant(ctx, req.TenantID, req.UserID, scope, req.Grant) + if err != nil { + logger.Warnf(ctx, "tool approval: read grant: %v", err) + return false, "" + } + if grant == nil { + return false, "" + } + if !policy.Covers(policy.Risk(grant.Risk), req.grantRisk()) { + logger.Infof(ctx, "tool approval: grant %s was approved for %s, not %s; asking", + grant.ID, grant.Risk, req.grantRisk()) + return false, "" + } + now := time.Now() + if lapse := grant.LapseAt(now, scope.BindingHash); lapse != "" { + if lapse == types.AgentGrantLapseRevoked { + return false, "" + } + logger.Infof(ctx, "tool approval: grant %s %s; asking again", grant.ID, lapse) + return false, lapse + } + if err := g.grants.TouchGrant(ctx, grant.ID, now); err != nil { + logger.Warnf(ctx, "tool approval: record grant use: %v", err) + } + if req.grantRisk() == policy.RiskDestructive { + logger.GetLogger(ctx).WithFields(logger.Fields{ + "agent_action": req.Grant, "agent_grant_id": grant.ID, "agent_granted_destructive": true, + "agent_acting_via": types.ActingViaFromContext(ctx), + }).Info("agent policy decision") + } + return true, "" +} + +// remember stores the grant an approved prompt allowed for the rest of the +// run's scope. +func (g *Gate) remember(ctx context.Context, d Decision, prompt *types.AgentPrompt) { + if g.grants == nil || prompt == nil || !d.Approved || !d.AllowInSession { + return + } + var request types.ToolApprovalPromptRequest + if json.Unmarshal(prompt.Request, &request) != nil || request.Grant == "" { + return + } + scope, ok := grantScope(ctx, prompt.SessionID) + if !ok || prompt.TenantID == 0 || prompt.UserID == "" { + return + } + grant := &types.AgentGrant{ + TenantID: prompt.TenantID, UserID: prompt.UserID, + Scope: scope.Scope, ScopeID: scope.ScopeID, GrantKey: request.Grant, + Label: request.GrantScope, BindingHash: scope.BindingHash, PromptID: prompt.ID, + Risk: string(policy.RiskWrite), + } + if err := g.grants.SaveGrant(context.WithoutCancel(ctx), grant); err != nil { + logger.Warnf(ctx, "tool approval: remember grant: %v", err) + } +} diff --git a/internal/agent/approval/mcp_risk.go b/internal/agent/approval/mcp_risk.go new file mode 100644 index 00000000..90313bef --- /dev/null +++ b/internal/agent/approval/mcp_risk.go @@ -0,0 +1,126 @@ +package approval + +import ( + "context" + + "github.com/Tencent/WeKnora/internal/agent/policy" + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/types" +) + +// RiskChecker reads and records the risk policy of MCP tools. A Checker that +// does not implement it leaves every MCP tool at RiskWrite. +type RiskChecker interface { + // Policy returns the stored policy of a tool, or nil when it has none. + Policy(ctx context.Context, tenantID uint64, serviceID, toolName string) (*types.MCPToolApproval, error) + // ObserveRisk records a risk the service declared; the stored one only rises. + ObserveRisk(ctx context.Context, tenantID uint64, serviceID, toolName string, risk string) error +} + +// DeclaredRisk is the risk a service's annotations give its tool. Only +// readOnlyHint lowers it: MCP defaults destructiveHint to true, so reading +// it would make every unannotated tool destructive. Destructive is set by +// the workspace. +func DeclaredRisk(tool *types.MCPTool) policy.Risk { + if tool.DeclaresReadOnly() { + return policy.RiskRead + } + return policy.RiskWrite +} + +// ToolRisk is the risk a stored policy and the service's declaration give a +// tool. The workspace's explicit risk wins; otherwise the declaration counts +// unless the service declared a higher risk before, so a service cannot +// lower its own tool's risk without the workspace agreeing. +func ToolRisk(row *types.MCPToolApproval, declared policy.Risk) policy.Risk { + if row == nil { + return declared + } + if explicit := policy.Risk(row.Risk); explicit.Valid() { + return explicit + } + if observed := policy.Risk(row.ObservedRisk); observed.Above(declared) { + return observed + } + return declared +} + +// PendingDowngrade reports whether the service now declares a lower risk +// than the one in force, which only the workspace can accept. +func PendingDowngrade(row *types.MCPToolApproval, declared policy.Risk) bool { + return row != nil && !policy.Risk(row.Risk).Valid() && policy.Risk(row.ObservedRisk).Above(declared) +} + +// Action is the policy action of calling tool: its risk, and whether the +// workspace marked it as always requiring approval. +func (g *Gate) Action(ctx context.Context, tenantID uint64, serviceID string, tool *types.MCPTool) policy.Action { + declared := DeclaredRisk(tool) + if g == nil || g.checker == nil || tenantID == 0 || serviceID == "" || tool == nil || tool.Name == "" { + return policy.Action{Risk: declared} + } + risks, ok := g.checker.(RiskChecker) + if !ok { + return policy.Action{Risk: policy.RiskWrite, Always: g.requiredByPolicy(ctx, tenantID, serviceID, tool.Name)} + } + row, err := risks.Policy(ctx, tenantID, serviceID, tool.Name) + if err != nil { + return g.failedAction(ctx, err) + } + if row == nil || declared.Above(policy.Risk(row.ObservedRisk)) { + if err := risks.ObserveRisk(ctx, tenantID, serviceID, tool.Name, string(declared)); err != nil { + logger.GetLogger(ctx).Warnf("record declared risk of MCP tool %s: %v", tool.Name, err) + } + } + return policy.Action{Risk: ToolRisk(row, declared), Always: row != nil && row.RequireApproval} +} + +// failedAction is the action used when the tool's policy cannot be read. +func (g *Gate) failedAction(ctx context.Context, err error) policy.Action { + // Default fail-close: a transient DB error must NOT silently allow a + // dangerous tool to run. Operators can opt into legacy behaviour via + // WEKNORA_AGENT_TOOL_APPROVAL_FAIL_OPEN=true. + if g.failClose { + logger.GetLogger(ctx).Warnf("mcp tool approval check failed (fail-close: requiring approval): %v", err) + return policy.Action{Risk: policy.RiskWrite, Always: true} + } + logger.GetLogger(ctx).Warnf("mcp tool approval check failed (fail-open: skip gate): %v", err) + return policy.Action{Risk: policy.RiskWrite} +} + +// ToolRisks returns the risk of each tool of a service in one policy read, +// without recording what the service declares. +func (g *Gate) ToolRisks( + ctx context.Context, tenantID uint64, serviceID string, tools []*types.MCPTool, +) (map[string]policy.Risk, error) { + rows := map[string]*types.MCPToolApproval{} + if g != nil && g.checker != nil && tenantID != 0 && serviceID != "" { + lister, ok := g.checker.(interface { + ListByService(context.Context, uint64, string) ([]*types.MCPToolApproval, error) + }) + if !ok { + if adapter, isAdapter := g.checker.(*Adapter); isAdapter && adapter != nil { + lister, ok = adapter.Svc.(interface { + ListByService(context.Context, uint64, string) ([]*types.MCPToolApproval, error) + }) + } + } + if ok { + list, err := lister.ListByService(ctx, tenantID, serviceID) + if err != nil { + return nil, err + } + for _, row := range list { + if row != nil && row.TenantID == tenantID && row.ServiceID == serviceID { + rows[row.ToolName] = row + } + } + } + } + risks := make(map[string]policy.Risk, len(tools)) + for _, tool := range tools { + if tool != nil { + risks[tool.Name] = ToolRisk(rows[tool.Name], DeclaredRisk(tool)) + } + } + return risks, nil +} diff --git a/internal/agent/approval/mcp_risk_test.go b/internal/agent/approval/mcp_risk_test.go new file mode 100644 index 00000000..df2ee1f3 --- /dev/null +++ b/internal/agent/approval/mcp_risk_test.go @@ -0,0 +1,98 @@ +package approval + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/Tencent/WeKnora/internal/agent/policy" + "github.com/Tencent/WeKnora/internal/types" +) + +type riskChecker struct { + stubChecker + row *types.MCPToolApproval + observed []string +} + +func (c *riskChecker) Policy(context.Context, uint64, string, string) (*types.MCPToolApproval, error) { + return c.row, c.err +} + +func (c *riskChecker) ObserveRisk(_ context.Context, _ uint64, _, _ string, risk string) error { + c.observed = append(c.observed, risk) + return nil +} + +func readOnlyTool(readOnly bool) *types.MCPTool { + return &types.MCPTool{Name: "t", Annotations: &types.MCPToolAnnotations{ReadOnlyHint: &readOnly}} +} + +func TestDeclaredRiskReadsOnlyTheReadOnlyHint(t *testing.T) { + destructive := true + require.Equal(t, policy.RiskRead, DeclaredRisk(readOnlyTool(true))) + require.Equal(t, policy.RiskWrite, DeclaredRisk(readOnlyTool(false))) + require.Equal(t, policy.RiskWrite, DeclaredRisk(&types.MCPTool{Name: "t"})) + require.Equal(t, policy.RiskWrite, DeclaredRisk(&types.MCPTool{ + Name: "t", Annotations: &types.MCPToolAnnotations{DestructiveHint: &destructive}, + }), "destructive is the workspace's call, not the service's") +} + +func TestToolRisk(t *testing.T) { + require.Equal(t, policy.RiskRead, ToolRisk(nil, policy.RiskRead)) + raised := &types.MCPToolApproval{ObservedRisk: "write"} + require.Equal(t, policy.RiskWrite, ToolRisk(raised, policy.RiskRead), "a service cannot lower its own risk") + require.True(t, PendingDowngrade(raised, policy.RiskRead)) + require.Equal(t, policy.RiskWrite, ToolRisk(&types.MCPToolApproval{ObservedRisk: "read"}, policy.RiskWrite), + "a raised declaration counts at once") + explicit := &types.MCPToolApproval{Risk: "read", ObservedRisk: "write"} + require.Equal(t, policy.RiskRead, ToolRisk(explicit, policy.RiskWrite), "the workspace's setting wins") + require.False(t, PendingDowngrade(explicit, policy.RiskRead)) +} + +func TestGateVerdictAppliesTheRunLevelToMCP(t *testing.T) { + ctxAt := func(level types.AssistantAccessLevel) context.Context { + return types.WithAccessLevel(context.Background(), level) + } + g := NewGate(nil, &riskChecker{}, nil) + read, write := readOnlyTool(true), readOnlyTool(false) + + require.Equal(t, policy.Allow, g.Verdict(ctxAt(types.AssistantAccessReadOnly), 1, "svc", read)) + require.Equal(t, policy.Deny, g.Verdict(ctxAt(types.AssistantAccessReadOnly), 1, "svc", write)) + require.Equal(t, policy.Ask, g.Verdict(ctxAt(types.AssistantAccessConfirm), 1, "svc", write)) + require.Equal(t, policy.Allow, g.Verdict(ctxAt(types.AssistantAccessAutoWrite), 1, "svc", write)) + require.Equal(t, policy.Allow, g.Verdict(context.Background(), 1, "svc", write), + "a run without a level keeps the unconfigured agent's auto_write") + + always := NewGate(nil, &riskChecker{row: &types.MCPToolApproval{RequireApproval: true}}, nil) + require.Equal(t, policy.Ask, always.Verdict(ctxAt(types.AssistantAccessAutoWrite), 1, "svc", read)) + + destructive := NewGate(nil, &riskChecker{row: &types.MCPToolApproval{Risk: "destructive"}}, nil) + require.Equal(t, policy.Ask, destructive.Verdict(ctxAt(types.AssistantAccessAutoWrite), 1, "svc", write)) +} + +func TestGateVerdictRecordsOnlyRaisedDeclarations(t *testing.T) { + ctx := types.WithAccessLevel(context.Background(), types.AssistantAccessConfirm) + checker := &riskChecker{} + g := NewGate(nil, checker, nil) + + g.Verdict(ctx, 1, "svc", readOnlyTool(true)) + require.Equal(t, []string{"read"}, checker.observed, "a first declaration is recorded") + + checker.row, checker.observed = &types.MCPToolApproval{ObservedRisk: "read"}, nil + require.Equal(t, policy.Ask, g.Verdict(ctx, 1, "svc", readOnlyTool(false))) + require.Equal(t, []string{"write"}, checker.observed, "a raised declaration is recorded") + + checker.row, checker.observed = &types.MCPToolApproval{ObservedRisk: "write"}, nil + require.Equal(t, policy.Ask, g.Verdict(ctx, 1, "svc", readOnlyTool(true)), + "a lowered declaration waits for the workspace") + require.Empty(t, checker.observed) +} + +func TestGateToolRisksReadsPoliciesInBulk(t *testing.T) { + g := NewGate(nil, nil, nil) + risks, err := g.ToolRisks(context.Background(), 1, "svc", []*types.MCPTool{readOnlyTool(true)}) + require.NoError(t, err) + require.Equal(t, policy.RiskRead, risks["t"]) +} diff --git a/internal/agent/approval/session_grant_test.go b/internal/agent/approval/session_grant_test.go index a0824a72..f9361581 100644 --- a/internal/agent/approval/session_grant_test.go +++ b/internal/agent/approval/session_grant_test.go @@ -3,10 +3,13 @@ package approval import ( "context" "encoding/json" + "fmt" + "sync" "testing" "time" "github.com/Tencent/WeKnora/internal/agent/hitl" + "github.com/Tencent/WeKnora/internal/agent/policy" "github.com/Tencent/WeKnora/internal/config" "github.com/Tencent/WeKnora/internal/event" "github.com/Tencent/WeKnora/internal/types" @@ -14,10 +17,63 @@ import ( "github.com/stretchr/testify/require" ) +// memGrants is an in-memory GrantStore keyed like the agent_grants table. +type memGrants struct { + mu sync.Mutex + grants map[string]*types.AgentGrant +} + +func newMemGrants() *memGrants { return &memGrants{grants: map[string]*types.AgentGrant{}} } + +func memGrantKey(tenantID uint64, userID string, scope types.GrantScope, key string) string { + return fmt.Sprint(tenantID, "|", userID, "|", scope.Scope, "|", scope.ScopeID, "|", key) +} + +func (m *memGrants) FindGrant( + _ context.Context, tenantID uint64, userID string, scope types.GrantScope, key string, +) (*types.AgentGrant, error) { + m.mu.Lock() + defer m.mu.Unlock() + if g, ok := m.grants[memGrantKey(tenantID, userID, scope, key)]; ok { + copied := *g + return &copied, nil + } + return nil, nil +} + +func (m *memGrants) SaveGrant(_ context.Context, g *types.AgentGrant) error { + m.mu.Lock() + defer m.mu.Unlock() + copied := *g + copied.ID = memGrantKey(g.TenantID, g.UserID, types.GrantScope{Scope: g.Scope, ScopeID: g.ScopeID}, g.GrantKey) + copied.CreatedAt = time.Now() + m.grants[copied.ID] = &copied + return nil +} + +func (m *memGrants) TouchGrant(_ context.Context, id string, at time.Time) error { + m.mu.Lock() + defer m.mu.Unlock() + if g, ok := m.grants[id]; ok { + g.LastUsedAt = &at + } + return nil +} + +func (m *memGrants) revokeAll() { + m.mu.Lock() + defer m.mu.Unlock() + now := time.Now() + for _, g := range m.grants { + g.RevokedAt = &now + } +} + // grantGate answers every approval it raises with answer and counts them. func grantGate(t *testing.T, answer Decision) (*Gate, *event.EventBus, *[]event.ToolApprovalRequiredData) { t.Helper() - g := NewGate(&config.Config{Agent: &config.AgentConfig{ToolApprovalTimeoutSeconds: 2}}, nil, nil) + g := NewGate(&config.Config{Agent: &config.AgentConfig{ToolApprovalTimeoutSeconds: 2}}, nil, nil). + WithGrants(newMemGrants()) bus := event.NewEventBus() var raised []event.ToolApprovalRequiredData bus.On(event.EventToolApprovalRequired, func(_ context.Context, evt event.Event) error { @@ -43,7 +99,7 @@ func grantRequest(bus *event.EventBus, session, grant string) PendingRequest { func approveAndRun(t *testing.T, g *Gate, req PendingRequest) Decision { t.Helper() - d, err := g.RequestBuiltinApproval(context.Background(), req) + d, err := g.RequestBuiltinApproval(attended(), req) require.NoError(t, err) g.MarkExecuted(context.Background(), d.PendingID) return d @@ -70,7 +126,7 @@ func TestSessionGrantSkipsLaterApprovalsOfTheSameKind(t *testing.T) { approveAndRun(t, g, grantRequest(bus, "s2", grant)) other := grantRequest(bus, "s1", grant) other.UserID = "u2" - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + ctx, cancel := context.WithTimeout(attended(), 100*time.Millisecond) defer cancel() d, _ := g.RequestBuiltinApproval(ctx, other) assert.False(t, d.Approved, "u2's prompt is answered by nobody here") @@ -88,7 +144,7 @@ func TestApprovalWithoutSessionGrantAsksAgain(t *testing.T) { func TestRequestWithoutGrantCannotBeAllowedForTheSession(t *testing.T) { g, bus, raised := grantGate(t, Decision{Approved: true, AllowInSession: true}) - ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) + ctx, cancel := context.WithTimeout(attended(), 300*time.Millisecond) defer cancel() d, err := g.RequestBuiltinApproval(ctx, grantRequest(bus, "s1", "")) require.NoError(t, err) @@ -136,8 +192,113 @@ func TestRejectingDropsAllowInSession(t *testing.T) { }() return nil }) - d, err := g.RequestBuiltinApproval(context.Background(), grantRequest(bus, "s1", "g")) + d, err := g.RequestBuiltinApproval(attended(), grantRequest(bus, "s1", "g")) require.NoError(t, err) assert.False(t, d.Approved) assert.False(t, d.AllowInSession) } + +func TestGrantsBelongToTheRunScope(t *testing.T) { + g, bus, raised := grantGate(t, Decision{Approved: true, AllowInSession: true}) + grant := "mcp:svc/write#abc" + root := types.GrantScope{Scope: types.AgentGrantScopeSession, ScopeID: "root"} + child := func() context.Context { return types.WithGrantScope(attended(), root) } + + d, err := g.RequestBuiltinApproval(child(), grantRequest(bus, "child-1", grant)) + require.NoError(t, err) + g.MarkExecuted(context.Background(), d.PendingID) + require.Len(t, *raised, 1) + + d, err = g.RequestBuiltinApproval(child(), grantRequest(bus, "child-2", grant)) + require.NoError(t, err) + assert.True(t, d.Granted, "a sibling child shares the root conversation's grant") + d = approveAndRun(t, g, grantRequest(bus, "root", grant)) + assert.True(t, d.Granted, "so does the root conversation") + assert.Len(t, *raised, 1) +} + +func TestRevokedOrRebindedGrantAsksAgain(t *testing.T) { + g, bus, raised := grantGate(t, Decision{Approved: true, AllowInSession: true}) + store := g.grants.(*memGrants) + grant := "mcp:svc/write#abc" + bound := func(binding string) context.Context { + return types.WithGrantScope(attended(), types.GrantScope{ + Scope: types.AgentGrantScopeAutomation, ScopeID: "auto-1", BindingHash: binding, + }) + } + run := func(ctx context.Context) Decision { + d, err := g.RequestBuiltinApproval(ctx, grantRequest(bus, "s", grant)) + require.NoError(t, err) + g.MarkExecuted(context.Background(), d.PendingID) + return d + } + run(bound("v1")) + assert.True(t, run(bound("v1")).Granted) + assert.False(t, run(bound("v2")).Granted, "a changed automation asks again") + require.Len(t, *raised, 2) + assert.Equal(t, types.AgentGrantLapseChanged, (*raised)[1].GrantLapsed, "the card says why it asks again") + + store.revokeAll() + assert.False(t, run(bound("v2")).Granted, "a revoked grant asks again") + require.Len(t, *raised, 3) + assert.Empty(t, (*raised)[2].GrantLapsed, "the user withdrew it, so nothing to explain") +} + +func TestStandingGrantsCoverOnlyWhatTheyWereApprovedFor(t *testing.T) { + g, bus, raised := grantGate(t, Decision{Approved: true, AllowInSession: true}) + store := g.grants.(*memGrants) + standing := types.GrantScope{Scope: types.AgentGrantScopeAutomation, ScopeID: "auto-1", BindingHash: "v1"} + runCtx := func() context.Context { + ctx := types.WithGrantScope(attended(), types.GrantScope{Scope: types.AgentGrantScopeSession, ScopeID: "run-1"}) + return types.WithStandingGrantScope(ctx, standing) + } + require.NoError(t, store.SaveGrant(context.Background(), &types.AgentGrant{ + TenantID: 7, UserID: "u1", Scope: standing.Scope, ScopeID: standing.ScopeID, BindingHash: "v1", + GrantKey: "knowledge.delete knowledge_base:kb1", Risk: string(policy.RiskDestructive), + })) + require.NoError(t, store.SaveGrant(context.Background(), &types.AgentGrant{ + TenantID: 7, UserID: "u1", Scope: standing.Scope, ScopeID: standing.ScopeID, BindingHash: "v1", + GrantKey: "mcp:svc/purge#abc", Risk: string(policy.RiskWrite), + })) + ask := func(grant string, risk policy.Risk) Decision { + req := grantRequest(bus, "run-1", grant) + req.GrantRisk = risk + d, err := g.RequestBuiltinApproval(runCtx(), req) + require.NoError(t, err) + g.MarkExecuted(context.Background(), d.PendingID) + return d + } + + assert.True(t, ask("knowledge.delete knowledge_base:kb1", policy.RiskDestructive).Granted, + "a destructive call pre-approved for this knowledge base runs") + assert.Empty(t, *raised) + + assert.False(t, ask("knowledge.delete knowledge_base:kb2", policy.RiskDestructive).Granted, + "another knowledge base asks") + require.Len(t, *raised, 1) + assert.Empty(t, (*raised)[0].GrantScope, "a destructive call is never offered for the rest of the run") + + assert.False(t, ask("mcp:svc/purge#abc", policy.RiskDestructive).Granted, + "a grant approved for a write does not cover the tool once it is destructive") + assert.Len(t, *raised, 2) +} + +func TestApprovalsDuringAnAutomationRunStayInTheRun(t *testing.T) { + g, bus, raised := grantGate(t, Decision{Approved: true, AllowInSession: true}) + standing := types.GrantScope{Scope: types.AgentGrantScopeAutomation, ScopeID: "auto-1"} + run := func(session string) Decision { + ctx := types.WithGrantScope(attended(), types.GrantScope{Scope: types.AgentGrantScopeSession, ScopeID: session}) + ctx = types.WithStandingGrantScope(ctx, standing) + d, err := g.RequestBuiltinApproval(ctx, grantRequest(bus, session, "mcp:svc/write#abc")) + require.NoError(t, err) + g.MarkExecuted(context.Background(), d.PendingID) + return d + } + run("run-1") + assert.True(t, run("run-1").Granted, "the run remembers its own approval") + assert.False(t, run("run-2").Granted, "the next run does not inherit it") + assert.Len(t, *raised, 2) + found, err := g.grants.FindGrant(context.Background(), 7, "u1", standing, "mcp:svc/write#abc") + require.NoError(t, err) + assert.Nil(t, found, "nothing approved during a run becomes a standing grant") +} diff --git a/internal/agent/engine.go b/internal/agent/engine.go index 122eefe8..9d43738c 100644 --- a/internal/agent/engine.go +++ b/internal/agent/engine.go @@ -94,9 +94,9 @@ type AgentEngine struct { suspendRequest []byte // collaborationOnlySuspension limits suspension to collaboration waits. collaborationOnlySuspension bool - // interactive: the client renders prompt cards and can answer them. - interactive bool - progress turnProgress + // mode: whether the client renders prompt cards and can answer them. + mode types.RunMode + progress turnProgress // Hold speculative parent prose until delegated work has been reviewed. holdCollaborationAnswer bool } diff --git a/internal/agent/hitl/delegation.go b/internal/agent/hitl/delegation.go index b9764347..9d8ca5c4 100644 --- a/internal/agent/hitl/delegation.go +++ b/internal/agent/hitl/delegation.go @@ -11,9 +11,8 @@ type delegationKey struct{} // Delegation is installed by the worker, never from model arguments. Register // durably associates a prompt with the current run before it can be answered. type Delegation struct { - Register func(context.Context, *types.AgentPrompt) error - Check func(context.Context) error - RequireApproval bool + Register func(context.Context, *types.AgentPrompt) error + Check func(context.Context) error } // WithDelegation attaches child prompt ownership checks to the execution context. @@ -31,9 +30,3 @@ func CheckDelegation(ctx context.Context) error { } return nil } - -// RequiresDelegatedApproval reports whether the child must request explicit tool approval. -func RequiresDelegatedApproval(ctx context.Context) bool { - d, _ := ctx.Value(delegationKey{}).(Delegation) - return d.RequireApproval -} diff --git a/internal/agent/operations/catalog.go b/internal/agent/operations/catalog.go index 3d265e0a..0a0eb95d 100644 --- a/internal/agent/operations/catalog.go +++ b/internal/agent/operations/catalog.go @@ -18,32 +18,22 @@ import ( "strings" "unicode" + "github.com/Tencent/WeKnora/internal/agent/policy" "github.com/Tencent/WeKnora/internal/types" ) // Risk classifies an operation by its effect on user data. -type Risk string +type Risk = policy.Risk +// A probe operation runs without approval within a per-run budget, and uses +// POST because the API does. const ( - // RiskRead has no side effects. - RiskRead Risk = "read" - // RiskProbe changes no data but does real work to answer: it connects to - // an external service or runs a retrieval. It runs without approval, - // within a per-run budget, and uses POST because the API does. - RiskProbe Risk = "probe" - // RiskWrite changes state in a recoverable way (reparse, status change). - RiskWrite Risk = "write" - // RiskDestructive removes data or cannot be undone. - RiskDestructive Risk = "destructive" + RiskRead = policy.RiskRead + RiskProbe = policy.RiskProbe + RiskWrite = policy.RiskWrite + RiskDestructive = policy.RiskDestructive ) -func (r Risk) valid() bool { - return r == RiskRead || r == RiskProbe || r == RiskWrite || r == RiskDestructive -} - -// Mutates reports whether running the operation needs the user's approval. -func (r Risk) Mutates() bool { return r == RiskWrite || r == RiskDestructive } - // Location is where a parameter goes in the HTTP request. type Location string @@ -203,22 +193,15 @@ type Access struct { Level types.AssistantAccessLevel } -// NeedsApproval reports whether running op must wait for the user. +// NeedsApproval reports whether running op must wait for the user. An +// operation the level denies is withheld before it gets here. func (a Access) NeedsApproval(op Operation) bool { - return op.AlwaysConfirm || a.NeedsApprovalFor(op.Risk) + return policy.Decide(policy.Action{Risk: op.Risk, Always: op.AlwaysConfirm}, a.Rules()) != policy.Allow } -// NeedsApprovalFor reports whether a change of the given risk must wait for -// the user; it also covers tools outside the catalog. -func (a Access) NeedsApprovalFor(risk Risk) bool { - switch risk { - case RiskRead, RiskProbe: - return false - case RiskWrite: - return a.Level != types.AssistantAccessAutoWrite - default: - return true - } +// Rules are the execution rules this access gives a run. +func (a Access) Rules() policy.Rules { + return policy.Rules{Level: a.Level} } // Withholding says why an access leaves an operation out. @@ -235,7 +218,7 @@ type Withholding struct { // approval target is withheld is withheld for the same reason, so every // offered mutation can still show the user what it acts on. func (c *Catalog) Withheld(a Access, op Operation) (Withholding, bool) { - if a.Level == types.AssistantAccessReadOnly && op.Risk.Mutates() { + if !policy.Offered(a.Level, op.Risk) { return Withholding{ReadOnly: true}, true } if op.SystemAdmin && !a.SystemAdmin { @@ -512,7 +495,7 @@ func validateOperation(op Operation) error { if strings.TrimSpace(op.Summary) == "" { return fmt.Errorf("summary is required") } - if !op.Risk.valid() { + if !op.Risk.Valid() { return fmt.Errorf("invalid risk %q", op.Risk) } if !allowedMethods[op.Method] { diff --git a/internal/agent/policy/policy.go b/internal/agent/policy/policy.go new file mode 100644 index 00000000..d894e611 --- /dev/null +++ b/internal/agent/policy/policy.go @@ -0,0 +1,113 @@ +// Package policy decides whether an agent may run an action without asking +// the user. It is the only place that maps an action's risk and the run's +// access level to allow, ask or deny; tools ask it instead of comparing +// levels themselves. What the agent can reach at all (registered tools, +// workspace roles, writable knowledge bases) is decided elsewhere and is not +// widened by anything here. +// +// See docs/design/agent-permission-model.md. +package policy + +import "github.com/Tencent/WeKnora/internal/types" + +// Risk classifies an action by its effect on user data. +type Risk string + +const ( + // RiskRead has no side effects. + RiskRead Risk = "read" + // RiskProbe changes no data but does real work to answer: it connects to + // an external service or runs a retrieval. + RiskProbe Risk = "probe" + // RiskWrite changes state in a recoverable way (reparse, status change). + RiskWrite Risk = "write" + // RiskDestructive removes data or cannot be undone. + RiskDestructive Risk = "destructive" +) + +// Valid reports whether r is a known risk. +func (r Risk) Valid() bool { + return r == RiskRead || r == RiskProbe || r == RiskWrite || r == RiskDestructive +} + +// Mutates reports whether the action changes data. +func (r Risk) Mutates() bool { return r == RiskWrite || r == RiskDestructive } + +var riskRank = map[Risk]int{RiskRead: 1, RiskProbe: 2, RiskWrite: 3, RiskDestructive: 4} + +// Above reports whether r is a higher risk than other. Every known risk is +// above an unknown or empty one. +func (r Risk) Above(other Risk) bool { return riskRank[r] > riskRank[other] } + +// Action is one call the agent wants to make. +type Action struct { + Risk Risk + // Always asks every time, whatever the level: a skill installation, or an + // MCP tool the workspace marked as requiring approval. + Always bool +} + +// Rules are what the run allows. +type Rules struct { + // Level is the run's effective access level. + Level types.AssistantAccessLevel +} + +// Verdict is the outcome of Decide. +type Verdict int + +const ( + // Allow runs the action without asking. + Allow Verdict = iota + // Ask runs the action only after the user approves it. + Ask + // Deny refuses the action: the run may not make it even with approval. + Deny +) + +// Decide returns whether a may run under r. Mutations a read-only run must +// not make are kept from the model by Offered; one that still arrives is +// denied. +func Decide(a Action, r Rules) Verdict { + if !Offered(r.Level, a.Risk) { + return Deny + } + if a.Always { + return Ask + } + switch a.Risk { + case RiskRead, RiskProbe: + return Allow + case RiskWrite: + if r.Level == types.AssistantAccessAutoWrite { + return Allow + } + return Ask + default: + return Ask + } +} + +// Grantable reports whether approving a during a run may be remembered for +// later calls of the same kind: only recoverable changes the workspace does +// not require approving every time. +func Grantable(a Action) bool { return a.Risk == RiskWrite && !a.Always } + +// Pregrantable reports whether a standing grant, approved ahead of time +// for a specific resource, may cover a. Unlike Grantable this includes +// destructive actions, which only an automation's settings may pre-approve; +// Always still asks every time. +func Pregrantable(a Action) bool { + return (a.Risk == RiskWrite || a.Risk == RiskDestructive) && !a.Always +} + +// Covers reports whether a grant approved for risk granted applies to a call +// of risk r: a grant never covers a riskier call than it was approved for. +func Covers(granted, r Risk) bool { return r.Valid() && !r.Above(granted) } + +// Offered reports whether an action of risk should be offered to the model +// at all under level. A read-only run is not shown changes it cannot make, +// nor anything whose risk is unknown. +func Offered(level types.AssistantAccessLevel, risk Risk) bool { + return level != types.AssistantAccessReadOnly || risk == RiskRead || risk == RiskProbe +} diff --git a/internal/agent/policy/policy_test.go b/internal/agent/policy/policy_test.go new file mode 100644 index 00000000..a0aeb562 --- /dev/null +++ b/internal/agent/policy/policy_test.go @@ -0,0 +1,69 @@ +package policy + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/Tencent/WeKnora/internal/types" +) + +const ( + readOnly = types.AssistantAccessReadOnly + confirm = types.AssistantAccessConfirm + autoWrite = types.AssistantAccessAutoWrite +) + +func TestDecide(t *testing.T) { + want := map[Risk]map[types.AssistantAccessLevel]Verdict{ + RiskRead: {readOnly: Allow, confirm: Allow, autoWrite: Allow}, + RiskProbe: {readOnly: Allow, confirm: Allow, autoWrite: Allow}, + RiskWrite: {readOnly: Deny, confirm: Ask, autoWrite: Allow}, + RiskDestructive: {readOnly: Deny, confirm: Ask, autoWrite: Ask}, + } + for risk, byLevel := range want { + for level, verdict := range byLevel { + assert.Equal(t, verdict, Decide(Action{Risk: risk}, Rules{Level: level}), "%s at %s", risk, level) + asked := Ask + if verdict == Deny { + asked = Deny + } + assert.Equal(t, asked, Decide(Action{Risk: risk, Always: true}, Rules{Level: level}), + "always %s at %s", risk, level) + } + } +} + +func TestDecideTreatsAnUnknownRiskAsDestructive(t *testing.T) { + assert.Equal(t, Ask, Decide(Action{Risk: "unknown"}, Rules{Level: autoWrite})) + assert.Equal(t, Deny, Decide(Action{Risk: "unknown"}, Rules{Level: readOnly})) +} + +func TestRiskAbove(t *testing.T) { + assert.True(t, RiskWrite.Above(RiskRead)) + assert.True(t, RiskRead.Above("")) + assert.False(t, RiskRead.Above(RiskWrite)) + assert.False(t, RiskWrite.Above(RiskWrite)) +} + +func TestOffered(t *testing.T) { + assert.True(t, Offered(readOnly, RiskRead)) + assert.True(t, Offered(readOnly, RiskProbe)) + assert.False(t, Offered(readOnly, RiskWrite)) + assert.False(t, Offered(readOnly, RiskDestructive)) + assert.True(t, Offered(confirm, RiskDestructive)) +} + +func TestPregrantableAndCovers(t *testing.T) { + assert.True(t, Pregrantable(Action{Risk: RiskWrite})) + assert.True(t, Pregrantable(Action{Risk: RiskDestructive})) + assert.False(t, Pregrantable(Action{Risk: RiskDestructive, Always: true})) + assert.False(t, Pregrantable(Action{Risk: RiskRead})) + assert.False(t, Grantable(Action{Risk: RiskDestructive}), "a run's card never remembers a destructive call") + + assert.True(t, Covers(RiskDestructive, RiskWrite)) + assert.True(t, Covers(RiskWrite, RiskWrite)) + assert.False(t, Covers(RiskWrite, RiskDestructive)) + assert.False(t, Covers("", RiskWrite)) + assert.False(t, Covers(RiskDestructive, "bogus")) +} diff --git a/internal/agent/policy/record.go b/internal/agent/policy/record.go new file mode 100644 index 00000000..fec0c8ff --- /dev/null +++ b/internal/agent/policy/record.go @@ -0,0 +1,43 @@ +package policy + +import ( + "context" + + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/types" +) + +// String names v for logs. +func (v Verdict) String() string { + switch v { + case Allow: + return "allow" + case Ask: + return "ask" + case Deny: + return "deny" + default: + return "unknown" + } +} + +// Record logs a decision on anything but a read, so what an agent changed +// without asking, and on whose behalf, can be traced later. key names the +// action, e.g. an operation ID or "mcp:/". +func Record(ctx context.Context, key string, a Action, r Rules, v Verdict) { + if a.Risk == RiskRead { + return + } + fields := logger.Fields{ + "agent_action": key, + "agent_risk": string(a.Risk), + "agent_always": a.Always, + "agent_level": string(r.Level), + "agent_mode": string(types.RunModeFromContext(ctx)), + "agent_verdict": v.String(), + } + if via := types.ActingViaFromContext(ctx); via != "" { + fields["agent_acting_via"] = via + } + logger.GetLogger(ctx).WithFields(fields).Info("agent policy decision") +} diff --git a/internal/agent/resume_mcp_test.go b/internal/agent/resume_mcp_test.go index 25f1c700..58704ff9 100644 --- a/internal/agent/resume_mcp_test.go +++ b/internal/agent/resume_mcp_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/Tencent/WeKnora/internal/agent/approval" + "github.com/Tencent/WeKnora/internal/agent/policy" "github.com/Tencent/WeKnora/internal/agent/tools" "github.com/Tencent/WeKnora/internal/event" "github.com/Tencent/WeKnora/internal/types" @@ -17,7 +18,11 @@ type resumeMCPGate struct{ resumed bool } func (*resumeMCPGate) IsEnabled(context.Context, uint64, string, string) (bool, error) { return true, nil } -func (*resumeMCPGate) NeedsApproval(context.Context, uint64, string, string) bool { return true } + +func (*resumeMCPGate) Action(context.Context, uint64, string, *types.MCPTool) policy.Action { + return policy.Action{Risk: policy.RiskWrite, Always: true} +} + func (*resumeMCPGate) RequestAndWait(context.Context, approval.PendingRequest) (approval.Decision, error) { return approval.Decision{Reason: "unexpected new approval"}, nil } diff --git a/internal/agent/suspend.go b/internal/agent/suspend.go index 61f016f3..c712cc56 100644 --- a/internal/agent/suspend.go +++ b/internal/agent/suspend.go @@ -149,10 +149,10 @@ func (e *AgentEngine) EnableSuspension(request json.RawMessage) { e.suspendable = true } -// SetInteractive marks the run's client as able to render and answer -// prompts such as ask_user, whether or not the run may also suspend. -func (e *AgentEngine) SetInteractive(interactive bool) { - e.interactive = interactive +// SetRunMode says whether the run's client can render and answer prompts +// such as ask_user, whether or not the run may also suspend. +func (e *AgentEngine) SetRunMode(mode types.RunMode) { + e.mode = mode.Normalize() } func (e *AgentEngine) beginTurn(query string, imageURLs []string, state *types.AgentState) { diff --git a/internal/agent/tools/ask_user.go b/internal/agent/tools/ask_user.go index ac1db12b..f05c70ff 100644 --- a/internal/agent/tools/ask_user.go +++ b/internal/agent/tools/ask_user.go @@ -87,7 +87,7 @@ func (t *AskUserTool) Execute(ctx context.Context, args json.RawMessage) (*types } meta, _ := ToolExecFromContext(ctx) resumed := meta != nil && meta.Answered != nil && meta.Answered.Kind == types.AgentPromptKindAskUser - if !resumed && (meta == nil || !meta.Interactive || meta.EventBus == nil || t.asker == nil) { + if !resumed && (!meta.Attended() || meta.EventBus == nil || t.asker == nil) { return &types.ToolResult{ Success: true, Output: "This conversation cannot show an interactive question. Ask the user directly in your " + diff --git a/internal/agent/tools/ask_user_test.go b/internal/agent/tools/ask_user_test.go index f0e44830..5a4316b1 100644 --- a/internal/agent/tools/ask_user_test.go +++ b/internal/agent/tools/ask_user_test.go @@ -49,7 +49,7 @@ func TestAskUserTool_NotInteractiveAsksInReply(t *testing.T) { func TestAskUserTool_RejectsInvalidQuestion(t *testing.T) { res, err := NewAskUserTool(&fakeAsker{}).Execute( - askCtx(&ToolExecContext{Interactive: true, EventBus: event.NewEventBus()}), + askCtx(&ToolExecContext{Mode: types.RunModeAttended, EventBus: event.NewEventBus()}), json.RawMessage(`{"question":"q","options":["a"],"fields":[{"name":"n","type":"text"}]}`)) require.NoError(t, err) assert.False(t, res.Success) @@ -61,7 +61,7 @@ func TestAskUserTool_ReturnsAnswer(t *testing.T) { Values: map[string]any{"replicas": float64(3), "env": "prod"}, }}} meta := &ToolExecContext{ - Interactive: true, EventBus: event.NewEventBus(), SessionID: "s1", AssistantMessageID: "m1", + Mode: types.RunModeAttended, EventBus: event.NewEventBus(), SessionID: "s1", AssistantMessageID: "m1", ToolCallID: "tc1", UserID: "user:u1", Snapshot: func() ([]byte, int, error) { return []byte("state"), 1, nil }, } @@ -79,7 +79,8 @@ func TestAskUserTool_Suspends(t *testing.T) { suspension := &types.PromptSuspension{PromptID: "p1", Kind: types.AgentPromptKindAskUser} asker := &fakeAsker{answer: approval.Answer{PromptID: "p1", Suspended: suspension}} res, err := NewAskUserTool(asker).Execute( - askCtx(&ToolExecContext{Interactive: true, EventBus: event.NewEventBus()}), json.RawMessage(`{"question":"q"}`)) + askCtx(&ToolExecContext{Mode: types.RunModeAttended, EventBus: event.NewEventBus()}), + json.RawMessage(`{"question":"q"}`)) require.NoError(t, err) assert.Same(t, suspension, res.Suspend) } @@ -102,7 +103,8 @@ func TestAskUserTool_ResumedUsesStoredAnswer(t *testing.T) { func TestAskUserTool_NoAnswer(t *testing.T) { asker := &fakeAsker{answer: approval.Answer{PromptID: "p1", Reason: "the user declined to answer"}} res, err := NewAskUserTool(asker).Execute( - askCtx(&ToolExecContext{Interactive: true, EventBus: event.NewEventBus()}), json.RawMessage(`{"question":"q"}`)) + askCtx(&ToolExecContext{Mode: types.RunModeAttended, EventBus: event.NewEventBus()}), + json.RawMessage(`{"question":"q"}`)) require.NoError(t, err) assert.True(t, res.Success) assert.Contains(t, res.Output, "did not answer (the user declined to answer)") @@ -112,7 +114,7 @@ func TestAskUserUsesCallerTenantForSharedAgent(t *testing.T) { asker := &fakeAsker{} ctx := context.WithValue(t.Context(), types.TenantIDContextKey, uint64(1)) ctx = types.WithExecutionTenant(ctx, 2) - ctx = WithToolExecContext(ctx, &ToolExecContext{Interactive: true, EventBus: event.NewEventBus()}) + ctx = WithToolExecContext(ctx, &ToolExecContext{Mode: types.RunModeAttended, EventBus: event.NewEventBus()}) _, err := NewAskUserTool(asker).Execute(ctx, json.RawMessage(`{"question":"which?"}`)) require.NoError(t, err) require.Len(t, asker.asked, 1) @@ -141,7 +143,7 @@ func TestAskUserRegistryValidatesSerializedOptions(t *testing.T) { asker := &fakeAsker{} registry := NewToolRegistry() registry.RegisterTool(NewAskUserTool(asker)) - ctx := askCtx(&ToolExecContext{Interactive: true, EventBus: event.NewEventBus()}) + ctx := askCtx(&ToolExecContext{Mode: types.RunModeAttended, EventBus: event.NewEventBus()}) args, err := json.Marshal(map[string]any{"question": "which?", "options": tc.options}) require.NoError(t, err) result, err := registry.ExecuteTool(ctx, ToolAskUser, args) @@ -161,7 +163,7 @@ func TestAskUserRegistryValidatesSerializedOptions(t *testing.T) { func TestAskUserRejectsSerializedFormChoices(t *testing.T) { asker := &fakeAsker{} result, err := NewAskUserTool(asker).Execute( - askCtx(&ToolExecContext{Interactive: true, EventBus: event.NewEventBus()}), + askCtx(&ToolExecContext{Mode: types.RunModeAttended, EventBus: event.NewEventBus()}), json.RawMessage(`{"question":"which?","fields":[ {"name":"env","type":"select","options":["[\"dev\",\"prod\"]"]} ]}`)) diff --git a/internal/agent/tools/confirmed_tool.go b/internal/agent/tools/confirmed_tool.go index a2beed9d..db24784b 100644 --- a/internal/agent/tools/confirmed_tool.go +++ b/internal/agent/tools/confirmed_tool.go @@ -10,6 +10,7 @@ import ( "github.com/Tencent/WeKnora/internal/agent/approval" "github.com/Tencent/WeKnora/internal/agent/hitl" "github.com/Tencent/WeKnora/internal/agent/operations" + "github.com/Tencent/WeKnora/internal/agent/policy" "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/types" ) @@ -67,10 +68,18 @@ func (t *ConfirmedTool) Parameters() json.RawMessage { return t.inner.Parameters func (t *ConfirmedTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) { meta, _ := ToolExecFromContext(ctx) resumed := meta != nil && meta.Answered != nil && meta.Answered.Kind == types.AgentPromptKindToolApproval - if !resumed && !t.access.NeedsApprovalFor(t.risk) { + action := policy.Action{Risk: t.risk} + verdict := policy.Decide(action, t.access.Rules()) + policy.Record(ctx, t.Name(), action, t.access.Rules(), verdict) + if verdict == policy.Deny { + return operationFailure(fmt.Sprintf( + "%s changes data, which this conversation's read-only access does not allow. "+ + "Tell the user; do not retry.", t.Name())), nil + } + if !resumed && verdict == policy.Allow { return t.inner.Execute(ctx, args) } - if t.gate == nil || meta == nil || meta.EventBus == nil || (!meta.Interactive && !resumed) { + if t.gate == nil || meta == nil || meta.EventBus == nil || (!meta.CanAsk() && !resumed) { return operationFailure(fmt.Sprintf( "%s changes data and needs the user's confirmation, which cannot be shown here. "+ "Tell the user what you would do and let them do it in WeKnora.", t.Name())), nil @@ -112,6 +121,7 @@ func (t *ConfirmedTool) Execute(ctx context.Context, args json.RawMessage) (*typ ToolCallID: meta.ToolCallID, Grant: grant, GrantScope: grantScope, + GrantRisk: t.risk, }) if err != nil { return operationFailure(fmt.Sprintf("could not ask the user to confirm %s: %v", t.Name(), err)), nil @@ -173,9 +183,10 @@ type approvalGranter interface { ApprovalGrant(ctx context.Context, args json.RawMessage) (grant, scope string) } -// grant offers a session-wide approval only for recoverable changes. +// grant names the call for remembered grants. The card offers to remember +// only recoverable changes; a destructive one can match a standing grant. func (t *ConfirmedTool) grant(ctx context.Context, args json.RawMessage) (string, string) { - if t.risk != operations.RiskWrite { + if !policy.Pregrantable(policy.Action{Risk: t.risk}) { return "", "" } if g, ok := t.inner.(approvalGranter); ok { diff --git a/internal/agent/tools/exec_context.go b/internal/agent/tools/exec_context.go index cb9ef2bd..f4dd5c67 100644 --- a/internal/agent/tools/exec_context.go +++ b/internal/agent/tools/exec_context.go @@ -35,9 +35,18 @@ type ToolExecContext struct { // it raised, now answered. The tool acts on the answer instead of // raising the prompt again. Answered *types.AgentPrompt - // Interactive is set when the client can show and answer prompts; IM - // and MCP-server runs have no such surface. - Interactive bool + // Mode says whether the client can show and answer prompts; IM and + // MCP-server runs have no such surface. + Mode types.RunMode +} + +// Attended reports whether a client can answer prompts now. +func (m *ToolExecContext) Attended() bool { return m != nil && m.Mode.Attended() } + +// CanAsk reports whether the run may raise an approval, now or by suspending +// until its owner answers. +func (m *ToolExecContext) CanAsk() bool { + return m != nil && m.Mode.Normalize() != types.RunModeUnattended } // WithToolExecContext returns ctx that carries ToolExecContext for MCP approval and similar features. diff --git a/internal/agent/tools/mcp_catalog.go b/internal/agent/tools/mcp_catalog.go index ed23816c..67b7ea13 100644 --- a/internal/agent/tools/mcp_catalog.go +++ b/internal/agent/tools/mcp_catalog.go @@ -13,6 +13,7 @@ import ( "unicode/utf8" "github.com/Tencent/WeKnora/internal/agent/approval" + "github.com/Tencent/WeKnora/internal/agent/policy" "github.com/Tencent/WeKnora/internal/types" ) @@ -324,15 +325,46 @@ func (c *MCPCatalog) visibleTools(ctx context.Context, id string, tools []*MCPTo if err != nil { return nil, fmt.Errorf("MCP tool permissions are temporarily unavailable") } + offered, err := c.offeredTools(ctx, id, tools) + if err != nil { + return nil, fmt.Errorf("MCP tool permissions are temporarily unavailable") + } visible := make([]*MCPTool, 0, len(tools)) for _, tool := range tools { - if policies[tool.mcpTool.Name] { + if policies[tool.mcpTool.Name] && offered(tool) { visible = append(visible, tool) } } return visible, nil } +// offeredTools reports which tools the run's access level offers at all: a +// read-only run is not shown tools that change data. +func (c *MCPCatalog) offeredTools(ctx context.Context, id string, tools []*MCPTool) (func(*MCPTool) bool, error) { + level := types.AccessLevelFromContext(ctx) + if level != types.AssistantAccessReadOnly { + return func(*MCPTool) bool { return true }, nil + } + definitions := make([]*types.MCPTool, 0, len(tools)) + for _, tool := range tools { + definitions = append(definitions, tool.mcpTool) + } + risks := make(map[string]policy.Risk, len(tools)) + if ranker, ok := c.gate.(interface { + ToolRisks(context.Context, uint64, string, []*types.MCPTool) (map[string]policy.Risk, error) + }); ok { + var err error + if risks, err = ranker.ToolRisks(ctx, c.tenantID, id, definitions); err != nil { + return nil, err + } + } else { + for _, definition := range definitions { + risks[definition.Name] = approval.DeclaredRisk(definition) + } + } + return func(tool *MCPTool) bool { return policy.Offered(level, risks[tool.mcpTool.Name]) }, nil +} + func (c *MCPCatalog) checkEnabled(ctx context.Context, tool *MCPTool) error { if err := ctx.Err(); err != nil { return err diff --git a/internal/agent/tools/mcp_catalog_integration_test.go b/internal/agent/tools/mcp_catalog_integration_test.go index 420e8330..7a880045 100644 --- a/internal/agent/tools/mcp_catalog_integration_test.go +++ b/internal/agent/tools/mcp_catalog_integration_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/Tencent/WeKnora/internal/agent/approval" + "github.com/Tencent/WeKnora/internal/agent/policy" "github.com/Tencent/WeKnora/internal/event" internalmcp "github.com/Tencent/WeKnora/internal/mcp" "github.com/Tencent/WeKnora/internal/types" @@ -27,7 +28,10 @@ type proxyApprovalGate struct { func (g *proxyApprovalGate) IsEnabled(context.Context, uint64, string, string) (bool, error) { return !g.disabled, nil } -func (*proxyApprovalGate) NeedsApproval(context.Context, uint64, string, string) bool { return true } + +func (*proxyApprovalGate) Action(context.Context, uint64, string, *types.MCPTool) policy.Action { + return policy.Action{Risk: policy.RiskWrite, Always: true} +} func (g *proxyApprovalGate) RequestAndWait( _ context.Context, diff --git a/internal/agent/tools/mcp_catalog_test.go b/internal/agent/tools/mcp_catalog_test.go index d486da6e..baa22c11 100644 --- a/internal/agent/tools/mcp_catalog_test.go +++ b/internal/agent/tools/mcp_catalog_test.go @@ -11,6 +11,7 @@ import ( "time" "github.com/Tencent/WeKnora/internal/agent/approval" + "github.com/Tencent/WeKnora/internal/agent/policy" "github.com/Tencent/WeKnora/internal/event" "github.com/Tencent/WeKnora/internal/types" "github.com/stretchr/testify/require" @@ -24,7 +25,11 @@ type catalogPolicy struct { func (g *catalogPolicy) IsEnabled(_ context.Context, _ uint64, server, name string) (bool, error) { return !g.disabled[server+"/"+name], g.err } -func (*catalogPolicy) NeedsApproval(context.Context, uint64, string, string) bool { return false } + +func (*catalogPolicy) Action(context.Context, uint64, string, *types.MCPTool) policy.Action { + return policy.Action{Risk: policy.RiskRead} +} + func (*catalogPolicy) RequestAndWait(context.Context, approval.PendingRequest) (approval.Decision, error) { return approval.Decision{Approved: true}, nil } @@ -661,3 +666,32 @@ func TestMCPCallInvalidArgumentsExplainObjectEnvelope(t *testing.T) { require.Contains(t, result.Error, `"arguments":{}`) } } + +func TestMCPCatalogHidesWriteToolsFromReadOnlyRuns(t *testing.T) { + server := &types.MCPService{ID: "server-1", Name: "orders", Enabled: true} + for name, gate := range map[string]approval.MCPApproval{ + "policy gate": approval.NewGate(nil, nil, nil), + "custom gate": &catalogPolicy{disabled: map[string]bool{}}, + } { + t.Run(name, func(t *testing.T) { + readOnly := true + c := newMCPCatalog(catalogTestContext(), []*types.MCPService{server}, gate, + func(_ context.Context, s *types.MCPService, _ bool) ([]*MCPTool, error) { + lookup := catalogTestTool(s, "lookup", "find orders", gate) + lookup.mcpTool.Annotations = &types.MCPToolAnnotations{ReadOnlyHint: &readOnly} + return []*MCPTool{lookup, catalogTestTool(s, "cancel", "cancel orders", gate)}, nil + }, nil) + r := NewToolRegistry() + installMCPCatalog(r, c) + list := map[string]any{"mode": "list_tools", "server_id": "server-1"} + + readOnlyCtx := types.WithAccessLevel(catalogTestContext(), types.AssistantAccessReadOnly) + page := discoverPage(readOnlyCtx, t, r, list) + require.Len(t, page.Tools, 1) + require.Equal(t, "lookup", page.Tools[0].Name) + + confirmCtx := types.WithAccessLevel(catalogTestContext(), types.AssistantAccessConfirm) + require.Len(t, discoverPage(confirmCtx, t, r, list).Tools, 2) + }) + } +} diff --git a/internal/agent/tools/mcp_oauth_test.go b/internal/agent/tools/mcp_oauth_test.go index 32c9e88b..fcfe9b49 100644 --- a/internal/agent/tools/mcp_oauth_test.go +++ b/internal/agent/tools/mcp_oauth_test.go @@ -10,6 +10,7 @@ import ( "time" "github.com/Tencent/WeKnora/internal/agent/approval" + "github.com/Tencent/WeKnora/internal/agent/policy" "github.com/Tencent/WeKnora/internal/event" "github.com/Tencent/WeKnora/internal/mcp" "github.com/Tencent/WeKnora/internal/types" @@ -88,7 +89,9 @@ type approvedOAuthGate struct { oauthPrompts *int } -func (approvedOAuthGate) NeedsApproval(context.Context, uint64, string, string) bool { return true } +func (approvedOAuthGate) Action(context.Context, uint64, string, *types.MCPTool) policy.Action { + return policy.Action{Risk: policy.RiskWrite, Always: true} +} func (approvedOAuthGate) IsEnabled(context.Context, uint64, string, string) (bool, error) { return true, nil diff --git a/internal/agent/tools/mcp_tool.go b/internal/agent/tools/mcp_tool.go index 9ea24de9..264eac62 100644 --- a/internal/agent/tools/mcp_tool.go +++ b/internal/agent/tools/mcp_tool.go @@ -3,6 +3,8 @@ package tools import ( "bytes" "context" + "crypto/sha256" + "encoding/hex" "encoding/json" "fmt" "sort" @@ -12,6 +14,7 @@ import ( "github.com/Tencent/WeKnora/internal/agent/approval" "github.com/Tencent/WeKnora/internal/agent/hitl" + "github.com/Tencent/WeKnora/internal/agent/policy" "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/mcp" "github.com/Tencent/WeKnora/internal/types" @@ -178,13 +181,24 @@ func (t *MCPTool) Execute(ctx context.Context, args json.RawMessage) (*types.Too // Human approval gate for dangerous tools (issue #1173) if t.gate != nil { + tenantID, _ := types.TenantIDFromContext(ctx) + action := t.gate.Action(ctx, tenantID, t.service.ID, t.mcpTool) + rules := policy.Rules{Level: types.AccessLevelFromContext(ctx)} + verdict := policy.Decide(action, rules) + policy.Record(ctx, "mcp:"+t.service.Name+"/"+t.mcpTool.Name, action, rules, verdict) + if verdict == policy.Deny { + return &types.ToolResult{ + Success: false, + Error: "this tool changes data, which this conversation's read-only access does not allow. " + + "Tell the user; do not retry.", + }, nil + } if meta := execMeta; meta != nil && meta.EventBus != nil { - tenantID, _ := types.TenantIDFromContext(ctx) // A resumed call already holds the user's decision. It is honored // even if the tool stopped requiring approval meanwhile, since the // user may have edited the arguments. resumed := meta.Answered != nil && meta.Answered.Kind == types.AgentPromptKindToolApproval - if resumed || t.gate.NeedsApproval(ctx, tenantID, t.service.ID, t.mcpTool.Name) { + if resumed || verdict == policy.Ask { // Use ApprovalCtx (round-level ctx WITHOUT defaultToolExecTimeout) so // human approval can legitimately wait longer than the per-tool 60s. // User-stop / request cancel still propagates because ApprovalCtx is a @@ -198,6 +212,10 @@ func (t *MCPTool) Execute(ctx context.Context, args json.RawMessage) (*types.Too if resumed { decision = t.gate.ResumeDecision(waitCtx, meta.Answered, meta.EventBus) } else { + var grant, grantScope string + if policy.Pregrantable(action) { + grant, grantScope = t.approvalGrant(ctx) + } var snapshot []byte var snapshotVersion int if meta.Snapshot != nil { @@ -226,6 +244,9 @@ func (t *MCPTool) Execute(ctx context.Context, args json.RawMessage) (*types.Too Description: t.mcpTool.Description, Args: args, ToolCallID: meta.ToolCallID, + Grant: grant, + GrantScope: grantScope, + GrantRisk: action.Risk, }) } if waitErr != nil { @@ -871,3 +892,15 @@ func SerializeMCPToolResult(result *types.ToolResult) (string, error) { return output, nil } + +// approvalGrant is what approving a call of this tool may allow for the rest +// of the session: calls of the same tool while its argument schema stays the +// same, so a changed tool asks again. +func (t *MCPTool) approvalGrant(ctx context.Context) (grant, scope string) { + sum := sha256.Sum256(t.mcpTool.InputSchema) + grant = "mcp:" + t.service.ID + "/" + t.mcpTool.Name + "#" + hex.EncodeToString(sum[:6]) + if strings.HasPrefix(types.LanguageFromContextOrDefault(ctx), "zh") { + return grant, fmt.Sprintf("调用 %s 的工具 %s", t.service.Name, t.mcpTool.Name) + } + return grant, fmt.Sprintf("Call %s tool %s", t.service.Name, t.mcpTool.Name) +} diff --git a/internal/agent/tools/mcp_tool_enabled_test.go b/internal/agent/tools/mcp_tool_enabled_test.go index 61fd0a45..cf8629a7 100644 --- a/internal/agent/tools/mcp_tool_enabled_test.go +++ b/internal/agent/tools/mcp_tool_enabled_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/Tencent/WeKnora/internal/agent/approval" + "github.com/Tencent/WeKnora/internal/agent/policy" "github.com/Tencent/WeKnora/internal/event" "github.com/Tencent/WeKnora/internal/types" "github.com/stretchr/testify/require" @@ -17,8 +18,8 @@ type staticPolicyGate struct { err error } -func (g staticPolicyGate) NeedsApproval(context.Context, uint64, string, string) bool { - return false +func (g staticPolicyGate) Action(context.Context, uint64, string, *types.MCPTool) policy.Action { + return policy.Action{Risk: policy.RiskRead} } func (g staticPolicyGate) IsEnabled(context.Context, uint64, string, string) (bool, error) { diff --git a/internal/agent/tools/mcp_tool_grant_test.go b/internal/agent/tools/mcp_tool_grant_test.go new file mode 100644 index 00000000..d7124dba --- /dev/null +++ b/internal/agent/tools/mcp_tool_grant_test.go @@ -0,0 +1,26 @@ +package tools + +import ( + "context" + "encoding/json" + "testing" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/stretchr/testify/assert" +) + +func TestMCPGrantKeyFollowsTheToolContract(t *testing.T) { + svc := &types.MCPService{ID: "svc", Name: "Tracker"} + tool := func(schema string) *MCPTool { + return NewMCPTool(svc, &types.MCPTool{Name: "create_issue", InputSchema: json.RawMessage(schema)}, nil, nil, 0) + } + ctx := context.Background() + key, label := tool(`{"type":"object"}`).approvalGrant(ctx) + same, _ := tool(`{"type":"object"}`).approvalGrant(ctx) + changed, _ := tool(`{"type":"object","properties":{"x":{}}}`).approvalGrant(ctx) + + assert.Equal(t, key, same) + assert.NotEqual(t, key, changed, "a changed input schema needs a fresh approval") + assert.Contains(t, key, "mcp:svc/create_issue#") + assert.Contains(t, label, "Tracker") +} diff --git a/internal/agent/tools/operations.go b/internal/agent/tools/operations.go index f65e3ae7..91493d14 100644 --- a/internal/agent/tools/operations.go +++ b/internal/agent/tools/operations.go @@ -13,6 +13,7 @@ import ( "github.com/Tencent/WeKnora/internal/agent/approval" "github.com/Tencent/WeKnora/internal/agent/operations" + "github.com/Tencent/WeKnora/internal/agent/policy" "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/types" ) @@ -368,11 +369,15 @@ func (t *RunOperationTool) Execute(ctx context.Context, args json.RawMessage) (* identity.Agent.SessionID = meta.SessionID } identity.Agent.Operation = op.ID + identity.Agent.ActingVia = types.ActingViaFromContext(ctx) // An answered prompt still governs its blocked call even if the workspace // now allows writes without approval. Preserve declines and edited params. resumed := meta != nil && meta.Answered != nil && meta.Answered.Kind == types.AgentPromptKindToolApproval - if resumed || t.rt.Access.NeedsApproval(op) { + action := policy.Action{Risk: op.Risk, Always: op.AlwaysConfirm} + verdict := policy.Decide(action, t.rt.Access.Rules()) + policy.Record(ctx, op.ID, action, t.rt.Access.Rules(), verdict) + if resumed || verdict != policy.Allow { confirmed, blocked := t.confirm(ctx, op, input, identity) if blocked != nil { return blocked, nil @@ -501,7 +506,7 @@ func (t *RunOperationTool) confirm( ) (confirmedCall, *types.ToolResult) { meta, _ := ToolExecFromContext(ctx) resumed := meta != nil && meta.Answered != nil && meta.Answered.Kind == types.AgentPromptKindToolApproval - if t.rt.Gate == nil || meta == nil || meta.EventBus == nil || (!meta.Interactive && !resumed) { + if t.rt.Gate == nil || meta == nil || meta.EventBus == nil || (!meta.CanAsk() && !resumed) { return confirmedCall{}, operationFailure(fmt.Sprintf( "%s changes data and needs the user's confirmation, which cannot be shown here. "+ "Tell the user what you would do and let them do it in WeKnora.", op.ID)) @@ -551,6 +556,7 @@ func (t *RunOperationTool) confirm( ToolCallID: meta.ToolCallID, Grant: grant, GrantScope: grantScope, + GrantRisk: op.Risk, }) if err != nil { msg := fmt.Sprintf("could not ask the user to confirm %s: %v", op.ID, err) @@ -711,7 +717,7 @@ func (t *RunOperationTool) readTarget( func approvalGrant( ctx context.Context, op operations.Operation, params map[string]json.RawMessage, target operations.Projected, ) (grant, scope string) { - if op.Risk != operations.RiskWrite || op.AlwaysConfirm { + if !policy.Pregrantable(policy.Action{Risk: op.Risk, Always: op.AlwaysConfirm}) { return "", "" } declared := func(name string) string { diff --git a/internal/agent/tools/operations_faq_test.go b/internal/agent/tools/operations_faq_test.go index ec63e329..5cab0faf 100644 --- a/internal/agent/tools/operations_faq_test.go +++ b/internal/agent/tools/operations_faq_test.go @@ -133,7 +133,7 @@ func TestRunOperationFAQUpdateRechecksApprovedTarget(t *testing.T) { switch scenario { case "resumed": meta, _ := ToolExecFromContext(ctx) - meta.Interactive = false + meta.Mode = types.RunModeUnattended meta.Answered = &types.AgentPrompt{Kind: types.AgentPromptKindToolApproval} d.responses["GET "+faqEntryPath] = long case "edited target": diff --git a/internal/agent/tools/operations_grant_test.go b/internal/agent/tools/operations_grant_test.go index a9c5a07c..488c689c 100644 --- a/internal/agent/tools/operations_grant_test.go +++ b/internal/agent/tools/operations_grant_test.go @@ -61,7 +61,11 @@ func TestRunOperationGrantFollowsTheTargetScope(t *testing.T) { map[string]any{"agent_id": "a1", "name": "Bot"}, "agent.update agent:a1", `(only for agent "Support bot")`, }, - {"deletion", "knowledge.delete", map[string]any{"knowledge_id": "k1"}, "", ""}, + { + "deletion, matched only by a standing grant", "knowledge.delete", + map[string]any{"knowledge_id": "k1"}, + "knowledge.delete knowledge_base:kb1", "(only in the knowledge bases this call touches)", + }, {"creation without a scope", "knowledge_base.create", map[string]any{"name": "New"}, "", ""}, } { t.Run(tc.name, func(t *testing.T) { @@ -121,5 +125,8 @@ func TestConfirmedToolOffersGrantsOnlyForRecoverableChanges(t *testing.T) { require.Len(t, gate.requests, 2) assert.Equal(t, ToolWikiReplaceText+" knowledge_base:kb1,kb2", gate.requests[0].Grant) assert.Equal(t, "Edit Wiki page text", gate.requests[0].GrantScope) - assert.Empty(t, gate.requests[1].Grant, "a deletion always asks") + assert.Equal(t, ToolWikiDeletePage+" knowledge_base:kb1", gate.requests[1].Grant, + "a deletion is named so a standing grant can match it") + assert.Equal(t, operations.RiskDestructive, gate.requests[1].GrantRisk, + "and the gate never offers to remember it from the card") } diff --git a/internal/agent/tools/operations_test.go b/internal/agent/tools/operations_test.go index 141d1882..7b7819e9 100644 --- a/internal/agent/tools/operations_test.go +++ b/internal/agent/tools/operations_test.go @@ -86,7 +86,7 @@ func newRunTool(d *fakeDispatcher, gate approval.BuiltinApproval) *RunOperationT func interactiveCtx() context.Context { return WithToolExecContext(context.Background(), &ToolExecContext{ SessionID: "s1", UserID: "web_user:u1", ToolCallID: "call-1", - EventBus: event.NewEventBus(), Interactive: true, + EventBus: event.NewEventBus(), Mode: types.RunModeAttended, }) } @@ -597,7 +597,7 @@ func TestRunOperationAutoWriteHonorsResumedAnswer(t *testing.T) { tool.rt.Access.Level = types.AssistantAccessAutoWrite ctx := interactiveCtx() meta, _ := ToolExecFromContext(ctx) - meta.Interactive = false + meta.Mode = types.RunModeUnattended meta.Answered = &types.AgentPrompt{Kind: types.AgentPromptKindToolApproval} res, err := tool.Execute(ctx, runArgs("knowledge.reparse", map[string]any{"knowledge_id": "k1"})) require.NoError(t, err) diff --git a/internal/agent/tools/page_tools.go b/internal/agent/tools/page_tools.go index 8fdf937e..b3ff2c22 100644 --- a/internal/agent/tools/page_tools.go +++ b/internal/agent/tools/page_tools.go @@ -318,7 +318,7 @@ func requestPageAction( ctx context.Context, actor approval.PageActor, action types.PageActionPromptRequest, ) (approval.PageActionResult, *types.ToolResult) { meta, _ := ToolExecFromContext(ctx) - if actor == nil || meta == nil || !meta.Interactive || meta.EventBus == nil { + if actor == nil || !meta.Attended() || meta.EventBus == nil { return approval.PageActionResult{}, operationFailure( "the user's page cannot be reached from this conversation; ask the user instead") } diff --git a/internal/agent/tools/page_tools_test.go b/internal/agent/tools/page_tools_test.go index 0a32bf34..fdda5e61 100644 --- a/internal/agent/tools/page_tools_test.go +++ b/internal/agent/tools/page_tools_test.go @@ -29,7 +29,7 @@ func (f *fakePageActor) RequestPageAction( func pageToolContext() context.Context { return WithToolExecContext(context.Background(), &ToolExecContext{ SessionID: "s1", AssistantMessageID: "m1", ToolCallID: "tc1", UserID: "user:u1", - EventBus: event.NewEventBus(), Interactive: true, + EventBus: event.NewEventBus(), Mode: types.RunModeAttended, }) } diff --git a/internal/application/repository/agent_grant_repository.go b/internal/application/repository/agent_grant_repository.go new file mode 100644 index 00000000..ff99ec98 --- /dev/null +++ b/internal/application/repository/agent_grant_repository.go @@ -0,0 +1,117 @@ +package repository + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "gorm.io/gorm" + "gorm.io/gorm/clause" +) + +type agentGrantRepository struct { + db *gorm.DB +} + +// NewAgentGrantRepository creates a repository backed by GORM. +func NewAgentGrantRepository(db *gorm.DB) interfaces.AgentGrantRepository { + return &agentGrantRepository{db: db} +} + +func (r *agentGrantRepository) FindGrant( + ctx context.Context, tenantID uint64, userID string, scope types.GrantScope, key string, +) (*types.AgentGrant, error) { + var grant types.AgentGrant + err := r.db.WithContext(ctx). + Where("tenant_id = ? AND user_id = ? AND scope = ? AND scope_id = ? AND grant_key = ?", + tenantID, userID, scope.Scope, scope.ScopeID, key). + First(&grant).Error + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("find agent grant: %w", err) + } + return &grant, nil +} + +func (r *agentGrantRepository) SaveGrant(ctx context.Context, grant *types.AgentGrant) error { + if grant == nil || grant.TenantID == 0 || grant.UserID == "" || grant.Scope == "" || + grant.ScopeID == "" || grant.GrantKey == "" { + return errors.New("agent grant identity is required") + } + if grant.Risk == "" { + grant.Risk = "write" + } + now := time.Now() + if grant.CreatedAt.IsZero() { + grant.CreatedAt = now + } + grant.UpdatedAt = now + err := r.db.WithContext(ctx).Clauses(clause.OnConflict{ + Columns: []clause.Column{ + {Name: "tenant_id"}, {Name: "user_id"}, {Name: "scope"}, {Name: "scope_id"}, {Name: "grant_key"}, + }, + DoUpdates: clause.Assignments(map[string]interface{}{ + "label": grant.Label, + "binding_hash": grant.BindingHash, + "risk": grant.Risk, + "prompt_id": grant.PromptID, + "created_at": grant.CreatedAt, + "updated_at": now, + "last_used_at": nil, + "expires_at": grant.ExpiresAt, + "revoked_at": nil, + }), + }).Create(grant).Error + if err != nil { + return fmt.Errorf("save agent grant: %w", err) + } + return nil +} + +func (r *agentGrantRepository) TouchGrant(ctx context.Context, id string, at time.Time) error { + return r.db.WithContext(ctx).Model(&types.AgentGrant{}).Where("id = ?", id). + UpdateColumn("last_used_at", at).Error +} + +func (r *agentGrantRepository) ListGrants( + ctx context.Context, tenantID uint64, userID, scope, scopeID string, +) ([]*types.AgentGrant, error) { + var grants []*types.AgentGrant + err := r.db.WithContext(ctx). + Where("tenant_id = ? AND user_id = ? AND scope = ? AND scope_id = ? AND revoked_at IS NULL", + tenantID, userID, scope, scopeID). + Order("created_at DESC"). + Find(&grants).Error + if err != nil { + return nil, fmt.Errorf("list agent grants: %w", err) + } + return grants, nil +} + +func (r *agentGrantRepository) RevokeGrant( + ctx context.Context, tenantID uint64, userID, id string, at time.Time, +) (bool, error) { + res := r.db.WithContext(ctx).Model(&types.AgentGrant{}). + Where("id = ? AND tenant_id = ? AND user_id = ? AND revoked_at IS NULL", id, tenantID, userID). + Updates(map[string]interface{}{"revoked_at": at, "updated_at": at}) + if res.Error != nil { + return false, fmt.Errorf("revoke agent grant: %w", res.Error) + } + return res.RowsAffected > 0, nil +} + +func (r *agentGrantRepository) DeleteScopes( + ctx context.Context, tenantID uint64, scope string, scopeIDs []string, +) error { + if len(scopeIDs) == 0 { + return nil + } + return r.db.WithContext(ctx). + Where("tenant_id = ? AND scope = ? AND scope_id IN ?", tenantID, scope, scopeIDs). + Delete(&types.AgentGrant{}).Error +} diff --git a/internal/application/repository/agent_grant_repository_test.go b/internal/application/repository/agent_grant_repository_test.go new file mode 100644 index 00000000..5739496d --- /dev/null +++ b/internal/application/repository/agent_grant_repository_test.go @@ -0,0 +1,73 @@ +package repository + +import ( + "context" + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/sqlite" + "gorm.io/gorm" +) + +func TestAgentGrantRepositoryLifecycle(t *testing.T) { + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + require.NoError(t, err) + sqlDB, err := db.DB() + require.NoError(t, err) + sqlDB.SetMaxOpenConns(1) + t.Cleanup(func() { require.NoError(t, sqlDB.Close()) }) + require.NoError(t, db.AutoMigrate(&types.AgentGrant{})) + + ctx := context.Background() + repo := NewAgentGrantRepository(db) + scope := types.GrantScope{Scope: types.AgentGrantScopeSession, ScopeID: "root"} + save := func(user, label string) { + require.NoError(t, repo.SaveGrant(ctx, &types.AgentGrant{ + TenantID: 7, UserID: user, Scope: scope.Scope, ScopeID: scope.ScopeID, + GrantKey: "mcp:svc/write#abc", Label: label, + })) + } + save("u1", "first") + save("u2", "other user") + + found, err := repo.FindGrant(ctx, 7, "u1", scope, "mcp:svc/write#abc") + require.NoError(t, err) + require.NotNil(t, found) + missing, err := repo.FindGrant(ctx, 8, "u1", scope, "mcp:svc/write#abc") + require.NoError(t, err) + assert.Nil(t, missing, "grants do not cross tenants") + + used := time.Now() + require.NoError(t, repo.TouchGrant(ctx, found.ID, used)) + listed, err := repo.ListGrants(ctx, 7, "u1", scope.Scope, scope.ScopeID) + require.NoError(t, err) + require.Len(t, listed, 1) + require.NotNil(t, listed[0].LastUsedAt) + + revoked, err := repo.RevokeGrant(ctx, 7, "u2", found.ID, time.Now()) + require.NoError(t, err) + assert.False(t, revoked, "only the owner revokes a grant") + revoked, err = repo.RevokeGrant(ctx, 7, "u1", found.ID, time.Now()) + require.NoError(t, err) + assert.True(t, revoked) + listed, err = repo.ListGrants(ctx, 7, "u1", scope.Scope, scope.ScopeID) + require.NoError(t, err) + assert.Empty(t, listed) + + save("u1", "again") + again, err := repo.FindGrant(ctx, 7, "u1", scope, "mcp:svc/write#abc") + require.NoError(t, err) + require.NotNil(t, again) + assert.Equal(t, found.ID, again.ID, "approving again revives the same row") + assert.Nil(t, again.RevokedAt) + assert.Nil(t, again.LastUsedAt) + assert.Equal(t, "again", again.Label) + + require.NoError(t, repo.DeleteScopes(ctx, 7, scope.Scope, []string{"root"})) + gone, err := repo.FindGrant(ctx, 7, "u1", scope, "mcp:svc/write#abc") + require.NoError(t, err) + assert.Nil(t, gone) +} diff --git a/internal/application/repository/mcp_tool_approval_repository.go b/internal/application/repository/mcp_tool_approval_repository.go index 5cbcaf69..c25a64a3 100644 --- a/internal/application/repository/mcp_tool_approval_repository.go +++ b/internal/application/repository/mcp_tool_approval_repository.go @@ -36,6 +36,23 @@ func (r *MCPToolApprovalRepository) ListByService(ctx context.Context, tenantID return rows, nil } +// Get returns the stored policy of a tool, or nil when it has none. +func (r *MCPToolApprovalRepository) Get( + ctx context.Context, tenantID uint64, serviceID, toolName string, +) (*types.MCPToolApproval, error) { + var row types.MCPToolApproval + err := r.db.WithContext(ctx). + Where("tenant_id = ? AND service_id = ? AND tool_name = ?", tenantID, serviceID, toolName). + First(&row).Error + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("get mcp tool policy: %w", err) + } + return &row, nil +} + // IsRequired returns true when a row exists with require_approval = true. func (r *MCPToolApprovalRepository) IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) { var row types.MCPToolApproval @@ -69,7 +86,15 @@ func (r *MCPToolApprovalRepository) IsEnabled(ctx context.Context, tenantID uint return row.Enabled, nil } +// riskRankSQL ranks a risk column as policy.Risk.Above does; unknown and +// empty risks rank lowest. +func riskRankSQL(column string) string { + return "(CASE " + column + + " WHEN 'read' THEN 1 WHEN 'probe' THEN 2 WHEN 'write' THEN 3 WHEN 'destructive' THEN 4 ELSE 0 END)" +} + // UpsertPolicy creates or updates only the supplied policy columns. +// ObservedRisk only ever raises the stored value. // Concurrent patches of different fields cannot clobber each other because // ON CONFLICT updates omit unchanged columns. A first insert uses // require_approval=false and enabled=true for any field the patch omits. @@ -79,8 +104,8 @@ func (r *MCPToolApprovalRepository) UpsertPolicy( if serviceID == "" || toolName == "" { return errors.New("service_id and tool_name are required") } - if patch.RequireApproval == nil && patch.Enabled == nil { - return errors.New("require_approval or enabled is required") + if patch.RequireApproval == nil && patch.Enabled == nil && patch.Risk == nil && patch.ObservedRisk == nil { + return errors.New("an MCP tool policy field is required") } now := time.Now() @@ -100,6 +125,20 @@ func (r *MCPToolApprovalRepository) UpsertPolicy( if patch.Enabled != nil { updates["enabled"] = *patch.Enabled } + risk, observed := "", "" + if patch.Risk != nil { + risk = *patch.Risk + updates["risk"] = risk + } + if patch.ObservedRisk != nil { + observed = *patch.ObservedRisk + // Compare in the statement itself: a concurrent lower observation + // read before this one landed must not overwrite it. + updates["observed_risk"] = gorm.Expr( + "CASE WHEN " + riskRankSQL("excluded.observed_risk") + " > " + + riskRankSQL("mcp_tool_approvals.observed_risk") + + " THEN excluded.observed_risk ELSE mcp_tool_approvals.observed_risk END") + } row := map[string]interface{}{ "id": uuid.New().String(), @@ -108,6 +147,8 @@ func (r *MCPToolApprovalRepository) UpsertPolicy( "tool_name": toolName, "require_approval": requireApproval, "enabled": enabled, + "risk": risk, + "observed_risk": observed, "created_at": now, "updated_at": now, } diff --git a/internal/application/repository/mcp_tool_approval_repository_test.go b/internal/application/repository/mcp_tool_approval_repository_test.go index fd169337..6554a715 100644 --- a/internal/application/repository/mcp_tool_approval_repository_test.go +++ b/internal/application/repository/mcp_tool_approval_repository_test.go @@ -130,3 +130,48 @@ func TestMCPToolApprovalConcurrentColumnPatches(t *testing.T) { require.NoError(t, err) require.True(t, required) } + +func TestMCPToolApprovalObservedRiskOnlyRises(t *testing.T) { + repo := newMCPToolApprovalTestRepo(t) + ctx := context.Background() + observe := func(risk string) string { + require.NoError(t, repo.UpsertPolicy(ctx, 1, "svc", "tool", types.MCPToolPolicyPatch{ObservedRisk: &risk})) + row, err := repo.Get(ctx, 1, "svc", "tool") + require.NoError(t, err) + return row.ObservedRisk + } + require.Equal(t, "read", observe("read"), "the first observation is recorded") + require.Equal(t, "write", observe("write")) + require.Equal(t, "write", observe("read"), "a stale lower observation does not lower it") + require.Equal(t, "write", observe("probe")) + require.Equal(t, "destructive", observe("destructive")) +} + +func TestMCPToolApprovalConcurrentObservationsKeepTheHighest(t *testing.T) { + repo := newMCPToolApprovalTestRepo(t) + ctx := context.Background() + var wg sync.WaitGroup + start := make(chan struct{}) + errs := make(chan error, 20) + for i := range 20 { + risk := "read" + if i == 7 { + risk = "write" + } + wg.Add(1) + go func() { + defer wg.Done() + <-start + errs <- repo.UpsertPolicy(ctx, 1, "svc", "tool", types.MCPToolPolicyPatch{ObservedRisk: &risk}) + }() + } + close(start) + wg.Wait() + close(errs) + for err := range errs { + require.NoError(t, err) + } + row, err := repo.Get(ctx, 1, "svc", "tool") + require.NoError(t, err) + require.Equal(t, "write", row.ObservedRisk) +} diff --git a/internal/application/service/agent_collaboration.go b/internal/application/service/agent_collaboration.go index 65195c0a..19781462 100644 --- a/internal/application/service/agent_collaboration.go +++ b/internal/application/service/agent_collaboration.go @@ -85,6 +85,11 @@ func (s *AgentCollaboration) forgetSessions(ctx context.Context, tenantID uint64 if len(sessionIDs) == 0 { return } + if err := s.db.WithContext(ctx). + Where("tenant_id = ? AND scope = ? AND scope_id IN ?", tenantID, types.AgentGrantScopeSession, sessionIDs). + Delete(&types.AgentGrant{}).Error; err != nil { + logger.Warnf(ctx, "Delete grants of deleted sessions: %v", err) + } var rows []collaboration.Record query := s.db.WithContext(ctx).Where("tenant_id = ? AND session_id IN ?", tenantID, sessionIDs) if userID != "" { @@ -177,12 +182,36 @@ func (s *AgentCollaboration) prune(ctx context.Context) error { } type delegatedConfig struct { - Agent types.CustomAgent `json:"agent"` - Access types.AssistantAccessLevel `json:"access"` - Inherited *inheritedAgentConfig `json:"inherited,omitempty"` + Agent types.CustomAgent `json:"agent"` + Access types.AssistantAccessLevel `json:"access"` + // AssistantParent records that the delegating run was the WeKnora + // assistant, whose level stays under the workspace's assistant ceiling. + AssistantParent bool `json:"assistant_parent,omitempty"` + Inherited *inheritedAgentConfig `json:"inherited,omitempty"` +} + +// level is the child's access level: the delegating run's, capped by the +// child agent's own ceiling and, under an assistant parent, by the +// workspace's current assistant ceiling. +func (d *delegatedConfig) level(tenant *types.Tenant) types.AssistantAccessLevel { + level := types.CapAccessLevel(d.Access, d.Agent.Config.AccessLevel) + if d.AssistantParent || (d.Inherited != nil && d.Inherited.OperationsAgentID != "") { + var assistant *types.AssistantConfig + if tenant != nil { + assistant = tenant.AssistantConfig + } + level = types.CapAccessLevel(level, assistant.EffectiveAccessLevel(d.Access)) + } + return level } func (s *AgentCollaboration) resolve(ctx context.Context, id string, level types.AssistantAccessLevel) (string, error) { + return s.resolveDelegated(ctx, id, level, false) +} + +func (s *AgentCollaboration) resolveDelegated( + ctx context.Context, id string, level types.AssistantAccessLevel, assistantParent bool, +) (string, error) { a, err := s.agents.GetAgentByID(ctx, id) if err != nil { return "", err @@ -193,7 +222,7 @@ func (s *AgentCollaboration) resolve(ctx context.Context, id string, level types id == types.BuiltinSkillInstallerID { return "", errors.New("only same-workspace reasoning agents without management privileges may be delegated") } - data, err := json.Marshal(delegatedConfig{Agent: *a, Access: level}) + data, err := json.Marshal(delegatedConfig{Agent: *a, Access: level, AssistantParent: assistantParent}) return string(data), err } @@ -246,7 +275,7 @@ func (s *AgentCollaboration) attach( if strings.TrimSpace(id) == "" { return inheritedChildSnapshot(ctx, cfg, registry.ListTools()) } - return s.resolve(ctx, id, cfg.AssistantAccess) + return s.resolveDelegated(ctx, id, cfg.AssistantAccess, cfg.OperationsAgentID != "") }) { registry.RegisterTool(tool) } @@ -265,7 +294,12 @@ func (s *AgentCollaboration) attach( if err := json.Unmarshal([]byte(b.Child.Member.ConfigJSON), &pinned); err != nil { return err } - cfg.AssistantAccess = pinned.Access + workerCtx, err := s.workerContext(ctx, b.Scope) + if err != nil { + return err + } + tenant, _ := workerCtx.Value(types.TenantInfoContextKey).(*types.Tenant) + cfg.AssistantAccess = pinned.level(tenant) if pinned.Inherited != nil { registry.RestrictTools(append(append([]string(nil), pinned.Inherited.ToolNames...), "send_message")) } @@ -277,17 +311,15 @@ func (s *AgentCollaboration) attach( } } } - // Inherited workers may use arbitrary sandbox tools. Give mutations an - // actual approval path instead of the legacy template guard's dead end. - if pinned.Inherited != nil { - for _, name := range registry.ListTools() { - if inheritedToolOwnsPolicy(name) { - continue - } - if err := registry.RequireConfirmation(name, operations.RiskWrite, - operations.Access{Level: cfg.AssistantAccess}, s.gate); err != nil { - return err - } + // Workers may use arbitrary sandbox tools. Give mutations the same + // approval path as the parent's instead of refusing them. + for _, name := range registry.ListTools() { + if _, wrapped := assistantWriteToolRisk[name]; wrapped || inheritedToolOwnsPolicy(name) { + continue + } + if err := registry.RequireConfirmation(name, operations.RiskWrite, + operations.Access{Level: cfg.AssistantAccess}, s.gate); err != nil { + return err } } registry.SetExecutionGuard(func(ctx context.Context, tool types.Tool) error { @@ -309,28 +341,10 @@ func (s *AgentCollaboration) attach( return nil } currentTenant, _ := currentCtx.Value(types.TenantInfoContextKey).(*types.Tenant) - currentAccess := currentTenant.AssistantConfig.EffectiveAccessLevel(saved.Access) - if currentAccess != cfg.AssistantAccess { + if saved.level(currentTenant) != cfg.AssistantAccess { return errors.New("delegated access changed; start a newly authorized turn") } - if _, writes := assistantWriteToolRisk[tool.Name()]; writes { - return nil - } - if saved.Inherited != nil { - return nil // Registered tools own their policy or were wrapped above. - } - if strings.HasPrefix(tool.Name(), "mcp_") || tool.Name() == tools.ToolCallMCPTool || - tool.Name() == "ask_user" { - return nil - } - saved.Access = currentAccess - if saved.Access == types.AssistantAccessAutoWrite { - return nil - } - return fmt.Errorf( - "delegated tool %s requires approval in the parent conversation; this child cannot grant approval", - tool.Name(), - ) + return nil // Registered tools own their policy or were wrapped above. }) } return nil @@ -399,7 +413,7 @@ func (s *AgentCollaboration) run(ctx context.Context, w collaboration.Work) (col } } tenant, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant) - saved.Access = tenant.AssistantConfig.EffectiveAccessLevel(saved.Access) + saved.Access = saved.level(tenant) // Store the attenuated permission in this worker's private binding too. configJSON, err := json.Marshal(saved) if err != nil { @@ -496,7 +510,6 @@ func (s *AgentCollaboration) run(ctx context.Context, w collaboration.Work) (col } } ctx = hitl.WithDelegation(ctx, hitl.Delegation{ - RequireApproval: saved.Access != types.AssistantAccessAutoWrite, Register: func(ctx context.Context, p *types.AgentPrompt) error { if p.TenantID != w.Scope.TenantID || p.UserID != delegatedPromptUser(w.Scope.UserID) || p.SessionID != session.ID || @@ -597,7 +610,8 @@ func (s *AgentCollaboration) run(ctx context.Context, w collaboration.Work) (col ctx, &types.QARequest{ Resume: resume, - Interactive: true, + Mode: types.RunModeAttended, + GrantSessionID: w.Scope.SessionID, Suspendable: true, Session: session, Query: w.Run.Query, diff --git a/internal/application/service/agent_collaboration_inherited.go b/internal/application/service/agent_collaboration_inherited.go index 7c40f433..e2d8e806 100644 --- a/internal/application/service/agent_collaboration_inherited.go +++ b/internal/application/service/agent_collaboration_inherited.go @@ -75,11 +75,16 @@ func inheritedChildSnapshot(ctx context.Context, cfg *types.AgentConfig, toolNam } } // Marshal immediately: later changes to parent config cannot change queued work. - data, err := json.Marshal(delegatedConfig{Agent: *source.Agent, Access: cfg.AssistantAccess, Inherited: inherited}) + data, err := json.Marshal(delegatedConfig{ + Agent: *source.Agent, Access: cfg.AssistantAccess, AssistantParent: cfg.OperationsAgentID != "", + Inherited: inherited, + }) return string(data), err } -func inheritedConfigFromBinding(ctx context.Context) (*delegatedConfig, error) { +// delegatedConfigFromBinding is the pinned configuration of the delegated +// child running on ctx, or nil outside one. +func delegatedConfigFromBinding(ctx context.Context) (*delegatedConfig, error) { b := collaboration.FromContext(ctx) if b == nil || b.Child == nil { return nil, nil @@ -88,13 +93,19 @@ func inheritedConfigFromBinding(ctx context.Context) (*delegatedConfig, error) { if err := json.Unmarshal([]byte(b.Child.Member.ConfigJSON), &saved); err != nil { return nil, err } - if saved.Inherited == nil { - return nil, nil + return &saved, nil +} + +func inheritedConfigFromBinding(ctx context.Context) (*delegatedConfig, error) { + saved, err := delegatedConfigFromBinding(ctx) + if err != nil || saved == nil || saved.Inherited == nil { + return nil, err } + b := collaboration.FromContext(ctx) if saved.Agent.TenantID != b.Scope.TenantID || saved.Inherited.ModelID == "" { return nil, errors.New("invalid inherited execution scope") } - return &saved, nil + return saved, nil } // restoreInheritedConfig keeps the parent's resolved scope, including document @@ -109,7 +120,7 @@ func (s *sessionService) restoreInheritedConfig( cfg.SandboxConfigID = snapshot.SandboxConfigID cfg.OperationsAgentID = snapshot.OperationsAgentID cfg.AssistantName = snapshot.AssistantName - cfg.AssistantAccess = tenant.AssistantConfig.EffectiveAccessLevel(saved.Access) + cfg.AssistantAccess = saved.level(tenant) cfg.ProductDocs = snapshot.ProductDocs cfg.LocalBrowserEnabled = snapshot.LocalBrowserEnabled cfg.AttachmentParseWaitTimeoutSec = snapshot.AttachmentParseWaitTimeoutSec diff --git a/internal/application/service/agent_collaboration_inherited_test.go b/internal/application/service/agent_collaboration_inherited_test.go index 26273a6e..9d2a09fe 100644 --- a/internal/application/service/agent_collaboration_inherited_test.go +++ b/internal/application/service/agent_collaboration_inherited_test.go @@ -59,7 +59,14 @@ func TestInheritedChildSnapshotKeepsEffectiveScopeWithoutSecrets(t *testing.T) { } restored, err := svc.restoreInheritedConfig(ctx, &saved, tenant) require.NoError(t, err) - require.Equal(t, types.AssistantAccessConfirm, restored.AssistantAccess) + require.Equal(t, types.AssistantAccessAutoWrite, restored.AssistantAccess, + "an ordinary agent's child is not held to the assistant ceiling") + assistantChild := saved + assistantChild.AssistantParent = true + capped, err := svc.restoreInheritedConfig(ctx, &assistantChild, tenant) + require.NoError(t, err) + require.Equal(t, types.AssistantAccessConfirm, capped.AssistantAccess, + "the assistant's child stays under the workspace's current ceiling") require.Equal(t, []string{"doc"}, restored.SearchTargets[0].KnowledgeIDs) require.Equal(t, []string{"tag"}, restored.SearchTargets[0].TagIDs) require.Equal(t, []string{"kb"}, restored.WritableKBIDs) @@ -72,7 +79,7 @@ func TestInheritedChildSnapshotKeepsEffectiveScopeWithoutSecrets(t *testing.T) { require.True(t, restored.MultiTurnEnabled) require.Empty(t, restored.TenantSkills, "unavailable installed skills must not be restored from stale bodies") tenant.AssistantConfig.MaxAccessLevel = types.AssistantAccessReadOnly - restored, err = svc.restoreInheritedConfig(ctx, &saved, tenant) + restored, err = svc.restoreInheritedConfig(ctx, &assistantChild, tenant) require.NoError(t, err) require.Empty(t, restored.WritableKBIDs) svc.knowledgeBaseService = &tagTargetKnowledgeBaseService{kbs: map[string]*types.KnowledgeBase{}} diff --git a/internal/application/service/agent_collaboration_mcp_test.go b/internal/application/service/agent_collaboration_mcp_test.go index 424b99d9..89bbd2b0 100644 --- a/internal/application/service/agent_collaboration_mcp_test.go +++ b/internal/application/service/agent_collaboration_mcp_test.go @@ -157,7 +157,7 @@ func testCollaborationMCPApproval(t *testing.T, inherited bool) { if err := s.attach(ctx, engine, registry, cfg, req.Session.ID, req.AssistantMessageID); err != nil { return err } - engine.SetInteractive(true) + engine.SetRunMode(types.RunModeAttended) engine.EnableSuspension(json.RawMessage(`{}`)) if req.Resume != nil { _, err := engine.Resume( @@ -176,7 +176,7 @@ func testCollaborationMCPApproval(t *testing.T, inherited bool) { ) scope := collaboration.Scope{TenantID: 7, UserID: "u", SessionID: "parent", ID: "parent-message"} require.NoError(t, s.Runtime.Store.Ensure(ctx, scope)) - config, err := s.resolve(ctx, "a", types.AssistantAccessReadOnly) + config, err := s.resolve(ctx, "a", types.AssistantAccessConfirm) id := "a" if inherited { id = "" @@ -185,7 +185,7 @@ func testCollaborationMCPApproval(t *testing.T, inherited bool) { }) name := tools.NewMCPTool(svc, &types.MCPTool{Name: "write"}, manager, gate, 0).Name() config, err = inheritedChildSnapshot(ctx, &types.AgentConfig{ - MaxIterations: 5, AssistantAccess: types.AssistantAccessReadOnly, + MaxIterations: 5, AssistantAccess: types.AssistantAccessConfirm, }, []string{name}) } require.NoError(t, err) diff --git a/internal/application/service/agent_collaboration_recovery.go b/internal/application/service/agent_collaboration_recovery.go index 620c6b3b..223f2c3c 100644 --- a/internal/application/service/agent_collaboration_recovery.go +++ b/internal/application/service/agent_collaboration_recovery.go @@ -306,7 +306,7 @@ func (s *AgentCollaboration) resumeParent(ctx context.Context, b *collaboration. KnowledgeBaseIDs: saved.KnowledgeBaseIDs, KnowledgeIDs: saved.KnowledgeIDs, TagScopes: saved.TagScopes, MCPServiceIDs: saved.MCPServiceIDs, SkillNames: saved.SkillNames, WebSearchEnabled: saved.WebSearchEnabled, QuestionOrigin: saved.QuestionOrigin, PageContext: saved.PageContext, AssistantAccess: saved.AssistantAccess, - Interactive: true, Suspendable: true, Resume: &types.AgentResume{Snapshot: data}, + Mode: types.RunModeAttended, Suspendable: true, Resume: &types.AgentResume{Snapshot: data}, } if s.ParentSteer != nil { req.SteerSink = s.ParentSteer(ctx, session, answer) diff --git a/internal/application/service/agent_collaboration_regression_test.go b/internal/application/service/agent_collaboration_regression_test.go index cc840d78..ae35cc95 100644 --- a/internal/application/service/agent_collaboration_regression_test.go +++ b/internal/application/service/agent_collaboration_regression_test.go @@ -155,12 +155,17 @@ func testChildWikiConfirmation(t *testing.T, name string, level types.AssistantA require.False(t, result.Success) require.False(t, write.called, "missing interactive approval must fail closed") approvedCtx := tools.WithToolExecContext(ctx, &tools.ToolExecContext{ - EventBus: event.NewEventBus(), Interactive: true, SessionID: g.Members[0].SessionID, + EventBus: event.NewEventBus(), Mode: types.RunModeAttended, SessionID: g.Members[0].SessionID, AssistantMessageID: "child-answer", UserID: "web_user:u", ToolCallID: "write-call", }) result, err = registry.ExecuteTool(approvedCtx, name, json.RawMessage(`{}`)) require.NoError(t, err) require.False(t, result.Success) + if level == types.AssistantAccessReadOnly { + require.False(t, write.called, "a read-only child cannot write even with approval") + require.Zero(t, gate.requests, "a read-only child does not ask for a write") + return + } require.False(t, write.called, "denied approval must not execute") require.Equal(t, 1, gate.requests) gate.approved = true diff --git a/internal/application/service/agent_collaboration_test.go b/internal/application/service/agent_collaboration_test.go index 43fde96e..0389d46f 100644 --- a/internal/application/service/agent_collaboration_test.go +++ b/internal/application/service/agent_collaboration_test.go @@ -90,6 +90,10 @@ func (f *collaborationSessions) GetSession(_ context.Context, id string) (*types } func (f *collaborationSessions) AgentQA(ctx context.Context, req *types.QARequest, bus *event.EventBus) error { + ctx = types.WithRunMode(ctx, req.Mode) + if req.AssistantAccess.Valid() { + ctx = types.WithAccessLevel(ctx, req.AssistantAccess) + } return f.run(ctx, req, bus) } @@ -210,7 +214,7 @@ func TestCollaborationResultPublishedAfterTranscriptAndCapturesEventErrors(t *te require.NoError(t, s.Runtime.Store.Ensure(ctx, scope)) s.Bind( &collaborationSessions{run: func(ctx context.Context, req *types.QARequest, bus *event.EventBus) error { - if !req.Interactive || !req.Suspendable { + if req.Mode != types.RunModeAttended || !req.Suspendable { return errors.New("expected suspendable child with forwarded interaction") } if req.Session.ID == scope.SessionID { @@ -292,7 +296,7 @@ func TestCollaborationPinnedAccessDoesNotAllowImplicitWrite(t *testing.T) { s, _, _, ctx := collaborationService(t) scope := collaboration.Scope{TenantID: 7, UserID: "u", SessionID: "s", ID: "m"} require.NoError(t, s.Runtime.Store.Ensure(ctx, scope)) - snapshot, err := s.resolve(ctx, "a", types.AssistantAccessConfirm) + snapshot, err := s.resolveDelegated(ctx, "a", types.AssistantAccessConfirm, true) require.NoError(t, err) _, err = s.Runtime.Spawn(ctx, scope, "spawn", "one", "a", snapshot, "q") require.NoError(t, err) @@ -316,13 +320,16 @@ func TestCollaborationPinnedAccessDoesNotAllowImplicitWrite(t *testing.T) { t, s.attach(collaboration.WithBinding(ctx, b), &agent.AgentEngine{}, r, &types.AgentConfig{}, "child", "cm"), ) - _, err = r.ExecuteTool(ctx, "unsafe_write", json.RawMessage(`{}`)) - require.ErrorContains(t, err, "requires approval") + res, err := r.ExecuteTool(ctx, "unsafe_write", json.RawMessage(`{}`)) + require.NoError(t, err) + require.False(t, res.Success, "a write the child cannot get approved here is refused") require.False(t, write.called) - snapshot, err = s.resolve(ctx, "a", types.AssistantAccessAutoWrite) + snapshot, err = s.resolveDelegated(ctx, "a", types.AssistantAccessAutoWrite, true) require.NoError(t, err) work.Member.ConfigJSON = snapshot s.tenants = &collaborationTenants{level: types.AssistantAccessAutoWrite} + r = tools.NewToolRegistry() + r.RegisterTool(write) require.NoError( t, s.attach(collaboration.WithBinding(ctx, b), &agent.AgentEngine{}, r, &types.AgentConfig{}, "child", "cm"), @@ -350,3 +357,45 @@ func (t *collaborationWriteTool) Execute(context.Context, json.RawMessage) (*typ t.called = true return &types.ToolResult{Success: true}, nil } + +func TestWorkerAppliesAssistantCeilingOnlyUnderAssistantParent(t *testing.T) { + for _, tc := range []struct { + name string + assistantParent bool + want types.AssistantAccessLevel + }{ + {"ordinary parent", false, types.AssistantAccessAutoWrite}, + {"assistant parent", true, types.AssistantAccessReadOnly}, + } { + t.Run(tc.name, func(t *testing.T) { + s, _, _, ctx := collaborationService(t) + s.tenants = &collaborationTenants{level: types.AssistantAccessReadOnly} + scope := collaboration.Scope{TenantID: 7, UserID: "u", SessionID: "parent", ID: "group"} + require.NoError(t, s.Runtime.Store.Ensure(ctx, scope)) + config, err := s.resolveDelegated(ctx, "a", types.AssistantAccessAutoWrite, tc.assistantParent) + require.NoError(t, err) + _, err = s.Runtime.Spawn(ctx, scope, "spawn", "worker", "a", config, "q") + require.NoError(t, err) + var work collaboration.Work + require.NoError(t, s.Runtime.Store.Change(ctx, scope, func(g *collaboration.Group) error { + m := g.Members[0] + r := m.Runs[0] + r.State, r.Owner, r.Lease = "running", "owner", time.Now().Add(time.Minute) + work = collaboration.Work{Scope: scope, Member: *m, Run: *r} + return nil + })) + var got types.AssistantAccessLevel + s.Bind(&collaborationSessions{run: func( + _ context.Context, req *types.QARequest, bus *event.EventBus, + ) error { + got = req.AssistantAccess + return bus.Emit(context.Background(), event.Event{ + Type: event.EventAgentComplete, Data: event.AgentCompleteData{FinalAnswer: "done"}, + }) + }}) + _, err = s.run(ctx, work) + require.NoError(t, err) + require.Equal(t, tc.want, got) + }) + } +} diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.go index eb97b01c..8a5d56ea 100644 --- a/internal/application/service/agent_service.go +++ b/internal/application/service/agent_service.go @@ -1437,7 +1437,8 @@ func (s *agentService) registerTools( if toolToRegister.Name() != toolName { logger.Warnf(ctx, "Tool name mismatch: expected %s, got %s", toolName, toolToRegister.Name()) } - if risk, writes := assistantWriteToolRisk[toolName]; writes && config.OperationsAgentID != "" { + confirms := config.OperationsAgentID != "" || config.AssistantAccess != types.AssistantAccessAutoWrite + if risk, writes := assistantWriteToolRisk[toolName]; writes && confirms { gate, _ := s.toolApprovalGate.(approval.BuiltinApproval) toolToRegister = tools.NewConfirmedTool(toolToRegister, risk, operations.Access{Level: config.AssistantAccess}, gate) diff --git a/internal/application/service/kb_activity.go b/internal/application/service/kb_activity.go index e1778de9..a7193d2a 100644 --- a/internal/application/service/kb_activity.go +++ b/internal/application/service/kb_activity.go @@ -154,6 +154,11 @@ func recordKBActivity( activityDetails["agent_operation"] = agent.Operation } } + if via := types.ActingViaFromContext(ctx); via != "" { + if _, exists := activityDetails["agent_acting_via"]; !exists { + activityDetails["agent_acting_via"] = via + } + } if task, ok := ctx.Value(kbActivityTaskContextKey{}).(kbActivityTaskMetadata); ok { if task.TaskID != "" { if _, exists := activityDetails["task_id"]; !exists { diff --git a/internal/application/service/kb_activity_test.go b/internal/application/service/kb_activity_test.go index 95eb5dd9..77147b6f 100644 --- a/internal/application/service/kb_activity_test.go +++ b/internal/application/service/kb_activity_test.go @@ -186,6 +186,7 @@ func TestRecordKBActivityAttributesAgentActionsThroughTasks(t *testing.T) { types.TaskInitiator{UserID: "user-1", Role: types.TenantRoleContributor}.Apply(context.Background()), types.AuditAgentAction{ SessionID: "s-1", AgentID: types.BuiltinWeKnoraAssistantID, Operation: "knowledge.delete", + ActingVia: "automation:a-1", }, ) // The worker only sees what the task payload carried. @@ -209,7 +210,8 @@ func TestRecordKBActivityAttributesAgentActionsThroughTasks(t *testing.T) { t.Fatalf("unmarshal details: %v", err) } if details["via"] != "agent" || details["agent_session_id"] != "s-1" || - details["agent_id"] != types.BuiltinWeKnoraAssistantID || details["agent_operation"] != "knowledge.delete" { + details["agent_id"] != types.BuiltinWeKnoraAssistantID || details["agent_operation"] != "knowledge.delete" || + details["agent_acting_via"] != "automation:a-1" { t.Fatalf("details = %#v", details) } if details["trigger"] != nil { diff --git a/internal/application/service/mcp_tool_approval_service.go b/internal/application/service/mcp_tool_approval_service.go index 966be34f..f6105ec2 100644 --- a/internal/application/service/mcp_tool_approval_service.go +++ b/internal/application/service/mcp_tool_approval_service.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/Tencent/WeKnora/internal/agent/policy" "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" ) @@ -33,13 +34,18 @@ func (s *mcpToolApprovalService) ListByService(ctx context.Context, tenantID uin } func (s *mcpToolApprovalService) SetPolicy( - ctx context.Context, tenantID uint64, serviceID, toolName string, requireApproval, enabled *bool, + ctx context.Context, tenantID uint64, serviceID, toolName string, patch types.MCPToolPolicyPatch, ) error { if toolName == "" { return fmt.Errorf("tool_name is required") } - if requireApproval == nil && enabled == nil { - return fmt.Errorf("require_approval or enabled is required") + // The observed risk is the service's own declaration, never an edit. + patch.ObservedRisk = nil + if patch.RequireApproval == nil && patch.Enabled == nil && patch.Risk == nil { + return fmt.Errorf("require_approval, enabled or risk is required") + } + if patch.Risk != nil && *patch.Risk != "" && !policy.Risk(*patch.Risk).Valid() { + return fmt.Errorf("%w: unknown risk %q", types.ErrInvalidMCPToolPolicy, *patch.Risk) } svc, err := s.mcpRepo.GetByID(ctx, tenantID, serviceID) if err != nil { @@ -48,22 +54,19 @@ func (s *mcpToolApprovalService) SetPolicy( if svc == nil { return fmt.Errorf("mcp service not found") } - return s.repo.UpsertPolicy(ctx, tenantID, serviceID, toolName, types.MCPToolPolicyPatch{ - RequireApproval: requireApproval, - Enabled: enabled, - }) + return s.repo.UpsertPolicy(ctx, tenantID, serviceID, toolName, patch) } func (s *mcpToolApprovalService) SetRequireApproval( ctx context.Context, tenantID uint64, serviceID, toolName string, require bool, ) error { - return s.SetPolicy(ctx, tenantID, serviceID, toolName, &require, nil) + return s.SetPolicy(ctx, tenantID, serviceID, toolName, types.MCPToolPolicyPatch{RequireApproval: &require}) } func (s *mcpToolApprovalService) SetEnabled( ctx context.Context, tenantID uint64, serviceID, toolName string, enabled bool, ) error { - return s.SetPolicy(ctx, tenantID, serviceID, toolName, nil, &enabled) + return s.SetPolicy(ctx, tenantID, serviceID, toolName, types.MCPToolPolicyPatch{Enabled: &enabled}) } func (s *mcpToolApprovalService) IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) { @@ -73,3 +76,27 @@ func (s *mcpToolApprovalService) IsRequired(ctx context.Context, tenantID uint64 func (s *mcpToolApprovalService) IsEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) { return s.repo.IsEnabled(ctx, tenantID, serviceID, toolName) } + +func (s *mcpToolApprovalService) Policy( + ctx context.Context, tenantID uint64, serviceID, toolName string, +) (*types.MCPToolApproval, error) { + return s.repo.Get(ctx, tenantID, serviceID, toolName) +} + +// ObserveRisk records a risk the service declared when it is above the one +// recorded so far; a lower declaration is ignored. +func (s *mcpToolApprovalService) ObserveRisk( + ctx context.Context, tenantID uint64, serviceID, toolName string, risk string, +) error { + if !policy.Risk(risk).Valid() { + return fmt.Errorf("%w: unknown risk %q", types.ErrInvalidMCPToolPolicy, risk) + } + row, err := s.repo.Get(ctx, tenantID, serviceID, toolName) + if err != nil { + return err + } + if row != nil && !policy.Risk(risk).Above(policy.Risk(row.ObservedRisk)) { + return nil + } + return s.repo.UpsertPolicy(ctx, tenantID, serviceID, toolName, types.MCPToolPolicyPatch{ObservedRisk: &risk}) +} diff --git a/internal/application/service/mcp_tool_approval_service_test.go b/internal/application/service/mcp_tool_approval_service_test.go index 1eb0e872..4a90196b 100644 --- a/internal/application/service/mcp_tool_approval_service_test.go +++ b/internal/application/service/mcp_tool_approval_service_test.go @@ -94,7 +94,9 @@ func TestMCPToolApprovalServiceSetPolicyWritesBothFieldsOnce(t *testing.T) { svc, _ := newMCPToolApprovalServiceForTest(t) ctx := context.Background() - require.NoError(t, svc.SetPolicy(ctx, 1, "svc-1", "get_forecast", boolPtr(true), boolPtr(false))) + require.NoError(t, svc.SetPolicy(ctx, 1, "svc-1", "get_forecast", types.MCPToolPolicyPatch{ + RequireApproval: boolPtr(true), Enabled: boolPtr(false), + })) required, err := svc.IsRequired(ctx, 1, "svc-1", "get_forecast") require.NoError(t, err) require.True(t, required) @@ -105,7 +107,7 @@ func TestMCPToolApprovalServiceSetPolicyWritesBothFieldsOnce(t *testing.T) { func TestMCPToolApprovalServiceSetPolicyRejectsEmptyPatch(t *testing.T) { svc, _ := newMCPToolApprovalServiceForTest(t) - err := svc.SetPolicy(context.Background(), 1, "svc-1", "get_forecast", nil, nil) + err := svc.SetPolicy(context.Background(), 1, "svc-1", "get_forecast", types.MCPToolPolicyPatch{}) require.Error(t, err) } @@ -114,3 +116,36 @@ func TestMCPToolApprovalServiceUnknownService(t *testing.T) { err := svc.SetEnabled(context.Background(), 1, "missing", "tool", false) require.ErrorContains(t, err, "not found") } + +func TestMCPToolApprovalServiceObservedRiskOnlyRises(t *testing.T) { + svc, _ := newMCPToolApprovalServiceForTest(t) + ctx := context.Background() + + require.NoError(t, svc.ObserveRisk(ctx, 1, "svc-1", "get_forecast", "read")) + require.NoError(t, svc.ObserveRisk(ctx, 1, "svc-1", "get_forecast", "write")) + require.NoError(t, svc.ObserveRisk(ctx, 1, "svc-1", "get_forecast", "read")) + row, err := svc.Policy(ctx, 1, "svc-1", "get_forecast") + require.NoError(t, err) + require.Equal(t, "write", row.ObservedRisk) + require.True(t, row.Enabled, "recording a risk does not disable the tool") + require.False(t, row.RequireApproval) + + risk := "read" + require.NoError(t, svc.SetPolicy(ctx, 1, "svc-1", "get_forecast", types.MCPToolPolicyPatch{Risk: &risk})) + row, err = svc.Policy(ctx, 1, "svc-1", "get_forecast") + require.NoError(t, err) + require.Equal(t, "read", row.Risk) + require.Equal(t, "write", row.ObservedRisk) +} + +func TestMCPToolApprovalServiceRejectsUnknownRisk(t *testing.T) { + svc, _ := newMCPToolApprovalServiceForTest(t) + risk := "harmless" + err := svc.SetPolicy(context.Background(), 1, "svc-1", "get_forecast", types.MCPToolPolicyPatch{Risk: &risk}) + require.ErrorIs(t, err, types.ErrInvalidMCPToolPolicy) + observed := "read" + err = svc.SetPolicy(context.Background(), 1, "svc-1", "get_forecast", types.MCPToolPolicyPatch{ + ObservedRisk: &observed, + }) + require.Error(t, err, "the observed risk is not editable") +} diff --git a/internal/application/service/session_agent_qa.go b/internal/application/service/session_agent_qa.go index 7ff349a1..27e85a04 100644 --- a/internal/application/service/session_agent_qa.go +++ b/internal/application/service/session_agent_qa.go @@ -60,6 +60,7 @@ func (s *sessionService) AgentQA( // Propagate the session ID so stateful sandbox backends (CubeSandbox) can // bind script execution to a per-session MicroVM instance. ctx = types.WithSessionID(ctx, sessionID) + ctx = types.WithRunMode(ctx, req.Mode) sessionJSON, err := json.Marshal(req.Session) if err != nil { logger.Errorf(ctx, "Failed to marshal session, session ID: %s, error: %v", sessionID, err) @@ -103,6 +104,24 @@ func (s *sessionService) AgentQA( if err != nil { return err } + if delegated, err := delegatedConfigFromBinding(ctx); err != nil { + return err + } else if delegated != nil { + agentConfig.AssistantAccess = delegated.level(tenantInfo) + if agentConfig.AssistantAccess == types.AssistantAccessReadOnly { + agentConfig.WritableKBIDs = nil + } + } + ctx = types.WithAccessLevel(ctx, agentConfig.AssistantAccess) + if _, scoped := types.GrantScopeFromContext(ctx); !scoped { + // Grants given anywhere in a conversation, including by its delegated + // children, belong to the root conversation. + grantSessionID := req.GrantSessionID + if grantSessionID == "" { + grantSessionID = sessionID + } + ctx = types.WithGrantScope(ctx, types.GrantScope{Scope: types.AgentGrantScopeSession, ScopeID: grantSessionID}) + } // Set VLM model ID for tool result image analysis (runtime-only field) if req.CustomAgent != nil && req.CustomAgent.Config.VLMModelID != "" { @@ -322,7 +341,7 @@ func (s *sessionService) AgentQA( engine.SetSteerSink(req.SteerSink) } - engine.SetInteractive(req.Interactive) + engine.SetRunMode(req.Mode) collaborating := false if bound, ok := engine.(interface{ HasCollaboration() bool }); ok { collaborating = bound.HasCollaboration() @@ -464,7 +483,7 @@ func (s *sessionService) buildAgentConfig( MaxCompletionTokens: customAgent.Config.MaxCompletionTokens, RetainRetrievalHistory: customAgent.Config.RetainRetrievalHistory, SharedAgentReadOnly: req.SharedAgentReadOnly, - AssistantAccess: tenantInfo.AssistantConfig.EffectiveAccessLevel(req.AssistantAccess), + AssistantAccess: types.CapAccessLevel(req.AssistantAccess, customAgent.Config.AccessLevel), // The model is always told it may call tools in parallel; without // this the engine still ran them one by one, so three searches in // one reply cost three sequential embed/retrieve/rerank rounds. @@ -586,10 +605,10 @@ func (s *sessionService) buildAgentConfig( if cfg := tenantInfo.AssistantConfig; cfg != nil { agentConfig.AssistantName = strings.TrimSpace(cfg.DisplayName) } - if agentConfig.AssistantAccess == types.AssistantAccessReadOnly { - // Wiki tools write outside the catalog; read-only covers them too. - agentConfig.WritableKBIDs = nil - } + } + if agentConfig.AssistantAccess == types.AssistantAccessReadOnly { + // Wiki tools write outside the catalog; read-only covers them too. + agentConfig.WritableKBIDs = nil } } agentConfig.QuestionOrigin = questionOriginInTargets(ctx, req.QuestionOrigin, searchTargets) diff --git a/internal/application/service/tenant_skill_install_test.go b/internal/application/service/tenant_skill_install_test.go index f29239fe..cf9718d4 100644 --- a/internal/application/service/tenant_skill_install_test.go +++ b/internal/application/service/tenant_skill_install_test.go @@ -3230,7 +3230,7 @@ func (e *installAgentEngine) SetContextCheckpointSink(types.ContextCheckpointSin func (e *installAgentEngine) EnableSuspension(json.RawMessage) {} -func (e *installAgentEngine) SetInteractive(bool) {} +func (e *installAgentEngine) SetRunMode(types.RunMode) {} func (e *installAgentEngine) Resume(context.Context, string, string, []chat.Message, []byte, *types.AgentPrompt, diff --git a/internal/container/container.go b/internal/container/container.go index 065eb81c..31236117 100644 --- a/internal/container/container.go +++ b/internal/container/container.go @@ -183,6 +183,7 @@ func BuildContainer(container *dig.Container) *dig.Container { must(container.Provide(repository.NewMCPServiceRepository)) must(container.Provide(repository.NewMCPToolApprovalRepository)) must(container.Provide(repository.NewAgentPromptRepository)) + must(container.Provide(repository.NewAgentGrantRepository)) must(container.Provide(repository.NewAgentRunSuspensionRepository)) must(container.Provide(repository.NewMCPOAuthRepository)) must(container.Provide(repository.NewTenantSandboxConfigRepository)) @@ -348,8 +349,9 @@ func BuildContainer(container *dig.Container) *dig.Container { must(container.Provide(service.NewSuspendedRunService)) must(container.Provide(func( cfg *config.Config, s interfaces.MCPToolApprovalService, broker *hitl.Broker, + grants interfaces.AgentGrantRepository, ) *approval.Gate { - return approval.NewGate(cfg, &approval.Adapter{Svc: s}, broker) + return approval.NewGate(cfg, &approval.Adapter{Svc: s}, broker).WithGrants(grants) })) // Expose Gate as MCPApproval interface so AgentService and others can depend on the abstraction. must(container.Provide(func(g *approval.Gate) approval.MCPApproval { return g })) @@ -603,8 +605,9 @@ func BuildContainer(container *dig.Container) *dig.Container { gate *approval.Gate, models interfaces.ModelService, agents interfaces.AgentShareService, + grants interfaces.AgentGrantRepository, ) *handler.MCPServiceHandler { - return handler.NewMCPServiceHandler(mcpService, toolApprovals, gate, models, agents) + return handler.NewMCPServiceHandler(mcpService, toolApprovals, gate, models, agents).WithGrants(grants) })) must(container.Invoke(func( sessions *session.Handler, mcp *handler.MCPServiceHandler, diff --git a/internal/database/migration_sqlite_versioned_schema_test.go b/internal/database/migration_sqlite_versioned_schema_test.go index b9f841a2..b68d1de9 100644 --- a/internal/database/migration_sqlite_versioned_schema_test.go +++ b/internal/database/migration_sqlite_versioned_schema_test.go @@ -39,6 +39,7 @@ var versionedSQLiteTables = []string{ "agent_prompts", "agent_run_suspensions", "agent_collaborations", + "agent_grants", } // versionedSQLiteColumns maps each existing table to the columns that the @@ -59,14 +60,14 @@ var versionedSQLiteColumns = map[string][]string{ "sandbox_config_tenant_id", // 000027 "host_workspace_dir", // 000029 }, - "tenant_invitations": {"token", "accepted_count"}, // 000054 - "embed_channels": {"allow_memory"}, // 000060 - "im_channels": {"locale"}, // 000030 - "chunks": {"source_locators"}, // 000033 - "mcp_oauth_tokens": {"principal_type", "principal_id"}, // 000064 - "mcp_tool_approvals": {"enabled"}, // 000091 - "mcp_services": {"usage_instructions"}, // 000092 - "message_artifacts": {"deleted_at"}, // 000107 + "tenant_invitations": {"token", "accepted_count"}, // 000054 + "embed_channels": {"allow_memory"}, // 000060 + "im_channels": {"locale"}, // 000030 + "chunks": {"source_locators"}, // 000033 + "mcp_oauth_tokens": {"principal_type", "principal_id"}, // 000064 + "mcp_tool_approvals": {"enabled", "risk", "observed_risk"}, // 000091, 000126 + "mcp_services": {"usage_instructions"}, // 000092 + "message_artifacts": {"deleted_at"}, // 000107 "tenant_skills": { "envs", "served", "catalog_id", "install_session_id", "install_message_id", }, // 000028 @@ -76,7 +77,7 @@ var versionedSQLiteColumns = map[string][]string{ }, // 000028 } -const expectedSQLiteMigrationVersion = 42 +const expectedSQLiteMigrationVersion = 44 func TestSQLiteMigrationsCreateVersionedSchema(t *testing.T) { repoRoot := sqliteRepoRoot(t) diff --git a/internal/event/event_data.go b/internal/event/event_data.go index 35aa37ec..2a7ce8dc 100644 --- a/internal/event/event_data.go +++ b/internal/event/event_data.go @@ -299,6 +299,9 @@ type ToolApprovalRequiredData struct { // GrantScope, when set, offers to allow calls like this one for the rest // of the session, and describes which calls that covers. GrantScope string `json:"grant_scope,omitempty"` + // GrantLapsed, when set, is why an earlier grant for this call no longer + // applies; see types.ToolApprovalPromptRequest. + GrantLapsed string `json:"grant_lapsed,omitempty"` } // ToolApprovalResolvedData confirms the user decision (or timeout/cancel). diff --git a/internal/handler/agent_grant.go b/internal/handler/agent_grant.go new file mode 100644 index 00000000..8c75ea48 --- /dev/null +++ b/internal/handler/agent_grant.go @@ -0,0 +1,100 @@ +package handler + +import ( + "net/http" + "strings" + "time" + + "github.com/gin-gonic/gin" + + "github.com/Tencent/WeKnora/internal/errors" + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" +) + +// WithGrants lets the handler list and revoke the caller's agent grants. +func (h *MCPServiceHandler) WithGrants(grants interfaces.AgentGrantRepository) *MCPServiceHandler { + h.grants = grants + return h +} + +// grantOwner is the caller as grants record it. +func grantOwner(c *gin.Context) (uint64, string, bool) { + tenantID := c.GetUint64(types.TenantIDContextKey.String()) + principal, _ := types.PrincipalFromContext(c.Request.Context()) + userID := principal.StorageID() + return tenantID, userID, tenantID != 0 && strings.TrimSpace(userID) != "" +} + +// ListAgentGrants godoc +// @Summary 列出会话内的 Agent 授权 +// @Description 列出当前用户在某个会话(根会话)中通过“本会话允许”记住的授权,包括其委派子任务上批准的授权。 +// @Tags Agent +// @Produce json +// @Param session_id query string true "根会话 ID" +// @Success 200 {object} map[string]interface{} "授权列表" +// @Failure 400 {object} errors.AppError "请求参数错误" +// @Security Bearer +// @Router /agent/grants [get] +func (h *MCPServiceHandler) ListAgentGrants(c *gin.Context) { + ctx := c.Request.Context() + if h.grants == nil { + _ = c.Error(errors.NewInternalServerError("agent grants are not configured")) + return + } + tenantID, userID, ok := grantOwner(c) + if !ok { + _ = c.Error(errors.NewUnauthorizedError("a signed-in user is required")) + return + } + sessionID := strings.TrimSpace(c.Query("session_id")) + if sessionID == "" { + _ = c.Error(errors.NewBadRequestError("session_id is required")) + return + } + grants, err := h.grants.ListGrants(ctx, tenantID, userID, types.AgentGrantScopeSession, sessionID) + if err != nil { + logger.ErrorWithFields(ctx, err, map[string]interface{}{"session_id": sessionID}) + _ = c.Error(errors.NewInternalServerError(err.Error())) + return + } + if grants == nil { + grants = []*types.AgentGrant{} + } + c.JSON(http.StatusOK, gin.H{"success": true, "data": grants}) +} + +// RevokeAgentGrant godoc +// @Summary 撤销 Agent 授权 +// @Description 撤销当前用户的一条授权;之后同类调用会重新询问。 +// @Tags Agent +// @Produce json +// @Param id path string true "授权 ID" +// @Success 200 {object} map[string]interface{} "撤销结果" +// @Failure 404 {object} errors.AppError "授权不存在" +// @Security Bearer +// @Router /agent/grants/{id} [delete] +func (h *MCPServiceHandler) RevokeAgentGrant(c *gin.Context) { + ctx := c.Request.Context() + if h.grants == nil { + _ = c.Error(errors.NewInternalServerError("agent grants are not configured")) + return + } + tenantID, userID, ok := grantOwner(c) + if !ok { + _ = c.Error(errors.NewUnauthorizedError("a signed-in user is required")) + return + } + revoked, err := h.grants.RevokeGrant(ctx, tenantID, userID, c.Param("id"), time.Now()) + if err != nil { + logger.ErrorWithFields(ctx, err, nil) + _ = c.Error(errors.NewInternalServerError(err.Error())) + return + } + if !revoked { + _ = c.Error(errors.NewNotFoundError("grant not found")) + return + } + c.JSON(http.StatusOK, gin.H{"success": true}) +} diff --git a/internal/handler/mcp_service.go b/internal/handler/mcp_service.go index ad66b865..b1179bda 100644 --- a/internal/handler/mcp_service.go +++ b/internal/handler/mcp_service.go @@ -34,6 +34,8 @@ type MCPServiceHandler struct { // runResumer continues a run suspended on an approval once it is // answered. Nil leaves such answers to the reaper, which closes the run. runResumer RunResumer + // grants are the callers' remembered agent approvals. + grants interfaces.AgentGrantRepository } // RunResumer continues an agent run that ended suspended on prompt, now @@ -780,6 +782,9 @@ func (h *MCPServiceHandler) ListMCPToolApprovals(c *gin.Context) { type setMCPToolApprovalBody struct { RequireApproval *bool `json:"require_approval"` Enabled *bool `json:"enabled"` + // Risk is read, probe, write or destructive; an empty string returns the + // tool to the risk its service declares. + Risk *string `json:"risk"` } // SetMCPToolApproval updates per-tool MCP policy fields. The route name is kept @@ -787,13 +792,15 @@ type setMCPToolApprovalBody struct { // // SetMCPToolApproval godoc // @Summary 设置 MCP 工具策略 -// @Description 为指定 MCP 服务下的某个工具更新启用状态和/或人工审批要求。至少提供 require_approval 或 enabled 之一;省略的字段保持原值。 +// @Description 为指定 MCP 服务下的某个工具更新启用状态、人工审批要求和/或风险等级。 +// @Description 至少提供 require_approval、enabled、risk 之一;省略的字段保持原值。 +// @Description risk 为 read/probe/write/destructive,空字符串表示改回按服务注解推断。 // @Tags MCP服务 // @Accept json // @Produce json // @Param id path string true "MCP 服务 ID" // @Param tool_name path string true "工具名" -// @Param request body map[string]interface{} true "{require_approval?: bool, enabled?: bool}" +// @Param request body map[string]interface{} true "{require_approval?: bool, enabled?: bool, risk?: string}" // @Success 200 {object} handler.SuccessResponse "更新结果" // @Failure 400 {object} errors.AppError "请求参数错误" // @Failure 404 {object} errors.AppError "MCP 服务或工具不存在" @@ -820,13 +827,17 @@ func (h *MCPServiceHandler) SetMCPToolApproval(c *gin.Context) { c.Error(errors.NewBadRequestError(err.Error())) return } - if body.RequireApproval == nil && body.Enabled == nil { - c.Error(errors.NewBadRequestError("require_approval or enabled is required")) + if body.RequireApproval == nil && body.Enabled == nil && body.Risk == nil { + _ = c.Error(errors.NewBadRequestError("require_approval, enabled or risk is required")) return } - if err := h.mcpToolApprovalService.SetPolicy( - ctx, tenantID, serviceID, toolName, body.RequireApproval, body.Enabled, - ); err != nil { + if err := h.mcpToolApprovalService.SetPolicy(ctx, tenantID, serviceID, toolName, types.MCPToolPolicyPatch{ + RequireApproval: body.RequireApproval, Enabled: body.Enabled, Risk: body.Risk, + }); err != nil { + if stderrors.Is(err, types.ErrInvalidMCPToolPolicy) { + _ = c.Error(errors.NewBadRequestError(err.Error())) + return + } if strings.Contains(err.Error(), "not found") { c.Error(errors.NewNotFoundError(err.Error())) return diff --git a/internal/handler/mcp_tool_approval_test.go b/internal/handler/mcp_tool_approval_test.go index 964caf44..fd1fc2f8 100644 --- a/internal/handler/mcp_tool_approval_test.go +++ b/internal/handler/mcp_tool_approval_test.go @@ -20,14 +20,16 @@ type stubMCPToolApprovalService struct { interfaces.MCPToolApprovalService requireApproval *bool enabled *bool + risk *string err error } func (s *stubMCPToolApprovalService) SetPolicy( - _ context.Context, _ uint64, _, _ string, requireApproval, enabled *bool, + _ context.Context, _ uint64, _, _ string, patch types.MCPToolPolicyPatch, ) error { - s.requireApproval = requireApproval - s.enabled = enabled + s.requireApproval = patch.RequireApproval + s.enabled = patch.Enabled + s.risk = patch.Risk return s.err } diff --git a/internal/handler/session/qa.go b/internal/handler/session/qa.go index 580041e6..6b51aac8 100644 --- a/internal/handler/session/qa.go +++ b/internal/handler/session/qa.go @@ -119,6 +119,10 @@ func calledWithAPIKey(ctx context.Context) bool { func (rc *qaRequestContext) buildQARequest() *types.QARequest { imageURLs, imageDescription := extractImageURLsAndOCRText(rc.images) interactive := !calledWithAPIKey(rc.ctx) + mode := types.RunModeUnattended + if interactive { + mode = types.RunModeAttended + } req := &types.QARequest{ Session: rc.session, Query: rc.query, @@ -145,7 +149,7 @@ func (rc *qaRequestContext) buildQARequest() *types.QARequest { // Only a caller that can answer the prompt later may leave the run // suspended; an API-key caller would get a turn with no answer. Suspendable: interactive, - Interactive: interactive, + Mode: mode, Resume: rc.resume, } if rc.steerSink != nil { diff --git a/internal/mcp/client.go b/internal/mcp/client.go index a749e882..dd721bc8 100644 --- a/internal/mcp/client.go +++ b/internal/mcp/client.go @@ -695,9 +695,10 @@ func (c *mcpGoClient) listRawTools(ctx context.Context) ([]*types.MCPTool, error } var page struct { Tools []struct { - Name string `json:"name"` - Description string `json:"description"` - InputSchema json.RawMessage `json:"inputSchema"` + Name string `json:"name"` + Description string `json:"description"` + InputSchema json.RawMessage `json:"inputSchema"` + Annotations *types.MCPToolAnnotations `json:"annotations"` } `json:"tools"` NextCursor string `json:"nextCursor"` } @@ -712,7 +713,10 @@ func (c *mcpGoClient) listRawTools(ctx context.Context) ([]*types.MCPTool, error } tools = append( tools, - &types.MCPTool{Name: tool.Name, Description: tool.Description, InputSchema: tool.InputSchema}, + &types.MCPTool{ + Name: tool.Name, Description: tool.Description, InputSchema: tool.InputSchema, + Annotations: tool.Annotations, + }, ) } if len(tools) > maxToolsPerService { diff --git a/internal/router/operations_mcp_metadata_integration_test.go b/internal/router/operations_mcp_metadata_integration_test.go index 66e995de..ba669e16 100644 --- a/internal/router/operations_mcp_metadata_integration_test.go +++ b/internal/router/operations_mcp_metadata_integration_test.go @@ -144,11 +144,11 @@ func TestAssistantMCPDirectoryEndToEnd(t *testing.T) { interactive := tools.WithToolExecContext( ctx, &tools.ToolExecContext{ - SessionID: "session", - UserID: "web_user:user-a", - ToolCallID: "call", - EventBus: event.NewEventBus(), - Interactive: true, + SessionID: "session", + UserID: "web_user:user-a", + ToolCallID: "call", + EventBus: event.NewEventBus(), + Mode: types.RunModeAttended, }, ) run := func(id string) *types.ToolResult { diff --git a/internal/router/routes_infra.go b/internal/router/routes_infra.go index 2c4461c6..90af757b 100644 --- a/internal/router/routes_infra.go +++ b/internal/router/routes_infra.go @@ -210,6 +210,9 @@ func RegisterMCPServiceRoutes( // Same tenant-member (Viewer+) gating rationale as tool-approvals. agentTool.POST("/mcp-oauth-resolutions/:pending_id", g.Viewer(), oauthHandler.ResolveMCPOAuth) agentTool.POST("/mcp-oauth-resolutions/:pending_id/cancel", g.Viewer(), oauthHandler.CancelMCPOAuth) + // The caller's own remembered approvals; same gating. + agentTool.GET("/grants", g.Viewer(), handler.ListAgentGrants) + agentTool.DELETE("/grants/:id", g.Viewer(), handler.RevokeAgentGrant) } } diff --git a/internal/types/agent_grant.go b/internal/types/agent_grant.go new file mode 100644 index 00000000..ef09845a --- /dev/null +++ b/internal/types/agent_grant.go @@ -0,0 +1,154 @@ +package types + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "slices" + "time" + + "github.com/google/uuid" + "gorm.io/gorm" +) + +// Agent grant scopes. A session grant lives as long as its root +// conversation; an automation grant lives with its automation and stops +// applying when the automation's binding changes. +const ( + AgentGrantScopeSession = "session" + AgentGrantScopeAutomation = "automation" +) + +// AgentGrantIdleExpiry is how long an automation grant survives without use. +const AgentGrantIdleExpiry = 90 * 24 * time.Hour + +// AgentGrant remembers that a user allowed one kind of agent action without +// asking again. GrantKey names the action and its resource scope; Label is +// how the approval card described it. +type AgentGrant struct { + ID string `json:"id" gorm:"type:varchar(36);primaryKey"` + TenantID uint64 `json:"tenant_id" gorm:"not null;uniqueIndex:idx_agent_grants_key"` + // UserID is the principal storage ID of the user who granted it. + UserID string `json:"-" gorm:"type:varchar(128);not null;uniqueIndex:idx_agent_grants_key"` + Scope string `json:"scope" gorm:"type:varchar(16);not null;uniqueIndex:idx_agent_grants_key"` + ScopeID string `json:"scope_id" gorm:"type:varchar(64);not null;uniqueIndex:idx_agent_grants_key"` + // GrantKey is what the grant allows; see approval.PendingRequest.Grant. + GrantKey string `json:"grant_key" gorm:"type:varchar(512);not null;uniqueIndex:idx_agent_grants_key"` + Label string `json:"label" gorm:"type:text"` + // BindingHash, when set, is the configuration the grant was given + // under; a run with a different one does not get it. + BindingHash string `json:"-" gorm:"type:varchar(64);not null;default:''"` + // Risk is the highest risk the grant was approved for; a call that has + // since become riskier is not covered. + Risk string `json:"risk" gorm:"type:varchar(16);not null;default:'write'"` + PromptID string `json:"prompt_id" gorm:"type:varchar(36)"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + LastUsedAt *time.Time `json:"last_used_at"` + ExpiresAt *time.Time `json:"expires_at"` + RevokedAt *time.Time `json:"revoked_at"` +} + +// BeforeCreate sets the ID. +func (g *AgentGrant) BeforeCreate(*gorm.DB) error { + if g.ID == "" { + g.ID = uuid.NewString() + } + return nil +} + +// Why a remembered grant no longer applies. The approval card shows it so +// the user knows why they are asked again. +const ( + AgentGrantLapseRevoked = "revoked" + AgentGrantLapseExpired = "expired" + // AgentGrantLapseChanged: the run's configuration differs from the one + // the grant was given under. + AgentGrantLapseChanged = "changed" + // AgentGrantLapseIdle: an automation grant went unused too long. + AgentGrantLapseIdle = "idle" +) + +// ActiveAt reports whether the grant applies at now under binding. +func (g *AgentGrant) ActiveAt(now time.Time, binding string) bool { + return g != nil && g.LapseAt(now, binding) == "" +} + +// LapseAt is why an existing grant does not apply at now under binding, or +// "" when it does. +func (g *AgentGrant) LapseAt(now time.Time, binding string) string { + switch { + case g.RevokedAt != nil: + return AgentGrantLapseRevoked + case g.ExpiresAt != nil && !now.Before(*g.ExpiresAt): + return AgentGrantLapseExpired + case g.BindingHash != binding: + return AgentGrantLapseChanged + } + if g.Scope == AgentGrantScopeAutomation { + used := g.CreatedAt + if g.LastUsedAt != nil { + used = *g.LastUsedAt + } + if now.Sub(used) >= AgentGrantIdleExpiry { + return AgentGrantLapseIdle + } + } + return "" +} + +// GrantScope is where a run's grants are kept and looked up. +type GrantScope struct { + Scope string + ScopeID string + // BindingHash is the run's configuration; see AgentGrant.BindingHash. + BindingHash string +} + +// WithGrantScope records where the run's grants live. +func WithGrantScope(ctx context.Context, scope GrantScope) context.Context { + return context.WithValue(ctx, GrantScopeContextKey, scope) +} + +// GrantScopeFromContext is the run's grant scope, if it has one. +func GrantScopeFromContext(ctx context.Context) (GrantScope, bool) { + scope, ok := ctx.Value(GrantScopeContextKey).(GrantScope) + return scope, ok && scope.Scope != "" && scope.ScopeID != "" +} + +// WithStandingGrantScope records grants the run may use but never adds to: +// an automation's, approved in its settings. Approvals given during the run +// go to the run's own scope. +func WithStandingGrantScope(ctx context.Context, scope GrantScope) context.Context { + return context.WithValue(ctx, StandingGrantScopeContextKey, scope) +} + +// StandingGrantScopeFromContext is the run's standing grant scope, if any. +func StandingGrantScopeFromContext(ctx context.Context) (GrantScope, bool) { + scope, ok := ctx.Value(StandingGrantScopeContextKey).(GrantScope) + return scope, ok && scope.Scope != "" && scope.ScopeID != "" +} + +// AutomationBinding is what an automation's grants were given under. A +// grant stops applying once any of it changes: the agent's tools, MCP +// services or instructions, the owner's workspace role, or the agent's +// access ceiling. +type AutomationBinding struct { + AgentID string `json:"agent_id"` + Tools []string `json:"tools"` + MCPServiceIDs []string `json:"mcp_service_ids"` + SystemPrompt string `json:"system_prompt"` + OwnerRole TenantRole `json:"owner_role"` + Ceiling AssistantAccessLevel `json:"ceiling"` +} + +// Hash is the binding as stored in AgentGrant.BindingHash. Tool and +// service order does not matter. +func (b AutomationBinding) Hash() string { + b.Tools = slices.Sorted(slices.Values(b.Tools)) + b.MCPServiceIDs = slices.Sorted(slices.Values(b.MCPServiceIDs)) + data, _ := json.Marshal(b) + sum := sha256.Sum256(data) + return hex.EncodeToString(sum[:]) +} diff --git a/internal/types/agent_grant_test.go b/internal/types/agent_grant_test.go new file mode 100644 index 00000000..73a9b94a --- /dev/null +++ b/internal/types/agent_grant_test.go @@ -0,0 +1,66 @@ +package types + +import ( + "slices" + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +func TestAgentGrantActiveAt(t *testing.T) { + now := time.Now() + session := &AgentGrant{Scope: AgentGrantScopeSession, CreatedAt: now.Add(-365 * 24 * time.Hour)} + assert.True(t, session.ActiveAt(now, ""), "a session grant lasts as long as its conversation") + assert.False(t, session.ActiveAt(now, "other"), "a grant applies only under its binding") + + automation := &AgentGrant{ + Scope: AgentGrantScopeAutomation, BindingHash: "b", CreatedAt: now.Add(-100 * 24 * time.Hour), + } + assert.False(t, automation.ActiveAt(now, "b"), "an automation grant unused for 90 days lapses") + used := now.Add(-time.Hour) + automation.LastUsedAt = &used + assert.True(t, automation.ActiveAt(now, "b")) + + expired := now.Add(-time.Minute) + assert.False(t, (&AgentGrant{Scope: AgentGrantScopeSession, ExpiresAt: &expired}).ActiveAt(now, "")) + assert.False(t, (&AgentGrant{Scope: AgentGrantScopeSession, RevokedAt: &expired}).ActiveAt(now, "")) + assert.False(t, (*AgentGrant)(nil).ActiveAt(now, "")) +} + +func TestAgentGrantLapseReasons(t *testing.T) { + now := time.Now() + past := now.Add(-time.Minute) + assert.Equal(t, AgentGrantLapseRevoked, (&AgentGrant{RevokedAt: &past}).LapseAt(now, "")) + assert.Equal(t, AgentGrantLapseExpired, (&AgentGrant{ExpiresAt: &past}).LapseAt(now, "")) + assert.Equal(t, AgentGrantLapseChanged, (&AgentGrant{BindingHash: "a"}).LapseAt(now, "b")) + idle := &AgentGrant{Scope: AgentGrantScopeAutomation, CreatedAt: now.Add(-AgentGrantIdleExpiry)} + assert.Equal(t, AgentGrantLapseIdle, idle.LapseAt(now, "")) + assert.Empty(t, (&AgentGrant{Scope: AgentGrantScopeSession}).LapseAt(now, "")) +} + +func TestAutomationBindingHash(t *testing.T) { + base := AutomationBinding{ + AgentID: "a", Tools: []string{"x", "y"}, MCPServiceIDs: []string{"m1", "m2"}, + SystemPrompt: "p", OwnerRole: TenantRoleContributor, Ceiling: AssistantAccessAutoWrite, + } + reordered := base + reordered.Tools = []string{"y", "x"} + reordered.MCPServiceIDs = []string{"m2", "m1"} + assert.Equal(t, base.Hash(), reordered.Hash(), "order does not matter") + assert.Len(t, base.Hash(), 64, "fits binding_hash") + + for name, change := range map[string]func(*AutomationBinding){ + "tools": func(b *AutomationBinding) { b.Tools = []string{"x"} }, + "mcp": func(b *AutomationBinding) { b.MCPServiceIDs = []string{"m1", "m3"} }, + "prompt": func(b *AutomationBinding) { b.SystemPrompt = "q" }, + "role": func(b *AutomationBinding) { b.OwnerRole = TenantRoleViewer }, + "ceiling": func(b *AutomationBinding) { b.Ceiling = AssistantAccessReadOnly }, + } { + changed := base + changed.Tools = slices.Clone(base.Tools) + change(&changed) + assert.NotEqual(t, base.Hash(), changed.Hash(), name) + } + assert.Equal(t, []string{"x", "y"}, base.Tools, "hashing leaves the binding unchanged") +} diff --git a/internal/types/agent_operation.go b/internal/types/agent_operation.go index d8a95939..d52c1d16 100644 --- a/internal/types/agent_operation.go +++ b/internal/types/agent_operation.go @@ -46,10 +46,13 @@ type AuditAgentAction struct { SessionID string `json:"session_id,omitempty"` AgentID string `json:"agent_id,omitempty"` Operation string `json:"operation,omitempty"` + // ActingVia is the principal's ActingVia when the agent ran on its own, + // e.g. "automation:". + ActingVia string `json:"acting_via,omitempty"` } func (a AuditAgentAction) valid() bool { - return a.SessionID != "" || a.AgentID != "" || a.Operation != "" + return a.SessionID != "" || a.AgentID != "" || a.Operation != "" || a.ActingVia != "" } type auditAgentActionContextKey struct{} @@ -73,3 +76,15 @@ func AuditAgentActionFromContext(ctx context.Context) (AuditAgentAction, bool) { } return a, true } + +// ActingViaFromContext returns what acts for the caller in ctx, or "" when +// the caller acts in person. +func ActingViaFromContext(ctx context.Context) string { + if a, ok := AuditAgentActionFromContext(ctx); ok && a.ActingVia != "" { + return a.ActingVia + } + if p, ok := PrincipalFromContext(ctx); ok { + return p.ActingVia + } + return "" +} diff --git a/internal/types/agent_operation_acting_via_test.go b/internal/types/agent_operation_acting_via_test.go new file mode 100644 index 00000000..549968ef --- /dev/null +++ b/internal/types/agent_operation_acting_via_test.go @@ -0,0 +1,22 @@ +package types + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestActingViaFromContext(t *testing.T) { + assert.Empty(t, ActingViaFromContext(context.Background())) + + ctx := WithPrincipal(context.Background(), Principal{ + Type: PrincipalWebUser, ID: "u1", ActingVia: " automation:a-1 ", + }) + assert.Equal(t, "automation:a-1", ActingViaFromContext(ctx)) + p, _ := PrincipalFromContext(ctx) + assert.Equal(t, "web_user:u1", p.StorageID(), "acting for a user keeps their identity") + + ctx = WithAuditAgentAction(ctx, AuditAgentAction{SessionID: "s", ActingVia: "automation:a-2"}) + assert.Equal(t, "automation:a-2", ActingViaFromContext(ctx), "the dispatched action's record wins") +} diff --git a/internal/types/agent_prompt.go b/internal/types/agent_prompt.go index 1d5f68bc..e237b35b 100644 --- a/internal/types/agent_prompt.go +++ b/internal/types/agent_prompt.go @@ -205,6 +205,9 @@ type ToolApprovalPromptRequest struct { // derives it from the call; GrantScope describes it to the user. Grant string `json:"grant,omitempty"` GrantScope string `json:"grant_scope,omitempty"` + // GrantLapsed, when set, is why an earlier grant for this call no longer + // applies (an AgentGrantLapse value). + GrantLapsed string `json:"grant_lapsed,omitempty"` } // ToolApprovalPromptResponse is the Response of an AgentPromptKindToolApproval. diff --git a/internal/types/assistant.go b/internal/types/assistant.go index 387126c6..4ae89570 100644 --- a/internal/types/assistant.go +++ b/internal/types/assistant.go @@ -73,6 +73,19 @@ func (c *AssistantConfig) EffectiveAccessLevel(requested AssistantAccessLevel) A return level } +// CapAccessLevel is the level a run of an agent whose ceiling is ceiling +// gets for the requested level. An unset or unknown ceiling is auto_write; +// an unset or unknown request gets the ceiling. +func CapAccessLevel(requested, ceiling AssistantAccessLevel) AssistantAccessLevel { + if !ceiling.Valid() { + ceiling = AssistantAccessAutoWrite + } + if !requested.Valid() || assistantAccessRank[requested] > assistantAccessRank[ceiling] { + return ceiling + } + return requested +} + // Value implements driver.Valuer for JSON storage. func (c AssistantConfig) Value() (driver.Value, error) { return json.Marshal(c) } diff --git a/internal/types/const.go b/internal/types/const.go index 671c311d..a569c105 100644 --- a/internal/types/const.go +++ b/internal/types/const.go @@ -105,10 +105,15 @@ const ( // the agent emits a one-shot authorization notice and continues instead of // blocking until the OAuth wait times out. See IsMCPOAuthNonInteractive. MCPOAuthNonInteractiveContextKey ContextKey = "MCPOAuthNonInteractive" - // UnattendedRunContextKey marks a run whose prompts nobody can see, such as - // an agent trial. A tool approval it raises is refused at once instead of - // waiting out its timeout. See IsUnattendedRun. - UnattendedRunContextKey ContextKey = "UnattendedRun" + // RunModeContextKey carries the RunMode of the agent run. See + // RunModeFromContext. + RunModeContextKey ContextKey = "RunMode" + // AccessLevelContextKey carries the agent run's effective access level. + AccessLevelContextKey ContextKey = "AccessLevel" + // GrantScopeContextKey carries the GrantScope of the agent run. + GrantScopeContextKey ContextKey = "GrantScope" + // StandingGrantScopeContextKey carries the standing GrantScope of an agent run; see WithStandingGrantScope. + StandingGrantScopeContextKey ContextKey = "StandingGrantScope" // ChatParserEngineContextKey carries the resolved parser engine // from the agent's ChatParserEngineRules for chat attachment processing. ChatParserEngineContextKey ContextKey = "ChatParserEngine" diff --git a/internal/types/context_clone.go b/internal/types/context_clone.go index 3a947ab0..ee4f28a4 100644 --- a/internal/types/context_clone.go +++ b/internal/types/context_clone.go @@ -93,9 +93,15 @@ var contextCloneAcrossDetach = map[ContextKey]bool{ // of emitting its one-shot notice, so the failure is a stalled reply. // A detached context has no live client either, which is what this says. MCPOAuthNonInteractiveContextKey: true, - // Marks a run nobody watches (an agent trial). Dropping it makes a tool - // approval wait out its full timeout for an answer that cannot come. - UnattendedRunContextKey: true, + // Whether anyone can answer the run's prompts. Dropping it reads as + // unattended, which refuses an approval an attended run could have asked. + RunModeContextKey: true, + // The run's access level. Dropping it reads as auto_write, which would + // let a lower-level run's MCP writes through without asking. + AccessLevelContextKey: true, + // Where the run's grants live. Dropping it only asks again. + GrantScopeContextKey: true, + StandingGrantScopeContextKey: true, // ---- Deliberately does not survive a detach ---- // diff --git a/internal/types/context_helpers.go b/internal/types/context_helpers.go index 53ffc69f..14d3c779 100644 --- a/internal/types/context_helpers.go +++ b/internal/types/context_helpers.go @@ -298,28 +298,17 @@ func WithMCPOAuthNonInteractive(ctx context.Context) context.Context { } // IsMCPOAuthNonInteractive reports whether ctx was marked non-interactive for -// MCP OAuth (see WithMCPOAuthNonInteractive). +// MCP OAuth (see WithMCPOAuthNonInteractive), or belongs to an agent run +// whose mode is not attended. func IsMCPOAuthNonInteractive(ctx context.Context) bool { if ctx == nil { return false } - v, _ := ctx.Value(MCPOAuthNonInteractiveContextKey).(bool) - return v -} - -// WithUnattendedRun marks ctx as a run whose prompts nobody can answer. See -// UnattendedRunContextKey. -func WithUnattendedRun(ctx context.Context) context.Context { - return context.WithValue(ctx, UnattendedRunContextKey, true) -} - -// IsUnattendedRun reports whether ctx was marked by WithUnattendedRun. -func IsUnattendedRun(ctx context.Context) bool { - if ctx == nil { - return false + if v, _ := ctx.Value(MCPOAuthNonInteractiveContextKey).(bool); v { + return true } - v, _ := ctx.Value(UnattendedRunContextKey).(bool) - return v + m, set := ctx.Value(RunModeContextKey).(RunMode) + return set && !m.Attended() } // WithBackgroundTask marks ctx as originating from an asynq background worker diff --git a/internal/types/custom_agent.go b/internal/types/custom_agent.go index 3de756d0..fd0448ee 100644 --- a/internal/types/custom_agent.go +++ b/internal/types/custom_agent.go @@ -212,6 +212,11 @@ type CustomAgentConfig struct { // MCPAuthWaitTimeout is how many seconds to wait for in-conversation OAuth // authorization before skipping. <=0 uses the gate's configured timeout. MCPAuthWaitTimeout int `yaml:"mcp_auth_wait_timeout,omitempty" json:"mcp_auth_wait_timeout,omitempty"` + // AccessLevel is the highest access level a run of this agent gets: how + // far it may change data (MCP tools, Wiki writes) without asking. Empty + // means auto_write. The WeKnora assistant uses the workspace's assistant + // ceiling instead. + AccessLevel AssistantAccessLevel `yaml:"access_level,omitempty" json:"access_level,omitempty"` // ===== Skills Settings (only for smart-reasoning mode) ===== // Skills selection mode: "all" = all installed skills, "selected" = specific skills, "none" = no skills diff --git a/internal/types/interfaces/agent.go b/internal/types/interfaces/agent.go index 5f682536..75384330 100644 --- a/internal/types/interfaces/agent.go +++ b/internal/types/interfaces/agent.go @@ -50,9 +50,9 @@ type AgentEngine interface { // types.ResumableAgentRequest. Must be called before Execute. EnableSuspension(request json.RawMessage) - // SetInteractive marks the client as able to render and answer prompts - // (ask_user). Must be called before Execute or Resume. - SetInteractive(interactive bool) + // SetRunMode says whether the client can render and answer prompts + // (ask_user, approvals). Must be called before Execute or Resume. + SetRunMode(mode types.RunMode) // Resume continues a suspended run from its saved snapshot, delivering // the answered prompt to the call it was blocked on. Use instead of diff --git a/internal/types/interfaces/agent_grant.go b/internal/types/interfaces/agent_grant.go new file mode 100644 index 00000000..986453d6 --- /dev/null +++ b/internal/types/interfaces/agent_grant.go @@ -0,0 +1,26 @@ +package interfaces + +import ( + "context" + "time" + + "github.com/Tencent/WeKnora/internal/types" +) + +// AgentGrantRepository persists remembered agent approvals. +type AgentGrantRepository interface { + // FindGrant returns the grant for the key in the scope, revoked or not, + // or nil when there is none. + FindGrant(ctx context.Context, tenantID uint64, userID string, scope types.GrantScope, key string) ( + *types.AgentGrant, error) + // SaveGrant creates the grant or renews a revoked or outdated one. + SaveGrant(ctx context.Context, grant *types.AgentGrant) error + // TouchGrant records that the grant allowed a call at at. + TouchGrant(ctx context.Context, id string, at time.Time) error + // ListGrants returns the user's grants in a scope, newest first. + ListGrants(ctx context.Context, tenantID uint64, userID, scope, scopeID string) ([]*types.AgentGrant, error) + // RevokeGrant revokes one of the user's grants; it reports whether one was. + RevokeGrant(ctx context.Context, tenantID uint64, userID, id string, at time.Time) (bool, error) + // DeleteScopes drops every grant of the given scopes. + DeleteScopes(ctx context.Context, tenantID uint64, scope string, scopeIDs []string) error +} diff --git a/internal/types/interfaces/mcp_tool_approval.go b/internal/types/interfaces/mcp_tool_approval.go index e3aca00c..a16c0b9f 100644 --- a/internal/types/interfaces/mcp_tool_approval.go +++ b/internal/types/interfaces/mcp_tool_approval.go @@ -11,15 +11,22 @@ type MCPToolApprovalRepository interface { ListByService(ctx context.Context, tenantID uint64, serviceID string) ([]*types.MCPToolApproval, error) IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) IsEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) + // Get returns the stored policy of a tool, or nil when it has none. + Get(ctx context.Context, tenantID uint64, serviceID, toolName string) (*types.MCPToolApproval, error) UpsertPolicy(ctx context.Context, tenantID uint64, serviceID, toolName string, patch types.MCPToolPolicyPatch) error } // MCPToolApprovalService is the business layer for MCP tool policies. type MCPToolApprovalService interface { ListByService(ctx context.Context, tenantID uint64, serviceID string) ([]*types.MCPToolApproval, error) - SetPolicy(ctx context.Context, tenantID uint64, serviceID, toolName string, requireApproval, enabled *bool) error + SetPolicy(ctx context.Context, tenantID uint64, serviceID, toolName string, patch types.MCPToolPolicyPatch) error SetRequireApproval(ctx context.Context, tenantID uint64, serviceID, toolName string, require bool) error SetEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string, enabled bool) error IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) IsEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) + // Policy returns the stored policy of a tool, or nil when it has none. + Policy(ctx context.Context, tenantID uint64, serviceID, toolName string) (*types.MCPToolApproval, error) + // ObserveRisk records a risk the service declared for a tool; the + // recorded risk only rises. + ObserveRisk(ctx context.Context, tenantID uint64, serviceID, toolName string, risk string) error } diff --git a/internal/types/mcp.go b/internal/types/mcp.go index 0e62b31d..3b380fb6 100644 --- a/internal/types/mcp.go +++ b/internal/types/mcp.go @@ -3,6 +3,7 @@ package types import ( "database/sql/driver" "encoding/json" + "errors" "log" "strings" "time" @@ -147,6 +148,20 @@ type MCPTool struct { InputSchema json.RawMessage `json:"inputSchema"` // JSON Schema for tool parameters // RequireApproval when true: agent execution pauses until the user approves in UI (issue #1173). RequireApproval bool `json:"require_approval,omitempty" extensions:"x-agent"` + // Annotations are the hints the service declares in tools/list. They come + // from outside and only seed the tool's risk. + Annotations *MCPToolAnnotations `json:"annotations,omitempty"` +} + +// MCPToolAnnotations are the MCP tool annotations WeKnora reads. +type MCPToolAnnotations struct { + ReadOnlyHint *bool `json:"readOnlyHint,omitempty"` + DestructiveHint *bool `json:"destructiveHint,omitempty"` +} + +// DeclaresReadOnly reports whether the service declared the tool read-only. +func (t *MCPTool) DeclaresReadOnly() bool { + return t != nil && t.Annotations != nil && t.Annotations.ReadOnlyHint != nil && *t.Annotations.ReadOnlyHint } // MCPToolApproval persists per-tool policies for an MCP service, including @@ -162,17 +177,31 @@ type MCPToolApproval struct { // are treated as enabled for backwards compatibility. The DB/GORM default is // true; inserts persist false via a map Create so GORM does not omit the // Go zero value. - Enabled bool `json:"enabled" gorm:"not null;default:true"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` + Enabled bool `json:"enabled" gorm:"not null;default:true"` + // Risk is the workspace's explicit risk for the tool (read, probe, write + // or destructive); empty defers to ObservedRisk. + Risk string `json:"risk" gorm:"type:varchar(16);not null;default:''"` + // ObservedRisk is the highest risk the service has declared for the tool. + // It only rises on its own: a service cannot lower its tool's risk + // without the workspace setting Risk. + ObservedRisk string `json:"observed_risk" gorm:"type:varchar(16);not null;default:''"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` } +// ErrInvalidMCPToolPolicy rejects a policy value the caller supplied. +var ErrInvalidMCPToolPolicy = errors.New("invalid MCP tool policy") + // MCPToolPolicyPatch is a partial per-tool policy update. Nil fields are left // unchanged on existing rows. A newly inserted row uses RequireApproval=false // and Enabled=true for any omitted field. type MCPToolPolicyPatch struct { RequireApproval *bool Enabled *bool + // Risk sets the explicit risk; an empty string clears it. + Risk *string + // ObservedRisk records a risk the service declared. + ObservedRisk *string } // BeforeCreate sets ID for MCPToolApproval. diff --git a/internal/types/principal.go b/internal/types/principal.go index ca06274e..58a9460b 100644 --- a/internal/types/principal.go +++ b/internal/types/principal.go @@ -46,12 +46,18 @@ func IsAPISessionOwnerID(ownerID string) bool { type Principal struct { Type string ID string + // ActingVia names what acts for this principal without them present, + // e.g. "automation:". Empty when the principal acts in person. It + // does not change who is authorized or StorageID: the principal still + // owns the run and answers its approvals. + ActingVia string } func (p Principal) Normalize() Principal { return Principal{ - Type: strings.TrimSpace(p.Type), - ID: strings.TrimSpace(p.ID), + Type: strings.TrimSpace(p.Type), + ID: strings.TrimSpace(p.ID), + ActingVia: strings.TrimSpace(p.ActingVia), } } diff --git a/internal/types/qa_request.go b/internal/types/qa_request.go index 1778adb6..a7a1eaa5 100644 --- a/internal/types/qa_request.go +++ b/internal/types/qa_request.go @@ -208,10 +208,14 @@ type QARequest struct { // message and answer it afterwards (web, embed, API); IM and MCP callers // wait synchronously. Suspendable bool - // Interactive marks a caller that can show and answer a prompt the agent - // raises on its own, such as an ask_user question. API-key callers cannot - // answer prompts, so their runs are not interactive. - Interactive bool + // Mode says whether anyone can answer a prompt the agent raises, such as + // an ask_user question or a tool approval. Empty is unattended: API-key, + // IM and MCP-server callers cannot answer prompts. + Mode RunMode + // GrantSessionID is the session whose "allow for this session" grants + // the run uses: the root conversation for a delegated child, empty for + // the run's own session. + GrantSessionID string // Resume, when set, continues a suspended run instead of starting one. Resume *AgentResume } diff --git a/internal/types/run_mode.go b/internal/types/run_mode.go new file mode 100644 index 00000000..abf5bc5d --- /dev/null +++ b/internal/types/run_mode.go @@ -0,0 +1,61 @@ +package types + +import "context" + +// RunMode says whether anyone can answer the prompts an agent run raises. +type RunMode string + +const ( + // RunModeAttended is a run whose client renders prompt cards and answers + // them: the web chat and the assistant panel. + RunModeAttended RunMode = "attended" + // RunModeDeferred is a run nobody watches now whose owner can answer + // later: a prompt suspends the run until it is answered. + RunModeDeferred RunMode = "deferred" + // RunModeUnattended is a run nobody can answer, such as an API, embed or + // IM request: a prompt is refused at once. + RunModeUnattended RunMode = "unattended" +) + +// Normalize returns m, treating anything unknown, including empty, as +// unattended: a run is only answerable when its caller says so. +func (m RunMode) Normalize() RunMode { + switch m { + case RunModeAttended, RunModeDeferred: + return m + default: + return RunModeUnattended + } +} + +// Attended reports whether a client can answer prompts now. +func (m RunMode) Attended() bool { return m.Normalize() == RunModeAttended } + +// WithRunMode attaches the run's mode to ctx. +func WithRunMode(ctx context.Context, m RunMode) context.Context { + return context.WithValue(ctx, RunModeContextKey, m.Normalize()) +} + +// RunModeFromContext returns the mode attached to ctx, unattended when none. +func RunModeFromContext(ctx context.Context) RunMode { + if ctx == nil { + return RunModeUnattended + } + m, _ := ctx.Value(RunModeContextKey).(RunMode) + return m.Normalize() +} + +// WithAccessLevel records the run's effective access level. +func WithAccessLevel(ctx context.Context, level AssistantAccessLevel) context.Context { + return context.WithValue(ctx, AccessLevelContextKey, level) +} + +// AccessLevelFromContext is the run's access level. A context that never +// set one gets AssistantAccessAutoWrite, the level of an agent with no +// configured ceiling. +func AccessLevelFromContext(ctx context.Context) AssistantAccessLevel { + if level, ok := ctx.Value(AccessLevelContextKey).(AssistantAccessLevel); ok && level.Valid() { + return level + } + return AssistantAccessAutoWrite +} diff --git a/migrations/sqlite/000043_mcp_tool_risk.down.sql b/migrations/sqlite/000043_mcp_tool_risk.down.sql new file mode 100644 index 00000000..c9a74346 --- /dev/null +++ b/migrations/sqlite/000043_mcp_tool_risk.down.sql @@ -0,0 +1,2 @@ +ALTER TABLE mcp_tool_approvals DROP COLUMN observed_risk; +ALTER TABLE mcp_tool_approvals DROP COLUMN risk; diff --git a/migrations/sqlite/000043_mcp_tool_risk.up.sql b/migrations/sqlite/000043_mcp_tool_risk.up.sql new file mode 100644 index 00000000..844a908c --- /dev/null +++ b/migrations/sqlite/000043_mcp_tool_risk.up.sql @@ -0,0 +1,4 @@ +-- Per-tool MCP risk: the workspace's explicit setting and the highest risk +-- declared through tool annotations. Empty means "not set". +ALTER TABLE mcp_tool_approvals ADD COLUMN risk VARCHAR(16) NOT NULL DEFAULT ''; +ALTER TABLE mcp_tool_approvals ADD COLUMN observed_risk VARCHAR(16) NOT NULL DEFAULT ''; diff --git a/migrations/sqlite/000044_agent_grants.down.sql b/migrations/sqlite/000044_agent_grants.down.sql new file mode 100644 index 00000000..8950c6d3 --- /dev/null +++ b/migrations/sqlite/000044_agent_grants.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS agent_grants; diff --git a/migrations/sqlite/000044_agent_grants.up.sql b/migrations/sqlite/000044_agent_grants.up.sql new file mode 100644 index 00000000..6816eb88 --- /dev/null +++ b/migrations/sqlite/000044_agent_grants.up.sql @@ -0,0 +1,22 @@ +-- Remembered agent approvals: "allow for the rest of this conversation" and +-- the grants an automation carries between runs. +CREATE TABLE IF NOT EXISTS agent_grants ( + id VARCHAR(36) PRIMARY KEY, + tenant_id BIGINT NOT NULL, + user_id VARCHAR(128) NOT NULL, + scope VARCHAR(16) NOT NULL, + scope_id VARCHAR(64) NOT NULL, + grant_key VARCHAR(512) NOT NULL, + label TEXT, + binding_hash VARCHAR(64) NOT NULL DEFAULT '', + risk VARCHAR(16) NOT NULL DEFAULT 'write', + prompt_id VARCHAR(36), + created_at DATETIME NOT NULL, + updated_at DATETIME NOT NULL, + last_used_at DATETIME, + expires_at DATETIME, + revoked_at DATETIME +); +CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_grants_key + ON agent_grants(tenant_id, user_id, scope, scope_id, grant_key); +CREATE INDEX IF NOT EXISTS idx_agent_grants_scope ON agent_grants(tenant_id, scope, scope_id); diff --git a/migrations/versioned/000126_mcp_tool_risk.down.sql b/migrations/versioned/000126_mcp_tool_risk.down.sql new file mode 100644 index 00000000..a12c1dd4 --- /dev/null +++ b/migrations/versioned/000126_mcp_tool_risk.down.sql @@ -0,0 +1,2 @@ +ALTER TABLE mcp_tool_approvals DROP COLUMN IF EXISTS observed_risk; +ALTER TABLE mcp_tool_approvals DROP COLUMN IF EXISTS risk; diff --git a/migrations/versioned/000126_mcp_tool_risk.up.sql b/migrations/versioned/000126_mcp_tool_risk.up.sql new file mode 100644 index 00000000..65205e3c --- /dev/null +++ b/migrations/versioned/000126_mcp_tool_risk.up.sql @@ -0,0 +1,7 @@ +-- Per-tool MCP risk. risk is the workspace's explicit setting; observed_risk +-- is the highest risk the service has declared through tool annotations. +-- Empty values mean "not set" so existing rows keep their behaviour. +ALTER TABLE mcp_tool_approvals + ADD COLUMN IF NOT EXISTS risk VARCHAR(16) NOT NULL DEFAULT ''; +ALTER TABLE mcp_tool_approvals + ADD COLUMN IF NOT EXISTS observed_risk VARCHAR(16) NOT NULL DEFAULT ''; diff --git a/migrations/versioned/000127_agent_grants.down.sql b/migrations/versioned/000127_agent_grants.down.sql new file mode 100644 index 00000000..8950c6d3 --- /dev/null +++ b/migrations/versioned/000127_agent_grants.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS agent_grants; diff --git a/migrations/versioned/000127_agent_grants.up.sql b/migrations/versioned/000127_agent_grants.up.sql new file mode 100644 index 00000000..1597ddf8 --- /dev/null +++ b/migrations/versioned/000127_agent_grants.up.sql @@ -0,0 +1,22 @@ +-- Remembered agent approvals: "allow for the rest of this conversation" and +-- the grants an automation carries between runs. +CREATE TABLE IF NOT EXISTS agent_grants ( + id VARCHAR(36) PRIMARY KEY, + tenant_id BIGINT NOT NULL, + user_id VARCHAR(128) NOT NULL, + scope VARCHAR(16) NOT NULL, + scope_id VARCHAR(64) NOT NULL, + grant_key VARCHAR(512) NOT NULL, + label TEXT, + binding_hash VARCHAR(64) NOT NULL DEFAULT '', + risk VARCHAR(16) NOT NULL DEFAULT 'write', + prompt_id VARCHAR(36), + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + last_used_at TIMESTAMPTZ, + expires_at TIMESTAMPTZ, + revoked_at TIMESTAMPTZ +); +CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_grants_key + ON agent_grants(tenant_id, user_id, scope, scope_id, grant_key); +CREATE INDEX IF NOT EXISTS idx_agent_grants_scope ON agent_grants(tenant_id, scope, scope_id);