Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(automation): scheduled agent runs with in-app notifications (#4492)

lyingbugeecfe4b3c8c3
diff --git a/config/prompt_templates/agent_system_prompt.yaml b/config/prompt_templates/agent_system_prompt.yaml
index ba88f9321..85c3b1d52 100644
--- a/config/prompt_templates/agent_system_prompt.yaml
+++ b/config/prompt_templates/agent_system_prompt.yaml
@@ -186,6 +186,12 @@ templates:
- When the user asks why something is not found, run knowledge_base.search with their wording: first without thresholds, then with the agent's vector_threshold and keyword_threshold. Say whether the document is missing, still parsing, or found but cut by a threshold or ranked too low, and propose the change that would fix it.
- Probe operations change nothing, but a turn may run only a few. Check once, then report what you found.
- When delegating to existing reasoning agents, follow the runtime coordination instructions and available collaboration tool definitions.
+ Scheduled and recurring work (automations):
+ - An automation has an agent run a task on a schedule as the user, in the background, and notifies them in WeKnora when a run finishes, fails or waits for their approval. Use it for anything to be done later or repeatedly ("every morning", "remind me at 5pm", "each Monday summarise"), instead of saying you cannot act after the conversation. Find the automation.* operations with find_operations.
+ - Turn the user's wording into a five-field cron expression (minute first) or a one-time at, with the user's IANA timezone (ask if you cannot tell). A one-time at is a wall-clock time in that timezone, "2006-01-02 15:04" or RFC3339; do not invent a UTC offset. Check it with automation.validate_trigger and tell the user the next run times, in their timezone, before creating it.
+ - Runs are at least 5 minutes apart. If the user asks for more often, say so and offer every 5 minutes or a longer interval rather than giving up.
+ - Nobody watches a run and it cannot ask questions, so write the instruction as the complete task: what to do, where to look, what the result should contain. Results arrive as WeKnora notifications, not on the user's phone or in chat apps; say so when they expect a reminder elsewhere.
+ - Leave access_level at confirm unless the user asks for changes to run without approval. After creating one, offer open_page with page automations and its automation_id.
The user's past conversations:
- You can read the user's own conversations and nobody else's, and you cannot change them. session.list shows recent ones or matches titles; message.search finds one by what was said; message.list reads one.
- When the user refers to something from before ("last time", "what I asked about X"), search before saying it was never discussed. If message.search finds nothing, check message.chat_history_stats: without indexing it matches exact words only, so retry with the user's own wording and tell them search by meaning is off.
diff --git a/docs/design/agent-automation.md b/docs/design/agent-automation.md
index 1b20550c2..9f6be0ec2 100644
--- a/docs/design/agent-automation.md
+++ b/docs/design/agent-automation.md
@@ -1,6 +1,6 @@
# Agent 自动化(定时任务)
-状态:设计稿,未实现。日期:2026-10-19。
+状态:第一版已实现,与设计的差异见 §13。日期:2026-10-19。
权限部分建立在 [Agent 执行权限模型](agent-permission-model.md) 之上:自动化不定义自己的审批策略或白名单,只使用该模型的 `deferred` 运行模式、`automation` 作用域授权和 `ActingVia` 身份。权限模型的前三步是本需求的前置条件。
@@ -242,3 +242,18 @@ operations 新增:`automation.list`、`automation.get`、`automation.create`
- `persistent` 会话长期运行后的上下文压缩策略是否需要比普通会话更激进。
- 通知中心是否需要按工作空间隔离展示。
- 每租户数量与并发上限的默认值,以及是否放进系统设置页。
+
+## 13. 实现说明
+
+第一版按 §10 的第 1–4 步实现,以下几处与设计不同:
+
+- **没有抽出 `AgentRunService`**。执行器 `automation_runner.go` 照协作执行器的写法自己完成建消息对、挂事件流、监听完成与错误、落库;协作执行器不动。四个后台调用方的统一留作单独的重构。
+- **只有所有者能访问**。接口按所有者过滤,空间管理员不能查看或停用他人的自动化(§12 第一条仍待定)。API Key、IM 用户和自动化运行内部(`ActingVia` 非空)都不能创建或管理自动化。
+- **调度只走数据库**。所有实例每 15 秒扫描到期记录,用 `version` 做 CAS 领取,不经 Redis 投递;Lite 与多实例部署同一套逻辑。
+- **审批过期由调度器对账**,不改 HITL Broker 的过期时间:等待审批超过 `approval_timeout_minutes` 后运行记为失败并关闭提示。Broker 对挂起提示的回收如果更早,运行同样记为失败,原因取提示的关闭原因。
+- **长期授权从历史审批提升**。设置页不提供工具清单勾选,而是列出本自动化运行中请求过审批、尚未授权的写类与 destructive 调用,由所有者逐条确认;授权绑定 Agent 配置与所有者角色(`AutomationBinding`),变化后显示失效。需要每次审批的调用不会出现在候选里。
+- **限制只有时长**。`limits` 目前只有 `max_duration_minutes`(默认 30,上限 240,不含等待审批的时间);token 上限没有单独实现,由 Agent 自身的 `max_iterations` 约束。
+- **`persistent` 会话忙时跳过**。长期会话里还有进行中的运行(包括用户在该会话里手动对话)时,本次运行记为 `skipped`。
+- **内置助手的 `agent_id` 存为助手 ID**(`builtin-weknora-assistant`),空字符串只在创建时作为默认值。
+- **前端入口**:侧栏“自动化”页面(`/platform/automations`),运行详情直接打开自动化会话;通知链接 `/platform/automations/:id?run=:runId` 打开对应运行。右上角铃铛合并展示邀请与通知,60 秒轮询。
+- **助手审批卡**仍是通用的 operation 参数展示,未单独渲染触发描述与未来触发时间;助手需要先调用 `automation.validate_trigger` 并在对话里告知用户。
diff --git a/docs/docs.go b/docs/docs.go
index 826588e67..931cf1991 100644
--- a/docs/docs.go
+++ b/docs/docs.go
@@ -85,6 +85,88 @@ const docTemplate = `{
}
}
},
+ "/agent/grants": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "列出当前用户在某个会话(根会话)中通过“本会话允许”记住的授权,包括其委派子任务上批准的授权。",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Agent"
+ ],
+ "summary": "列出会话内的 Agent 授权",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "根会话 ID",
+ "name": "session_id",
+ "in": "query",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "授权列表",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "400": {
+ "description": "请求参数错误",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ }
+ }
+ },
+ "/agent/grants/{id}": {
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "撤销当前用户的一条授权;之后同类调用会重新询问。",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Agent"
+ ],
+ "summary": "撤销 Agent 授权",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "授权 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "撤销结果",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "404": {
+ "description": "授权不存在",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ }
+ }
+ },
"/agent/mcp-oauth-resolutions/{pending_id}": {
"post": {
"security": [
@@ -1832,6 +1914,801 @@ const docTemplate = `{
}
}
},
+ "/automation-runs/{id}": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "获取运行记录",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "运行 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "运行记录",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/internal_handler.DataResponse"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationRun"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/automation-runs/{id}/cancel": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "排队或等待审批的运行立即结束;执行中的运行在下一次检查时停止",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "停止运行",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "运行 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "运行记录",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/internal_handler.DataResponse"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationRun"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/automations": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "列出当前用户在本空间创建的自动化(定时任务),最新的在前",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "列出我的自动化",
+ "responses": {
+ "200": {
+ "description": "自动化列表",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/internal_handler.DataResponse"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Automation"
+ }
+ }
+ }
+ }
+ ]
+ }
+ }
+ },
+ "x-agent": {
+ "id": "automation.list",
+ "max_items": 100,
+ "risk": "read"
+ },
+ "x-agent-hint": "Lists the user's automations: scheduled tasks an agent runs on their behalf, with next and last run."
+ },
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "创建一个按计划由 Agent 以当前用户身份运行的任务",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "创建自动化",
+ "parameters": [
+ {
+ "description": "自动化",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/internal_handler.CreateAutomationRequest"
+ }
+ }
+ ],
+ "responses": {
+ "201": {
+ "description": "创建的自动化",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/internal_handler.DataResponse"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Automation"
+ }
+ }
+ }
+ ]
+ }
+ },
+ "400": {
+ "description": "参数不合法",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ },
+ "x-agent": {
+ "always_confirm": true,
+ "id": "automation.create",
+ "label_param": "name",
+ "risk": "write",
+ "role": "viewer"
+ },
+ "x-agent-hint": "Creates an automation the user runs as. Turn the user's wording into a cron expression (five fields, minute first) and an IANA timezone, and check it with automation.validate_trigger first, telling the user the next run times it returns. Runs are unattended: write the instruction as a complete task, since nobody can answer questions during a run. access_level defaults to confirm, where each change waits for the user's approval; only set auto_write when the user asks for it."
+ }
+ },
+ "/automations/validate-trigger": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "校验 cron 或一次性触发器,返回未来 3 次触发时间",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "校验触发器",
+ "parameters": [
+ {
+ "description": "触发器",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/internal_handler.ValidateTriggerRequest"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "未来触发时间",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/internal_handler.DataResponse"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/internal_handler.ValidateTriggerResult"
+ }
+ }
+ }
+ ]
+ }
+ },
+ "400": {
+ "description": "触发器不合法",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ },
+ "x-agent": {
+ "id": "automation.validate_trigger",
+ "risk": "probe"
+ },
+ "x-agent-hint": "Checks a trigger and returns its next three run times in UTC; convert them to the trigger's timezone for the user."
+ }
+ },
+ "/automations/{id}": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "获取自动化",
+ "parameters": [
+ {
+ "type": "string",
+ "x-agent": "automation_id",
+ "description": "自动化 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "自动化",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/internal_handler.DataResponse"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Automation"
+ }
+ }
+ }
+ ]
+ }
+ },
+ "404": {
+ "description": "不存在",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ },
+ "x-agent": {
+ "id": "automation.get",
+ "risk": "read"
+ },
+ "x-agent-hint": "Returns one automation, including its instruction."
+ },
+ "put": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "只修改请求中出现的字段,其余保持不变",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "修改自动化",
+ "parameters": [
+ {
+ "type": "string",
+ "x-agent": "automation_id",
+ "description": "自动化 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ },
+ {
+ "description": "要修改的字段",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationPatch"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "修改后的自动化",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/internal_handler.DataResponse"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Automation"
+ }
+ }
+ }
+ ]
+ }
+ },
+ "400": {
+ "description": "参数不合法",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ },
+ "x-agent": {
+ "always_confirm": true,
+ "id": "automation.update",
+ "label": "name",
+ "risk": "write",
+ "role": "viewer",
+ "target": "automation.get"
+ },
+ "x-agent-hint": "Changes the listed fields of an automation; a field left out is kept. Check a new trigger with automation.validate_trigger first. Use automation.pause and automation.resume to switch it off and on."
+ },
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "停止进行中的运行,删除自动化及其运行记录、会话和长期授权",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "删除自动化",
+ "parameters": [
+ {
+ "type": "string",
+ "x-agent": "automation_id",
+ "description": "自动化 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "删除成功",
+ "schema": {
+ "$ref": "#/definitions/internal_handler.SuccessResponse"
+ }
+ },
+ "404": {
+ "description": "不存在",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ },
+ "x-agent": {
+ "id": "automation.delete",
+ "label": "name",
+ "risk": "destructive",
+ "role": "viewer",
+ "target": "automation.get"
+ },
+ "x-agent-hint": "Deletes an automation with its run history and conversations. Cannot be undone; automation.pause keeps it."
+ }
+ },
+ "/automations/{id}/grant-candidates": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "列出本自动化的运行请求过审批、尚未长期授权的调用;需每次审批的调用不在其中",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "列出可设为长期授权的调用",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "自动化 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "候选调用",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ }
+ },
+ "/automations/{id}/grants": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "列出以后的运行无需确认即可执行的调用,以及失效原因",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "列出自动化的长期授权",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "自动化 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "长期授权",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ },
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "让以后的运行无需确认即可执行某次运行请求过审批的调用;Agent 配置或所有者角色变化后失效",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "添加长期授权",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "自动化 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ },
+ {
+ "description": "{prompt_id}",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "type": "object"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "授权",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ }
+ },
+ "/automations/{id}/pause": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "停止按计划触发;进行中的运行不受影响",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "暂停自动化",
+ "parameters": [
+ {
+ "type": "string",
+ "x-agent": "automation_id",
+ "description": "自动化 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "暂停后的自动化",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/internal_handler.DataResponse"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Automation"
+ }
+ }
+ }
+ ]
+ }
+ }
+ },
+ "x-agent": {
+ "id": "automation.pause",
+ "label": "name",
+ "risk": "write",
+ "role": "viewer",
+ "target": "automation.get"
+ },
+ "x-agent-hint": "Stops an automation from running on schedule until automation.resume."
+ }
+ },
+ "/automations/{id}/resume": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "从现在起重新按计划触发,并清零连续失败计数",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "恢复自动化",
+ "parameters": [
+ {
+ "type": "string",
+ "x-agent": "automation_id",
+ "description": "自动化 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "恢复后的自动化",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/internal_handler.DataResponse"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Automation"
+ }
+ }
+ }
+ ]
+ }
+ }
+ },
+ "x-agent": {
+ "always_confirm": true,
+ "id": "automation.resume",
+ "label": "name",
+ "risk": "write",
+ "role": "viewer",
+ "target": "automation.get"
+ },
+ "x-agent-hint": "Schedules a paused automation again from now; missed runs are not caught up."
+ }
+ },
+ "/automations/{id}/run": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "排队一次手动运行;已有运行在排队或进行中时拒绝",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "立即运行自动化",
+ "parameters": [
+ {
+ "type": "string",
+ "x-agent": "automation_id",
+ "description": "自动化 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "202": {
+ "description": "排队的运行",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/internal_handler.DataResponse"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationRun"
+ }
+ }
+ }
+ ]
+ }
+ },
+ "409": {
+ "description": "已有运行",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ },
+ "x-agent": {
+ "always_confirm": true,
+ "id": "automation.run_now",
+ "label": "name",
+ "risk": "write",
+ "role": "viewer",
+ "target": "automation.get"
+ },
+ "x-agent-hint": "Queues a run now, in the background; follow it with automation.list_runs."
+ }
+ },
+ "/automations/{id}/runs": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "列出运行记录",
+ "parameters": [
+ {
+ "type": "string",
+ "x-agent": "automation_id",
+ "description": "自动化 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ },
+ {
+ "type": "integer",
+ "x-agent": true,
+ "description": "页码,从 1 开始",
+ "name": "page",
+ "in": "query"
+ },
+ {
+ "type": "integer",
+ "x-agent": true,
+ "x-agent-maximum": "20",
+ "description": "每页条数,最多 100",
+ "name": "page_size",
+ "in": "query"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "运行记录",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/internal_handler.PageResponse"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationRun"
+ }
+ }
+ }
+ }
+ ]
+ }
+ }
+ },
+ "x-agent": {
+ "id": "automation.list_runs",
+ "risk": "read"
+ },
+ "x-agent-hint": "Lists an automation's runs, newest first, with status, error and the start of the answer."
+ }
+ },
"/chunker/preview": {
"post": {
"security": [
@@ -2597,7 +3474,7 @@ const docTemplate = `{
"id": "data_source.get_sync_log",
"risk": "read"
},
- "x-agent-hint": "Read the current status, counts and errors of a sync_log_id returned by data_source.sync or data_source.list_sync_logs. A started job is not a completed sync."
+ "x-agent-hint": "Read the current status and counts of a sync_log_id returned by data_source.sync or data_source.list_sync_logs. A started job is not a completed sync. Raw upstream errors are omitted; detailed failures remain on the data source settings page."
}
},
"/datasource/types": {
@@ -2710,7 +3587,7 @@ const docTemplate = `{
"id": "data_source.get",
"risk": "read"
},
- "x-agent-hint": "Read a configured data source and its sync state; credentials and connector configuration are not returned."
+ "x-agent-hint": "Read a configured data source and its sync state; credentials, connector settings and raw upstream errors are omitted. For detailed failures use the data source settings page."
},
"put": {
"description": "Update an existing data source configuration",
@@ -2854,7 +3731,7 @@ const docTemplate = `{
"id": "data_source.list_sync_logs",
"risk": "read"
},
- "x-agent-hint": "Read recent sync results, counts and errors. Use limit and offset for older records."
+ "x-agent-hint": "Read recent sync status and counts. Use limit and offset for older records. Raw upstream errors are omitted; detailed failures remain on the data source settings page."
}
},
"/datasource/{id}/pause": {
@@ -12091,7 +12968,7 @@ const docTemplate = `{
"ApiKeyAuth": []
}
],
- "description": "为指定 MCP 服务下的某个工具更新启用状态和/或人工审批要求。至少提供 require_approval 或 enabled 之一;省略的字段保持原值。",
+ "description": "为指定 MCP 服务下的某个工具更新启用状态、人工审批要求和/或风险等级。\n至少提供 require_approval、enabled、risk 之一;省略的字段保持原值。\nrisk 为 read/probe/write/destructive,空字符串表示改回按服务注解推断。",
"consumes": [
"application/json"
],
@@ -12118,7 +12995,7 @@ const docTemplate = `{
"required": true
},
{
- "description": "{require_approval?: bool, enabled?: bool}",
+ "description": "{require_approval?: bool, enabled?: bool, risk?: string}",
"name": "request",
"in": "body",
"required": true,
@@ -14239,6 +15116,84 @@ const docTemplate = `{
"x-agent-hint": "Copies a workspace-owned model configuration under a required new display_name. Choose model_id from model.list; builtin models cannot be copied. The upstream model name, connection parameters and saved credentials are copied on the backend; never request or resend credentials. The copy is not the default and does not change agent or knowledge base bindings. Active local models are reused without downloading again; copying an unfinished or failed local model starts a background download, so read the returned model_id with model.get until its status is active or download_failed."
}
},
+ "/notifications": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "通知"
+ ],
+ "summary": "列出我的通知",
+ "parameters": [
+ {
+ "type": "integer",
+ "description": "条数,最多 100",
+ "name": "limit",
+ "in": "query"
+ },
+ {
+ "type": "boolean",
+ "description": "只看未读",
+ "name": "unread",
+ "in": "query"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "{items, unread}",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ }
+ },
+ "/notifications/read": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "ids 为空时全部标记已读",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "通知"
+ ],
+ "summary": "标记通知已读",
+ "parameters": [
+ {
+ "description": "{ids}",
+ "name": "request",
+ "in": "body",
+ "schema": {
+ "type": "object"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "结果",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ }
+ },
"/organizations": {
"get": {
"security": [
@@ -24762,6 +25717,13 @@ const docTemplate = `{
"description": "Iteration number (0-indexed)",
"type": "integer"
},
+ "progress": {
+ "description": "Progress is user-facing commentary from a non-terminal round. Thought stays intact for model replay.",
+ "type": "string"
+ },
+ "progress_event_id": {
+ "type": "string"
+ },
"reasoning_content": {
"description": "ReasoningContent stores the OpenAI-protocol reasoning_content emitted by the\nmodel in this round. Persisted on AgentStep so cross-turn replay can put it\nback on the assistant message — required by MiMo / DeepSeek V3.2+ thinking\nmode, ignored by providers that don't recognize the field.",
"type": "string"
@@ -25252,6 +26214,346 @@ const docTemplate = `{
}
}
},
+ "github_com_Tencent_WeKnora_internal_types.Automation": {
+ "type": "object",
+ "properties": {
+ "access_level": {
+ "description": "AccessLevel is how far runs may change data without asking, capped by\nthe agent's and the workspace's ceilings.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AssistantAccessLevel"
+ }
+ ],
+ "x-agent": true
+ },
+ "agent_id": {
+ "description": "AgentID is the agent that runs it; the WeKnora assistant's ID runs the\nassistant.",
+ "type": "string",
+ "x-agent": true
+ },
+ "approval_timeout_minutes": {
+ "description": "ApprovalTimeoutMinutes is how long a run waits for an approval before\nit fails.",
+ "type": "integer",
+ "x-agent": true
+ },
+ "carry_last_result": {
+ "description": "CarryLastResult adds the last successful answer to each per-run\nconversation.",
+ "type": "boolean",
+ "x-agent": true
+ },
+ "consecutive_failures": {
+ "type": "integer"
+ },
+ "created_at": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string",
+ "x-agent": true
+ },
+ "enabled": {
+ "type": "boolean",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "id": {
+ "type": "string",
+ "x-agent": "automation_id",
+ "x-agent-response": true
+ },
+ "instruction": {
+ "description": "Instruction is the task, sent as the user message of each run after\nits variables are filled in.",
+ "type": "string",
+ "x-agent": true,
+ "x-agent-detail": true
+ },
+ "last_run_at": {
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "last_run_status": {
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "last_success_at": {
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "limits": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationLimits"
+ },
+ "misfire_policy": {
+ "type": "string",
+ "x-agent": true
+ },
+ "name": {
+ "type": "string",
+ "x-agent": true
+ },
+ "next_run_at": {
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "notify_on_success": {
+ "type": "boolean",
+ "x-agent": true
+ },
+ "overlap_policy": {
+ "type": "string",
+ "x-agent": true
+ },
+ "owner_user_id": {
+ "description": "OwnerUserID is the account the automation runs as.",
+ "type": "string"
+ },
+ "paused_reason": {
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "persistent_session_id": {
+ "description": "PersistentSessionID is the conversation of a persistent automation,\ncreated on its first run.",
+ "type": "string"
+ },
+ "session_mode": {
+ "type": "string",
+ "x-agent": true
+ },
+ "tenant_id": {
+ "type": "integer"
+ },
+ "trigger": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationTrigger"
+ }
+ ],
+ "x-agent": true
+ },
+ "updated_at": {
+ "type": "string"
+ }
+ }
+ },
+ "github_com_Tencent_WeKnora_internal_types.AutomationLimits": {
+ "type": "object",
+ "properties": {
+ "max_duration_minutes": {
+ "description": "MaxDurationMinutes caps a run's execution time, not counting time spent\nwaiting for approval. 0 uses the default.",
+ "type": "integer",
+ "x-agent": true
+ }
+ }
+ },
+ "github_com_Tencent_WeKnora_internal_types.AutomationPatch": {
+ "type": "object",
+ "properties": {
+ "access_level": {
+ "description": "How far runs may change data without asking",
+ "enum": [
+ "read_only",
+ "confirm",
+ "auto_write"
+ ],
+ "allOf": [
+ {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AssistantAccessLevel"
+ }
+ ],
+ "x-agent": true
+ },
+ "agent_id": {
+ "description": "Agent that runs it, from agent.list; empty runs the WeKnora assistant",
+ "type": "string",
+ "x-agent": true
+ },
+ "approval_timeout_minutes": {
+ "description": "How long a run waits for an approval before it fails, in minutes",
+ "type": "integer",
+ "x-agent": true
+ },
+ "carry_last_result": {
+ "description": "Whether each per_run conversation gets the last successful answer",
+ "type": "boolean",
+ "x-agent": true
+ },
+ "description": {
+ "description": "What it is for",
+ "type": "string",
+ "x-agent": true
+ },
+ "enabled": {
+ "description": "Whether it is scheduled; on update use pause and resume instead",
+ "type": "boolean"
+ },
+ "instruction": {
+ "description": "The task, sent as the user message of each run. May name now,\nlast_run_at, last_success_at, run_id or automation_name inside double\ncurly braces to have it filled in",
+ "type": "string",
+ "x-agent": true,
+ "x-agent-max-bytes": "32000"
+ },
+ "limits": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationLimits"
+ },
+ "misfire_policy": {
+ "description": "What happens to runs missed while the service was down or paused",
+ "type": "string",
+ "enum": [
+ "skip",
+ "run_once"
+ ],
+ "x-agent": true
+ },
+ "name": {
+ "description": "What the automation is called",
+ "type": "string",
+ "x-agent": true
+ },
+ "notify_on_success": {
+ "description": "Whether a successful run notifies the owner",
+ "type": "boolean",
+ "x-agent": true
+ },
+ "overlap_policy": {
+ "description": "What happens when a run is due while the previous one is still going",
+ "type": "string",
+ "enum": [
+ "skip",
+ "queue"
+ ],
+ "x-agent": true
+ },
+ "session_mode": {
+ "description": "per_run starts a new conversation each run; persistent keeps one",
+ "type": "string",
+ "enum": [
+ "per_run",
+ "persistent"
+ ],
+ "x-agent": true
+ },
+ "trigger": {
+ "description": "When it runs",
+ "allOf": [
+ {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationTrigger"
+ }
+ ],
+ "x-agent": true
+ }
+ }
+ },
+ "github_com_Tencent_WeKnora_internal_types.AutomationRun": {
+ "type": "object",
+ "properties": {
+ "answer": {
+ "description": "Answer is the start of the final answer, for listings.",
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "assistant_message_id": {
+ "type": "string"
+ },
+ "automation_id": {
+ "type": "string"
+ },
+ "cancel_requested": {
+ "description": "CancelRequested stops the run at its next check.",
+ "type": "boolean"
+ },
+ "created_at": {
+ "type": "string"
+ },
+ "error": {
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "finished_at": {
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "id": {
+ "type": "string",
+ "x-agent": "run_id",
+ "x-agent-response": true
+ },
+ "pending_prompt_id": {
+ "description": "PendingPromptID is the approval a waiting run is suspended on.",
+ "type": "string"
+ },
+ "scheduled_at": {
+ "description": "ScheduledAt is when the run was due; for a manual run, when it was\nasked for.",
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "session_id": {
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "started_at": {
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "status": {
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "tenant_id": {
+ "type": "integer"
+ },
+ "trigger_kind": {
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "updated_at": {
+ "type": "string"
+ },
+ "usage": {
+ "type": "object"
+ },
+ "user_message_id": {
+ "description": "UserMessageID and AssistantMessageID are the run's turn in SessionID.",
+ "type": "string"
+ }
+ }
+ },
+ "github_com_Tencent_WeKnora_internal_types.AutomationTrigger": {
+ "type": "object",
+ "properties": {
+ "at": {
+ "description": "At is when a once trigger fires.",
+ "type": "string",
+ "x-agent": true
+ },
+ "expr": {
+ "description": "Expr is a cron expression: five fields (minute first) or six (seconds\nfirst), or a descriptor such as @daily.",
+ "type": "string",
+ "x-agent": true
+ },
+ "timezone": {
+ "description": "Timezone is an IANA zone, e.g. Asia/Shanghai; empty means UTC.",
+ "type": "string",
+ "x-agent": true
+ },
+ "type": {
+ "description": "Type is cron or once.",
+ "type": "string",
+ "x-agent": true
+ }
+ }
+ },
"github_com_Tencent_WeKnora_internal_types.COSEngineConfig": {
"type": "object",
"properties": {
@@ -26055,6 +27357,14 @@ const docTemplate = `{
"github_com_Tencent_WeKnora_internal_types.CustomAgentConfig": {
"type": "object",
"properties": {
+ "access_level": {
+ "description": "AccessLevel is the highest access level a run of this agent gets: how\nfar it may change data (MCP tools, Wiki writes) without asking. Empty\nmeans auto_write. The WeKnora assistant uses the workspace's assistant\nceiling instead.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AssistantAccessLevel"
+ }
+ ]
+ },
"agent_mode": {
"description": "===== Basic Settings =====\nAgent mode: \"quick-answer\" for RAG mode, \"smart-reasoning\" for ReAct agent mode",
"type": "string",
@@ -26194,7 +27504,7 @@ const docTemplate = `{
"type": "integer"
},
"max_completion_tokens": {
- "description": "Maximum completion tokens. Quick-answer uses this for the RAG answer.\nSmart-reasoning ReAct rounds send this value as-is (zero becomes\nDefaultMaxCompletionTokens at call time: 4096, or 24576 with a sandbox).",
+ "description": "Maximum completion tokens. Quick-answer uses this for the RAG answer.\nSmart-reasoning ReAct rounds send this value as-is (zero becomes\nDefaultMaxCompletionTokens at call time: 24576 for smart reasoning).",
"type": "integer"
},
"max_iterations": {
@@ -29501,6 +30811,14 @@ const docTemplate = `{
"github_com_Tencent_WeKnora_internal_types.MCPTool": {
"type": "object",
"properties": {
+ "annotations": {
+ "description": "Annotations are the hints the service declares in tools/list. They come\nfrom outside and only seed the tool's risk.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MCPToolAnnotations"
+ }
+ ]
+ },
"description": {
"type": "string",
"x-agent": true,
@@ -29521,6 +30839,17 @@ const docTemplate = `{
}
}
},
+ "github_com_Tencent_WeKnora_internal_types.MCPToolAnnotations": {
+ "type": "object",
+ "properties": {
+ "destructiveHint": {
+ "type": "boolean"
+ },
+ "readOnlyHint": {
+ "type": "boolean"
+ }
+ }
+ },
"github_com_Tencent_WeKnora_internal_types.MCPTransportType": {
"type": "string",
"enum": [
@@ -29952,6 +31281,10 @@ const docTemplate = `{
"description": "Channel indicates the source channel of this message (e.g., \"web\", \"api\", \"im\")",
"type": "string"
},
+ "collaboration_status": {
+ "description": "CollaborationStatus is projected from durable collaboration state at read\ntime, including completed tasks after the transient stream has expired.",
+ "type": "object"
+ },
"content": {
"description": "Message text content",
"type": "string",
@@ -29965,6 +31298,12 @@ const docTemplate = `{
"x-agent": true,
"x-agent-response": true
},
+ "delegated_prompts": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.PendingPromptView"
+ }
+ },
"deleted_at": {
"description": "Soft delete timestamp",
"allOf": [
@@ -30017,12 +31356,14 @@ const docTemplate = `{
"type": "string"
},
"pending_prompt": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.PendingPromptView"
+ },
+ "prompt_history": {
"description": "PendingPrompt is the prompt an awaiting_input message waits on. The\nmessage list fills it in for the prompt's owner; it is never stored.",
- "allOf": [
- {
- "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.PendingPromptView"
- }
- ]
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.PendingPromptView"
+ }
},
"request_id": {
"description": "Request identifier for tracking API requests",
@@ -31320,9 +32661,15 @@ const docTemplate = `{
"github_com_Tencent_WeKnora_internal_types.PendingPromptView": {
"type": "object",
"properties": {
+ "close_reason": {
+ "type": "string"
+ },
"created_at": {
"type": "string"
},
+ "delegated_task": {
+ "type": "string"
+ },
"expires_at": {
"type": "string"
},
@@ -31335,6 +32682,12 @@ const docTemplate = `{
"request": {
"type": "object"
},
+ "response": {
+ "type": "object"
+ },
+ "status": {
+ "type": "string"
+ },
"tool_call_id": {
"type": "string"
}
@@ -35939,6 +37292,105 @@ const docTemplate = `{
}
}
},
+ "internal_handler.CreateAutomationRequest": {
+ "type": "object",
+ "required": [
+ "instruction",
+ "name",
+ "trigger"
+ ],
+ "properties": {
+ "access_level": {
+ "description": "How far runs may change data without asking; default confirm",
+ "enum": [
+ "read_only",
+ "confirm",
+ "auto_write"
+ ],
+ "allOf": [
+ {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AssistantAccessLevel"
+ }
+ ],
+ "x-agent": true
+ },
+ "agent_id": {
+ "description": "Agent that runs it, from agent.list; empty runs the WeKnora assistant",
+ "type": "string",
+ "x-agent": true
+ },
+ "approval_timeout_minutes": {
+ "description": "How long a run waits for an approval before it fails, in minutes; default 1440",
+ "type": "integer",
+ "x-agent": true
+ },
+ "carry_last_result": {
+ "description": "Whether each per_run conversation gets the last successful answer",
+ "type": "boolean",
+ "x-agent": true
+ },
+ "description": {
+ "description": "What it is for",
+ "type": "string",
+ "x-agent": true
+ },
+ "instruction": {
+ "description": "The task, sent as the user message of each run. May name now,\nlast_run_at, last_success_at, run_id or automation_name inside double\ncurly braces to have it filled in",
+ "type": "string",
+ "x-agent": true,
+ "x-agent-max-bytes": "32000"
+ },
+ "limits": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationLimits"
+ },
+ "misfire_policy": {
+ "description": "What happens to runs missed while the service was down; default skip",
+ "type": "string",
+ "enum": [
+ "skip",
+ "run_once"
+ ],
+ "x-agent": true
+ },
+ "name": {
+ "description": "What the automation is called",
+ "type": "string",
+ "x-agent": true
+ },
+ "notify_on_success": {
+ "description": "Whether a successful run notifies the owner; failures always do",
+ "type": "boolean",
+ "x-agent": true
+ },
+ "overlap_policy": {
+ "description": "What happens when a run is due while the previous one is still going; default skip",
+ "type": "string",
+ "enum": [
+ "skip",
+ "queue"
+ ],
+ "x-agent": true
+ },
+ "session_mode": {
+ "description": "per_run (default) starts a new conversation each run; persistent keeps one",
+ "type": "string",
+ "enum": [
+ "per_run",
+ "persistent"
+ ],
+ "x-agent": true
+ },
+ "trigger": {
+ "description": "When it runs",
+ "allOf": [
+ {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationTrigger"
+ }
+ ],
+ "x-agent": true
+ }
+ }
+ },
"internal_handler.CreateKnowledgeFromURLRequest": {
"type": "object",
"required": [
@@ -39645,6 +41097,36 @@ const docTemplate = `{
}
}
},
+ "internal_handler.ValidateTriggerRequest": {
+ "type": "object",
+ "required": [
+ "trigger"
+ ],
+ "properties": {
+ "trigger": {
+ "description": "The trigger to check",
+ "allOf": [
+ {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationTrigger"
+ }
+ ],
+ "x-agent": true
+ }
+ }
+ },
+ "internal_handler.ValidateTriggerResult": {
+ "type": "object",
+ "properties": {
+ "next_runs": {
+ "description": "The next times the trigger fires, in UTC",
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "x-agent": true
+ }
+ }
+ },
"internal_handler.WebSearchProviderTestResponse": {
"type": "object",
"properties": {
diff --git a/docs/swagger.json b/docs/swagger.json
index 5ae09e897..ae103ed0c 100644
--- a/docs/swagger.json
+++ b/docs/swagger.json
@@ -78,6 +78,88 @@
}
}
},
+ "/agent/grants": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "列出当前用户在某个会话(根会话)中通过“本会话允许”记住的授权,包括其委派子任务上批准的授权。",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Agent"
+ ],
+ "summary": "列出会话内的 Agent 授权",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "根会话 ID",
+ "name": "session_id",
+ "in": "query",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "授权列表",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "400": {
+ "description": "请求参数错误",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ }
+ }
+ },
+ "/agent/grants/{id}": {
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "撤销当前用户的一条授权;之后同类调用会重新询问。",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Agent"
+ ],
+ "summary": "撤销 Agent 授权",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "授权 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "撤销结果",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "404": {
+ "description": "授权不存在",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ }
+ }
+ },
"/agent/mcp-oauth-resolutions/{pending_id}": {
"post": {
"security": [
@@ -1825,6 +1907,801 @@
}
}
},
+ "/automation-runs/{id}": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "获取运行记录",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "运行 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "运行记录",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/internal_handler.DataResponse"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationRun"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/automation-runs/{id}/cancel": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "排队或等待审批的运行立即结束;执行中的运行在下一次检查时停止",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "停止运行",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "运行 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "运行记录",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/internal_handler.DataResponse"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationRun"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/automations": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "列出当前用户在本空间创建的自动化(定时任务),最新的在前",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "列出我的自动化",
+ "responses": {
+ "200": {
+ "description": "自动化列表",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/internal_handler.DataResponse"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Automation"
+ }
+ }
+ }
+ }
+ ]
+ }
+ }
+ },
+ "x-agent": {
+ "id": "automation.list",
+ "max_items": 100,
+ "risk": "read"
+ },
+ "x-agent-hint": "Lists the user's automations: scheduled tasks an agent runs on their behalf, with next and last run."
+ },
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "创建一个按计划由 Agent 以当前用户身份运行的任务",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "创建自动化",
+ "parameters": [
+ {
+ "description": "自动化",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/internal_handler.CreateAutomationRequest"
+ }
+ }
+ ],
+ "responses": {
+ "201": {
+ "description": "创建的自动化",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/internal_handler.DataResponse"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Automation"
+ }
+ }
+ }
+ ]
+ }
+ },
+ "400": {
+ "description": "参数不合法",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ },
+ "x-agent": {
+ "always_confirm": true,
+ "id": "automation.create",
+ "label_param": "name",
+ "risk": "write",
+ "role": "viewer"
+ },
+ "x-agent-hint": "Creates an automation the user runs as. Turn the user's wording into a cron expression (five fields, minute first) and an IANA timezone, and check it with automation.validate_trigger first, telling the user the next run times it returns. Runs are unattended: write the instruction as a complete task, since nobody can answer questions during a run. access_level defaults to confirm, where each change waits for the user's approval; only set auto_write when the user asks for it."
+ }
+ },
+ "/automations/validate-trigger": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "校验 cron 或一次性触发器,返回未来 3 次触发时间",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "校验触发器",
+ "parameters": [
+ {
+ "description": "触发器",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/internal_handler.ValidateTriggerRequest"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "未来触发时间",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/internal_handler.DataResponse"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/internal_handler.ValidateTriggerResult"
+ }
+ }
+ }
+ ]
+ }
+ },
+ "400": {
+ "description": "触发器不合法",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ },
+ "x-agent": {
+ "id": "automation.validate_trigger",
+ "risk": "probe"
+ },
+ "x-agent-hint": "Checks a trigger and returns its next three run times in UTC; convert them to the trigger's timezone for the user."
+ }
+ },
+ "/automations/{id}": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "获取自动化",
+ "parameters": [
+ {
+ "type": "string",
+ "x-agent": "automation_id",
+ "description": "自动化 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "自动化",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/internal_handler.DataResponse"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Automation"
+ }
+ }
+ }
+ ]
+ }
+ },
+ "404": {
+ "description": "不存在",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ },
+ "x-agent": {
+ "id": "automation.get",
+ "risk": "read"
+ },
+ "x-agent-hint": "Returns one automation, including its instruction."
+ },
+ "put": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "只修改请求中出现的字段,其余保持不变",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "修改自动化",
+ "parameters": [
+ {
+ "type": "string",
+ "x-agent": "automation_id",
+ "description": "自动化 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ },
+ {
+ "description": "要修改的字段",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationPatch"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "修改后的自动化",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/internal_handler.DataResponse"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Automation"
+ }
+ }
+ }
+ ]
+ }
+ },
+ "400": {
+ "description": "参数不合法",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ },
+ "x-agent": {
+ "always_confirm": true,
+ "id": "automation.update",
+ "label": "name",
+ "risk": "write",
+ "role": "viewer",
+ "target": "automation.get"
+ },
+ "x-agent-hint": "Changes the listed fields of an automation; a field left out is kept. Check a new trigger with automation.validate_trigger first. Use automation.pause and automation.resume to switch it off and on."
+ },
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "停止进行中的运行,删除自动化及其运行记录、会话和长期授权",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "删除自动化",
+ "parameters": [
+ {
+ "type": "string",
+ "x-agent": "automation_id",
+ "description": "自动化 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "删除成功",
+ "schema": {
+ "$ref": "#/definitions/internal_handler.SuccessResponse"
+ }
+ },
+ "404": {
+ "description": "不存在",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ },
+ "x-agent": {
+ "id": "automation.delete",
+ "label": "name",
+ "risk": "destructive",
+ "role": "viewer",
+ "target": "automation.get"
+ },
+ "x-agent-hint": "Deletes an automation with its run history and conversations. Cannot be undone; automation.pause keeps it."
+ }
+ },
+ "/automations/{id}/grant-candidates": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "列出本自动化的运行请求过审批、尚未长期授权的调用;需每次审批的调用不在其中",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "列出可设为长期授权的调用",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "自动化 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "候选调用",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ }
+ },
+ "/automations/{id}/grants": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "列出以后的运行无需确认即可执行的调用,以及失效原因",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "列出自动化的长期授权",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "自动化 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "长期授权",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ },
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "让以后的运行无需确认即可执行某次运行请求过审批的调用;Agent 配置或所有者角色变化后失效",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "添加长期授权",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "自动化 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ },
+ {
+ "description": "{prompt_id}",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "type": "object"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "授权",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ }
+ },
+ "/automations/{id}/pause": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "停止按计划触发;进行中的运行不受影响",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "暂停自动化",
+ "parameters": [
+ {
+ "type": "string",
+ "x-agent": "automation_id",
+ "description": "自动化 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "暂停后的自动化",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/internal_handler.DataResponse"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Automation"
+ }
+ }
+ }
+ ]
+ }
+ }
+ },
+ "x-agent": {
+ "id": "automation.pause",
+ "label": "name",
+ "risk": "write",
+ "role": "viewer",
+ "target": "automation.get"
+ },
+ "x-agent-hint": "Stops an automation from running on schedule until automation.resume."
+ }
+ },
+ "/automations/{id}/resume": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "从现在起重新按计划触发,并清零连续失败计数",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "恢复自动化",
+ "parameters": [
+ {
+ "type": "string",
+ "x-agent": "automation_id",
+ "description": "自动化 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "恢复后的自动化",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/internal_handler.DataResponse"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Automation"
+ }
+ }
+ }
+ ]
+ }
+ }
+ },
+ "x-agent": {
+ "always_confirm": true,
+ "id": "automation.resume",
+ "label": "name",
+ "risk": "write",
+ "role": "viewer",
+ "target": "automation.get"
+ },
+ "x-agent-hint": "Schedules a paused automation again from now; missed runs are not caught up."
+ }
+ },
+ "/automations/{id}/run": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "排队一次手动运行;已有运行在排队或进行中时拒绝",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "立即运行自动化",
+ "parameters": [
+ {
+ "type": "string",
+ "x-agent": "automation_id",
+ "description": "自动化 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "202": {
+ "description": "排队的运行",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/internal_handler.DataResponse"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationRun"
+ }
+ }
+ }
+ ]
+ }
+ },
+ "409": {
+ "description": "已有运行",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ },
+ "x-agent": {
+ "always_confirm": true,
+ "id": "automation.run_now",
+ "label": "name",
+ "risk": "write",
+ "role": "viewer",
+ "target": "automation.get"
+ },
+ "x-agent-hint": "Queues a run now, in the background; follow it with automation.list_runs."
+ }
+ },
+ "/automations/{id}/runs": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "自动化"
+ ],
+ "summary": "列出运行记录",
+ "parameters": [
+ {
+ "type": "string",
+ "x-agent": "automation_id",
+ "description": "自动化 ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ },
+ {
+ "type": "integer",
+ "x-agent": true,
+ "description": "页码,从 1 开始",
+ "name": "page",
+ "in": "query"
+ },
+ {
+ "type": "integer",
+ "x-agent": true,
+ "x-agent-maximum": "20",
+ "description": "每页条数,最多 100",
+ "name": "page_size",
+ "in": "query"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "运行记录",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/internal_handler.PageResponse"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationRun"
+ }
+ }
+ }
+ }
+ ]
+ }
+ }
+ },
+ "x-agent": {
+ "id": "automation.list_runs",
+ "risk": "read"
+ },
+ "x-agent-hint": "Lists an automation's runs, newest first, with status, error and the start of the answer."
+ }
+ },
"/chunker/preview": {
"post": {
"security": [
@@ -2590,7 +3467,7 @@
"id": "data_source.get_sync_log",
"risk": "read"
},
- "x-agent-hint": "Read the current status, counts and errors of a sync_log_id returned by data_source.sync or data_source.list_sync_logs. A started job is not a completed sync."
+ "x-agent-hint": "Read the current status and counts of a sync_log_id returned by data_source.sync or data_source.list_sync_logs. A started job is not a completed sync. Raw upstream errors are omitted; detailed failures remain on the data source settings page."
}
},
"/datasource/types": {
@@ -2703,7 +3580,7 @@
"id": "data_source.get",
"risk": "read"
},
- "x-agent-hint": "Read a configured data source and its sync state; credentials and connector configuration are not returned."
+ "x-agent-hint": "Read a configured data source and its sync state; credentials, connector settings and raw upstream errors are omitted. For detailed failures use the data source settings page."
},
"put": {
"description": "Update an existing data source configuration",
@@ -2847,7 +3724,7 @@
"id": "data_source.list_sync_logs",
"risk": "read"
},
- "x-agent-hint": "Read recent sync results, counts and errors. Use limit and offset for older records."
+ "x-agent-hint": "Read recent sync status and counts. Use limit and offset for older records. Raw upstream errors are omitted; detailed failures remain on the data source settings page."
}
},
"/datasource/{id}/pause": {
@@ -12084,7 +12961,7 @@
"ApiKeyAuth": []
}
],
- "description": "为指定 MCP 服务下的某个工具更新启用状态和/或人工审批要求。至少提供 require_approval 或 enabled 之一;省略的字段保持原值。",
+ "description": "为指定 MCP 服务下的某个工具更新启用状态、人工审批要求和/或风险等级。\n至少提供 require_approval、enabled、risk 之一;省略的字段保持原值。\nrisk 为 read/probe/write/destructive,空字符串表示改回按服务注解推断。",
"consumes": [
"application/json"
],
@@ -12111,7 +12988,7 @@
"required": true
},
{
- "description": "{require_approval?: bool, enabled?: bool}",
+ "description": "{require_approval?: bool, enabled?: bool, risk?: string}",
"name": "request",
"in": "body",
"required": true,
@@ -14232,6 +15109,84 @@
"x-agent-hint": "Copies a workspace-owned model configuration under a required new display_name. Choose model_id from model.list; builtin models cannot be copied. The upstream model name, connection parameters and saved credentials are copied on the backend; never request or resend credentials. The copy is not the default and does not change agent or knowledge base bindings. Active local models are reused without downloading again; copying an unfinished or failed local model starts a background download, so read the returned model_id with model.get until its status is active or download_failed."
}
},
+ "/notifications": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "通知"
+ ],
+ "summary": "列出我的通知",
+ "parameters": [
+ {
+ "type": "integer",
+ "description": "条数,最多 100",
+ "name": "limit",
+ "in": "query"
+ },
+ {
+ "type": "boolean",
+ "description": "只看未读",
+ "name": "unread",
+ "in": "query"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "{items, unread}",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ }
+ },
+ "/notifications/read": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "ids 为空时全部标记已读",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "通知"
+ ],
+ "summary": "标记通知已读",
+ "parameters": [
+ {
+ "description": "{ids}",
+ "name": "request",
+ "in": "body",
+ "schema": {
+ "type": "object"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "结果",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ }
+ },
"/organizations": {
"get": {
"security": [
@@ -24755,6 +25710,13 @@
"description": "Iteration number (0-indexed)",
"type": "integer"
},
+ "progress": {
+ "description": "Progress is user-facing commentary from a non-terminal round. Thought stays intact for model replay.",
+ "type": "string"
+ },
+ "progress_event_id": {
+ "type": "string"
+ },
"reasoning_content": {
"description": "ReasoningContent stores the OpenAI-protocol reasoning_content emitted by the\nmodel in this round. Persisted on AgentStep so cross-turn replay can put it\nback on the assistant message — required by MiMo / DeepSeek V3.2+ thinking\nmode, ignored by providers that don't recognize the field.",
"type": "string"
@@ -25245,6 +26207,346 @@
}
}
},
+ "github_com_Tencent_WeKnora_internal_types.Automation": {
+ "type": "object",
+ "properties": {
+ "access_level": {
+ "description": "AccessLevel is how far runs may change data without asking, capped by\nthe agent's and the workspace's ceilings.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AssistantAccessLevel"
+ }
+ ],
+ "x-agent": true
+ },
+ "agent_id": {
+ "description": "AgentID is the agent that runs it; the WeKnora assistant's ID runs the\nassistant.",
+ "type": "string",
+ "x-agent": true
+ },
+ "approval_timeout_minutes": {
+ "description": "ApprovalTimeoutMinutes is how long a run waits for an approval before\nit fails.",
+ "type": "integer",
+ "x-agent": true
+ },
+ "carry_last_result": {
+ "description": "CarryLastResult adds the last successful answer to each per-run\nconversation.",
+ "type": "boolean",
+ "x-agent": true
+ },
+ "consecutive_failures": {
+ "type": "integer"
+ },
+ "created_at": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string",
+ "x-agent": true
+ },
+ "enabled": {
+ "type": "boolean",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "id": {
+ "type": "string",
+ "x-agent": "automation_id",
+ "x-agent-response": true
+ },
+ "instruction": {
+ "description": "Instruction is the task, sent as the user message of each run after\nits variables are filled in.",
+ "type": "string",
+ "x-agent": true,
+ "x-agent-detail": true
+ },
+ "last_run_at": {
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "last_run_status": {
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "last_success_at": {
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "limits": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationLimits"
+ },
+ "misfire_policy": {
+ "type": "string",
+ "x-agent": true
+ },
+ "name": {
+ "type": "string",
+ "x-agent": true
+ },
+ "next_run_at": {
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "notify_on_success": {
+ "type": "boolean",
+ "x-agent": true
+ },
+ "overlap_policy": {
+ "type": "string",
+ "x-agent": true
+ },
+ "owner_user_id": {
+ "description": "OwnerUserID is the account the automation runs as.",
+ "type": "string"
+ },
+ "paused_reason": {
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "persistent_session_id": {
+ "description": "PersistentSessionID is the conversation of a persistent automation,\ncreated on its first run.",
+ "type": "string"
+ },
+ "session_mode": {
+ "type": "string",
+ "x-agent": true
+ },
+ "tenant_id": {
+ "type": "integer"
+ },
+ "trigger": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationTrigger"
+ }
+ ],
+ "x-agent": true
+ },
+ "updated_at": {
+ "type": "string"
+ }
+ }
+ },
+ "github_com_Tencent_WeKnora_internal_types.AutomationLimits": {
+ "type": "object",
+ "properties": {
+ "max_duration_minutes": {
+ "description": "MaxDurationMinutes caps a run's execution time, not counting time spent\nwaiting for approval. 0 uses the default.",
+ "type": "integer",
+ "x-agent": true
+ }
+ }
+ },
+ "github_com_Tencent_WeKnora_internal_types.AutomationPatch": {
+ "type": "object",
+ "properties": {
+ "access_level": {
+ "description": "How far runs may change data without asking",
+ "enum": [
+ "read_only",
+ "confirm",
+ "auto_write"
+ ],
+ "allOf": [
+ {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AssistantAccessLevel"
+ }
+ ],
+ "x-agent": true
+ },
+ "agent_id": {
+ "description": "Agent that runs it, from agent.list; empty runs the WeKnora assistant",
+ "type": "string",
+ "x-agent": true
+ },
+ "approval_timeout_minutes": {
+ "description": "How long a run waits for an approval before it fails, in minutes",
+ "type": "integer",
+ "x-agent": true
+ },
+ "carry_last_result": {
+ "description": "Whether each per_run conversation gets the last successful answer",
+ "type": "boolean",
+ "x-agent": true
+ },
+ "description": {
+ "description": "What it is for",
+ "type": "string",
+ "x-agent": true
+ },
+ "enabled": {
+ "description": "Whether it is scheduled; on update use pause and resume instead",
+ "type": "boolean"
+ },
+ "instruction": {
+ "description": "The task, sent as the user message of each run. May name now,\nlast_run_at, last_success_at, run_id or automation_name inside double\ncurly braces to have it filled in",
+ "type": "string",
+ "x-agent": true,
+ "x-agent-max-bytes": "32000"
+ },
+ "limits": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationLimits"
+ },
+ "misfire_policy": {
+ "description": "What happens to runs missed while the service was down or paused",
+ "type": "string",
+ "enum": [
+ "skip",
+ "run_once"
+ ],
+ "x-agent": true
+ },
+ "name": {
+ "description": "What the automation is called",
+ "type": "string",
+ "x-agent": true
+ },
+ "notify_on_success": {
+ "description": "Whether a successful run notifies the owner",
+ "type": "boolean",
+ "x-agent": true
+ },
+ "overlap_policy": {
+ "description": "What happens when a run is due while the previous one is still going",
+ "type": "string",
+ "enum": [
+ "skip",
+ "queue"
+ ],
+ "x-agent": true
+ },
+ "session_mode": {
+ "description": "per_run starts a new conversation each run; persistent keeps one",
+ "type": "string",
+ "enum": [
+ "per_run",
+ "persistent"
+ ],
+ "x-agent": true
+ },
+ "trigger": {
+ "description": "When it runs",
+ "allOf": [
+ {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationTrigger"
+ }
+ ],
+ "x-agent": true
+ }
+ }
+ },
+ "github_com_Tencent_WeKnora_internal_types.AutomationRun": {
+ "type": "object",
+ "properties": {
+ "answer": {
+ "description": "Answer is the start of the final answer, for listings.",
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "assistant_message_id": {
+ "type": "string"
+ },
+ "automation_id": {
+ "type": "string"
+ },
+ "cancel_requested": {
+ "description": "CancelRequested stops the run at its next check.",
+ "type": "boolean"
+ },
+ "created_at": {
+ "type": "string"
+ },
+ "error": {
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "finished_at": {
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "id": {
+ "type": "string",
+ "x-agent": "run_id",
+ "x-agent-response": true
+ },
+ "pending_prompt_id": {
+ "description": "PendingPromptID is the approval a waiting run is suspended on.",
+ "type": "string"
+ },
+ "scheduled_at": {
+ "description": "ScheduledAt is when the run was due; for a manual run, when it was\nasked for.",
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "session_id": {
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "started_at": {
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "status": {
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "tenant_id": {
+ "type": "integer"
+ },
+ "trigger_kind": {
+ "type": "string",
+ "x-agent": true,
+ "x-agent-response": true
+ },
+ "updated_at": {
+ "type": "string"
+ },
+ "usage": {
+ "type": "object"
+ },
+ "user_message_id": {
+ "description": "UserMessageID and AssistantMessageID are the run's turn in SessionID.",
+ "type": "string"
+ }
+ }
+ },
+ "github_com_Tencent_WeKnora_internal_types.AutomationTrigger": {
+ "type": "object",
+ "properties": {
+ "at": {
+ "description": "At is when a once trigger fires.",
+ "type": "string",
+ "x-agent": true
+ },
+ "expr": {
+ "description": "Expr is a cron expression: five fields (minute first) or six (seconds\nfirst), or a descriptor such as @daily.",
+ "type": "string",
+ "x-agent": true
+ },
+ "timezone": {
+ "description": "Timezone is an IANA zone, e.g. Asia/Shanghai; empty means UTC.",
+ "type": "string",
+ "x-agent": true
+ },
+ "type": {
+ "description": "Type is cron or once.",
+ "type": "string",
+ "x-agent": true
+ }
+ }
+ },
"github_com_Tencent_WeKnora_internal_types.COSEngineConfig": {
"type": "object",
"properties": {
@@ -26048,6 +27350,14 @@
"github_com_Tencent_WeKnora_internal_types.CustomAgentConfig": {
"type": "object",
"properties": {
+ "access_level": {
+ "description": "AccessLevel is the highest access level a run of this agent gets: how\nfar it may change data (MCP tools, Wiki writes) without asking. Empty\nmeans auto_write. The WeKnora assistant uses the workspace's assistant\nceiling instead.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AssistantAccessLevel"
+ }
+ ]
+ },
"agent_mode": {
"description": "===== Basic Settings =====\nAgent mode: \"quick-answer\" for RAG mode, \"smart-reasoning\" for ReAct agent mode",
"type": "string",
@@ -26187,7 +27497,7 @@
"type": "integer"
},
"max_completion_tokens": {
- "description": "Maximum completion tokens. Quick-answer uses this for the RAG answer.\nSmart-reasoning ReAct rounds send this value as-is (zero becomes\nDefaultMaxCompletionTokens at call time: 4096, or 24576 with a sandbox).",
+ "description": "Maximum completion tokens. Quick-answer uses this for the RAG answer.\nSmart-reasoning ReAct rounds send this value as-is (zero becomes\nDefaultMaxCompletionTokens at call time: 24576 for smart reasoning).",
"type": "integer"
},
"max_iterations": {
@@ -29494,6 +30804,14 @@
"github_com_Tencent_WeKnora_internal_types.MCPTool": {
"type": "object",
"properties": {
+ "annotations": {
+ "description": "Annotations are the hints the service declares in tools/list. They come\nfrom outside and only seed the tool's risk.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MCPToolAnnotations"
+ }
+ ]
+ },
"description": {
"type": "string",
"x-agent": true,
@@ -29514,6 +30832,17 @@
}
}
},
+ "github_com_Tencent_WeKnora_internal_types.MCPToolAnnotations": {
+ "type": "object",
+ "properties": {
+ "destructiveHint": {
+ "type": "boolean"
+ },
+ "readOnlyHint": {
+ "type": "boolean"
+ }
+ }
+ },
"github_com_Tencent_WeKnora_internal_types.MCPTransportType": {
"type": "string",
"enum": [
@@ -29945,6 +31274,10 @@
"description": "Channel indicates the source channel of this message (e.g., \"web\", \"api\", \"im\")",
"type": "string"
},
+ "collaboration_status": {
+ "description": "CollaborationStatus is projected from durable collaboration state at read\ntime, including completed tasks after the transient stream has expired.",
+ "type": "object"
+ },
"content": {
"description": "Message text content",
"type": "string",
@@ -29958,6 +31291,12 @@
"x-agent": true,
"x-agent-response": true
},
+ "delegated_prompts": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.PendingPromptView"
+ }
+ },
"deleted_at": {
"description": "Soft delete timestamp",
"allOf": [
@@ -30010,12 +31349,14 @@
"type": "string"
},
"pending_prompt": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.PendingPromptView"
+ },
+ "prompt_history": {
"description": "PendingPrompt is the prompt an awaiting_input message waits on. The\nmessage list fills it in for the prompt's owner; it is never stored.",
- "allOf": [
- {
- "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.PendingPromptView"
- }
- ]
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.PendingPromptView"
+ }
},
"request_id": {
"description": "Request identifier for tracking API requests",
@@ -31313,9 +32654,15 @@
"github_com_Tencent_WeKnora_internal_types.PendingPromptView": {
"type": "object",
"properties": {
+ "close_reason": {
+ "type": "string"
+ },
"created_at": {
"type": "string"
},
+ "delegated_task": {
+ "type": "string"
+ },
"expires_at": {
"type": "string"
},
@@ -31328,6 +32675,12 @@
"request": {
"type": "object"
},
+ "response": {
+ "type": "object"
+ },
+ "status": {
+ "type": "string"
+ },
"tool_call_id": {
"type": "string"
}
@@ -35932,6 +37285,105 @@
}
}
},
+ "internal_handler.CreateAutomationRequest": {
+ "type": "object",
+ "required": [
+ "instruction",
+ "name",
+ "trigger"
+ ],
+ "properties": {
+ "access_level": {
+ "description": "How far runs may change data without asking; default confirm",
+ "enum": [
+ "read_only",
+ "confirm",
+ "auto_write"
+ ],
+ "allOf": [
+ {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AssistantAccessLevel"
+ }
+ ],
+ "x-agent": true
+ },
+ "agent_id": {
+ "description": "Agent that runs it, from agent.list; empty runs the WeKnora assistant",
+ "type": "string",
+ "x-agent": true
+ },
+ "approval_timeout_minutes": {
+ "description": "How long a run waits for an approval before it fails, in minutes; default 1440",
+ "type": "integer",
+ "x-agent": true
+ },
+ "carry_last_result": {
+ "description": "Whether each per_run conversation gets the last successful answer",
+ "type": "boolean",
+ "x-agent": true
+ },
+ "description": {
+ "description": "What it is for",
+ "type": "string",
+ "x-agent": true
+ },
+ "instruction": {
+ "description": "The task, sent as the user message of each run. May name now,\nlast_run_at, last_success_at, run_id or automation_name inside double\ncurly braces to have it filled in",
+ "type": "string",
+ "x-agent": true,
+ "x-agent-max-bytes": "32000"
+ },
+ "limits": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationLimits"
+ },
+ "misfire_policy": {
+ "description": "What happens to runs missed while the service was down; default skip",
+ "type": "string",
+ "enum": [
+ "skip",
+ "run_once"
+ ],
+ "x-agent": true
+ },
+ "name": {
+ "description": "What the automation is called",
+ "type": "string",
+ "x-agent": true
+ },
+ "notify_on_success": {
+ "description": "Whether a successful run notifies the owner; failures always do",
+ "type": "boolean",
+ "x-agent": true
+ },
+ "overlap_policy": {
+ "description": "What happens when a run is due while the previous one is still going; default skip",
+ "type": "string",
+ "enum": [
+ "skip",
+ "queue"
+ ],
+ "x-agent": true
+ },
+ "session_mode": {
+ "description": "per_run (default) starts a new conversation each run; persistent keeps one",
+ "type": "string",
+ "enum": [
+ "per_run",
+ "persistent"
+ ],
+ "x-agent": true
+ },
+ "trigger": {
+ "description": "When it runs",
+ "allOf": [
+ {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationTrigger"
+ }
+ ],
+ "x-agent": true
+ }
+ }
+ },
"internal_handler.CreateKnowledgeFromURLRequest": {
"type": "object",
"required": [
@@ -39638,6 +41090,36 @@
}
}
},
+ "internal_handler.ValidateTriggerRequest": {
+ "type": "object",
+ "required": [
+ "trigger"
+ ],
+ "properties": {
+ "trigger": {
+ "description": "The trigger to check",
+ "allOf": [
+ {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationTrigger"
+ }
+ ],
+ "x-agent": true
+ }
+ }
+ },
+ "internal_handler.ValidateTriggerResult": {
+ "type": "object",
+ "properties": {
+ "next_runs": {
+ "description": "The next times the trigger fires, in UTC",
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "x-agent": true
+ }
+ }
+ },
"internal_handler.WebSearchProviderTestResponse": {
"type": "object",
"properties": {
diff --git a/docs/swagger.yaml b/docs/swagger.yaml
index ffa670703..e2c2b0a41 100644
--- a/docs/swagger.yaml
+++ b/docs/swagger.yaml
@@ -1344,6 +1344,12 @@ definitions:
iteration:
description: Iteration number (0-indexed)
type: integer
+ progress:
+ description: Progress is user-facing commentary from a non-terminal round.
+ Thought stays intact for model replay.
+ type: string
+ progress_event_id:
+ type: string
reasoning_content:
description: |-
ReasoningContent stores the OpenAI-protocol reasoning_content emitted by the
@@ -1744,6 +1750,280 @@ definitions:
type: boolean
x-agent: auto_tag_skip_if_tagged
type: object
+ github_com_Tencent_WeKnora_internal_types.Automation:
+ properties:
+ access_level:
+ allOf:
+ - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AssistantAccessLevel'
+ description: |-
+ AccessLevel is how far runs may change data without asking, capped by
+ the agent's and the workspace's ceilings.
+ x-agent: true
+ agent_id:
+ description: |-
+ AgentID is the agent that runs it; the WeKnora assistant's ID runs the
+ assistant.
+ type: string
+ x-agent: true
+ approval_timeout_minutes:
+ description: |-
+ ApprovalTimeoutMinutes is how long a run waits for an approval before
+ it fails.
+ type: integer
+ x-agent: true
+ carry_last_result:
+ description: |-
+ CarryLastResult adds the last successful answer to each per-run
+ conversation.
+ type: boolean
+ x-agent: true
+ consecutive_failures:
+ type: integer
+ created_at:
+ type: string
+ description:
+ type: string
+ x-agent: true
+ enabled:
+ type: boolean
+ x-agent: true
+ x-agent-response: true
+ id:
+ type: string
+ x-agent: automation_id
+ x-agent-response: true
+ instruction:
+ description: |-
+ Instruction is the task, sent as the user message of each run after
+ its variables are filled in.
+ type: string
+ x-agent: true
+ x-agent-detail: true
+ last_run_at:
+ type: string
+ x-agent: true
+ x-agent-response: true
+ last_run_status:
+ type: string
+ x-agent: true
+ x-agent-response: true
+ last_success_at:
+ type: string
+ x-agent: true
+ x-agent-response: true
+ limits:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationLimits'
+ misfire_policy:
+ type: string
+ x-agent: true
+ name:
+ type: string
+ x-agent: true
+ next_run_at:
+ type: string
+ x-agent: true
+ x-agent-response: true
+ notify_on_success:
+ type: boolean
+ x-agent: true
+ overlap_policy:
+ type: string
+ x-agent: true
+ owner_user_id:
+ description: OwnerUserID is the account the automation runs as.
+ type: string
+ paused_reason:
+ type: string
+ x-agent: true
+ x-agent-response: true
+ persistent_session_id:
+ description: |-
+ PersistentSessionID is the conversation of a persistent automation,
+ created on its first run.
+ type: string
+ session_mode:
+ type: string
+ x-agent: true
+ tenant_id:
+ type: integer
+ trigger:
+ allOf:
+ - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationTrigger'
+ x-agent: true
+ updated_at:
+ type: string
+ type: object
+ github_com_Tencent_WeKnora_internal_types.AutomationLimits:
+ properties:
+ max_duration_minutes:
+ description: |-
+ MaxDurationMinutes caps a run's execution time, not counting time spent
+ waiting for approval. 0 uses the default.
+ type: integer
+ x-agent: true
+ type: object
+ github_com_Tencent_WeKnora_internal_types.AutomationPatch:
+ properties:
+ access_level:
+ allOf:
+ - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AssistantAccessLevel'
+ description: How far runs may change data without asking
+ enum:
+ - read_only
+ - confirm
+ - auto_write
+ x-agent: true
+ agent_id:
+ description: Agent that runs it, from agent.list; empty runs the WeKnora assistant
+ type: string
+ x-agent: true
+ approval_timeout_minutes:
+ description: How long a run waits for an approval before it fails, in minutes
+ type: integer
+ x-agent: true
+ carry_last_result:
+ description: Whether each per_run conversation gets the last successful answer
+ type: boolean
+ x-agent: true
+ description:
+ description: What it is for
+ type: string
+ x-agent: true
+ enabled:
+ description: Whether it is scheduled; on update use pause and resume instead
+ type: boolean
+ instruction:
+ description: |-
+ The task, sent as the user message of each run. May name now,
+ last_run_at, last_success_at, run_id or automation_name inside double
+ curly braces to have it filled in
+ type: string
+ x-agent: true
+ x-agent-max-bytes: "32000"
+ limits:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationLimits'
+ misfire_policy:
+ description: What happens to runs missed while the service was down or paused
+ enum:
+ - skip
+ - run_once
+ type: string
+ x-agent: true
+ name:
+ description: What the automation is called
+ type: string
+ x-agent: true
+ notify_on_success:
+ description: Whether a successful run notifies the owner
+ type: boolean
+ x-agent: true
+ overlap_policy:
+ description: What happens when a run is due while the previous one is still
+ going
+ enum:
+ - skip
+ - queue
+ type: string
+ x-agent: true
+ session_mode:
+ description: per_run starts a new conversation each run; persistent keeps
+ one
+ enum:
+ - per_run
+ - persistent
+ type: string
+ x-agent: true
+ trigger:
+ allOf:
+ - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationTrigger'
+ description: When it runs
+ x-agent: true
+ type: object
+ github_com_Tencent_WeKnora_internal_types.AutomationRun:
+ properties:
+ answer:
+ description: Answer is the start of the final answer, for listings.
+ type: string
+ x-agent: true
+ x-agent-response: true
+ assistant_message_id:
+ type: string
+ automation_id:
+ type: string
+ cancel_requested:
+ description: CancelRequested stops the run at its next check.
+ type: boolean
+ created_at:
+ type: string
+ error:
+ type: string
+ x-agent: true
+ x-agent-response: true
+ finished_at:
+ type: string
+ x-agent: true
+ x-agent-response: true
+ id:
+ type: string
+ x-agent: run_id
+ x-agent-response: true
+ pending_prompt_id:
+ description: PendingPromptID is the approval a waiting run is suspended on.
+ type: string
+ scheduled_at:
+ description: |-
+ ScheduledAt is when the run was due; for a manual run, when it was
+ asked for.
+ type: string
+ x-agent: true
+ x-agent-response: true
+ session_id:
+ type: string
+ x-agent: true
+ x-agent-response: true
+ started_at:
+ type: string
+ x-agent: true
+ x-agent-response: true
+ status:
+ type: string
+ x-agent: true
+ x-agent-response: true
+ tenant_id:
+ type: integer
+ trigger_kind:
+ type: string
+ x-agent: true
+ x-agent-response: true
+ updated_at:
+ type: string
+ usage:
+ type: object
+ user_message_id:
+ description: UserMessageID and AssistantMessageID are the run's turn in SessionID.
+ type: string
+ type: object
+ github_com_Tencent_WeKnora_internal_types.AutomationTrigger:
+ properties:
+ at:
+ description: At is when a once trigger fires.
+ type: string
+ x-agent: true
+ expr:
+ description: |-
+ Expr is a cron expression: five fields (minute first) or six (seconds
+ first), or a descriptor such as @daily.
+ type: string
+ x-agent: true
+ timezone:
+ description: Timezone is an IANA zone, e.g. Asia/Shanghai; empty means UTC.
+ type: string
+ x-agent: true
+ type:
+ description: Type is cron or once.
+ type: string
+ x-agent: true
+ type: object
github_com_Tencent_WeKnora_internal_types.COSEngineConfig:
properties:
app_id:
@@ -2392,6 +2672,14 @@ definitions:
type: object
github_com_Tencent_WeKnora_internal_types.CustomAgentConfig:
properties:
+ access_level:
+ allOf:
+ - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AssistantAccessLevel'
+ description: |-
+ 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.
agent_mode:
description: |-
===== Basic Settings =====
@@ -2554,7 +2842,7 @@ definitions:
description: |-
Maximum completion tokens. Quick-answer uses this for the RAG answer.
Smart-reasoning ReAct rounds send this value as-is (zero becomes
- DefaultMaxCompletionTokens at call time: 4096, or 24576 with a sandbox).
+ DefaultMaxCompletionTokens at call time: 24576 for smart reasoning).
type: integer
max_iterations:
description: |-
@@ -5156,6 +5444,12 @@ definitions:
type: object
github_com_Tencent_WeKnora_internal_types.MCPTool:
properties:
+ annotations:
+ allOf:
+ - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.MCPToolAnnotations'
+ description: |-
+ Annotations are the hints the service declares in tools/list. They come
+ from outside and only seed the tool's risk.
description:
type: string
x-agent: true
@@ -5172,6 +5466,13 @@ definitions:
type: boolean
x-agent: true
type: object
+ github_com_Tencent_WeKnora_internal_types.MCPToolAnnotations:
+ properties:
+ destructiveHint:
+ type: boolean
+ readOnlyHint:
+ type: boolean
+ type: object
github_com_Tencent_WeKnora_internal_types.MCPTransportType:
enum:
- sse
@@ -5551,6 +5852,11 @@ definitions:
description: Channel indicates the source channel of this message (e.g., "web",
"api", "im")
type: string
+ collaboration_status:
+ description: |-
+ CollaborationStatus is projected from durable collaboration state at read
+ time, including completed tasks after the transient stream has expired.
+ type: object
content:
description: Message text content
type: string
@@ -5562,6 +5868,10 @@ definitions:
type: string
x-agent: true
x-agent-response: true
+ delegated_prompts:
+ items:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.PendingPromptView'
+ type: array
deleted_at:
allOf:
- $ref: '#/definitions/gorm.DeletedAt'
@@ -5606,11 +5916,14 @@ definitions:
turn. It is useful for reproducibility and suggestion generation.
type: string
pending_prompt:
- allOf:
- - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.PendingPromptView'
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.PendingPromptView'
+ prompt_history:
description: |-
PendingPrompt is the prompt an awaiting_input message waits on. The
message list fills it in for the prompt's owner; it is never stored.
+ items:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.PendingPromptView'
+ type: array
request_id:
description: Request identifier for tracking API requests
type: string
@@ -6597,8 +6910,12 @@ definitions:
type: object
github_com_Tencent_WeKnora_internal_types.PendingPromptView:
properties:
+ close_reason:
+ type: string
created_at:
type: string
+ delegated_task:
+ type: string
expires_at:
type: string
id:
@@ -6607,6 +6924,10 @@ definitions:
type: string
request:
type: object
+ response:
+ type: object
+ status:
+ type: string
tool_call_id:
type: string
type: object
@@ -10284,6 +10605,87 @@ definitions:
required:
- name
type: object
+ internal_handler.CreateAutomationRequest:
+ properties:
+ access_level:
+ allOf:
+ - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AssistantAccessLevel'
+ description: How far runs may change data without asking; default confirm
+ enum:
+ - read_only
+ - confirm
+ - auto_write
+ x-agent: true
+ agent_id:
+ description: Agent that runs it, from agent.list; empty runs the WeKnora assistant
+ type: string
+ x-agent: true
+ approval_timeout_minutes:
+ description: How long a run waits for an approval before it fails, in minutes;
+ default 1440
+ type: integer
+ x-agent: true
+ carry_last_result:
+ description: Whether each per_run conversation gets the last successful answer
+ type: boolean
+ x-agent: true
+ description:
+ description: What it is for
+ type: string
+ x-agent: true
+ instruction:
+ description: |-
+ The task, sent as the user message of each run. May name now,
+ last_run_at, last_success_at, run_id or automation_name inside double
+ curly braces to have it filled in
+ type: string
+ x-agent: true
+ x-agent-max-bytes: "32000"
+ limits:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationLimits'
+ misfire_policy:
+ description: What happens to runs missed while the service was down; default
+ skip
+ enum:
+ - skip
+ - run_once
+ type: string
+ x-agent: true
+ name:
+ description: What the automation is called
+ type: string
+ x-agent: true
+ notify_on_success:
+ description: Whether a successful run notifies the owner; failures always
+ do
+ type: boolean
+ x-agent: true
+ overlap_policy:
+ description: What happens when a run is due while the previous one is still
+ going; default skip
+ enum:
+ - skip
+ - queue
+ type: string
+ x-agent: true
+ session_mode:
+ description: per_run (default) starts a new conversation each run; persistent
+ keeps one
+ enum:
+ - per_run
+ - persistent
+ type: string
+ x-agent: true
+ trigger:
+ allOf:
+ - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationTrigger'
+ description: When it runs
+ x-agent: true
+ required:
+ - instruction
+ - name
+ - trigger
+ type: object
internal_handler.CreateKnowledgeFromURLRequest:
properties:
channel:
@@ -12950,6 +13352,25 @@ definitions:
user:
$ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.UserInfo'
type: object
+ internal_handler.ValidateTriggerRequest:
+ properties:
+ trigger:
+ allOf:
+ - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationTrigger'
+ description: The trigger to check
+ x-agent: true
+ required:
+ - trigger
+ type: object
+ internal_handler.ValidateTriggerResult:
+ properties:
+ next_runs:
+ description: The next times the trigger fires, in UTC
+ items:
+ type: string
+ type: array
+ x-agent: true
+ type: object
internal_handler.WebSearchProviderTestResponse:
properties:
error:
@@ -13941,9 +14362,61 @@ paths:
summary: Agent问答
tags:
- 问答
- /agent/mcp-oauth-resolutions/{pending_id}:
- post:
- consumes:
+ /agent/grants:
+ get:
+ description: 列出当前用户在某个会话(根会话)中通过“本会话允许”记住的授权,包括其委派子任务上批准的授权。
+ parameters:
+ - description: 根会话 ID
+ in: query
+ name: session_id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 授权列表
+ schema:
+ additionalProperties: true
+ type: object
+ "400":
+ description: 请求参数错误
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ security:
+ - Bearer: []
+ summary: 列出会话内的 Agent 授权
+ tags:
+ - Agent
+ /agent/grants/{id}:
+ delete:
+ description: 撤销当前用户的一条授权;之后同类调用会重新询问。
+ parameters:
+ - description: 授权 ID
+ in: path
+ name: id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 撤销结果
+ schema:
+ additionalProperties: true
+ type: object
+ "404":
+ description: 授权不存在
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ security:
+ - Bearer: []
+ summary: 撤销 Agent 授权
+ tags:
+ - Agent
+ /agent/mcp-oauth-resolutions/{pending_id}:
+ post:
+ consumes:
- application/json
description: 用户在对话中完成 OAuth 授权后调用,校验令牌存在后恢复被暂停的 Agent 工具调用
parameters:
@@ -15072,6 +15545,509 @@ paths:
summary: 验证令牌
tags:
- 认证
+ /automation-runs/{id}:
+ get:
+ parameters:
+ - description: 运行 ID
+ in: path
+ name: id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 运行记录
+ schema:
+ allOf:
+ - $ref: '#/definitions/internal_handler.DataResponse'
+ - properties:
+ data:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationRun'
+ type: object
+ security:
+ - Bearer: []
+ summary: 获取运行记录
+ tags:
+ - 自动化
+ /automation-runs/{id}/cancel:
+ post:
+ description: 排队或等待审批的运行立即结束;执行中的运行在下一次检查时停止
+ parameters:
+ - description: 运行 ID
+ in: path
+ name: id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 运行记录
+ schema:
+ allOf:
+ - $ref: '#/definitions/internal_handler.DataResponse'
+ - properties:
+ data:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationRun'
+ type: object
+ security:
+ - Bearer: []
+ summary: 停止运行
+ tags:
+ - 自动化
+ /automations:
+ get:
+ description: 列出当前用户在本空间创建的自动化(定时任务),最新的在前
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 自动化列表
+ schema:
+ allOf:
+ - $ref: '#/definitions/internal_handler.DataResponse'
+ - properties:
+ data:
+ items:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.Automation'
+ type: array
+ type: object
+ security:
+ - Bearer: []
+ summary: 列出我的自动化
+ tags:
+ - 自动化
+ x-agent:
+ id: automation.list
+ max_items: 100
+ risk: read
+ x-agent-hint: 'Lists the user''s automations: scheduled tasks an agent runs
+ on their behalf, with next and last run.'
+ post:
+ consumes:
+ - application/json
+ description: 创建一个按计划由 Agent 以当前用户身份运行的任务
+ parameters:
+ - description: 自动化
+ in: body
+ name: request
+ required: true
+ schema:
+ $ref: '#/definitions/internal_handler.CreateAutomationRequest'
+ produces:
+ - application/json
+ responses:
+ "201":
+ description: 创建的自动化
+ schema:
+ allOf:
+ - $ref: '#/definitions/internal_handler.DataResponse'
+ - properties:
+ data:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.Automation'
+ type: object
+ "400":
+ description: 参数不合法
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ security:
+ - Bearer: []
+ summary: 创建自动化
+ tags:
+ - 自动化
+ x-agent:
+ always_confirm: true
+ id: automation.create
+ label_param: name
+ risk: write
+ role: viewer
+ x-agent-hint: 'Creates an automation the user runs as. Turn the user''s wording
+ into a cron expression (five fields, minute first) and an IANA timezone, and
+ check it with automation.validate_trigger first, telling the user the next
+ run times it returns. Runs are unattended: write the instruction as a complete
+ task, since nobody can answer questions during a run. access_level defaults
+ to confirm, where each change waits for the user''s approval; only set auto_write
+ when the user asks for it.'
+ /automations/{id}:
+ delete:
+ description: 停止进行中的运行,删除自动化及其运行记录、会话和长期授权
+ parameters:
+ - description: 自动化 ID
+ in: path
+ name: id
+ required: true
+ type: string
+ x-agent: automation_id
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 删除成功
+ schema:
+ $ref: '#/definitions/internal_handler.SuccessResponse'
+ "404":
+ description: 不存在
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ security:
+ - Bearer: []
+ summary: 删除自动化
+ tags:
+ - 自动化
+ x-agent:
+ id: automation.delete
+ label: name
+ risk: destructive
+ role: viewer
+ target: automation.get
+ x-agent-hint: Deletes an automation with its run history and conversations.
+ Cannot be undone; automation.pause keeps it.
+ get:
+ parameters:
+ - description: 自动化 ID
+ in: path
+ name: id
+ required: true
+ type: string
+ x-agent: automation_id
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 自动化
+ schema:
+ allOf:
+ - $ref: '#/definitions/internal_handler.DataResponse'
+ - properties:
+ data:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.Automation'
+ type: object
+ "404":
+ description: 不存在
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ security:
+ - Bearer: []
+ summary: 获取自动化
+ tags:
+ - 自动化
+ x-agent:
+ id: automation.get
+ risk: read
+ x-agent-hint: Returns one automation, including its instruction.
+ put:
+ consumes:
+ - application/json
+ description: 只修改请求中出现的字段,其余保持不变
+ parameters:
+ - description: 自动化 ID
+ in: path
+ name: id
+ required: true
+ type: string
+ x-agent: automation_id
+ - description: 要修改的字段
+ in: body
+ name: request
+ required: true
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationPatch'
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 修改后的自动化
+ schema:
+ allOf:
+ - $ref: '#/definitions/internal_handler.DataResponse'
+ - properties:
+ data:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.Automation'
+ type: object
+ "400":
+ description: 参数不合法
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ security:
+ - Bearer: []
+ summary: 修改自动化
+ tags:
+ - 自动化
+ x-agent:
+ always_confirm: true
+ id: automation.update
+ label: name
+ risk: write
+ role: viewer
+ target: automation.get
+ x-agent-hint: Changes the listed fields of an automation; a field left out is
+ kept. Check a new trigger with automation.validate_trigger first. Use automation.pause
+ and automation.resume to switch it off and on.
+ /automations/{id}/grant-candidates:
+ get:
+ description: 列出本自动化的运行请求过审批、尚未长期授权的调用;需每次审批的调用不在其中
+ parameters:
+ - description: 自动化 ID
+ in: path
+ name: id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 候选调用
+ schema:
+ additionalProperties: true
+ type: object
+ security:
+ - Bearer: []
+ summary: 列出可设为长期授权的调用
+ tags:
+ - 自动化
+ /automations/{id}/grants:
+ get:
+ description: 列出以后的运行无需确认即可执行的调用,以及失效原因
+ parameters:
+ - description: 自动化 ID
+ in: path
+ name: id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 长期授权
+ schema:
+ additionalProperties: true
+ type: object
+ security:
+ - Bearer: []
+ summary: 列出自动化的长期授权
+ tags:
+ - 自动化
+ post:
+ consumes:
+ - application/json
+ description: 让以后的运行无需确认即可执行某次运行请求过审批的调用;Agent 配置或所有者角色变化后失效
+ parameters:
+ - description: 自动化 ID
+ in: path
+ name: id
+ required: true
+ type: string
+ - description: '{prompt_id}'
+ in: body
+ name: request
+ required: true
+ schema:
+ type: object
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 授权
+ schema:
+ additionalProperties: true
+ type: object
+ security:
+ - Bearer: []
+ summary: 添加长期授权
+ tags:
+ - 自动化
+ /automations/{id}/pause:
+ post:
+ description: 停止按计划触发;进行中的运行不受影响
+ parameters:
+ - description: 自动化 ID
+ in: path
+ name: id
+ required: true
+ type: string
+ x-agent: automation_id
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 暂停后的自动化
+ schema:
+ allOf:
+ - $ref: '#/definitions/internal_handler.DataResponse'
+ - properties:
+ data:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.Automation'
+ type: object
+ security:
+ - Bearer: []
+ summary: 暂停自动化
+ tags:
+ - 自动化
+ x-agent:
+ id: automation.pause
+ label: name
+ risk: write
+ role: viewer
+ target: automation.get
+ x-agent-hint: Stops an automation from running on schedule until automation.resume.
+ /automations/{id}/resume:
+ post:
+ description: 从现在起重新按计划触发,并清零连续失败计数
+ parameters:
+ - description: 自动化 ID
+ in: path
+ name: id
+ required: true
+ type: string
+ x-agent: automation_id
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 恢复后的自动化
+ schema:
+ allOf:
+ - $ref: '#/definitions/internal_handler.DataResponse'
+ - properties:
+ data:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.Automation'
+ type: object
+ security:
+ - Bearer: []
+ summary: 恢复自动化
+ tags:
+ - 自动化
+ x-agent:
+ always_confirm: true
+ id: automation.resume
+ label: name
+ risk: write
+ role: viewer
+ target: automation.get
+ x-agent-hint: Schedules a paused automation again from now; missed runs are
+ not caught up.
+ /automations/{id}/run:
+ post:
+ description: 排队一次手动运行;已有运行在排队或进行中时拒绝
+ parameters:
+ - description: 自动化 ID
+ in: path
+ name: id
+ required: true
+ type: string
+ x-agent: automation_id
+ produces:
+ - application/json
+ responses:
+ "202":
+ description: 排队的运行
+ schema:
+ allOf:
+ - $ref: '#/definitions/internal_handler.DataResponse'
+ - properties:
+ data:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationRun'
+ type: object
+ "409":
+ description: 已有运行
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ security:
+ - Bearer: []
+ summary: 立即运行自动化
+ tags:
+ - 自动化
+ x-agent:
+ always_confirm: true
+ id: automation.run_now
+ label: name
+ risk: write
+ role: viewer
+ target: automation.get
+ x-agent-hint: Queues a run now, in the background; follow it with automation.list_runs.
+ /automations/{id}/runs:
+ get:
+ parameters:
+ - description: 自动化 ID
+ in: path
+ name: id
+ required: true
+ type: string
+ x-agent: automation_id
+ - description: 页码,从 1 开始
+ in: query
+ name: page
+ type: integer
+ x-agent: true
+ - description: 每页条数,最多 100
+ in: query
+ name: page_size
+ type: integer
+ x-agent: true
+ x-agent-maximum: "20"
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 运行记录
+ schema:
+ allOf:
+ - $ref: '#/definitions/internal_handler.PageResponse'
+ - properties:
+ data:
+ items:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AutomationRun'
+ type: array
+ type: object
+ security:
+ - Bearer: []
+ summary: 列出运行记录
+ tags:
+ - 自动化
+ x-agent:
+ id: automation.list_runs
+ risk: read
+ x-agent-hint: Lists an automation's runs, newest first, with status, error and
+ the start of the answer.
+ /automations/validate-trigger:
+ post:
+ consumes:
+ - application/json
+ description: 校验 cron 或一次性触发器,返回未来 3 次触发时间
+ parameters:
+ - description: 触发器
+ in: body
+ name: request
+ required: true
+ schema:
+ $ref: '#/definitions/internal_handler.ValidateTriggerRequest'
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 未来触发时间
+ schema:
+ allOf:
+ - $ref: '#/definitions/internal_handler.DataResponse'
+ - properties:
+ data:
+ $ref: '#/definitions/internal_handler.ValidateTriggerResult'
+ type: object
+ "400":
+ description: 触发器不合法
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ security:
+ - Bearer: []
+ summary: 校验触发器
+ tags:
+ - 自动化
+ x-agent:
+ id: automation.validate_trigger
+ risk: probe
+ x-agent-hint: Checks a trigger and returns its next three run times in UTC;
+ convert them to the trigger's timezone for the user.
/chunker/preview:
post:
consumes:
@@ -15599,8 +16575,9 @@ paths:
x-agent:
id: data_source.get
risk: read
- x-agent-hint: Read a configured data source and its sync state; credentials
- and connector configuration are not returned.
+ x-agent-hint: Read a configured data source and its sync state; credentials,
+ connector settings and raw upstream errors are omitted. For detailed failures
+ use the data source settings page.
put:
consumes:
- application/json
@@ -15679,8 +16656,9 @@ paths:
x-agent:
id: data_source.list_sync_logs
risk: read
- x-agent-hint: Read recent sync results, counts and errors. Use limit and offset
- for older records.
+ x-agent-hint: Read recent sync status and counts. Use limit and offset for older
+ records. Raw upstream errors are omitted; detailed failures remain on the
+ data source settings page.
/datasource/{id}/pause:
post:
description: Pause a data source's scheduled syncs
@@ -15966,9 +16944,10 @@ paths:
x-agent:
id: data_source.get_sync_log
risk: read
- x-agent-hint: Read the current status, counts and errors of a sync_log_id returned
- by data_source.sync or data_source.list_sync_logs. A started job is not a
- completed sync.
+ x-agent-hint: Read the current status and counts of a sync_log_id returned by
+ data_source.sync or data_source.list_sync_logs. A started job is not a completed
+ sync. Raw upstream errors are omitted; detailed failures remain on the data
+ source settings page.
/datasource/types:
get:
description: Get list of available data source connectors
@@ -21733,8 +22712,10 @@ paths:
put:
consumes:
- application/json
- description: 为指定 MCP 服务下的某个工具更新启用状态和/或人工审批要求。至少提供 require_approval 或 enabled
- 之一;省略的字段保持原值。
+ description: |-
+ 为指定 MCP 服务下的某个工具更新启用状态、人工审批要求和/或风险等级。
+ 至少提供 require_approval、enabled、risk 之一;省略的字段保持原值。
+ risk 为 read/probe/write/destructive,空字符串表示改回按服务注解推断。
parameters:
- description: MCP 服务 ID
in: path
@@ -21746,7 +22727,7 @@ paths:
name: tool_name
required: true
type: string
- - description: '{require_approval?: bool, enabled?: bool}'
+ - description: '{require_approval?: bool, enabled?: bool, risk?: string}'
in: body
name: request
required: true
@@ -23103,6 +24084,54 @@ paths:
summary: 检查 WeKnoraCloud 凭证状态
tags:
- WeKnoraCloud
+ /notifications:
+ get:
+ parameters:
+ - description: 条数,最多 100
+ in: query
+ name: limit
+ type: integer
+ - description: 只看未读
+ in: query
+ name: unread
+ type: boolean
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: '{items, unread}'
+ schema:
+ additionalProperties: true
+ type: object
+ security:
+ - Bearer: []
+ summary: 列出我的通知
+ tags:
+ - 通知
+ /notifications/read:
+ post:
+ consumes:
+ - application/json
+ description: ids 为空时全部标记已读
+ parameters:
+ - description: '{ids}'
+ in: body
+ name: request
+ schema:
+ type: object
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 结果
+ schema:
+ additionalProperties: true
+ type: object
+ security:
+ - Bearer: []
+ summary: 标记通知已读
+ tags:
+ - 通知
/organizations:
get:
description: 获取当前空间所属的所有组织,并附带各空间内知识库/智能体数量
diff --git a/frontend/src/api/automation.ts b/frontend/src/api/automation.ts
new file mode 100644
index 000000000..ebef9259f
--- /dev/null
+++ b/frontend/src/api/automation.ts
@@ -0,0 +1,225 @@
+import { get, post, put, del } from '@/utils/request'
+import type { AssistantAccessLevel } from '@/api/assistant'
+
+// Shapes mirror internal/types/automation.go. Every endpoint works on the
+// caller's own automations; the server derives the owner from the request.
+
+export type AutomationTriggerType = 'cron' | 'once'
+export type AutomationSessionMode = 'per_run' | 'persistent'
+export type AutomationMisfirePolicy = 'skip' | 'run_once'
+export type AutomationOverlapPolicy = 'skip' | 'queue'
+export type AutomationRunStatus =
+ | 'queued'
+ | 'running'
+ | 'awaiting_approval'
+ | 'succeeded'
+ | 'failed'
+ | 'cancelled'
+ | 'skipped'
+ | 'needs_attention'
+export type AutomationRunTrigger = 'schedule' | 'manual' | 'misfire'
+
+export interface AutomationTrigger {
+ type: AutomationTriggerType
+ /** Five fields (minute first), six (seconds first) or a descriptor such as @daily. */
+ expr?: string
+ /** When a once trigger fires, RFC 3339. */
+ at?: string
+ /** IANA zone; empty means UTC. */
+ timezone?: string
+}
+
+export interface AutomationLimits {
+ /** Execution time of one run, not counting approval waits. 0 uses the default. */
+ max_duration_minutes?: number
+}
+
+export interface Automation {
+ id: string
+ name: string
+ description: string
+ enabled: boolean
+ agent_id: string
+ instruction: string
+ trigger: AutomationTrigger
+ session_mode: AutomationSessionMode
+ persistent_session_id: string
+ carry_last_result: boolean
+ misfire_policy: AutomationMisfirePolicy
+ overlap_policy: AutomationOverlapPolicy
+ access_level: AssistantAccessLevel
+ approval_timeout_minutes: number
+ limits: AutomationLimits
+ notify_on_success: boolean
+ next_run_at: string | null
+ last_run_at: string | null
+ last_success_at: string | null
+ last_run_status: AutomationRunStatus | ''
+ consecutive_failures: number
+ paused_reason: string
+ created_at: string
+ updated_at: string
+}
+
+/** Fields of a create or update; on update a field left out is kept. */
+export type AutomationInput = Partial<Pick<Automation,
+ | 'name'
+ | 'description'
+ | 'agent_id'
+ | 'instruction'
+ | 'trigger'
+ | 'session_mode'
+ | 'carry_last_result'
+ | 'misfire_policy'
+ | 'overlap_policy'
+ | 'access_level'
+ | 'approval_timeout_minutes'
+ | 'limits'
+ | 'notify_on_success'
+>>
+
+export interface AutomationRun {
+ id: string
+ automation_id: string
+ scheduled_at: string
+ trigger_kind: AutomationRunTrigger
+ status: AutomationRunStatus
+ session_id: string
+ user_message_id: string
+ assistant_message_id: string
+ pending_prompt_id: string
+ cancel_requested: boolean
+ answer: string
+ error: string
+ started_at: string | null
+ finished_at: string | null
+ created_at: string
+}
+
+export interface AutomationGrant {
+ id: string
+ grant_key: string
+ label: string
+ risk: string
+ prompt_id: string
+ created_at: string
+ last_used_at: string | null
+ /** Why the grant no longer applies, e.g. the agent changed. Empty while it does. */
+ lapse?: string
+}
+
+export interface AutomationGrantCandidate {
+ prompt_id: string
+ grant_key: string
+ label: string
+ risk: string
+ tool: string
+ service_name?: string
+ asked_at: string
+}
+
+const base = '/api/v1/automations'
+const enc = encodeURIComponent
+
+export function listAutomations() {
+ return get<{ success: boolean; data: Automation[] }>(base)
+}
+
+export function getAutomation(id: string) {
+ return get<{ success: boolean; data: Automation }>(`${base}/${enc(id)}`)
+}
+
+export function getAutomationBySession(sessionId: string) {
+ return get<{ success: boolean; data: Automation }>(`${base}/by-session/${enc(sessionId)}`)
+}
+
+export function createAutomation(input: AutomationInput) {
+ return post<{ success: boolean; data: Automation }>(base, input)
+}
+
+export function updateAutomation(id: string, input: AutomationInput) {
+ return put<{ success: boolean; data: Automation }>(`${base}/${enc(id)}`, input)
+}
+
+export function deleteAutomation(id: string) {
+ return del<{ success: boolean }>(`${base}/${enc(id)}`)
+}
+
+export function pauseAutomation(id: string) {
+ return post<{ success: boolean; data: Automation }>(`${base}/${enc(id)}/pause`, {})
+}
+
+/** Schedule again from now and clear the failure count; missed runs are not caught up. */
+export function resumeAutomation(id: string) {
+ return post<{ success: boolean; data: Automation }>(`${base}/${enc(id)}/resume`, {})
+}
+
+export function runAutomationNow(id: string) {
+ return post<{ success: boolean; data: AutomationRun }>(`${base}/${enc(id)}/run`, {})
+}
+
+/** The next three times trigger fires, in UTC; rejects an invalid or too frequent trigger. */
+export function validateAutomationTrigger(trigger: AutomationTrigger) {
+ return post<{ success: boolean; data: { next_runs: string[] } }>(`${base}/validate-trigger`, { trigger })
+}
+
+export function listAutomationRuns(id: string, page = 1, pageSize = 20) {
+ return get<{ success: boolean; data: AutomationRun[]; total: number }>(
+ `${base}/${enc(id)}/runs?page=${page}&page_size=${pageSize}`,
+ )
+}
+
+export function cancelAutomationRun(runId: string) {
+ return post<{ success: boolean; data: AutomationRun }>(`/api/v1/automation-runs/${enc(runId)}/cancel`, {})
+}
+
+export function listAutomationGrants(id: string) {
+ return get<{ success: boolean; data: AutomationGrant[] }>(`${base}/${enc(id)}/grants`)
+}
+
+export function listAutomationGrantCandidates(id: string) {
+ return get<{ success: boolean; data: AutomationGrantCandidate[] }>(`${base}/${enc(id)}/grant-candidates`)
+}
+
+/** Let later runs make the call a past run asked approval for without asking. */
+export function addAutomationGrant(id: string, promptId: string) {
+ return post<{ success: boolean; data: AutomationGrant }>(`${base}/${enc(id)}/grants`, { prompt_id: promptId })
+}
+
+export function revokeAutomationGrant(grantId: string) {
+ return del<{ success: boolean }>(`/api/v1/agent/grants/${enc(grantId)}`)
+}
+
+// ---------------------------------------------------------------------------
+// In-app notifications.
+// ---------------------------------------------------------------------------
+
+export type NotificationKind =
+ | 'automation.succeeded'
+ | 'automation.failed'
+ | 'automation.awaiting_approval'
+ | 'automation.paused'
+
+export interface AppNotification {
+ id: string
+ kind: NotificationKind | string
+ title: string
+ body: string
+ /** In-app route the notification opens. */
+ link: string
+ source_type: string
+ source_id: string
+ read_at: string | null
+ created_at: string
+}
+
+export function listNotifications(limit = 20) {
+ return get<{ success: boolean; data: { items: AppNotification[]; unread: number } }>(
+ `/api/v1/notifications?limit=${limit}`,
+ )
+}
+
+/** Mark ids read; no ids marks all of them. */
+export function markNotificationsRead(ids: string[] = []) {
+ return post<{ success: boolean }>('/api/v1/notifications/read', { ids })
+}
diff --git a/frontend/src/assets/img/automation-green.svg b/frontend/src/assets/img/automation-green.svg
new file mode 100644
index 000000000..f7373faca
--- /dev/null
+++ b/frontend/src/assets/img/automation-green.svg
@@ -0,0 +1,6 @@
+<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <circle cx="10" cy="10.75" r="6.5" stroke="#07C05F" stroke-width="1.5"/>
+ <path d="M10 7.5V10.75L12.25 12.25" stroke="#07C05F" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+ <path d="M7.75 2.75H12.25" stroke="#07C05F" stroke-width="1.5" stroke-linecap="round"/>
+ <path d="M15.25 4.75L16.25 5.75" stroke="#07C05F" stroke-width="1.5" stroke-linecap="round"/>
+</svg>
diff --git a/frontend/src/assets/img/automation.svg b/frontend/src/assets/img/automation.svg
new file mode 100644
index 000000000..f01f5923f
--- /dev/null
+++ b/frontend/src/assets/img/automation.svg
@@ -0,0 +1,6 @@
+<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <circle cx="10" cy="10.75" r="6.5" stroke="currentColor" stroke-width="1.5"/>
+ <path d="M10 7.5V10.75L12.25 12.25" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+ <path d="M7.75 2.75H12.25" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
+ <path d="M15.25 4.75L16.25 5.75" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
+</svg>
diff --git a/frontend/src/components/ChatHeader.vue b/frontend/src/components/ChatHeader.vue
index 470553428..4fd4eb2aa 100644
--- a/frontend/src/components/ChatHeader.vue
+++ b/frontend/src/components/ChatHeader.vue
@@ -26,6 +26,22 @@
<t-icon v-if="session?.is_pinned" name="pin" size="12px" class="chat-header__pin" />
<span ref="titleTextRef" class="chat-header__title-text">{{ displayTitle }}</span>
</h1>
+ <router-link
+ v-if="!titleEditing && automation"
+ class="chat-header__automation"
+ :to="`/platform/automations/${encodeURIComponent(automation.id)}`"
+ :title="t('chatHeader.automationOpen', { name: automation.name })"
+ >
+ <t-icon name="time" size="12px" />
+ <span>{{ automation.name }}</span>
+ </router-link>
+ <span
+ v-else-if="!titleEditing && session?.kind === 'automation'"
+ class="chat-header__automation"
+ >
+ <t-icon name="time" size="12px" />
+ <span>{{ t('chatHeader.automationTask') }}</span>
+ </span>
<span
v-if="!titleEditing && workspaceLabel"
class="chat-header__workspace"
@@ -121,11 +137,12 @@
</template>
<script setup lang="ts">
-import { computed, nextTick, ref } from 'vue'
+import { computed, nextTick, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { MessagePlugin } from 'tdesign-vue-next'
import { copyToClipboard } from '@/utils/clipboard'
import { getMessageList } from '@/api/chat'
+import { getAutomationBySession } from '@/api/automation'
import { listAgentGrants, revokeAgentGrant, type AgentGrant } from '@/api/mcp-service'
import {
removeSession,
@@ -141,6 +158,7 @@ interface ChatHeaderSession {
id: string
title?: string
description?: string
+ kind?: string
tenant_id?: number | string
is_pinned?: boolean
host_workspace_dir?: string
@@ -162,6 +180,20 @@ const titleDraft = ref('')
const titleInputRef = ref<HTMLInputElement | null>(null)
const displayTitle = computed(() => props.session?.title?.trim() || t('menu.newSession'))
+const automation = ref<{ id: string; name: string } | null>(null)
+
+watch(() => [props.session?.id, props.session?.kind] as const, async ([id, kind]) => {
+ automation.value = null
+ if (!id || kind !== 'automation') return
+ try {
+ const res = await getAutomationBySession(id)
+ if (props.session?.id === id && res.data?.id) {
+ automation.value = { id: res.data.id, name: res.data.name }
+ }
+ } catch {
+ // The badge stays, without a link, when the automation is gone.
+ }
+}, { immediate: true })
const titleTextRef = ref<HTMLElement | null>(null)
useSessionTitleMotion(titleTextRef, () => props.session?.id, () => displayTitle.value)
const workspaceLabel = computed(() => {
@@ -339,7 +371,7 @@ async function submitDeleteSession(): Promise<void> {
display: inline-flex;
align-items: center;
gap: 2px;
- max-width: min(360px, calc(100% - 36px));
+ max-width: min(520px, calc(100% - 36px));
min-width: 0;
box-sizing: border-box;
}
@@ -391,6 +423,36 @@ async function submitDeleteSession(): Promise<void> {
white-space: nowrap;
}
+.chat-header__automation {
+ display: inline-flex;
+ flex: 0 1 auto;
+ align-items: center;
+ gap: 4px;
+ min-width: 0;
+ max-width: 160px;
+ margin-left: 6px;
+ padding: 0 8px;
+ height: 22px;
+ border-radius: var(--app-radius-sm);
+ background: var(--td-bg-color-secondarycontainer);
+ color: var(--td-text-color-secondary);
+ font-size: var(--app-text-xs);
+ line-height: 22px;
+ text-decoration: none;
+ white-space: nowrap;
+
+ span {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+
+ &:hover {
+ color: var(--td-brand-color);
+ background: var(--td-bg-color-secondarycontainer-hover);
+ }
+}
+
.chat-header__workspace {
flex: 0 1 auto;
min-width: 0;
diff --git a/frontend/src/components/GlobalInvitationBell.vue b/frontend/src/components/GlobalInvitationBell.vue
index d2c8be988..48da46e07 100644
--- a/frontend/src/components/GlobalInvitationBell.vue
+++ b/frontend/src/components/GlobalInvitationBell.vue
@@ -1,72 +1,228 @@
<template>
- <!-- 全局右上角"待处理邀请"铃铛。
- - 与原先 UserMenu 中铃铛的逻辑一致:只在 pendingInvitationCount > 0 时渲染,
- 空收件箱场景不占用角落像素。
- - 固定定位、z-index 远低于 t-drawer 默认 2500,业务页面右侧抽屉(FAQ、KB 调试、
- Tenant 审计、SettingDrawer 等)弹出时会自然覆盖铃铛,不需要特意联动隐藏。
- - 点击铃铛复用同一份 MyInvitationsDialog,行为与之前一致。 -->
- <template v-if="pendingInvitationCount > 0">
- <t-badge :count="pendingInvitationCount" :max-count="99" :offset="[6, 4]"
- class="global-invitation-bell">
- <button type="button" class="global-invitation-bell__btn"
- :title="$t('tenantInvitation.inboxTooltip')" @click="openDialog">
- <t-icon name="notification" size="18px" />
- </button>
- </t-badge>
- </template>
+ <!-- 通知入口:合并展示"待处理邀请"与站内通知(自动化运行结果、等待审批等)。
+ 触发区域由调用方通过默认插槽渲染(侧栏底部用户栏右侧),面板向右弹出。
+ 通知靠轮询刷新,页面不可见时暂停。 -->
+ <t-popup v-model:visible="panelVisible" trigger="click" placement="right-bottom" :overlay-inner-style="{ padding: 0 }">
+ <slot :count="badgeCount" :open="panelVisible" />
+ <template #content>
+ <div class="notification-panel">
+ <div class="notification-panel__head">
+ <span>{{ $t('notifications.title') }}</span>
+ <t-button v-if="unread > 0" size="small" variant="text" theme="primary" @click="markAllRead">
+ {{ $t('notifications.markAllRead') }}
+ </t-button>
+ </div>
+ <button v-if="pendingInvitationCount > 0" type="button" class="notification-item" @click="openInvitations">
+ <t-icon name="usergroup-add" size="16px" class="notification-item__icon" />
+ <span class="notification-item__body">
+ <span class="notification-item__title">{{ $t('tenantInvitation.inboxTooltip') }}</span>
+ <span class="notification-item__text">
+ {{ $t('notifications.pendingInvitations', { count: pendingInvitationCount }) }}
+ </span>
+ </span>
+ </button>
+ <button v-for="item in items" :key="item.id" type="button" class="notification-item"
+ :class="{ 'is-unread': !item.read_at }" @click="open(item)">
+ <span class="notification-item__dot" :class="`is-${item.kind.replace('.', '-')}`" aria-hidden="true" />
+ <span class="notification-item__body">
+ <span class="notification-item__title">{{ item.title }}</span>
+ <span v-if="item.body" class="notification-item__text">{{ item.body }}</span>
+ <span class="notification-item__time">
+ {{ kindLabel(item.kind) }} · {{ formatTime(item.created_at) }}
+ </span>
+ </span>
+ </button>
+ <p v-if="!items.length && pendingInvitationCount === 0" class="notification-panel__empty">
+ {{ $t('notifications.empty') }}
+ </p>
+ </div>
+ </template>
+ </t-popup>
<MyInvitationsDialog v-model:visible="dialogVisible" />
</template>
<script setup lang="ts">
-import { computed, ref } from 'vue'
+import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
+import { useRouter } from 'vue-router'
+import { useI18n } from 'vue-i18n'
import { useAuthStore } from '@/stores/auth'
import MyInvitationsDialog from '@/components/MyInvitationsDialog.vue'
+import { listNotifications, markNotificationsRead, type AppNotification } from '@/api/automation'
+
+const POLL_MS = 60_000
const authStore = useAuthStore()
+const router = useRouter()
+const { t, te, locale } = useI18n()
const pendingInvitationCount = computed(() => authStore.pendingInvitationCount)
+const items = ref<AppNotification[]>([])
+const unread = ref(0)
+const badgeCount = computed(() => pendingInvitationCount.value + unread.value)
const dialogVisible = ref(false)
-const openDialog = () => {
+const panelVisible = ref(false)
+let timer: ReturnType<typeof setInterval> | undefined
+
+async function refresh() {
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return
+ try {
+ const res = await listNotifications(20)
+ items.value = res.data?.items ?? []
+ unread.value = res.data?.unread ?? 0
+ } catch {
+ // Polling retries on the next tick.
+ }
+}
+
+const onVisible = () => {
+ if (document.visibilityState === 'visible') void refresh()
+}
+
+onMounted(() => {
+ void refresh()
+ timer = setInterval(refresh, POLL_MS)
+ document.addEventListener('visibilitychange', onVisible)
+})
+
+onBeforeUnmount(() => {
+ clearInterval(timer)
+ document.removeEventListener('visibilitychange', onVisible)
+})
+
+const kindLabel = (kind: string) => {
+ const key = `notifications.kinds.${kind.replace('.', '_')}`
+ return te(key) ? t(key) : t('notifications.title')
+}
+const formatTime = (iso: string) => {
+ const date = new Date(iso)
+ if (Number.isNaN(date.getTime())) return ''
+ return new Intl.DateTimeFormat(locale.value, { dateStyle: 'short', timeStyle: 'short' }).format(date)
+}
+
+const openInvitations = () => {
+ panelVisible.value = false
dialogVisible.value = true
}
+
+async function open(item: AppNotification) {
+ panelVisible.value = false
+ if (!item.read_at) {
+ item.read_at = new Date().toISOString()
+ unread.value = Math.max(0, unread.value - 1)
+ markNotificationsRead([item.id]).catch(() => {})
+ }
+ if (item.link.startsWith('/')) void router.push(item.link)
+}
+
+async function markAllRead() {
+ try {
+ await markNotificationsRead()
+ const now = new Date().toISOString()
+ items.value = items.value.map((item) => ({ ...item, read_at: item.read_at ?? now }))
+ unread.value = 0
+ } catch {
+ // Left unread; the next poll shows the real state.
+ }
+}
</script>
<style lang="less" scoped>
-.global-invitation-bell {
- position: fixed;
- top: 12px;
- right: calc(16px + var(--assistant-dock-width, 0px));
- /* 远低于 TDesign 抽屉的默认 z-index (2500),确保业务页右侧抽屉弹出时能正常盖住铃铛。
- 高于普通页面内容(一般 0~10),避免被列表卡片覆盖。 */
- z-index: 100;
+.notification-panel {
+ width: 360px;
+ max-height: 460px;
+ overflow-y: auto;
+ padding: 4px 0;
}
-.global-invitation-bell__btn {
- display: inline-flex;
+.notification-panel__head {
+ display: flex;
align-items: center;
- justify-content: center;
- width: 32px;
- height: 32px;
- padding: 0;
- border: 1px solid var(--td-component-stroke);
- border-radius: var(--app-radius-lg);
- /* 用 container 背景而非透明,铃铛悬在内容区上方时和不同颜色的页面背景都能看清。 */
- background: var(--td-bg-color-container);
- color: var(--td-text-color-secondary);
+ justify-content: space-between;
+ margin: 0 4px 4px;
+ padding: 6px 12px 8px;
+ border-bottom: 1px solid var(--td-component-stroke);
+ font-weight: 600;
+}
+
+.notification-panel__empty {
+ margin: 0;
+ padding: 16px 12px;
+ color: var(--td-text-color-placeholder);
+ font-size: var(--app-text-sm);
+ text-align: center;
+}
+
+.notification-item {
+ display: flex;
+ gap: 10px;
+ width: calc(100% - 8px);
+ margin: 2px 4px;
+ padding: 8px 12px;
+ border: 0;
+ border-radius: var(--app-radius-sm);
+ background: none;
+ color: var(--td-text-color-primary);
+ font: inherit;
+ text-align: left;
cursor: pointer;
- box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);
- transition: background-color 0.18s ease, color 0.18s ease, box-shadow 0.18s ease;
&:hover {
- background-color: var(--td-bg-color-secondarycontainer);
- color: var(--td-brand-color);
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
+ background: var(--td-bg-color-container-hover);
}
- &:focus-visible {
- outline: 2px solid var(--td-brand-color-focus);
- outline-offset: 1px;
+ &.is-unread {
+ background: var(--td-bg-color-secondarycontainer);
+
+ &:hover {
+ background: var(--td-bg-color-secondarycontainer-hover);
+ }
}
}
+
+.notification-item__dot {
+ flex-shrink: 0;
+ width: 6px;
+ height: 6px;
+ margin-top: 6px;
+ border-radius: 50%;
+ background: var(--td-text-color-placeholder);
+
+ &.is-automation-succeeded { background: var(--td-success-color); }
+ &.is-automation-failed { background: var(--td-error-color); }
+ &.is-automation-awaiting_approval,
+ &.is-automation-paused { background: var(--td-warning-color); }
+}
+
+.notification-item__body {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ min-width: 0;
+}
+
+.notification-item__title {
+ overflow: hidden;
+ font-size: var(--app-text-md);
+ font-weight: 500;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.notification-item__text {
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 2;
+ line-clamp: 2;
+ overflow: hidden;
+ color: var(--td-text-color-secondary);
+ font-size: var(--app-text-xs);
+ line-height: 1.5;
+ overflow-wrap: anywhere;
+}
+
+.notification-item__time {
+ color: var(--td-text-color-placeholder);
+ font-size: var(--app-text-xs);
+}
</style>
diff --git a/frontend/src/components/UserMenu.vue b/frontend/src/components/UserMenu.vue
index e57f02891..a5b8ec470 100644
--- a/frontend/src/components/UserMenu.vue
+++ b/frontend/src/components/UserMenu.vue
@@ -1,13 +1,13 @@
<template>
<div class="user-menu" :class="{ 'user-menu--collapsed': uiStore.sidebarCollapsed }" ref="menuRef">
+ <div class="user-bar">
<!-- 用户按钮 -->
<div class="user-button" data-guide="user-menu" @click="toggleMenu">
<div class="user-avatar">
<img v-if="userAvatar" :src="userAvatar" :alt="$t('common.avatar')" />
<span v-else class="avatar-placeholder">{{ userInitial }}</span>
</div>
- <template v-if="!uiStore.sidebarCollapsed">
- <div class="user-info">
+ <div v-if="!uiStore.sidebarCollapsed" class="user-info">
<!-- 多空间 / superuser:首行空间名,次行 username · 角色。单空间:昵称 + 邮箱。 -->
<template v-if="showTenantIdentityLine">
<div class="user-tenant-name" :title="activeTenantName">{{ activeTenantName }}</div>
@@ -24,9 +24,27 @@
<div class="user-email">{{ userEmail }}</div>
</template>
</div>
- <t-icon :name="menuVisible ? 'chevron-up' : 'chevron-down'" class="dropdown-icon" />
- </template>
</div>
+ <GlobalInvitationBell v-if="!uiStore.sidebarCollapsed" v-slot="{ count, open }">
+ <t-tooltip :content="t('notifications.title')" placement="top">
+ <button type="button" class="user-notify" :class="{ 'is-open': open }"
+ :aria-label="t('notifications.title')" @click.stop>
+ <t-badge :count="count" :max-count="99" size="small" :offset="[2, -2]">
+ <t-icon name="notification" size="16px" />
+ </t-badge>
+ </button>
+ </t-tooltip>
+ </GlobalInvitationBell>
+ </div>
+ <GlobalInvitationBell v-if="uiStore.sidebarCollapsed" v-slot="{ count, open }">
+ <t-tooltip :content="t('notifications.title')" placement="right">
+ <button type="button" class="user-notify" :class="{ 'is-open': open }"
+ :aria-label="t('notifications.title')" @click.stop>
+ <t-icon name="notification" size="16px" />
+ <i v-if="count > 0" class="user-notify__dot" aria-hidden="true" />
+ </button>
+ </t-tooltip>
+ </GlobalInvitationBell>
<!-- 下拉菜单 -->
<Transition name="dropdown">
@@ -205,6 +223,7 @@ import { MessagePlugin } from 'tdesign-vue-next'
import { logout as logoutApi } from '@/api/auth'
import { useI18n } from 'vue-i18n'
import CreateTenantDialog from '@/components/CreateTenantDialog.vue'
+import GlobalInvitationBell from '@/components/GlobalInvitationBell.vue'
import {
navigateAfterTenantSwitch,
persistLastActiveTenantPreference,
@@ -564,7 +583,18 @@ onUnmounted(() => {
width: 100%;
&--collapsed {
+ display: flex;
+ flex-direction: column-reverse;
+ align-items: center;
+ gap: 4px;
+
+ .user-bar {
+ width: auto;
+ justify-content: center;
+ }
+
.user-button {
+ flex: none;
justify-content: center;
width: 32px;
height: 32px;
@@ -584,14 +614,24 @@ onUnmounted(() => {
}
}
+.user-bar {
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ width: 100%;
+ min-width: 0;
+}
+
.user-button {
display: flex;
+ flex: 1;
align-items: center;
gap: 6px;
+ min-width: 0;
padding: 8px 6px;
border-radius: var(--app-radius-md);
cursor: pointer;
- transition: all var(--app-motion-base);
+ transition: background-color var(--app-motion-base);
background: transparent;
&:hover {
@@ -700,11 +740,40 @@ onUnmounted(() => {
}
}
-.dropdown-icon {
- font-size: var(--app-text-xl);
- color: var(--td-text-color-secondary);
+.user-notify {
+ display: inline-flex;
flex-shrink: 0;
- transition: transform var(--app-motion-base);
+ align-items: center;
+ justify-content: center;
+ width: 24px;
+ height: 24px;
+ padding: 0;
+ border: 0;
+ border-radius: var(--app-radius-sm);
+ background: transparent;
+ color: var(--td-text-color-placeholder);
+ cursor: pointer;
+
+ &:hover,
+ &.is-open {
+ background: var(--td-bg-color-container-hover);
+ color: var(--td-text-color-primary);
+ }
+}
+
+.user-notify__dot {
+ position: absolute;
+ top: 2px;
+ right: 2px;
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--td-error-color);
+ box-shadow: 0 0 0 1.5px var(--td-bg-color-sidebar);
+}
+
+.user-menu--collapsed .user-notify {
+ position: relative;
}
.user-dropdown {
diff --git a/frontend/src/components/icons/ResourceIcon.vue b/frontend/src/components/icons/ResourceIcon.vue
index dda59b645..e56c4fa65 100644
--- a/frontend/src/components/icons/ResourceIcon.vue
+++ b/frontend/src/components/icons/ResourceIcon.vue
@@ -9,9 +9,10 @@ import agentIcon from '@/assets/img/agent.svg'
import artifactIcon from '@/assets/img/artifact.svg'
import organizationIcon from '@/assets/img/organization.svg'
import toolboxIcon from '@/assets/img/toolbox.svg'
+import automationIcon from '@/assets/img/automation.svg'
const props = withDefaults(defineProps<{
- type: 'knowledge' | 'agent' | 'artifact' | 'organization' | 'toolbox'
+ type: 'knowledge' | 'agent' | 'artifact' | 'organization' | 'toolbox' | 'automation'
size?: number
}>(), { size: 20 })
@@ -22,6 +23,7 @@ const icons = {
artifact: artifactIcon,
organization: organizationIcon,
toolbox: toolboxIcon,
+ automation: automationIcon,
}
const iconStyle = computed(() => ({
width: `${props.size}px`,
diff --git a/frontend/src/components/menu.vue b/frontend/src/components/menu.vue
index a650eed18..24a84f6ea 100644
--- a/frontend/src/components/menu.vue
+++ b/frontend/src/components/menu.vue
@@ -103,7 +103,7 @@
<div class="menu_item-box">
<div class="menu_icon" :class="`menu_icon--${item.icon}`">
<img class="icon"
- :src="getImgSrc(item.icon == 'zhishiku' ? knowledgeIcon : item.icon == 'agent' ? agentIcon : item.icon == 'artifact' ? artifactIcon : item.icon == 'toolbox' ? toolboxIcon : item.icon == 'organization' ? organizationIcon : item.icon == 'logout' ? logoutIcon : item.icon == 'setting' ? settingIcon : prefixIcon)"
+ :src="getImgSrc(item.icon == 'zhishiku' ? knowledgeIcon : item.icon == 'agent' ? agentIcon : item.icon == 'artifact' ? artifactIcon : item.icon == 'automation' ? automationIcon : item.icon == 'toolbox' ? toolboxIcon : item.icon == 'organization' ? organizationIcon : item.icon == 'logout' ? logoutIcon : item.icon == 'setting' ? settingIcon : prefixIcon)"
alt="">
</div>
<template v-if="!uiStore.sidebarCollapsed">
@@ -470,6 +470,8 @@ const isMenuItemActive = (itemPath: string): boolean => {
return currentRoute === 'toolbox';
case 'artifacts':
return currentRoute === 'artifactLibrary';
+ case 'automations':
+ return currentRoute === 'automationList';
case 'organizations':
return currentRoute === 'organizationList';
case 'creatChat':
@@ -498,7 +500,7 @@ const getIconActiveState = (itemPath: string) => {
};
// 分离上下两部分菜单(使用 visibleMenuArr 以便 lite 模式过滤 logout)
-const TOP_MENU_PATHS = new Set(['creatChat', 'knowledge-bases', 'artifacts', 'agents', 'toolbox', 'organizations']);
+const TOP_MENU_PATHS = new Set(['creatChat', 'knowledge-bases', 'artifacts', 'agents', 'automations', 'toolbox', 'organizations']);
const topMenuItems = computed<MenuItem[]>(() => {
return (visibleMenuArr.value as unknown as MenuItem[]).filter((item: MenuItem) => TOP_MENU_PATHS.has(item.path));
@@ -1143,6 +1145,7 @@ let settingIcon = ref('setting.svg');
let agentIcon = ref('agent.svg');
let artifactIcon = ref('artifact.svg');
let toolboxIcon = ref('toolbox.svg');
+let automationIcon = ref('automation.svg');
let organizationIcon = ref('organization.svg');
let pathPrefix = ref(route.name)
const getIcon = (path: string) => {
@@ -1164,6 +1167,7 @@ const getIcon = (path: string) => {
artifactIcon.value = artifactsActiveState ? 'artifact-green.svg' : 'artifact.svg';
toolboxIcon.value = route.name === 'toolbox' ? 'toolbox-green.svg' : 'toolbox.svg';
+ automationIcon.value = route.name === 'automationList' ? 'automation-green.svg' : 'automation.svg';
// 组织图标:只在组织页面显示绿色
organizationIcon.value = organizationsActiveState ? 'organization-green.svg' : 'organization.svg';
@@ -1345,7 +1349,6 @@ const resizeSidebar = (delta: number, keyboard: boolean) => {
.menu_bottom {
align-items: center;
}
-
.menu_top {
margin-right: 0;
padding-right: 0;
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 4d0ab0990..c81fe8bb1 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -124,6 +124,207 @@ export default {
"historyModels": "{count} models changed",
"historyNoOverrides": "No administrator changes",
},
+ automation: {
+ title: 'Automations',
+ description: 'Have an agent run tasks on a schedule as you. You are notified of results and pending approvals.',
+ add: 'New automation',
+ addHint: 'Or ask the WeKnora assistant to set one up',
+ paused: 'Paused',
+ nextRunAt: 'Next {time}',
+ notScheduled: 'Not scheduled',
+ agentUnavailable: 'Agent unavailable',
+ deleteTitle: 'Delete automation',
+ deleteBody: 'Stops any run in progress and deletes the runs, conversations and standing approvals of "{name}". This cannot be undone.',
+ fields: {
+ name: 'Name',
+ agent: 'Agent',
+ instruction: 'Task',
+ schedule: 'Schedule',
+ timezone: 'Timezone',
+ accessLevel: 'Access',
+ sessionMode: 'Conversation',
+ carryLastResult: 'Include the last successful result',
+ overlapPolicy: 'If the last run is still going',
+ misfirePolicy: 'Missed runs',
+ approvalTimeout: 'Approval wait',
+ maxDuration: 'Max run time',
+ notifyOnSuccess: 'Notify on success',
+ nextRun: 'Next run',
+ enabled: 'Enabled',
+ },
+ editor: {
+ createTitle: 'New automation',
+ editTitle: 'Edit automation',
+ namePlaceholder: 'e.g. Daily knowledge base digest',
+ instructionPlaceholder: 'Say what to do, which sources to use and how to present the result',
+ variablesHint: 'Variables:',
+ unattendedHint: 'Nobody is watching a run, so the agent cannot ask you questions. Actions that need approval pause it and notify you.',
+ nameDesc: 'Shown in the list and in notifications so you can tell it apart',
+ agentDesc: 'The agent that does the task, with its knowledge bases, tools and skills',
+ frequency: 'Repeats',
+ weekdays: 'Days',
+ dayOfMonthDesc: 'In months without this day, it runs on the last day',
+ runAt: 'Run at',
+ cron: 'Cron expression',
+ timeOfDay: 'Time',
+ timezoneDesc: 'Runs by the clock in this time zone, daylight saving included',
+ previewEmpty: 'Once the time is set, the next few runs show up here',
+ carryDesc: 'Starts each new conversation with the last successful result, for incremental summaries',
+ misfireDesc: 'What to do with runs missed while the service was down',
+ maxDurationDesc: 'A run still going after this long is stopped',
+ navGroups: {
+ task: 'Task',
+ run: 'Running',
+ },
+ sections: {
+ basic: {
+ title: 'Basics',
+ desc: 'Name the task, pick the agent that runs it and describe what to do.',
+ },
+ schedule: {
+ title: 'Schedule',
+ desc: 'When the task runs. Runs are at least 5 minutes apart.',
+ },
+ execution: {
+ title: 'Execution',
+ desc: 'What a run may change, which conversation it uses, and what happens on overlap or missed runs.',
+ },
+ notify: {
+ title: 'Approvals and notifications',
+ desc: 'Results and actions waiting for approval appear in the notifications at the top right.',
+ },
+ },
+ sessionModeDesc: {
+ per_run: 'Each run starts a new conversation',
+ persistent: 'All runs share one conversation, so the agent sees earlier ones',
+ },
+ errors: {
+ name: 'Enter a name',
+ instruction: 'Describe the task to run',
+ schedule: 'Set a valid schedule',
+ },
+ approvalTimeoutHelp: 'A run still waiting after this fails',
+ notifyHint: 'Failures, pending approvals and automatic pauses always notify you',
+ access: {
+ read_only: 'Only reads; changes nothing.',
+ confirm: 'Each change pauses the run for your approval. Recurring ones can be allowed for good in the details.',
+ auto_write: 'Reversible changes run directly; deletions and similar still pause for approval.',
+ },
+ },
+ schedule: {
+ kinds: {
+ daily: 'Daily',
+ weekdays: 'Weekdays',
+ weekly: 'Weekly',
+ monthly: 'Monthly',
+ hourly: 'Hourly',
+ once: 'Once',
+ custom: 'Custom cron',
+ },
+ atMinute: 'Minute past the hour',
+ dayOfMonth: 'Day of month',
+ pickTime: 'Pick a time',
+ customHint: 'Five fields: minute hour day month weekday. 0 9 * * 1-5 is 9:00 on weekdays. At least 5 minutes apart.',
+ nextRuns: 'Next:',
+ invalid: 'Invalid schedule',
+ describe: {
+ hourly: 'Every hour at :{minute}',
+ daily: 'Every day at {time}',
+ weekdays: 'Weekdays at {time}',
+ weekly: 'Every {days} at {time}',
+ monthly: 'Monthly on day {day} at {time}',
+ once: 'Once at {at}',
+ custom: 'cron: {expr}',
+ everyMinutes: 'Every {n} minutes',
+ everyHours: 'Every {n} hours',
+ },
+ },
+ sessionMode: {
+ per_run: 'New conversation each run',
+ persistent: 'One ongoing conversation',
+ },
+ overlap: {
+ skip: 'Skip this run',
+ queue: 'Queue it until the last one ends',
+ },
+ misfire: {
+ skip: 'Skip them',
+ run_once: 'Run once on recovery',
+ },
+ units: {
+ hours: 'hours',
+ minutes: 'minutes',
+ },
+ status: {
+ queued: 'Queued',
+ running: 'Running',
+ awaiting_approval: 'Awaiting approval',
+ succeeded: 'Succeeded',
+ failed: 'Failed',
+ cancelled: 'Stopped',
+ skipped: 'Skipped',
+ needs_attention: 'Needs attention',
+ paused: 'Paused',
+ },
+ runTrigger: {
+ schedule: 'Scheduled',
+ manual: 'Manual',
+ misfire: 'Catch-up',
+ },
+ actions: {
+ runNow: 'Run now',
+ pause: 'Pause',
+ resume: 'Resume',
+ review: 'Review',
+ openConversation: 'Open conversation',
+ stop: 'Stop',
+ },
+ detail: {
+ overview: 'Overview',
+ lastRun: 'Last run',
+ pausedBecause: 'Paused: {reason}',
+ runs: 'Runs',
+ noRuns: 'No runs yet',
+ stopping: 'Stopping',
+ grants: 'Standing approvals',
+ task: 'Task',
+ durationSeconds: '{n}s',
+ durationMinutes: '{n} min',
+ },
+ grants: {
+ intro: 'Later runs make these calls without asking. Each covers specific resources and lapses when the agent or your workspace role changes. Tools that always need approval never appear here.',
+ active: 'Allowed',
+ none: 'Nothing allowed yet',
+ lapsed: 'The setup changed, so this no longer applies',
+ revoke: 'Revoke',
+ candidates: 'Asked for approval in past runs',
+ noCandidates: 'Nothing to allow yet',
+ allow: 'Always allow',
+ allowTitle: 'Allow in future runs',
+ allowBody: 'Later runs will do "{label}" without pausing for approval.',
+ allowDestructiveBody: '"{label}" deletes or overwrites data and cannot be undone. Once allowed, later runs do it without asking.',
+ },
+ risk: {
+ write: 'Change',
+ destructive: 'Delete/overwrite',
+ },
+ messages: {
+ queued: 'Run started',
+ notFound: 'The automation no longer exists',
+ },
+ },
+ notifications: {
+ title: 'Notifications',
+ markAllRead: 'Mark all read',
+ pendingInvitations: '{count} pending invitations',
+ empty: 'No notifications',
+ kinds: {
+ automation_succeeded: 'Automation finished',
+ automation_failed: 'Automation failed',
+ automation_awaiting_approval: 'Automation needs approval',
+ automation_paused: 'Automation paused',
+ },
+ },
toolbox: {
"title": "Toolbox",
"description": "Manage skills, external tools, and browser connections for your agents.",
@@ -327,6 +528,7 @@ export default {
sessionUnread: 'New reply',
knowledgeBase: 'Knowledge Base',
agents: 'Agents',
+ automations: 'Automations',
artifacts: 'Artifacts',
organizations: 'Shared Spaces',
newChat: 'New Chat',
@@ -362,6 +564,8 @@ export default {
revokeFailed: 'Failed to revoke',
loadFailed: 'Failed to load',
},
+ automationTask: 'Automation',
+ automationOpen: 'Open automation "{name}"',
moreActions: 'More conversation actions',
toggleSandboxPanel: 'Sandbox terminal',
copySessionId: 'Copy Session ID',
@@ -6860,6 +7064,18 @@ export default {
get_catalog: "Get workspace skill details",
install_catalog: "Install catalog skill onto sandboxes",
},
+ automation: {
+ list: "List automations",
+ create: "Create automation",
+ validate_trigger: "Check schedule",
+ get: "Get automation",
+ update: "Update automation",
+ delete: "Delete automation",
+ pause: "Pause automation",
+ resume: "Resume automation",
+ run_now: "Run automation now",
+ list_runs: "List automation runs",
+ },
session: {
list: "List conversations",
},
diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts
index d172a256f..7f624f154 100644
--- a/frontend/src/i18n/locales/ja-JP.ts
+++ b/frontend/src/i18n/locales/ja-JP.ts
@@ -124,6 +124,207 @@ export default {
"historyModels": "{count} 件のモデルを変更",
"historyNoOverrides": "管理者の変更なし",
},
+ automation: {
+ title: 'オートメーション',
+ description: 'エージェントにスケジュールどおりあなたとしてタスクを実行させます。結果と承認待ちは通知されます。',
+ add: '新規オートメーション',
+ addHint: 'WeKnora アシスタントに作成を頼むこともできます',
+ paused: '一時停止中',
+ nextRunAt: '次回 {time}',
+ notScheduled: '予定なし',
+ agentUnavailable: 'エージェントを利用できません',
+ deleteTitle: 'オートメーションを削除',
+ deleteBody: '実行中の処理を停止し、「{name}」の実行履歴・会話・継続承認を削除します。元に戻せません。',
+ fields: {
+ name: '名前',
+ agent: '実行エージェント',
+ instruction: 'タスク',
+ schedule: 'スケジュール',
+ timezone: 'タイムゾーン',
+ accessLevel: '実行権限',
+ sessionMode: '会話の形式',
+ carryLastResult: '前回成功した結果を引き継ぐ',
+ overlapPolicy: '前回の実行が続いている場合',
+ misfirePolicy: '実行されなかった回',
+ approvalTimeout: '承認の待機期限',
+ maxDuration: '1 回の最大実行時間',
+ notifyOnSuccess: '成功時も通知',
+ nextRun: '次回実行',
+ enabled: '有効',
+ },
+ editor: {
+ createTitle: '新規オートメーション',
+ editTitle: 'オートメーションを編集',
+ namePlaceholder: '例:毎日のナレッジベース要約',
+ instructionPlaceholder: '何をするか、どの資料を使うか、結果をどう出すかを書いてください',
+ variablesHint: '使える変数:',
+ unattendedHint: '実行中は誰も見ていないため、エージェントは質問できません。承認が必要な操作は一時停止して通知します。',
+ nameDesc: '一覧と通知に表示され、タスクを見分けるのに使います',
+ agentDesc: 'タスクを実行するエージェント。そのナレッジベース、ツール、スキルを使えます',
+ frequency: '繰り返し',
+ weekdays: '曜日',
+ dayOfMonthDesc: 'その日がない月は月末に実行します',
+ runAt: '実行日時',
+ cron: 'Cron 式',
+ timeOfDay: '時刻',
+ timezoneDesc: 'このタイムゾーンの時刻で実行します。夏時間も自動で考慮します',
+ previewEmpty: '時刻を設定すると、この先の実行予定がここに表示されます',
+ carryDesc: '新しい会話の冒頭に前回成功した結果を添えます。差分の要約に便利です',
+ misfireDesc: 'サービス停止中に逃した実行を、復旧後にどう扱うか',
+ maxDurationDesc: 'この時間を過ぎても終わらない実行は停止します',
+ navGroups: {
+ task: 'タスク',
+ run: '実行',
+ },
+ sections: {
+ basic: {
+ title: '基本情報',
+ desc: 'タスクに名前を付け、実行するエージェントを選び、やることを書きます。',
+ },
+ schedule: {
+ title: '実行スケジュール',
+ desc: 'タスクを実行するタイミング。実行間隔は 5 分以上です。',
+ },
+ execution: {
+ title: '実行方法',
+ desc: '実行時に許可する変更、使う会話、重複や実行漏れ時の扱い。',
+ },
+ notify: {
+ title: '承認と通知',
+ desc: '実行結果と承認待ちの操作は右上の通知に表示されます。',
+ },
+ },
+ sessionModeDesc: {
+ per_run: '実行ごとに新しい会話を開きます',
+ persistent: 'すべての実行が同じ会話で行われ、以前の内容を参照できます',
+ },
+ errors: {
+ name: '名前を入力してください',
+ instruction: '実行するタスクを入力してください',
+ schedule: '有効なスケジュールを設定してください',
+ },
+ approvalTimeoutHelp: 'この期限を過ぎても未承認の実行は失敗になります',
+ notifyHint: '失敗・承認待ち・自動停止は常に通知されます',
+ access: {
+ read_only: '閲覧のみで、何も変更しません。',
+ confirm: '変更のたびに一時停止して承認を求めます。よく使う操作は詳細で継続承認にできます。',
+ auto_write: '元に戻せる変更はそのまま実行し、削除などは引き続き承認を待ちます。',
+ },
+ },
+ schedule: {
+ kinds: {
+ daily: '毎日',
+ weekdays: '平日',
+ weekly: '毎週',
+ monthly: '毎月',
+ hourly: '毎時',
+ once: '1 回のみ',
+ custom: 'カスタム cron',
+ },
+ atMinute: '毎時の何分',
+ dayOfMonth: '毎月の日付',
+ pickTime: '日時を選択',
+ customHint: '5 項目:分 時 日 月 曜日。0 9 * * 1-5 は平日 9:00。最短間隔は 5 分です。',
+ nextRuns: '次回:',
+ invalid: 'スケジュールが不正です',
+ describe: {
+ hourly: '毎時 {minute} 分',
+ daily: '毎日 {time}',
+ weekdays: '平日 {time}',
+ weekly: '毎週 {days} {time}',
+ monthly: '毎月 {day} 日 {time}',
+ once: '{at} に 1 回',
+ custom: 'cron:{expr}',
+ everyMinutes: '{n} 分ごと',
+ everyHours: '{n} 時間ごと',
+ },
+ },
+ sessionMode: {
+ per_run: '毎回新しい会話',
+ persistent: '同じ会話を継続',
+ },
+ overlap: {
+ skip: '今回はスキップ',
+ queue: '前回の終了後に実行',
+ },
+ misfire: {
+ skip: 'スキップ',
+ run_once: '復旧後に 1 回実行',
+ },
+ units: {
+ hours: '時間',
+ minutes: '分',
+ },
+ status: {
+ queued: '待機中',
+ running: '実行中',
+ awaiting_approval: '承認待ち',
+ succeeded: '成功',
+ failed: '失敗',
+ cancelled: '停止済み',
+ skipped: 'スキップ',
+ needs_attention: '要確認',
+ paused: '一時停止中',
+ },
+ runTrigger: {
+ schedule: 'スケジュール',
+ manual: '手動',
+ misfire: '補完実行',
+ },
+ actions: {
+ runNow: '今すぐ実行',
+ pause: '一時停止',
+ resume: '再開',
+ review: '承認する',
+ openConversation: '会話を開く',
+ stop: '停止',
+ },
+ detail: {
+ overview: '概要',
+ lastRun: '前回の実行',
+ pausedBecause: '一時停止中:{reason}',
+ runs: '実行履歴',
+ noRuns: 'まだ実行されていません',
+ stopping: '停止中',
+ grants: '継続承認',
+ task: 'タスク内容',
+ durationSeconds: '{n} 秒',
+ durationMinutes: '{n} 分',
+ },
+ grants: {
+ intro: 'ここにある操作は以降の実行で再承認不要です。特定のリソースに限られ、エージェントやワークスペースでのロールが変わると無効になります。毎回承認が必要なツールは表示されません。',
+ active: '承認済み',
+ none: '継続承認はありません',
+ lapsed: '設定が変わったため、現在は無効です',
+ revoke: '取り消す',
+ candidates: '過去の実行で承認を求めた操作',
+ noCandidates: '継続承認にできる操作はまだありません',
+ allow: '今後は常に許可',
+ allowTitle: '以降の実行で許可',
+ allowBody: '以降の実行では「{label}」を承認待ちなしで行います。',
+ allowDestructiveBody: '「{label}」はデータを削除または上書きし、元に戻せません。許可すると、以降の実行は確認なしで行います。',
+ },
+ risk: {
+ write: '変更',
+ destructive: '削除/上書き',
+ },
+ messages: {
+ queued: '実行を開始しました',
+ notFound: 'オートメーションは存在しないか削除されました',
+ },
+ },
+ notifications: {
+ title: '通知',
+ markAllRead: 'すべて既読',
+ pendingInvitations: '保留中の招待 {count} 件',
+ empty: '通知はありません',
+ kinds: {
+ automation_succeeded: 'オートメーション完了',
+ automation_failed: 'オートメーション失敗',
+ automation_awaiting_approval: 'オートメーション承認待ち',
+ automation_paused: 'オートメーション一時停止',
+ },
+ },
toolbox: {
"title": "ツールボックス",
"description": "エージェントのスキル、外部ツール、ブラウザー接続を管理します。",
@@ -327,6 +528,7 @@ export default {
sessionUnread: '新しい回答',
knowledgeBase: 'ナレッジベース',
agents: 'エージェント',
+ automations: 'オートメーション',
artifacts: '成果物',
organizations: '共有スペース',
newChat: '新しいチャット',
@@ -362,6 +564,8 @@ export default {
revokeFailed: '取り消しに失敗しました',
loadFailed: '読み込みに失敗しました',
},
+ automationTask: '自動化',
+ automationOpen: '自動化「{name}」を開く',
moreActions: 'その他の会話操作',
toggleSandboxPanel: 'サンドボックスターミナル',
copySessionId: 'セッションIDをコピー',
@@ -6860,6 +7064,18 @@ export default {
get_catalog: "ワークスペースのスキルの詳細を取得",
install_catalog: "カタログのスキルをサンドボックスにインストール",
},
+ automation: {
+ list: "自動化の一覧を取得",
+ create: "自動化を作成",
+ validate_trigger: "実行時刻を確認",
+ get: "自動化の詳細を取得",
+ update: "自動化を更新",
+ delete: "自動化を削除",
+ pause: "自動化を一時停止",
+ resume: "自動化を再開",
+ run_now: "自動化を今すぐ実行",
+ list_runs: "自動化の実行履歴を取得",
+ },
session: {
list: "会話一覧を取得",
},
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index 291092973..fcb6c9f29 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -124,6 +124,207 @@ export default {
"historyModels": "모델 {count}개 변경",
"historyNoOverrides": "관리자 변경 없음",
},
+ automation: {
+ title: '자동화',
+ description: '에이전트가 일정에 따라 사용자 본인으로 작업을 실행합니다. 결과와 승인 대기 항목은 알림으로 받습니다.',
+ add: '새 자동화',
+ addHint: 'WeKnora 어시스턴트에게 만들어 달라고 할 수도 있습니다',
+ paused: '일시 중지됨',
+ nextRunAt: '다음 {time}',
+ notScheduled: '예약 없음',
+ agentUnavailable: '에이전트를 사용할 수 없음',
+ deleteTitle: '자동화 삭제',
+ deleteBody: '진행 중인 실행을 중지하고 "{name}"의 실행 기록, 대화, 상시 승인을 삭제합니다. 되돌릴 수 없습니다.',
+ fields: {
+ name: '이름',
+ agent: '실행 에이전트',
+ instruction: '작업',
+ schedule: '일정',
+ timezone: '시간대',
+ accessLevel: '실행 권한',
+ sessionMode: '대화 방식',
+ carryLastResult: '지난번 성공 결과를 포함',
+ overlapPolicy: '이전 실행이 아직 진행 중이면',
+ misfirePolicy: '놓친 실행',
+ approvalTimeout: '승인 대기 기한',
+ maxDuration: '1회 최대 실행 시간',
+ notifyOnSuccess: '성공 시에도 알림',
+ nextRun: '다음 실행',
+ enabled: '사용',
+ },
+ editor: {
+ createTitle: '새 자동화',
+ editTitle: '자동화 편집',
+ namePlaceholder: '예: 매일 지식 베이스 요약',
+ instructionPlaceholder: '무엇을 할지, 어떤 자료를 쓸지, 결과를 어떻게 낼지 적어 주세요',
+ variablesHint: '사용 가능한 변수:',
+ unattendedHint: '실행 중에는 아무도 보고 있지 않으므로 에이전트가 질문할 수 없습니다. 승인이 필요한 작업은 일시 중지되고 알림이 갑니다.',
+ nameDesc: '목록과 알림에 표시되어 작업을 구분하는 데 쓰입니다',
+ agentDesc: '작업을 실행할 에이전트. 해당 지식베이스, 도구, 스킬을 사용할 수 있습니다',
+ frequency: '반복',
+ weekdays: '요일',
+ dayOfMonthDesc: '해당 날짜가 없는 달에는 마지막 날에 실행합니다',
+ runAt: '실행 시각',
+ cron: 'Cron 표현식',
+ timeOfDay: '시간',
+ timezoneDesc: '이 시간대의 시각으로 실행하며, 서머타임도 자동 반영됩니다',
+ previewEmpty: '시간을 설정하면 다음 실행 예정이 여기에 표시됩니다',
+ carryDesc: '새 대화 시작 시 지난번 성공한 결과를 함께 넣습니다. 증분 요약에 적합합니다',
+ misfireDesc: '서비스 중단 중 놓친 실행을 복구 후 어떻게 처리할지',
+ maxDurationDesc: '이 시간이 지나도 끝나지 않은 실행은 중지됩니다',
+ navGroups: {
+ task: '작업',
+ run: '실행',
+ },
+ sections: {
+ basic: {
+ title: '기본 정보',
+ desc: '작업 이름을 정하고, 실행할 에이전트를 고른 뒤 할 일을 적습니다.',
+ },
+ schedule: {
+ title: '실행 시간',
+ desc: '작업이 언제 실행될지 설정합니다. 실행 간격은 최소 5분입니다.',
+ },
+ execution: {
+ title: '실행 방식',
+ desc: '실행 중 허용할 변경, 사용할 대화, 겹치거나 놓친 실행의 처리 방식.',
+ },
+ notify: {
+ title: '승인 및 알림',
+ desc: '실행 결과와 승인 대기 작업은 오른쪽 위 알림에 표시됩니다.',
+ },
+ },
+ sessionModeDesc: {
+ per_run: '실행마다 새 대화를 엽니다',
+ persistent: '모든 실행이 같은 대화에서 진행되어 이전 내용을 볼 수 있습니다',
+ },
+ errors: {
+ name: '이름을 입력하세요',
+ instruction: '실행할 작업을 입력하세요',
+ schedule: '올바른 실행 시간을 설정하세요',
+ },
+ approvalTimeoutHelp: '이 기한이 지나도 승인되지 않으면 실행이 실패합니다',
+ notifyHint: '실패, 승인 대기, 자동 일시 중지는 항상 알림이 갑니다',
+ access: {
+ read_only: '읽기만 하고 아무것도 변경하지 않습니다.',
+ confirm: '변경할 때마다 일시 중지하고 승인을 요청합니다. 자주 쓰는 작업은 상세에서 상시 승인할 수 있습니다.',
+ auto_write: '되돌릴 수 있는 변경은 바로 실행하고, 삭제 등은 여전히 승인을 기다립니다.',
+ },
+ },
+ schedule: {
+ kinds: {
+ daily: '매일',
+ weekdays: '평일',
+ weekly: '매주',
+ monthly: '매월',
+ hourly: '매시간',
+ once: '한 번',
+ custom: '사용자 지정 cron',
+ },
+ atMinute: '매시 몇 분',
+ dayOfMonth: '매월 며칠',
+ pickTime: '시간 선택',
+ customHint: '다섯 필드: 분 시 일 월 요일. 0 9 * * 1-5는 평일 9:00입니다. 최소 간격은 5분입니다.',
+ nextRuns: '다음:',
+ invalid: '잘못된 일정',
+ describe: {
+ hourly: '매시 {minute}분',
+ daily: '매일 {time}',
+ weekdays: '평일 {time}',
+ weekly: '매주 {days} {time}',
+ monthly: '매월 {day}일 {time}',
+ once: '{at}에 한 번',
+ custom: 'cron: {expr}',
+ everyMinutes: '{n}분마다',
+ everyHours: '{n}시간마다',
+ },
+ },
+ sessionMode: {
+ per_run: '실행마다 새 대화',
+ persistent: '하나의 대화 유지',
+ },
+ overlap: {
+ skip: '이번 실행 건너뛰기',
+ queue: '이전 실행이 끝나면 실행',
+ },
+ misfire: {
+ skip: '건너뛰기',
+ run_once: '복구 후 한 번 실행',
+ },
+ units: {
+ hours: '시간',
+ minutes: '분',
+ },
+ status: {
+ queued: '대기 중',
+ running: '실행 중',
+ awaiting_approval: '승인 대기',
+ succeeded: '성공',
+ failed: '실패',
+ cancelled: '중지됨',
+ skipped: '건너뜀',
+ needs_attention: '확인 필요',
+ paused: '일시 중지됨',
+ },
+ runTrigger: {
+ schedule: '예약',
+ manual: '수동',
+ misfire: '보충 실행',
+ },
+ actions: {
+ runNow: '지금 실행',
+ pause: '일시 중지',
+ resume: '재개',
+ review: '검토',
+ openConversation: '대화 열기',
+ stop: '중지',
+ },
+ detail: {
+ overview: '개요',
+ lastRun: '마지막 실행',
+ pausedBecause: '일시 중지됨: {reason}',
+ runs: '실행 기록',
+ noRuns: '아직 실행되지 않았습니다',
+ stopping: '중지 중',
+ grants: '상시 승인',
+ task: '작업 내용',
+ durationSeconds: '{n}초',
+ durationMinutes: '{n}분',
+ },
+ grants: {
+ intro: '여기 있는 작업은 이후 실행에서 다시 승인하지 않아도 됩니다. 특정 리소스에만 적용되며 에이전트나 워크스페이스 역할이 바뀌면 효력을 잃습니다. 매번 승인이 필요한 도구는 표시되지 않습니다.',
+ active: '허용됨',
+ none: '상시 승인 없음',
+ lapsed: '설정이 바뀌어 현재 적용되지 않습니다',
+ revoke: '취소',
+ candidates: '이전 실행에서 승인을 요청한 작업',
+ noCandidates: '상시 승인할 수 있는 작업이 아직 없습니다',
+ allow: '항상 허용',
+ allowTitle: '이후 실행에서 허용',
+ allowBody: '이후 실행에서는 "{label}"을(를) 승인 대기 없이 수행합니다.',
+ allowDestructiveBody: '"{label}"은(는) 데이터를 삭제하거나 덮어쓰며 되돌릴 수 없습니다. 허용하면 이후 실행은 묻지 않고 수행합니다.',
+ },
+ risk: {
+ write: '변경',
+ destructive: '삭제/덮어쓰기',
+ },
+ messages: {
+ queued: '실행을 시작했습니다',
+ notFound: '자동화가 없거나 삭제되었습니다',
+ },
+ },
+ notifications: {
+ title: '알림',
+ markAllRead: '모두 읽음',
+ pendingInvitations: '대기 중인 초대 {count}개',
+ empty: '알림 없음',
+ kinds: {
+ automation_succeeded: '자동화 완료',
+ automation_failed: '자동화 실패',
+ automation_awaiting_approval: '자동화 승인 필요',
+ automation_paused: '자동화 일시 중지',
+ },
+ },
toolbox: {
"title": "도구함",
"description": "에이전트의 스킬, 외부 도구 및 브라우저 연결을 관리합니다.",
@@ -2089,6 +2290,18 @@ export default {
get_catalog: "워크스페이스 스킬 상세 조회",
install_catalog: "카탈로그 스킬을 샌드박스에 설치",
},
+ automation: {
+ list: "자동화 목록 가져오기",
+ create: "자동화 만들기",
+ validate_trigger: "실행 시간 확인",
+ get: "자동화 상세 가져오기",
+ update: "자동화 수정",
+ delete: "자동화 삭제",
+ pause: "자동화 일시 중지",
+ resume: "자동화 다시 시작",
+ run_now: "자동화 즉시 실행",
+ list_runs: "자동화 실행 기록 가져오기",
+ },
session: {
list: "대화 목록 조회",
},
@@ -8319,6 +8532,8 @@ export default {
revokeFailed: '취소하지 못했습니다',
loadFailed: '불러오지 못했습니다',
},
+ automationTask: '자동화',
+ automationOpen: '자동화 「{name}」 열기',
moreActions: '대화 추가 작업',
toggleSandboxPanel: '샌드박스 터미널',
copySessionId: '세션 ID 복사',
@@ -8400,6 +8615,7 @@ export default {
sessionUnread: '새 답변',
knowledgeBase: '지식베이스',
agents: '에이전트',
+ automations: '자동화',
artifacts: '산출물',
organizations: '공유 공간',
newChat: '새 대화',
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index d385fa0bc..90019aef0 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -124,6 +124,207 @@ export default {
"historyModels": "Изменено моделей: {count}",
"historyNoOverrides": "Нет изменений администратора",
},
+ automation: {
+ title: 'Автоматизации',
+ description: 'Агент выполняет задачи по расписанию от вашего имени. О результатах и ожидающих подтверждениях вы получите уведомление.',
+ add: 'Новая автоматизация',
+ addHint: 'Или попросите ассистента WeKnora создать её',
+ paused: 'Приостановлена',
+ nextRunAt: 'Далее {time}',
+ notScheduled: 'Не запланировано',
+ agentUnavailable: 'Агент недоступен',
+ deleteTitle: 'Удалить автоматизацию',
+ deleteBody: 'Текущий запуск будет остановлен, а запуски, беседы и постоянные разрешения «{name}» удалены. Это действие необратимо.',
+ fields: {
+ name: 'Название',
+ agent: 'Агент',
+ instruction: 'Задача',
+ schedule: 'Расписание',
+ timezone: 'Часовой пояс',
+ accessLevel: 'Права',
+ sessionMode: 'Беседа',
+ carryLastResult: 'Передавать последний успешный результат',
+ overlapPolicy: 'Если прошлый запуск ещё идёт',
+ misfirePolicy: 'Пропущенные запуски',
+ approvalTimeout: 'Ожидание подтверждения',
+ maxDuration: 'Макс. длительность запуска',
+ notifyOnSuccess: 'Уведомлять об успехе',
+ nextRun: 'Следующий запуск',
+ enabled: 'Включена',
+ },
+ editor: {
+ createTitle: 'Новая автоматизация',
+ editTitle: 'Изменить автоматизацию',
+ namePlaceholder: 'Например: ежедневная сводка базы знаний',
+ instructionPlaceholder: 'Опишите, что сделать, какие источники использовать и как оформить результат',
+ variablesHint: 'Переменные:',
+ unattendedHint: 'За запуском никто не следит, поэтому агент не может задавать вопросы. Действия, требующие подтверждения, приостанавливают запуск и присылают уведомление.',
+ nameDesc: 'Показывается в списке и уведомлениях, чтобы отличать задачу',
+ agentDesc: 'Агент, который выполняет задачу, со своими базами знаний, инструментами и навыками',
+ frequency: 'Повтор',
+ weekdays: 'Дни недели',
+ dayOfMonthDesc: 'В месяцы без этого дня запуск будет в последний день',
+ runAt: 'Время запуска',
+ cron: 'Выражение Cron',
+ timeOfDay: 'Время',
+ timezoneDesc: 'Запуск по часам этого часового пояса, с учётом летнего времени',
+ previewEmpty: 'Когда время задано, здесь появятся ближайшие запуски',
+ carryDesc: 'Каждый новый диалог начинается с последнего успешного результата, удобно для сводок изменений',
+ misfireDesc: 'Что делать с запусками, пропущенными, пока сервис не работал',
+ maxDurationDesc: 'Запуск, не завершившийся за это время, останавливается',
+ navGroups: {
+ task: 'Задача',
+ run: 'Выполнение',
+ },
+ sections: {
+ basic: {
+ title: 'Основное',
+ desc: 'Назовите задачу, выберите агента и опишите, что нужно сделать.',
+ },
+ schedule: {
+ title: 'Расписание',
+ desc: 'Когда запускать задачу. Интервал между запусками не меньше 5 минут.',
+ },
+ execution: {
+ title: 'Выполнение',
+ desc: 'Какие изменения разрешены, в каком диалоге идёт запуск и что делать при наложении или пропуске.',
+ },
+ notify: {
+ title: 'Одобрения и уведомления',
+ desc: 'Результаты и действия, ждущие одобрения, появляются в уведомлениях справа вверху.',
+ },
+ },
+ sessionModeDesc: {
+ per_run: 'Каждый запуск открывает новый диалог',
+ persistent: 'Все запуски идут в одном диалоге, агент видит прошлые',
+ },
+ errors: {
+ name: 'Введите название',
+ instruction: 'Опишите задачу',
+ schedule: 'Задайте корректное расписание',
+ },
+ approvalTimeoutHelp: 'Если подтверждения нет дольше этого срока, запуск завершается ошибкой',
+ notifyHint: 'О сбоях, ожидающих подтверждениях и автоматической паузе вы узнаете всегда',
+ access: {
+ read_only: 'Только чтение, без изменений.',
+ confirm: 'Каждое изменение приостанавливает запуск до вашего подтверждения. Повторяющиеся можно разрешить навсегда в деталях.',
+ auto_write: 'Обратимые изменения выполняются сразу; удаление и подобное по-прежнему ждут подтверждения.',
+ },
+ },
+ schedule: {
+ kinds: {
+ daily: 'Ежедневно',
+ weekdays: 'По будням',
+ weekly: 'Еженедельно',
+ monthly: 'Ежемесячно',
+ hourly: 'Ежечасно',
+ once: 'Однократно',
+ custom: 'Свой cron',
+ },
+ atMinute: 'Минута часа',
+ dayOfMonth: 'День месяца',
+ pickTime: 'Выберите время',
+ customHint: 'Пять полей: минута час день месяц день_недели. 0 9 * * 1-5 — 9:00 по будням. Интервал не меньше 5 минут.',
+ nextRuns: 'Далее:',
+ invalid: 'Недопустимое расписание',
+ describe: {
+ hourly: 'Каждый час в :{minute}',
+ daily: 'Каждый день в {time}',
+ weekdays: 'По будням в {time}',
+ weekly: 'Каждую неделю: {days} в {time}',
+ monthly: 'Ежемесячно, {day}-го в {time}',
+ once: 'Однократно: {at}',
+ custom: 'cron: {expr}',
+ everyMinutes: 'Каждые {n} мин',
+ everyHours: 'Каждые {n} ч',
+ },
+ },
+ sessionMode: {
+ per_run: 'Новая беседа на каждый запуск',
+ persistent: 'Одна общая беседа',
+ },
+ overlap: {
+ skip: 'Пропустить запуск',
+ queue: 'Поставить в очередь',
+ },
+ misfire: {
+ skip: 'Пропустить',
+ run_once: 'Выполнить один раз после восстановления',
+ },
+ units: {
+ hours: 'ч',
+ minutes: 'мин',
+ },
+ status: {
+ queued: 'В очереди',
+ running: 'Выполняется',
+ awaiting_approval: 'Ждёт подтверждения',
+ succeeded: 'Успешно',
+ failed: 'Ошибка',
+ cancelled: 'Остановлен',
+ skipped: 'Пропущен',
+ needs_attention: 'Требует внимания',
+ paused: 'Приостановлена',
+ },
+ runTrigger: {
+ schedule: 'По расписанию',
+ manual: 'Вручную',
+ misfire: 'Догоняющий',
+ },
+ actions: {
+ runNow: 'Запустить сейчас',
+ pause: 'Приостановить',
+ resume: 'Возобновить',
+ review: 'Проверить',
+ openConversation: 'Открыть беседу',
+ stop: 'Остановить',
+ },
+ detail: {
+ overview: 'Обзор',
+ lastRun: 'Последний запуск',
+ pausedBecause: 'Приостановлена: {reason}',
+ runs: 'Запуски',
+ noRuns: 'Запусков пока нет',
+ stopping: 'Остановка',
+ grants: 'Постоянные разрешения',
+ task: 'Задача',
+ durationSeconds: '{n} с',
+ durationMinutes: '{n} мин',
+ },
+ grants: {
+ intro: 'Эти вызовы последующие запуски выполняют без вопросов. Каждое разрешение касается конкретных ресурсов и перестаёт действовать при смене агента или вашей роли. Инструменты, требующие подтверждения каждый раз, здесь не появляются.',
+ active: 'Разрешено',
+ none: 'Пока ничего не разрешено',
+ lapsed: 'Настройки изменились, разрешение не действует',
+ revoke: 'Отозвать',
+ candidates: 'Запрашивали подтверждение в прошлых запусках',
+ noCandidates: 'Пока нечего разрешать',
+ allow: 'Всегда разрешать',
+ allowTitle: 'Разрешить в будущих запусках',
+ allowBody: 'Последующие запуски будут выполнять «{label}» без ожидания подтверждения.',
+ allowDestructiveBody: '«{label}» удаляет или перезаписывает данные безвозвратно. После разрешения последующие запуски будут делать это без вопросов.',
+ },
+ risk: {
+ write: 'Изменение',
+ destructive: 'Удаление/перезапись',
+ },
+ messages: {
+ queued: 'Запуск начат',
+ notFound: 'Автоматизация не найдена или удалена',
+ },
+ },
+ notifications: {
+ title: 'Уведомления',
+ markAllRead: 'Прочитать все',
+ pendingInvitations: 'Ожидающих приглашений: {count}',
+ empty: 'Уведомлений нет',
+ kinds: {
+ automation_succeeded: 'Автоматизация выполнена',
+ automation_failed: 'Сбой автоматизации',
+ automation_awaiting_approval: 'Автоматизация ждёт подтверждения',
+ automation_paused: 'Автоматизация приостановлена',
+ },
+ },
toolbox: {
"title": "Инструменты",
"description": "Управляйте навыками, внешними инструментами и подключением браузера для агентов.",
@@ -2089,6 +2290,18 @@ export default {
get_catalog: "Получить сведения о навыке рабочего пространства",
install_catalog: "Установить навык из каталога в песочницы",
},
+ automation: {
+ list: "Список автоматизаций",
+ create: "Создать автоматизацию",
+ validate_trigger: "Проверить расписание",
+ get: "Сведения об автоматизации",
+ update: "Изменить автоматизацию",
+ delete: "Удалить автоматизацию",
+ pause: "Приостановить автоматизацию",
+ resume: "Возобновить автоматизацию",
+ run_now: "Запустить автоматизацию сейчас",
+ list_runs: "История запусков автоматизации",
+ },
session: {
list: "Получить список диалогов",
},
@@ -8319,6 +8532,8 @@ export default {
revokeFailed: 'Не удалось отозвать',
loadFailed: 'Не удалось загрузить',
},
+ automationTask: 'Автоматизация',
+ automationOpen: 'Открыть автоматизацию «{name}»',
moreActions: 'Другие действия с диалогом',
toggleSandboxPanel: 'Терминал песочницы',
copySessionId: 'Копировать ID сессии',
@@ -8400,6 +8615,7 @@ export default {
sessionUnread: 'Новый ответ',
knowledgeBase: 'База знаний',
agents: 'Агенты',
+ automations: 'Автоматизации',
artifacts: 'Артефакты',
organizations: 'Общие пространства',
newChat: 'Новый диалог',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index 91be92180..b224e9ad5 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -124,6 +124,207 @@ export default {
"historyModels": "修改了 {count} 个模型",
"historyNoOverrides": "无管理员修改",
},
+ automation: {
+ title: '自动化',
+ description: '让智能体按计划以你的身份执行任务,结果和待审批事项会通知你。',
+ add: '新建自动化',
+ addHint: '也可以直接让 WeKnora 助手帮你创建',
+ paused: '已暂停',
+ nextRunAt: '下次 {time}',
+ notScheduled: '未排程',
+ agentUnavailable: '智能体不可用',
+ deleteTitle: '删除自动化',
+ deleteBody: '将停止进行中的运行,并删除「{name}」的运行记录、对话和长期授权。此操作无法撤销。',
+ fields: {
+ name: '名称',
+ agent: '执行智能体',
+ instruction: '任务',
+ schedule: '运行时间',
+ timezone: '时区',
+ accessLevel: '执行权限',
+ sessionMode: '对话形式',
+ carryLastResult: '把上次成功的结果带入本次对话',
+ overlapPolicy: '上次仍在运行时',
+ misfirePolicy: '错过的运行',
+ approvalTimeout: '审批等待期限',
+ maxDuration: '单次运行时长上限',
+ notifyOnSuccess: '成功时也通知',
+ nextRun: '下次运行',
+ enabled: '启用',
+ },
+ editor: {
+ createTitle: '新建自动化',
+ editTitle: '编辑自动化',
+ namePlaceholder: '例如:每日知识库周报',
+ instructionPlaceholder: '写清楚要做什么、用哪些资料、结果如何输出',
+ variablesHint: '可用变量:',
+ unattendedHint: '运行时无人在场,智能体不能向你提问;需要审批的操作会暂停并通知你。',
+ nameDesc: '在列表和通知里显示,方便你认出这项任务',
+ agentDesc: '由哪个智能体执行任务,它的知识库、工具和技能都可用',
+ frequency: '重复频率',
+ weekdays: '星期',
+ dayOfMonthDesc: '当月没有这一天时,在最后一天运行',
+ runAt: '运行时间',
+ cron: 'Cron 表达式',
+ timeOfDay: '时间',
+ timezoneDesc: '按这个时区的钟点运行,夏令时会自动换算',
+ previewEmpty: '设置好时间后,这里会显示接下来几次的运行时间',
+ carryDesc: '新对话开头附上上次成功运行的结果,适合做增量汇总',
+ misfireDesc: '服务停机期间错过的运行,恢复后如何处理',
+ maxDurationDesc: '超过这个时长仍未完成,本次运行会被终止',
+ navGroups: {
+ task: '任务',
+ run: '运行',
+ },
+ sections: {
+ basic: {
+ title: '基本信息',
+ desc: '给任务起个名字,选择执行的智能体,并写下要做的事。',
+ },
+ schedule: {
+ title: '运行时间',
+ desc: '设置任务什么时候运行,两次运行至少间隔 5 分钟。',
+ },
+ execution: {
+ title: '执行方式',
+ desc: '运行时可以做哪些修改、在哪个对话里进行,以及重叠和错过时的处理。',
+ },
+ notify: {
+ title: '审批与通知',
+ desc: '运行结果和待审批的操作会出现在右上角的通知里。',
+ },
+ },
+ sessionModeDesc: {
+ per_run: '每次运行开一个新对话,互不影响',
+ persistent: '所有运行都在同一个对话里,智能体能看到之前的内容',
+ },
+ errors: {
+ name: '请填写名称',
+ instruction: '请填写要执行的任务',
+ schedule: '请设置有效的运行时间',
+ },
+ approvalTimeoutHelp: '超过期限仍未审批,本次运行记为失败',
+ notifyHint: '失败、等待审批和自动暂停总会通知你',
+ access: {
+ read_only: '只查看,不做任何修改。',
+ confirm: '每次修改前暂停并通知你审批;可在详情里把常用操作设为长期授权。',
+ auto_write: '可恢复的修改直接执行;删除等操作仍暂停等待审批。',
+ },
+ },
+ schedule: {
+ kinds: {
+ daily: '每天',
+ weekdays: '工作日',
+ weekly: '每周',
+ monthly: '每月',
+ hourly: '每小时',
+ once: '仅一次',
+ custom: '自定义 cron',
+ },
+ atMinute: '每小时的第几分钟',
+ dayOfMonth: '每月几号',
+ pickTime: '选择时间',
+ customHint: '五段式:分 时 日 月 周,例如 0 9 * * 1-5 表示工作日 9:00。最短间隔 5 分钟。',
+ nextRuns: '接下来:',
+ invalid: '触发时间不合法',
+ describe: {
+ hourly: '每小时第 {minute} 分',
+ daily: '每天 {time}',
+ weekdays: '工作日 {time}',
+ weekly: '每周 {days} {time}',
+ monthly: '每月 {day} 日 {time}',
+ once: '仅在 {at}',
+ custom: 'cron:{expr}',
+ everyMinutes: '每 {n} 分钟',
+ everyHours: '每 {n} 小时',
+ },
+ },
+ sessionMode: {
+ per_run: '每次新对话',
+ persistent: '始终同一对话',
+ },
+ overlap: {
+ skip: '跳过本次',
+ queue: '排队,等上次结束后运行',
+ },
+ misfire: {
+ skip: '跳过',
+ run_once: '恢复后补跑一次',
+ },
+ units: {
+ hours: '小时',
+ minutes: '分钟',
+ },
+ status: {
+ queued: '排队中',
+ running: '运行中',
+ awaiting_approval: '等待审批',
+ succeeded: '成功',
+ failed: '失败',
+ cancelled: '已停止',
+ skipped: '已跳过',
+ needs_attention: '需要检查',
+ paused: '已暂停',
+ },
+ runTrigger: {
+ schedule: '按计划',
+ manual: '手动',
+ misfire: '补跑',
+ },
+ actions: {
+ runNow: '立即运行',
+ pause: '暂停',
+ resume: '恢复',
+ review: '去审批',
+ openConversation: '查看对话',
+ stop: '停止',
+ },
+ detail: {
+ overview: '概览',
+ lastRun: '上次运行',
+ pausedBecause: '已暂停:{reason}',
+ runs: '运行记录',
+ noRuns: '还没有运行过',
+ stopping: '正在停止',
+ grants: '长期授权',
+ task: '任务内容',
+ durationSeconds: '{n} 秒',
+ durationMinutes: '{n} 分钟',
+ },
+ grants: {
+ intro: '这里的操作在以后的运行中无需再次审批。只针对具体资源;更换智能体或你的空间角色变化后自动失效。需要每次审批的工具不会出现在这里。',
+ active: '已授权',
+ none: '暂无长期授权',
+ lapsed: '配置已变化,此授权暂不生效',
+ revoke: '撤销',
+ candidates: '运行中请求过审批的操作',
+ noCandidates: '还没有可设为长期授权的操作',
+ allow: '以后都允许',
+ allowTitle: '设为长期授权',
+ allowBody: '以后的运行执行「{label}」时将不再暂停等待审批。',
+ allowDestructiveBody: '「{label}」会删除或覆盖数据,且无法撤销。确认后,以后的运行将直接执行它,不再询问。',
+ },
+ risk: {
+ write: '修改',
+ destructive: '删除/覆盖',
+ },
+ messages: {
+ queued: '已开始运行',
+ notFound: '自动化不存在或已删除',
+ },
+ },
+ notifications: {
+ title: '通知',
+ markAllRead: '全部已读',
+ pendingInvitations: '{count} 个待处理邀请',
+ empty: '暂无通知',
+ kinds: {
+ automation_succeeded: '自动化已完成',
+ automation_failed: '自动化失败',
+ automation_awaiting_approval: '自动化等待审批',
+ automation_paused: '自动化已暂停',
+ },
+ },
toolbox: {
"title": "工具箱",
"description": "管理智能体可用的技能、外部工具和浏览器连接。",
@@ -2091,6 +2292,18 @@ export default {
get_catalog: "获取工作空间技能详情",
install_catalog: "将目录技能安装到沙箱",
},
+ automation: {
+ list: "获取自动化列表",
+ create: "创建自动化",
+ validate_trigger: "校验运行时间",
+ get: "获取自动化详情",
+ update: "更新自动化",
+ delete: "删除自动化",
+ pause: "暂停自动化",
+ resume: "恢复自动化",
+ run_now: "立即运行自动化",
+ list_runs: "获取自动化运行记录",
+ },
session: {
list: "获取会话列表",
},
@@ -8320,6 +8533,8 @@ export default {
revokeFailed: '撤销失败',
loadFailed: '加载失败',
},
+ automationTask: '自动化',
+ automationOpen: '打开自动化「{name}」',
moreActions: '更多对话操作',
toggleSandboxPanel: '沙箱终端',
copySessionId: '复制会话 ID',
@@ -8401,6 +8616,7 @@ export default {
sessionUnread: '有新回复',
knowledgeBase: '知识库',
agents: '智能体',
+ automations: '自动化',
artifacts: '产物',
organizations: '共享空间',
newChat: '新对话',
diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts
index 7a3452346..e62fadb2f 100644
--- a/frontend/src/i18n/locales/zh-TW.ts
+++ b/frontend/src/i18n/locales/zh-TW.ts
@@ -124,6 +124,207 @@ export default {
"historyModels": "修改了 {count} 個模型",
"historyNoOverrides": "無管理員修改",
},
+ automation: {
+ title: '自動化',
+ description: '讓智慧代理按排程以你的身分執行任務,結果與待審批事項會通知你。',
+ add: '新增自動化',
+ addHint: '也可以直接請 WeKnora 助手幫你建立',
+ paused: '已暫停',
+ nextRunAt: '下次 {time}',
+ notScheduled: '未排程',
+ agentUnavailable: '智慧代理不可用',
+ deleteTitle: '刪除自動化',
+ deleteBody: '將停止進行中的執行,並刪除「{name}」的執行紀錄、對話與長期授權。此操作無法復原。',
+ fields: {
+ name: '名稱',
+ agent: '執行智慧代理',
+ instruction: '任務',
+ schedule: '執行時間',
+ timezone: '時區',
+ accessLevel: '執行權限',
+ sessionMode: '對話形式',
+ carryLastResult: '把上次成功的結果帶入本次對話',
+ overlapPolicy: '上次仍在執行時',
+ misfirePolicy: '錯過的執行',
+ approvalTimeout: '審批等待期限',
+ maxDuration: '單次執行時長上限',
+ notifyOnSuccess: '成功時也通知',
+ nextRun: '下次執行',
+ enabled: '啟用',
+ },
+ editor: {
+ createTitle: '新增自動化',
+ editTitle: '編輯自動化',
+ namePlaceholder: '例如:每日知識庫週報',
+ instructionPlaceholder: '寫清楚要做什麼、用哪些資料、結果如何輸出',
+ variablesHint: '可用變數:',
+ unattendedHint: '執行時無人在場,智慧代理不能向你提問;需要審批的操作會暫停並通知你。',
+ nameDesc: '在列表和通知中顯示,方便你認出這項任務',
+ agentDesc: '由哪個智慧體執行任務,它的知識庫、工具和技能都可用',
+ frequency: '重複頻率',
+ weekdays: '星期',
+ dayOfMonthDesc: '當月沒有這一天時,在最後一天執行',
+ runAt: '執行時間',
+ cron: 'Cron 表達式',
+ timeOfDay: '時間',
+ timezoneDesc: '依此時區的鐘點執行,夏令時間會自動換算',
+ previewEmpty: '設定好時間後,這裡會顯示接下來幾次的執行時間',
+ carryDesc: '新對話開頭附上上次成功執行的結果,適合做增量彙總',
+ misfireDesc: '服務停機期間錯過的執行,恢復後如何處理',
+ maxDurationDesc: '超過這個時長仍未完成,本次執行會被終止',
+ navGroups: {
+ task: '任務',
+ run: '執行',
+ },
+ sections: {
+ basic: {
+ title: '基本資訊',
+ desc: '為任務命名,選擇執行的智慧體,並寫下要做的事。',
+ },
+ schedule: {
+ title: '執行時間',
+ desc: '設定任務何時執行,兩次執行至少間隔 5 分鐘。',
+ },
+ execution: {
+ title: '執行方式',
+ desc: '執行時可以做哪些修改、在哪個對話中進行,以及重疊和錯過時的處理。',
+ },
+ notify: {
+ title: '審批與通知',
+ desc: '執行結果和待審批的操作會出現在右上角的通知中。',
+ },
+ },
+ sessionModeDesc: {
+ per_run: '每次執行開一個新對話,互不影響',
+ persistent: '所有執行都在同一個對話中,智慧體能看到先前的內容',
+ },
+ errors: {
+ name: '請填寫名稱',
+ instruction: '請填寫要執行的任務',
+ schedule: '請設定有效的執行時間',
+ },
+ approvalTimeoutHelp: '超過期限仍未審批,本次執行記為失敗',
+ notifyHint: '失敗、等待審批與自動暫停總會通知你',
+ access: {
+ read_only: '只檢視,不做任何修改。',
+ confirm: '每次修改前暫停並通知你審批;可在詳情裡把常用操作設為長期授權。',
+ auto_write: '可復原的修改直接執行;刪除等操作仍暫停等待審批。',
+ },
+ },
+ schedule: {
+ kinds: {
+ daily: '每天',
+ weekdays: '工作日',
+ weekly: '每週',
+ monthly: '每月',
+ hourly: '每小時',
+ once: '僅一次',
+ custom: '自訂 cron',
+ },
+ atMinute: '每小時的第幾分鐘',
+ dayOfMonth: '每月幾號',
+ pickTime: '選擇時間',
+ customHint: '五段式:分 時 日 月 週,例如 0 9 * * 1-5 表示工作日 9:00。最短間隔 5 分鐘。',
+ nextRuns: '接下來:',
+ invalid: '觸發時間不合法',
+ describe: {
+ hourly: '每小時第 {minute} 分',
+ daily: '每天 {time}',
+ weekdays: '工作日 {time}',
+ weekly: '每週 {days} {time}',
+ monthly: '每月 {day} 日 {time}',
+ once: '僅在 {at}',
+ custom: 'cron:{expr}',
+ everyMinutes: '每 {n} 分鐘',
+ everyHours: '每 {n} 小時',
+ },
+ },
+ sessionMode: {
+ per_run: '每次新對話',
+ persistent: '始終同一對話',
+ },
+ overlap: {
+ skip: '跳過本次',
+ queue: '排隊,等上次結束後執行',
+ },
+ misfire: {
+ skip: '跳過',
+ run_once: '恢復後補跑一次',
+ },
+ units: {
+ hours: '小時',
+ minutes: '分鐘',
+ },
+ status: {
+ queued: '排隊中',
+ running: '執行中',
+ awaiting_approval: '等待審批',
+ succeeded: '成功',
+ failed: '失敗',
+ cancelled: '已停止',
+ skipped: '已跳過',
+ needs_attention: '需要檢查',
+ paused: '已暫停',
+ },
+ runTrigger: {
+ schedule: '按排程',
+ manual: '手動',
+ misfire: '補跑',
+ },
+ actions: {
+ runNow: '立即執行',
+ pause: '暫停',
+ resume: '恢復',
+ review: '去審批',
+ openConversation: '檢視對話',
+ stop: '停止',
+ },
+ detail: {
+ overview: '概覽',
+ lastRun: '上次執行',
+ pausedBecause: '已暫停:{reason}',
+ runs: '執行紀錄',
+ noRuns: '還沒有執行過',
+ stopping: '正在停止',
+ grants: '長期授權',
+ task: '任務內容',
+ durationSeconds: '{n} 秒',
+ durationMinutes: '{n} 分鐘',
+ },
+ grants: {
+ intro: '這裡的操作在以後的執行中無需再次審批。只針對具體資源;更換智慧代理或你的空間角色變化後自動失效。需要每次審批的工具不會出現在這裡。',
+ active: '已授權',
+ none: '暫無長期授權',
+ lapsed: '設定已變化,此授權暫不生效',
+ revoke: '撤銷',
+ candidates: '執行中請求過審批的操作',
+ noCandidates: '還沒有可設為長期授權的操作',
+ allow: '以後都允許',
+ allowTitle: '設為長期授權',
+ allowBody: '以後的執行進行「{label}」時將不再暫停等待審批。',
+ allowDestructiveBody: '「{label}」會刪除或覆寫資料,且無法復原。確認後,以後的執行將直接進行,不再詢問。',
+ },
+ risk: {
+ write: '修改',
+ destructive: '刪除/覆寫',
+ },
+ messages: {
+ queued: '已開始執行',
+ notFound: '自動化不存在或已刪除',
+ },
+ },
+ notifications: {
+ title: '通知',
+ markAllRead: '全部已讀',
+ pendingInvitations: '{count} 個待處理邀請',
+ empty: '暫無通知',
+ kinds: {
+ automation_succeeded: '自動化已完成',
+ automation_failed: '自動化失敗',
+ automation_awaiting_approval: '自動化等待審批',
+ automation_paused: '自動化已暫停',
+ },
+ },
toolbox: {
"title": "工具箱",
"description": "管理智慧代理可用的技能、外部工具和瀏覽器連結。",
@@ -2091,6 +2292,18 @@ export default {
get_catalog: "取得工作空間技能詳細資訊",
install_catalog: "將目錄技能安裝至沙箱",
},
+ automation: {
+ list: "取得自動化列表",
+ create: "建立自動化",
+ validate_trigger: "檢查執行時間",
+ get: "取得自動化詳情",
+ update: "更新自動化",
+ delete: "刪除自動化",
+ pause: "暫停自動化",
+ resume: "恢復自動化",
+ run_now: "立即執行自動化",
+ list_runs: "取得自動化執行記錄",
+ },
session: {
list: "取得對話清單",
},
@@ -8320,6 +8533,8 @@ export default {
revokeFailed: '撤銷失敗',
loadFailed: '載入失敗',
},
+ automationTask: '自動化',
+ automationOpen: '開啟自動化「{name}」',
moreActions: '更多對話操作',
toggleSandboxPanel: '沙箱終端',
copySessionId: '複製會話 ID',
@@ -8401,6 +8616,7 @@ export default {
sessionUnread: '有新回覆',
knowledgeBase: '知識庫',
agents: '智慧代理',
+ automations: '自動化',
artifacts: '產物',
organizations: '共享空間',
newChat: '新對話',
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index dd6d065b9..80514600d 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -143,6 +143,12 @@ const router = createRouter({
component: () => import("../views/toolbox/Toolbox.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
+ {
+ path: "automations/:automationId?",
+ name: "automationList",
+ component: () => import("../views/automation/AutomationList.vue"),
+ meta: { requiresInit: true, requiresAuth: true }
+ },
{
path: "agents",
name: "agentList",
diff --git a/frontend/src/stores/menu.ts b/frontend/src/stores/menu.ts
index b8e611019..b66ae0427 100644
--- a/frontend/src/stores/menu.ts
+++ b/frontend/src/stores/menu.ts
@@ -34,6 +34,7 @@ export const useMenuStore = defineStore('menuStore', () => {
// Artifacts only exist where skills run in a sandbox.
{ title: '', titleKey: 'menu.artifacts', icon: 'artifact', path: 'artifacts', requiredCapability: 'settings.sandbox' },
{ title: '', titleKey: 'menu.agents', icon: 'agent', path: 'agents', requiredCapability: 'agents' },
+ { title: '', titleKey: 'menu.automations', icon: 'automation', path: 'automations' },
{ title: '', titleKey: 'toolbox.title', icon: 'toolbox', path: 'toolbox' },
{ title: '', titleKey: 'menu.organizations', icon: 'organization', path: 'organizations', requiredCapability: 'organizations' },
{ title: '', titleKey: 'menu.settings', icon: 'setting', path: 'settings' },
diff --git a/frontend/src/utils/assistantPageLink.test.ts b/frontend/src/utils/assistantPageLink.test.ts
index d9a70e5e6..67fcbd88a 100644
--- a/frontend/src/utils/assistantPageLink.test.ts
+++ b/frontend/src/utils/assistantPageLink.test.ts
@@ -17,6 +17,9 @@ test('links use the deep links each page reads', () => {
assert.deepEqual(pageLinkLocation(link({ page: 'settings_models', model_id: 'm' })),
{ path: '/platform/settings', query: { section: 'models', model_id: 'm' } })
assert.deepEqual(pageLinkLocation(link({ page: 'mcp_services' })), { path: '/platform/toolbox/mcp', query: {} })
+ assert.deepEqual(pageLinkLocation(link({ page: 'automations', automation_id: 'a/1' })),
+ { path: '/platform/automations/a%2F1', query: {} })
+ assert.deepEqual(pageLinkLocation(link({ page: 'automations' })), { path: '/platform/automations', query: {} })
assert.equal(pageLinkLocation(link({ page: 'agent_editor' })), null, 'a link without its target goes nowhere')
})
diff --git a/frontend/src/utils/assistantPageLink.ts b/frontend/src/utils/assistantPageLink.ts
index 74b64270e..e08799cf8 100644
--- a/frontend/src/utils/assistantPageLink.ts
+++ b/frontend/src/utils/assistantPageLink.ts
@@ -9,7 +9,7 @@ export interface AssistantPageLink {
display_type: 'open_page'
page:
| 'knowledge_base' | 'wiki' | 'agent_editor' | 'settings_models' | 'mcp_services'
- | 'settings' | 'toolbox' | 'agents' | 'knowledge_bases' | 'organizations'
+ | 'settings' | 'toolbox' | 'agents' | 'knowledge_bases' | 'organizations' | 'automations'
label: string
detail?: string
note?: string
@@ -17,6 +17,7 @@ export interface AssistantPageLink {
knowledge_id?: string
wiki_slug?: string
agent_id?: string
+ automation_id?: string
section?: string
/** A tab inside a settings section, e.g. system-global's users. */
panel?: string
@@ -95,6 +96,13 @@ export function pageLinkLocation(link: AssistantPageLink): PageLinkLocation | nu
return { path: '/platform/knowledge-bases', query: {} }
case 'organizations':
return { path: '/platform/organizations', query: {} }
+ case 'automations':
+ return {
+ path: link.automation_id
+ ? `/platform/automations/${encodeURIComponent(link.automation_id)}`
+ : '/platform/automations',
+ query: {},
+ }
default:
return null
}
diff --git a/frontend/src/utils/automationSchedule.test.ts b/frontend/src/utils/automationSchedule.test.ts
new file mode 100644
index 000000000..aab280ab4
--- /dev/null
+++ b/frontend/src/utils/automationSchedule.test.ts
@@ -0,0 +1,73 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+
+import {
+ describeTrigger,
+ scheduleFormFromTrigger,
+ triggerFromScheduleForm,
+ wallClockToISO,
+ zonedWallClock,
+ defaultScheduleForm,
+} from './automationSchedule'
+
+test('presets round-trip through cron', () => {
+ const cases = [
+ { kind: 'hourly', expr: '15 * * * *' },
+ { kind: 'daily', expr: '30 9 * * *' },
+ { kind: 'weekdays', expr: '0 8 * * 1-5' },
+ { kind: 'weekly', expr: '0 18 * * 1,5' },
+ { kind: 'monthly', expr: '0 7 1 * *' },
+ ]
+ for (const { kind, expr } of cases) {
+ const form = scheduleFormFromTrigger({ type: 'cron', expr, timezone: 'Asia/Shanghai' })
+ assert.equal(form.kind, kind, expr)
+ assert.deepEqual(triggerFromScheduleForm(form, 'Asia/Shanghai'), { type: 'cron', expr, timezone: 'Asia/Shanghai' })
+ }
+})
+
+test('expressions outside the presets stay custom', () => {
+ for (const expr of ['*/30 * * * *', '0 9 * * MON', '0 0 9 * * *', '@daily', '0 9 1 1 *']) {
+ const form = scheduleFormFromTrigger({ type: 'cron', expr })
+ assert.equal(form.kind, 'custom', expr)
+ assert.equal(triggerFromScheduleForm(form, 'UTC')?.expr, expr)
+ }
+})
+
+test('incomplete forms give no trigger', () => {
+ assert.equal(triggerFromScheduleForm({ ...defaultScheduleForm(), kind: 'weekly', days: [] }, 'UTC'), null)
+ assert.equal(triggerFromScheduleForm({ ...defaultScheduleForm(), kind: 'custom', expr: ' ' }, 'UTC'), null)
+ assert.equal(triggerFromScheduleForm({ ...defaultScheduleForm(), kind: 'once', at: '' }, 'UTC'), null)
+})
+
+test('once triggers use wall-clock time in their timezone', () => {
+ assert.equal(wallClockToISO('2026-03-01 09:00', 'Asia/Shanghai'), '2026-03-01T01:00:00.000Z')
+ // New York is UTC-5 in winter and UTC-4 in summer.
+ assert.equal(wallClockToISO('2026-01-15 09:00', 'America/New_York'), '2026-01-15T14:00:00.000Z')
+ assert.equal(wallClockToISO('2026-07-15 09:00', 'America/New_York'), '2026-07-15T13:00:00.000Z')
+ assert.equal(zonedWallClock('2026-07-15T13:00:00Z', 'America/New_York'), '2026-07-15 09:00')
+ assert.equal(wallClockToISO('soon', 'UTC'), '')
+
+ const trigger = triggerFromScheduleForm({ ...defaultScheduleForm(), kind: 'once', at: '2026-03-01 09:00' }, 'Asia/Shanghai')
+ assert.deepEqual(trigger, { type: 'once', at: '2026-03-01T01:00:00.000Z', timezone: 'Asia/Shanghai' })
+ assert.equal(scheduleFormFromTrigger(trigger!).at, '2026-03-01 09:00')
+})
+
+test('describeTrigger names the schedule', () => {
+ const t = (key: string, params?: Record<string, unknown>) => `${key}${params ? JSON.stringify(params) : ''}`
+ assert.equal(
+ describeTrigger({ type: 'cron', expr: '5 9 * * 1,3' }, t, 'en-US'),
+ 'automation.schedule.describe.weekly{"days":"Mon, Wed","time":"09:05"}',
+ )
+ assert.equal(
+ describeTrigger({ type: 'cron', expr: '*/10 * * * *' }, t, 'en-US'),
+ 'automation.schedule.describe.everyMinutes{"n":10}',
+ )
+ assert.equal(
+ describeTrigger({ type: 'cron', expr: '0 */2 * * *' }, t, 'en-US'),
+ 'automation.schedule.describe.everyHours{"n":2}',
+ )
+ assert.equal(
+ describeTrigger({ type: 'cron', expr: '*/10 9-17 * * *' }, t, 'en-US'),
+ 'automation.schedule.describe.custom{"expr":"*/10 9-17 * * *"}',
+ )
+})
diff --git a/frontend/src/utils/automationSchedule.ts b/frontend/src/utils/automationSchedule.ts
new file mode 100644
index 000000000..28b5d4374
--- /dev/null
+++ b/frontend/src/utils/automationSchedule.ts
@@ -0,0 +1,215 @@
+import type { AutomationTrigger } from '@/api/automation'
+
+// The editor offers a few schedule shapes and falls back to a raw cron
+// expression for anything else. Cron here is the server's five-field form,
+// minute first, evaluated in the trigger's timezone.
+
+export type ScheduleKind = 'hourly' | 'daily' | 'weekdays' | 'weekly' | 'monthly' | 'once' | 'custom'
+
+export interface ScheduleForm {
+ kind: ScheduleKind
+ minute: number
+ hour: number
+ /** Days of the week for weekly, 0 = Sunday. */
+ days: number[]
+ /** Day of the month for monthly. */
+ day: number
+ /** Wall-clock time of a once trigger in the timezone, "YYYY-MM-DD HH:mm". */
+ at: string
+ /** Expression of a custom trigger. */
+ expr: string
+}
+
+export function defaultScheduleForm(): ScheduleForm {
+ return { kind: 'daily', minute: 0, hour: 9, days: [1], day: 1, at: '', expr: '' }
+}
+
+export function browserTimezone(): string {
+ try {
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'
+ } catch {
+ return 'UTC'
+ }
+}
+
+export function timezoneOptions(current?: string): string[] {
+ let zones: string[] = []
+ try {
+ zones = (Intl as unknown as { supportedValuesOf?: (key: string) => string[] }).supportedValuesOf?.('timeZone') ?? []
+ } catch {
+ zones = []
+ }
+ const set = new Set(zones.length ? zones : ['UTC', 'Asia/Shanghai', 'America/New_York', 'Europe/London'])
+ set.add('UTC')
+ if (current) set.add(current)
+ return [...set]
+}
+
+const NUM = /^\d{1,2}$/
+
+function num(field: string, min: number, max: number): number | null {
+ if (!NUM.test(field)) return null
+ const n = Number(field)
+ return n >= min && n <= max ? n : null
+}
+
+/** Read a trigger back into the editor; anything the presets cannot express is custom. */
+export function scheduleFormFromTrigger(trigger: AutomationTrigger | undefined): ScheduleForm {
+ const form = defaultScheduleForm()
+ if (!trigger) return form
+ if (trigger.type === 'once') {
+ form.kind = 'once'
+ form.at = trigger.at ? zonedWallClock(trigger.at, trigger.timezone) : ''
+ return form
+ }
+ const expr = (trigger.expr || '').trim()
+ form.expr = expr
+ form.kind = 'custom'
+ const f = expr.split(/\s+/)
+ if (f.length !== 5) return form
+ const [mi, h, dom, mon, dow] = f
+ const minute = num(mi, 0, 59)
+ if (minute === null || mon !== '*') return form
+ if (h === '*' && dom === '*' && dow === '*') {
+ return { ...form, kind: 'hourly', minute }
+ }
+ const hour = num(h, 0, 23)
+ if (hour === null) return form
+ if (dom === '*' && dow === '*') return { ...form, kind: 'daily', minute, hour }
+ if (dom === '*' && dow === '1-5') return { ...form, kind: 'weekdays', minute, hour }
+ if (dom === '*' && /^[0-6](,[0-6])*$/.test(dow)) {
+ const days = [...new Set(dow.split(',').map(Number))].sort((a, b) => a - b)
+ return { ...form, kind: 'weekly', minute, hour, days }
+ }
+ const day = num(dom, 1, 31)
+ if (day !== null && dow === '*') return { ...form, kind: 'monthly', minute, hour, day }
+ return form
+}
+
+/** The trigger the editor describes, or null while it is incomplete. */
+export function triggerFromScheduleForm(form: ScheduleForm, timezone: string): AutomationTrigger | null {
+ const tz = timezone || 'UTC'
+ const m = form.minute
+ const h = form.hour
+ let expr = ''
+ switch (form.kind) {
+ case 'hourly':
+ expr = `${m} * * * *`
+ break
+ case 'daily':
+ expr = `${m} ${h} * * *`
+ break
+ case 'weekdays':
+ expr = `${m} ${h} * * 1-5`
+ break
+ case 'weekly':
+ if (!form.days.length) return null
+ expr = `${m} ${h} * * ${[...new Set(form.days)].sort((a, b) => a - b).join(',')}`
+ break
+ case 'monthly':
+ expr = `${m} ${h} ${form.day} * *`
+ break
+ case 'custom':
+ expr = form.expr.trim()
+ if (!expr) return null
+ break
+ case 'once': {
+ const at = wallClockToISO(form.at, tz)
+ return at ? { type: 'once', at, timezone: tz } : null
+ }
+ }
+ return { type: 'cron', expr, timezone: tz }
+}
+
+function zoneParts(date: Date, timeZone: string) {
+ const parts = new Intl.DateTimeFormat('en-US', {
+ timeZone,
+ hourCycle: 'h23',
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit',
+ }).formatToParts(date)
+ const get = (type: string) => Number(parts.find((p) => p.type === type)?.value ?? 0)
+ return { y: get('year'), mo: get('month'), d: get('day'), h: get('hour') % 24, mi: get('minute'), s: get('second') }
+}
+
+function offsetMs(date: Date, timeZone: string): number {
+ const p = zoneParts(date, timeZone)
+ return Date.UTC(p.y, p.mo - 1, p.d, p.h, p.mi, p.s) - Math.floor(date.getTime() / 1000) * 1000
+}
+
+const WALL = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})/
+
+/** RFC 3339 instant of wall-clock time local in timeZone, or '' if local is malformed. */
+export function wallClockToISO(local: string, timeZone: string): string {
+ const match = WALL.exec(local || '')
+ if (!match) return ''
+ const [, y, mo, d, h, mi] = match.map(Number)
+ const guess = Date.UTC(y, mo - 1, d, h, mi)
+ let t = guess - offsetMs(new Date(guess), timeZone)
+ // A second pass settles instants near a daylight-saving change.
+ t = guess - offsetMs(new Date(t), timeZone)
+ return new Date(t).toISOString()
+}
+
+/** Wall-clock "YYYY-MM-DD HH:mm" of iso in timeZone. */
+export function zonedWallClock(iso: string, timeZone?: string): string {
+ const date = new Date(iso)
+ if (Number.isNaN(date.getTime())) return ''
+ const p = zoneParts(date, timeZone || 'UTC')
+ const pad = (n: number) => String(n).padStart(2, '0')
+ return `${p.y}-${pad(p.mo)}-${pad(p.d)} ${pad(p.h)}:${pad(p.mi)}`
+}
+
+/** iso as a medium date and short time in timeZone. */
+export function formatInZone(iso: string | null | undefined, timeZone: string | undefined, locale: string): string {
+ if (!iso) return ''
+ const date = new Date(iso)
+ if (Number.isNaN(date.getTime())) return ''
+ try {
+ return new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'short', timeZone: timeZone || 'UTC' })
+ .format(date)
+ } catch {
+ return date.toLocaleString(locale)
+ }
+}
+
+export function weekdayName(day: number, locale: string): string {
+ // 2023-01-01 was a Sunday.
+ return new Intl.DateTimeFormat(locale, { weekday: 'short', timeZone: 'UTC' }).format(new Date(Date.UTC(2023, 0, 1 + day)))
+}
+
+type Translate = (key: string, params?: Record<string, unknown>) => string
+
+/** A short sentence for when trigger runs, such as "Every day at 09:00". */
+export function describeTrigger(trigger: AutomationTrigger, t: Translate, locale: string): string {
+ const form = scheduleFormFromTrigger(trigger)
+ const time = `${String(form.hour).padStart(2, '0')}:${String(form.minute).padStart(2, '0')}`
+ switch (form.kind) {
+ case 'hourly':
+ return t('automation.schedule.describe.hourly', { minute: String(form.minute).padStart(2, '0') })
+ case 'daily':
+ return t('automation.schedule.describe.daily', { time })
+ case 'weekdays':
+ return t('automation.schedule.describe.weekdays', { time })
+ case 'weekly':
+ return t('automation.schedule.describe.weekly', {
+ days: form.days.map((d) => weekdayName(d, locale)).join(', '),
+ time,
+ })
+ case 'monthly':
+ return t('automation.schedule.describe.monthly', { day: form.day, time })
+ case 'once':
+ return t('automation.schedule.describe.once', { at: formatInZone(trigger.at, trigger.timezone, locale) })
+ default: {
+ const every = /^\*\/(\d+) \* \* \* \*$/.exec(form.expr.trim())
+ if (every) return t('automation.schedule.describe.everyMinutes', { n: Number(every[1]) })
+ const hours = /^0 \*\/(\d+) \* \* \*$/.exec(form.expr.trim())
+ if (hours) return t('automation.schedule.describe.everyHours', { n: Number(hours[1]) })
+ return t('automation.schedule.describe.custom', { expr: form.expr })
+ }
+ }
+}
diff --git a/frontend/src/utils/catalogToolDisplay.test.ts b/frontend/src/utils/catalogToolDisplay.test.ts
index 7cf3a64d7..c44851c3c 100644
--- a/frontend/src/utils/catalogToolDisplay.test.ts
+++ b/frontend/src/utils/catalogToolDisplay.test.ts
@@ -26,6 +26,9 @@ test('operation titles follow the UI locale for live events, history, and status
const { global } = createI18n({ legacy: false, locale: 'zh-CN', messages: LOCALE_BUNDLES })
const event = { tool_name: 'run_operation', arguments: { operation: 'model.list' } }
assert.equal(getCatalogToolTitle(global.t, event), '执行操作:获取模型列表')
+ assert.equal(getCatalogToolTitle(global.t, {
+ tool_name: 'run_operation', arguments: { operation: 'automation.validate_trigger' },
+ }), '执行操作:校验运行时间')
assert.equal(getCatalogToolTitle(global.t, {
tool_name: 'run_operation', output: JSON.stringify({ operation: 'agent.list' }),
}), '执行操作:获取智能体列表')
diff --git a/frontend/src/views/automation/AutomationDetail.vue b/frontend/src/views/automation/AutomationDetail.vue
new file mode 100644
index 000000000..8464c0ebe
--- /dev/null
+++ b/frontend/src/views/automation/AutomationDetail.vue
@@ -0,0 +1,607 @@
+<template>
+ <SettingDrawer :visible="visible" :title="automation?.name || ''" icon="time" width="640px" :min-width="480"
+ :max-width="960" storage-key="setting-drawer:width:automation-detail" class="automation-detail-drawer"
+ @update:visible="(v: boolean) => !v && close()">
+ <template v-if="automation" #subtitle>
+ <span class="automation-detail__subtitle">
+ <AutomationStatusTag v-if="!automation.enabled" status="paused" />
+ <span>{{ describeTrigger(automation.trigger, t, locale) }} · {{ automation.trigger.timezone || 'UTC' }}</span>
+ </span>
+ </template>
+
+ <template v-if="automation">
+ <t-alert v-if="!automation.enabled && automation.paused_reason" theme="warning" class="automation-detail__alert"
+ :message="t('automation.detail.pausedBecause', { reason: automation.paused_reason })" />
+
+ <section class="setting-drawer__section">
+ <h4 class="setting-drawer__section-title">{{ t('automation.detail.overview') }}</h4>
+ <dl class="automation-detail__fields">
+ <div class="automation-detail__field">
+ <dt>{{ t('automation.fields.nextRun') }}</dt>
+ <dd>{{ automation.enabled && automation.next_run_at ? when(automation.next_run_at) : t('automation.notScheduled') }}</dd>
+ </div>
+ <div class="automation-detail__field">
+ <dt>{{ t('automation.detail.lastRun') }}</dt>
+ <dd class="automation-detail__inline">
+ <template v-if="automation.last_run_at">
+ {{ when(automation.last_run_at) }}
+ <AutomationStatusTag v-if="automation.last_run_status" :status="automation.last_run_status" />
+ </template>
+ <template v-else>{{ t('automation.detail.noRuns') }}</template>
+ </dd>
+ </div>
+ <div class="automation-detail__field">
+ <dt>{{ t('automation.fields.agent') }}</dt>
+ <dd>{{ agentName }}</dd>
+ </div>
+ <div class="automation-detail__field">
+ <dt>{{ t('automation.fields.accessLevel') }}</dt>
+ <dd>{{ t(`assistant.access.levels.${automation.access_level}.label`) }}</dd>
+ </div>
+ <div class="automation-detail__field">
+ <dt>{{ t('automation.fields.sessionMode') }}</dt>
+ <dd>{{ t(`automation.sessionMode.${automation.session_mode}`) }}</dd>
+ </div>
+ </dl>
+ </section>
+
+ <section class="setting-drawer__section">
+ <h4 class="setting-drawer__section-title">
+ {{ t('automation.detail.task') }}
+ <t-button v-if="instructionLong" size="small" variant="text" theme="primary" class="automation-detail__toggle"
+ @click="instructionOpen = !instructionOpen">
+ {{ instructionOpen ? t('common.collapse') : t('common.expand') }}
+ </t-button>
+ </h4>
+ <p class="automation-detail__instruction" :class="{ 'is-clamped': instructionLong && !instructionOpen }">
+ {{ automation.instruction }}
+ </p>
+ </section>
+
+ <section class="setting-drawer__section">
+ <h4 class="setting-drawer__section-title">
+ {{ t('automation.detail.runs') }}
+ <span v-if="runsTotal" class="automation-detail__count">{{ runsTotal }}</span>
+ </h4>
+ <div v-if="runsLoading && !runs.length" class="automation-detail__loading"><t-loading size="small" /></div>
+ <p v-else-if="!runs.length" class="automation-detail__muted">{{ t('automation.detail.noRuns') }}</p>
+ <ul v-else class="automation-detail__list">
+ <li v-for="run in runs" :key="run.id" class="automation-run"
+ :class="{ 'is-focused': run.id === focusRunId, 'is-link': !!run.session_id }"
+ :role="run.session_id ? 'button' : undefined" :tabindex="run.session_id ? 0 : undefined"
+ @click="run.session_id && openRun(run)"
+ @keydown.enter="run.session_id && openRun(run)">
+ <span class="automation-run__dot" :class="`is-${run.status}`" aria-hidden="true" />
+ <div class="automation-run__body">
+ <div class="automation-run__head">
+ <span class="automation-run__time">{{ when(run.scheduled_at) }}</span>
+ <span class="automation-run__status">{{ t(`automation.status.${run.status}`) }}</span>
+ <span class="automation-run__meta">
+ {{ t(`automation.runTrigger.${run.trigger_kind}`) }}<template v-if="duration(run)"> · {{ duration(run) }}</template>
+ </span>
+ <t-link v-if="cancellable(run)" theme="danger" hover="color" class="automation-run__stop"
+ :disabled="run.cancel_requested" @click.stop="cancel(run)">
+ {{ run.cancel_requested ? t('automation.detail.stopping') : t('automation.actions.stop') }}
+ </t-link>
+ </div>
+ <p v-if="run.error" class="automation-run__text is-error">{{ run.error }}</p>
+ <p v-else-if="run.answer" class="automation-run__text">{{ run.answer }}</p>
+ </div>
+ <t-icon v-if="run.session_id" name="chevron-right" size="16px" class="automation-run__chevron" />
+ </li>
+ </ul>
+ <div v-if="runs.length < runsTotal" class="automation-detail__more">
+ <t-button size="small" variant="text" :loading="runsLoading" @click="loadRuns(false)">
+ {{ t('common.loadMore') }}
+ </t-button>
+ </div>
+ </section>
+
+ <section class="setting-drawer__section">
+ <h4 class="setting-drawer__section-title">{{ t('automation.detail.grants') }}</h4>
+ <p class="automation-detail__muted">{{ t('automation.grants.intro') }}</p>
+ <div v-if="grantsLoading" class="automation-detail__loading"><t-loading size="small" /></div>
+ <template v-else>
+ <ul v-if="grants.length" class="automation-detail__list">
+ <li v-for="grant in grants" :key="grant.id" class="automation-grant">
+ <span class="automation-grant__label">{{ grant.label || grant.grant_key }}</span>
+ <t-tag size="small" variant="light" :theme="grant.risk === 'destructive' ? 'danger' : 'warning'">
+ {{ t(`automation.risk.${grant.risk}`, grant.risk) }}
+ </t-tag>
+ <span v-if="grant.lapse" class="automation-grant__lapse">{{ t('automation.grants.lapsed') }}</span>
+ <t-link theme="danger" hover="color" class="automation-grant__action" @click="revoke(grant)">
+ {{ t('automation.grants.revoke') }}
+ </t-link>
+ </li>
+ </ul>
+ <template v-if="candidates.length">
+ <div class="automation-detail__subhead">{{ t('automation.grants.candidates') }}</div>
+ <ul class="automation-detail__list">
+ <li v-for="candidate in candidates" :key="candidate.prompt_id" class="automation-grant">
+ <span class="automation-grant__label">{{ candidate.label || candidate.tool }}</span>
+ <t-tag size="small" variant="light" :theme="candidate.risk === 'destructive' ? 'danger' : 'warning'">
+ {{ t(`automation.risk.${candidate.risk}`, candidate.risk) }}
+ </t-tag>
+ <span v-if="candidate.service_name" class="automation-grant__meta">{{ candidate.service_name }}</span>
+ <t-link theme="primary" hover="color" class="automation-grant__action" @click="allow(candidate)">
+ {{ t('automation.grants.allow') }}
+ </t-link>
+ </li>
+ </ul>
+ </template>
+ <p v-if="!grants.length && !candidates.length" class="automation-detail__muted">{{ t('automation.grants.none') }}</p>
+ </template>
+ </section>
+ </template>
+
+ <template v-if="automation" #footer-left>
+ <t-button variant="outline" :loading="busy === 'toggle'" @click="toggle">
+ {{ automation.enabled ? t('automation.actions.pause') : t('automation.actions.resume') }}
+ </t-button>
+ <t-button variant="outline" @click="emit('edit', automation)">{{ t('common.edit') }}</t-button>
+ </template>
+ <template v-if="automation" #footer-right>
+ <t-button theme="primary" :loading="busy === 'run'" @click="runNow">{{ t('automation.actions.runNow') }}</t-button>
+ </template>
+ </SettingDrawer>
+</template>
+
+<script setup lang="ts">
+import { computed, onBeforeUnmount, ref, watch } from 'vue'
+import { useRouter } from 'vue-router'
+import { useI18n } from 'vue-i18n'
+import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next'
+import {
+ addAutomationGrant,
+ cancelAutomationRun,
+ listAutomationGrantCandidates,
+ listAutomationGrants,
+ listAutomationRuns,
+ pauseAutomation,
+ resumeAutomation,
+ revokeAutomationGrant,
+ runAutomationNow,
+ type Automation,
+ type AutomationGrant,
+ type AutomationGrantCandidate,
+ type AutomationRun,
+} from '@/api/automation'
+import { describeTrigger, formatInZone } from '@/utils/automationSchedule'
+import SettingDrawer from '@/components/settings/SettingDrawer.vue'
+import AutomationStatusTag from './AutomationStatusTag.vue'
+
+const props = defineProps<{
+ visible: boolean
+ automation: Automation | null
+ agentName: string
+ focusRunId?: string
+}>()
+const emit = defineEmits<{
+ 'update:visible': [value: boolean]
+ changed: [value: Automation]
+ edit: [value: Automation]
+}>()
+
+const { t, locale } = useI18n()
+const router = useRouter()
+
+const PAGE = 20
+const busy = ref<'' | 'run' | 'toggle'>('')
+const instructionOpen = ref(false)
+const runs = ref<AutomationRun[]>([])
+const runsTotal = ref(0)
+const runsPage = ref(0)
+const runsLoading = ref(false)
+const grants = ref<AutomationGrant[]>([])
+const candidates = ref<AutomationGrantCandidate[]>([])
+const grantsLoading = ref(false)
+let poll: ReturnType<typeof setInterval> | undefined
+
+const instructionLong = computed(() => {
+ const text = props.automation?.instruction ?? ''
+ return text.length > 160 || text.split('\n').length > 4
+})
+
+const when = (iso: string | null) => formatInZone(iso, props.automation?.trigger.timezone, locale.value)
+const cancellable = (run: AutomationRun) =>
+ run.status === 'queued' || run.status === 'running' || run.status === 'awaiting_approval'
+
+function duration(run: AutomationRun): string {
+ if (!run.started_at || !run.finished_at) return ''
+ const seconds = Math.round((Date.parse(run.finished_at) - Date.parse(run.started_at)) / 1000)
+ if (!Number.isFinite(seconds) || seconds < 0) return ''
+ if (seconds < 60) return t('automation.detail.durationSeconds', { n: Math.max(1, seconds) })
+ return t('automation.detail.durationMinutes', { n: Math.round(seconds / 60) })
+}
+
+function close() {
+ emit('update:visible', false)
+}
+
+async function loadRuns(reset: boolean) {
+ const a = props.automation
+ if (!a) return
+ runsLoading.value = true
+ try {
+ const page = reset ? 1 : runsPage.value + 1
+ const res = await listAutomationRuns(a.id, page, PAGE)
+ const items = res.data ?? []
+ runs.value = reset ? items : [...runs.value, ...items]
+ runsTotal.value = res.total ?? runs.value.length
+ runsPage.value = page
+ } catch (e: any) {
+ MessagePlugin.error(e?.message || t('common.operationFailed'))
+ } finally {
+ runsLoading.value = false
+ }
+}
+
+// Refresh the first page in place while a run is in flight, so its status
+// moves without the user reopening the drawer.
+async function refreshActive() {
+ const a = props.automation
+ if (!a || runsLoading.value || !runs.value.some(cancellable)) return
+ try {
+ const res = await listAutomationRuns(a.id, 1, PAGE)
+ const fresh = new Map((res.data ?? []).map((run) => [run.id, run]))
+ const known = new Set(runs.value.map((run) => run.id))
+ runs.value = [
+ ...(res.data ?? []).filter((run) => !known.has(run.id)),
+ ...runs.value.map((run) => fresh.get(run.id) ?? run),
+ ]
+ runsTotal.value = res.total ?? runsTotal.value
+ } catch {
+ // The next tick tries again.
+ }
+}
+
+async function loadGrants() {
+ const a = props.automation
+ if (!a) return
+ grantsLoading.value = true
+ try {
+ const [g, c] = await Promise.all([listAutomationGrants(a.id), listAutomationGrantCandidates(a.id)])
+ grants.value = g.data ?? []
+ candidates.value = c.data ?? []
+ } catch (e: any) {
+ MessagePlugin.error(e?.message || t('common.operationFailed'))
+ } finally {
+ grantsLoading.value = false
+ }
+}
+
+watch(() => [props.visible, props.automation?.id] as const, ([open, id]) => {
+ clearInterval(poll)
+ if (!open || !id) return
+ instructionOpen.value = false
+ runs.value = []
+ runsTotal.value = 0
+ grants.value = []
+ candidates.value = []
+ void loadRuns(true)
+ void loadGrants()
+ poll = setInterval(refreshActive, 5000)
+}, { immediate: true })
+
+onBeforeUnmount(() => clearInterval(poll))
+
+async function runNow() {
+ const a = props.automation
+ if (!a) return
+ busy.value = 'run'
+ try {
+ const res = await runAutomationNow(a.id)
+ MessagePlugin.success(t('automation.messages.queued'))
+ if (res.data) {
+ runs.value = [res.data, ...runs.value]
+ runsTotal.value += 1
+ }
+ } catch (e: any) {
+ MessagePlugin.error(e?.message || t('common.operationFailed'))
+ } finally {
+ busy.value = ''
+ }
+}
+
+async function toggle() {
+ const a = props.automation
+ if (!a) return
+ busy.value = 'toggle'
+ try {
+ const res = a.enabled ? await pauseAutomation(a.id) : await resumeAutomation(a.id)
+ emit('changed', res.data)
+ } catch (e: any) {
+ MessagePlugin.error(e?.message || t('common.operationFailed'))
+ } finally {
+ busy.value = ''
+ }
+}
+
+function openRun(run: AutomationRun) {
+ close()
+ void router.push(`/platform/chat/${encodeURIComponent(run.session_id)}`)
+}
+
+async function cancel(run: AutomationRun) {
+ try {
+ const res = await cancelAutomationRun(run.id)
+ runs.value = runs.value.map((r) => (r.id === run.id ? res.data : r))
+ } catch (e: any) {
+ MessagePlugin.error(e?.message || t('common.operationFailed'))
+ }
+}
+
+function allow(candidate: AutomationGrantCandidate) {
+ const a = props.automation
+ if (!a) return
+ const destructive = candidate.risk === 'destructive'
+ const dialog = DialogPlugin.confirm({
+ header: t('automation.grants.allowTitle'),
+ body: t(destructive ? 'automation.grants.allowDestructiveBody' : 'automation.grants.allowBody', {
+ label: candidate.label || candidate.tool,
+ }),
+ theme: destructive ? 'danger' : 'warning',
+ confirmBtn: { content: t('automation.grants.allow'), theme: destructive ? 'danger' : 'primary' },
+ onConfirm: async () => {
+ dialog.hide()
+ try {
+ await addAutomationGrant(a.id, candidate.prompt_id)
+ await loadGrants()
+ } catch (e: any) {
+ MessagePlugin.error(e?.message || t('common.operationFailed'))
+ }
+ },
+ })
+}
+
+async function revoke(grant: AutomationGrant) {
+ try {
+ await revokeAutomationGrant(grant.id)
+ await loadGrants()
+ } catch (e: any) {
+ MessagePlugin.error(e?.message || t('common.operationFailed'))
+ }
+}
+</script>
+
+<style scoped lang="less">
+.automation-detail__subtitle {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+}
+
+.automation-detail__alert {
+ margin-bottom: 12px;
+}
+
+.automation-detail__fields {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ margin: 0;
+}
+
+.automation-detail__field {
+ display: grid;
+ grid-template-columns: 96px minmax(0, 1fr);
+ gap: 12px;
+ align-items: baseline;
+
+ dt {
+ color: var(--td-text-color-placeholder);
+ font-size: var(--app-text-sm);
+ line-height: 1.45;
+ white-space: nowrap;
+ }
+
+ dd {
+ margin: 0;
+ color: var(--td-text-color-primary);
+ font-size: var(--app-text-md);
+ line-height: 1.55;
+ overflow-wrap: anywhere;
+ }
+}
+
+.automation-detail__inline {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.automation-detail__toggle {
+ margin-left: auto;
+}
+
+.automation-detail__count {
+ color: var(--td-text-color-placeholder);
+ font-weight: 400;
+}
+
+.automation-detail__instruction {
+ margin: 0;
+ padding: 12px 14px;
+ border: 1px solid var(--td-component-stroke);
+ border-radius: var(--app-radius-md);
+ background: var(--td-bg-color-container);
+ color: var(--td-text-color-primary);
+ font-size: var(--app-text-md);
+ line-height: 1.6;
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+
+ &.is-clamped {
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 4;
+ line-clamp: 4;
+ overflow: hidden;
+ }
+}
+
+.automation-detail__muted {
+ margin: 0;
+ color: var(--td-text-color-placeholder);
+ font-size: var(--app-text-sm);
+ line-height: 1.5;
+}
+
+.automation-detail__loading,
+.automation-detail__more {
+ display: flex;
+ justify-content: center;
+}
+
+.automation-detail__subhead {
+ color: var(--td-text-color-secondary);
+ font-size: var(--app-text-sm);
+}
+
+.automation-detail__list {
+ margin: 0;
+ padding: 0;
+ border: 1px solid var(--td-component-stroke);
+ border-radius: var(--app-radius-md);
+ list-style: none;
+
+ > li + li {
+ border-top: 1px solid var(--td-component-stroke);
+ }
+}
+
+.automation-run {
+ display: flex;
+ align-items: flex-start;
+ gap: 10px;
+ padding: 10px 14px;
+
+ &.is-link {
+ cursor: pointer;
+
+ &:hover {
+ background: var(--td-bg-color-container-hover);
+ }
+
+ &:focus-visible {
+ outline: 2px solid var(--td-brand-color-focus);
+ outline-offset: -2px;
+ }
+ }
+
+ &.is-focused {
+ background: var(--td-bg-color-container-hover);
+ }
+}
+
+.automation-run__dot {
+ flex-shrink: 0;
+ width: 6px;
+ height: 6px;
+ margin-top: 7px;
+ border-radius: 50%;
+ background: var(--td-text-color-placeholder);
+
+ &.is-succeeded { background: var(--td-success-color); }
+ &.is-failed { background: var(--td-error-color); }
+ &.is-running { background: var(--td-brand-color); }
+ &.is-awaiting_approval,
+ &.is-needs_attention { background: var(--td-warning-color); }
+}
+
+.automation-run__body {
+ flex: 1;
+ min-width: 0;
+}
+
+.automation-run__head {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+}
+
+.automation-run__time {
+ color: var(--td-text-color-primary);
+ font-size: var(--app-text-md);
+ font-variant-numeric: tabular-nums;
+}
+
+.automation-run__status {
+ color: var(--td-text-color-secondary);
+ font-size: var(--app-text-sm);
+ white-space: nowrap;
+}
+
+.automation-run__meta {
+ color: var(--td-text-color-placeholder);
+ font-size: var(--app-text-sm);
+ white-space: nowrap;
+}
+
+.automation-run__stop {
+ margin-left: auto;
+ font-size: var(--app-text-sm);
+}
+
+.automation-run__chevron {
+ flex-shrink: 0;
+ align-self: center;
+ color: var(--td-text-color-placeholder);
+}
+
+.automation-run__text {
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 3;
+ line-clamp: 3;
+ margin: 6px 0 0;
+ overflow: hidden;
+ color: var(--td-text-color-secondary);
+ font-size: var(--app-text-sm);
+ line-height: 1.6;
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+
+ &.is-error {
+ color: var(--td-error-color);
+ }
+}
+
+.automation-grant {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+ padding: 10px 14px;
+}
+
+.automation-grant__label {
+ min-width: 0;
+ overflow: hidden;
+ color: var(--td-text-color-primary);
+ font-size: var(--app-text-md);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.automation-grant__meta,
+.automation-grant__lapse {
+ font-size: var(--app-text-sm);
+ white-space: nowrap;
+}
+
+.automation-grant__meta {
+ color: var(--td-text-color-placeholder);
+}
+
+.automation-grant__lapse {
+ color: var(--td-warning-color);
+}
+
+.automation-grant__action {
+ flex-shrink: 0;
+ margin-left: auto;
+ font-size: var(--app-text-sm);
+}
+</style>
diff --git a/frontend/src/views/automation/AutomationEditor.vue b/frontend/src/views/automation/AutomationEditor.vue
new file mode 100644
index 000000000..412ee9237
--- /dev/null
+++ b/frontend/src/views/automation/AutomationEditor.vue
@@ -0,0 +1,678 @@
+<template>
+ <SettingsModalShell :visible="visible"
+ :title="automation ? t('automation.editor.editTitle') : t('automation.editor.createTitle')"
+ v-model="section" :nav-groups="navGroups" :z-index="1000" @close="modalShell.requestClose">
+ <div class="content-wrapper">
+ <!-- 基本信息 -->
+ <div v-show="section === 'basic'" class="section">
+ <div class="section-header">
+ <h2>{{ t('automation.editor.sections.basic.title') }}</h2>
+ <p class="section-description">{{ t('automation.editor.sections.basic.desc') }}</p>
+ </div>
+ <div class="settings-group">
+ <div class="setting-row">
+ <div class="setting-info">
+ <label>{{ t('automation.fields.name') }}<span class="required">*</span></label>
+ <p class="desc">{{ t('automation.editor.nameDesc') }}</p>
+ </div>
+ <div class="setting-control">
+ <t-input v-model="form.name" :maxlength="100" :placeholder="t('automation.editor.namePlaceholder')" />
+ </div>
+ </div>
+ <div class="setting-row">
+ <div class="setting-info">
+ <label>{{ t('automation.fields.agent') }}</label>
+ <p class="desc">{{ t('automation.editor.agentDesc') }}</p>
+ </div>
+ <div class="setting-control">
+ <t-select v-model="form.agent_id" :loading="agentsLoading" filterable>
+ <t-option v-for="agent in agentOptions" :key="agent.id" :value="agent.id" :label="agent.name" />
+ </t-select>
+ </div>
+ </div>
+ <div class="setting-row setting-row-vertical">
+ <div class="setting-info">
+ <label>{{ t('automation.fields.instruction') }}<span class="required">*</span></label>
+ <p class="desc">{{ t('automation.editor.unattendedHint') }}</p>
+ </div>
+ <div class="setting-control setting-control-full automation-editor__stack">
+ <t-textarea v-model="form.instruction" :autosize="{ minRows: 6, maxRows: 16 }" :maxlength="20000"
+ :placeholder="t('automation.editor.instructionPlaceholder')" />
+ <p class="automation-editor__hint">
+ {{ t('automation.editor.variablesHint') }}
+ <code v-for="tag in VARIABLE_TAGS" :key="tag">{{ tag }}</code>
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- 运行时间 -->
+ <div v-show="section === 'schedule'" class="section">
+ <div class="section-header">
+ <h2>{{ t('automation.editor.sections.schedule.title') }}</h2>
+ <p class="section-description">{{ t('automation.editor.sections.schedule.desc') }}</p>
+ </div>
+ <div class="settings-group">
+ <div class="setting-row setting-row-vertical">
+ <div class="setting-info">
+ <label>{{ t('automation.editor.frequency') }}<span class="required">*</span></label>
+ </div>
+ <div class="setting-control setting-control-full">
+ <t-radio-group v-model="schedule.kind" variant="default-filled">
+ <t-radio-button v-for="kind in KINDS" :key="kind" :value="kind">
+ {{ t(`automation.schedule.kinds.${kind}`) }}
+ </t-radio-button>
+ </t-radio-group>
+ </div>
+ </div>
+
+ <div v-if="schedule.kind === 'weekly'" class="setting-row">
+ <div class="setting-info">
+ <label>{{ t('automation.editor.weekdays') }}</label>
+ </div>
+ <div class="setting-control">
+ <t-checkbox-group v-model="schedule.days" class="automation-editor__days">
+ <t-checkbox v-for="day in WEEK" :key="day" :value="day">{{ weekdayName(day, locale) }}</t-checkbox>
+ </t-checkbox-group>
+ </div>
+ </div>
+
+ <div v-if="schedule.kind === 'monthly'" class="setting-row">
+ <div class="setting-info">
+ <label>{{ t('automation.schedule.dayOfMonth') }}</label>
+ <p class="desc">{{ t('automation.editor.dayOfMonthDesc') }}</p>
+ </div>
+ <div class="setting-control">
+ <t-input-number v-model="schedule.day" :min="1" :max="31" theme="column" />
+ </div>
+ </div>
+
+ <div v-if="schedule.kind === 'hourly'" class="setting-row">
+ <div class="setting-info">
+ <label>{{ t('automation.schedule.atMinute') }}</label>
+ </div>
+ <div class="setting-control">
+ <t-input-number v-model="schedule.minute" :min="0" :max="59" theme="column" />
+ </div>
+ </div>
+
+ <div v-else-if="schedule.kind === 'once'" class="setting-row">
+ <div class="setting-info">
+ <label>{{ t('automation.editor.runAt') }}</label>
+ </div>
+ <div class="setting-control">
+ <t-date-picker v-model="schedule.at" enable-time-picker format="YYYY-MM-DD HH:mm"
+ value-type="YYYY-MM-DD HH:mm" :placeholder="t('automation.schedule.pickTime')" />
+ </div>
+ </div>
+
+ <div v-else-if="schedule.kind === 'custom'" class="setting-row">
+ <div class="setting-info">
+ <label>{{ t('automation.editor.cron') }}</label>
+ <p class="desc">{{ t('automation.schedule.customHint') }}</p>
+ </div>
+ <div class="setting-control">
+ <t-input v-model="schedule.expr" class="automation-editor__mono" placeholder="0 9 * * 1-5" />
+ </div>
+ </div>
+
+ <div v-else class="setting-row">
+ <div class="setting-info">
+ <label>{{ t('automation.editor.timeOfDay') }}</label>
+ </div>
+ <div class="setting-control">
+ <t-time-picker v-model="clock" format="HH:mm" :clearable="false" />
+ </div>
+ </div>
+
+ <div class="setting-row">
+ <div class="setting-info">
+ <label>{{ t('automation.fields.timezone') }}</label>
+ <p class="desc">{{ t('automation.editor.timezoneDesc') }}</p>
+ </div>
+ <div class="setting-control">
+ <t-select v-model="timezone" filterable>
+ <t-option v-for="zone in zones" :key="zone" :value="zone" :label="zone" />
+ </t-select>
+ </div>
+ </div>
+
+ <div class="setting-row setting-row-vertical">
+ <div class="setting-info">
+ <label>{{ t('automation.schedule.nextRuns') }}</label>
+ </div>
+ <div class="setting-control setting-control-full">
+ <div class="automation-editor__preview" :class="{ 'is-error': previewError }" aria-live="polite">
+ <template v-if="previewError">
+ <t-icon name="error-circle" size="16px" /> {{ previewError }}
+ </template>
+ <ul v-else-if="previewRuns.length" class="automation-editor__runs">
+ <li v-for="run in previewRuns" :key="run">
+ <t-icon name="time" size="14px" /> {{ formatInZone(run, timezone, locale) }}
+ </li>
+ </ul>
+ <span v-else-if="previewLoading">{{ t('common.loading') }}</span>
+ <span v-else class="automation-editor__muted">{{ t('automation.editor.previewEmpty') }}</span>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- 执行方式 -->
+ <div v-show="section === 'execution'" class="section">
+ <div class="section-header">
+ <h2>{{ t('automation.editor.sections.execution.title') }}</h2>
+ <p class="section-description">{{ t('automation.editor.sections.execution.desc') }}</p>
+ </div>
+ <div class="settings-group">
+ <div class="setting-row">
+ <div class="setting-info">
+ <label>{{ t('automation.fields.accessLevel') }}</label>
+ <p class="desc">{{ t(`automation.editor.access.${form.access_level}`) }}</p>
+ </div>
+ <div class="setting-control">
+ <t-select v-model="form.access_level">
+ <t-option v-for="level in ASSISTANT_ACCESS_LEVELS" :key="level" :value="level"
+ :label="t(`assistant.access.levels.${level}.label`)" />
+ </t-select>
+ </div>
+ </div>
+ <div class="setting-row">
+ <div class="setting-info">
+ <label>{{ t('automation.fields.sessionMode') }}</label>
+ <p class="desc">{{ t(`automation.editor.sessionModeDesc.${form.session_mode}`) }}</p>
+ </div>
+ <div class="setting-control">
+ <t-select v-model="form.session_mode">
+ <t-option value="per_run" :label="t('automation.sessionMode.per_run')" />
+ <t-option value="persistent" :label="t('automation.sessionMode.persistent')" />
+ </t-select>
+ </div>
+ </div>
+ <div v-if="form.session_mode === 'per_run'" class="setting-row">
+ <div class="setting-info">
+ <label>{{ t('automation.fields.carryLastResult') }}</label>
+ <p class="desc">{{ t('automation.editor.carryDesc') }}</p>
+ </div>
+ <div class="setting-control">
+ <t-switch v-model="form.carry_last_result" />
+ </div>
+ </div>
+ <div class="setting-row">
+ <div class="setting-info">
+ <label>{{ t('automation.fields.overlapPolicy') }}</label>
+ </div>
+ <div class="setting-control">
+ <t-select v-model="form.overlap_policy">
+ <t-option value="skip" :label="t('automation.overlap.skip')" />
+ <t-option value="queue" :label="t('automation.overlap.queue')" />
+ </t-select>
+ </div>
+ </div>
+ <div class="setting-row">
+ <div class="setting-info">
+ <label>{{ t('automation.fields.misfirePolicy') }}</label>
+ <p class="desc">{{ t('automation.editor.misfireDesc') }}</p>
+ </div>
+ <div class="setting-control">
+ <t-select v-model="form.misfire_policy">
+ <t-option value="skip" :label="t('automation.misfire.skip')" />
+ <t-option value="run_once" :label="t('automation.misfire.run_once')" />
+ </t-select>
+ </div>
+ </div>
+ <div class="setting-row">
+ <div class="setting-info">
+ <label>{{ t('automation.fields.maxDuration') }}</label>
+ <p class="desc">{{ t('automation.editor.maxDurationDesc') }}</p>
+ </div>
+ <div class="setting-control">
+ <t-input-number v-model="maxMinutes" :min="1" :max="240" theme="column"
+ :suffix="t('automation.units.minutes')" />
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- 审批与通知 -->
+ <div v-show="section === 'notify'" class="section">
+ <div class="section-header">
+ <h2>{{ t('automation.editor.sections.notify.title') }}</h2>
+ <p class="section-description">{{ t('automation.editor.sections.notify.desc') }}</p>
+ </div>
+ <div class="settings-group">
+ <div class="setting-row">
+ <div class="setting-info">
+ <label>{{ t('automation.fields.approvalTimeout') }}</label>
+ <p class="desc">{{ t('automation.editor.approvalTimeoutHelp') }}</p>
+ </div>
+ <div class="setting-control">
+ <t-input-number v-model="approvalHours" :min="1" :max="168" theme="column"
+ :suffix="t('automation.units.hours')" />
+ </div>
+ </div>
+ <div class="setting-row">
+ <div class="setting-info">
+ <label>{{ t('automation.fields.notifyOnSuccess') }}</label>
+ <p class="desc">{{ t('automation.editor.notifyHint') }}</p>
+ </div>
+ <div class="setting-control">
+ <t-switch v-model="form.notify_on_success" />
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <template #footer-note>
+ <p v-if="previewRuns.length && !previewError" class="settings-footer-note">
+ <t-icon name="time" class="settings-footer-note__icon" />
+ <span><strong>{{ describeCurrent }}</strong>{{ t('automation.nextRunAt', { time: formatInZone(previewRuns[0], timezone, locale) }) }}</span>
+ </p>
+ </template>
+ <template #footer>
+ <t-button theme="default" variant="outline" @click="modalShell.requestClose">{{ t('common.cancel') }}</t-button>
+ <t-button theme="primary" :loading="saving" @click="save">
+ {{ automation ? t('common.save') : t('common.create') }}
+ </t-button>
+ </template>
+ </SettingsModalShell>
+</template>
+
+<script setup lang="ts">
+import { computed, reactive, ref, watch } from 'vue'
+import { useI18n } from 'vue-i18n'
+import { MessagePlugin } from 'tdesign-vue-next'
+import SettingsModalShell from '@/components/SettingsModalShell.vue'
+import { useModalShell } from '@/composables/useModalShell'
+import {
+ createAutomation,
+ updateAutomation,
+ validateAutomationTrigger,
+ type Automation,
+ type AutomationInput,
+} from '@/api/automation'
+import { ASSISTANT_ACCESS_LEVELS } from '@/api/assistant'
+import {
+ browserTimezone,
+ defaultScheduleForm,
+ describeTrigger,
+ formatInZone,
+ scheduleFormFromTrigger,
+ timezoneOptions,
+ triggerFromScheduleForm,
+ weekdayName,
+ type ScheduleKind,
+} from '@/utils/automationSchedule'
+import type { AutomationAgentOption } from './agents'
+
+const props = defineProps<{
+ visible: boolean
+ automation: Automation | null
+ agents: AutomationAgentOption[]
+ agentsLoading?: boolean
+ defaultAgentId: string
+}>()
+const emit = defineEmits<{ 'update:visible': [value: boolean]; saved: [value: Automation] }>()
+
+const { t, locale } = useI18n()
+
+type Section = 'basic' | 'schedule' | 'execution' | 'notify'
+
+const VARIABLE_TAGS = ['now', 'last_run_at', 'last_success_at', 'run_id', 'automation_name']
+ .map((name) => `{{${name}}}`)
+const KINDS: ScheduleKind[] = ['daily', 'weekdays', 'weekly', 'monthly', 'hourly', 'once', 'custom']
+const WEEK = [1, 2, 3, 4, 5, 6, 0]
+
+const section = ref<Section>('basic')
+const navGroups = computed(() => [
+ {
+ key: 'task',
+ label: t('automation.editor.navGroups.task'),
+ items: [
+ { key: 'basic', label: t('automation.editor.sections.basic.title'), icon: 'edit-1' },
+ { key: 'schedule', label: t('automation.editor.sections.schedule.title'), icon: 'time' },
+ ],
+ },
+ {
+ key: 'run',
+ label: t('automation.editor.navGroups.run'),
+ items: [
+ { key: 'execution', label: t('automation.editor.sections.execution.title'), icon: 'secured' },
+ { key: 'notify', label: t('automation.editor.sections.notify.title'), icon: 'notification' },
+ ],
+ },
+])
+
+const blank = (): Required<Omit<AutomationInput, 'trigger' | 'limits' | 'description'>> => ({
+ name: '',
+ agent_id: props.defaultAgentId,
+ instruction: '',
+ session_mode: 'per_run',
+ carry_last_result: false,
+ misfire_policy: 'skip',
+ overlap_policy: 'skip',
+ access_level: 'confirm',
+ approval_timeout_minutes: 1440,
+ notify_on_success: false,
+})
+
+const form = reactive(blank())
+const schedule = reactive(defaultScheduleForm())
+const timezone = ref(browserTimezone())
+const maxMinutes = ref(30)
+const saving = ref(false)
+
+const zones = computed(() => timezoneOptions(timezone.value))
+
+const agentOptions = computed(() => {
+ const list = [...props.agents]
+ if (form.agent_id && !list.some((a) => a.id === form.agent_id)) {
+ list.push({ id: form.agent_id, name: t('automation.agentUnavailable') })
+ }
+ return list
+})
+
+const approvalHours = computed({
+ get: () => Math.max(1, Math.round(form.approval_timeout_minutes / 60)),
+ set: (v: number) => { form.approval_timeout_minutes = Math.max(1, Number(v) || 1) * 60 },
+})
+
+const clock = computed({
+ get: () => `${String(schedule.hour).padStart(2, '0')}:${String(schedule.minute).padStart(2, '0')}`,
+ set: (v: string) => {
+ const [h, m] = String(v || '').split(':').map(Number)
+ if (Number.isFinite(h)) schedule.hour = h
+ if (Number.isFinite(m)) schedule.minute = m
+ },
+})
+
+const trigger = computed(() => triggerFromScheduleForm(schedule, timezone.value))
+const describeCurrent = computed(() => (trigger.value ? `${describeTrigger(trigger.value, t, locale.value)} · ` : ''))
+
+function close() {
+ emit('update:visible', false)
+}
+
+const modalShell = useModalShell({
+ visible: () => props.visible,
+ close,
+ snapshot: () => ({ form, schedule, timezone: timezone.value, maxMinutes: maxMinutes.value }),
+})
+
+watch(() => props.visible, (open) => {
+ if (!open) return
+ const a = props.automation
+ section.value = 'basic'
+ Object.assign(form, blank())
+ Object.assign(schedule, defaultScheduleForm())
+ timezone.value = browserTimezone()
+ maxMinutes.value = 30
+ if (a) {
+ Object.assign(form, {
+ name: a.name,
+ agent_id: a.agent_id,
+ instruction: a.instruction,
+ session_mode: a.session_mode,
+ carry_last_result: a.carry_last_result,
+ misfire_policy: a.misfire_policy,
+ overlap_policy: a.overlap_policy,
+ access_level: a.access_level,
+ approval_timeout_minutes: a.approval_timeout_minutes,
+ notify_on_success: a.notify_on_success,
+ })
+ Object.assign(schedule, scheduleFormFromTrigger(a.trigger))
+ timezone.value = a.trigger.timezone || 'UTC'
+ maxMinutes.value = a.limits?.max_duration_minutes || 30
+ }
+ previewRuns.value = []
+ previewError.value = ''
+ modalShell.markClean()
+}, { immediate: true })
+
+const previewRuns = ref<string[]>([])
+const previewError = ref('')
+const previewLoading = ref(false)
+let previewSeq = 0
+let previewTimer: ReturnType<typeof setTimeout> | undefined
+
+watch([trigger, () => props.visible], () => {
+ clearTimeout(previewTimer)
+ const current = trigger.value
+ previewRuns.value = []
+ previewError.value = ''
+ if (!props.visible || !current) return
+ previewLoading.value = true
+ const seq = ++previewSeq
+ previewTimer = setTimeout(async () => {
+ try {
+ const res = await validateAutomationTrigger(current)
+ if (seq === previewSeq) previewRuns.value = res.data?.next_runs ?? []
+ } catch (e: any) {
+ if (seq === previewSeq) previewError.value = e?.message || t('automation.schedule.invalid')
+ } finally {
+ if (seq === previewSeq) previewLoading.value = false
+ }
+ }, 400)
+}, { deep: true })
+
+// The first section with a problem, with what to tell the user.
+function firstProblem(): [Section, string] | null {
+ if (!form.name.trim()) return ['basic', t('automation.editor.errors.name')]
+ if (!form.instruction.trim()) return ['basic', t('automation.editor.errors.instruction')]
+ if (!trigger.value || previewError.value) return ['schedule', previewError.value || t('automation.editor.errors.schedule')]
+ return null
+}
+
+async function save() {
+ const problem = firstProblem()
+ if (problem) {
+ section.value = problem[0]
+ MessagePlugin.warning(problem[1])
+ return
+ }
+ saving.value = true
+ const input: AutomationInput = {
+ ...form,
+ name: form.name.trim(),
+ trigger: trigger.value!,
+ limits: { max_duration_minutes: maxMinutes.value },
+ }
+ try {
+ const res = props.automation
+ ? await updateAutomation(props.automation.id, input)
+ : await createAutomation(input)
+ MessagePlugin.success(props.automation ? t('common.saveSuccess') : t('common.createSuccess'))
+ modalShell.markClean()
+ emit('saved', res.data)
+ close()
+ } catch (e: any) {
+ MessagePlugin.error(e?.message || t('common.saveFailed'))
+ } finally {
+ saving.value = false
+ }
+}
+</script>
+
+<style scoped lang="less">
+.content-wrapper {
+ flex: 1;
+ overflow-y: auto;
+ min-height: 0;
+ padding: 28px 40px 48px;
+ box-sizing: border-box;
+}
+
+.section {
+ width: 100%;
+}
+
+.section-header {
+ margin-bottom: 20px;
+
+ h2 {
+ margin: 0 0 6px;
+ color: var(--td-text-color-primary);
+ font-size: var(--app-text-3xl);
+ font-weight: 600;
+ }
+
+ .section-description {
+ margin: 0;
+ color: var(--td-text-color-secondary);
+ font-size: var(--app-text-base);
+ line-height: 1.5;
+ }
+}
+
+.settings-group {
+ display: flex;
+ flex-direction: column;
+}
+
+.setting-row {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 24px;
+ min-width: 0;
+ padding: 16px 0;
+ border-bottom: 1px solid var(--td-component-stroke);
+
+ &:last-child {
+ border-bottom: none;
+ }
+
+ &.setting-row-vertical {
+ flex-direction: column;
+ gap: 12px;
+
+ .setting-info {
+ flex: none;
+ max-width: 100%;
+ }
+ }
+}
+
+.setting-info {
+ flex: 0 0 42%;
+ max-width: 42%;
+ min-width: 0;
+
+ label {
+ display: block;
+ margin-bottom: 4px;
+ color: var(--td-text-color-primary);
+ font-size: var(--app-text-lg);
+ font-weight: 500;
+
+ .required {
+ margin-left: 2px;
+ color: var(--td-error-color);
+ }
+ }
+
+ .desc {
+ margin: 0;
+ color: var(--td-text-color-secondary);
+ font-size: var(--app-text-md);
+ line-height: 1.5;
+ }
+}
+
+.setting-control {
+ display: flex;
+ flex: 1 1 58%;
+ justify-content: flex-end;
+ align-items: flex-start;
+ min-width: 0;
+ max-width: 58%;
+
+ > :deep(.t-select__wrap),
+ > :deep(.t-input__wrap),
+ > :deep(.t-date-picker) {
+ width: 100%;
+ max-width: 320px;
+ }
+
+ &.setting-control-full {
+ width: 100%;
+ max-width: 100%;
+ justify-content: flex-start;
+ }
+}
+
+.automation-editor__stack {
+ flex-direction: column;
+ gap: 8px;
+}
+
+.automation-editor__hint {
+ margin: 0;
+ color: var(--td-text-color-placeholder);
+ font-size: var(--app-text-sm);
+ line-height: 1.8;
+
+ code {
+ margin: 0 2px;
+ padding: 1px 6px;
+ border-radius: var(--app-radius-xs);
+ background: var(--td-bg-color-secondarycontainer);
+ color: var(--td-text-color-secondary);
+ font-size: var(--app-text-xs);
+ }
+}
+
+.automation-editor__days {
+ flex-wrap: wrap;
+ justify-content: flex-end;
+ row-gap: 4px;
+}
+
+.automation-editor__mono :deep(input) {
+ font-family: var(--app-font-family-mono);
+}
+
+.automation-editor__preview {
+ width: 100%;
+ padding: 12px 16px;
+ border-radius: var(--app-radius-md);
+ background: var(--td-bg-color-secondarycontainer);
+ color: var(--td-text-color-primary);
+ font-size: var(--app-text-base);
+
+ &.is-error {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ background: var(--td-error-color-light);
+ color: var(--td-error-color);
+ }
+}
+
+.automation-editor__runs {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ font-variant-numeric: tabular-nums;
+
+ li {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+
+ :deep(.t-icon) {
+ color: var(--td-brand-color);
+ }
+}
+
+.automation-editor__muted {
+ color: var(--td-text-color-placeholder);
+}
+</style>
diff --git a/frontend/src/views/automation/AutomationList.vue b/frontend/src/views/automation/AutomationList.vue
new file mode 100644
index 000000000..ab712f48c
--- /dev/null
+++ b/frontend/src/views/automation/AutomationList.vue
@@ -0,0 +1,574 @@
+<template>
+ <main class="automation-page">
+ <header class="automation-page__header" style="--wails-draggable: drag">
+ <div class="automation-page__title-row" style="--wails-draggable: drag">
+ <h2 style="--wails-draggable: drag">
+ <ResourceIcon type="automation" :size="24" />
+ {{ t('automation.title') }}
+ </h2>
+ <div class="automation-page__tools" style="--wails-draggable: no-drag">
+ <t-input v-if="automations.length > 0" v-model="query" class="automation-page__search"
+ :placeholder="t('menu.search')" :aria-label="t('menu.search')" clearable>
+ <template #prefix-icon><t-icon name="search" size="16px" /></template>
+ </t-input>
+ <t-button variant="text" theme="default" size="small" class="automation-page__add" @click="openEditor(null)">
+ <template #icon><t-icon name="add" size="16px" /></template>
+ {{ t('automation.add') }}
+ </t-button>
+ </div>
+ </div>
+ <p class="automation-page__subtitle" style="--wails-draggable: drag">{{ t('automation.description') }}</p>
+ </header>
+
+ <div v-if="loading" class="loading-container">
+ <t-loading :text="t('common.loading')" />
+ </div>
+
+ <section v-else class="automation-page__main">
+ <div v-if="automations.length > 0 && filtered.length === 0" class="empty-state">
+ <t-empty :description="t('common.noResult')" />
+ <t-button variant="outline" @click="query = ''">{{ t('common.clear') }}</t-button>
+ </div>
+ <div v-else class="automation-grid">
+ <article v-for="item in filtered" :key="item.id" class="automation-card" :class="{ 'is-paused': !item.enabled }">
+ <button type="button" class="automation-card__open" :aria-label="item.name" @click="openDetail(item)" />
+ <div class="automation-card__header">
+ <div class="automation-card__badge" aria-hidden="true"><t-icon name="time" size="14px" /></div>
+ <h3 class="automation-card__title" :title="item.name">{{ item.name }}</h3>
+ <div class="automation-card__actions">
+ <button type="button" class="automation-card__icon-btn" :title="t('automation.actions.runNow')"
+ :aria-label="`${item.name} · ${t('automation.actions.runNow')}`" :disabled="busy.has(item.id)"
+ @click="runNow(item)">
+ <t-icon name="play-circle" size="14px" />
+ </button>
+ <button type="button" class="automation-card__icon-btn" :title="t('common.edit')"
+ :aria-label="`${item.name} · ${t('common.edit')}`" @click="openEditor(item)">
+ <t-icon name="edit" size="14px" />
+ </button>
+ <button type="button" class="automation-card__icon-btn automation-card__icon-btn--danger"
+ :title="t('common.delete')" :aria-label="`${item.name} · ${t('common.delete')}`"
+ :disabled="busy.has(item.id)" @click="remove(item)">
+ <t-icon name="delete" size="14px" />
+ </button>
+ </div>
+ </div>
+ <p class="automation-card__schedule">{{ describeTrigger(item.trigger, t, locale) }}</p>
+ <p v-if="!item.enabled && item.paused_reason" class="automation-card__paused" :title="item.paused_reason">
+ {{ item.paused_reason }}
+ </p>
+ <div class="automation-card__footer">
+ <div class="automation-card__meta">
+ <span>{{ agentName(item.agent_id) }}</span>
+ <span v-if="item.enabled && item.next_run_at">
+ {{ t('automation.nextRunAt', { time: formatInZone(item.next_run_at, item.trigger.timezone, locale) }) }}
+ </span>
+ <AutomationStatusTag :status="item.last_run_status" />
+ </div>
+ <button type="button" role="switch" class="automation-card__status" :class="{ 'is-enabled': item.enabled }"
+ :aria-checked="item.enabled" :aria-label="`${item.name} · ${t('automation.fields.enabled')}`"
+ :disabled="busy.has(item.id)" @click="toggle(item)">
+ <t-loading v-if="busy.has(item.id)" size="12px" />
+ <span v-else class="automation-card__dot" aria-hidden="true" />
+ {{ item.enabled ? t('common.on') : t('automation.paused') }}
+ </button>
+ </div>
+ </article>
+ <button type="button" class="automation-card automation-card--add" @click="openEditor(null)">
+ <span class="automation-card--add__icon" aria-hidden="true"><t-icon name="add" /></span>
+ <span class="automation-card--add__label">{{ t('automation.add') }}</span>
+ <span class="automation-card--add__hint">{{ t('automation.addHint') }}</span>
+ </button>
+ </div>
+ </section>
+
+ <AutomationEditor v-model:visible="editorVisible" :automation="editing" :agents="agents"
+ :agents-loading="agentsLoading" :default-agent-id="BUILTIN_WEKNORA_ASSISTANT_ID" @saved="onSaved" />
+ <AutomationDetail v-model:visible="detailVisible" :automation="detail" :agent-name="detail ? agentName(detail.agent_id) : ''"
+ :focus-run-id="focusRunId" @changed="onSaved" @edit="openEditor" />
+ </main>
+</template>
+
+<script setup lang="ts">
+import { computed, onMounted, ref, watch } from 'vue'
+import { useRoute, useRouter } from 'vue-router'
+import { useI18n } from 'vue-i18n'
+import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next'
+import { BUILTIN_WEKNORA_ASSISTANT_ID } from '@/api/agent'
+import {
+ deleteAutomation,
+ getAutomation,
+ listAutomations,
+ pauseAutomation,
+ resumeAutomation,
+ runAutomationNow,
+ type Automation,
+} from '@/api/automation'
+import { useAuthStore } from '@/stores/auth'
+import { describeTrigger, formatInZone } from '@/utils/automationSchedule'
+import AutomationEditor from './AutomationEditor.vue'
+import AutomationDetail from './AutomationDetail.vue'
+import AutomationStatusTag from './AutomationStatusTag.vue'
+import ResourceIcon from '@/components/icons/ResourceIcon.vue'
+import { loadAutomationAgents, type AutomationAgentOption } from './agents'
+
+const { t, locale } = useI18n()
+const route = useRoute()
+const router = useRouter()
+const authStore = useAuthStore()
+
+const automations = ref<Automation[]>([])
+const loading = ref(true)
+const query = ref('')
+const busy = ref(new Set<string>())
+const agents = ref<AutomationAgentOption[]>([])
+const agentsLoading = ref(false)
+const editorVisible = ref(false)
+const editing = ref<Automation | null>(null)
+const detailVisible = ref(false)
+const detail = ref<Automation | null>(null)
+const focusRunId = ref('')
+
+const filtered = computed(() => {
+ const q = query.value.trim().toLowerCase()
+ if (!q) return automations.value
+ return automations.value.filter((a) =>
+ a.name.toLowerCase().includes(q) || a.instruction.toLowerCase().includes(q))
+})
+
+const agentName = (id: string) =>
+ agents.value.find((a) => a.id === id)?.name ?? t('automation.agentUnavailable')
+
+async function load() {
+ try {
+ const res = await listAutomations()
+ automations.value = res.data ?? []
+ } catch (e: any) {
+ MessagePlugin.error(e?.message || t('common.operationFailed'))
+ } finally {
+ loading.value = false
+ }
+}
+
+async function loadAgents() {
+ agentsLoading.value = true
+ try {
+ agents.value = await loadAutomationAgents(authStore.currentTenantId, t('assistant.title'))
+ } catch {
+ agents.value = [{ id: BUILTIN_WEKNORA_ASSISTANT_ID, name: t('assistant.title') }]
+ } finally {
+ agentsLoading.value = false
+ }
+}
+
+function replace(item: Automation) {
+ const index = automations.value.findIndex((a) => a.id === item.id)
+ if (index >= 0) automations.value.splice(index, 1, item)
+ else automations.value.unshift(item)
+ if (detail.value?.id === item.id) detail.value = item
+}
+
+function onSaved(item: Automation) {
+ replace(item)
+}
+
+function openEditor(item: Automation | null) {
+ editing.value = item
+ detailVisible.value = false
+ editorVisible.value = true
+}
+
+function openDetail(item: Automation, runId = '') {
+ detail.value = item
+ focusRunId.value = runId
+ detailVisible.value = true
+}
+
+// Notifications link to /platform/automations/:id?run=…; the detail opens
+// over the list and the URL drops back to the list.
+async function openFromRoute() {
+ const id = typeof route.params.automationId === 'string' ? route.params.automationId : ''
+ if (!id) return
+ const runId = typeof route.query.run === 'string' ? route.query.run : ''
+ let item = automations.value.find((a) => a.id === id)
+ if (!item) {
+ try {
+ item = (await getAutomation(id)).data
+ } catch {
+ MessagePlugin.warning(t('automation.messages.notFound'))
+ }
+ }
+ if (item) openDetail(item, runId)
+ const rest = { ...route.query }
+ delete rest.run
+ void router.replace({ name: 'automationList', query: rest })
+}
+
+watch(() => route.params.automationId, () => {
+ if (!loading.value) void openFromRoute()
+})
+
+watch(detailVisible, (open) => {
+ if (!open) focusRunId.value = ''
+})
+
+async function toggle(item: Automation) {
+ busy.value.add(item.id)
+ try {
+ const res = item.enabled ? await pauseAutomation(item.id) : await resumeAutomation(item.id)
+ replace(res.data)
+ } catch (e: any) {
+ MessagePlugin.error(e?.message || t('common.operationFailed'))
+ } finally {
+ busy.value.delete(item.id)
+ }
+}
+
+async function runNow(item: Automation) {
+ busy.value.add(item.id)
+ try {
+ const res = await runAutomationNow(item.id)
+ MessagePlugin.success(t('automation.messages.queued'))
+ openDetail(item, res.data?.id ?? '')
+ } catch (e: any) {
+ MessagePlugin.error(e?.message || t('common.operationFailed'))
+ } finally {
+ busy.value.delete(item.id)
+ }
+}
+
+function remove(item: Automation) {
+ const dialog = DialogPlugin.confirm({
+ header: t('automation.deleteTitle'),
+ body: t('automation.deleteBody', { name: item.name }),
+ theme: 'danger',
+ confirmBtn: { content: t('common.delete'), theme: 'danger' },
+ onConfirm: async () => {
+ dialog.hide()
+ busy.value.add(item.id)
+ try {
+ await deleteAutomation(item.id)
+ automations.value = automations.value.filter((a) => a.id !== item.id)
+ if (detail.value?.id === item.id) detailVisible.value = false
+ MessagePlugin.success(t('common.deleteSuccess'))
+ } catch (e: any) {
+ MessagePlugin.error(e?.message || t('common.deleteFailed'))
+ } finally {
+ busy.value.delete(item.id)
+ }
+ },
+ })
+}
+
+onMounted(async () => {
+ void loadAgents()
+ await load()
+ await openFromRoute()
+})
+</script>
+
+<style scoped lang="less">
+@import (reference) '@/components/css/provider-card.less';
+@import (reference) '@/components/css/resource-card.less';
+
+.automation-page {
+ .resource-list-content();
+ color: var(--td-text-color-primary);
+}
+
+.automation-page__header {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ margin-bottom: 16px;
+ flex-shrink: 0;
+
+ h2 {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin: 0;
+ font-family: var(--app-font-family);
+ font-size: var(--app-text-4xl);
+ font-weight: 600;
+ line-height: 32px;
+ }
+}
+
+.automation-page__title-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--app-space-4);
+}
+
+.automation-page__tools {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.automation-page__search {
+ width: 240px;
+}
+
+.automation-page__add.t-button {
+ flex-shrink: 0;
+ min-height: 32px;
+ padding: 0 12px;
+ border: 1px solid var(--td-component-stroke);
+ border-radius: var(--app-radius-sm);
+ background: var(--td-bg-color-container);
+ color: var(--td-text-color-primary);
+
+ :deep(.t-icon) {
+ color: var(--td-brand-color);
+ }
+}
+
+.automation-page__subtitle {
+ margin: 0;
+ color: var(--td-text-color-secondary);
+ font-size: var(--app-text-base);
+ line-height: 20px;
+}
+
+.automation-page__main {
+ flex: 1;
+ min-height: 0;
+ overflow-y: auto;
+ overflow-x: hidden;
+ padding-bottom: var(--app-space-8);
+}
+
+.loading-container {
+ padding: 40px 0;
+ text-align: center;
+}
+
+.empty-state {
+ padding: 80px 0;
+ text-align: center;
+}
+
+.automation-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(min(100%, 320px), 1fr));
+ gap: 10px;
+ align-items: stretch;
+}
+
+.automation-card {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ min-width: 0;
+ padding: 12px;
+ border: 1px solid var(--td-component-stroke);
+ border-radius: var(--app-radius-md);
+ background: var(--td-bg-color-container);
+ transition: border-color var(--app-motion-base) ease, box-shadow var(--app-motion-base) ease;
+
+ &:hover:not(.automation-card--add) {
+ border-color: color-mix(in srgb, var(--td-brand-color) 40%, var(--td-component-stroke));
+ box-shadow: 0 3px 12px color-mix(in srgb, var(--td-text-color-primary) 6%, transparent);
+ }
+
+ &.is-paused .automation-card__schedule {
+ color: var(--td-text-color-placeholder);
+ }
+
+ &--add {
+ align-items: center;
+ justify-content: center;
+ gap: 4px;
+ min-height: 112px;
+ border-style: dashed;
+ background: transparent;
+ color: var(--td-text-color-placeholder);
+ cursor: pointer;
+ font: inherit;
+ text-align: center;
+
+ &:hover,
+ &:focus-visible {
+ color: var(--td-brand-color);
+ border-color: var(--td-brand-color);
+ background: color-mix(in srgb, var(--td-brand-color) 6%, transparent);
+ }
+
+ &__icon {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 32px;
+ height: 32px;
+ border-radius: var(--app-radius-md);
+ background: var(--td-bg-color-secondarycontainer);
+ font-size: var(--app-text-2xl);
+ }
+
+ &__label {
+ font-size: var(--app-text-md);
+ font-weight: 500;
+ }
+
+ &__hint {
+ font-size: var(--app-text-xs);
+ }
+ }
+}
+
+// The whole card opens the detail; the buttons on it sit above this layer.
+.automation-card__open {
+ position: absolute;
+ inset: 0;
+ border: 0;
+ border-radius: inherit;
+ background: transparent;
+ cursor: pointer;
+}
+
+.automation-card__header,
+.automation-card__footer,
+.automation-card__schedule,
+.automation-card__paused {
+ position: relative;
+ pointer-events: none;
+}
+
+.automation-card__actions,
+.automation-card__status {
+ pointer-events: auto;
+}
+
+.automation-card__header {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ min-height: 28px;
+}
+
+.automation-card__badge {
+ .provider-card-badge(28px, 8px);
+}
+
+.automation-card__title {
+ flex: 1;
+ min-width: 0;
+ margin: 0;
+ overflow: hidden;
+ font-size: var(--app-text-base);
+ font-weight: 600;
+ line-height: 20px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.automation-card__actions {
+ display: flex;
+ gap: 2px;
+}
+
+.automation-card__icon-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 24px;
+ height: 24px;
+ padding: 0;
+ border: 0;
+ border-radius: var(--app-radius-sm);
+ background: none;
+ color: var(--td-text-color-placeholder);
+ cursor: pointer;
+
+ &:hover:not(:disabled) {
+ color: var(--td-text-color-primary);
+ background: var(--td-bg-color-container-hover);
+ }
+
+ &--danger:hover:not(:disabled) {
+ color: var(--td-error-color);
+ background: color-mix(in srgb, var(--td-error-color) 8%, transparent);
+ }
+
+ &:disabled {
+ cursor: not-allowed;
+ opacity: 0.4;
+ }
+}
+
+.automation-card__schedule,
+.automation-card__paused {
+ margin: 0;
+ overflow: hidden;
+ font-size: var(--app-text-sm);
+ line-height: 1.5;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: var(--td-text-color-secondary);
+}
+
+.automation-card__paused {
+ color: var(--td-warning-color);
+}
+
+.automation-card__footer {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ margin-top: auto;
+}
+
+.automation-card__meta {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 6px 8px;
+ min-width: 0;
+ color: var(--td-text-color-placeholder);
+ font-size: var(--app-text-xs);
+}
+
+.automation-card__status {
+ flex-shrink: 0;
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ padding: 2px 4px;
+ border: 0;
+ border-radius: var(--app-radius-sm);
+ background: none;
+ color: var(--td-text-color-placeholder);
+ cursor: pointer;
+ font: inherit;
+ font-size: var(--app-text-sm);
+
+ &.is-enabled {
+ color: var(--td-success-color);
+ }
+
+ &:hover:not(:disabled) {
+ background: var(--td-bg-color-container-hover);
+ }
+
+ &:disabled {
+ cursor: wait;
+ }
+}
+
+.automation-card__dot {
+ width: 5px;
+ height: 5px;
+ border-radius: 50%;
+ background: currentColor;
+}
+
+.automation-card button:focus-visible,
+.automation-card--add:focus-visible {
+ outline: 2px solid var(--td-brand-color);
+ outline-offset: -2px;
+}
+</style>
diff --git a/frontend/src/views/automation/AutomationStatusTag.vue b/frontend/src/views/automation/AutomationStatusTag.vue
new file mode 100644
index 000000000..2413900f7
--- /dev/null
+++ b/frontend/src/views/automation/AutomationStatusTag.vue
@@ -0,0 +1,26 @@
+<template>
+ <t-tag v-if="status" size="small" variant="light" :theme="theme">{{ t(`automation.status.${status}`) }}</t-tag>
+</template>
+
+<script setup lang="ts">
+import { computed } from 'vue'
+import { useI18n } from 'vue-i18n'
+import type { AutomationRunStatus } from '@/api/automation'
+
+const props = defineProps<{ status: AutomationRunStatus | 'paused' | '' }>()
+const { t } = useI18n()
+
+const THEMES: Record<string, 'default' | 'primary' | 'success' | 'warning' | 'danger'> = {
+ queued: 'default',
+ running: 'primary',
+ awaiting_approval: 'warning',
+ succeeded: 'success',
+ failed: 'danger',
+ cancelled: 'default',
+ skipped: 'default',
+ needs_attention: 'warning',
+ paused: 'default',
+}
+
+const theme = computed(() => THEMES[props.status] ?? 'default')
+</script>
diff --git a/frontend/src/views/automation/agents.ts b/frontend/src/views/automation/agents.ts
new file mode 100644
index 000000000..db4e6aa13
--- /dev/null
+++ b/frontend/src/views/automation/agents.ts
@@ -0,0 +1,36 @@
+import { BUILTIN_WEKNORA_ASSISTANT_ID, listAgents, type CustomAgent } from '@/api/agent'
+
+export interface AutomationAgentOption {
+ id: string
+ name: string
+}
+
+// Built-in agents that serve one feature and cannot run an automation.
+const RESERVED = new Set(['builtin-wiki-fixer', 'builtin-skill-installer'])
+
+/**
+ * Agents the server accepts for an automation: the WeKnora assistant, then
+ * this workspace's smart-reasoning agents. Agents shared in from other
+ * workspaces are left out because a run would be refused.
+ */
+export function automationAgentOptions(
+ agents: CustomAgent[],
+ tenantId: number | string | null | undefined,
+ assistantName: string,
+): AutomationAgentOption[] {
+ const tenant = tenantId == null ? null : Number(tenantId)
+ const runnable = agents.filter((agent) =>
+ agent.id !== BUILTIN_WEKNORA_ASSISTANT_ID
+ && !RESERVED.has(agent.id)
+ && agent.config?.agent_mode === 'smart-reasoning'
+ && (tenant === null || agent.tenant_id == null || Number(agent.tenant_id) === tenant))
+ return [
+ { id: BUILTIN_WEKNORA_ASSISTANT_ID, name: assistantName },
+ ...runnable.map((agent) => ({ id: agent.id, name: agent.name })),
+ ]
+}
+
+export async function loadAutomationAgents(tenantId: number | string | null | undefined, assistantName: string) {
+ const res = await listAgents()
+ return automationAgentOptions(res.data ?? [], tenantId, assistantName)
+}
diff --git a/frontend/src/views/chat/components/OpenPageCard.test.ts b/frontend/src/views/chat/components/OpenPageCard.test.ts
index fc145dc9b..38d580609 100644
--- a/frontend/src/views/chat/components/OpenPageCard.test.ts
+++ b/frontend/src/views/chat/components/OpenPageCard.test.ts
@@ -41,6 +41,11 @@ function setup(link: unknown, initialPath = '/platform/knowledge-bases') {
return { state, pushed, drafts, router }
}
+test('an automation link uses the clock icon', () => {
+ const { state } = setup({ display_type: 'open_page', page: 'automations', label: 'Automations', detail: 'Remind me' })
+ assert.equal(state.icon.value, 'time')
+})
+
test('opening a new-model link hands its form to the page, then navigates', () => {
const { state, pushed, drafts } = setup({
display_type: 'open_page', page: 'settings_models', label: 'Models',
diff --git a/frontend/src/views/chat/components/OpenPageCard.vue b/frontend/src/views/chat/components/OpenPageCard.vue
index fd7761a1f..31878bb57 100644
--- a/frontend/src/views/chat/components/OpenPageCard.vue
+++ b/frontend/src/views/chat/components/OpenPageCard.vue
@@ -78,6 +78,7 @@ const icon = computed(() => {
case 'toolbox': return 'tools'
case 'agents': return 'robot'
case 'organizations': return 'usergroup'
+ case 'automations': return 'time'
default: return props.link.knowledge_id ? 'file' : 'folder'
}
})
diff --git a/frontend/src/views/platform/index.vue b/frontend/src/views/platform/index.vue
index f9dd3133c..cb857f4e5 100644
--- a/frontend/src/views/platform/index.vue
+++ b/frontend/src/views/platform/index.vue
@@ -16,9 +16,6 @@
<Settings />
<!-- 全局命令面板 (⌘K),随 platform 路由存活 -->
<GlobalCommandPalette />
- <!-- 全局右上角"待处理邀请"铃铛。固定定位,z-index 低于抽屉,业务页面
- 右侧抽屉弹出时会自然覆盖;仅在有待处理邀请时渲染。 -->
- <GlobalInvitationBell />
<!-- 知识库文件上传进度浮层:上传队列放在 store 里,切换页面不中断 -->
<UploadTasksPanel />
<!-- 带遮罩层的新手引导:首次进入自动开启,可从用户菜单顶部昵称旁帮助按钮重新打开 -->
@@ -35,7 +32,6 @@ import GlobalCommandPalette from '@/components/GlobalCommandPalette.vue'
import AssistantPanel from '@/components/assistant/AssistantPanel.vue'
import AssistantLauncher from '@/components/assistant/AssistantLauncher.vue'
import AssistantPageBridge from '@/components/assistant/AssistantPageBridge.vue'
-import GlobalInvitationBell from '@/components/GlobalInvitationBell.vue'
import UploadTasksPanel from '@/components/upload-tasks/UploadTasksPanel.vue'
import NewUserGuide from '@/components/NewUserGuide.vue'
import { useCommandPaletteStore } from '@/stores/commandPalette'
diff --git a/internal/agent/approval/gate.go b/internal/agent/approval/gate.go
index 0f1038e39..caf538240 100644
--- a/internal/agent/approval/gate.go
+++ b/internal/agent/approval/gate.go
@@ -249,6 +249,20 @@ func offeredGrantScope(req PendingRequest) string {
return req.GrantScope
}
+func grantRiskLabel(req PendingRequest) string {
+ if req.Grant == "" {
+ return ""
+ }
+ return string(req.grantRisk())
+}
+
+func grantLabel(req PendingRequest) string {
+ if req.Grant == "" {
+ return ""
+ }
+ return req.GrantScope
+}
+
func (req PendingRequest) grantRisk() policy.Risk {
if req.GrantRisk == "" {
return policy.RiskWrite
@@ -282,6 +296,8 @@ func (g *Gate) awaitToolApproval(ctx context.Context, req PendingRequest) (Decis
Grant: req.Grant,
GrantScope: offeredGrantScope(req),
GrantLapsed: lapse,
+ GrantRisk: grantRiskLabel(req),
+ GrantLabel: grantLabel(req),
})
if err != nil {
return Decision{}, fmt.Errorf("encode tool approval: %w", err)
diff --git a/internal/agent/engine.go b/internal/agent/engine.go
index 9d43738cd..cc433de76 100644
--- a/internal/agent/engine.go
+++ b/internal/agent/engine.go
@@ -53,6 +53,7 @@ type AgentEngine struct {
sessionID string // Session ID for logging and event emission
systemPromptTemplate string // System prompt template (optional, uses default if empty)
memoryPrompt string // Long-term memory envelope appended to the system prompt
+ runNote string // How this run was started; see SetRunNote
skillsManager *skills.Manager // Skills manager for Progressive Disclosure (optional)
appConfig *appconfig.Config // Application config for prompt template resolution (optional)
imageDescriber ImageDescriberFunc // VLM function for describing images in tool results (optional)
@@ -230,7 +231,16 @@ func (e *AgentEngine) buildSystemPrompt(ctx context.Context) string {
for _, section := range sections {
logger.Debugf(ctx, "[Agent][Prompt] section=%s bytes=%d", section.Name, len(section.Content))
}
- return renderSystemPromptSections(sections) + e.collaborationGuidance()
+ prompt := renderSystemPromptSections(sections) + e.collaborationGuidance()
+ if e.runNote != "" {
+ prompt += "\n\n" + e.runNote
+ }
+ return prompt
+}
+
+// SetRunNote adds note to the end of this run's system prompt.
+func (e *AgentEngine) SetRunNote(note string) {
+ e.runNote = strings.TrimSpace(note)
}
// SetMemoryPrompt supplies the long-term memory envelope for this run. Empty
diff --git a/internal/agent/operations/catalog.go b/internal/agent/operations/catalog.go
index 0a0eb95dc..8bd9f0f86 100644
--- a/internal/agent/operations/catalog.go
+++ b/internal/agent/operations/catalog.go
@@ -329,6 +329,10 @@ var allowedRouteAreas = map[string]bool{
"faq": true,
"agents": true,
"skills": true,
+ // The caller's own automations. Runs, grants and notifications live
+ // in other areas or behind routes left unannotated: the owner approves
+ // standing grants themselves.
+ "automations": true,
// Model and MCP responses carry endpoints and headers next to the
// names; only fields tagged x-agent are projected, so annotate the
// identifying ones and nothing else.
diff --git a/internal/agent/tools/open_page.go b/internal/agent/tools/open_page.go
index 3d939c6b3..9d9c00f00 100644
--- a/internal/agent/tools/open_page.go
+++ b/internal/agent/tools/open_page.go
@@ -41,11 +41,13 @@ const (
openPageAgents = "agents"
openPageKnowledgeBases = "knowledge_bases"
openPageOrganizations = "organizations"
+ openPageAutomations = "automations"
)
var openPages = []string{
types.PageKnowledgeBase, types.PageWiki, types.PageAgentEditor, types.PageModelSettings, types.PageMCPServices,
openPageSettings, openPageToolbox, openPageAgents, openPageKnowledgeBases, openPageOrganizations,
+ openPageAutomations,
}
type openPageSection struct{ zh, en string }
@@ -189,7 +191,7 @@ const openPageSchema = `{
"page": {
"type": "string",
"enum": ["knowledge_base", "wiki", "agent_editor", "settings_models", "mcp_services",
- "settings", "toolbox", "agents", "knowledge_bases", "organizations"],
+ "settings", "toolbox", "agents", "knowledge_bases", "organizations", "automations"],
"description": "Which page to open. ` +
`For a model or MCP service use settings_models or mcp_services, which can open one."
},
@@ -197,6 +199,7 @@ const openPageSchema = `{
"knowledge_id": {"type": "string", "description": "knowledge_base only: open this document."},
"wiki_slug": {"type": "string", "description": "wiki only: open this page; omit for the Wiki home."},
"agent_id": {"type": "string", "description": "agent_editor: the agent to edit."},
+ "automation_id": {"type": "string", "description": "automations only: open this automation's runs."},
"section": {
"type": "string",
"description": "The part of the page to open. ` +
@@ -304,6 +307,7 @@ type openPageInput struct {
KnowledgeID string `json:"knowledge_id"`
WikiSlug string `json:"wiki_slug"`
AgentID string `json:"agent_id"`
+ AutomationID string `json:"automation_id"`
Section string `json:"section"`
Panel string `json:"panel"`
ModelID string `json:"model_id"`
@@ -325,6 +329,7 @@ type OpenPageLink struct {
KnowledgeID string `json:"knowledge_id,omitempty"`
WikiSlug string `json:"wiki_slug,omitempty"`
AgentID string `json:"agent_id,omitempty"`
+ AutomationID string `json:"automation_id,omitempty"`
Section string `json:"section,omitempty"`
Panel string `json:"panel,omitempty"`
ModelID string `json:"model_id,omitempty"`
@@ -354,7 +359,7 @@ func parseOpenPageInput(args json.RawMessage) (openPageInput, error) {
}
}
trim(&input.Page, &input.KnowledgeBaseID, &input.KnowledgeID, &input.WikiSlug, &input.AgentID,
- &input.Section, &input.Panel, &input.ModelID, &input.MCPServiceID, &input.Note)
+ &input.AutomationID, &input.Section, &input.Panel, &input.ModelID, &input.MCPServiceID, &input.Note)
if d := input.ModelDraft; d != nil {
trim(&d.Type, &d.Source, &d.Provider, &d.ModelName, &d.DisplayName, &d.BaseURL)
}
@@ -374,6 +379,7 @@ func validateOpenPageInput(in openPageInput) error {
"wiki_slug": in.WikiSlug != "", "agent_id": in.AgentID != "", "section": in.Section != "",
"panel": in.Panel != "", "model_id": in.ModelID != "", "model_draft": in.ModelDraft != nil,
"mcp_service_id": in.MCPServiceID != "", "mcp_service_draft": in.MCPServiceDraft != nil,
+ "automation_id": in.AutomationID != "",
}
for name, present := range set {
if present && !slices.Contains(allowed, name) {
@@ -432,6 +438,8 @@ func validateOpenPageInput(in openPageInput) error {
return only("section")
case openPageAgents, openPageKnowledgeBases, openPageOrganizations:
return only()
+ case openPageAutomations:
+ return only("automation_id")
default:
return fmt.Errorf("page must be one of %s", strings.Join(openPages, ", "))
}
@@ -551,7 +559,8 @@ func (t *OpenPageTool) navigate(ctx context.Context, link *OpenPageLink, button
Action: types.PageActionNavigate,
Target: &types.PageNavigateTarget{
Page: link.Page, KnowledgeBaseID: link.KnowledgeBaseID, KnowledgeID: link.KnowledgeID,
- WikiSlug: link.WikiSlug, AgentID: link.AgentID, Section: link.Section, Panel: link.Panel,
+ WikiSlug: link.WikiSlug, AgentID: link.AgentID, AutomationID: link.AutomationID,
+ Section: link.Section, Panel: link.Panel,
ModelID: link.ModelID, MCPServiceID: link.MCPServiceID,
},
})
@@ -671,6 +680,16 @@ func (t *OpenPageTool) resolve(ctx context.Context, in openPageInput) (*OpenPage
link.Label = pick("知识库", "Knowledge bases")
case openPageOrganizations:
link.Label = pick("共享空间", "Shared spaces")
+ case openPageAutomations:
+ link.Label = pick("自动化", "Automations")
+ if in.AutomationID != "" {
+ a, blocked := t.read(ctx, "automation.get", map[string]string{"automation_id": in.AutomationID})
+ if blocked != nil {
+ return nil, blocked
+ }
+ link.AutomationID = in.AutomationID
+ link.Detail = firstNonEmpty(a.Label("name"), in.AutomationID)
+ }
}
return link, nil
}
diff --git a/internal/agent/tools/open_page_test.go b/internal/agent/tools/open_page_test.go
index 4df25cc73..a3ffd4732 100644
--- a/internal/agent/tools/open_page_test.go
+++ b/internal/agent/tools/open_page_test.go
@@ -25,6 +25,7 @@ func openPageFixture(role types.TenantRole) (*OpenPageTool, *fakeDispatcher) {
"/api/v1/agents/agent-1": `{"success":true,"data":{"id":"agent-1","name":"Support bot"}}`,
"/api/v1/models/m-1": `{"success":true,"data":{"id":"m-1","name":"qwen-max","display_name":"Qwen"}}`,
"/api/v1/mcp-services/mcp-1": `{"success":true,"data":{"id":"mcp-1","name":"Jira"}}`,
+ "/api/v1/automations/auto-1": `{"success":true,"data":{"id":"auto-1","name":"Morning digest"}}`,
}
responses["/api/v1/knowledgebase/kb-1/wiki/pages/entity/acme"] = `{"slug":"entity/acme","title":"Acme"}`
d := &fakeDispatcher{responses: map[string]*operations.Response{}}
@@ -114,6 +115,13 @@ func TestOpenPageLinksCheckedTargets(t *testing.T) {
args: `{"page":"agents"}`,
want: map[string]any{"page": "agents", "label": "Agents"},
},
+ {
+ name: "automation",
+ args: `{"page":"automations","automation_id":"auto-1"}`,
+ want: map[string]any{
+ "page": "automations", "label": "Automations", "detail": "Morning digest", "automation_id": "auto-1",
+ },
+ },
} {
t.Run(tc.name, func(t *testing.T) {
result := runOpenPage(t, tool, tc.args)
diff --git a/internal/agent/tools/operations.go b/internal/agent/tools/operations.go
index 91493d145..b4daa8aa3 100644
--- a/internal/agent/tools/operations.go
+++ b/internal/agent/tools/operations.go
@@ -48,6 +48,8 @@ const findOperationsDescription = "" +
"workspace's models, MCP services and skills (adding, renaming, enabling, removing, installing a " +
"skill from a hub), copying knowledge bases, editing or restoring document chunks, " +
"inspecting data sources and sync logs, pausing/resuming sync schedules, triggering syncs, " +
+ "creating and managing the user's automations (an agent runs a task on a schedule as them, " +
+ "for reminders and recurring or later work), " +
"configuring document parsing, chunking, OCR and generated questions, " +
"batch updating FAQ enabled/recommended states and tags, reading and refreshing saved MCP tool directories, " +
"managing saved web search providers and data source sync settings, checking connections and retrieval, " +
diff --git a/internal/application/service/automation.go b/internal/application/service/automation.go
new file mode 100644
index 000000000..f5f07d7e9
--- /dev/null
+++ b/internal/application/service/automation.go
@@ -0,0 +1,853 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/agent/hitl"
+ "github.com/Tencent/WeKnora/internal/agent/policy"
+ "github.com/Tencent/WeKnora/internal/automation"
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/event"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+// AutomationConfig bounds the scheduler and the automations it runs.
+type AutomationConfig struct {
+ // Tick is how often each instance looks for due work.
+ Tick time.Duration
+ // Lease is how long a running run stays owned without a heartbeat.
+ Lease time.Duration
+ // MaxConcurrent is how many runs one instance executes at once.
+ MaxConcurrent int
+ // MaxPerTenant caps the automations of one workspace.
+ MaxPerTenant int64
+ // Retention is how many runs each automation keeps.
+ Retention int
+ // MinInterval is the shortest gap allowed between two runs.
+ MinInterval time.Duration
+ // DefaultMaxDuration caps a run that sets no limit of its own.
+ DefaultMaxDuration time.Duration
+ // FailuresBeforePause pauses an automation after that many failed runs
+ // in a row.
+ FailuresBeforePause int
+}
+
+// DefaultAutomationConfig is used for every zero field.
+var DefaultAutomationConfig = AutomationConfig{
+ Tick: 15 * time.Second,
+ Lease: 2 * time.Minute,
+ MaxConcurrent: 4,
+ MaxPerTenant: 100,
+ Retention: 200,
+ MinInterval: automation.DefaultMinInterval,
+ DefaultMaxDuration: 30 * time.Minute,
+ FailuresBeforePause: 3,
+}
+
+const (
+ maxAutomationDuration = 4 * time.Hour
+ minApprovalTimeoutMinutes = 5
+ maxApprovalTimeoutMinutes = 7 * 24 * 60
+ defaultApprovalTimeout = 24 * 60
+ maxAutomationInstructionRune = 20000
+)
+
+// AutomationService manages automations and runs them on schedule as their
+// owners. No credential is stored: each run reloads and rechecks the owner.
+type AutomationService struct {
+ db *gorm.DB
+ agents interfaces.CustomAgentService
+ users interfaces.UserService
+ members interfaces.TenantMemberService
+ tenants interfaces.TenantService
+ messages interfaces.MessageService
+ grants interfaces.AgentGrantRepository
+ notices *NotificationService
+
+ sessions interfaces.SessionService
+ broker *hitl.Broker
+ runs *SuspendedRunService
+ streams interfaces.StreamManager
+ // Events publishes a run to its message's event stream; see
+ // AgentCollaboration.ChildEvents.
+ Events func(context.Context, *types.Session, *types.Message, *event.EventBus) func(context.Context) error
+
+ cfg AutomationConfig
+ instance string
+ now func() time.Time
+ wake chan struct{}
+ slots chan struct{}
+
+ mu sync.Mutex
+ running map[string]context.CancelFunc
+}
+
+// NewAutomationService builds the service. Bind it before Start.
+func NewAutomationService(
+ db *gorm.DB,
+ agents interfaces.CustomAgentService,
+ users interfaces.UserService,
+ members interfaces.TenantMemberService,
+ tenants interfaces.TenantService,
+ messages interfaces.MessageService,
+ grants interfaces.AgentGrantRepository,
+ notices *NotificationService,
+) *AutomationService {
+ s := &AutomationService{
+ db: db, agents: agents, users: users, members: members, tenants: tenants,
+ messages: messages, grants: grants, notices: notices,
+ instance: uuid.NewString(),
+ now: time.Now,
+ wake: make(chan struct{}, 1),
+ running: map[string]context.CancelFunc{},
+ }
+ s.Configure(AutomationConfig{})
+ return s
+}
+
+// Configure overrides the defaults with cfg's non-zero fields.
+func (s *AutomationService) Configure(cfg AutomationConfig) {
+ d := DefaultAutomationConfig
+ if cfg.Tick > 0 {
+ d.Tick = cfg.Tick
+ }
+ if cfg.Lease > 0 {
+ d.Lease = cfg.Lease
+ }
+ if cfg.MaxConcurrent > 0 {
+ d.MaxConcurrent = cfg.MaxConcurrent
+ }
+ if cfg.MaxPerTenant > 0 {
+ d.MaxPerTenant = cfg.MaxPerTenant
+ }
+ if cfg.Retention > 0 {
+ d.Retention = cfg.Retention
+ }
+ if cfg.MinInterval > 0 {
+ d.MinInterval = cfg.MinInterval
+ }
+ if cfg.DefaultMaxDuration > 0 {
+ d.DefaultMaxDuration = cfg.DefaultMaxDuration
+ }
+ if cfg.FailuresBeforePause > 0 {
+ d.FailuresBeforePause = cfg.FailuresBeforePause
+ }
+ s.cfg = d
+ s.slots = make(chan struct{}, d.MaxConcurrent)
+}
+
+// Bind attaches what runs need once DI has built it.
+func (s *AutomationService) Bind(
+ sessions interfaces.SessionService, broker *hitl.Broker,
+ runs *SuspendedRunService, streams interfaces.StreamManager,
+) {
+ s.sessions, s.broker, s.runs, s.streams = sessions, broker, runs, streams
+}
+
+// automationOwner is the signed-in web user an automation of ctx belongs to.
+func automationOwner(ctx context.Context) (uint64, string, error) {
+ principal, ok := types.PrincipalFromContext(ctx)
+ caller := types.CallerFromContext(ctx)
+ if _, scoped := types.TenantAPIKeyScopeFromContext(ctx); scoped || !ok ||
+ principal.Type != types.PrincipalWebUser || types.ActingViaFromContext(ctx) != "" ||
+ caller.TenantID == 0 || caller.UserID == "" || caller.UserID != principal.ID ||
+ types.IsSyntheticUserID(caller.UserID) {
+ return 0, "", apperrors.NewForbiddenError("automations belong to a signed-in user")
+ }
+ return caller.TenantID, caller.UserID, nil
+}
+
+func (s *AutomationService) owned(ctx context.Context) (*gorm.DB, error) {
+ tenantID, userID, err := automationOwner(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return s.db.WithContext(ctx).Where("tenant_id = ? AND owner_user_id = ?", tenantID, userID), nil
+}
+
+func (s *AutomationService) load(ctx context.Context, id string) (*types.Automation, error) {
+ query, err := s.owned(ctx)
+ if err != nil {
+ return nil, err
+ }
+ var a types.Automation
+ if err := query.Where("id = ?", id).First(&a).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, apperrors.NewNotFoundError("automation not found")
+ }
+ return nil, err
+ }
+ return &a, nil
+}
+
+// List returns the caller's automations, newest first.
+func (s *AutomationService) List(ctx context.Context) ([]*types.Automation, error) {
+ query, err := s.owned(ctx)
+ if err != nil {
+ return nil, err
+ }
+ out := []*types.Automation{}
+ return out, query.Order("created_at DESC").Find(&out).Error
+}
+
+// Get returns one of the caller's automations.
+func (s *AutomationService) Get(ctx context.Context, id string) (*types.Automation, error) {
+ return s.load(ctx, id)
+}
+
+// FindBySession returns the caller's automation whose run, or persistent
+// conversation, is sessionID.
+func (s *AutomationService) FindBySession(ctx context.Context, sessionID string) (*types.Automation, error) {
+ query, err := s.owned(ctx)
+ if err != nil {
+ return nil, err
+ }
+ sessionID = strings.TrimSpace(sessionID)
+ if sessionID == "" {
+ return nil, badAutomation("a session id is required")
+ }
+ var a types.Automation
+ runs := s.db.WithContext(ctx).Model(&types.AutomationRun{}).
+ Select("automation_id").Where("session_id = ?", sessionID)
+ err = query.Where("persistent_session_id = ? OR id IN (?)", sessionID, runs).First(&a).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, apperrors.NewNotFoundError("automation not found")
+ }
+ return &a, err
+}
+
+func badAutomation(format string, args ...any) error {
+ return apperrors.NewBadRequestError(fmt.Sprintf(format, args...))
+}
+
+func applyAutomationPatch(a *types.Automation, p *types.AutomationPatch) {
+ if p.Name != nil {
+ a.Name = strings.TrimSpace(*p.Name)
+ }
+ if p.Description != nil {
+ a.Description = strings.TrimSpace(*p.Description)
+ }
+ if p.AgentID != nil {
+ a.AgentID = strings.TrimSpace(*p.AgentID)
+ }
+ if p.Instruction != nil {
+ a.Instruction = strings.TrimSpace(*p.Instruction)
+ }
+ if p.Trigger != nil {
+ a.Trigger = *p.Trigger
+ }
+ if p.SessionMode != nil {
+ a.SessionMode = *p.SessionMode
+ }
+ if p.CarryLastResult != nil {
+ a.CarryLastResult = *p.CarryLastResult
+ }
+ if p.MisfirePolicy != nil {
+ a.MisfirePolicy = *p.MisfirePolicy
+ }
+ if p.OverlapPolicy != nil {
+ a.OverlapPolicy = *p.OverlapPolicy
+ }
+ if p.AccessLevel != nil {
+ a.AccessLevel = *p.AccessLevel
+ }
+ if p.ApprovalTimeoutMinutes != nil {
+ a.ApprovalTimeoutMinutes = *p.ApprovalTimeoutMinutes
+ }
+ if p.Limits != nil {
+ a.Limits = *p.Limits
+ }
+ if p.NotifyOnSuccess != nil {
+ a.NotifyOnSuccess = *p.NotifyOnSuccess
+ }
+}
+
+// validate normalizes a and checks it can run; it returns its schedule.
+func (s *AutomationService) validate(ctx context.Context, a *types.Automation) (*automation.Schedule, error) {
+ if a.Name == "" || len([]rune(a.Name)) > 100 {
+ return nil, badAutomation("name is required, at most 100 characters")
+ }
+ if a.Instruction == "" || len([]rune(a.Instruction)) > maxAutomationInstructionRune {
+ return nil, badAutomation("instruction is required, at most %d characters", maxAutomationInstructionRune)
+ }
+ if a.AgentID == "" {
+ a.AgentID = types.BuiltinWeKnoraAssistantID
+ }
+ if _, err := s.runnableAgent(ctx, a.AgentID, a.TenantID); err != nil {
+ return nil, apperrors.NewBadRequestError(err.Error())
+ }
+ sched, err := automation.Parse(a.Trigger)
+ if err != nil {
+ return nil, apperrors.NewBadRequestError(err.Error())
+ }
+ a.Trigger = sched.Trigger()
+ now := s.now()
+ if err := sched.CheckInterval(now, s.cfg.MinInterval); err != nil {
+ return nil, apperrors.NewBadRequestError(err.Error())
+ }
+ if a.Enabled && sched.Next(now) == nil {
+ return nil, badAutomation("the trigger never fires again")
+ }
+ switch a.SessionMode {
+ case "":
+ a.SessionMode = types.AutomationSessionPerRun
+ case types.AutomationSessionPerRun, types.AutomationSessionPersistent:
+ default:
+ return nil, badAutomation("session_mode must be per_run or persistent")
+ }
+ if a.MisfirePolicy == "" {
+ a.MisfirePolicy = types.AutomationPolicySkip
+ }
+ if a.MisfirePolicy != types.AutomationPolicySkip && a.MisfirePolicy != types.AutomationPolicyRunOnce {
+ return nil, badAutomation("misfire_policy must be skip or run_once")
+ }
+ if a.OverlapPolicy == "" {
+ a.OverlapPolicy = types.AutomationPolicySkip
+ }
+ if a.OverlapPolicy != types.AutomationPolicySkip && a.OverlapPolicy != types.AutomationPolicyQueue {
+ return nil, badAutomation("overlap_policy must be skip or queue")
+ }
+ if a.AccessLevel == "" {
+ a.AccessLevel = types.AssistantAccessConfirm
+ }
+ if !a.AccessLevel.Valid() {
+ return nil, badAutomation("access_level must be read_only, confirm or auto_write")
+ }
+ if a.ApprovalTimeoutMinutes == 0 {
+ a.ApprovalTimeoutMinutes = defaultApprovalTimeout
+ }
+ if a.ApprovalTimeoutMinutes < minApprovalTimeoutMinutes || a.ApprovalTimeoutMinutes > maxApprovalTimeoutMinutes {
+ return nil, badAutomation("approval_timeout_minutes must be between %d and %d",
+ minApprovalTimeoutMinutes, maxApprovalTimeoutMinutes)
+ }
+ if m := a.Limits.MaxDurationMinutes; m < 0 || time.Duration(m)*time.Minute > maxAutomationDuration {
+ return nil, badAutomation("limits.max_duration_minutes must be at most %d",
+ int(maxAutomationDuration.Minutes()))
+ }
+ return sched, nil
+}
+
+// runnableAgent loads agent id for a run in tenantID: a smart-reasoning
+// agent of the workspace, or the WeKnora assistant. ctx must carry tenantID.
+func (s *AutomationService) runnableAgent(ctx context.Context, id string, tenantID uint64) (*types.CustomAgent, error) {
+ if id == types.BuiltinWikiFixerID || id == types.BuiltinSkillInstallerID {
+ return nil, errors.New("this built-in agent cannot run automations")
+ }
+ agent, err := s.agents.GetAgentByID(ctx, id)
+ if err != nil || agent == nil {
+ return nil, fmt.Errorf("agent %s is not available in this workspace", id)
+ }
+ if !types.GrantsOperationCatalog(agent) && agent.TenantID != tenantID {
+ return nil, fmt.Errorf("agent %s is not available in this workspace", id)
+ }
+ if !agent.IsAgentMode() {
+ return nil, fmt.Errorf("agent %s must use smart reasoning to run automations", id)
+ }
+ return agent, nil
+}
+
+// Create adds an automation owned by the caller.
+func (s *AutomationService) Create(ctx context.Context, p *types.AutomationPatch) (*types.Automation, error) {
+ tenantID, userID, err := automationOwner(ctx)
+ if err != nil {
+ return nil, err
+ }
+ var count int64
+ if err := s.db.WithContext(ctx).Model(&types.Automation{}).
+ Where("tenant_id = ?", tenantID).Count(&count).Error; err != nil {
+ return nil, err
+ }
+ if count >= s.cfg.MaxPerTenant {
+ return nil, apperrors.NewBadRequestError(
+ fmt.Sprintf("a workspace can have at most %d automations", s.cfg.MaxPerTenant))
+ }
+ a := &types.Automation{TenantID: tenantID, OwnerUserID: userID, Enabled: true}
+ applyAutomationPatch(a, p)
+ if p.Enabled != nil {
+ a.Enabled = *p.Enabled
+ }
+ sched, err := s.validate(ctx, a)
+ if err != nil {
+ return nil, err
+ }
+ if a.Enabled {
+ a.NextRunAt = sched.Next(s.now())
+ }
+ if err := s.db.WithContext(ctx).Create(a).Error; err != nil {
+ return nil, err
+ }
+ return a, nil
+}
+
+var automationEditable = []string{
+ "name", "description", "agent_id", "instruction", "trigger_config", "session_mode", "carry_last_result",
+ "misfire_policy", "overlap_policy", "access_level", "approval_timeout_minutes", "limits",
+ "notify_on_success", "enabled", "next_run_at", "paused_reason", "consecutive_failures", "version",
+ "updated_at",
+}
+
+// save writes a's editable fields if nobody changed it since it was read.
+func (s *AutomationService) save(ctx context.Context, a *types.Automation) error {
+ read := a.Version
+ a.Version++
+ a.UpdatedAt = s.now()
+ res := s.db.WithContext(ctx).Model(a).Where("version = ?", read).Select(automationEditable).Updates(a)
+ if res.Error != nil {
+ return res.Error
+ }
+ if res.RowsAffected == 0 {
+ return apperrors.NewConflictError("the automation changed meanwhile; reload and try again")
+ }
+ return nil
+}
+
+// Update changes the fields p carries.
+func (s *AutomationService) Update(
+ ctx context.Context, id string, p *types.AutomationPatch,
+) (*types.Automation, error) {
+ a, err := s.load(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ before := a.Trigger
+ applyAutomationPatch(a, p)
+ enable := p.Enabled != nil && *p.Enabled && !a.Enabled
+ if p.Enabled != nil {
+ a.Enabled = *p.Enabled
+ }
+ sched, err := s.validate(ctx, a)
+ if err != nil {
+ return nil, err
+ }
+ triggerChanged, _ := json.Marshal(before)
+ triggerNow, _ := json.Marshal(a.Trigger)
+ switch {
+ case !a.Enabled:
+ a.NextRunAt = nil
+ case enable || a.NextRunAt == nil || string(triggerChanged) != string(triggerNow):
+ a.NextRunAt = sched.Next(s.now())
+ }
+ if enable {
+ a.PausedReason, a.ConsecutiveFailures = "", 0
+ }
+ if err := s.save(ctx, a); err != nil {
+ return nil, err
+ }
+ return a, nil
+}
+
+// Pause stops scheduling; runs already going continue.
+func (s *AutomationService) Pause(ctx context.Context, id string) (*types.Automation, error) {
+ a, err := s.load(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ if !a.Enabled {
+ return a, nil
+ }
+ a.Enabled, a.NextRunAt = false, nil
+ if err := s.save(ctx, a); err != nil {
+ return nil, err
+ }
+ return a, nil
+}
+
+// Resume schedules it again from now, clearing a pause and its failures.
+func (s *AutomationService) Resume(ctx context.Context, id string) (*types.Automation, error) {
+ t := true
+ return s.Update(ctx, id, &types.AutomationPatch{Enabled: &t})
+}
+
+// Delete stops an automation's runs and removes it with its conversations
+// and standing grants.
+func (s *AutomationService) Delete(ctx context.Context, id string) error {
+ a, err := s.load(ctx, id)
+ if err != nil {
+ return err
+ }
+ var active []*types.AutomationRun
+ if err := s.db.WithContext(ctx).Where("automation_id = ? AND status IN ?", a.ID, []string{
+ types.AutomationRunQueued, types.AutomationRunRunning, types.AutomationRunAwaitingApproval,
+ }).Find(&active).Error; err != nil {
+ return err
+ }
+ for _, run := range active {
+ if err := s.cancelRun(ctx, run, "the automation was deleted"); err != nil {
+ return err
+ }
+ }
+ return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ sessionIDs := tx.Model(&types.AutomationRun{}).Select("session_id").
+ Where("automation_id = ? AND session_id <> ''", a.ID)
+ if err := tx.Where("tenant_id = ? AND kind = ? AND (id IN (?) OR id = ?)",
+ a.TenantID, types.SessionKindAutomation, sessionIDs, a.PersistentSessionID).
+ Delete(&types.Session{}).Error; err != nil {
+ return err
+ }
+ if err := tx.Where("tenant_id = ? AND scope = ? AND scope_id = ?",
+ a.TenantID, types.AgentGrantScopeAutomation, a.ID).Delete(&types.AgentGrant{}).Error; err != nil {
+ return err
+ }
+ if err := tx.Where("automation_id = ? AND status NOT IN ?", a.ID, []string{
+ types.AutomationRunRunning, types.AutomationRunAwaitingApproval,
+ }).Delete(&types.AutomationRun{}).Error; err != nil {
+ return err
+ }
+ return tx.Delete(a).Error
+ })
+}
+
+// ValidateTrigger checks t and returns its next n firing times.
+func (s *AutomationService) ValidateTrigger(t types.AutomationTrigger, n int) ([]time.Time, error) {
+ sched, err := automation.Parse(t)
+ if err != nil {
+ return nil, apperrors.NewBadRequestError(err.Error())
+ }
+ now := s.now()
+ if err := sched.CheckInterval(now, s.cfg.MinInterval); err != nil {
+ return nil, apperrors.NewBadRequestError(err.Error())
+ }
+ return sched.Upcoming(now, n), nil
+}
+
+// RunNow queues a manual run. It is refused while another run is queued,
+// running or waiting.
+func (s *AutomationService) RunNow(ctx context.Context, id string) (*types.AutomationRun, error) {
+ a, err := s.load(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ busy, err := s.hasLiveRun(s.db.WithContext(ctx), a.ID)
+ if err != nil {
+ return nil, err
+ }
+ if busy {
+ return nil, apperrors.NewConflictError("a run of this automation is already queued or in progress")
+ }
+ run := &types.AutomationRun{
+ AutomationID: a.ID, TenantID: a.TenantID, ScheduledAt: s.now().UTC().Truncate(time.Millisecond),
+ TriggerKind: types.AutomationRunManual, Status: types.AutomationRunQueued,
+ }
+ if err := s.db.WithContext(ctx).Create(run).Error; err != nil {
+ return nil, err
+ }
+ s.Wake()
+ return run, nil
+}
+
+func (s *AutomationService) hasLiveRun(db *gorm.DB, automationID string) (bool, error) {
+ var n int64
+ err := db.Model(&types.AutomationRun{}).Where("automation_id = ? AND status IN ?", automationID, []string{
+ types.AutomationRunQueued, types.AutomationRunRunning, types.AutomationRunAwaitingApproval,
+ }).Count(&n).Error
+ return n > 0, err
+}
+
+// ListRuns returns a page of an automation's runs, newest first.
+func (s *AutomationService) ListRuns(
+ ctx context.Context, id string, limit, offset int,
+) ([]*types.AutomationRun, int64, error) {
+ if _, err := s.load(ctx, id); err != nil {
+ return nil, 0, err
+ }
+ if limit <= 0 || limit > 100 {
+ limit = 20
+ }
+ query := s.db.WithContext(ctx).Model(&types.AutomationRun{}).Where("automation_id = ?", id)
+ var total int64
+ if err := query.Count(&total).Error; err != nil {
+ return nil, 0, err
+ }
+ out := []*types.AutomationRun{}
+ err := query.Order("scheduled_at DESC, created_at DESC").Limit(limit).Offset(offset).Find(&out).Error
+ return out, total, err
+}
+
+// GetRun returns one of the caller's runs.
+func (s *AutomationService) GetRun(ctx context.Context, runID string) (*types.AutomationRun, error) {
+ var run types.AutomationRun
+ if err := s.db.WithContext(ctx).Where("id = ?", runID).First(&run).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, apperrors.NewNotFoundError("run not found")
+ }
+ return nil, err
+ }
+ if _, err := s.load(ctx, run.AutomationID); err != nil {
+ return nil, apperrors.NewNotFoundError("run not found")
+ }
+ return &run, nil
+}
+
+// CancelRun stops one of the caller's runs.
+func (s *AutomationService) CancelRun(ctx context.Context, runID string) (*types.AutomationRun, error) {
+ run, err := s.GetRun(ctx, runID)
+ if err != nil {
+ return nil, err
+ }
+ if types.AutomationRunFinished(run.Status) {
+ return run, nil
+ }
+ if err := s.cancelRun(ctx, run, "cancelled by the owner"); err != nil {
+ return nil, err
+ }
+ return s.GetRun(ctx, runID)
+}
+
+// cancelRun ends a queued or waiting run at once and asks a running one to
+// stop at its next check.
+func (s *AutomationService) cancelRun(ctx context.Context, run *types.AutomationRun, reason string) error {
+ switch run.Status {
+ case types.AutomationRunQueued, types.AutomationRunAwaitingApproval:
+ ok, err := s.finishRun(ctx, run, []string{run.Status}, types.AutomationRunCancelled, reason, nil)
+ if err != nil || !ok {
+ return err
+ }
+ if run.PendingPromptID != "" {
+ s.closePrompt(ctx, run.PendingPromptID, types.AgentPromptCanceled, reason)
+ }
+ return nil
+ case types.AutomationRunRunning:
+ if err := s.db.WithContext(ctx).Model(&types.AutomationRun{}).
+ Where("id = ? AND status = ?", run.ID, types.AutomationRunRunning).
+ Update("cancel_requested", true).Error; err != nil {
+ return err
+ }
+ s.mu.Lock()
+ cancel := s.running[run.ID]
+ s.mu.Unlock()
+ if cancel != nil {
+ cancel()
+ }
+ }
+ return nil
+}
+
+// closePrompt ends the open prompt id a run waits on and completes the
+// run's message, as the prompt reaper would.
+func (s *AutomationService) closePrompt(ctx context.Context, id, status, reason string) {
+ if s.broker == nil {
+ return
+ }
+ ctx = context.WithoutCancel(ctx)
+ row, err := s.broker.Store().Get(ctx, id)
+ if err != nil || row == nil || (!row.IsOpen() && row.Status != types.AgentPromptAnswered) {
+ return
+ }
+ ok, err := s.broker.Store().Transition(ctx, id, types.AgentPromptTransition{
+ From: []string{types.AgentPromptPending, types.AgentPromptSuspended, types.AgentPromptAnswered},
+ To: status,
+ CloseReason: &reason,
+ })
+ if err != nil || !ok {
+ return
+ }
+ state, _ := s.broker.Suspensions().Get(ctx, row.AssistantMessageID)
+ if state == nil || state.PromptID != id {
+ return
+ }
+ if s.runs != nil {
+ _ = s.runs.Close(ctx, row, state, reason)
+ }
+ _ = s.broker.Suspensions().Delete(ctx, row.AssistantMessageID, id)
+}
+
+// AutomationGrant is a standing grant of an automation, with why it no
+// longer applies when it does not.
+type AutomationGrant struct {
+ *types.AgentGrant
+ Lapse string `json:"lapse,omitempty"`
+}
+
+// AutomationGrantCandidate is a call an automation's runs asked approval for
+// that its owner may allow for future runs.
+type AutomationGrantCandidate struct {
+ PromptID string `json:"prompt_id"`
+ GrantKey string `json:"grant_key"`
+ Label string `json:"label"`
+ Risk string `json:"risk"`
+ Tool string `json:"tool"`
+ ServiceName string `json:"service_name,omitempty"`
+ AskedAt time.Time `json:"asked_at"`
+}
+
+// binding is what a's standing grants are given under right now.
+func (s *AutomationService) binding(ctx context.Context, a *types.Automation) (string, error) {
+ agent, err := s.runnableAgent(ctx, a.AgentID, a.TenantID)
+ if err != nil {
+ return "", err
+ }
+ membership, err := s.members.GetMembership(ctx, a.OwnerUserID, a.TenantID)
+ if err != nil {
+ return "", err
+ }
+ if membership == nil {
+ return "", errors.New("the owner is no longer a member of this workspace")
+ }
+ tenant, err := s.tenants.GetTenantByID(ctx, a.TenantID)
+ if err != nil {
+ return "", err
+ }
+ return automationBinding(agent, tenant, membership.Role), nil
+}
+
+func automationBinding(agent *types.CustomAgent, tenant *types.Tenant, role types.TenantRole) string {
+ ceiling := agent.Config.AccessLevel
+ if types.GrantsOperationCatalog(agent) {
+ var cfg *types.AssistantConfig
+ if tenant != nil {
+ cfg = tenant.AssistantConfig
+ }
+ ceiling = cfg.EffectiveAccessLevel(types.AssistantAccessAutoWrite)
+ }
+ services := append([]string{"mode:" + agent.Config.MCPSelectionMode}, agent.Config.MCPServices...)
+ return types.AutomationBinding{
+ AgentID: agent.ID,
+ Tools: agent.Config.AllowedTools,
+ MCPServiceIDs: services,
+ SystemPrompt: agent.Config.SystemPrompt,
+ OwnerRole: role,
+ Ceiling: ceiling,
+ }.Hash()
+}
+
+func automationGrantUser(userID string) string {
+ return types.Principal{Type: types.PrincipalWebUser, ID: userID}.StorageID()
+}
+
+// Grants lists an automation's standing grants.
+func (s *AutomationService) Grants(ctx context.Context, id string) ([]AutomationGrant, error) {
+ a, err := s.load(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ rows, err := s.grants.ListGrants(ctx, a.TenantID, automationGrantUser(a.OwnerUserID),
+ types.AgentGrantScopeAutomation, a.ID)
+ if err != nil {
+ return nil, err
+ }
+ binding, bindErr := s.binding(ctx, a)
+ out := make([]AutomationGrant, 0, len(rows))
+ for _, g := range rows {
+ if g.RevokedAt != nil {
+ continue
+ }
+ lapse := types.AgentGrantLapseChanged
+ if bindErr == nil {
+ lapse = g.LapseAt(s.now(), binding)
+ }
+ out = append(out, AutomationGrant{AgentGrant: g, Lapse: lapse})
+ }
+ return out, nil
+}
+
+// GrantCandidates lists the calls the automation's runs asked approval for
+// that are not allowed for future runs yet, newest first.
+func (s *AutomationService) GrantCandidates(ctx context.Context, id string) ([]AutomationGrantCandidate, error) {
+ a, err := s.load(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ granted := map[string]bool{}
+ if existing, err := s.Grants(ctx, id); err == nil {
+ for _, g := range existing {
+ if g.Lapse == "" {
+ granted[g.GrantKey] = true
+ }
+ }
+ }
+ var prompts []*types.AgentPrompt
+ if err := s.db.WithContext(ctx).
+ Where("tenant_id = ? AND user_id = ? AND kind = ?", a.TenantID, automationGrantUser(a.OwnerUserID),
+ types.AgentPromptKindToolApproval).
+ Where("session_id IN (?)", s.db.Model(&types.AutomationRun{}).Select("session_id").
+ Where("automation_id = ? AND session_id <> ''", a.ID)).
+ Order("created_at DESC").Limit(200).Find(&prompts).Error; err != nil {
+ return nil, err
+ }
+ out := []AutomationGrantCandidate{}
+ for _, p := range prompts {
+ c, ok := grantCandidate(p)
+ if !ok || granted[c.GrantKey] {
+ continue
+ }
+ granted[c.GrantKey] = true
+ out = append(out, c)
+ }
+ return out, nil
+}
+
+func grantCandidate(p *types.AgentPrompt) (AutomationGrantCandidate, bool) {
+ var req types.ToolApprovalPromptRequest
+ if json.Unmarshal(p.Request, &req) != nil || req.Grant == "" {
+ return AutomationGrantCandidate{}, false
+ }
+ risk := policy.Risk(req.GrantRisk)
+ if risk != policy.RiskWrite && risk != policy.RiskDestructive {
+ return AutomationGrantCandidate{}, false
+ }
+ tool := req.RegisteredToolName
+ if req.MCPToolName != "" {
+ tool = req.MCPToolName
+ }
+ return AutomationGrantCandidate{
+ PromptID: p.ID, GrantKey: req.Grant, Label: req.GrantLabel, Risk: req.GrantRisk,
+ Tool: tool, ServiceName: req.ServiceName, AskedAt: p.CreatedAt,
+ }, true
+}
+
+// AddGrant lets future runs make the call an earlier run asked approval
+// for in prompt promptID without asking. The grant stops applying when the
+// agent's configuration or the owner's role changes.
+func (s *AutomationService) AddGrant(ctx context.Context, id, promptID string) (*types.AgentGrant, error) {
+ a, err := s.load(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ var prompt types.AgentPrompt
+ err = s.db.WithContext(ctx).
+ Where("id = ? AND tenant_id = ? AND user_id = ? AND kind = ?", promptID, a.TenantID,
+ automationGrantUser(a.OwnerUserID), types.AgentPromptKindToolApproval).
+ Where("session_id IN (?)", s.db.Model(&types.AutomationRun{}).Select("session_id").
+ Where("automation_id = ? AND session_id <> ''", a.ID)).
+ First(&prompt).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, apperrors.NewNotFoundError("approval not found among this automation's runs")
+ }
+ if err != nil {
+ return nil, err
+ }
+ c, ok := grantCandidate(&prompt)
+ if !ok {
+ return nil, apperrors.NewBadRequestError("this call must be approved every time")
+ }
+ binding, err := s.binding(ctx, a)
+ if err != nil {
+ return nil, apperrors.NewBadRequestError(err.Error())
+ }
+ grant := &types.AgentGrant{
+ TenantID: a.TenantID, UserID: automationGrantUser(a.OwnerUserID),
+ Scope: types.AgentGrantScopeAutomation, ScopeID: a.ID, GrantKey: c.GrantKey,
+ Label: c.Label, BindingHash: binding, Risk: c.Risk, PromptID: prompt.ID,
+ }
+ if err := s.grants.SaveGrant(ctx, grant); err != nil {
+ return nil, err
+ }
+ return grant, nil
+}
+
+// Wake makes the scheduler look for work now.
+func (s *AutomationService) Wake() {
+ select {
+ case s.wake <- struct{}{}:
+ default:
+ }
+}
diff --git a/internal/application/service/automation_runner.go b/internal/application/service/automation_runner.go
new file mode 100644
index 000000000..e10c4e391
--- /dev/null
+++ b/internal/application/service/automation_runner.go
@@ -0,0 +1,552 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "sync"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/agent"
+ "github.com/Tencent/WeKnora/internal/agent/hitl"
+ "github.com/Tencent/WeKnora/internal/agent/tools"
+ "github.com/Tencent/WeKnora/internal/automation"
+ "github.com/Tencent/WeKnora/internal/event"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+ "gorm.io/gorm/clause"
+)
+
+// maxStoredAnswerRunes bounds the answer a run keeps for listings and for
+// the next run's carried result.
+const maxStoredAnswerRunes = 4000
+
+// errOwnerUnavailable fails a run because its owner may no longer run it;
+// the automation is paused rather than retried.
+var errOwnerUnavailable = errors.New("owner unavailable")
+
+// runOutcome is how one execution of a run ended.
+type runOutcome struct {
+ status string
+ reason string
+ answer string
+ usage *types.TokenUsage
+ promptID string
+ // pause, when set, pauses the automation with this reason.
+ pause string
+}
+
+// execute runs a claimed run to its next resting state and releases its
+// slot.
+func (s *AutomationService) execute(parent context.Context, run *types.AutomationRun) {
+ defer func() { <-s.slots }()
+ ctx, cancel := context.WithCancel(logger.CloneContext(context.WithoutCancel(parent)))
+ defer cancel()
+ s.mu.Lock()
+ s.running[run.ID] = cancel
+ s.mu.Unlock()
+ defer func() {
+ s.mu.Lock()
+ delete(s.running, run.ID)
+ s.mu.Unlock()
+ }()
+ go s.heartbeat(ctx, run.ID, cancel)
+
+ out := func() (out runOutcome) {
+ defer func() {
+ if r := recover(); r != nil {
+ out = runOutcome{status: types.AutomationRunFailed, reason: fmt.Sprintf("the run panicked: %v", r)}
+ }
+ }()
+ return s.runOnce(ctx, run)
+ }()
+ if ctx.Err() != nil && out.status != types.AutomationRunAwaitingApproval {
+ var row types.AutomationRun
+ if err := s.db.WithContext(context.WithoutCancel(ctx)).Select("cancel_requested").
+ Where("id = ?", run.ID).Take(&row).Error; err == nil && row.CancelRequested {
+ out.status, out.reason = types.AutomationRunCancelled, "cancelled by the owner"
+ }
+ }
+ s.record(ctx, run, out)
+}
+
+// heartbeat renews the run's lease and cancels it when the owner asked to
+// stop it or another instance took it over.
+func (s *AutomationService) heartbeat(ctx context.Context, runID string, cancel func()) {
+ ticker := time.NewTicker(max(s.cfg.Lease/4, time.Second))
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ }
+ res := s.db.WithContext(ctx).Model(&types.AutomationRun{}).
+ Where("id = ? AND status = ? AND owner = ?", runID, types.AutomationRunRunning, s.instance).
+ Update("lease_until", s.now().Add(s.cfg.Lease))
+ if res.Error != nil {
+ logger.Warnf(ctx, "Renew automation run %s: %v", runID, res.Error)
+ continue
+ }
+ var row types.AutomationRun
+ if err := s.db.WithContext(ctx).Select("cancel_requested").Where("id = ?", runID).
+ Take(&row).Error; err == nil && row.CancelRequested {
+ cancel()
+ return
+ }
+ if res.RowsAffected == 0 {
+ cancel()
+ return
+ }
+ }
+}
+
+// record stores how the execution ended, if this instance still owns it.
+func (s *AutomationService) record(ctx context.Context, run *types.AutomationRun, out runOutcome) {
+ ctx = context.WithoutCancel(ctx)
+ run.Answer = clipRunes(out.answer, maxStoredAnswerRunes)
+ updates := map[string]any{"answer": run.Answer, "updated_at": s.now()}
+ if out.usage != nil {
+ if data, err := json.Marshal(out.usage); err == nil {
+ updates["usage"] = types.JSON(data)
+ }
+ }
+ owned := func(db *gorm.DB) *gorm.DB { return db.Where("owner = ?", s.instance) }
+ if out.status == types.AutomationRunAwaitingApproval {
+ updates["status"], updates["pending_prompt_id"], updates["resume"] = out.status, out.promptID, false
+ updates["lease_until"] = nil
+ res := owned(s.db.WithContext(ctx).Model(&types.AutomationRun{}).
+ Where("id = ? AND status = ?", run.ID, types.AutomationRunRunning)).Updates(updates)
+ if res.Error != nil || res.RowsAffected == 0 {
+ logger.Warnf(ctx, "Record waiting automation run %s: %v", run.ID, res.Error)
+ return
+ }
+ if a, err := s.automationOf(ctx, run); err == nil {
+ s.notify(ctx, a, run, types.NotificationAutomationAwaitingApproval, "")
+ }
+ // The approval may have been answered before the run was marked
+ // waiting; pick it up now rather than at the next tick.
+ s.Wake()
+ return
+ }
+ if err := owned(s.db.WithContext(ctx).Model(&types.AutomationRun{}).
+ Where("id = ? AND status = ?", run.ID, types.AutomationRunRunning)).Updates(updates).Error; err != nil {
+ logger.Warnf(ctx, "Record automation run %s: %v", run.ID, err)
+ }
+ running := []string{types.AutomationRunRunning}
+ if _, err := s.finishRun(ctx, run, running, out.status, out.reason, owned); err != nil {
+ logger.Warnf(ctx, "Finish automation run %s: %v", run.ID, err)
+ }
+ if out.pause != "" {
+ if a, err := s.automationOf(ctx, run); err == nil {
+ _ = s.pause(ctx, a, out.pause)
+ }
+ }
+ s.Wake()
+}
+
+func (s *AutomationService) automationOf(ctx context.Context, run *types.AutomationRun) (*types.Automation, error) {
+ var a types.Automation
+ err := s.db.WithContext(ctx).Unscoped().Where("id = ?", run.AutomationID).First(&a).Error
+ return &a, err
+}
+
+func clipRunes(s string, n int) string {
+ if r := []rune(s); len(r) > n {
+ return string(r[:n]) + "…"
+ }
+ return s
+}
+
+func failed(reason string) runOutcome {
+ return runOutcome{status: types.AutomationRunFailed, reason: reason}
+}
+
+// ownerContext is ctx acting as a's owner, rechecked now: the account is
+// active and still a member of the workspace.
+func (s *AutomationService) ownerContext(ctx context.Context, a *types.Automation) (context.Context, error) {
+ user, err := s.users.GetUserByID(ctx, a.OwnerUserID)
+ if err != nil {
+ return nil, err
+ }
+ if user == nil || !user.IsActive {
+ return nil, fmt.Errorf("%w: the owner's account is inactive", errOwnerUnavailable)
+ }
+ membership, err := s.members.GetMembership(ctx, a.OwnerUserID, a.TenantID)
+ if err != nil {
+ return nil, err
+ }
+ if membership == nil || membership.Status != types.TenantMemberStatusActive {
+ return nil, fmt.Errorf("%w: the owner is no longer a member of this workspace", errOwnerUnavailable)
+ }
+ tenant, err := s.tenants.GetTenantByID(ctx, a.TenantID)
+ if err != nil {
+ return nil, err
+ }
+ if tenant == nil {
+ return nil, fmt.Errorf("%w: the workspace is unavailable", errOwnerUnavailable)
+ }
+ ctx = context.WithValue(ctx, types.TenantIDContextKey, a.TenantID)
+ ctx = context.WithValue(ctx, types.UserIDContextKey, a.OwnerUserID)
+ ctx = context.WithValue(ctx, types.TenantRoleContextKey, membership.Role)
+ ctx = context.WithValue(ctx, types.TenantInfoContextKey, tenant)
+ ctx = context.WithValue(ctx, types.UserContextKey, user)
+ ctx = types.WithCaller(ctx, types.Caller{TenantID: a.TenantID, UserID: a.OwnerUserID, Role: membership.Role})
+ ctx = types.WithPrincipal(ctx, types.Principal{
+ Type: types.PrincipalWebUser, ID: a.OwnerUserID, ActingVia: types.AutomationActingVia(a.ID),
+ })
+ return ctx, nil
+}
+
+// runOnce executes run, or continues it from its answered approval.
+func (s *AutomationService) runOnce(ctx context.Context, run *types.AutomationRun) runOutcome {
+ if s.sessions == nil {
+ return failed("the agent executor is unavailable")
+ }
+ a, err := s.automationOf(ctx, run)
+ if err != nil {
+ return failed("the automation is gone")
+ }
+ if a.DeletedAt.Valid {
+ return runOutcome{status: types.AutomationRunCancelled, reason: "the automation was deleted"}
+ }
+ ctx, err = s.ownerContext(ctx, a)
+ if err != nil {
+ if errors.Is(err, errOwnerUnavailable) {
+ return runOutcome{status: types.AutomationRunFailed, reason: err.Error(), pause: err.Error()}
+ }
+ return failed(err.Error())
+ }
+ agentConfig, err := s.runnableAgent(ctx, a.AgentID, a.TenantID)
+ if err != nil {
+ return runOutcome{status: types.AutomationRunFailed, reason: err.Error(), pause: err.Error()}
+ }
+ tenant, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
+ ctx = types.WithStandingGrantScope(ctx, types.GrantScope{
+ Scope: types.AgentGrantScopeAutomation, ScopeID: a.ID,
+ BindingHash: automationBinding(agentConfig, tenant, types.TenantRoleFromContext(ctx)),
+ })
+ limit := s.cfg.DefaultMaxDuration
+ if m := a.Limits.MaxDurationMinutes; m > 0 {
+ limit = time.Duration(m) * time.Minute
+ }
+ ctx, cancel := context.WithTimeout(ctx, limit)
+ defer cancel()
+
+ var resume *types.AgentResume
+ session, userMsg, answer, query := (*types.Session)(nil), (*types.Message)(nil), (*types.Message)(nil), ""
+ if run.Resume {
+ var stop func()
+ session, userMsg, answer, resume, stop, err = s.resumeState(ctx, run)
+ if err != nil {
+ if run.PendingPromptID != "" {
+ s.closePrompt(ctx, run.PendingPromptID, types.AgentPromptFailed, hitl.ReasonResumeStopped)
+ }
+ return failed("could not continue after the approval: " + err.Error())
+ }
+ defer stop()
+ if snap, err := agent.DecodeRunSnapshot(resume.Snapshot); err == nil {
+ query = snap.Query
+ }
+ } else {
+ session, err = s.runSession(ctx, a, run)
+ if err != nil {
+ return failed("could not open the conversation: " + err.Error())
+ }
+ if a.SessionMode == types.AutomationSessionPersistent && s.streams != nil {
+ if live, _, _ := s.streams.GetLiveRun(ctx, session.ID); live != "" {
+ return runOutcome{status: types.AutomationRunSkipped, reason: "its conversation was busy"}
+ }
+ }
+ query = s.runQuery(ctx, a, run)
+ userMsg, answer, err = s.startMessages(ctx, run, session, query)
+ if err != nil {
+ return failed("could not record the run: " + err.Error())
+ }
+ }
+ loc := scheduleLocation(a.Trigger)
+ req := &types.QARequest{
+ Session: session, Query: query, AssistantMessageID: answer.ID, UserMessageID: userMsg.ID,
+ CustomAgent: agentConfig, WebSearchEnabled: agentConfig.Config.WebSearchEnabled,
+ AssistantAccess: a.AccessLevel, Mode: types.RunModeDeferred, Suspendable: true, Resume: resume,
+ RunNote: automation.RunNote(a.Name, run.ScheduledAt, loc),
+ }
+ out := s.agentQA(ctx, req, session, answer)
+ if resume != nil && out.status != types.AutomationRunAwaitingApproval {
+ _ = s.broker.Suspensions().Delete(context.WithoutCancel(ctx), answer.ID, resume.Prompt.ID)
+ }
+ if out.status == types.AutomationRunFailed && errors.Is(ctx.Err(), context.DeadlineExceeded) {
+ out.reason = fmt.Sprintf("the run took longer than %s", limit)
+ }
+ return out
+}
+
+func scheduleLocation(t types.AutomationTrigger) *time.Location {
+ if loc, err := time.LoadLocation(t.Timezone); err == nil && t.Timezone != "" {
+ return loc
+ }
+ return time.UTC
+}
+
+// runQuery is the user message of a new run.
+func (s *AutomationService) runQuery(ctx context.Context, a *types.Automation, run *types.AutomationRun) string {
+ vars := automation.RunVars{
+ Now: run.ScheduledAt, LastRunAt: a.LastRunAt, LastSuccessAt: a.LastSuccessAt,
+ RunID: run.ID, AutomationName: a.Name, Location: scheduleLocation(a.Trigger),
+ }
+ last := ""
+ if a.SessionMode == types.AutomationSessionPerRun && a.CarryLastResult {
+ var prev types.AutomationRun
+ if err := s.db.WithContext(ctx).Select("answer").
+ Where("automation_id = ? AND status = ? AND id <> ?", a.ID, types.AutomationRunSucceeded, run.ID).
+ Order("finished_at DESC").Take(&prev).Error; err == nil {
+ last = prev.Answer
+ }
+ }
+ return automation.RunQuery(a.Instruction, vars, last)
+}
+
+// runSession is the conversation a new run writes to: a new one per run, or
+// the automation's persistent one, created on first use.
+func (s *AutomationService) runSession(
+ ctx context.Context, a *types.Automation, run *types.AutomationRun,
+) (*types.Session, error) {
+ if a.SessionMode == types.AutomationSessionPersistent && a.PersistentSessionID != "" {
+ if session, err := s.sessions.GetSession(ctx, a.PersistentSessionID); err == nil && session != nil {
+ return session, nil
+ }
+ }
+ title := a.Name
+ if a.SessionMode == types.AutomationSessionPerRun {
+ title += " · " + run.ScheduledAt.In(scheduleLocation(a.Trigger)).Format("2006-01-02 15:04")
+ }
+ now := s.now()
+ session := &types.Session{
+ ID: uuid.NewString(), TenantID: a.TenantID, UserID: a.OwnerUserID, Kind: types.SessionKindAutomation,
+ Title: clipRunes(title, 200), CreatedAt: now, UpdatedAt: now,
+ LastRequestState: &types.SessionLastRequestState{AgentID: a.AgentID, AgentEnabled: true},
+ }
+ if err := s.db.WithContext(ctx).Session(&gorm.Session{SkipHooks: true}).
+ Clauses(clause.OnConflict{DoNothing: true}).Create(session).Error; err != nil {
+ return nil, err
+ }
+ if a.SessionMode == types.AutomationSessionPersistent {
+ res := s.db.WithContext(ctx).Model(&types.Automation{}).
+ Where("id = ? AND persistent_session_id = ?", a.ID, a.PersistentSessionID).
+ Update("persistent_session_id", session.ID)
+ if res.Error != nil {
+ return nil, res.Error
+ }
+ if res.RowsAffected == 0 {
+ return nil, errors.New("the automation's conversation changed meanwhile")
+ }
+ }
+ return s.sessions.GetSession(ctx, session.ID)
+}
+
+func (s *AutomationService) startMessages(
+ ctx context.Context, run *types.AutomationRun, session *types.Session, query string,
+) (*types.Message, *types.Message, error) {
+ now := s.now()
+ userMsg, err := s.messages.CreateMessage(ctx, &types.Message{
+ SessionID: session.ID, RequestID: run.ID, Role: "user", Content: query,
+ IsCompleted: true, CreatedAt: now, Channel: types.ChannelWeb,
+ })
+ if err != nil {
+ return nil, nil, err
+ }
+ answer, err := s.messages.CreateMessage(ctx, &types.Message{
+ SessionID: session.ID, RequestID: run.ID, Role: "assistant", CreatedAt: now, Channel: types.ChannelWeb,
+ })
+ if err != nil {
+ return nil, nil, err
+ }
+ res := s.db.WithContext(ctx).Model(&types.AutomationRun{}).
+ Where("id = ? AND status = ? AND owner = ?", run.ID, types.AutomationRunRunning, s.instance).
+ Updates(map[string]any{
+ "session_id": session.ID, "user_message_id": userMsg.ID, "assistant_message_id": answer.ID,
+ })
+ if res.Error != nil {
+ return nil, nil, res.Error
+ }
+ if res.RowsAffected == 0 {
+ return nil, nil, errors.New("the run was taken over")
+ }
+ run.SessionID, run.UserMessageID, run.AssistantMessageID = session.ID, userMsg.ID, answer.ID
+ return userMsg, answer, nil
+}
+
+// resumeState loads what a run waiting on an answered approval continues
+// from. stop releases the prompt's lease.
+func (s *AutomationService) resumeState(ctx context.Context, run *types.AutomationRun) (
+ session *types.Session, userMsg, answer *types.Message, resume *types.AgentResume, stop func(), err error,
+) {
+ stop = func() {}
+ if s.broker == nil {
+ return nil, nil, nil, nil, stop, errors.New("approvals are unavailable")
+ }
+ prompt, err := s.broker.Store().Get(ctx, run.PendingPromptID)
+ if err != nil {
+ return nil, nil, nil, nil, stop, err
+ }
+ if prompt == nil || prompt.Status != types.AgentPromptAnswered || prompt.SessionID != run.SessionID ||
+ prompt.AssistantMessageID != run.AssistantMessageID || prompt.TenantID != run.TenantID {
+ return nil, nil, nil, nil, stop, errors.New("the approval can no longer be resumed")
+ }
+ stop = s.broker.KeepLease(ctx, prompt.ID, prompt.OwnerInstance)
+ snapshot, err := s.broker.Suspensions().Get(ctx, prompt.AssistantMessageID)
+ if err != nil {
+ return nil, nil, nil, nil, stop, err
+ }
+ if snapshot == nil || snapshot.PromptID != prompt.ID {
+ return nil, nil, nil, nil, stop, errors.New("the saved run state is missing")
+ }
+ if session, err = s.sessions.GetSession(ctx, run.SessionID); err != nil {
+ return nil, nil, nil, nil, stop, err
+ }
+ if answer, err = s.messages.GetMessage(ctx, run.SessionID, run.AssistantMessageID); err != nil {
+ return nil, nil, nil, nil, stop, err
+ }
+ if answer == nil || answer.IsCompleted {
+ return nil, nil, nil, nil, stop, errors.New("the run's message was closed")
+ }
+ answer.RunState = ""
+ answer.UpdatedAt = s.now()
+ if err := s.messages.UpdateMessage(ctx, answer); err != nil {
+ return nil, nil, nil, nil, stop, err
+ }
+ resume = &types.AgentResume{Snapshot: []byte(snapshot.Snapshot), Prompt: prompt}
+ return session, &types.Message{ID: run.UserMessageID}, answer, resume, stop, nil
+}
+
+// agentQA executes req, streaming to the run's message, and persists the
+// message.
+func (s *AutomationService) agentQA(
+ ctx context.Context, req *types.QARequest, session *types.Session, answer *types.Message,
+) runOutcome {
+ bus := event.NewEventBus()
+ var finishStream func(context.Context) error
+ if s.Events != nil && s.streams != nil {
+ if err := s.streams.SetLiveRun(ctx, session.ID, answer.ID, answer.RequestID); err != nil {
+ return failed("could not publish the run: " + err.Error())
+ }
+ defer func() {
+ if err := s.streams.ClearLiveRun(context.WithoutCancel(ctx), session.ID, answer.ID); err != nil {
+ logger.Warnf(ctx, "Clear automation live run: %v", err)
+ }
+ }()
+ if req.Resume != nil {
+ _ = s.streams.ResetEvents(ctx, session.ID, answer.ID)
+ }
+ answer.Content = ""
+ finishStream = s.Events(ctx, session, answer, bus)
+ data := map[string]any{
+ "session_id": session.ID, "assistant_message_id": answer.ID, "user_message_id": req.UserMessageID,
+ }
+ if req.Resume != nil {
+ data["resume_pending_id"] = req.Resume.Prompt.ID
+ data["resume_tool_call_id"] = req.Resume.Prompt.ToolCallID
+ }
+ if err := s.streams.AppendEvent(ctx, session.ID, answer.ID, interfaces.StreamEvent{
+ ID: "query-" + answer.ID, Type: types.ResponseTypeAgentQuery, Done: true, Timestamp: s.now(), Data: data,
+ }); err != nil {
+ return failed("could not publish the run: " + err.Error())
+ }
+ }
+ var mu sync.Mutex
+ var runErr error
+ var suspended *types.PromptSuspension
+ var usage *types.TokenUsage
+ completed := false
+ bus.On(event.EventAgentComplete, func(_ context.Context, evt event.Event) error {
+ data, ok := evt.Data.(event.AgentCompleteData)
+ if !ok {
+ return nil
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ completed = true
+ if u, ok := data.Usage.(*types.TokenUsage); ok {
+ usage = u
+ }
+ if finishStream == nil {
+ answer.Content = data.FinalAnswer
+ answer.AgentDurationMs = data.TotalDurationMs
+ if steps, ok := data.AgentSteps.([]types.AgentStep); ok {
+ answer.AgentSteps = tools.SanitizeAgentStepsForStorage(steps)
+ }
+ answer.Usage = usage
+ }
+ if p, ok := data.Suspended.(*types.PromptSuspension); ok && p != nil {
+ suspended = p
+ answer.RunState = types.MessageRunStateAwaitingInput
+ }
+ return nil
+ })
+ bus.On(event.EventError, func(_ context.Context, evt event.Event) error {
+ if data, ok := evt.Data.(event.ErrorData); ok {
+ mu.Lock()
+ runErr = errors.New(data.Error)
+ mu.Unlock()
+ }
+ return nil
+ })
+ err := func() (err error) {
+ defer func() {
+ if p := recover(); p != nil {
+ err = fmt.Errorf("agent executor panicked: %v", p)
+ }
+ }()
+ return s.sessions.AgentQA(ctx, req, bus)
+ }()
+ mu.Lock()
+ if err == nil {
+ err = runErr
+ }
+ if err == nil {
+ err = ctx.Err()
+ }
+ missing := !completed
+ mu.Unlock()
+ if finishStream != nil && missing {
+ if err != nil {
+ _ = bus.Emit(context.WithoutCancel(ctx), event.Event{
+ Type: event.EventError, Data: event.ErrorData{Error: err.Error(), Stage: "automation"},
+ })
+ }
+ _ = bus.Emit(context.WithoutCancel(ctx), event.Event{
+ Type: event.EventAgentComplete, Data: event.AgentCompleteData{MessageID: answer.ID},
+ })
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ answer.IsCompleted = suspended == nil
+ answer.UpdatedAt = s.now()
+ if err != nil && answer.Content == "" {
+ answer.Content = err.Error()
+ }
+ persistCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
+ defer cancel()
+ if saveErr := s.messages.UpdateMessage(persistCtx, answer); saveErr != nil && err == nil {
+ err = saveErr
+ }
+ if finishStream != nil {
+ if streamErr := finishStream(persistCtx); streamErr != nil && err == nil {
+ err = streamErr
+ }
+ }
+ out := runOutcome{answer: answer.Content, usage: usage}
+ switch {
+ case suspended != nil && err == nil:
+ out.status, out.promptID = types.AutomationRunAwaitingApproval, suspended.PromptID
+ case err != nil:
+ out.status, out.reason = types.AutomationRunFailed, err.Error()
+ default:
+ out.status = types.AutomationRunSucceeded
+ }
+ return out
+}
diff --git a/internal/application/service/automation_scheduler.go b/internal/application/service/automation_scheduler.go
new file mode 100644
index 000000000..6c2196c70
--- /dev/null
+++ b/internal/application/service/automation_scheduler.go
@@ -0,0 +1,543 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/automation"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/types"
+ "gorm.io/gorm"
+ "gorm.io/gorm/clause"
+)
+
+const (
+ automationClaimBatch = 50
+ automationPruneEvery = time.Hour
+)
+
+// Start schedules automations until ctx ends. Every instance runs it: due
+// automations and queued runs are claimed by compare-and-set in the
+// database, so each run executes once however many instances look.
+func (s *AutomationService) Start(ctx context.Context) {
+ go func() {
+ ticker := time.NewTicker(s.cfg.Tick)
+ defer ticker.Stop()
+ var pruned time.Time
+ for {
+ s.tick(ctx)
+ if time.Since(pruned) >= automationPruneEvery {
+ pruned = time.Now()
+ s.prune(ctx)
+ }
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ case <-s.wake:
+ }
+ }
+ }()
+}
+
+func (s *AutomationService) tick(ctx context.Context) {
+ defer func() {
+ if r := recover(); r != nil {
+ logger.Errorf(ctx, "Automation scheduler panicked: %v", r)
+ }
+ }()
+ now := s.now()
+ steps := []struct {
+ name string
+ run func(context.Context, time.Time) error
+ }{
+ {"claim due automations", s.claimDue},
+ {"reconcile waiting runs", s.reconcileAwaiting},
+ {"expire abandoned runs", s.expireLeases},
+ {"start queued runs", s.startQueued},
+ }
+ for _, step := range steps {
+ if err := step.run(ctx, now); err != nil && ctx.Err() == nil {
+ logger.Warnf(ctx, "Automation scheduler: %s: %v", step.name, err)
+ }
+ }
+}
+
+// misfireGrace is how late a due time may be seen and still count as on
+// time rather than missed.
+func (s *AutomationService) misfireGrace() time.Duration {
+ return max(2*s.cfg.Tick, time.Minute)
+}
+
+func (s *AutomationService) claimDue(ctx context.Context, now time.Time) error {
+ var due []*types.Automation
+ if err := s.db.WithContext(ctx).
+ Where("enabled = ? AND next_run_at IS NOT NULL AND next_run_at <= ?", true, now).
+ Order("next_run_at").Limit(automationClaimBatch).Find(&due).Error; err != nil {
+ return err
+ }
+ for _, a := range due {
+ if err := s.claim(ctx, a, now); err != nil {
+ logger.Warnf(ctx, "Claim automation %s: %v", a.ID, err)
+ }
+ }
+ return nil
+}
+
+// claim advances a past its due time and records the run that time is
+// owed, unless another instance did first.
+func (s *AutomationService) claim(ctx context.Context, a *types.Automation, now time.Time) error {
+ sched, err := automation.Parse(a.Trigger)
+ if err != nil {
+ return s.pause(ctx, a, "the trigger is no longer valid: "+err.Error())
+ }
+ dueAt := a.NextRunAt.UTC()
+ next := sched.Next(now)
+ kind := types.AutomationRunSchedule
+ if now.Sub(dueAt) > s.misfireGrace() {
+ kind = types.AutomationRunMisfire
+ if a.MisfirePolicy != types.AutomationPolicyRunOnce {
+ kind = ""
+ }
+ }
+ queued := false
+ err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ res := tx.Model(&types.Automation{}).Where("id = ? AND version = ?", a.ID, a.Version).
+ Updates(map[string]any{
+ "next_run_at": next, "enabled": next != nil, "version": a.Version + 1, "updated_at": now,
+ })
+ if res.Error != nil || res.RowsAffected == 0 || kind == "" {
+ return res.Error
+ }
+ run := &types.AutomationRun{
+ AutomationID: a.ID, TenantID: a.TenantID, ScheduledAt: dueAt, TriggerKind: kind,
+ Status: types.AutomationRunQueued,
+ }
+ if reason, err := s.overlap(tx, a); err != nil {
+ return err
+ } else if reason != "" {
+ run.Status, run.Error, run.FinishedAt = types.AutomationRunSkipped, reason, &now
+ }
+ if err := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(run).Error; err != nil {
+ return err
+ }
+ queued = run.Status == types.AutomationRunQueued
+ return nil
+ })
+ if err == nil && queued {
+ s.Wake()
+ }
+ return err
+}
+
+// overlap is why a new run of a must be skipped, or "" when it may queue.
+func (s *AutomationService) overlap(tx *gorm.DB, a *types.Automation) (string, error) {
+ var live []types.AutomationRun
+ if err := tx.Select("status").Where("automation_id = ? AND status IN ?", a.ID, []string{
+ types.AutomationRunQueued, types.AutomationRunRunning, types.AutomationRunAwaitingApproval,
+ }).Find(&live).Error; err != nil {
+ return "", err
+ }
+ if len(live) == 0 {
+ return "", nil
+ }
+ if a.OverlapPolicy != types.AutomationPolicyQueue {
+ return "the previous run was still in progress", nil
+ }
+ for _, r := range live {
+ if r.Status == types.AutomationRunQueued {
+ return "a run was already queued", nil
+ }
+ }
+ return "", nil
+}
+
+// startQueued claims queued runs while this instance has free slots. A run
+// waits while another run of its automation holds it.
+func (s *AutomationService) startQueued(ctx context.Context, now time.Time) error {
+ free := cap(s.slots) - len(s.slots)
+ if free <= 0 {
+ return nil
+ }
+ var queued []*types.AutomationRun
+ if err := s.db.WithContext(ctx).Where("status = ?", types.AutomationRunQueued).
+ Order("resume DESC, scheduled_at").Limit(free * 4).Find(&queued).Error; err != nil {
+ return err
+ }
+ for _, run := range queued {
+ select {
+ case s.slots <- struct{}{}:
+ default:
+ return nil
+ }
+ started, err := s.startRun(ctx, run, now)
+ if err != nil || !started {
+ <-s.slots
+ if err != nil {
+ logger.Warnf(ctx, "Start automation run %s: %v", run.ID, err)
+ }
+ continue
+ }
+ go s.execute(ctx, run)
+ }
+ return nil
+}
+
+func (s *AutomationService) startRun(ctx context.Context, run *types.AutomationRun, now time.Time) (bool, error) {
+ var holding int64
+ if err := s.db.WithContext(ctx).Model(&types.AutomationRun{}).
+ Where("automation_id = ? AND id <> ? AND status IN ?", run.AutomationID, run.ID, []string{
+ types.AutomationRunRunning, types.AutomationRunAwaitingApproval,
+ }).Count(&holding).Error; err != nil {
+ return false, err
+ }
+ if holding > 0 {
+ return false, nil
+ }
+ lease := now.Add(s.cfg.Lease)
+ updates := map[string]any{
+ "status": types.AutomationRunRunning, "owner": s.instance, "lease_until": lease, "updated_at": now,
+ }
+ if run.StartedAt == nil {
+ updates["started_at"] = now
+ }
+ res := s.db.WithContext(ctx).Model(&types.AutomationRun{}).
+ Where("id = ? AND status = ?", run.ID, types.AutomationRunQueued).Updates(updates)
+ if res.Error != nil || res.RowsAffected == 0 {
+ return false, res.Error
+ }
+ run.Status, run.Owner, run.LeaseUntil = types.AutomationRunRunning, s.instance, &lease
+ if run.StartedAt == nil {
+ run.StartedAt = &now
+ }
+ return true, nil
+}
+
+// expireLeases ends runs whose instance stopped renewing them. What their
+// tool calls did is unknown, so they are never replayed.
+func (s *AutomationService) expireLeases(ctx context.Context, now time.Time) error {
+ var stale []*types.AutomationRun
+ if err := s.db.WithContext(ctx).Where("status = ? AND lease_until < ?", types.AutomationRunRunning, now).
+ Limit(automationClaimBatch).Find(&stale).Error; err != nil {
+ return err
+ }
+ for _, run := range stale {
+ ok, err := s.finishRun(ctx, run, []string{types.AutomationRunRunning},
+ types.AutomationRunNeedsAttention,
+ "the instance executing this run stopped; check the conversation for what it already did",
+ func(db *gorm.DB) *gorm.DB { return db.Where("lease_until < ?", now) })
+ if err != nil {
+ return err
+ }
+ if ok {
+ s.closeAbandonedMessage(ctx, run)
+ }
+ }
+ return nil
+}
+
+// closeAbandonedMessage completes the message of a run whose executor died,
+// so its conversation does not look generating forever.
+func (s *AutomationService) closeAbandonedMessage(ctx context.Context, run *types.AutomationRun) {
+ if run.SessionID == "" || run.AssistantMessageID == "" {
+ return
+ }
+ msg, err := s.messages.GetMessage(ctx, run.SessionID, run.AssistantMessageID)
+ if err != nil || msg == nil || msg.IsCompleted || msg.RunState == types.MessageRunStateAwaitingInput {
+ return
+ }
+ msg.IsCompleted, msg.UpdatedAt = true, s.now()
+ if msg.Content == "" {
+ msg.Content = "The run was interrupted."
+ }
+ if err := s.messages.UpdateMessage(ctx, msg); err != nil {
+ logger.Warnf(ctx, "Close message of abandoned automation run %s: %v", run.ID, err)
+ }
+ if s.streams != nil {
+ _ = s.streams.ClearLiveRun(ctx, run.SessionID, run.AssistantMessageID)
+ }
+}
+
+// reconcileAwaiting moves waiting runs on once their approval is answered,
+// and fails those whose approval ended any other way or timed out.
+func (s *AutomationService) reconcileAwaiting(ctx context.Context, now time.Time) error {
+ if s.broker == nil {
+ return nil
+ }
+ var waiting []*types.AutomationRun
+ if err := s.db.WithContext(ctx).Where("status = ?", types.AutomationRunAwaitingApproval).
+ Order("updated_at").Limit(automationClaimBatch * 2).Find(&waiting).Error; err != nil {
+ return err
+ }
+ for _, run := range waiting {
+ if err := s.reconcileRun(ctx, run, now); err != nil {
+ logger.Warnf(ctx, "Reconcile automation run %s: %v", run.ID, err)
+ }
+ }
+ return nil
+}
+
+func (s *AutomationService) reconcileRun(ctx context.Context, run *types.AutomationRun, now time.Time) error {
+ waiting := []string{types.AutomationRunAwaitingApproval}
+ prompt, err := s.broker.Store().Get(ctx, run.PendingPromptID)
+ if err != nil {
+ return err
+ }
+ if prompt == nil {
+ _, err := s.finishRun(ctx, run, waiting, types.AutomationRunFailed, "the approval it waited for is gone", nil)
+ return err
+ }
+ switch {
+ case prompt.Status == types.AgentPromptAnswered:
+ return s.queueResume(ctx, run.ID, prompt.ID)
+ case prompt.IsOpen():
+ var a types.Automation
+ if err := s.db.WithContext(ctx).Unscoped().Where("id = ?", run.AutomationID).First(&a).Error; err != nil {
+ return err
+ }
+ timeout := time.Duration(a.ApprovalTimeoutMinutes) * time.Minute
+ if a.DeletedAt.Valid || now.Sub(run.UpdatedAt) < timeout {
+ return nil
+ }
+ reason := fmt.Sprintf("no approval within %d minutes", a.ApprovalTimeoutMinutes)
+ ok, err := s.finishRun(ctx, run, waiting, types.AutomationRunFailed, reason, nil)
+ if ok {
+ s.closePrompt(ctx, prompt.ID, types.AgentPromptExpired, reason)
+ }
+ return err
+ case prompt.Status == types.AgentPromptExecuting:
+ // A resumed run is executing the approved call; it owns the run.
+ return nil
+ default:
+ reason := "the approval ended without an answer"
+ if prompt.CloseReason != "" {
+ reason = "the approval ended: " + prompt.CloseReason
+ }
+ _, err := s.finishRun(ctx, run, waiting, types.AutomationRunFailed, reason, nil)
+ return err
+ }
+}
+
+// queueResume hands a waiting run whose approval was answered back to the
+// queue, to continue from the answer.
+func (s *AutomationService) queueResume(ctx context.Context, runID, promptID string) error {
+ res := s.db.WithContext(ctx).Model(&types.AutomationRun{}).
+ Where("id = ? AND status = ? AND pending_prompt_id = ?", runID, types.AutomationRunAwaitingApproval, promptID).
+ Updates(map[string]any{"status": types.AutomationRunQueued, "resume": true, "updated_at": s.now()})
+ if res.Error == nil && res.RowsAffected > 0 {
+ s.Wake()
+ }
+ return res.Error
+}
+
+// promptRun is the run of an automation that raised prompt p, if any.
+func (s *AutomationService) promptRun(ctx context.Context, p *types.AgentPrompt) (*types.AutomationRun, error) {
+ if p == nil || p.SessionID == "" || p.AssistantMessageID == "" {
+ return nil, nil
+ }
+ var run types.AutomationRun
+ err := s.db.WithContext(ctx).
+ Where("tenant_id = ? AND session_id = ? AND assistant_message_id = ? AND status IN ?",
+ p.TenantID, p.SessionID, p.AssistantMessageID, []string{
+ types.AutomationRunQueued, types.AutomationRunRunning, types.AutomationRunAwaitingApproval,
+ }).First(&run).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, nil
+ }
+ return &run, err
+}
+
+// HandlesPrompt claims the prompts automation runs raise, so answering one
+// continues the run under the automation instead of as an ordinary chat.
+// It fails closed: when it cannot tell, the prompt is left to the scheduler.
+func (s *AutomationService) HandlesPrompt(ctx context.Context, p *types.AgentPrompt) bool {
+ run, err := s.promptRun(ctx, p)
+ if err != nil {
+ logger.Warnf(ctx, "Classify prompt %s for automation resume: %v", p.ID, err)
+ return true
+ }
+ if run == nil {
+ return false
+ }
+ if p.Status == types.AgentPromptAnswered && run.Status == types.AutomationRunAwaitingApproval {
+ if err := s.queueResume(ctx, run.ID, p.ID); err != nil {
+ logger.Warnf(ctx, "Queue automation run %s to resume: %v", run.ID, err)
+ }
+ }
+ return true
+}
+
+// RecoverAnswered keeps an answered prompt of an automation run alive until
+// the scheduler resumes the run.
+func (s *AutomationService) RecoverAnswered(ctx context.Context, p *types.AgentPrompt) (bool, error) {
+ run, err := s.promptRun(ctx, p)
+ if err != nil || run == nil || s.broker == nil {
+ return false, err
+ }
+ if run.Status == types.AutomationRunAwaitingApproval {
+ if err := s.queueResume(ctx, run.ID, p.ID); err != nil {
+ return false, err
+ }
+ }
+ until := s.now().Add(30 * time.Second)
+ return s.broker.Store().Transition(ctx, p.ID, types.AgentPromptTransition{
+ From: []string{types.AgentPromptAnswered}, To: types.AgentPromptAnswered,
+ ExpectedOwner: &p.OwnerInstance, LeaseUntil: &until,
+ })
+}
+
+// finishRun moves run from one of from to status and settles its
+// automation. narrow, when set, adds conditions to the update.
+func (s *AutomationService) finishRun(
+ ctx context.Context, run *types.AutomationRun, from []string, status, reason string,
+ narrow func(*gorm.DB) *gorm.DB,
+) (bool, error) {
+ now := s.now()
+ query := s.db.WithContext(context.WithoutCancel(ctx)).Model(&types.AutomationRun{}).
+ Where("id = ? AND status IN ?", run.ID, from)
+ if narrow != nil {
+ query = narrow(query)
+ }
+ res := query.Updates(map[string]any{
+ "status": status, "error": reason, "finished_at": now, "updated_at": now, "lease_until": nil,
+ })
+ if res.Error != nil || res.RowsAffected == 0 {
+ return false, res.Error
+ }
+ run.Status, run.Error, run.FinishedAt = status, reason, &now
+ s.settle(ctx, run)
+ return true, nil
+}
+
+// settle records a finished run on its automation, pauses it after too many
+// failures in a row, and notifies the owner.
+func (s *AutomationService) settle(ctx context.Context, run *types.AutomationRun) {
+ ctx = context.WithoutCancel(ctx)
+ var a types.Automation
+ if err := s.db.WithContext(ctx).Where("id = ?", run.AutomationID).First(&a).Error; err != nil {
+ return
+ }
+ updates := map[string]any{"last_run_status": run.Status}
+ if run.Status != types.AutomationRunSkipped {
+ updates["last_run_at"] = run.ScheduledAt
+ }
+ failure := run.Status == types.AutomationRunFailed || run.Status == types.AutomationRunNeedsAttention
+ switch {
+ case run.Status == types.AutomationRunSucceeded:
+ updates["last_success_at"] = run.FinishedAt
+ updates["consecutive_failures"] = 0
+ case failure:
+ updates["consecutive_failures"] = gorm.Expr("consecutive_failures + 1")
+ }
+ if err := s.db.WithContext(ctx).Model(&types.Automation{}).Where("id = ?", a.ID).
+ Updates(updates).Error; err != nil {
+ logger.Warnf(ctx, "Record run %s on automation %s: %v", run.ID, a.ID, err)
+ }
+ switch {
+ case run.Status == types.AutomationRunSucceeded && a.NotifyOnSuccess:
+ s.notify(ctx, &a, run, types.NotificationAutomationSucceeded, run.Answer)
+ case failure:
+ s.notify(ctx, &a, run, types.NotificationAutomationFailed, run.Error)
+ if a.ConsecutiveFailures+1 >= s.cfg.FailuresBeforePause && a.Enabled {
+ _ = s.pause(ctx, &a, fmt.Sprintf("%d runs in a row failed", a.ConsecutiveFailures+1))
+ }
+ }
+}
+
+// pause disables a for reason and tells the owner.
+func (s *AutomationService) pause(ctx context.Context, a *types.Automation, reason string) error {
+ res := s.db.WithContext(context.WithoutCancel(ctx)).Model(&types.Automation{}).
+ Where("id = ? AND enabled = ?", a.ID, true).
+ Updates(map[string]any{
+ "enabled": false, "next_run_at": nil, "paused_reason": reason,
+ "version": gorm.Expr("version + 1"), "updated_at": s.now(),
+ })
+ if res.Error != nil || res.RowsAffected == 0 {
+ return res.Error
+ }
+ s.notify(ctx, a, nil, types.NotificationAutomationPaused, reason)
+ return nil
+}
+
+func (s *AutomationService) notify(
+ ctx context.Context, a *types.Automation, run *types.AutomationRun, kind, body string,
+) {
+ n := &types.Notification{
+ TenantID: a.TenantID, UserID: a.OwnerUserID, Kind: kind, Title: a.Name, Body: body,
+ SourceType: "automation", SourceID: a.ID, Link: "/platform/automations/" + a.ID,
+ }
+ if run != nil {
+ n.Link += "?run=" + run.ID
+ }
+ s.notices.Notify(ctx, n)
+}
+
+// prune keeps the newest runs of each automation and drops the runs, and
+// per-run conversations, beyond them or of deleted automations.
+func (s *AutomationService) prune(ctx context.Context) {
+ finished := []string{
+ types.AutomationRunSucceeded, types.AutomationRunFailed, types.AutomationRunCancelled,
+ types.AutomationRunSkipped, types.AutomationRunNeedsAttention,
+ }
+ var over []struct {
+ AutomationID string
+ N int64
+ }
+ if err := s.db.WithContext(ctx).Model(&types.AutomationRun{}).Select("automation_id, count(*) AS n").
+ Group("automation_id").Having("count(*) > ?", s.cfg.Retention).Scan(&over).Error; err != nil {
+ logger.Warnf(ctx, "Prune automation runs: %v", err)
+ return
+ }
+ for _, o := range over {
+ var cutoff types.AutomationRun
+ if err := s.db.WithContext(ctx).Where("automation_id = ?", o.AutomationID).
+ Order("scheduled_at DESC").Offset(s.cfg.Retention).Limit(1).Take(&cutoff).Error; err != nil {
+ continue
+ }
+ old := s.db.Model(&types.AutomationRun{}).
+ Where("automation_id = ? AND scheduled_at <= ? AND status IN ?",
+ o.AutomationID, cutoff.ScheduledAt, finished)
+ s.dropRuns(ctx, old)
+ }
+ orphaned := s.db.Model(&types.AutomationRun{}).Where("status IN ?", finished).
+ Where("automation_id NOT IN (?)", s.db.Model(&types.Automation{}).Select("id"))
+ s.dropRuns(ctx, orphaned)
+ if err := s.notices.Prune(ctx); err != nil {
+ logger.Warnf(ctx, "Prune notifications: %v", err)
+ }
+}
+
+func (s *AutomationService) dropRuns(ctx context.Context, runs *gorm.DB) {
+ var rows []types.AutomationRun
+ if err := runs.WithContext(ctx).Select("id, session_id").Limit(1000).Find(&rows).Error; err != nil {
+ logger.Warnf(ctx, "Prune automation runs: %v", err)
+ return
+ }
+ if len(rows) == 0 {
+ return
+ }
+ ids, sessions := make([]string, 0, len(rows)), make([]string, 0, len(rows))
+ for _, r := range rows {
+ ids = append(ids, r.ID)
+ if r.SessionID != "" {
+ sessions = append(sessions, r.SessionID)
+ }
+ }
+ err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if len(sessions) > 0 {
+ persistent := tx.Model(&types.Automation{}).Unscoped().Select("persistent_session_id").
+ Where("persistent_session_id <> ''")
+ if err := tx.Where("kind = ? AND id IN ? AND id NOT IN (?)",
+ types.SessionKindAutomation, sessions, persistent).
+ Delete(&types.Session{}).Error; err != nil {
+ return err
+ }
+ }
+ return tx.Where("id IN ?", ids).Delete(&types.AutomationRun{}).Error
+ })
+ if err != nil {
+ logger.Warnf(ctx, "Prune automation runs: %v", err)
+ }
+}
diff --git a/internal/application/service/automation_test.go b/internal/application/service/automation_test.go
new file mode 100644
index 000000000..952ad4086
--- /dev/null
+++ b/internal/application/service/automation_test.go
@@ -0,0 +1,559 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "path/filepath"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/agent"
+ "github.com/Tencent/WeKnora/internal/agent/hitl"
+ "github.com/Tencent/WeKnora/internal/application/repository"
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/event"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/require"
+ "gorm.io/driver/sqlite"
+ "gorm.io/gorm"
+ "gorm.io/gorm/logger"
+)
+
+const automationTenant uint64 = 7
+
+type automationMessages struct {
+ interfaces.MessageService
+ mu sync.Mutex
+ rows map[string]*types.Message
+}
+
+func (f *automationMessages) CreateMessage(_ context.Context, m *types.Message) (*types.Message, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ m.ID = uuid.NewString()
+ copied := *m
+ f.rows[m.ID] = &copied
+ return m, nil
+}
+
+func (f *automationMessages) GetMessage(_ context.Context, _, id string) (*types.Message, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ m, ok := f.rows[id]
+ if !ok {
+ return nil, errors.New("message not found")
+ }
+ copied := *m
+ return &copied, nil
+}
+
+func (f *automationMessages) UpdateMessage(_ context.Context, m *types.Message) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ copied := *m
+ f.rows[m.ID] = &copied
+ return nil
+}
+
+// automationCall is what one AgentQA call of a run saw.
+type automationCall struct {
+ req *types.QARequest
+ mode types.RunMode
+ via string
+ standing types.GrantScope
+}
+
+type automationSessions struct {
+ interfaces.SessionService
+ db *gorm.DB
+ mu sync.Mutex
+ calls []automationCall
+ run func(context.Context, *types.QARequest, *event.EventBus) error
+}
+
+func (f *automationSessions) GetSession(ctx context.Context, id string) (*types.Session, error) {
+ var s types.Session
+ if err := f.db.WithContext(ctx).Where("id = ?", id).First(&s).Error; err != nil {
+ return nil, err
+ }
+ return &s, nil
+}
+
+func (f *automationSessions) AgentQA(ctx context.Context, req *types.QARequest, bus *event.EventBus) error {
+ principal, _ := types.PrincipalFromContext(ctx)
+ standing, _ := types.StandingGrantScopeFromContext(ctx)
+ f.mu.Lock()
+ f.calls = append(f.calls, automationCall{req: req, mode: req.Mode, via: principal.ActingVia, standing: standing})
+ f.mu.Unlock()
+ return f.run(ctx, req, bus)
+}
+
+func (f *automationSessions) last() automationCall {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.calls[len(f.calls)-1]
+}
+
+func complete(ctx context.Context, bus *event.EventBus, data event.AgentCompleteData) error {
+ return bus.Emit(ctx, event.Event{Type: event.EventAgentComplete, Data: data})
+}
+
+type automationFixture struct {
+ svc *AutomationService
+ db *gorm.DB
+ sessions *automationSessions
+ messages *automationMessages
+ users *collaborationUsers
+ members *collaborationMembers
+ agents *collaborationAgents
+ broker *hitl.Broker
+ now time.Time
+ ctx context.Context
+}
+
+func newAutomationFixture(t *testing.T) *automationFixture {
+ t.Helper()
+ db, err := gorm.Open(
+ sqlite.Open(filepath.Join(t.TempDir(), "automation.db")+"?_busy_timeout=5000&_journal_mode=WAL"),
+ &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)},
+ )
+ require.NoError(t, err)
+ raw, err := db.DB()
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = raw.Close() })
+ require.NoError(t, db.AutoMigrate(&types.Automation{}, &types.AutomationRun{}, &types.Notification{},
+ &types.Session{}, &types.AgentGrant{}, &types.AgentPrompt{}))
+ f := &automationFixture{
+ db: db,
+ messages: &automationMessages{rows: map[string]*types.Message{}},
+ users: &collaborationUsers{active: true},
+ members: &collaborationMembers{active: true},
+ agents: &collaborationAgents{agent: &types.CustomAgent{
+ ID: "a", TenantID: automationTenant,
+ Config: types.CustomAgentConfig{AgentMode: types.AgentModeSmartReasoning, AllowedTools: []string{"x"}},
+ }},
+ broker: hitl.NewBroker(nil, nil),
+ now: time.Date(2026, 10, 19, 1, 0, 0, 0, time.UTC),
+ }
+ done := func(ctx context.Context, _ *types.QARequest, bus *event.EventBus) error {
+ return complete(ctx, bus, event.AgentCompleteData{FinalAnswer: "done"})
+ }
+ f.sessions = &automationSessions{db: db, run: done}
+ f.svc = NewAutomationService(db, f.agents, f.users, f.members, &collaborationTenants{},
+ f.messages, repository.NewAgentGrantRepository(db), NewNotificationService(db))
+ f.svc.now = func() time.Time { return f.now }
+ f.svc.Bind(f.sessions, f.broker, nil, nil)
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, automationTenant)
+ ctx = context.WithValue(ctx, types.UserIDContextKey, "u")
+ ctx = types.WithCaller(ctx, types.Caller{
+ TenantID: automationTenant, UserID: "u", Role: types.TenantRoleContributor,
+ })
+ f.ctx = types.WithPrincipal(ctx, types.Principal{Type: types.PrincipalWebUser, ID: "u"})
+ return f
+}
+
+func (f *automationFixture) create(t *testing.T, p types.AutomationPatch) *types.Automation {
+ t.Helper()
+ if p.Name == nil {
+ p.Name = ptr("daily")
+ }
+ if p.Instruction == nil {
+ p.Instruction = ptr("summarize {{automation_name}} at {{now}}")
+ }
+ if p.AgentID == nil {
+ p.AgentID = ptr("a")
+ }
+ if p.Trigger == nil {
+ p.Trigger = &types.AutomationTrigger{Type: types.AutomationTriggerCron, Expr: "0 9 * * *"}
+ }
+ a, err := f.svc.Create(f.ctx, &p)
+ require.NoError(t, err)
+ return a
+}
+
+func (f *automationFixture) runs(t *testing.T, id string) []types.AutomationRun {
+ t.Helper()
+ var runs []types.AutomationRun
+ require.NoError(t, f.db.Where("automation_id = ?", id).Order("scheduled_at, created_at").Find(&runs).Error)
+ return runs
+}
+
+func (f *automationFixture) reload(t *testing.T, id string) *types.Automation {
+ t.Helper()
+ var a types.Automation
+ require.NoError(t, f.db.Unscoped().Where("id = ?", id).First(&a).Error)
+ return &a
+}
+
+// settleRun runs scheduler ticks until run id rests.
+func (f *automationFixture) settleRun(t *testing.T, id string) types.AutomationRun {
+ t.Helper()
+ var run types.AutomationRun
+ require.Eventually(t, func() bool {
+ f.svc.tick(context.Background())
+ require.NoError(t, f.db.Where("id = ?", id).First(&run).Error)
+ return run.Status != types.AutomationRunQueued && run.Status != types.AutomationRunRunning &&
+ len(f.svc.slots) == 0
+ }, 5*time.Second, 10*time.Millisecond)
+ return run
+}
+
+func TestAutomationCreateValidatesAndSchedules(t *testing.T) {
+ f := newAutomationFixture(t)
+ a := f.create(t, types.AutomationPatch{Trigger: &types.AutomationTrigger{
+ Type: types.AutomationTriggerCron, Expr: "0 9 * * *", Timezone: "Asia/Shanghai",
+ }})
+ require.Equal(t, time.Date(2026, 10, 20, 1, 0, 0, 0, time.UTC), a.NextRunAt.UTC())
+ require.Equal(t, types.AssistantAccessConfirm, a.AccessLevel)
+ require.Equal(t, types.AutomationSessionPerRun, a.SessionMode)
+
+ for name, p := range map[string]types.AutomationPatch{
+ "too frequent": {Trigger: &types.AutomationTrigger{Type: types.AutomationTriggerCron, Expr: "* * * * *"}},
+ "bad agent": {AgentID: ptr("builtin-wiki-fixer")},
+ "bad mode": {SessionMode: ptr("forever")},
+ "once in past": {Trigger: &types.AutomationTrigger{
+ Type: types.AutomationTriggerOnce, At: f.now.Add(-time.Hour).Format(time.RFC3339),
+ }},
+ } {
+ p.Name, p.Instruction = ptr("n"), ptr("i")
+ if p.AgentID == nil {
+ p.AgentID = ptr("a")
+ }
+ if p.Trigger == nil {
+ p.Trigger = &types.AutomationTrigger{Type: types.AutomationTriggerCron, Expr: "0 9 * * *"}
+ }
+ _, err := f.svc.Create(f.ctx, &p)
+ var appErr *apperrors.AppError
+ require.Truef(t, errors.As(err, &appErr), "%s: %v", name, err)
+ }
+
+ other := types.WithCaller(f.ctx, types.Caller{TenantID: automationTenant, UserID: "v"})
+ other = types.WithPrincipal(other, types.Principal{Type: types.PrincipalWebUser, ID: "v"})
+ _, err := f.svc.Get(other, a.ID)
+ require.Error(t, err)
+ list, err := f.svc.List(other)
+ require.NoError(t, err)
+ require.Empty(t, list)
+
+ acting := types.WithPrincipal(f.ctx, types.Principal{
+ Type: types.PrincipalWebUser, ID: "u", ActingVia: "automation:x",
+ })
+ _, err = f.svc.List(acting)
+ require.Error(t, err, "an automation run must not manage automations")
+}
+
+func TestAutomationClaimRunsOnceAcrossInstances(t *testing.T) {
+ f := newAutomationFixture(t)
+ a := f.create(t, types.AutomationPatch{})
+ f.now = a.NextRunAt.Add(time.Second)
+ stale := *a
+ require.NoError(t, f.svc.claim(f.ctx, a, f.now))
+ require.NoError(t, f.svc.claim(f.ctx, &stale, f.now))
+ runs := f.runs(t, a.ID)
+ require.Len(t, runs, 1)
+ require.Equal(t, types.AutomationRunSchedule, runs[0].TriggerKind)
+ require.Equal(t, a.NextRunAt.UTC(), runs[0].ScheduledAt.UTC())
+ require.True(t, f.reload(t, a.ID).NextRunAt.After(f.now))
+}
+
+func TestAutomationMisfireAndOverlap(t *testing.T) {
+ f := newAutomationFixture(t)
+ skip := f.create(t, types.AutomationPatch{})
+ catchUp := f.create(t, types.AutomationPatch{MisfirePolicy: ptr(types.AutomationPolicyRunOnce)})
+ f.now = skip.NextRunAt.Add(3 * 24 * time.Hour)
+ require.NoError(t, f.svc.claimDue(f.ctx, f.now))
+ require.Empty(t, f.runs(t, skip.ID))
+ runs := f.runs(t, catchUp.ID)
+ require.Len(t, runs, 1)
+ require.Equal(t, types.AutomationRunMisfire, runs[0].TriggerKind)
+
+ // The caught-up run is still queued, so the next due run is skipped.
+ f.now = f.reload(t, catchUp.ID).NextRunAt.Add(time.Second)
+ require.NoError(t, f.svc.claimDue(f.ctx, f.now))
+ runs = f.runs(t, catchUp.ID)
+ require.Len(t, runs, 2)
+ require.Equal(t, types.AutomationRunSkipped, runs[1].Status)
+}
+
+func TestAutomationRunSucceedsAsOwnerUnattended(t *testing.T) {
+ f := newAutomationFixture(t)
+ a := f.create(t, types.AutomationPatch{AccessLevel: ptr(types.AssistantAccessAutoWrite)})
+ run, err := f.svc.RunNow(f.ctx, a.ID)
+ require.NoError(t, err)
+ _, err = f.svc.RunNow(f.ctx, a.ID)
+ require.Error(t, err, "a second manual run while one is queued")
+
+ done := f.settleRun(t, run.ID)
+ require.Equal(t, types.AutomationRunSucceeded, done.Status)
+ require.Equal(t, "done", done.Answer)
+ call := f.sessions.last()
+ require.Equal(t, types.RunModeDeferred, call.mode)
+ require.Equal(t, types.AutomationActingVia(a.ID), call.via)
+ require.Equal(t, types.GrantScope{
+ Scope: types.AgentGrantScopeAutomation, ScopeID: a.ID,
+ BindingHash: automationBinding(
+ f.agents.agent, &types.Tenant{ID: automationTenant}, types.TenantRoleContributor),
+ }, call.standing)
+ require.Equal(t, types.AssistantAccessAutoWrite, call.req.AssistantAccess)
+ require.Contains(t, call.req.Query, "summarize daily at ")
+ require.Contains(t, call.req.RunNote, "No user is watching")
+
+ var session types.Session
+ require.NoError(t, f.db.Where("id = ?", done.SessionID).First(&session).Error)
+ require.Equal(t, types.SessionKindAutomation, session.Kind)
+ require.Equal(t, "u", session.UserID)
+ stored := f.reload(t, a.ID)
+ require.Equal(t, types.AutomationRunSucceeded, stored.LastRunStatus)
+ require.NotNil(t, stored.LastSuccessAt)
+}
+
+func TestAutomationPersistentSessionCarriesAcrossRuns(t *testing.T) {
+ f := newAutomationFixture(t)
+ a := f.create(t, types.AutomationPatch{SessionMode: ptr(types.AutomationSessionPersistent)})
+ first, err := f.svc.RunNow(f.ctx, a.ID)
+ require.NoError(t, err)
+ r1 := f.settleRun(t, first.ID)
+ f.now = f.now.Add(time.Minute)
+ second, err := f.svc.RunNow(f.ctx, a.ID)
+ require.NoError(t, err)
+ r2 := f.settleRun(t, second.ID)
+ require.Equal(t, r1.SessionID, r2.SessionID)
+ require.Equal(t, r1.SessionID, f.reload(t, a.ID).PersistentSessionID)
+}
+
+func TestAutomationCarriesLastResult(t *testing.T) {
+ f := newAutomationFixture(t)
+ a := f.create(t, types.AutomationPatch{CarryLastResult: ptr(true)})
+ first, _ := f.svc.RunNow(f.ctx, a.ID)
+ f.settleRun(t, first.ID)
+ f.now = f.now.Add(time.Minute)
+ second, _ := f.svc.RunNow(f.ctx, a.ID)
+ f.settleRun(t, second.ID)
+ require.Contains(t, f.sessions.last().req.Query, "<previous_run_result>\ndone\n</previous_run_result>")
+}
+
+// suspendOnApproval makes the next run raise a suspended tool approval.
+func (f *automationFixture) suspendOnApproval(t *testing.T, grant string) {
+ f.sessions.run = func(ctx context.Context, req *types.QARequest, bus *event.EventBus) error {
+ if req.Resume != nil {
+ return complete(ctx, bus, event.AgentCompleteData{FinalAnswer: "resumed"})
+ }
+ request, _ := json.Marshal(types.ToolApprovalPromptRequest{
+ RegisteredToolName: "delete_doc", Grant: grant, GrantRisk: "destructive", GrantLabel: "documents in kb1",
+ })
+ prompt := &types.AgentPrompt{
+ ID: uuid.NewString(), TenantID: automationTenant, UserID: automationGrantUser("u"),
+ SessionID: req.Session.ID, AssistantMessageID: req.AssistantMessageID,
+ Kind: types.AgentPromptKindToolApproval, Status: types.AgentPromptSuspended, Suspendable: true,
+ Request: request, CreatedAt: f.now,
+ }
+ require.NoError(t, f.broker.Store().Create(ctx, prompt))
+ require.NoError(t, f.db.Create(prompt).Error)
+ snap, _ := json.Marshal(agent.RunSnapshot{Version: agent.RunSnapshotVersion, Query: req.Query})
+ require.NoError(t, f.broker.Suspensions().Save(ctx, &types.AgentRunSuspension{
+ AssistantMessageID: req.AssistantMessageID, PromptID: prompt.ID, SessionID: req.Session.ID,
+ Snapshot: snap,
+ }))
+ return complete(ctx, bus, event.AgentCompleteData{
+ Suspended: &types.PromptSuspension{PromptID: prompt.ID, Kind: prompt.Kind},
+ })
+ }
+}
+
+func TestAutomationSuspendsAndResumesAfterApproval(t *testing.T) {
+ f := newAutomationFixture(t)
+ a := f.create(t, types.AutomationPatch{})
+ f.suspendOnApproval(t, "op:knowledge.delete:kb1")
+ queued, _ := f.svc.RunNow(f.ctx, a.ID)
+ run := f.settleRun(t, queued.ID)
+ require.Equal(t, types.AutomationRunAwaitingApproval, run.Status)
+ require.NotEmpty(t, run.PendingPromptID)
+ page, err := NewNotificationService(f.db).List(f.ctx, 10, false)
+ require.NoError(t, err)
+ require.Equal(t, types.NotificationAutomationAwaitingApproval, page.Items[0].Kind)
+
+ prompt, _ := f.broker.Store().Get(f.ctx, run.PendingPromptID)
+ require.True(t, f.svc.HandlesPrompt(f.ctx, prompt), "an automation prompt is not resumed as a chat")
+ ok, err := f.broker.Store().Transition(f.ctx, prompt.ID, types.AgentPromptTransition{
+ From: []string{types.AgentPromptSuspended}, To: types.AgentPromptAnswered,
+ Response: types.JSON(`{"approved":true}`),
+ })
+ require.NoError(t, err)
+ require.True(t, ok)
+ prompt, _ = f.broker.Store().Get(f.ctx, prompt.ID)
+ require.True(t, f.svc.HandlesPrompt(f.ctx, prompt))
+
+ run = f.settleRun(t, run.ID)
+ require.Equal(t, types.AutomationRunSucceeded, run.Status)
+ require.Equal(t, "resumed", run.Answer)
+ call := f.sessions.last()
+ require.NotNil(t, call.req.Resume)
+ require.Equal(t, run.SessionID, call.req.Session.ID)
+ require.Equal(t, types.AutomationActingVia(a.ID), call.via)
+
+ // A prompt of an ordinary chat turn in the same conversation is not claimed.
+ require.False(t, f.svc.HandlesPrompt(f.ctx, &types.AgentPrompt{
+ ID: "p2", TenantID: automationTenant, SessionID: run.SessionID, AssistantMessageID: "other",
+ }))
+}
+
+func TestAutomationApprovalTimesOut(t *testing.T) {
+ f := newAutomationFixture(t)
+ a := f.create(t, types.AutomationPatch{ApprovalTimeoutMinutes: ptr(10)})
+ f.suspendOnApproval(t, "op:x")
+ queued, _ := f.svc.RunNow(f.ctx, a.ID)
+ run := f.settleRun(t, queued.ID)
+ require.Equal(t, types.AutomationRunAwaitingApproval, run.Status)
+ f.now = f.now.Add(11 * time.Minute)
+ f.svc.tick(f.ctx)
+ run = f.runs(t, a.ID)[0]
+ require.Equal(t, types.AutomationRunFailed, run.Status)
+ require.Contains(t, run.Error, "no approval within 10 minutes")
+ prompt, _ := f.broker.Store().Get(f.ctx, run.PendingPromptID)
+ require.Equal(t, types.AgentPromptExpired, prompt.Status)
+}
+
+func TestAutomationPausesWhenOwnerLeaves(t *testing.T) {
+ f := newAutomationFixture(t)
+ a := f.create(t, types.AutomationPatch{})
+ f.members.active = false
+ queued, err := f.svc.RunNow(f.ctx, a.ID)
+ require.NoError(t, err)
+ run := f.settleRun(t, queued.ID)
+ require.Equal(t, types.AutomationRunFailed, run.Status)
+ require.Empty(t, f.sessions.calls, "nothing runs with the old permissions")
+ stored := f.reload(t, a.ID)
+ require.False(t, stored.Enabled)
+ require.Contains(t, stored.PausedReason, "no longer a member")
+}
+
+func TestAutomationPausesAfterRepeatedFailures(t *testing.T) {
+ f := newAutomationFixture(t)
+ a := f.create(t, types.AutomationPatch{})
+ f.sessions.run = func(context.Context, *types.QARequest, *event.EventBus) error {
+ return errors.New("model unavailable")
+ }
+ for i := 0; i < 3; i++ {
+ f.now = f.now.Add(time.Minute)
+ queued, err := f.svc.RunNow(f.ctx, a.ID)
+ require.NoError(t, err)
+ require.Equal(t, types.AutomationRunFailed, f.settleRun(t, queued.ID).Status)
+ }
+ stored := f.reload(t, a.ID)
+ require.False(t, stored.Enabled)
+ require.Equal(t, 3, stored.ConsecutiveFailures)
+ require.Contains(t, stored.PausedReason, "3 runs in a row failed")
+
+ resumed, err := f.svc.Resume(f.ctx, a.ID)
+ require.NoError(t, err)
+ require.True(t, resumed.Enabled)
+ require.Zero(t, resumed.ConsecutiveFailures)
+}
+
+func TestAutomationAbandonedRunNeedsAttention(t *testing.T) {
+ f := newAutomationFixture(t)
+ a := f.create(t, types.AutomationPatch{})
+ past := f.now.Add(-time.Minute)
+ run := &types.AutomationRun{
+ AutomationID: a.ID, TenantID: automationTenant, ScheduledAt: past, TriggerKind: types.AutomationRunSchedule,
+ Status: types.AutomationRunRunning, Owner: "dead", LeaseUntil: &past,
+ }
+ require.NoError(t, f.db.Create(run).Error)
+ require.NoError(t, f.svc.expireLeases(f.ctx, f.now))
+ require.Equal(t, types.AutomationRunNeedsAttention, f.runs(t, a.ID)[0].Status)
+ require.Equal(t, 1, f.reload(t, a.ID).ConsecutiveFailures)
+}
+
+func TestAutomationCancelQueuedAndDelete(t *testing.T) {
+ f := newAutomationFixture(t)
+ a := f.create(t, types.AutomationPatch{})
+ queued, _ := f.svc.RunNow(f.ctx, a.ID)
+ cancelled, err := f.svc.CancelRun(f.ctx, queued.ID)
+ require.NoError(t, err)
+ require.Equal(t, types.AutomationRunCancelled, cancelled.Status)
+ require.NoError(t, f.svc.Delete(f.ctx, a.ID))
+ _, err = f.svc.Get(f.ctx, a.ID)
+ require.Error(t, err)
+}
+
+func TestAutomationStandingGrantFromApproval(t *testing.T) {
+ f := newAutomationFixture(t)
+ a := f.create(t, types.AutomationPatch{})
+ f.suspendOnApproval(t, "op:knowledge.delete:kb1")
+ queued, _ := f.svc.RunNow(f.ctx, a.ID)
+ run := f.settleRun(t, queued.ID)
+
+ candidates, err := f.svc.GrantCandidates(f.ctx, a.ID)
+ require.NoError(t, err)
+ require.Len(t, candidates, 1)
+ require.Equal(t, "destructive", candidates[0].Risk)
+ require.Equal(t, "documents in kb1", candidates[0].Label)
+
+ grant, err := f.svc.AddGrant(f.ctx, a.ID, run.PendingPromptID)
+ require.NoError(t, err)
+ require.Equal(t, types.AgentGrantScopeAutomation, grant.Scope)
+ require.Equal(t, a.ID, grant.ScopeID)
+ require.Equal(t, "destructive", grant.Risk)
+
+ grants, err := f.svc.Grants(f.ctx, a.ID)
+ require.NoError(t, err)
+ require.Len(t, grants, 1)
+ require.Empty(t, grants[0].Lapse)
+ candidates, err = f.svc.GrantCandidates(f.ctx, a.ID)
+ require.NoError(t, err)
+ require.Empty(t, candidates)
+
+ // Changing the agent's tools changes the binding the grant was given under.
+ f.agents.agent.Config.AllowedTools = []string{"x", "y"}
+ grants, err = f.svc.Grants(f.ctx, a.ID)
+ require.NoError(t, err)
+ require.Equal(t, types.AgentGrantLapseChanged, grants[0].Lapse)
+
+ _, err = f.svc.AddGrant(f.ctx, a.ID, "unknown")
+ require.Error(t, err)
+ b := f.create(t, types.AutomationPatch{Name: ptr("other")})
+ _, err = f.svc.AddGrant(f.ctx, b.ID, run.PendingPromptID)
+ require.Error(t, err, "a prompt of another automation cannot become its grant")
+}
+
+func TestAutomationValidateTrigger(t *testing.T) {
+ f := newAutomationFixture(t)
+ times, err := f.svc.ValidateTrigger(types.AutomationTrigger{
+ Type: types.AutomationTriggerCron, Expr: "0 9 * * MON", Timezone: "Asia/Shanghai",
+ }, 3)
+ require.NoError(t, err)
+ require.Len(t, times, 3)
+ shanghai := scheduleLocation(types.AutomationTrigger{Timezone: "Asia/Shanghai"})
+ for i, at := range times {
+ require.Equal(t, time.Monday, at.In(shanghai).Weekday(), fmt.Sprint(i))
+ }
+}
+
+func TestAutomationFindBySession(t *testing.T) {
+ f := newAutomationFixture(t)
+ a := f.create(t, types.AutomationPatch{})
+ require.NoError(t, f.db.Create(&types.AutomationRun{
+ ID: "run-1", AutomationID: a.ID, TenantID: a.TenantID, ScheduledAt: f.now,
+ TriggerKind: types.AutomationRunManual, Status: types.AutomationRunSucceeded, SessionID: "sess-1",
+ }).Error)
+
+ found, err := f.svc.FindBySession(f.ctx, "sess-1")
+ require.NoError(t, err)
+ require.Equal(t, a.ID, found.ID)
+
+ require.NoError(t, f.db.Model(&types.Automation{}).Where("id = ?", a.ID).
+ Update("persistent_session_id", "sess-persistent").Error)
+ found, err = f.svc.FindBySession(f.ctx, "sess-persistent")
+ require.NoError(t, err)
+ require.Equal(t, a.ID, found.ID)
+
+ _, err = f.svc.FindBySession(f.ctx, "missing")
+ var appErr *apperrors.AppError
+ require.ErrorAs(t, err, &appErr)
+ require.Equal(t, apperrors.ErrNotFound, appErr.Code)
+}
diff --git a/internal/application/service/notification.go b/internal/application/service/notification.go
new file mode 100644
index 000000000..467761a98
--- /dev/null
+++ b/internal/application/service/notification.go
@@ -0,0 +1,96 @@
+package service
+
+import (
+ "context"
+ "strings"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/types"
+ "gorm.io/gorm"
+)
+
+// notificationRetention is how long a notification is kept.
+const notificationRetention = 30 * 24 * time.Hour
+
+// NotificationService keeps in-app notifications.
+type NotificationService struct {
+ db *gorm.DB
+}
+
+// NewNotificationService builds the service.
+func NewNotificationService(db *gorm.DB) *NotificationService {
+ return &NotificationService{db: db}
+}
+
+// Notify records n. A failure is logged, not returned: a notification never
+// decides whether the work it reports succeeded.
+func (s *NotificationService) Notify(ctx context.Context, n *types.Notification) {
+ if s == nil || n == nil || n.TenantID == 0 || n.UserID == "" {
+ return
+ }
+ if r := []rune(n.Title); len(r) > 250 {
+ n.Title = string(r[:250]) + "…"
+ }
+ if r := []rune(n.Body); len(r) > 2000 {
+ n.Body = string(r[:2000]) + "…"
+ }
+ if err := s.db.WithContext(context.WithoutCancel(ctx)).Create(n).Error; err != nil {
+ logger.Warnf(ctx, "Record notification %s: %v", n.Kind, err)
+ }
+}
+
+// NotificationPage is one page of the caller's notifications.
+type NotificationPage struct {
+ Items []*types.Notification `json:"items"`
+ Unread int64 `json:"unread"`
+}
+
+// List returns the caller's newest notifications, at most limit, and how
+// many are unread. unreadOnly leaves out the read ones.
+func (s *NotificationService) List(ctx context.Context, limit int, unreadOnly bool) (*NotificationPage, error) {
+ tenantID, userID := notificationOwner(ctx)
+ if limit <= 0 || limit > 100 {
+ limit = 20
+ }
+ mine := func() *gorm.DB {
+ return s.db.WithContext(ctx).Model(&types.Notification{}).
+ Where("tenant_id = ? AND user_id = ?", tenantID, userID)
+ }
+ page := &NotificationPage{Items: []*types.Notification{}}
+ query := mine()
+ if unreadOnly {
+ query = query.Where("read_at IS NULL")
+ }
+ if err := query.Order("created_at DESC").Limit(limit).Find(&page.Items).Error; err != nil {
+ return nil, err
+ }
+ if err := mine().Where("read_at IS NULL").Count(&page.Unread).Error; err != nil {
+ return nil, err
+ }
+ return page, nil
+}
+
+// MarkRead marks the caller's notifications ids read, or all of them when
+// ids is empty.
+func (s *NotificationService) MarkRead(ctx context.Context, ids []string) error {
+ tenantID, userID := notificationOwner(ctx)
+ query := s.db.WithContext(ctx).Model(&types.Notification{}).
+ Where("tenant_id = ? AND user_id = ? AND read_at IS NULL", tenantID, userID)
+ if len(ids) > 0 {
+ query = query.Where("id IN ?", ids)
+ }
+ return query.Update("read_at", time.Now()).Error
+}
+
+// Prune drops notifications past retention.
+func (s *NotificationService) Prune(ctx context.Context) error {
+ return s.db.WithContext(ctx).
+ Where("created_at < ?", time.Now().Add(-notificationRetention)).
+ Delete(&types.Notification{}).Error
+}
+
+func notificationOwner(ctx context.Context) (uint64, string) {
+ caller := types.CallerFromContext(ctx)
+ return caller.TenantID, strings.TrimSpace(caller.UserID)
+}
diff --git a/internal/application/service/session_agent_qa.go b/internal/application/service/session_agent_qa.go
index 27e85a042..22db2983f 100644
--- a/internal/application/service/session_agent_qa.go
+++ b/internal/application/service/session_agent_qa.go
@@ -342,6 +342,11 @@ func (s *sessionService) AgentQA(
}
engine.SetRunMode(req.Mode)
+ if req.RunNote != "" {
+ if noted, ok := engine.(interface{ SetRunNote(string) }); ok {
+ noted.SetRunNote(req.RunNote)
+ }
+ }
collaborating := false
if bound, ok := engine.(interface{ HasCollaboration() bool }); ok {
collaborating = bound.HasCollaboration()
diff --git a/internal/automation/instruction.go b/internal/automation/instruction.go
new file mode 100644
index 000000000..686463033
--- /dev/null
+++ b/internal/automation/instruction.go
@@ -0,0 +1,68 @@
+package automation
+
+import (
+ "strings"
+ "time"
+)
+
+// RunVars are the values an instruction may reference.
+type RunVars struct {
+ Now time.Time
+ LastRunAt *time.Time
+ LastSuccessAt *time.Time
+ RunID string
+ AutomationName string
+ Location *time.Location
+}
+
+func formatTime(t *time.Time, loc *time.Location) string {
+ if t == nil || t.IsZero() {
+ return ""
+ }
+ if loc == nil {
+ loc = time.UTC
+ }
+ return t.In(loc).Format(time.RFC3339)
+}
+
+// RenderInstruction substitutes {{now}}, {{last_run_at}},
+// {{last_success_at}}, {{run_id}} and {{automation_name}}. Unknown
+// placeholders are left alone so a literal "{{" in a prompt survives.
+func RenderInstruction(instruction string, v RunVars) string {
+ now := v.Now
+ return strings.NewReplacer(
+ "{{now}}", formatTime(&now, v.Location),
+ "{{last_run_at}}", formatTime(v.LastRunAt, v.Location),
+ "{{last_success_at}}", formatTime(v.LastSuccessAt, v.Location),
+ "{{run_id}}", v.RunID,
+ "{{automation_name}}", v.AutomationName,
+ ).Replace(instruction)
+}
+
+// maxCarriedResult bounds how much of the previous answer a per-run session
+// is handed.
+const maxCarriedResult = 4000
+
+// RunQuery is the user turn of one run: the rendered instruction, preceded
+// by the previous run's answer when the automation carries it over.
+func RunQuery(instruction string, v RunVars, lastResult string) string {
+ query := RenderInstruction(instruction, v)
+ lastResult = strings.TrimSpace(lastResult)
+ if lastResult == "" {
+ return query
+ }
+ if r := []rune(lastResult); len(r) > maxCarriedResult {
+ lastResult = string(r[:maxCarriedResult]) + "…"
+ }
+ return "<previous_run_result>\n" + lastResult + "\n</previous_run_result>\n\n" + query
+}
+
+// RunNote tells the agent it is running unattended, so it does not wait on
+// a user who is not there.
+func RunNote(name string, scheduledAt time.Time, loc *time.Location) string {
+ at := scheduledAt
+ return "This turn is a scheduled run of the automation \"" + name + "\", fired for " +
+ formatTime(&at, loc) + ". No user is watching: do not ask clarifying questions; " +
+ "make reasonable assumptions, state them, and finish the task. Actions that need " +
+ "approval will wait for the owner."
+}
diff --git a/internal/automation/trigger.go b/internal/automation/trigger.go
new file mode 100644
index 000000000..91b132ada
--- /dev/null
+++ b/internal/automation/trigger.go
@@ -0,0 +1,165 @@
+// Package automation holds the scheduling rules of agent automations: when
+// a trigger fires, and what an automation's run is told. It does no I/O.
+package automation
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+
+ // Timezones must resolve on hosts without a zoneinfo database (Lite).
+ _ "time/tzdata"
+
+ "github.com/robfig/cron/v3"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// DefaultMinInterval is the shortest gap allowed between two runs.
+const DefaultMinInterval = 5 * time.Minute
+
+// ErrInvalidTrigger wraps every trigger validation failure.
+var ErrInvalidTrigger = errors.New("invalid trigger")
+
+var (
+ standardParser = cron.NewParser(
+ cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor,
+ )
+ secondsParser = cron.NewParser(
+ cron.Second | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor,
+ )
+)
+
+// Schedule is a validated trigger.
+type Schedule struct {
+ trigger types.AutomationTrigger
+ location *time.Location
+ cron cron.Schedule
+ once time.Time
+}
+
+// Wall-clock forms a once trigger accepts, read in its timezone. The first
+// match wins, so a zone suffix is never silently dropped.
+var onceLayouts = []string{
+ time.RFC3339Nano,
+ time.RFC3339,
+ "2006-01-02T15:04:05",
+ "2006-01-02 15:04:05",
+ "2006-01-02T15:04",
+ "2006-01-02 15:04",
+}
+
+func parseOnce(at string, loc *time.Location) (time.Time, error) {
+ for _, layout := range onceLayouts {
+ if parsed, err := time.ParseInLocation(layout, at, loc); err == nil {
+ return parsed.UTC(), nil
+ }
+ }
+ return time.Time{}, invalid("cannot read %q as a time; use RFC3339 or \"2006-01-02 15:04\"", at)
+}
+
+func invalid(format string, args ...any) error {
+ return fmt.Errorf("%w: %s", ErrInvalidTrigger, fmt.Sprintf(format, args...))
+}
+
+// Parse validates t. A cron expression has five fields (minute first) or
+// six (seconds first), or is a descriptor such as @daily; it is evaluated in
+// t.Timezone, which a CRON_TZ= prefix in the expression may not override.
+func Parse(t types.AutomationTrigger) (*Schedule, error) {
+ t.Expr = strings.TrimSpace(t.Expr)
+ t.Timezone = strings.TrimSpace(t.Timezone)
+ loc := time.UTC
+ if t.Timezone != "" {
+ var err error
+ if loc, err = time.LoadLocation(t.Timezone); err != nil {
+ return nil, invalid("unknown timezone %q", t.Timezone)
+ }
+ }
+ s := &Schedule{trigger: t, location: loc}
+ switch t.Type {
+ case types.AutomationTriggerCron:
+ if t.Expr == "" {
+ return nil, invalid("a cron trigger needs an expression")
+ }
+ if strings.HasPrefix(t.Expr, "CRON_TZ=") || strings.HasPrefix(t.Expr, "TZ=") {
+ return nil, invalid("set the timezone field instead of a TZ prefix")
+ }
+ parser := standardParser
+ if !strings.HasPrefix(t.Expr, "@") && len(strings.Fields(t.Expr)) == 6 {
+ parser = secondsParser
+ }
+ sched, err := parser.Parse(t.Expr)
+ if err != nil {
+ return nil, invalid("%v", err)
+ }
+ s.cron = sched
+ case types.AutomationTriggerOnce:
+ if strings.TrimSpace(t.At) == "" {
+ return nil, invalid("a once trigger needs a time")
+ }
+ if t.Expr != "" {
+ return nil, invalid("a once trigger takes no expression")
+ }
+ at, err := parseOnce(strings.TrimSpace(t.At), loc)
+ if err != nil {
+ return nil, err
+ }
+ s.once = at
+ s.trigger.At = at.Format(time.RFC3339)
+ default:
+ return nil, invalid("unknown trigger type %q", t.Type)
+ }
+ return s, nil
+}
+
+// Trigger is the normalized trigger.
+func (s *Schedule) Trigger() types.AutomationTrigger { return s.trigger }
+
+// Next is the first time the trigger fires strictly after after, or nil when
+// it never fires again.
+func (s *Schedule) Next(after time.Time) *time.Time {
+ if s.cron == nil {
+ at := s.once
+ if at.After(after) {
+ return &at
+ }
+ return nil
+ }
+ next := s.cron.Next(after.In(s.location))
+ if next.IsZero() {
+ return nil
+ }
+ next = next.UTC()
+ return &next
+}
+
+// Upcoming is the next n firing times after after.
+func (s *Schedule) Upcoming(after time.Time, n int) []time.Time {
+ var out []time.Time
+ for len(out) < n {
+ next := s.Next(after)
+ if next == nil {
+ break
+ }
+ out = append(out, *next)
+ after = *next
+ }
+ return out
+}
+
+// CheckInterval rejects a cron trigger that can fire twice within min. It
+// looks at the gaps over the next days, which catches expressions such as
+// "* * * * *" and "*/2 9 * * *" alike.
+func (s *Schedule) CheckInterval(from time.Time, minInterval time.Duration) error {
+ if s.cron == nil || minInterval <= 0 {
+ return nil
+ }
+ times := s.Upcoming(from, 64)
+ for i := 1; i < len(times); i++ {
+ if gap := times[i].Sub(times[i-1]); gap < minInterval {
+ return invalid("runs would be %s apart; the minimum is %s", gap, minInterval)
+ }
+ }
+ return nil
+}
diff --git a/internal/automation/trigger_test.go b/internal/automation/trigger_test.go
new file mode 100644
index 000000000..e242e938c
--- /dev/null
+++ b/internal/automation/trigger_test.go
@@ -0,0 +1,99 @@
+package automation
+
+import (
+ "errors"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+func cronTrigger(expr, tz string) types.AutomationTrigger {
+ return types.AutomationTrigger{Type: types.AutomationTriggerCron, Expr: expr, Timezone: tz}
+}
+
+func TestParseRejectsBadTriggers(t *testing.T) {
+ for name, tr := range map[string]types.AutomationTrigger{
+ "empty type": {},
+ "no expr": cronTrigger("", ""),
+ "garbage": cronTrigger("every day", ""),
+ "bad timezone": cronTrigger("0 9 * * *", "Mars/Olympus"),
+ "tz prefix": cronTrigger("CRON_TZ=Asia/Tokyo 0 9 * * *", ""),
+ "once without": {Type: types.AutomationTriggerOnce},
+ "once with expr": {Type: types.AutomationTriggerOnce, Expr: "0 9 * * *", At: "2026-10-19T22:09:00Z"},
+ "once nonsense": {Type: types.AutomationTriggerOnce, At: "tomorrow"},
+ } {
+ _, err := Parse(tr)
+ require.Truef(t, errors.Is(err, ErrInvalidTrigger), "%s: %v", name, err)
+ }
+}
+
+func TestNextHonorsTimezone(t *testing.T) {
+ s, err := Parse(cronTrigger("0 9 * * *", "Asia/Shanghai"))
+ require.NoError(t, err)
+ from := time.Date(2026, 10, 19, 2, 0, 0, 0, time.UTC) // 10:00 Shanghai
+ next := s.Next(from)
+ require.NotNil(t, next)
+ require.Equal(t, time.Date(2026, 10, 20, 1, 0, 0, 0, time.UTC), *next)
+ require.Equal(t, time.UTC, next.Location())
+}
+
+func TestSixFieldsAndDescriptors(t *testing.T) {
+ from := time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC)
+ s, err := Parse(cronTrigger("0 30 9 * * MON", ""))
+ require.NoError(t, err)
+ require.Equal(t, time.Date(2026, 10, 19, 9, 30, 0, 0, time.UTC), *s.Next(from))
+
+ s, err = Parse(cronTrigger("@daily", ""))
+ require.NoError(t, err)
+ require.Equal(t, time.Date(2026, 10, 20, 0, 0, 0, 0, time.UTC), *s.Next(from))
+}
+
+func TestOnceFiresOnce(t *testing.T) {
+ at := time.Date(2026, 10, 20, 7, 0, 0, 0, time.UTC)
+ for _, given := range []types.AutomationTrigger{
+ {Type: types.AutomationTriggerOnce, At: "2026-10-20T08:00:00+01:00"},
+ {Type: types.AutomationTriggerOnce, At: "2026-10-20 15:00", Timezone: "Asia/Shanghai"},
+ {Type: types.AutomationTriggerOnce, At: "2026-10-20T15:00:00", Timezone: "Asia/Shanghai"},
+ } {
+ s, err := Parse(given)
+ require.NoError(t, err, given.At)
+ require.Equal(t, "2026-10-20T07:00:00Z", s.Trigger().At)
+ from := time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC)
+ require.Equal(t, at, *s.Next(from))
+ require.Nil(t, s.Next(at))
+ require.Len(t, s.Upcoming(from, 3), 1)
+ }
+}
+
+func TestCheckInterval(t *testing.T) {
+ from := time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC)
+ for expr, ok := range map[string]bool{
+ "* * * * *": false,
+ "*/2 9 * * *": false,
+ "*/5 * * * *": true,
+ "0 9,10 * * *": true,
+ "0 0 9 * * *": true,
+ "*/30 * * * * *": false,
+ } {
+ s, err := Parse(cronTrigger(expr, ""))
+ require.NoError(t, err, expr)
+ err = s.CheckInterval(from, DefaultMinInterval)
+ require.Equalf(t, ok, err == nil, "%s: %v", expr, err)
+ }
+}
+
+func TestRunQuery(t *testing.T) {
+ loc, _ := time.LoadLocation("Asia/Shanghai")
+ now := time.Date(2026, 10, 19, 1, 0, 0, 0, time.UTC)
+ v := RunVars{Now: now, RunID: "r1", AutomationName: "日报", Location: loc}
+ q := RunQuery("{{automation_name}} at {{now}} since {{last_run_at}} {{unknown}}", v, "")
+ require.Equal(t, "日报 at 2026-10-19T09:00:00+08:00 since {{unknown}}", q)
+
+ q = RunQuery("go", v, strings.Repeat("长", maxCarriedResult+10))
+ require.True(t, strings.HasPrefix(q, "<previous_run_result>\n"))
+ require.True(t, strings.HasSuffix(q, "…\n</previous_run_result>\n\ngo"))
+}
diff --git a/internal/container/container.go b/internal/container/container.go
index 312361170..bbaa8a00f 100644
--- a/internal/container/container.go
+++ b/internal/container/container.go
@@ -368,6 +368,8 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(operations.NewHandlerDispatcher))
// Collaboration workers bind SessionService after the dependency graph is built.
must(container.Provide(service.NewAgentCollaboration))
+ must(container.Provide(service.NewNotificationService))
+ must(container.Provide(service.NewAutomationService))
must(container.Provide(service.NewAgentService))
// Session service (depends on agent service)
@@ -612,26 +614,39 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Invoke(func(
sessions *session.Handler, mcp *handler.MCPServiceHandler,
broker *hitl.Broker, runs *service.SuspendedRunService, rewind *service.SessionRewindService,
- collaboration *service.AgentCollaboration,
+ collaboration *service.AgentCollaboration, automations *service.AutomationService,
+ sessionService interfaces.SessionService,
messages *handler.MessageHandler, gate *approval.Gate, streams interfaces.StreamManager,
) {
rewind.SetSuspendedRuns(runs)
sessions.SetSuspendedRuns(broker, runs)
sessions.SetCollaborationStopper(collaboration.Stop)
- sessions.SetDelegatedPromptRouter(collaboration.HandlesPrompt)
+ // Automation runs resume under their automation, delegated ones
+ // through the collaboration scheduler; neither as an ordinary chat.
+ sessions.SetDelegatedPromptRouter(func(ctx context.Context, p *types.AgentPrompt) bool {
+ return automations.HandlesPrompt(ctx, p) || collaboration.HandlesPrompt(ctx, p)
+ })
messages.DelegatedPrompts = collaboration.PendingPrompts
messages.CollaborationStatuses = collaboration.HistoryStatuses
collaboration.BindRecovery(broker, gate, streams)
collaboration.ParentEvents = sessions.CollaborationEvents
collaboration.ChildEvents = sessions.CollaborationEvents
collaboration.ParentSteer = sessions.CollaborationSteer
- runs.RecoverAnswered = collaboration.RecoverAnswered
+ runs.RecoverAnswered = func(ctx context.Context, p *types.AgentPrompt) (bool, error) {
+ if ok, err := automations.RecoverAnswered(ctx, p); ok || err != nil {
+ return ok, err
+ }
+ return collaboration.RecoverAnswered(ctx, p)
+ }
+ automations.Bind(sessionService, broker, runs, streams)
+ automations.Events = sessions.CollaborationEvents
broker.SetRunHooks(runs.Hooks())
runs.StopDelegation = func(ctx context.Context, p *types.AgentPrompt) error {
return collaboration.StopPrompt(ctx, p)
}
mcp.SetRunResumer(sessions)
collaboration.Runtime.Start(context.Background())
+ automations.Start(context.Background())
}))
// Start only after the delegation close hook is installed.
must(container.Invoke(startAgentPromptReaper))
@@ -653,6 +668,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
}))
must(container.Provide(handler.NewOrganizationHandler))
must(container.Provide(handler.NewMemoryHandler))
+ must(container.Provide(handler.NewAutomationHandler))
// Data source handler
must(container.Provide(handler.NewDataSourceHandler))
diff --git a/internal/database/migration_sqlite_versioned_schema_test.go b/internal/database/migration_sqlite_versioned_schema_test.go
index b68d1de96..1a33dc968 100644
--- a/internal/database/migration_sqlite_versioned_schema_test.go
+++ b/internal/database/migration_sqlite_versioned_schema_test.go
@@ -40,6 +40,9 @@ var versionedSQLiteTables = []string{
"agent_run_suspensions",
"agent_collaborations",
"agent_grants",
+ "automations",
+ "automation_runs",
+ "notifications",
}
// versionedSQLiteColumns maps each existing table to the columns that the
@@ -77,7 +80,7 @@ var versionedSQLiteColumns = map[string][]string{
}, // 000028
}
-const expectedSQLiteMigrationVersion = 44
+const expectedSQLiteMigrationVersion = 45
func TestSQLiteMigrationsCreateVersionedSchema(t *testing.T) {
repoRoot := sqliteRepoRoot(t)
diff --git a/internal/handler/automation.go b/internal/handler/automation.go
new file mode 100644
index 000000000..bfd7327b6
--- /dev/null
+++ b/internal/handler/automation.go
@@ -0,0 +1,482 @@
+package handler
+
+import (
+ stderrors "errors"
+ "net/http"
+ "strconv"
+ "time"
+
+ "github.com/gin-gonic/gin"
+
+ "github.com/Tencent/WeKnora/internal/application/service"
+ "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// AutomationHandler serves the caller's automations and notifications.
+type AutomationHandler struct {
+ automations *service.AutomationService
+ notifications *service.NotificationService
+}
+
+// NewAutomationHandler builds the handler.
+func NewAutomationHandler(
+ automations *service.AutomationService, notifications *service.NotificationService,
+) *AutomationHandler {
+ return &AutomationHandler{automations: automations, notifications: notifications}
+}
+
+func (h *AutomationHandler) fail(c *gin.Context, err error) {
+ var appErr *errors.AppError
+ if stderrors.As(err, &appErr) {
+ _ = c.Error(appErr)
+ return
+ }
+ logger.ErrorWithFields(c.Request.Context(), err, nil)
+ _ = c.Error(errors.NewInternalServerError("automation request failed"))
+}
+
+// CreateAutomationRequest is the body of POST /automations; see
+// types.AutomationPatch for the fields.
+type CreateAutomationRequest struct {
+ // What the automation is called
+ Name string `json:"name" binding:"required" extensions:"x-agent"`
+ // What it is for
+ Description string `json:"description" extensions:"x-agent"`
+ // Agent that runs it, from agent.list; empty runs the WeKnora assistant
+ AgentID string `json:"agent_id" extensions:"x-agent"`
+ // The task, sent as the user message of each run. May name now,
+ // last_run_at, last_success_at, run_id or automation_name inside double
+ // curly braces to have it filled in
+ Instruction string `json:"instruction" binding:"required" extensions:"x-agent,x-agent-max-bytes=32000"`
+ // When it runs
+ Trigger types.AutomationTrigger `json:"trigger" binding:"required" extensions:"x-agent"`
+ // per_run (default) starts a new conversation each run; persistent keeps one
+ SessionMode string `json:"session_mode" enums:"per_run,persistent" extensions:"x-agent"`
+ // Whether each per_run conversation gets the last successful answer
+ CarryLastResult bool `json:"carry_last_result" extensions:"x-agent"`
+ // What happens to runs missed while the service was down; default skip
+ MisfirePolicy string `json:"misfire_policy" enums:"skip,run_once" extensions:"x-agent"`
+ // What happens when a run is due while the previous one is still going; default skip
+ OverlapPolicy string `json:"overlap_policy" enums:"skip,queue" extensions:"x-agent"`
+ // How far runs may change data without asking; default confirm
+ AccessLevel types.AssistantAccessLevel `json:"access_level" enums:"read_only,confirm,auto_write" extensions:"x-agent"`
+ // How long a run waits for an approval before it fails, in minutes; default 1440
+ ApprovalTimeoutMinutes int `json:"approval_timeout_minutes" extensions:"x-agent"`
+ Limits types.AutomationLimits `json:"limits"`
+ // Whether a successful run notifies the owner; failures always do
+ NotifyOnSuccess bool `json:"notify_on_success" extensions:"x-agent"`
+}
+
+func (r CreateAutomationRequest) patch() *types.AutomationPatch {
+ return &types.AutomationPatch{
+ Name: &r.Name, Description: &r.Description, AgentID: &r.AgentID, Instruction: &r.Instruction,
+ Trigger: &r.Trigger, SessionMode: &r.SessionMode, CarryLastResult: &r.CarryLastResult,
+ MisfirePolicy: &r.MisfirePolicy, OverlapPolicy: &r.OverlapPolicy, AccessLevel: &r.AccessLevel,
+ ApprovalTimeoutMinutes: &r.ApprovalTimeoutMinutes, Limits: &r.Limits, NotifyOnSuccess: &r.NotifyOnSuccess,
+ }
+}
+
+// ListAutomations godoc
+// @Summary 列出我的自动化
+// @Description 列出当前用户在本空间创建的自动化(定时任务),最新的在前
+// @Tags 自动化
+// @Produce json
+// @Success 200 {object} handler.DataResponse{data=[]types.Automation} "自动化列表"
+// @Security Bearer
+// @x-agent {"id":"automation.list","risk":"read","max_items":100}
+// @x-agent-hint "Lists the user's automations: scheduled tasks an agent runs on their behalf, with next and last run."
+// @Router /automations [get]
+func (h *AutomationHandler) ListAutomations(c *gin.Context) {
+ list, err := h.automations.List(c.Request.Context())
+ if err != nil {
+ h.fail(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": list})
+}
+
+// CreateAutomation godoc
+// @Summary 创建自动化
+// @Description 创建一个按计划由 Agent 以当前用户身份运行的任务
+// @Tags 自动化
+// @Accept json
+// @Produce json
+// @Param request body CreateAutomationRequest true "自动化"
+// @Success 201 {object} handler.DataResponse{data=types.Automation} "创建的自动化"
+// @Failure 400 {object} errors.AppError "参数不合法"
+// @Security Bearer
+// @x-agent {"id":"automation.create","role":"viewer","risk":"write","label_param":"name","always_confirm":true}
+// @x-agent-hint "Creates an automation the user runs as. Turn the user's wording into a cron expression (five fields, minute first) and an IANA timezone, and check it with automation.validate_trigger first, telling the user the next run times it returns. Runs are unattended: write the instruction as a complete task, since nobody can answer questions during a run. access_level defaults to confirm, where each change waits for the user's approval; only set auto_write when the user asks for it."
+// @Router /automations [post]
+func (h *AutomationHandler) CreateAutomation(c *gin.Context) {
+ var req CreateAutomationRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ _ = c.Error(errors.NewBadRequestError("invalid automation").WithDetails(err.Error()))
+ return
+ }
+ a, err := h.automations.Create(c.Request.Context(), req.patch())
+ if err != nil {
+ h.fail(c, err)
+ return
+ }
+ c.JSON(http.StatusCreated, gin.H{"success": true, "data": a})
+}
+
+// ValidateTriggerRequest is the body of POST /automations/validate-trigger.
+type ValidateTriggerRequest struct {
+ // The trigger to check
+ Trigger types.AutomationTrigger `json:"trigger" binding:"required" extensions:"x-agent"`
+}
+
+// ValidateTriggerResult is the data of POST /automations/validate-trigger.
+type ValidateTriggerResult struct {
+ // The next times the trigger fires, in UTC
+ NextRuns []time.Time `json:"next_runs" extensions:"x-agent"`
+}
+
+// ValidateTrigger godoc
+// @Summary 校验触发器
+// @Description 校验 cron 或一次性触发器,返回未来 3 次触发时间
+// @Tags 自动化
+// @Accept json
+// @Produce json
+// @Param request body ValidateTriggerRequest true "触发器"
+// @Success 200 {object} handler.DataResponse{data=ValidateTriggerResult} "未来触发时间"
+// @Failure 400 {object} errors.AppError "触发器不合法"
+// @Security Bearer
+// @x-agent {"id":"automation.validate_trigger","risk":"probe"}
+// @x-agent-hint "Checks a trigger and returns its next three run times in UTC; convert them to the trigger's timezone for the user."
+// @Router /automations/validate-trigger [post]
+func (h *AutomationHandler) ValidateTrigger(c *gin.Context) {
+ var req ValidateTriggerRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ _ = c.Error(errors.NewBadRequestError("invalid trigger").WithDetails(err.Error()))
+ return
+ }
+ times, err := h.automations.ValidateTrigger(req.Trigger, 3)
+ if err != nil {
+ h.fail(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": ValidateTriggerResult{NextRuns: times}})
+}
+
+// GetAutomationBySession godoc
+// @Summary 按会话查找自动化
+// @Description 返回这次会话所属的自动化,供会话页跳回
+// @Tags 自动化
+// @Produce json
+// @Param session_id path string true "会话 ID"
+// @Success 200 {object} handler.DataResponse{data=types.Automation} "自动化"
+// @Failure 404 {object} errors.AppError "不存在"
+// @Security Bearer
+// @Router /automations/by-session/{session_id} [get]
+func (h *AutomationHandler) GetAutomationBySession(c *gin.Context) {
+ a, err := h.automations.FindBySession(c.Request.Context(), c.Param("session_id"))
+ if err != nil {
+ h.fail(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": a})
+}
+
+// GetAutomation godoc
+// @Summary 获取自动化
+// @Tags 自动化
+// @Produce json
+// @Param id path string true "自动化 ID" extensions(x-agent=automation_id)
+// @Success 200 {object} handler.DataResponse{data=types.Automation} "自动化"
+// @Failure 404 {object} errors.AppError "不存在"
+// @Security Bearer
+// @x-agent {"id":"automation.get","risk":"read"}
+// @x-agent-hint "Returns one automation, including its instruction."
+// @Router /automations/{id} [get]
+func (h *AutomationHandler) GetAutomation(c *gin.Context) {
+ a, err := h.automations.Get(c.Request.Context(), c.Param("id"))
+ if err != nil {
+ h.fail(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": a})
+}
+
+// UpdateAutomation godoc
+// @Summary 修改自动化
+// @Description 只修改请求中出现的字段,其余保持不变
+// @Tags 自动化
+// @Accept json
+// @Produce json
+// @Param id path string true "自动化 ID" extensions(x-agent=automation_id)
+// @Param request body types.AutomationPatch true "要修改的字段"
+// @Success 200 {object} handler.DataResponse{data=types.Automation} "修改后的自动化"
+// @Failure 400 {object} errors.AppError "参数不合法"
+// @Security Bearer
+// @x-agent {"id":"automation.update","role":"viewer","risk":"write","target":"automation.get","label":"name","always_confirm":true}
+// @x-agent-hint "Changes the listed fields of an automation; a field left out is kept. Check a new trigger with automation.validate_trigger first. Use automation.pause and automation.resume to switch it off and on."
+// @Router /automations/{id} [put]
+func (h *AutomationHandler) UpdateAutomation(c *gin.Context) {
+ var req types.AutomationPatch
+ if err := c.ShouldBindJSON(&req); err != nil {
+ _ = c.Error(errors.NewBadRequestError("invalid automation").WithDetails(err.Error()))
+ return
+ }
+ a, err := h.automations.Update(c.Request.Context(), c.Param("id"), &req)
+ if err != nil {
+ h.fail(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": a})
+}
+
+// DeleteAutomation godoc
+// @Summary 删除自动化
+// @Description 停止进行中的运行,删除自动化及其运行记录、会话和长期授权
+// @Tags 自动化
+// @Produce json
+// @Param id path string true "自动化 ID" extensions(x-agent=automation_id)
+// @Success 200 {object} handler.SuccessResponse "删除成功"
+// @Failure 404 {object} errors.AppError "不存在"
+// @Security Bearer
+// @x-agent {"id":"automation.delete","role":"viewer","risk":"destructive","target":"automation.get","label":"name"}
+// @x-agent-hint "Deletes an automation with its run history and conversations. Cannot be undone; automation.pause keeps it."
+// @Router /automations/{id} [delete]
+func (h *AutomationHandler) DeleteAutomation(c *gin.Context) {
+ if err := h.automations.Delete(c.Request.Context(), c.Param("id")); err != nil {
+ h.fail(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true})
+}
+
+// PauseAutomation godoc
+// @Summary 暂停自动化
+// @Description 停止按计划触发;进行中的运行不受影响
+// @Tags 自动化
+// @Produce json
+// @Param id path string true "自动化 ID" extensions(x-agent=automation_id)
+// @Success 200 {object} handler.DataResponse{data=types.Automation} "暂停后的自动化"
+// @Security Bearer
+// @x-agent {"id":"automation.pause","role":"viewer","risk":"write","target":"automation.get","label":"name"}
+// @x-agent-hint "Stops an automation from running on schedule until automation.resume."
+// @Router /automations/{id}/pause [post]
+func (h *AutomationHandler) PauseAutomation(c *gin.Context) {
+ a, err := h.automations.Pause(c.Request.Context(), c.Param("id"))
+ if err != nil {
+ h.fail(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": a})
+}
+
+// ResumeAutomation godoc
+// @Summary 恢复自动化
+// @Description 从现在起重新按计划触发,并清零连续失败计数
+// @Tags 自动化
+// @Produce json
+// @Param id path string true "自动化 ID" extensions(x-agent=automation_id)
+// @Success 200 {object} handler.DataResponse{data=types.Automation} "恢复后的自动化"
+// @Security Bearer
+// @x-agent {"id":"automation.resume","role":"viewer","risk":"write","target":"automation.get","label":"name","always_confirm":true}
+// @x-agent-hint "Schedules a paused automation again from now; missed runs are not caught up."
+// @Router /automations/{id}/resume [post]
+func (h *AutomationHandler) ResumeAutomation(c *gin.Context) {
+ a, err := h.automations.Resume(c.Request.Context(), c.Param("id"))
+ if err != nil {
+ h.fail(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": a})
+}
+
+// RunAutomation godoc
+// @Summary 立即运行自动化
+// @Description 排队一次手动运行;已有运行在排队或进行中时拒绝
+// @Tags 自动化
+// @Produce json
+// @Param id path string true "自动化 ID" extensions(x-agent=automation_id)
+// @Success 202 {object} handler.DataResponse{data=types.AutomationRun} "排队的运行"
+// @Failure 409 {object} errors.AppError "已有运行"
+// @Security Bearer
+// @x-agent {"id":"automation.run_now","role":"viewer","risk":"write","target":"automation.get","label":"name","always_confirm":true}
+// @x-agent-hint "Queues a run now, in the background; follow it with automation.list_runs."
+// @Router /automations/{id}/run [post]
+func (h *AutomationHandler) RunAutomation(c *gin.Context) {
+ run, err := h.automations.RunNow(c.Request.Context(), c.Param("id"))
+ if err != nil {
+ h.fail(c, err)
+ return
+ }
+ c.JSON(http.StatusAccepted, gin.H{"success": true, "data": run})
+}
+
+// ListAutomationRuns godoc
+// @Summary 列出运行记录
+// @Tags 自动化
+// @Produce json
+// @Param id path string true "自动化 ID" extensions(x-agent=automation_id)
+// @Param page query int false "页码,从 1 开始" extensions(x-agent)
+// @Param page_size query int false "每页条数,最多 100" extensions(x-agent,x-agent-maximum=20)
+// @Success 200 {object} handler.PageResponse{data=[]types.AutomationRun} "运行记录"
+// @Security Bearer
+// @x-agent {"id":"automation.list_runs","risk":"read"}
+// @x-agent-hint "Lists an automation's runs, newest first, with status, error and the start of the answer."
+// @Router /automations/{id}/runs [get]
+func (h *AutomationHandler) ListAutomationRuns(c *gin.Context) {
+ page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
+ size, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
+ page = max(page, 1)
+ if size <= 0 || size > 100 {
+ size = 20
+ }
+ runs, total, err := h.automations.ListRuns(c.Request.Context(), c.Param("id"), size, (page-1)*size)
+ if err != nil {
+ h.fail(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": runs, "total": total, "page": page, "page_size": size})
+}
+
+// GetAutomationRun godoc
+// @Summary 获取运行记录
+// @Tags 自动化
+// @Produce json
+// @Param id path string true "运行 ID"
+// @Success 200 {object} handler.DataResponse{data=types.AutomationRun} "运行记录"
+// @Security Bearer
+// @Router /automation-runs/{id} [get]
+func (h *AutomationHandler) GetAutomationRun(c *gin.Context) {
+ run, err := h.automations.GetRun(c.Request.Context(), c.Param("id"))
+ if err != nil {
+ h.fail(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": run})
+}
+
+// CancelAutomationRun godoc
+// @Summary 停止运行
+// @Description 排队或等待审批的运行立即结束;执行中的运行在下一次检查时停止
+// @Tags 自动化
+// @Produce json
+// @Param id path string true "运行 ID"
+// @Success 200 {object} handler.DataResponse{data=types.AutomationRun} "运行记录"
+// @Security Bearer
+// @Router /automation-runs/{id}/cancel [post]
+func (h *AutomationHandler) CancelAutomationRun(c *gin.Context) {
+ run, err := h.automations.CancelRun(c.Request.Context(), c.Param("id"))
+ if err != nil {
+ h.fail(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": run})
+}
+
+// ListAutomationGrants godoc
+// @Summary 列出自动化的长期授权
+// @Description 列出以后的运行无需确认即可执行的调用,以及失效原因
+// @Tags 自动化
+// @Produce json
+// @Param id path string true "自动化 ID"
+// @Success 200 {object} map[string]interface{} "长期授权"
+// @Security Bearer
+// @Router /automations/{id}/grants [get]
+func (h *AutomationHandler) ListAutomationGrants(c *gin.Context) {
+ grants, err := h.automations.Grants(c.Request.Context(), c.Param("id"))
+ if err != nil {
+ h.fail(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": grants})
+}
+
+// ListAutomationGrantCandidates godoc
+// @Summary 列出可设为长期授权的调用
+// @Description 列出本自动化的运行请求过审批、尚未长期授权的调用;需每次审批的调用不在其中
+// @Tags 自动化
+// @Produce json
+// @Param id path string true "自动化 ID"
+// @Success 200 {object} map[string]interface{} "候选调用"
+// @Security Bearer
+// @Router /automations/{id}/grant-candidates [get]
+func (h *AutomationHandler) ListAutomationGrantCandidates(c *gin.Context) {
+ candidates, err := h.automations.GrantCandidates(c.Request.Context(), c.Param("id"))
+ if err != nil {
+ h.fail(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": candidates})
+}
+
+type addAutomationGrantRequest struct {
+ PromptID string `json:"prompt_id" binding:"required"`
+}
+
+// AddAutomationGrant godoc
+// @Summary 添加长期授权
+// @Description 让以后的运行无需确认即可执行某次运行请求过审批的调用;Agent 配置或所有者角色变化后失效
+// @Tags 自动化
+// @Accept json
+// @Produce json
+// @Param id path string true "自动化 ID"
+// @Param request body object true "{prompt_id}"
+// @Success 200 {object} map[string]interface{} "授权"
+// @Security Bearer
+// @Router /automations/{id}/grants [post]
+func (h *AutomationHandler) AddAutomationGrant(c *gin.Context) {
+ var req addAutomationGrantRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ _ = c.Error(errors.NewBadRequestError("prompt_id is required"))
+ return
+ }
+ grant, err := h.automations.AddGrant(c.Request.Context(), c.Param("id"), req.PromptID)
+ if err != nil {
+ h.fail(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": grant})
+}
+
+// ListNotifications godoc
+// @Summary 列出我的通知
+// @Tags 通知
+// @Produce json
+// @Param limit query int false "条数,最多 100"
+// @Param unread query bool false "只看未读"
+// @Success 200 {object} map[string]interface{} "{items, unread}"
+// @Security Bearer
+// @Router /notifications [get]
+func (h *AutomationHandler) ListNotifications(c *gin.Context) {
+ limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20"))
+ page, err := h.notifications.List(c.Request.Context(), limit, c.Query("unread") == "true")
+ if err != nil {
+ h.fail(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": page})
+}
+
+type markNotificationsReadRequest struct {
+ IDs []string `json:"ids"`
+}
+
+// MarkNotificationsRead godoc
+// @Summary 标记通知已读
+// @Description ids 为空时全部标记已读
+// @Tags 通知
+// @Accept json
+// @Produce json
+// @Param request body object false "{ids}"
+// @Success 200 {object} map[string]interface{} "结果"
+// @Security Bearer
+// @Router /notifications/read [post]
+func (h *AutomationHandler) MarkNotificationsRead(c *gin.Context) {
+ var req markNotificationsReadRequest
+ _ = c.ShouldBindJSON(&req)
+ if err := h.notifications.MarkRead(c.Request.Context(), req.IDs); err != nil {
+ h.fail(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true})
+}
diff --git a/internal/handler/system_operations.go b/internal/handler/system_operations.go
index 8ed9ae825..8cea00ca0 100644
--- a/internal/handler/system_operations.go
+++ b/internal/handler/system_operations.go
@@ -14,7 +14,7 @@ import (
// @Tags System Admin
// @Produce json
// @Param key query string false "完整设置键;省略返回所有已注册设置" extensions(x-agent)
-// @Success 200 {array} types.SystemSettingSummary
+// @Success 200 {array} github_com_Tencent_WeKnora_internal_types.SystemSettingSummary
// @x-agent {"id":"system_admin.list_settings","risk":"read","system_admin":true,"max_items":100}
// @x-agent-hint "Reads registered platform settings, optionally selecting an exact key from this list. value_json encodes the settings page value, including service fallbacks; it is not proof that a running process has reloaded a restart-required change. value_hidden means secret, invalid or oversized and never means empty/default. Unknown out-of-band database rows are excluded. Read-only: cannot change or reset settings."
// @Router /system/admin/settings-summary [get]
diff --git a/internal/router/operations_test.go b/internal/router/operations_test.go
index f4869ae6d..87c222243 100644
--- a/internal/router/operations_test.go
+++ b/internal/router/operations_test.go
@@ -45,6 +45,7 @@ func registerOperationAreas(v1 *gin.RouterGroup, g *rbacGuards) {
g,
)
RegisterDataSourceRoutes(v1, &handler.DataSourceHandler{}, &handler.DataSourceCredentialsHandler{}, g)
+ RegisterAutomationRoutes(v1, &handler.AutomationHandler{}, g)
}
// TestBuiltinOperationsMatchRegisteredRoutes requires every operation to
diff --git a/internal/router/router.go b/internal/router/router.go
index 29f37d3b1..d0419a5bc 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -95,6 +95,7 @@ type RouterParams struct {
WeKnoraCloudHandler *handler.WeKnoraCloudHandler
WikiPageHandler *handler.WikiPageHandler
MemoryHandler *handler.MemoryHandler
+ AutomationHandler *handler.AutomationHandler
HostSandbox service.HostSandboxManager
OperationDispatcher *operations.HandlerDispatcher
}
@@ -330,6 +331,7 @@ func NewRouter(params RouterParams) *gin.Engine {
RegisterWeKnoraCloudRoutes(v1, params.WeKnoraCloudHandler, rbacGuards)
RegisterWikiPageRoutes(v1, params.WikiPageHandler, rbacGuards)
RegisterMemoryRoutes(v1, params.MemoryHandler, rbacGuards)
+ RegisterAutomationRoutes(v1, params.AutomationHandler, rbacGuards)
RegisterChunkerDebugRoutes(v1, rbacGuards)
// Fail fast if any declared API-key policy points at a route
diff --git a/internal/router/routes_automation.go b/internal/router/routes_automation.go
new file mode 100644
index 000000000..e1abf5f2a
--- /dev/null
+++ b/internal/router/routes_automation.go
@@ -0,0 +1,45 @@
+package router
+
+import (
+ "github.com/gin-gonic/gin"
+
+ "github.com/Tencent/WeKnora/internal/handler"
+)
+
+// RegisterAutomationRoutes registers the caller's automations and in-app
+// notifications. An automation runs as the person who made it, and the
+// service scopes every route to the caller's own records, so tenant members
+// (Viewer+) may use them. They are not declared for API keys (default-deny):
+// an automation needs a signed-in owner.
+func RegisterAutomationRoutes(r *gin.RouterGroup, h *handler.AutomationHandler, g *rbacGuards) {
+ if h == nil {
+ return
+ }
+ automations := r.Group("/automations", g.Viewer())
+ {
+ automations.GET("", h.ListAutomations)
+ automations.POST("", h.CreateAutomation)
+ automations.POST("/validate-trigger", h.ValidateTrigger)
+ automations.GET("/by-session/:session_id", h.GetAutomationBySession)
+ automations.GET("/:id", h.GetAutomation)
+ automations.PUT("/:id", h.UpdateAutomation)
+ automations.DELETE("/:id", h.DeleteAutomation)
+ automations.POST("/:id/pause", h.PauseAutomation)
+ automations.POST("/:id/resume", h.ResumeAutomation)
+ automations.POST("/:id/run", h.RunAutomation)
+ automations.GET("/:id/runs", h.ListAutomationRuns)
+ automations.GET("/:id/grants", h.ListAutomationGrants)
+ automations.POST("/:id/grants", h.AddAutomationGrant)
+ automations.GET("/:id/grant-candidates", h.ListAutomationGrantCandidates)
+ }
+ runs := r.Group("/automation-runs", g.Viewer())
+ {
+ runs.GET("/:id", h.GetAutomationRun)
+ runs.POST("/:id/cancel", h.CancelAutomationRun)
+ }
+ notifications := r.Group("/notifications", g.Viewer())
+ {
+ notifications.GET("", h.ListNotifications)
+ notifications.POST("/read", h.MarkNotificationsRead)
+ }
+}
diff --git a/internal/types/agent_prompt.go b/internal/types/agent_prompt.go
index e237b35bc..1365f3b4f 100644
--- a/internal/types/agent_prompt.go
+++ b/internal/types/agent_prompt.go
@@ -208,6 +208,11 @@ type ToolApprovalPromptRequest struct {
// GrantLapsed, when set, is why an earlier grant for this call no longer
// applies (an AgentGrantLapse value).
GrantLapsed string `json:"grant_lapsed,omitempty"`
+ // GrantRisk is the risk Grant would be given for, and GrantLabel its
+ // description, whether or not the card offers it: an automation's owner
+ // may later allow the same call for its future runs.
+ GrantRisk string `json:"grant_risk,omitempty"`
+ GrantLabel string `json:"grant_label,omitempty"`
}
// ToolApprovalPromptResponse is the Response of an AgentPromptKindToolApproval.
diff --git a/internal/types/automation.go b/internal/types/automation.go
new file mode 100644
index 000000000..a88ba78ac
--- /dev/null
+++ b/internal/types/automation.go
@@ -0,0 +1,258 @@
+package types
+
+import (
+ "time"
+
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+// SessionKindAutomation holds the conversations of automation runs; they are
+// opened from the automation, not the ordinary chat list.
+const SessionKindAutomation = "automation"
+
+// Automation trigger types.
+const (
+ AutomationTriggerCron = "cron"
+ AutomationTriggerOnce = "once"
+)
+
+// Automation session modes.
+const (
+ // AutomationSessionPerRun starts a new conversation for every run.
+ AutomationSessionPerRun = "per_run"
+ // AutomationSessionPersistent writes every run into one conversation.
+ AutomationSessionPersistent = "persistent"
+)
+
+// Automation misfire and overlap policies.
+const (
+ AutomationPolicySkip = "skip"
+ AutomationPolicyRunOnce = "run_once"
+ AutomationPolicyQueue = "queue"
+)
+
+// Automation run trigger kinds.
+const (
+ AutomationRunSchedule = "schedule"
+ AutomationRunManual = "manual"
+ AutomationRunMisfire = "misfire"
+)
+
+// Automation run statuses.
+const (
+ AutomationRunQueued = "queued"
+ AutomationRunRunning = "running"
+ AutomationRunAwaitingApproval = "awaiting_approval"
+ AutomationRunSucceeded = "succeeded"
+ AutomationRunFailed = "failed"
+ AutomationRunCancelled = "cancelled"
+ AutomationRunSkipped = "skipped"
+ // AutomationRunNeedsAttention: the executor died mid-run, so whether its
+ // tool calls took effect is unknown. It is never replayed.
+ AutomationRunNeedsAttention = "needs_attention"
+)
+
+// AutomationRunActive reports whether a run in status still holds the
+// automation: it is executing or waiting for the user.
+func AutomationRunActive(status string) bool {
+ return status == AutomationRunRunning || status == AutomationRunAwaitingApproval
+}
+
+// AutomationRunFinished reports whether status is final.
+func AutomationRunFinished(status string) bool {
+ switch status {
+ case AutomationRunSucceeded, AutomationRunFailed, AutomationRunCancelled,
+ AutomationRunSkipped, AutomationRunNeedsAttention:
+ return true
+ }
+ return false
+}
+
+// AutomationTrigger is when an automation runs.
+type AutomationTrigger struct {
+ // Type is cron or once.
+ Type string `json:"type" extensions:"x-agent"`
+ // Expr is a cron expression: five fields (minute first) or six (seconds
+ // first), or a descriptor such as @daily.
+ Expr string `json:"expr,omitempty" extensions:"x-agent"`
+ // At is when a once trigger fires, RFC3339 or a wall-clock time in
+ // Timezone, such as "2006-01-02T15:04:05" or "2006-01-02 15:04".
+ At string `json:"at,omitempty" extensions:"x-agent"`
+ // Timezone is an IANA zone, e.g. Asia/Shanghai; empty means UTC.
+ Timezone string `json:"timezone,omitempty" extensions:"x-agent"`
+}
+
+// AutomationLimits bound one run.
+type AutomationLimits struct {
+ // MaxDurationMinutes caps a run's execution time, not counting time spent
+ // waiting for approval. 0 uses the default.
+ MaxDurationMinutes int `json:"max_duration_minutes,omitempty" extensions:"x-agent"`
+}
+
+// Automation is a task an agent runs on a schedule on its owner's behalf.
+type Automation struct {
+ ID string `json:"id" gorm:"type:varchar(36);primaryKey" extensions:"x-agent=automation_id,x-agent-response"`
+ TenantID uint64 `json:"tenant_id" gorm:"not null;index:idx_automations_owner"`
+ // OwnerUserID is the account the automation runs as.
+ OwnerUserID string `json:"owner_user_id" gorm:"type:varchar(36);not null;index:idx_automations_owner"`
+ Name string `json:"name" gorm:"type:varchar(255);not null" extensions:"x-agent"`
+ Description string `json:"description" gorm:"type:text" extensions:"x-agent"`
+ Enabled bool `json:"enabled" gorm:"not null;default:true;index:idx_automations_due" extensions:"x-agent,x-agent-response"`
+ // AgentID is the agent that runs it; the WeKnora assistant's ID runs the
+ // assistant.
+ AgentID string `json:"agent_id" gorm:"type:varchar(64);not null" extensions:"x-agent"`
+ // Instruction is the task, sent as the user message of each run after
+ // its variables are filled in.
+ Instruction string `json:"instruction" gorm:"type:text;not null" extensions:"x-agent,x-agent-detail"`
+ Trigger AutomationTrigger `json:"trigger" gorm:"column:trigger_config;serializer:json;type:text;not null" extensions:"x-agent"`
+ SessionMode string `json:"session_mode" gorm:"type:varchar(16);not null;default:'per_run'" extensions:"x-agent"`
+ // PersistentSessionID is the conversation of a persistent automation,
+ // created on its first run.
+ PersistentSessionID string `json:"persistent_session_id" gorm:"type:varchar(36);not null;default:''"`
+ // CarryLastResult adds the last successful answer to each per-run
+ // conversation.
+ CarryLastResult bool `json:"carry_last_result" gorm:"not null;default:false" extensions:"x-agent"`
+ MisfirePolicy string `json:"misfire_policy" gorm:"type:varchar(16);not null;default:'skip'" extensions:"x-agent"`
+ OverlapPolicy string `json:"overlap_policy" gorm:"type:varchar(16);not null;default:'skip'" extensions:"x-agent"`
+ // AccessLevel is how far runs may change data without asking, capped by
+ // the agent's and the workspace's ceilings.
+ AccessLevel AssistantAccessLevel `json:"access_level" gorm:"type:varchar(16);not null;default:'confirm'" extensions:"x-agent"`
+ // ApprovalTimeoutMinutes is how long a run waits for an approval before
+ // it fails.
+ ApprovalTimeoutMinutes int `json:"approval_timeout_minutes" gorm:"not null;default:1440" extensions:"x-agent"`
+ Limits AutomationLimits `json:"limits" gorm:"serializer:json;type:text;not null"`
+ NotifyOnSuccess bool `json:"notify_on_success" gorm:"not null;default:false" extensions:"x-agent"`
+
+ NextRunAt *time.Time `json:"next_run_at" gorm:"index:idx_automations_due" extensions:"x-agent,x-agent-response"`
+ LastRunAt *time.Time `json:"last_run_at" extensions:"x-agent,x-agent-response"`
+ LastSuccessAt *time.Time `json:"last_success_at" extensions:"x-agent,x-agent-response"`
+ LastRunStatus string `json:"last_run_status" gorm:"type:varchar(32);not null;default:''" extensions:"x-agent,x-agent-response"`
+ ConsecutiveFailures int `json:"consecutive_failures" gorm:"not null;default:0"`
+ PausedReason string `json:"paused_reason" gorm:"type:text;not null;default:''" extensions:"x-agent,x-agent-response"`
+ // Version guards claiming a due run against other instances.
+ Version int64 `json:"-" gorm:"not null;default:0"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
+ DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
+}
+
+// BeforeCreate sets the ID.
+func (a *Automation) BeforeCreate(*gorm.DB) error {
+ if a.ID == "" {
+ a.ID = uuid.NewString()
+ }
+ return nil
+}
+
+// AutomationRun is one execution of an automation.
+type AutomationRun struct {
+ ID string `json:"id" gorm:"type:varchar(36);primaryKey" extensions:"x-agent=run_id,x-agent-response"`
+ AutomationID string `json:"automation_id" gorm:"type:varchar(36);not null;uniqueIndex:idx_automation_runs_slot,priority:1;index:idx_automation_runs_automation"` //nolint:lll // one-line struct tag
+ TenantID uint64 `json:"tenant_id" gorm:"not null"`
+ // ScheduledAt is when the run was due; for a manual run, when it was
+ // asked for.
+ ScheduledAt time.Time `json:"scheduled_at" gorm:"not null;uniqueIndex:idx_automation_runs_slot,priority:2" extensions:"x-agent,x-agent-response"`
+ TriggerKind string `json:"trigger_kind" gorm:"type:varchar(16);not null;uniqueIndex:idx_automation_runs_slot,priority:3" extensions:"x-agent,x-agent-response"`
+ Status string `json:"status" gorm:"type:varchar(32);not null;index:idx_automation_runs_status" extensions:"x-agent,x-agent-response"`
+ SessionID string `json:"session_id" gorm:"type:varchar(36);not null;default:''" extensions:"x-agent,x-agent-response"`
+ // UserMessageID and AssistantMessageID are the run's turn in SessionID.
+ UserMessageID string `json:"user_message_id" gorm:"type:varchar(36);not null;default:''"`
+ AssistantMessageID string `json:"assistant_message_id" gorm:"type:varchar(36);not null;default:''"`
+ // Owner and LeaseUntil fence execution: only the instance holding an
+ // unexpired lease may finish the run.
+ Owner string `json:"-" gorm:"type:varchar(36);not null;default:''"`
+ LeaseUntil *time.Time `json:"-"`
+ // PendingPromptID is the approval a waiting run is suspended on.
+ PendingPromptID string `json:"pending_prompt_id" gorm:"type:varchar(36);not null;default:''"`
+ // Resume asks the executor to continue the run from PendingPromptID's
+ // answer rather than start it.
+ Resume bool `json:"-" gorm:"not null;default:false"`
+ // CancelRequested stops the run at its next check.
+ CancelRequested bool `json:"cancel_requested" gorm:"not null;default:false"`
+ // Answer is the start of the final answer, for listings.
+ Answer string `json:"answer" gorm:"type:text;not null;default:''" extensions:"x-agent,x-agent-response"`
+ Error string `json:"error" gorm:"type:text;not null;default:''" extensions:"x-agent,x-agent-response"`
+ Usage JSON `json:"usage" gorm:"type:text"`
+ StartedAt *time.Time `json:"started_at" extensions:"x-agent,x-agent-response"`
+ FinishedAt *time.Time `json:"finished_at" extensions:"x-agent,x-agent-response"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
+}
+
+// BeforeCreate sets the ID.
+func (r *AutomationRun) BeforeCreate(*gorm.DB) error {
+ if r.ID == "" {
+ r.ID = uuid.NewString()
+ }
+ return nil
+}
+
+// AutomationPatch creates an automation, or changes the fields it carries
+// on an existing one; a field left out is kept.
+type AutomationPatch struct {
+ // What the automation is called
+ Name *string `json:"name" extensions:"x-agent"`
+ // What it is for
+ Description *string `json:"description" extensions:"x-agent"`
+ // Agent that runs it, from agent.list; empty runs the WeKnora assistant
+ AgentID *string `json:"agent_id" extensions:"x-agent"`
+ // The task, sent as the user message of each run. May name now,
+ // last_run_at, last_success_at, run_id or automation_name inside double
+ // curly braces to have it filled in
+ Instruction *string `json:"instruction" extensions:"x-agent,x-agent-max-bytes=32000"`
+ // When it runs
+ Trigger *AutomationTrigger `json:"trigger" extensions:"x-agent"`
+ // per_run starts a new conversation each run; persistent keeps one
+ SessionMode *string `json:"session_mode" enums:"per_run,persistent" extensions:"x-agent"`
+ // Whether each per_run conversation gets the last successful answer
+ CarryLastResult *bool `json:"carry_last_result" extensions:"x-agent"`
+ // What happens to runs missed while the service was down or paused
+ MisfirePolicy *string `json:"misfire_policy" enums:"skip,run_once" extensions:"x-agent"`
+ // What happens when a run is due while the previous one is still going
+ OverlapPolicy *string `json:"overlap_policy" enums:"skip,queue" extensions:"x-agent"`
+ // How far runs may change data without asking
+ AccessLevel *AssistantAccessLevel `json:"access_level" enums:"read_only,confirm,auto_write" extensions:"x-agent"`
+ // How long a run waits for an approval before it fails, in minutes
+ ApprovalTimeoutMinutes *int `json:"approval_timeout_minutes" extensions:"x-agent"`
+ Limits *AutomationLimits `json:"limits"`
+ // Whether a successful run notifies the owner
+ NotifyOnSuccess *bool `json:"notify_on_success" extensions:"x-agent"`
+ // Whether it is scheduled; on update use pause and resume instead
+ Enabled *bool `json:"enabled"`
+}
+
+// AutomationActingVia is the Principal.ActingVia of a run of automation id.
+func AutomationActingVia(id string) string { return "automation:" + id }
+
+// Notification kinds.
+const (
+ NotificationAutomationSucceeded = "automation.succeeded"
+ NotificationAutomationFailed = "automation.failed"
+ NotificationAutomationAwaitingApproval = "automation.awaiting_approval"
+ NotificationAutomationPaused = "automation.paused"
+)
+
+// Notification is an in-app message for one user.
+type Notification struct {
+ ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
+ TenantID uint64 `json:"tenant_id" gorm:"not null;index:idx_notifications_user,priority:1"`
+ UserID string `json:"-" gorm:"type:varchar(36);not null;index:idx_notifications_user,priority:2"`
+ Kind string `json:"kind" gorm:"type:varchar(64);not null"`
+ Title string `json:"title" gorm:"type:varchar(255);not null"`
+ Body string `json:"body" gorm:"type:text;not null;default:''"`
+ // Link is an in-app route the notification opens.
+ Link string `json:"link" gorm:"type:text;not null;default:''"`
+ SourceType string `json:"source_type" gorm:"type:varchar(32);not null;default:''"`
+ SourceID string `json:"source_id" gorm:"type:varchar(36);not null;default:''"`
+ ReadAt *time.Time `json:"read_at"`
+ CreatedAt time.Time `json:"created_at" gorm:"index:idx_notifications_user,priority:3"`
+}
+
+// BeforeCreate sets the ID.
+func (n *Notification) BeforeCreate(*gorm.DB) error {
+ if n.ID == "" {
+ n.ID = uuid.NewString()
+ }
+ return nil
+}
diff --git a/internal/types/page_action.go b/internal/types/page_action.go
index 9ed9a481b..244f73b68 100644
--- a/internal/types/page_action.go
+++ b/internal/types/page_action.go
@@ -78,6 +78,7 @@ type PageNavigateTarget struct {
KnowledgeID string `json:"knowledge_id,omitempty"`
WikiSlug string `json:"wiki_slug,omitempty"`
AgentID string `json:"agent_id,omitempty"`
+ AutomationID string `json:"automation_id,omitempty"`
Section string `json:"section,omitempty"`
// Panel is a tab inside a settings section, e.g. system-global's users.
Panel string `json:"panel,omitempty"`
diff --git a/internal/types/qa_request.go b/internal/types/qa_request.go
index a7a1eaa59..0f9b1c0f0 100644
--- a/internal/types/qa_request.go
+++ b/internal/types/qa_request.go
@@ -218,6 +218,9 @@ type QARequest struct {
GrantSessionID string
// Resume, when set, continues a suspended run instead of starting one.
Resume *AgentResume
+ // RunNote is appended to the system prompt of this run only: how the
+ // run was started, for runs nobody is watching.
+ RunNote string
}
// AgentResume is what a resumed run continues from.
diff --git a/migrations/sqlite/000045_automations.down.sql b/migrations/sqlite/000045_automations.down.sql
new file mode 100644
index 000000000..873940ca6
--- /dev/null
+++ b/migrations/sqlite/000045_automations.down.sql
@@ -0,0 +1,3 @@
+DROP TABLE IF EXISTS notifications;
+DROP TABLE IF EXISTS automation_runs;
+DROP TABLE IF EXISTS automations;
diff --git a/migrations/sqlite/000045_automations.up.sql b/migrations/sqlite/000045_automations.up.sql
new file mode 100644
index 000000000..02e74fa7b
--- /dev/null
+++ b/migrations/sqlite/000045_automations.up.sql
@@ -0,0 +1,77 @@
+-- Scheduled agent tasks, their runs, and in-app notifications.
+CREATE TABLE IF NOT EXISTS automations (
+ id VARCHAR(36) PRIMARY KEY,
+ tenant_id BIGINT NOT NULL,
+ owner_user_id VARCHAR(36) NOT NULL,
+ name VARCHAR(255) NOT NULL,
+ description TEXT,
+ enabled BOOLEAN NOT NULL DEFAULT 1,
+ agent_id VARCHAR(64) NOT NULL,
+ instruction TEXT NOT NULL,
+ trigger_config TEXT NOT NULL,
+ session_mode VARCHAR(16) NOT NULL DEFAULT 'per_run',
+ persistent_session_id VARCHAR(36) NOT NULL DEFAULT '',
+ carry_last_result BOOLEAN NOT NULL DEFAULT 0,
+ misfire_policy VARCHAR(16) NOT NULL DEFAULT 'skip',
+ overlap_policy VARCHAR(16) NOT NULL DEFAULT 'skip',
+ access_level VARCHAR(16) NOT NULL DEFAULT 'confirm',
+ approval_timeout_minutes INTEGER NOT NULL DEFAULT 1440,
+ limits TEXT NOT NULL DEFAULT '{}',
+ notify_on_success BOOLEAN NOT NULL DEFAULT 0,
+ next_run_at DATETIME,
+ last_run_at DATETIME,
+ last_success_at DATETIME,
+ last_run_status VARCHAR(32) NOT NULL DEFAULT '',
+ consecutive_failures INTEGER NOT NULL DEFAULT 0,
+ paused_reason TEXT NOT NULL DEFAULT '',
+ version BIGINT NOT NULL DEFAULT 0,
+ created_at DATETIME NOT NULL,
+ updated_at DATETIME NOT NULL,
+ deleted_at DATETIME
+);
+CREATE INDEX IF NOT EXISTS idx_automations_due ON automations(enabled, next_run_at);
+CREATE INDEX IF NOT EXISTS idx_automations_owner ON automations(tenant_id, owner_user_id);
+CREATE INDEX IF NOT EXISTS idx_automations_deleted_at ON automations(deleted_at);
+
+CREATE TABLE IF NOT EXISTS automation_runs (
+ id VARCHAR(36) PRIMARY KEY,
+ automation_id VARCHAR(36) NOT NULL,
+ tenant_id BIGINT NOT NULL,
+ scheduled_at DATETIME NOT NULL,
+ trigger_kind VARCHAR(16) NOT NULL,
+ status VARCHAR(32) NOT NULL,
+ session_id VARCHAR(36) NOT NULL DEFAULT '',
+ user_message_id VARCHAR(36) NOT NULL DEFAULT '',
+ assistant_message_id VARCHAR(36) NOT NULL DEFAULT '',
+ owner VARCHAR(36) NOT NULL DEFAULT '',
+ lease_until DATETIME,
+ pending_prompt_id VARCHAR(36) NOT NULL DEFAULT '',
+ resume BOOLEAN NOT NULL DEFAULT 0,
+ cancel_requested BOOLEAN NOT NULL DEFAULT 0,
+ answer TEXT NOT NULL DEFAULT '',
+ error TEXT NOT NULL DEFAULT '',
+ usage TEXT,
+ started_at DATETIME,
+ finished_at DATETIME,
+ created_at DATETIME NOT NULL,
+ updated_at DATETIME NOT NULL
+);
+CREATE UNIQUE INDEX IF NOT EXISTS idx_automation_runs_slot
+ ON automation_runs(automation_id, scheduled_at, trigger_kind);
+CREATE INDEX IF NOT EXISTS idx_automation_runs_automation ON automation_runs(automation_id);
+CREATE INDEX IF NOT EXISTS idx_automation_runs_status ON automation_runs(status);
+
+CREATE TABLE IF NOT EXISTS notifications (
+ id VARCHAR(36) PRIMARY KEY,
+ tenant_id BIGINT NOT NULL,
+ user_id VARCHAR(36) NOT NULL,
+ kind VARCHAR(64) NOT NULL,
+ title VARCHAR(255) NOT NULL,
+ body TEXT NOT NULL DEFAULT '',
+ link TEXT NOT NULL DEFAULT '',
+ source_type VARCHAR(32) NOT NULL DEFAULT '',
+ source_id VARCHAR(36) NOT NULL DEFAULT '',
+ read_at DATETIME,
+ created_at DATETIME NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_notifications_user ON notifications(tenant_id, user_id, created_at);
diff --git a/migrations/versioned/000128_automations.down.sql b/migrations/versioned/000128_automations.down.sql
new file mode 100644
index 000000000..873940ca6
--- /dev/null
+++ b/migrations/versioned/000128_automations.down.sql
@@ -0,0 +1,3 @@
+DROP TABLE IF EXISTS notifications;
+DROP TABLE IF EXISTS automation_runs;
+DROP TABLE IF EXISTS automations;
diff --git a/migrations/versioned/000128_automations.up.sql b/migrations/versioned/000128_automations.up.sql
new file mode 100644
index 000000000..ef38f41db
--- /dev/null
+++ b/migrations/versioned/000128_automations.up.sql
@@ -0,0 +1,77 @@
+-- Scheduled agent tasks, their runs, and in-app notifications.
+CREATE TABLE IF NOT EXISTS automations (
+ id VARCHAR(36) PRIMARY KEY,
+ tenant_id BIGINT NOT NULL,
+ owner_user_id VARCHAR(36) NOT NULL,
+ name VARCHAR(255) NOT NULL,
+ description TEXT,
+ enabled BOOLEAN NOT NULL DEFAULT TRUE,
+ agent_id VARCHAR(64) NOT NULL,
+ instruction TEXT NOT NULL,
+ trigger_config TEXT NOT NULL,
+ session_mode VARCHAR(16) NOT NULL DEFAULT 'per_run',
+ persistent_session_id VARCHAR(36) NOT NULL DEFAULT '',
+ carry_last_result BOOLEAN NOT NULL DEFAULT FALSE,
+ misfire_policy VARCHAR(16) NOT NULL DEFAULT 'skip',
+ overlap_policy VARCHAR(16) NOT NULL DEFAULT 'skip',
+ access_level VARCHAR(16) NOT NULL DEFAULT 'confirm',
+ approval_timeout_minutes INTEGER NOT NULL DEFAULT 1440,
+ limits TEXT NOT NULL DEFAULT '{}',
+ notify_on_success BOOLEAN NOT NULL DEFAULT FALSE,
+ next_run_at TIMESTAMPTZ,
+ last_run_at TIMESTAMPTZ,
+ last_success_at TIMESTAMPTZ,
+ last_run_status VARCHAR(32) NOT NULL DEFAULT '',
+ consecutive_failures INTEGER NOT NULL DEFAULT 0,
+ paused_reason TEXT NOT NULL DEFAULT '',
+ version BIGINT NOT NULL DEFAULT 0,
+ created_at TIMESTAMPTZ NOT NULL,
+ updated_at TIMESTAMPTZ NOT NULL,
+ deleted_at TIMESTAMPTZ
+);
+CREATE INDEX IF NOT EXISTS idx_automations_due ON automations(enabled, next_run_at);
+CREATE INDEX IF NOT EXISTS idx_automations_owner ON automations(tenant_id, owner_user_id);
+CREATE INDEX IF NOT EXISTS idx_automations_deleted_at ON automations(deleted_at);
+
+CREATE TABLE IF NOT EXISTS automation_runs (
+ id VARCHAR(36) PRIMARY KEY,
+ automation_id VARCHAR(36) NOT NULL,
+ tenant_id BIGINT NOT NULL,
+ scheduled_at TIMESTAMPTZ NOT NULL,
+ trigger_kind VARCHAR(16) NOT NULL,
+ status VARCHAR(32) NOT NULL,
+ session_id VARCHAR(36) NOT NULL DEFAULT '',
+ user_message_id VARCHAR(36) NOT NULL DEFAULT '',
+ assistant_message_id VARCHAR(36) NOT NULL DEFAULT '',
+ owner VARCHAR(36) NOT NULL DEFAULT '',
+ lease_until TIMESTAMPTZ,
+ pending_prompt_id VARCHAR(36) NOT NULL DEFAULT '',
+ resume BOOLEAN NOT NULL DEFAULT FALSE,
+ cancel_requested BOOLEAN NOT NULL DEFAULT FALSE,
+ answer TEXT NOT NULL DEFAULT '',
+ error TEXT NOT NULL DEFAULT '',
+ usage TEXT,
+ started_at TIMESTAMPTZ,
+ finished_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL,
+ updated_at TIMESTAMPTZ NOT NULL
+);
+CREATE UNIQUE INDEX IF NOT EXISTS idx_automation_runs_slot
+ ON automation_runs(automation_id, scheduled_at, trigger_kind);
+CREATE INDEX IF NOT EXISTS idx_automation_runs_automation ON automation_runs(automation_id);
+CREATE INDEX IF NOT EXISTS idx_automation_runs_status ON automation_runs(status);
+
+CREATE TABLE IF NOT EXISTS notifications (
+ id VARCHAR(36) PRIMARY KEY,
+ tenant_id BIGINT NOT NULL,
+ user_id VARCHAR(36) NOT NULL,
+ kind VARCHAR(64) NOT NULL,
+ title VARCHAR(255) NOT NULL,
+ body TEXT NOT NULL DEFAULT '',
+ link TEXT NOT NULL DEFAULT '',
+ source_type VARCHAR(32) NOT NULL DEFAULT '',
+ source_id VARCHAR(36) NOT NULL DEFAULT '',
+ read_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_notifications_user ON notifications(tenant_id, user_id, created_at);