From 04cebdc504f3a5b10eb6a462953dde6be884791a Mon Sep 17 00:00:00 2001 From: linkong Date: Tue, 1 Dec 2026 18:43:57 +0800 Subject: [PATCH] release: bump version to 0.82.0 --- .codex/skills/release/SKILL.md | 40 +- AGENTS.md | 11 + README.md | 119 +- VERSION | 2 +- aiprovider/provider_service.py | 154 +- aiprovider/schemas.py | 7 + backend/app/api/v1/ai_workflows.py | 681 ++- backend/app/api/v1/situational_awareness.py | 17 + .../0006_add_ai_workflow_bindings.py | 30 + backend/app/db/session.py | 8 + backend/app/models/ai_workflow.py | 4 +- backend/app/schemas/ai.py | 7 + backend/app/services/ai/dag_executor.py | 823 ++++ backend/app/services/ai/stream_turn.py | 163 +- backend/app/services/ai/workflow_evolver.py | 2179 ++++++++++ backend/app/services/ai/workflow_registry.py | 803 +++- backend/app/services/alert_ai_brief.py | 76 +- .../app/services/location/agent_resolver.py | 17 +- .../services/location/resolvers/nominatim.py | 79 +- backend/tests/test_ai_workflows.py | 428 +- backend/tests/test_dag_executor.py | 364 ++ backend/tests/test_location_agent_workflow.py | 142 + backend/tests/test_workflow_evolver.py | 672 +++ client/package.json | 2 +- client/src/main/gpu-monitor.ts | 13 +- client/src/main/hot-updater.ts | 69 +- client/src/main/i18n.ts | 46 + client/src/main/index.ts | 9 +- client/src/main/menu.ts | 89 +- client/src/main/recording-core.ts | 10 +- client/src/main/recording-indicator.ts | 7 +- client/src/main/screen-recorder.ts | 13 +- client/src/main/window.ts | 21 +- client/src/preload/splash.ts | 16 +- docs/CHANGELOG.md | 20 + docs/HARNESS.md | 5 +- ...dvisor-workflow-and-location-agent-plan.md | 14 + ...th-influence-zones-and-vfx-upgrade-plan.md | 62 + docs/technical/en/agents-aiprovider.md | 19 +- docs/technical/en/earth-frontend-context.md | 5 + .../en/frontend-admin-frontend-context.md | 15 +- docs/technical/en/manual.md | 22 +- docs/technical/en/ops-runbook.md | 3 + docs/technical/en/quickstart.md | 2 +- docs/technical/zh/agents-aiprovider.md | 19 +- docs/technical/zh/earth-frontend-context.md | 5 + .../zh/frontend-admin-frontend-context.md | 15 +- docs/technical/zh/manual.md | 22 +- docs/technical/zh/ops-runbook.md | 3 + docs/technical/zh/quickstart.md | 2 +- docs/version-history.md | 3 +- frontend/package.json | 2 +- frontend/public/earth/css/info-panel.css | 169 + frontend/public/earth/index.html | 120 +- frontend/public/earth/js/about.js | 6 +- frontend/public/earth/js/cables.js | 4 +- frontend/public/earth/js/compute-centers.js | 6 +- .../public/earth/js/compute-topic-model.js | 2 +- frontend/public/earth/js/compute-topic.js | 29 +- frontend/public/earth/js/controls.js | 66 +- frontend/public/earth/js/copilot-stream.js | 4 +- frontend/public/earth/js/frame-stats.js | 4 +- frontend/public/earth/js/i18n.js | 236 +- frontend/public/earth/js/info-card.js | 308 +- frontend/public/earth/js/legend.js | 2 +- frontend/public/earth/js/main.js | 61 +- .../public/earth/js/motion-agent-provider.js | 6 +- .../earth/js/motion-browser-provider.js | 8 +- .../public/earth/js/motion-debug-panel.js | 7 +- frontend/public/earth/js/news-locale.js | 68 +- frontend/public/earth/js/news-region-cards.js | 14 +- frontend/public/earth/js/news.js | 47 +- frontend/public/earth/js/oobe.js | 16 +- frontend/public/earth/js/search.js | 14 +- .../public/earth/js/situational-copilot.js | 143 +- .../earth/js/situational-copilot.test.js | 4 +- .../public/earth/js/stage-narrative-player.js | 6 +- frontend/public/earth/js/tv.js | 22 +- frontend/public/earth/js/ui.js | 7 +- frontend/public/earth/js/workbench-blocks.js | 21 +- frontend/public/earth/js/workflow-bindings.js | 523 +++ .../public/earth/js/workflow-bindings.test.js | 150 + frontend/src/admin/AdminRoutes.tsx | 15 +- .../admin/components/AdminErrorBoundary.tsx | 5 +- .../admin/components/layout/AdminLayout.tsx | 53 +- frontend/src/admin/pages/AdvisorPages.css | 1829 +++++++- .../src/admin/pages/AdvisorPlayground.tsx | 1615 +++++-- frontend/src/admin/pages/AdvisorRuns.tsx | 547 ++- frontend/src/admin/pages/AdvisorWorkflows.tsx | 3772 +++++++++++++++-- frontend/src/admin/pages/ApiKeySettings.tsx | 15 +- .../src/admin/pages/CardImageSettings.tsx | 9 +- .../admin/pages/ComputeComparisonSettings.tsx | 12 +- frontend/src/admin/pages/Dashboard.tsx | 12 +- frontend/src/admin/pages/DataList.tsx | 10 +- frontend/src/admin/pages/Logs.tsx | 12 +- .../src/admin/pages/PlainResourcePages.tsx | 419 +- frontend/src/admin/pages/Users.tsx | 5 +- .../src/admin/pages/advisorAttachments.ts | 323 ++ .../src/admin/pages/advisorGraphLayout.ts | 205 + .../src/admin/pages/advisorWorkflowEditOps.ts | 291 ++ frontend/src/admin/pages/card-images.css | 12 +- .../src/admin/pages/compute-comparison.css | 12 +- frontend/src/admin/patterns/patterns.tsx | 169 +- frontend/src/admin/routes/manifest.tsx | 4 +- frontend/src/admin/runtimeLogs.ts | 6 +- frontend/src/admin/search/indexers.ts | 27 +- frontend/src/admin/styles.css | 111 +- .../MarkdownRenderer/MarkdownRenderer.tsx | 4 +- .../src/components/tactile-ui/Scrollbar.tsx | 47 +- .../tactile-ui/ScrollbarOverlay.tsx | 36 +- frontend/src/components/tactile-ui/styles.css | 12 + frontend/src/i18n/LegacyI18nBridge.tsx | 125 +- frontend/src/i18n/api-errors.ts | 92 +- frontend/src/i18n/legacy-ui.ts | 88 +- frontend/src/i18n/resources.ts | 150 +- frontend/src/index.css | 13 +- frontend/src/pages/Auth/AuthShell.tsx | 6 +- frontend/src/pages/Docs/Docs.css | 18 +- frontend/src/pages/Docs/Docs.tsx | 30 +- frontend/src/pages/Earth/Earth.tsx | 5 +- .../src/pages/Earth/EarthDesktopRedirect.tsx | 17 +- frontend/tests/admin-sidebar-state.test.ts | 4 +- frontend/tests/advisor-attachments.test.ts | 63 + frontend/tests/advisor-graph-layout.test.ts | 71 + .../tests/advisor-workflow-edit-ops.test.ts | 145 + frontend/tests/i18n-copy-audit.test.ts | 96 + pyproject.toml | 2 +- rules.md | 15 +- scripts/harness/frontend-rules-check.sh | 4 +- scripts/harness/frontend-smoke.mjs | 331 +- uv.lock | 2 +- 131 files changed, 17975 insertions(+), 2323 deletions(-) create mode 100644 backend/app/db/migration_steps/0006_add_ai_workflow_bindings.py create mode 100644 backend/app/services/ai/dag_executor.py create mode 100644 backend/app/services/ai/workflow_evolver.py create mode 100644 backend/tests/test_dag_executor.py create mode 100644 backend/tests/test_workflow_evolver.py create mode 100644 client/src/main/i18n.ts create mode 100644 docs/plans/earth-influence-zones-and-vfx-upgrade-plan.md create mode 100644 frontend/public/earth/js/workflow-bindings.js create mode 100644 frontend/public/earth/js/workflow-bindings.test.js create mode 100644 frontend/src/admin/pages/advisorAttachments.ts create mode 100644 frontend/src/admin/pages/advisorGraphLayout.ts create mode 100644 frontend/src/admin/pages/advisorWorkflowEditOps.ts create mode 100644 frontend/tests/advisor-attachments.test.ts create mode 100644 frontend/tests/advisor-graph-layout.test.ts create mode 100644 frontend/tests/advisor-workflow-edit-ops.test.ts create mode 100644 frontend/tests/i18n-copy-audit.test.ts diff --git a/.codex/skills/release/SKILL.md b/.codex/skills/release/SKILL.md index 70f01629..56c2860e 100644 --- a/.codex/skills/release/SKILL.md +++ b/.codex/skills/release/SKILL.md @@ -1,15 +1,15 @@ --- name: release -description: Use when the user asks to release, bump version, update changelog/version files, or commit/push a repository release for the Planet repo. Determines version bump type from changes, updates all required version-bearing files, updates changelog and version-history, runs minimal validation, then commits, tags, and pushes. +description: Use when the user asks to release, deploy, bump version, update changelog/version files, or commit/push a repository release (`发版`, `部署`, `发版部署`) for the Planet repo. Covers version bumps, validation, commit/tag/push, Gitea/OCI publication, production host script/config sync, and live deployment verification. --- # Release Workflow -Use this skill for release-oriented work in this repository. +Use this skill for release and production deployment work in this repository. ## When To Use -- The user asks to `发版` +- The user asks to `发版`, `部署`, `发版部署`, `上线`, or `deploy` - The user asks to bump a version - The user asks to update `CHANGELOG`, `version-history`, or version files as part of a release - The user asks to commit/push a release or a publishable bugfix/feature bundle @@ -213,6 +213,38 @@ attachment names and sizes before publishing. Verify the published Release URL and expected attachments through Gitea before reporting success. If Gitea is unreachable, report the tag and package state and why publication is incomplete. +### Step 9.5 — Production Host Sync & Live Deployment Verification (Required for `部署` / `发版部署` / `上线`) + +Publishing images/manifests/Gitea assets in Step 9 does **not** deploy or update host-managed files (`发版 ≠ 已部署`). Whenever the user asks to `部署`, `发版部署`, or `上线`, run all four sub-checks before claiming deployment succeeded: + +1. **Detect host-side file drift** against the previous release tag (``): + + ```bash + git diff --name-only ..vx.x.x -- \ + scripts/production_deploy.py \ + scripts/production_registry.py \ + scripts/release_publish.py \ + deploy/ \ + docker-compose.deploy.yml + ``` + +2. **Sync changed host-managed files BEFORE rollout/retry** (using the operator's configured SSH access; never hardcode IPs or secrets in repo files): + - If `scripts/production_deploy.py`, `scripts/production_registry.py`, or `scripts/release_publish.py` changed -> install onto the production host `/usr/local/lib/planet-release/` **before** triggering or retrying deployment so stale host checks (e.g. newly added `401` auth gates) cannot trigger a false-positive rollback. + - If `deploy/systemd/planet-release-deploy.{service,timer}` changed -> install to `/etc/systemd/system/` and run `sudo systemctl daemon-reload`. + - If `docker-compose.deploy.yml` or `deploy/nginx/*` changed -> sync env/compose additions into `/opt/planet/current/` or host Nginx sites and run `sudo nginx -t && sudo systemctl reload nginx`. + +3. **Trigger or observe production rollout on host**: + - Inspect service status and trigger/retry as needed: + - Check logs: `journalctl -u planet-release-deploy.service -n 50 --no-pager` + - Verify state / manifest match: `sudo python3 /usr/local/lib/planet-release/production_deploy.py --check` + - If an earlier timer run failed (e.g. due to a host-script mismatch) and skipped `vx.x.x`, clear the skip after syncing host scripts by running `sudo python3 /usr/local/lib/planet-release/production_deploy.py --retry` (or `sudo systemctl start planet-release-deploy.service`). + - Confirm running containers (`backend`, `admin`, `aiprovider`) are `healthy` and their image digests match OCI `release-manifest:vx.x.x`. + +4. **Verify live public endpoints reflect `vx.x.x`**: + - Confirm `https://api.rclaw.top/health/ready` returns HTTP 200 and live version matches `x.x.x`. + - When `client.mode != "none"`, confirm `https://rclaw.top/api/v1/client/update-manifest` returns `version == "x.x.x"` and the expected bundle SHA-256. + - **Never claim `已部署` if host SSH is unavailable or live endpoints still show an older version**: report publication complete (`dev` / `vx.x.x` / Gitea / OCI) separately from the exact pending host sync / deploy commands. + ### Step 10 — Completion summary ``` @@ -225,6 +257,8 @@ unreachable, report the tag and package state and why publication is incomplete. ✓ tag: v0.76.19 ✓ Pushed to origin/dev (or reported pending manual push) ✓ Gitea Release and attachments verified (when publication was requested) +✓ Host-side deploy scripts / Compose / Nginx drift checked & synced (when deployment was requested) +✓ Production rollout & live endpoints verified at target version (or pending host steps listed explicitly) ``` ## Notes diff --git a/AGENTS.md b/AGENTS.md index eaa722d4..c9255e12 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -90,6 +90,7 @@ the user's login interactive shell instead of assuming a specific dotfile. - `planet.sh` owns local lifecycle, ports, WSL/LAN behavior, and destructive `destroy` cleanup. - Frontend package management is Bun-only. Do not use npm, pnpm, or yarn. +- **Local Frontend Dev Uses Vite, Not Static Nginx**: Local frontend/Admin development defaults to the host Vite HMR server (`./planet.sh start` / `./planet.sh restart -f`); do not run or rebuild the static Nginx `planet_admin` container (`./planet.sh admin ...`) unless the user explicitly asks to simulate production locally (`本地模拟线上`). - Frontend changes must satisfy `scripts/harness/frontend-rules-check.sh`; use rendered smoke evidence for public pages, auth guards, authenticated admin route/section availability, safe navigation/search/tab interactions, mobile @@ -131,6 +132,16 @@ the user's login interactive shell instead of assuming a specific dotfile. `release-manifest:` and must **not** create a Gitea Release; only `hotfix` or `full` client releases create a Gitea Release, and production `planet-release-deploy` reconciles from Git tags + OCI `release-manifest:`. +- **Release Publish vs. Production Deployment (`发版 ≠ 已部署`)**: + `scripts/release_publish.py` only publishes container images, OCI + `release-manifest:`, and optional Gitea Releases; it never updates + host-side files or verifies rollout. Whenever the user asks to `部署`, + `发版部署`, or `上线`, follow `.codex/skills/release/SKILL.md` to diff + host-managed files (`scripts/production_deploy.py`, `deploy/`, + `docker-compose.deploy.yml`) against the prior tag, sync any changed host + files before rollout/retry, inspect `planet-release-deploy.service`, and + verify live public endpoints reflect the target version before claiming + deployment succeeded. ### Conflict Policy diff --git a/README.md b/README.md index 8fd0abd9..d5867ee6 100644 --- a/README.md +++ b/README.md @@ -13,42 +13,35 @@ - **Admin 运维台**:支持通过 `PLANET_FRONTEND_TARGET=admin` 构建剔除 Earth 静态资源(约 110 MB)的轻量 Nginx 容器 `planet_admin`,也可保留在一体化 Web 开发服务中。 - **后端与模型适配层**:FastAPI 数据与 AI 编排后端 + `aiprovider` 独立模型协议适配层。 -``` -┌─────────────────────────────────────────────────────────────────────┐ -│ 浏览器展示与运维层 │ -│ ┌──────────────────────────────┐ ┌──────────────────────────────┐ │ -│ │ Web Earth │ │ React 运维台 │ │ -│ │ frontend/public/earth │ │ frontend/src │ │ -│ │ Three.js 地球 / HUD / 新闻 │ │ 数据源 / 告警 / AI 设置 │ │ -│ │ 国界精度 / 品牌内容配置 │ │ 提示词配置 / 用户与系统配置 │ │ -│ └──────────────────────────────┘ └──────────────────────────────┘ │ -└─────────────────────────────────────────────────────────────────────┘ - │ REST / WebSocket - ▼ -┌─────────────────────────────────────────────────────────────────────┐ -│ FastAPI 业务与编排后端 │ -│ ┌────────────────────┐ ┌────────────────────┐ ┌─────────────────┐ │ -│ │ 数据 API 与认证 │ │ Earth 新闻增强 │ │ 告警与态势简报 │ │ -│ │ JWT / 权限 / 审计 │ │ 位置推断 / 本地化 │ │ BGP / 告警研判 │ │ -│ └────────────────────┘ └────────────────────┘ └─────────────────┘ │ -│ ┌────────────────────┐ ┌────────────────────┐ ┌─────────────────┐ │ -│ │ 系统运行配置 │ │ 默认提示词注册表 │ │ 未来 Agent Runtime│ │ -│ │ system_settings │ │ 代码发布 + DB 覆盖 │ │ 工具/证据/工作流 │ │ -│ └────────────────────┘ └────────────────────┘ └─────────────────┘ │ -└─────────────────────────────────────────────────────────────────────┘ - │ SQLAlchemy / Redis Stream │ 纯净 LLM 调用 - ▼ ▼ -┌──────────────────────────────┐ ┌──────────────────────────────┐ -│ PostgreSQL / Redis │ │ aiprovider │ -│ 用户、配置、采集结果、新闻 │ │ provider + protocol adapter │ -│ Stream、缓存、运行状态 │ │ OpenAI / MiniMax / Ollama 等 │ -└──────────────────────────────┘ └──────────────────────────────┘ - ▲ - │ 采集器 / 外部数据源 - ▼ -┌─────────────────────────────────────────────────────────────────────┐ -│ RSS 新闻、BGP 观测、公开数据源、后续 WebSearch/OCR/语音识别等工具 │ -└─────────────────────────────────────────────────────────────────────┘ +```mermaid +flowchart TD + subgraph UI["展示与运维端"] + Earth["Web / Electron Earth (frontend/public/earth + client)"] + Admin["React 运维台与 AI 参谋 (frontend/src/admin)"] + end + + subgraph Backend["FastAPI 业务与 AI 编排后端 (backend/)"] + API["业务 API、认证与反爬网关"] + DAG["DAG 多节点工作流引擎与工具白名单"] + Evolve["三层工作流自进化与宪法校验内核"] + Settings["系统配置与默认提示词 (system_settings / default_prompts)"] + end + + subgraph Infra["数据存储与模型协议层"] + PG["PostgreSQL / Redis (数据、快照、运行轨迹与进化台账)"] + AIP["aiprovider 独立协议网关 (OpenAI / MiniMax / Ollama 等)"] + Sources["外部采集源 (RSS / BGP / PeeringDB / 海缆 / 卫星 / WebSearch)"] + end + + Earth -->|"REST / SSE / WebSocket"| API + Admin -->|"REST / SSE"| API + API --> DAG + API --> Settings + DAG -->|"运行遥测与灰度检查"| Evolve + Evolve -->|"受宪法约束写回草稿 / 发布 / 回滚"| PG + API --> PG + DAG -->|"纯净模型请求"| AIP + Sources -->|"采集与增强写入"| PG ``` 架构边界: @@ -57,7 +50,32 @@ - `aiprovider` 只负责把纯净模型请求适配到不同供应商或协议,不内置具体业务提示词。 - 默认提示词随代码发布并保存在 `backend/app/ai_tasks/default_prompts.json`,运维台可在数据库中保存覆盖值,重置时回到当前代码版本的默认提示词。 - Earth 新闻保留英文原文,中文展示结果存入 `localizations`,前端默认展示 `zh-CN` 的 `display_title`、`display_summary` 和中文地域/状态文案。 -- Earth LLM 指令、语音识别、多角色态势研判属于后续 Agent Runtime 方向,计划见 [docs/plans/agents-earth-command-runtime-plan.md](/home/ray/dev/linkong/planet/docs/plans/agents-earth-command-runtime-plan.md)。 +- AI 工作流支持可视化编排、自进化调优与地球交互联动,规划与演进记录见 [AI 参谋工作流与自进化方案](docs/plans/ai-advisor-workflow-and-location-agent-plan.md) 与 [Earth 贴地影响范围与三维视觉升级方案](docs/plans/earth-influence-zones-and-vfx-upgrade-plan.md)。 + +## AI 工作流自进化与元进化 + +为避免“人工写死工作流无法随新模型与真实运行退化持续迭代”,系统内置了 **零改表、三层有界自举架构**(详见 [workflow_evolver.py](backend/app/services/ai/workflow_evolver.py)): + +- **Tier 0 · 不可变宪法内核(Python 硬约束)**:AI 永远无法修改底层校验代码。强制执行单层元递归锁(禁止自定义 `meta.*`)、冻结元引擎 `verify_output` 节点、限制单次自动改动半径(`<= 2` 个且 `<= 40%` 节点)、强制冷却期与每日自动预算上限,以及 **5 次运行灰度自动回滚**。 +- **Tier 1 · 业务工作流自优化与模型适配**:零成本采集 `WorkflowRun.budget_used` 中的模型名、耗时、版本号与 👍/👎 反馈;结合 0-Token 健康诊断、模型能力漂移检测、DGM 历史最佳父版本分支与 AFlow 正负经验生成最小节点补丁,并支持 Fixture A/B 对照与从高频问题孵化新工作流。可在管理台 `/advisor/workflows` 顶栏随时切换 `关闭(手动)` / `自动写草稿` / `自动发布 + 灰度回滚` 模式及单工作流锁定开关。 +- **Tier 2 · 元进化(`meta.workflow_evolver` 自举)**:内置三节点元工作流直接在工作流画布可见、可回滚;在独立开启元进化开关后,可依据历史台账验证/回滚客观结果迭代自身诊断与补丁合成策略,并受 7 天冷却与下游 3 次结果窗口自动回退保护。 + +```mermaid +flowchart TD + Run["Playground / Earth 工作流运行 (记录 model_used / latency / 版本号)"] --> FB["管理员 👍 / 👎 反馈与失败轨迹"] + FB --> Health["0-Token 健康与模型漂移诊断 (信号检测 + DGM 最佳父版本)"] + Health -->|"手动触发或满足冷却/预算后异步触发"| Meta["Tier 2 元引擎 meta.workflow_evolver (diag_node -> patch_node -> verify_output)"] + Ledger["进化台账 system_settings.ai_evolution_ledger (正负经验 / 已验证 / 已回滚)"] -->|"AFlow 经验注入"| Meta + Meta -->|"生成最小节点 Diff 补丁"| Tier0{"Tier 0 不可变宪法内核:白名单 / 半径锁 / 禁清空提示词 / 禁 meta 递归"} + Tier0 -->|"拦截"| Block["记入台账 blocked 并保留原版本"] + Tier0 -->|"通过"| Mode{"策略模式 (off / draft / auto)"} + Mode -->|"draft"| Draft["写入 draft_graph 待人工审核 / Fixture A-B 对照"] + Mode -->|"auto (未锁定且未超日上限)"| Canary["自动发布新版本 + 开启 5 次运行灰度窗口"] + Canary -->|"连续 2 次失败或差评率超阈"| Rollback["自动回滚上一稳定版本 & 记为 rolled_back"] + Canary -->|"通过 5 次运行验证"| Verified["晋升为 verified 经验;积累 >=5 条后可触发元引擎自举"] + Verified --> Ledger + Rollback --> Ledger +``` ## 四大核心要素 @@ -239,7 +257,7 @@ bun run build 推荐按下面顺序排查和配置。 -端口占用、`iphlpsvc` / portproxy、摄像头和依赖问题的集中排障入口见 [常见问题](/home/ray/dev/linkong/planet/docs/technical/zh/faq.md)。 +端口占用、`iphlpsvc` / portproxy、摄像头和依赖问题的集中排障入口见 [常见问题](docs/technical/zh/faq.md)。 ### 1. 在 WSL 中启动服务 @@ -381,7 +399,7 @@ DATABASE_RETRY_INTERVAL=10 \ - 运维台 AI 设置可维护 provider、模型、协议、超时、token 等运行配置。 - 运维台 AI 设置中的“提示词”页可选择不同功能入口,手动覆盖提示词,并一键重置到默认值。 -- 默认提示词随代码发布,位于 [backend/app/ai_tasks/default_prompts.json](/home/ray/dev/linkong/planet/backend/app/ai_tasks/default_prompts.json)。 +- 默认提示词随代码发布,位于 [backend/app/ai_tasks/default_prompts.json](backend/app/ai_tasks/default_prompts.json)。 - 覆盖值保存在数据库运行配置中,升级代码后可继续保留现场配置,也可重置到新版本默认提示词。 - 态势摘要、告警研判、新闻本地化等入口应使用各自任务提示词;调用 `aiprovider` 时只传递当前任务所需的 `prompt` / `system_prompt`。 @@ -427,8 +445,8 @@ AI_ANTHROPIC_VERSION=2023-06-01 如果你要本地直接起模型适配层,项目里已经补了模板: -- [aiprovider/.env.example](/home/ray/dev/linkong/planet/aiprovider/.env.example) -- [docker-compose.local-model.yml](/home/ray/dev/linkong/planet/docker-compose.local-model.yml) +- [aiprovider/.env.example](aiprovider/.env.example) +- [docker-compose.local-model.yml](docker-compose.local-model.yml) 运行与调用补充: @@ -439,13 +457,14 @@ AI_ANTHROPIC_VERSION=2023-06-01 详细文档: -- [docs/technical/zh/agents-aiprovider.md](/home/ray/dev/linkong/planet/docs/technical/zh/agents-aiprovider.md) -- [docs/technical/en/agents-aiprovider.md](/home/ray/dev/linkong/planet/docs/technical/en/agents-aiprovider.md) -- [aiprovider/README.md](/home/ray/dev/linkong/planet/aiprovider/README.md) -- [docs/technical/frontend-layout-guidelines.md](/home/ray/dev/linkong/planet/docs/technical/frontend-layout-guidelines.md) -- [docs/plans/frontend-ai-playground-development-plan.md](/home/ray/dev/linkong/planet/docs/plans/frontend-ai-playground-development-plan.md) -- [docs/plans/agents-situational-awareness-foundation-plan.md](/home/ray/dev/linkong/planet/docs/plans/agents-situational-awareness-foundation-plan.md) -- [docs/plans/agents-earth-command-runtime-plan.md](/home/ray/dev/linkong/planet/docs/plans/agents-earth-command-runtime-plan.md) +- [docs/technical/zh/agents-aiprovider.md](docs/technical/zh/agents-aiprovider.md) +- [docs/technical/en/agents-aiprovider.md](docs/technical/en/agents-aiprovider.md) +- [aiprovider/README.md](aiprovider/README.md) +- [docs/technical/zh/frontend-layout-guidelines.md](docs/technical/zh/frontend-layout-guidelines.md) +- [docs/plans/ai-advisor-workflow-and-location-agent-plan.md](docs/plans/ai-advisor-workflow-and-location-agent-plan.md) +- [docs/plans/earth-influence-zones-and-vfx-upgrade-plan.md](docs/plans/earth-influence-zones-and-vfx-upgrade-plan.md) +- [docs/plans/agents-situational-awareness-foundation-plan.md](docs/plans/agents-situational-awareness-foundation-plan.md) +- [docs/plans/agents-earth-command-runtime-plan.md](docs/plans/agents-earth-command-runtime-plan.md) ## 前端页面布局规范 @@ -458,8 +477,8 @@ AI_ANTHROPIC_VERSION=2023-06-01 当前推荐参考实现: -- [frontend/src/pages/BGP/BGP.tsx](/home/ray/dev/linkong/planet/frontend/src/pages/BGP/BGP.tsx) -- [docs/technical/frontend-layout-guidelines.md](/home/ray/dev/linkong/planet/docs/technical/frontend-layout-guidelines.md) +- [frontend/src/admin/pages/AdvisorWorkflows.tsx](frontend/src/admin/pages/AdvisorWorkflows.tsx) +- [docs/technical/zh/frontend-layout-guidelines.md](docs/technical/zh/frontend-layout-guidelines.md) ## License diff --git a/VERSION b/VERSION index 9a55e280..92fc430a 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.81.0 +0.82.0 diff --git a/aiprovider/provider_service.py b/aiprovider/provider_service.py index 2ecd3e35..86a54f04 100644 --- a/aiprovider/provider_service.py +++ b/aiprovider/provider_service.py @@ -124,6 +124,7 @@ class ProviderService: tool_choice = getattr(payload, "tool_choice", None) response_format = getattr(payload, "response_format", None) native_web_search = bool(getattr(payload, "native_web_search", False)) + images = self._normalize_images(getattr(payload, "images", None)) tool_calls: list[ToolCallRecord] = [] stop_reason: str | None = None @@ -136,6 +137,7 @@ class ProviderService: tools=tools, tool_choice=tool_choice, response_format=response_format, + images=images, ) content = self._extract_openai_content(data) content_blocks = self._extract_openai_blocks(data) @@ -153,6 +155,7 @@ class ProviderService: tool_choice=tool_choice, response_format=response_format, native_web_search=native_web_search, + images=images, ) content_blocks = self._extract_responses_blocks(data) content = "".join(block.text for block in content_blocks if block.text) @@ -169,6 +172,7 @@ class ProviderService: tool_choice=tool_choice, response_format=response_format, native_web_search=native_web_search, + images=images, ) content = self._extract_anthropic_content(data) content_blocks = self._extract_anthropic_blocks(data) @@ -181,6 +185,7 @@ class ProviderService: payload.system_prompt, conversation_messages=conversation_messages, response_format=response_format, + images=images, ) content = self._extract_ollama_content(data) content_blocks = self._extract_ollama_blocks(data) @@ -230,6 +235,7 @@ class ProviderService: self.session_id = str(uuid5(NAMESPACE_URL, f"planet:{payload.context['session_id']}")) provider_api = self._resolve_model_provider_api(model) + images = self._normalize_images(getattr(payload, "images", None)) yield {"event": "start", "provider": self.provider, "model": model} if provider_api == "anthropic-messages": @@ -239,24 +245,37 @@ class ProviderService: payload.thinking, payload.system_prompt, conversation_messages=conversation_messages, + images=images, ): yield item return if provider_api == "openai-completions": async for item in self._stream_openai_compatible( - model, prompt, payload.system_prompt, conversation_messages=conversation_messages + model, + prompt, + payload.system_prompt, + conversation_messages=conversation_messages, + images=images, ): yield item return if provider_api == "openai-responses": async for item in self._stream_openai_responses( - model, prompt, payload.system_prompt, conversation_messages=conversation_messages + model, + prompt, + payload.system_prompt, + conversation_messages=conversation_messages, + images=images, ): yield item return if provider_api == "ollama-generate": async for item in self._stream_ollama( - model, prompt, payload.system_prompt, conversation_messages=conversation_messages + model, + prompt, + payload.system_prompt, + conversation_messages=conversation_messages, + images=images, ): yield item return @@ -308,6 +327,7 @@ class ProviderService: tool_choice: str | dict[str, Any] | None = None, response_format: dict[str, Any] | None = None, native_web_search: bool = False, + images: list[dict[str, str]] | None = None, ) -> tuple[str, dict[str, str], dict[str, Any]]: anthropic_messages: list[dict[str, Any]] = [] source_messages = ( @@ -357,6 +377,8 @@ class ProviderService: {"role": role or "user", "content": [{"type": "text", "text": str(msg.get("content") or "")}]} ) + self._apply_images_to_messages(anthropic_messages, images or [], "anthropic") + resolved_thinking, resolved_output_config = self._resolve_anthropic_thinking(thinking, model) thinking_active = bool( resolved_thinking @@ -438,7 +460,8 @@ class ProviderService: thinking: dict[str, Any] | None = None, system_prompt: str | None = None, *, - conversation_messages: list[dict[str, str]] | None = None, + conversation_messages: list[dict[str, Any]] | None = None, + images: list[dict[str, str]] | None = None, ) -> AsyncIterator[dict[str, Any]]: path, headers, request_body = self._build_anthropic_request( model, @@ -447,6 +470,7 @@ class ProviderService: system_prompt, stream=True, conversation_messages=conversation_messages, + images=images, ) resolved_model = model usage: dict[str, Any] = {} @@ -509,16 +533,18 @@ class ProviderService: prompt: str, system_prompt: str | None = None, *, - conversation_messages: list[dict[str, str]] | None = None, + conversation_messages: list[dict[str, Any]] | None = None, + images: list[dict[str, str]] | None = None, ) -> AsyncIterator[dict[str, Any]]: - messages = [] + messages: list[dict[str, Any]] = [] resolved_system_prompt = self._resolve_system_prompt(system_prompt) if resolved_system_prompt: messages.append({"role": "system", "content": resolved_system_prompt}) if conversation_messages and len(conversation_messages) > 1: - messages.extend(conversation_messages) + messages.extend(dict(m) for m in conversation_messages) else: messages.append({"role": "user", "content": prompt}) + self._apply_images_to_messages(messages, images or [], "openai-completions") request_body = { "model": model, "messages": messages, @@ -577,13 +603,15 @@ class ProviderService: prompt: str, system_prompt: str | None = None, *, - conversation_messages: list[dict[str, str]] | None = None, + conversation_messages: list[dict[str, Any]] | None = None, + images: list[dict[str, str]] | None = None, ) -> AsyncIterator[dict[str, Any]]: responses_input: Any = ( [{"role": m["role"], "content": m["content"]} for m in conversation_messages] if (conversation_messages and len(conversation_messages) > 1) else prompt ) + responses_input = self._apply_images_to_responses_input(responses_input, images or []) request_body: dict[str, Any] = { "model": model, "input": responses_input, @@ -639,7 +667,8 @@ class ProviderService: prompt: str, system_prompt: str | None = None, *, - conversation_messages: list[dict[str, str]] | None = None, + conversation_messages: list[dict[str, Any]] | None = None, + images: list[dict[str, str]] | None = None, ) -> AsyncIterator[dict[str, Any]]: ollama_prompt = self._format_ollama_prompt(prompt, conversation_messages) request_body: dict[str, Any] = { @@ -648,6 +677,8 @@ class ProviderService: "prompt": ollama_prompt, "options": {"temperature": 0.2, "num_predict": self.max_tokens}, } + if images: + request_body["images"] = [img["data_base64"] for img in images if img.get("data_base64")] resolved_system_prompt = self._resolve_system_prompt(system_prompt) if resolved_system_prompt: request_body["system"] = resolved_system_prompt @@ -796,6 +827,100 @@ class ProviderService: sections.append(f"附加上下文:\n{context_json}") return "\n\n".join(sections) + @staticmethod + def _normalize_images(images: list[Any] | None) -> list[dict[str, str]]: + normalized: list[dict[str, str]] = [] + for raw in images or []: + if isinstance(raw, dict): + mime = str(raw.get("mime_type") or "").strip().lower() + data = str(raw.get("data_base64") or "").strip() + name = str(raw.get("name") or "").strip() + else: + mime = str(getattr(raw, "mime_type", "") or "").strip().lower() + data = str(getattr(raw, "data_base64", "") or "").strip() + name = str(getattr(raw, "name", "") or "").strip() + if mime == "image/jpg": + mime = "image/jpeg" + if not mime.startswith("image/") or not data: + continue + normalized.append({"mime_type": mime, "data_base64": data, "name": name}) + if len(normalized) >= 8: + break + return normalized + + @staticmethod + def _apply_images_to_messages( + messages: list[dict[str, Any]], + images: list[dict[str, str]], + api_style: str, + ) -> None: + """Attach base64 images onto the final user turn for Anthropic or OpenAI chat payloads.""" + if not images or not messages: + return + for idx in range(len(messages) - 1, -1, -1): + if messages[idx].get("role") != "user": + continue + if api_style == "anthropic": + content = messages[idx].get("content") + blocks = list(content) if isinstance(content, list) else [{"type": "text", "text": str(content or "")}] + for img in images: + blocks.append( + { + "type": "image", + "source": { + "type": "base64", + "media_type": img["mime_type"], + "data": img["data_base64"], + }, + } + ) + messages[idx]["content"] = blocks + else: + text = str(messages[idx].get("content") or "") + blocks = [{"type": "text", "text": text}] + for img in images: + blocks.append( + { + "type": "image_url", + "image_url": {"url": f"data:{img['mime_type']};base64,{img['data_base64']}"}, + } + ) + messages[idx]["content"] = blocks + break + + @staticmethod + def _apply_images_to_responses_input( + responses_input: Any, + images: list[dict[str, str]], + ) -> Any: + """Attach base64 images onto OpenAI Responses API input items.""" + if not images: + return responses_input + image_blocks = [ + { + "type": "input_image", + "image_url": f"data:{img['mime_type']};base64,{img['data_base64']}", + } + for img in images + ] + if isinstance(responses_input, str): + return [ + { + "role": "user", + "content": [{"type": "input_text", "text": responses_input}, *image_blocks], + } + ] + if isinstance(responses_input, list): + items = [dict(item) if isinstance(item, dict) else item for item in responses_input] + for idx in range(len(items) - 1, -1, -1): + item = items[idx] + if isinstance(item, dict) and item.get("role") == "user": + text = str(item.get("content") or "") + item["content"] = [{"type": "input_text", "text": text}, *image_blocks] + break + return items + return responses_input + def _resolve_system_prompt(self, system_prompt: str | None) -> str | None: resolved = str(system_prompt or "").strip() return resolved or None @@ -810,6 +935,7 @@ class ProviderService: tools: list[dict[str, Any]] | None = None, tool_choice: str | dict[str, Any] | None = None, response_format: dict[str, Any] | None = None, + images: list[dict[str, str]] | None = None, ) -> dict[str, Any]: messages: list[dict[str, Any]] = [] resolved_system_prompt = self._resolve_system_prompt(system_prompt) @@ -857,6 +983,8 @@ class ProviderService: else: messages.append({"role": role, "content": str(msg.get("content") or "")}) + self._apply_images_to_messages(messages, images or [], "openai-completions") + request_body: dict[str, Any] = { "model": model, "messages": messages, @@ -912,6 +1040,7 @@ class ProviderService: tool_choice: str | dict[str, Any] | None = None, response_format: dict[str, Any] | None = None, native_web_search: bool = False, + images: list[dict[str, str]] | None = None, ) -> dict[str, Any]: has_multi_or_tools = bool( conversation_messages @@ -955,6 +1084,8 @@ class ProviderService: else: responses_input = prompt + responses_input = self._apply_images_to_responses_input(responses_input, images or []) + request_body: dict[str, Any] = { "model": model, "input": responses_input, @@ -1040,6 +1171,7 @@ class ProviderService: tool_choice: str | dict[str, Any] | None = None, response_format: dict[str, Any] | None = None, native_web_search: bool = False, + images: list[dict[str, str]] | None = None, ) -> dict[str, Any]: path, headers, request_body = self._build_anthropic_request( model, @@ -1052,6 +1184,7 @@ class ProviderService: tool_choice=tool_choice, response_format=response_format, native_web_search=native_web_search, + images=images, ) return await self._post( path=path, @@ -1106,6 +1239,7 @@ class ProviderService: *, conversation_messages: list[dict[str, Any]] | None = None, response_format: dict[str, Any] | None = None, + images: list[dict[str, str]] | None = None, ) -> dict[str, Any]: request_body: dict[str, Any] = { "model": model, @@ -1116,6 +1250,8 @@ class ProviderService: "num_predict": self.max_tokens, }, } + if images: + request_body["images"] = [img["data_base64"] for img in images if img.get("data_base64")] resolved_system_prompt = self._resolve_system_prompt(system_prompt) if resolved_system_prompt: request_body["system"] = resolved_system_prompt diff --git a/aiprovider/schemas.py b/aiprovider/schemas.py index 6b4dc7f0..d859c302 100644 --- a/aiprovider/schemas.py +++ b/aiprovider/schemas.py @@ -17,6 +17,12 @@ class ToolCallRecord(BaseModel): arguments: dict[str, Any] = Field(default_factory=dict) +class ImageAttachment(BaseModel): + mime_type: str = Field(..., pattern=r"^image/(png|jpeg|jpg|webp|gif)$") + data_base64: str = Field(..., min_length=8, max_length=6_000_000) + name: str = Field(default="", max_length=200) + + class AIContentBlock(BaseModel): type: str text: str | None = None @@ -39,6 +45,7 @@ class SituationalAnalysisRequest(BaseModel): tool_choice: str | dict[str, Any] | None = None response_format: dict[str, Any] | None = None native_web_search: bool = False + images: list[ImageAttachment] = Field(default_factory=list, max_length=8) class SituationalAnalysisResponse(BaseModel): diff --git a/backend/app/api/v1/ai_workflows.py b/backend/app/api/v1/ai_workflows.py index 860614ff..ab7b3450 100644 --- a/backend/app/api/v1/ai_workflows.py +++ b/backend/app/api/v1/ai_workflows.py @@ -4,7 +4,7 @@ from __future__ import annotations from datetime import UTC, datetime import json -from typing import Any +from typing import Any, Literal from uuid import uuid4 from fastapi import APIRouter, Depends, HTTPException, Query @@ -20,17 +20,42 @@ from app.db.session import get_db from app.models.ai_workflow import AIWorkflow, AIWorkflowFixture from app.models.situational_assessment import WorkflowRun from app.models.user import User -from app.schemas.ai import ChatMessage, SituationalAnalysisRequest +from app.schemas.ai import ChatMessage, ImageAttachment, SituationalAnalysisRequest +from app.services.ai.dag_executor import run_workflow_dag_stream from app.services.ai.thinking_sanitizer import strip_thinking_text +from app.services.ai.tool_registry import ( + SSRFBlockedError, + isolate_untrusted_external_text, + safe_web_fetch, +) +from app.services.ai.workflow_evolver import ( + compute_workflow_health, + dismiss_ledger_entry, + get_evolution_ledger, + get_evolution_policy, + incubate_workflow_from_runs, + propose_meta_evolution, + propose_workflow_evolution, + record_run_feedback, + run_fixture_ab_eval, + schedule_post_run_evolution, + update_evolution_policy, +) from app.services.ai.workflow_registry import ( + clone_workflow, + create_workflow, + delete_workflow, + discard_workflow_draft, ensure_builtin_workflows, generate_workflow_optimization_proposal, get_workflow_detail, + list_public_workflow_bindings, list_workflows, publish_workflow, resolve_runtime_workflow_node, rollback_workflow, save_workflow_draft, + update_workflow_metadata, ) from app.services.ai_client import get_ai_provider_client from app.services.alert_ai_brief import build_alert_brief_request @@ -49,13 +74,56 @@ logger = get_logger(__name__, service="ai_workflows") class WorkflowDraftUpdateRequest(BaseModel): graph: dict[str, Any] + bindings: dict[str, Any] | None = None + name: str | None = None + description: str | None = None class WorkflowPublishRequest(BaseModel): graph: dict[str, Any] | None = None + bindings: dict[str, Any] | None = None + name: str | None = None + description: str | None = None change_summary: str = "" +class WorkflowCreateRequest(BaseModel): + workflow_id: str | None = Field(default=None, max_length=80) + name: str = Field(..., min_length=1, max_length=160) + name_en: str = Field(default="", max_length=160) + category: str = Field(default="custom", max_length=60) + description: str = Field(default="", max_length=2000) + description_en: str = Field(default="", max_length=2000) + graph: dict[str, Any] | None = None + bindings: dict[str, Any] | None = None + + +class WorkflowCloneRequest(BaseModel): + workflow_id: str | None = Field(default=None, max_length=80) + name: str | None = Field(default=None, max_length=160) + name_en: str | None = Field(default=None, max_length=160) + + +class WorkflowMetadataUpdateRequest(BaseModel): + name: str | None = Field(default=None, max_length=160) + name_en: str | None = Field(default=None, max_length=160) + category: str | None = Field(default=None, max_length=60) + description: str | None = Field(default=None, max_length=2000) + description_en: str | None = Field(default=None, max_length=2000) + bindings: dict[str, Any] | None = None + + +class EarthTargetInput(BaseModel): + entity_type: str = Field(..., min_length=1, max_length=64) + entity_id: str | None = Field(default=None, max_length=160) + label: str = Field(default="", max_length=200) + latitude: float | None = None + longitude: float | None = None + layer: str | None = Field(default=None, max_length=80) + kind: str | None = Field(default=None, max_length=80) + properties: dict[str, Any] = Field(default_factory=dict) + + class WorkflowRollbackRequest(BaseModel): revision: int = Field(..., ge=1) @@ -65,6 +133,43 @@ class WorkflowOptimizeRequest(BaseModel): run_id: str | None = None +class WorkflowRunFeedbackRequest(BaseModel): + rating: Literal[-1, 0, 1] + note: str = Field(default="", max_length=500) + + +class EvolutionPolicyUpdateRequest(BaseModel): + business_mode: Literal["off", "draft", "auto"] | None = None + meta_mode: Literal["off", "draft", "auto"] | None = None + daily_auto_budget: int | None = Field(default=None, ge=1, le=20) + business_cooldown_hours: int | None = Field(default=None, ge=1, le=168) + meta_cooldown_days: int | None = Field(default=None, ge=1, le=30) + locked_workflows: list[str] | None = None + auto_adapt_on_model_change: bool | None = None + + +class EvolutionProposeRequest(BaseModel): + mode: Literal["optimize", "model_adapt"] = "optimize" + instruction: str = Field(default="", max_length=2000) + run_id: str | None = None + apply_mode: Literal["preview", "draft", "auto"] = "preview" + branch_from_best: bool = False + + +class EvolutionEvalRequest(BaseModel): + proposed_graph: dict[str, Any] + max_fixtures: int = Field(default=3, ge=1, le=5) + + +class MetaEvolveRequest(BaseModel): + instruction: str = Field(default="", max_length=2000) + apply_mode: Literal["preview", "draft", "auto"] = "preview" + + +class LedgerDismissRequest(BaseModel): + reason: str = Field(default="", max_length=300) + + class WorkflowFixtureCreateRequest(BaseModel): name: str = Field(..., min_length=1, max_length=160) description: str = "" @@ -78,12 +183,29 @@ class AdvisorChatMessageInput(BaseModel): content: str = Field(..., min_length=1, max_length=16000) +class PlaygroundLinkParseRequest(BaseModel): + url: str = Field(..., min_length=4, max_length=2000) + + +class PlaygroundAttachmentInput(BaseModel): + kind: Literal["image", "video", "link", "json", "text"] + name: str = Field(default="", max_length=240) + mime_type: str = Field(default="", max_length=120) + url: str | None = Field(default=None, max_length=2000) + text_content: str | None = Field(default=None, max_length=32000) + json_data: Any = None + images: list[ImageAttachment] = Field(default_factory=list, max_length=6) + metadata: dict[str, Any] = Field(default_factory=dict) + + class AdvisorPlaygroundChatRequest(BaseModel): workflow_id: str = "default.general" use_draft: bool = False - message: str = Field(..., min_length=1, max_length=16000) + message: str = Field(default="", max_length=16000) history: list[AdvisorChatMessageInput] = Field(default_factory=list) earth_context: dict[str, Any] | None = None + attachments: list[PlaygroundAttachmentInput] = Field(default_factory=list, max_length=8) + targets: list[EarthTargetInput] = Field(default_factory=list, max_length=8) model_override: str | None = None @@ -104,6 +226,81 @@ async def list_ai_workflows( return {"items": items, "total": len(items)} +@router.get("/workflows/bindings") +async def get_public_earth_workflow_bindings( + db: AsyncSession = Depends(get_db), +): + """Public-safe list of enabled published workflows and their Earth interaction bindings.""" + items = await list_public_workflow_bindings(db) + return {"items": items, "total": len(items)} + + +@router.post("/workflows") +async def create_ai_workflow( + payload: WorkflowCreateRequest, + admin: User = Depends(require_admin_user), + db: AsyncSession = Depends(get_db), +): + return await create_workflow( + db, + workflow_id=payload.workflow_id, + name=payload.name, + name_en=payload.name_en, + category=payload.category, + description=payload.description, + description_en=payload.description_en, + graph=payload.graph, + bindings=payload.bindings, + actor=_actor_label(admin), + ) + + +@router.post("/workflows/{workflow_id}/clone") +async def clone_ai_workflow( + workflow_id: str, + payload: WorkflowCloneRequest, + admin: User = Depends(require_admin_user), + db: AsyncSession = Depends(get_db), +): + return await clone_workflow( + db, + workflow_id, + workflow_id=payload.workflow_id, + name=payload.name, + name_en=payload.name_en, + actor=_actor_label(admin), + ) + + +@router.patch("/workflows/{workflow_id}") +async def patch_ai_workflow_metadata( + workflow_id: str, + payload: WorkflowMetadataUpdateRequest, + admin: User = Depends(require_admin_user), + db: AsyncSession = Depends(get_db), +): + return await update_workflow_metadata( + db, + workflow_id, + name=payload.name, + name_en=payload.name_en, + category=payload.category, + description=payload.description, + description_en=payload.description_en, + bindings=payload.bindings, + actor=_actor_label(admin), + ) + + +@router.delete("/workflows/{workflow_id}") +async def delete_ai_workflow( + workflow_id: str, + _admin: User = Depends(require_admin_user), + db: AsyncSession = Depends(get_db), +): + return await delete_workflow(db, workflow_id) + + @router.get("/workflows/{workflow_id}") async def get_ai_workflow_detail( workflow_id: str, @@ -124,6 +321,22 @@ async def update_ai_workflow_draft( db, workflow_id, payload.graph, + bindings=payload.bindings, + name=payload.name, + description=payload.description, + actor=_actor_label(admin), + ) + + +@router.delete("/workflows/{workflow_id}/draft") +async def discard_ai_workflow_draft( + workflow_id: str, + admin: User = Depends(require_admin_user), + db: AsyncSession = Depends(get_db), +): + return await discard_workflow_draft( + db, + workflow_id, actor=_actor_label(admin), ) @@ -139,6 +352,9 @@ async def publish_ai_workflow( db, workflow_id, graph=payload.graph, + bindings=payload.bindings, + name=payload.name, + description=payload.description, change_summary=payload.change_summary, actor=_actor_label(admin), ) @@ -243,17 +459,31 @@ async def delete_ai_workflow_fixture( async def list_ai_workflow_runs( workflow_id: str | None = None, status: str | None = None, + feedback: Literal["negative", "positive"] | None = None, limit: int = Query(50, ge=1, le=200), _admin: User = Depends(require_admin_user), db: AsyncSession = Depends(get_db), ): - stmt = select(WorkflowRun).order_by(desc(WorkflowRun.started_at)).limit(limit) + fetch_limit = min(400, limit * 3) if feedback else limit + stmt = select(WorkflowRun).order_by(desc(WorkflowRun.started_at)).limit(fetch_limit) if workflow_id: stmt = stmt.where(WorkflowRun.workflow_id == workflow_id) if status: stmt = stmt.where(WorkflowRun.status == status) rows = (await db.execute(stmt)).scalars().all() - items = [row.to_dict() for row in rows] + if feedback == "negative": + rows = [ + row + for row in rows + if row.status == "failed" or int((row.budget_used or {}).get("user_rating") or 0) == -1 + ] + elif feedback == "positive": + rows = [ + row + for row in rows + if int((row.budget_used or {}).get("user_rating") or 0) == 1 + ] + items = [row.to_dict() for row in rows[:limit]] return {"items": items, "total": len(items)} @@ -271,6 +501,153 @@ async def get_ai_workflow_run_detail( return row.to_dict() +@router.post("/runs/{run_id}/feedback") +async def submit_ai_workflow_run_feedback( + run_id: str, + payload: WorkflowRunFeedbackRequest, + admin: User = Depends(require_admin_user), + db: AsyncSession = Depends(get_db), +): + return await record_run_feedback( + db, + run_id, + rating=payload.rating, + note=payload.note, + actor=_actor_label(admin), + ) + + +@router.get("/evolution/policy") +async def get_ai_evolution_policy( + _admin: User = Depends(require_admin_user), + db: AsyncSession = Depends(get_db), +): + return await get_evolution_policy(db) + + +@router.put("/evolution/policy") +async def update_ai_evolution_policy( + payload: EvolutionPolicyUpdateRequest, + _admin: User = Depends(require_admin_user), + db: AsyncSession = Depends(get_db), +): + return await update_evolution_policy(db, payload.model_dump(exclude_none=True)) + + +@router.get("/evolution/ledger") +async def list_ai_evolution_ledger( + workflow_id: str | None = None, + limit: int = Query(30, ge=1, le=50), + _admin: User = Depends(require_admin_user), + db: AsyncSession = Depends(get_db), +): + items = await get_evolution_ledger(db, workflow_id=workflow_id, limit=limit) + return {"items": items, "total": len(items)} + + +@router.post("/evolution/ledger/{entry_id}/dismiss") +async def dismiss_ai_evolution_ledger_entry( + entry_id: str, + payload: LedgerDismissRequest | None = None, + _admin: User = Depends(require_admin_user), + db: AsyncSession = Depends(get_db), +): + return await dismiss_ledger_entry( + db, + entry_id, + reason=(payload.reason if payload else ""), + ) + + +@router.get("/evolution/health/{workflow_id}") +async def get_ai_workflow_evolution_health( + workflow_id: str, + _admin: User = Depends(require_admin_user), + db: AsyncSession = Depends(get_db), +): + ai_client = None + try: + ai_client = await get_ai_provider_client(db) + except Exception: + ai_client = None + return await compute_workflow_health(db, workflow_id, ai_client=ai_client) + + +@router.post("/evolution/propose/{workflow_id}") +async def propose_ai_workflow_evolution( + workflow_id: str, + payload: EvolutionProposeRequest, + admin: User = Depends(require_admin_user), + db: AsyncSession = Depends(get_db), +): + ai_client = None + try: + ai_client = await get_ai_provider_client(db) + except Exception: + ai_client = None + return await propose_workflow_evolution( + db, + workflow_id, + mode=payload.mode, + instruction=payload.instruction, + run_id=payload.run_id, + apply_mode=payload.apply_mode, + trigger="manual", + branch_from_best=payload.branch_from_best, + ai_client=ai_client, + actor=_actor_label(admin), + ) + + +@router.post("/evolution/eval/{workflow_id}") +async def evaluate_ai_workflow_fixtures( + workflow_id: str, + payload: EvolutionEvalRequest, + _admin: User = Depends(require_admin_user), + db: AsyncSession = Depends(get_db), +): + return await run_fixture_ab_eval( + db, + workflow_id, + payload.proposed_graph, + max_fixtures=payload.max_fixtures, + ) + + +@router.post("/evolution/incubate") +async def incubate_ai_workflow_candidate( + _admin: User = Depends(require_admin_user), + db: AsyncSession = Depends(get_db), +): + ai_client = None + try: + ai_client = await get_ai_provider_client(db) + except Exception: + ai_client = None + return await incubate_workflow_from_runs(db, ai_client=ai_client) + + +@router.post("/evolution/meta-evolve") +async def propose_ai_meta_evolution( + payload: MetaEvolveRequest, + admin: User = Depends(require_admin_user), + db: AsyncSession = Depends(get_db), +): + ai_client = None + try: + ai_client = await get_ai_provider_client(db) + except Exception: + ai_client = None + return await propose_meta_evolution( + db, + instruction=payload.instruction, + apply_mode=payload.apply_mode, + trigger="meta_manual", + ai_client=ai_client, + actor=_actor_label(admin), + ) + + async def _resolve_playground_slash_or_workflow( *, db: AsyncSession, @@ -286,7 +663,7 @@ async def _resolve_playground_slash_or_workflow( extra_meta: dict[str, Any] = {} if trimmed.startswith("/bgp-brief"): - active_wf = "ops.bgp_brief" + active_wf = "brief.bgp" req, facts, ctx = await build_bgp_brief_request(db) tool_trace.extend(["query_bgp_incidents", "query_bgp_anomalies", "synthesize"]) extra_meta["facts"] = facts @@ -294,7 +671,7 @@ async def _resolve_playground_slash_or_workflow( return active_wf, tool_trace, req, extra_meta if trimmed.startswith("/alerts-brief"): - active_wf = "ops.alerts_brief" + active_wf = "brief.alerts" req, facts, ctx = await build_alert_brief_request(db) tool_trace.extend(["query_system_alerts", "synthesize"]) extra_meta["facts"] = facts @@ -302,7 +679,7 @@ async def _resolve_playground_slash_or_workflow( return active_wf, tool_trace, req, extra_meta if trimmed.startswith("/situational-brief"): - active_wf = "ops.situational_alerts_brief" + active_wf = "brief.alerts" req, facts, ctx = await build_situational_alert_brief_request(db) tool_trace.extend(["query_system_alerts", "query_bgp_incidents", "synthesize"]) extra_meta["facts"] = facts @@ -348,6 +725,7 @@ async def _resolve_playground_slash_or_workflow( extra_meta["direct_reply"] = f"未能定位目标「{target_name}」:{res.failure_reason or '暂无可核验公开证据'}。" except Exception as exc: extra_meta["direct_reply"] = f"位置 Agent 调试执行失败:{exc}" + extra_meta["direct_reply_error"] = str(exc) return active_wf, tool_trace, None, extra_meta detail = await get_workflow_detail(db, active_wf) @@ -390,6 +768,78 @@ async def _resolve_playground_slash_or_workflow( return active_wf, tool_trace, req, extra_meta +def _normalize_playground_attachments( + attachments: list[PlaygroundAttachmentInput], +) -> tuple[list[dict[str, Any]], list[dict[str, str]]]: + """Extract prompt-safe attachment summaries and capped multimodal image blocks.""" + structured: list[dict[str, Any]] = [] + images: list[dict[str, str]] = [] + for item in attachments[:8]: + entry: dict[str, Any] = { + "kind": item.kind, + "name": item.name or item.url or item.kind, + } + if item.mime_type: + entry["mime_type"] = item.mime_type + if item.metadata: + entry["metadata"] = item.metadata + if item.kind == "link" and item.url: + entry["url"] = item.url + if item.text_content: + entry["fetched_content"] = isolate_untrusted_external_text( + item.url, + item.name or item.url, + item.text_content, + max_chars=4000, + ) + elif item.kind == "json" and item.json_data is not None: + raw_json = json.dumps(item.json_data, ensure_ascii=False, default=str) + entry["json_preview"] = raw_json[:8000] + elif item.kind in {"text", "json"} and item.text_content: + entry["text_preview"] = item.text_content[:8000] + + for img in item.images or []: + if len(images) >= 8: + break + images.append( + { + "mime_type": img.mime_type, + "data_base64": img.data_base64, + "name": img.name or item.name, + } + ) + if item.images: + entry["image_frames_attached"] = len(item.images) + structured.append(entry) + return structured, images + + +@router.post("/playground/parse-link") +async def parse_playground_link( + payload: PlaygroundLinkParseRequest, + _admin: User = Depends(require_admin_user), +): + """Fetch a public HTTP/HTTPS web page with SSRF validation and extract readable text.""" + try: + fetched = await safe_web_fetch(payload.url.strip(), timeout_seconds=10) + except SSRFBlockedError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + except Exception as exc: + raise HTTPException(status_code=502, detail=f"Failed to fetch URL: {exc}") from exc + + clean_text = (fetched.text or "")[:12000] + excerpt = clean_text[:320].strip() + return { + "url": fetched.url, + "final_url": fetched.final_url, + "title": fetched.title or fetched.final_url, + "text": clean_text, + "excerpt": excerpt, + "char_count": len(clean_text), + "content_hash": fetched.content_hash, + } + + @router.post("/playground/chat/stream") async def stream_advisor_playground_chat( payload: AdvisorPlaygroundChatRequest, @@ -397,6 +847,12 @@ async def stream_advisor_playground_chat( db: AsyncSession = Depends(get_db), ): """Stream AI Advisor Playground execution over SSE (`meta`, `node`, `reasoning`, `text`, `done`, `error`).""" + raw_msg = payload.message.strip() + if not raw_msg and not payload.attachments: + raise HTTPException(status_code=422, detail="Message or attachment is required") + effective_message = raw_msg or "请结合我上传的附件进行分析。" + attachment_summaries, attachment_images = _normalize_playground_attachments(payload.attachments) + run_id = f"run_{uuid4().hex[:16]}" started_at = datetime.now(UTC) @@ -405,74 +861,145 @@ async def stream_advisor_playground_chat( tool_trace: list[str] = [] status_value = "completed" error_text = "" + resolved_model = str(payload.model_override or "").strip() + resolved_provider = "" + workflow_revision = 1 + is_slash_cmd = effective_message.strip().startswith( + ("/bgp-brief", "/alerts-brief", "/situational-brief", "/locate") + ) try: - active_wf, tool_trace, req, extra_meta = await _resolve_playground_slash_or_workflow( - db=db, - workflow_id=active_wf, - message=payload.message, - use_draft=payload.use_draft, - earth_context=payload.earth_context, - ) - yield _sse_frame( - "meta", - { - "run_id": run_id, - "workflow_id": active_wf, - "use_draft": payload.use_draft, - "nodes": tool_trace, - **{k: v for k, v in extra_meta.items() if k != "direct_reply"}, - }, - ) - for node_id in tool_trace: - yield _sse_frame("node", {"node_id": node_id, "status": "completed"}) - - if "direct_reply" in extra_meta: - reply = str(extra_meta["direct_reply"]) - yield _sse_frame("text", {"delta": reply}) - yield _sse_frame("done", {"run_id": run_id, "workflow_id": active_wf, "nodes": tool_trace}) - return - - if req is not None: - if payload.model_override: - req.preferred_model = payload.model_override.strip() - if payload.history: - req.messages = [ - ChatMessage(role=m.role, content=m.content) # type: ignore[arg-type] - for m in payload.history[-12:] - ] - provider_client = await get_ai_provider_client(db) - ready, _, active_model = await provider_client.is_ready() - if not ready: - status_value = "failed" - error_text = "AI Provider 尚未配置可用密钥或服务地址,请前往「运维与配置 → AI 基础设施」检查。" - yield _sse_frame("error", {"message": error_text, "run_id": run_id}) - return - - full_text_parts: list[str] = [] - async for item in provider_client.stream_analyze(req, request_id=run_id): - ev = str(item.get("event") or "") - if ev == "reasoning" and item.get("delta"): - yield _sse_frame("reasoning", {"delta": str(item["delta"])}) - elif ev == "text" and item.get("delta"): - delta = str(item["delta"]) - full_text_parts.append(delta) - yield _sse_frame("text", {"delta": delta}) - elif ev == "error": - status_value = "failed" - error_text = str(item.get("message") or "Streaming error") - yield _sse_frame("error", {"message": error_text, "run_id": run_id}) - return - cleaned, _ = strip_thinking_text("".join(full_text_parts)) + if is_slash_cmd: + active_wf, tool_trace, req, extra_meta = await _resolve_playground_slash_or_workflow( + db=db, + workflow_id=active_wf, + message=effective_message, + use_draft=payload.use_draft, + earth_context=payload.earth_context, + ) yield _sse_frame( - "done", + "meta", { "run_id": run_id, "workflow_id": active_wf, - "model": payload.model_override or active_model, + "use_draft": payload.use_draft, "nodes": tool_trace, - "text_length": len(cleaned), + **{ + k: v + for k, v in extra_meta.items() + if k not in {"direct_reply", "direct_reply_error"} + }, }, ) + for node_id in tool_trace: + yield _sse_frame("node", {"node_id": node_id, "status": "completed"}) + + if "direct_reply" in extra_meta: + reply = str(extra_meta["direct_reply"]) + if extra_meta.get("direct_reply_error"): + status_value = "failed" + error_text = str(extra_meta["direct_reply_error"]) + yield _sse_frame("text", {"delta": reply}) + yield _sse_frame("done", {"run_id": run_id, "workflow_id": active_wf, "nodes": tool_trace}) + return + + if req is not None: + if attachment_summaries: + req.context = {**(req.context or {}), "attachments": attachment_summaries} + if attachment_images: + req.images = [ + ImageAttachment.model_validate(img) for img in attachment_images[:8] + ] + if payload.model_override: + req.preferred_model = payload.model_override.strip() + if payload.history: + req.messages = [ + ChatMessage(role=m.role, content=m.content) # type: ignore[arg-type] + for m in payload.history[-12:] + ] + provider_client = await get_ai_provider_client(db) + ready, active_provider, active_model = await provider_client.is_ready() + resolved_provider = resolved_provider or str(active_provider or "") + resolved_model = resolved_model or str(active_model or "") + if not ready: + status_value = "failed" + error_text = "AI Provider 尚未配置可用密钥或服务地址,请前往「运维与配置 → AI」检查。" + yield _sse_frame("error", {"message": error_text, "run_id": run_id}) + return + + full_text_parts: list[str] = [] + async for item in provider_client.stream_analyze(req, request_id=run_id): + ev = str(item.get("event") or "") + if ev == "reasoning" and item.get("delta"): + yield _sse_frame("reasoning", {"delta": str(item["delta"])}) + elif ev == "text" and item.get("delta"): + delta = str(item["delta"]) + full_text_parts.append(delta) + yield _sse_frame("text", {"delta": delta}) + elif ev == "error": + status_value = "failed" + error_text = str(item.get("message") or "Streaming error") + yield _sse_frame("error", {"message": error_text, "run_id": run_id}) + return + cleaned, _ = strip_thinking_text("".join(full_text_parts)) + yield _sse_frame( + "done", + { + "run_id": run_id, + "workflow_id": active_wf, + "model": payload.model_override or active_model, + "nodes": tool_trace, + "text_length": len(cleaned), + }, + ) + return + + detail = await get_workflow_detail(db, active_wf) + wf_obj = detail["workflow"] + workflow_revision = int(wf_obj.get("active_revision") or 1) + provider_client = None + try: + provider_client = await get_ai_provider_client(db) + except Exception: + provider_client = None + + targets_list = [t.model_dump() for t in payload.targets] + history_list = [{"role": m.role, "content": m.content} for m in payload.history[-12:]] + async for item in run_workflow_dag_stream( + db=db, + workflow=wf_obj, + question=effective_message, + use_draft=payload.use_draft, + targets=targets_list, + earth_context=payload.earth_context, + attachments=attachment_summaries, + images=attachment_images, + history=history_list, + ai_client=provider_client, + run_id=run_id, + model_override=payload.model_override, + allow_external_tools=True, + extra_meta={ + "earth_context_attached": bool(payload.earth_context), + "attachments_count": len(attachment_summaries), + }, + ): + ev_name = str(item.get("event") or "") + ev_data = dict(item.get("data") or {}) + if ev_name == "node" and ev_data.get("status") == "completed": + nid = str(ev_data.get("node_id") or "") + if nid and nid not in tool_trace: + tool_trace.append(nid) + elif ev_name == "done": + if isinstance(ev_data.get("nodes"), list): + tool_trace = [str(n) for n in ev_data["nodes"] if n] + if ev_data.get("model"): + resolved_model = str(ev_data["model"]) + if ev_data.get("provider"): + resolved_provider = str(ev_data["provider"]) + elif ev_name == "error": + status_value = "failed" + error_text = str(ev_data.get("message") or "Workflow execution failed") + yield _sse_frame(ev_name, ev_data) except Exception as exc: status_value = "failed" error_text = str(exc) @@ -484,6 +1011,8 @@ async def stream_advisor_playground_chat( yield _sse_frame("error", {"message": error_text, "run_id": run_id}) finally: try: + completed_at = datetime.now(UTC) + latency_ms = max(0, int((completed_at - started_at).total_seconds() * 1000)) db.add( WorkflowRun( id=run_id, @@ -491,20 +1020,30 @@ async def stream_advisor_playground_chat( status=status_value, access_tier="admin", actor_key=_actor_label(admin), - question=payload.message[:500], + question=effective_message[:500], input_params={ "use_draft": payload.use_draft, "model_override": payload.model_override, "has_earth_context": bool(payload.earth_context), + "attachments_count": len(attachment_summaries), + "targets_count": len(payload.targets), }, tool_trace=tool_trace, - budget_used={"steps": len(tool_trace)}, + budget_used={ + "steps": len(tool_trace), + "model_used": resolved_model, + "provider": resolved_provider, + "latency_ms": latency_ms, + "workflow_revision": workflow_revision, + }, error_message=error_text[:500], started_at=started_at, - completed_at=datetime.now(UTC), + completed_at=completed_at, ) ) await db.commit() + if not payload.use_draft: + schedule_post_run_evolution(active_wf, run_id) except Exception: try: await db.rollback() diff --git a/backend/app/api/v1/situational_awareness.py b/backend/app/api/v1/situational_awareness.py index eb25ad52..88f412be 100644 --- a/backend/app/api/v1/situational_awareness.py +++ b/backend/app/api/v1/situational_awareness.py @@ -89,10 +89,25 @@ class HistoryMessageItem(BaseModel): content: str = Field(min_length=1, max_length=6000) +class EarthTargetItem(BaseModel): + model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) + + entity_type: str = Field(min_length=1, max_length=64) + entity_id: str | None = Field(default=None, max_length=160) + label: str = Field(default="", max_length=200) + latitude: float | None = None + longitude: float | None = None + layer: str | None = Field(default=None, max_length=80) + kind: str | None = Field(default=None, max_length=80) + properties: dict[str, Any] = Field(default_factory=dict) + + class SessionTurnRequest(BaseModel): model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) question: str = Field(min_length=2, max_length=1000) + workflow_id: str | None = Field(default=None, max_length=80, pattern=r"^[A-Za-z0-9_.-]+$") + targets: list[EarthTargetItem] = Field(default_factory=list, max_length=8) domain: WorkbenchDomain | None = None selected_codes: list[str] | None = Field(default=None, max_length=12) mode: ComputeSeriesMode | None = None @@ -407,6 +422,8 @@ async def stream_investigation_session_turn( conversation_summary=payload.conversation_summary, memory_notes=payload.memory_notes, pinned_summaries=payload.pinned_summaries, + workflow_id=payload.workflow_id, + targets=[t.model_dump() for t in payload.targets], access=effective_access, ai_client=ai_client, client_run_id=payload.run_id, diff --git a/backend/app/db/migration_steps/0006_add_ai_workflow_bindings.py b/backend/app/db/migration_steps/0006_add_ai_workflow_bindings.py new file mode 100644 index 00000000..96fc993c --- /dev/null +++ b/backend/app/db/migration_steps/0006_add_ai_workflow_bindings.py @@ -0,0 +1,30 @@ +"""Add bindings JSON/JSONB column to ai_workflows for Earth interaction bindings.""" + +from __future__ import annotations + +from sqlalchemy import text + +VERSION = "0006" +NAME = "add_ai_workflow_bindings" + + +async def upgrade(conn) -> None: + """Add bindings column to ai_workflows idempotently across PostgreSQL and SQLite.""" + dialect = getattr(getattr(conn, "dialect", None), "name", "") + if dialect == "postgresql": + await conn.execute( + text( + """ + ALTER TABLE ai_workflows + ADD COLUMN IF NOT EXISTS bindings JSONB NOT NULL DEFAULT '{}'::jsonb + """ + ) + ) + return + + res = await conn.execute(text("PRAGMA table_info(ai_workflows)")) + columns = {str(row[1]) for row in res.fetchall()} + if columns and "bindings" not in columns: + await conn.execute( + text("ALTER TABLE ai_workflows ADD COLUMN bindings JSON NOT NULL DEFAULT '{}'") + ) diff --git a/backend/app/db/session.py b/backend/app/db/session.py index 71743996..7c6d22b4 100644 --- a/backend/app/db/session.py +++ b/backend/app/db/session.py @@ -911,6 +911,14 @@ async def _init_db_ddl_and_seed(): """ ) ) + await conn.execute( + text( + """ + ALTER TABLE ai_workflows + ADD COLUMN IF NOT EXISTS bindings JSONB NOT NULL DEFAULT '{}'::jsonb + """ + ) + ) await conn.execute( text( """ diff --git a/backend/app/models/ai_workflow.py b/backend/app/models/ai_workflow.py index f7fc9b51..df9790fd 100644 --- a/backend/app/models/ai_workflow.py +++ b/backend/app/models/ai_workflow.py @@ -25,7 +25,8 @@ class AIWorkflow(Base): is_builtin = Column(Boolean, nullable=False, default=True) active_revision = Column(Integer, nullable=False, default=1) published_graph = Column(JSON, nullable=False, default=dict) - draft_graph = Column(JSON, nullable=True) + draft_graph = Column(JSON(none_as_null=True), nullable=True) + bindings = Column(JSON, nullable=False, default=dict) updated_by = Column(String(120), nullable=True) created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False) updated_at = Column( @@ -50,6 +51,7 @@ class AIWorkflow(Base): "has_draft": self.draft_graph is not None, "published_graph": self.published_graph or {}, "draft_graph": self.draft_graph, + "bindings": self.bindings or {}, "updated_by": self.updated_by, "created_at": to_iso8601_utc(self.created_at), "updated_at": to_iso8601_utc(self.updated_at), diff --git a/backend/app/schemas/ai.py b/backend/app/schemas/ai.py index 26a1ec9c..6013480f 100644 --- a/backend/app/schemas/ai.py +++ b/backend/app/schemas/ai.py @@ -19,6 +19,12 @@ class ToolCallRecord(BaseModel): arguments: dict[str, Any] = Field(default_factory=dict) +class ImageAttachment(BaseModel): + mime_type: str = Field(..., pattern=r"^image/(png|jpeg|jpg|webp|gif)$") + data_base64: str = Field(..., min_length=8, max_length=6_000_000) + name: str = Field(default="", max_length=200) + + class AIContentBlock(BaseModel): type: str text: str | None = None @@ -41,6 +47,7 @@ class SituationalAnalysisRequest(BaseModel): tool_choice: str | dict[str, Any] | None = None response_format: dict[str, Any] | None = None native_web_search: bool = False + images: list[ImageAttachment] = Field(default_factory=list, max_length=8) class BGPBriefRequest(BaseModel): diff --git a/backend/app/services/ai/dag_executor.py b/backend/app/services/ai/dag_executor.py new file mode 100644 index 00000000..23bd3a01 --- /dev/null +++ b/backend/app/services/ai/dag_executor.py @@ -0,0 +1,823 @@ +"""Lightweight topological DAG workflow executor for AI Advisor and Earth Copilot.""" + +from __future__ import annotations + +import asyncio +from collections import defaultdict, deque +import json +import re +from typing import Any, AsyncIterator + +from app.core.logging import get_logger +from app.schemas.ai import ChatMessage, ImageAttachment, SituationalAnalysisRequest +from app.services.ai.thinking_sanitizer import strip_thinking_text +from app.services.ai.tool_registry import ( + TimeBasis, + isolate_untrusted_external_text, + query_bgp_incidents_tool, + query_cable_posture_tool, + query_compute_posture_tool, + query_global_situational_tool, + query_recent_earth_news_tool, + query_satellite_posture_tool, + query_vessel_posture_tool, + safe_web_fetch, +) +from app.services.ai.workflow_registry import MAX_WORKFLOW_NODES +from app.services.compute_center_locations import build_compute_center_location_query +from app.services.location.agent_resolver import run_l1_structured_facility_resolvers + +logger = get_logger(__name__, service="ai_dag_executor") + +_TEMPLATE_VAR_RE = re.compile(r"\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}") +_L1_KNOWLEDGE_TOOL_IDS = frozenset( + {"builds_upon_inherit", "wikidata_lookup", "peeringdb_fac_lookup", "ror_lookup"} +) + + +def summarize_targets(targets: list[dict[str, Any]] | None) -> str: + """Format selected Earth targets into a concise deterministic summary.""" + if not targets: + return "全球多域当前态势" + parts: list[str] = [] + for item in targets[:8]: + etype = str(item.get("entity_type") or item.get("type") or "entity").strip() + label = str(item.get("label") or item.get("name") or item.get("entity_id") or "").strip() + lat = item.get("latitude") + lon = item.get("longitude") + coord = "" + if isinstance(lat, (int, float)) and isinstance(lon, (int, float)): + coord = f"({lat:.2f}, {lon:.2f})" + token = f"{etype}「{label or etype}」{coord}" + parts.append(token) + return "; ".join(parts) + + +def render_workflow_template( + template: str, + *, + question: str = "", + targets: list[dict[str, Any]] | None = None, + node_outputs: dict[str, str] | None = None, +) -> str: + """Interpolate `{{...}}` placeholders safely without Python `.format` or eval.""" + raw = str(template or "") + if not raw or "{{" not in raw: + return raw + first = targets[0] if targets else {} + outputs = node_outputs or {} + targets_summary = summarize_targets(targets) + + def _lookup(key: str) -> str: + if key == "question": + return question + if key == "targets_summary": + return targets_summary + if key.startswith("target."): + sub = key[len("target.") :] + if sub == "label": + return str(first.get("label") or first.get("name") or "") + if sub == "type": + return str(first.get("entity_type") or first.get("type") or "") + if sub == "id": + return str(first.get("entity_id") or first.get("id") or "") + if sub == "lat": + val = first.get("latitude") + return f"{val:.4f}" if isinstance(val, (int, float)) else "" + if sub == "lon": + val = first.get("longitude") + return f"{val:.4f}" if isinstance(val, (int, float)) else "" + if sub in {"kind", "layer"}: + return str(first.get(sub) or "") + return "" + if key.startswith("node."): + nid = key[len("node.") :] + return str(outputs.get(nid) or "")[:4000] + if key.endswith(".output"): + nid = key[: -len(".output")] + return str(outputs.get(nid) or "")[:4000] + return "" + + return _TEMPLATE_VAR_RE.sub(lambda m: _lookup(m.group(1)), raw) + + +def _extract_target_ids_and_codes( + targets: list[dict[str, Any]], + earth_context: dict[str, Any], +) -> tuple[str | None, list[str], str]: + first = targets[0] if targets else {} + primary_id = str( + first.get("entity_id") + or first.get("id") + or earth_context.get("entity_id") + or "" + ).strip() or None + codes = earth_context.get("selected_codes") + if not isinstance(codes, list) or not codes: + codes = ["CN", "US"] + else: + codes = [str(c).strip().upper() for c in codes if str(c).strip()][:12] or ["CN", "US"] + mode = str(earth_context.get("mode") or "global_share") + return primary_id, codes, mode + + +async def _execute_tool( + db: Any, + tool_id: str, + *, + question: str, + targets: list[dict[str, Any]], + earth_context: dict[str, Any], + allow_external_tools: bool, +) -> dict[str, Any]: + """Execute one whitelisted read-only or controlled external tool cleanly.""" + primary_id, codes, mode = _extract_target_ids_and_codes(targets, earth_context) + time_basis: TimeBasis = str(earth_context.get("time_basis") or "retrospective") # type: ignore[assignment] + if time_basis not in {"live", "as_known_then", "retrospective"}: + time_basis = "retrospective" + cutoff_at = earth_context.get("cutoff_at") + visible_layers = earth_context.get("visible_layers") + visible_layers_dict = visible_layers if isinstance(visible_layers, dict) else None + + if tool_id == "query_global_situational": + return await query_global_situational_tool( + db, + selected_codes=codes, + visible_layers=visible_layers_dict, + time_basis=time_basis, + cutoff_at=cutoff_at, + ) + if tool_id == "query_compute_posture": + return await query_compute_posture_tool( + db, + countries=codes, + mode=mode, + time_basis=time_basis, + cutoff_at=cutoff_at, + ) + if tool_id == "query_bgp_incidents": + incidents = await query_bgp_incidents_tool( + db, + incident_key=primary_id if any(t.get("entity_type") == "bgp" for t in targets) else None, + limit=8, + time_basis=time_basis, + cutoff_at=cutoff_at, + ) + return {"items": incidents, "count": len(incidents)} + if tool_id == "query_cable_posture": + return await query_cable_posture_tool( + db, + time_basis=time_basis, + cutoff_at=cutoff_at, + entity_id=primary_id if any(t.get("entity_type") in {"cable", "landing_point"} for t in targets) else None, + ) + if tool_id == "query_satellite_posture": + return await query_satellite_posture_tool( + db, + time_basis=time_basis, + cutoff_at=cutoff_at, + entity_id=primary_id if any(t.get("entity_type") == "satellite" for t in targets) else None, + ) + if tool_id == "query_vessel_posture": + return await query_vessel_posture_tool( + db, + time_basis=time_basis, + cutoff_at=cutoff_at, + entity_id=primary_id if any(t.get("entity_type") == "vessel" for t in targets) else None, + ) + if tool_id == "query_recent_earth_news": + news_ctx = earth_context.get("news_context") if isinstance(earth_context.get("news_context"), dict) else {} + region = str(news_ctx.get("region_key") or "").strip() or None + return await query_recent_earth_news_tool(db, region=region, limit=10) + if tool_id in _L1_KNOWLEDGE_TOOL_IDS: + target_name = str( + (targets[0].get("label") if targets else "") + or question + or "Unknown Facility" + ).strip() + query = build_compute_center_location_query(name=target_name) + candidates, resolver_log, _ = await run_l1_structured_facility_resolvers(query, db=db) + return { + "candidates": [ + { + "display_name": c.display_name, + "country": c.country, + "latitude": c.latitude, + "longitude": c.longitude, + "precision": c.precision, + "confidence": c.confidence, + "source": c.source, + "source_note": c.source_note, + } + for c in candidates[:5] + ], + "resolver_log": resolver_log, + } + if tool_id == "web_search": + if not allow_external_tools: + return {"skipped": "external_web_search_admin_only"} + from app.api.v1.settings import get_web_search_client + + client = await get_web_search_client(db) + search_q = " ".join( + part for part in [summarize_targets(targets) if targets else "", question] if part + ).strip()[:200] + if not search_q: + return {"items": []} + hits = await client.search(search_q, max_results=5) + return { + "items": [ + { + "title": h.title, + "url": h.url, + "snippet": h.compact_text(400), + "source_provider": h.source_provider, + } + for h in hits + ] + } + if tool_id in {"safe_web_fetch", "fetch_source_url"}: + if not allow_external_tools: + return {"skipped": "external_fetch_admin_only"} + news_ctx = earth_context.get("news_context") if isinstance(earth_context.get("news_context"), dict) else {} + target_props = targets[0].get("properties") if targets and isinstance(targets[0].get("properties"), dict) else {} + url = str(news_ctx.get("url") or target_props.get("url") or "").strip() + if not url: + return {"skipped": "no_target_url"} + fetched = await safe_web_fetch(url) + return isolate_untrusted_external_text(fetched.final_url or fetched.url, fetched.title, fetched.text) + return {"skipped": f"unsupported_tool:{tool_id}"} + + +def _has_meaningful_tool_data(tool_results: dict[str, Any]) -> bool: + for val in tool_results.values(): + if not isinstance(val, dict): + continue + if val.get("skipped") or val.get("error"): + continue + for key in ("items", "candidates", "cables", "landing_points", "series", "satellites", "vessels"): + seq = val.get(key) + if isinstance(seq, list) and len(seq) > 0: + return True + if val.get("excerpt") or val.get("summary"): + return True + return False + + +def _topological_sort_nodes( + nodes: list[dict[str, Any]], + edges: list[dict[str, Any]], +) -> tuple[list[dict[str, Any]], dict[str, list[dict[str, Any]]], dict[str, list[str]]]: + enabled_nodes = [n for n in nodes if isinstance(n, dict) and n.get("enabled", True)][:MAX_WORKFLOW_NODES] + node_map = {str(n["id"]): n for n in enabled_nodes if n.get("id")} + adj: dict[str, list[str]] = {nid: [] for nid in node_map} + incoming: dict[str, list[dict[str, Any]]] = defaultdict(list) + indeg: dict[str, int] = {nid: 0 for nid in node_map} + + for edge in edges: + if not isinstance(edge, dict): + continue + src = str(edge.get("source") or "") + tgt = str(edge.get("target") or "") + if src in node_map and tgt in node_map and src != tgt: + adj[src].append(tgt) + incoming[tgt].append(edge) + indeg[tgt] += 1 + + queue = deque(nid for nid, d in indeg.items() if d == 0) + ordered: list[dict[str, Any]] = [] + while queue: + nid = queue.popleft() + ordered.append(node_map[nid]) + for nxt in adj[nid]: + indeg[nxt] -= 1 + if indeg[nxt] == 0: + queue.append(nxt) + + # Fallback: preserve enabled order if partial edge misalignment occurs. + seen = {str(n["id"]) for n in ordered} + for n in enabled_nodes: + if str(n["id"]) not in seen: + ordered.append(n) + return ordered, incoming, adj + + +def _has_downstream_llm( + start_id: str, + adj: dict[str, list[str]], + node_types: dict[str, str], +) -> bool: + visited: set[str] = set() + stack = list(adj.get(start_id) or []) + while stack: + cur = stack.pop() + if cur in visited: + continue + visited.add(cur) + if node_types.get(cur) in {"llm_agent", "tool_agent"}: + return True + stack.extend(adj.get(cur) or []) + return False + + +def _eval_edge_condition( + edge: dict[str, Any], + pred_state: dict[str, Any], + targets: list[dict[str, Any]], +) -> bool: + cond = str(edge.get("condition") or "always").strip() + if cond in {"always", "", "interactive", "ingest", "not_terminal", "high_confidence_hit", "fallback_to_agent"}: + return True + if cond == "on_empty_or_low_confidence": + return bool(pred_state.get("is_empty")) or float(pred_state.get("confidence", 1.0)) < 0.6 + if cond == "on_entity_type": + raw_val = str(edge.get("condition_value") or "").strip() + if not raw_val: + return False + wanted = {item.strip().lower() for item in raw_val.split(",") if item.strip()} + target_types = {str(t.get("entity_type") or t.get("type") or "").strip().lower() for t in targets} + return bool(wanted & target_types) + return True + + +def _build_deterministic_fallback_markdown( + *, + workflow_name: str, + question: str, + targets: list[dict[str, Any]], + tool_results: dict[str, Any], + ai_configured: bool, +) -> str: + lines = [f"### {workflow_name}", ""] + if targets: + lines.append(f"- **聚焦目标**:{summarize_targets(targets)}") + if question: + lines.append(f"- **分析问题**:{question}") + if tool_results: + lines.append("- **已加载遥测工具**:" + "、".join(f"`{k}`" for k in tool_results.keys())) + lines.append("") + if not ai_configured: + lines.append("> 当前系统尚未配置可用 AI Provider,以上为确定性规则与遥测快照摘要;配置模型后可启用深度推理节点。") + elif tool_results: + preview = json.dumps(tool_results, ensure_ascii=False, default=str)[:1200] + lines.append(f"```json\n{preview}\n```") + return "\n".join(lines).strip() + + +async def run_workflow_dag_stream( + *, + db: Any, + workflow: dict[str, Any], + question: str, + use_draft: bool = False, + targets: list[dict[str, Any]] | None = None, + earth_context: dict[str, Any] | None = None, + attachments: list[dict[str, Any]] | None = None, + images: list[dict[str, Any]] | None = None, + history: list[dict[str, Any]] | None = None, + ai_client: Any = None, + request: Any = None, + run_id: str = "", + model_override: str | None = None, + allow_external_tools: bool = False, + extra_meta: dict[str, Any] | None = None, +) -> AsyncIterator[dict[str, Any]]: + """Execute a workflow DAG topologically and emit structured SSE-ready events.""" + wf_id = str(workflow.get("workflow_id") or "default.general") + wf_name = str(workflow.get("name") or wf_id) + active_rev = int(workflow.get("active_revision") or 1) + bindings = workflow.get("bindings") if isinstance(workflow.get("bindings"), dict) else {} + graph = ( + workflow.get("draft_graph") + if use_draft and isinstance(workflow.get("draft_graph"), dict) + else workflow.get("published_graph") + ) or {} + raw_nodes = list(graph.get("nodes") or []) + raw_edges = list(graph.get("edges") or []) + ordered_nodes, incoming_map, adj = _topological_sort_nodes(raw_nodes, raw_edges) + node_types = {str(n["id"]): str(n.get("node_type") or "llm_agent") for n in ordered_nodes} + + clean_targets = [t for t in (targets or []) if isinstance(t, dict)][:8] + clean_earth_ctx = dict(earth_context or {}) + planned_ids = [str(n["id"]) for n in ordered_nodes] + + yield { + "event": "meta", + "data": { + "run_id": run_id, + "workflow_id": wf_id, + "workflow_name": wf_name, + "active_revision": active_rev, + "use_draft": use_draft, + "targets_count": len(clean_targets), + "planned_nodes": planned_ids, + "nodes": planned_ids, + **(extra_meta or {}), + }, + } + + ai_ready = False + provider_name = "" + default_model = "" + if ai_client is not None and hasattr(ai_client, "is_ready"): + try: + ai_ready, provider_name, default_model = await ai_client.is_ready() + except Exception: + ai_ready = False + + node_states: dict[str, dict[str, Any]] = {} + node_outputs: dict[str, str] = {} + tool_results: dict[str, Any] = {} + evidence: dict[str, Any] = {} + executed_trace: list[str] = [] + effective_question = question.strip() + final_answer_md = "" + final_reasoning_md = "" + generation_mode = "deterministic_baseline" + zero_token = True + resolved_provider: str | None = None + resolved_model: str | None = None + scene_spec: dict[str, Any] | None = None + last_llm_output: str = "" + + for node in ordered_nodes: + nid = str(node["id"]) + ntype = str(node.get("node_type") or "llm_agent") + ntitle = str(node.get("title") or nid) + + inc_edges = incoming_map.get(nid) or [] + if inc_edges: + passed = False + for edge in inc_edges: + pred_id = str(edge.get("source") or "") + pred_state = node_states.get(pred_id) + if not pred_state or pred_state.get("skipped"): + continue + if _eval_edge_condition(edge, pred_state, clean_targets): + passed = True + break + if not passed: + node_states[nid] = {"skipped": True, "confidence": 1.0, "is_empty": False} + yield { + "event": "node", + "data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "skipped"}, + } + continue + + yield { + "event": "node", + "data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "running"}, + } + + if ntype in {"trigger", "input"}: + tmpl = str(bindings.get("prompt_template") or node.get("prompt") or "").strip() + if not effective_question and tmpl: + effective_question = render_workflow_template( + tmpl, + question=effective_question, + targets=clean_targets, + node_outputs=node_outputs, + ).strip() + summary = summarize_targets(clean_targets) + node_outputs[nid] = summary + node_states[nid] = {"skipped": False, "confidence": 1.0, "is_empty": False} + executed_trace.append(nid) + yield { + "event": "node", + "data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"}, + } + continue + + if ntype == "deterministic": + local_results: dict[str, Any] = {} + l1_ran = False + for tid in node.get("tools") or []: + if tid in _L1_KNOWLEDGE_TOOL_IDS: + if l1_ran: + continue + l1_ran = True + result_key = "l1_facility_lookup" + else: + result_key = tid + try: + res = await _execute_tool( + db, + tid, + question=effective_question or question, + targets=clean_targets, + earth_context=clean_earth_ctx, + allow_external_tools=allow_external_tools, + ) + local_results[result_key] = res + tool_results[result_key] = res + if isinstance(res, dict) and isinstance(res.get("evidence"), dict): + evidence.update(res["evidence"]) + executed_trace.append(f"{nid}:{tid}") + except Exception as exc: + logger.warning_event( + "Deterministic DAG tool failed", + event="ai_dag.tool.failed", + context={"workflow_id": wf_id, "node_id": nid, "tool_id": tid, "error": str(exc)}, + ) + local_results[result_key] = {"error": str(exc)} + has_data = _has_meaningful_tool_data(local_results) + node_outputs[nid] = json.dumps(local_results, ensure_ascii=False, default=str)[:4000] + node_states[nid] = { + "skipped": False, + "confidence": 0.9 if has_data else 0.4, + "is_empty": not has_data, + } + if nid not in executed_trace: + executed_trace.append(nid) + yield { + "event": "node", + "data": { + "node_id": nid, + "title": ntitle, + "node_type": ntype, + "status": "completed", + "tools_count": len(local_results), + }, + } + continue + + if ntype in {"llm_agent", "tool_agent"}: + has_next_llm = _has_downstream_llm(nid, adj, node_types) + sys_prompt = render_workflow_template( + str(node.get("system_prompt") or "").strip() + or "你是智能星球(Planet)AI 参谋。结合当前地球上下文、选中交互物件与工具证据,给出严谨客观的中文分析。", + question=effective_question or question, + targets=clean_targets, + node_outputs=node_outputs, + ) + node_prompt = render_workflow_template( + str(node.get("prompt") or "").strip(), + question=effective_question or question, + targets=clean_targets, + node_outputs=node_outputs, + ) + objective = ( + f"{node_prompt}\n\n用户请求:{effective_question or question}" + if node_prompt + else (effective_question or question) + ).strip() + + # Execute any extra read-only tools configured directly on the LLM node before inference. + node_tool_results: dict[str, Any] = {} + for tid in node.get("tools") or []: + if tid in tool_results or tid in _L1_KNOWLEDGE_TOOL_IDS: + continue + try: + res = await _execute_tool( + db, + tid, + question=effective_question or question, + targets=clean_targets, + earth_context=clean_earth_ctx, + allow_external_tools=allow_external_tools, + ) + node_tool_results[tid] = res + tool_results[tid] = res + if isinstance(res, dict) and isinstance(res.get("evidence"), dict): + evidence.update(res["evidence"]) + except Exception as exc: + node_tool_results[tid] = {"error": str(exc)} + + ctx_payload: dict[str, Any] = { + "targets": clean_targets, + "targets_summary": summarize_targets(clean_targets), + "tool_results": tool_results, + "upstream_outputs": {k: v[:2000] for k, v in node_outputs.items()}, + "evidence": evidence, + } + if clean_earth_ctx: + ctx_payload["earth_context"] = clean_earth_ctx + if attachments: + ctx_payload["attachments"] = attachments[:8] + + parsed_images: list[ImageAttachment] = [] + if not has_next_llm and images: + for raw_img in images[:8]: + try: + parsed_images.append(ImageAttachment.model_validate(raw_img)) + except Exception: + continue + + chat_msgs = [ + ChatMessage(role=str(m["role"]), content=str(m["content"])) # type: ignore[arg-type] + for m in (history or [])[-12:] + if isinstance(m, dict) and m.get("role") in {"user", "assistant"} and m.get("content") + ] + + preferred_model = ( + str(model_override or "").strip() + or str(node.get("model_override") or "").strip() + or None + ) + req = SituationalAnalysisRequest( + title=f"Planet AI Advisor · {wf_name}", + objective=objective[:24000], + system_prompt=sys_prompt[:8000], + context=ctx_payload, + preferred_model=preferred_model, + thinking={"mode": "auto"} if bool(node.get("thinking_enabled", True)) else {"mode": "off"}, + native_web_search=bool(node.get("native_web_search", False)) and allow_external_tools, + messages=[] if has_next_llm else chat_msgs, + images=parsed_images, + ) + + if not ai_ready or ai_client is None: + fallback_md = _build_deterministic_fallback_markdown( + workflow_name=wf_name, + question=effective_question or question, + targets=clean_targets, + tool_results=tool_results, + ai_configured=False, + ) + node_outputs[nid] = fallback_md + node_states[nid] = {"skipped": False, "confidence": 0.65, "is_empty": False} + executed_trace.append(nid) + if not has_next_llm: + final_answer_md = fallback_md + yield {"event": "text", "data": {"delta": fallback_md}} + yield { + "event": "node", + "data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"}, + } + continue + + timeout_sec = max(5, min(int(node.get("timeout_seconds") or 60), 300)) + if has_next_llm: + resp = await asyncio.wait_for(ai_client.analyze(req), timeout=timeout_sec) + clean_text, inline_thoughts = strip_thinking_text(str(getattr(resp, "content", "") or "")) + node_outputs[nid] = clean_text or str(getattr(resp, "content", "") or "") + if node_outputs[nid]: + last_llm_output = node_outputs[nid] + resolved_provider = getattr(resp, "provider", None) or provider_name + resolved_model = getattr(resp, "model", None) or preferred_model or default_model + if inline_thoughts: + final_reasoning_md = f"{final_reasoning_md}\n\n" + "\n\n".join(inline_thoughts) + final_reasoning_md = final_reasoning_md.strip() + generation_mode = "llm_verified" + zero_token = False + node_states[nid] = { + "skipped": False, + "confidence": 0.85 if node_outputs[nid] else 0.4, + "is_empty": not bool(node_outputs[nid].strip()), + } + executed_trace.append(nid) + yield { + "event": "node", + "data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"}, + } + else: + text_parts: list[str] = [] + reasoning_parts: list[str] = [] + resolved_provider = provider_name or None + resolved_model = preferred_model or default_model or None + async for ev in ai_client.stream_analyze(req, request_id=run_id): + if request is not None and await request.is_disconnected(): + return + ev_type = str(ev.get("event") or "") + if ev_type == "start": + if isinstance(ev.get("provider"), str) and ev["provider"]: + resolved_provider = ev["provider"] + if isinstance(ev.get("model"), str) and ev["model"]: + resolved_model = ev["model"] + elif ev_type == "reasoning" and ev.get("delta"): + delta = str(ev["delta"]) + reasoning_parts.append(delta) + yield {"event": "reasoning", "data": {"delta": delta}} + elif ev_type == "text" and ev.get("delta"): + delta = str(ev["delta"]) + text_parts.append(delta) + yield {"event": "text", "data": {"delta": delta}} + elif ev_type == "done": + if isinstance(ev.get("provider"), str) and ev["provider"]: + resolved_provider = ev["provider"] + if isinstance(ev.get("model"), str) and ev["model"]: + resolved_model = ev["model"] + elif ev_type == "error": + err_msg = str(ev.get("message") or ev.get("detail") or "AI stream error") + raise RuntimeError(err_msg) + + raw_text = "".join(text_parts) + clean_text, inline_thoughts = strip_thinking_text(raw_text) + final_answer_md = (clean_text or raw_text).strip() + if inline_thoughts: + reasoning_parts.extend(inline_thoughts) + if reasoning_parts: + joined = "".join(reasoning_parts).strip() + final_reasoning_md = f"{final_reasoning_md}\n\n{joined}".strip() if final_reasoning_md else joined + generation_mode = "llm_verified" + zero_token = False + node_outputs[nid] = final_answer_md + node_states[nid] = { + "skipped": False, + "confidence": 0.9 if final_answer_md else 0.35, + "is_empty": not bool(final_answer_md), + } + executed_trace.append(nid) + yield { + "event": "node", + "data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"}, + } + continue + + if ntype == "guardrail": + gr = node.get("guardrails") if isinstance(node.get("guardrails"), dict) else {} + passed = True + warnings: list[str] = [] + if gr.get("require_evidence") and not evidence: + passed = False + warnings.append("缺少结构化证据条目(require_evidence)") + min_chars = int(gr.get("min_output_chars") or 0) + if min_chars > 0 and len(final_answer_md) < min_chars: + passed = False + warnings.append(f"输出长度低于最低阈值({min_chars} 字符)") + forbidden = gr.get("forbidden_phrases") + if isinstance(forbidden, list) and final_answer_md: + hits = [str(p) for p in forbidden if str(p) and str(p) in final_answer_md] + if hits: + passed = False + warnings.append("命中禁用表述: " + ", ".join(hits[:5])) + disclaimer = str(gr.get("append_disclaimer") or "").strip() + if disclaimer and final_answer_md and disclaimer not in final_answer_md: + extra_block = f"\n\n> {disclaimer}" + final_answer_md += extra_block + yield {"event": "text", "data": {"delta": extra_block}} + node_states[nid] = { + "skipped": False, + "confidence": 0.95 if passed else 0.45, + "is_empty": False, + "warnings": warnings, + } + executed_trace.append(nid) + yield { + "event": "node", + "data": { + "node_id": nid, + "title": ntitle, + "node_type": ntype, + "status": "completed", + "guardrail_passed": passed, + }, + } + continue + + if ntype == "output": + params = node.get("params") if isinstance(node.get("params"), dict) else {} + fly_enabled = bool(params.get("fly_to_target", True)) + if fly_enabled and clean_targets: + first = clean_targets[0] + lat = first.get("latitude") + lon = first.get("longitude") + if isinstance(lat, (int, float)) and isinstance(lon, (int, float)): + scene_spec = { + "fly_to": { + "lat": float(lat), + "lon": float(lon), + "zoom": float(params.get("fly_zoom") or 1.45), + }, + "highlight_entities": [ + str(t.get("entity_id") or t.get("id")) + for t in clean_targets + if t.get("entity_id") or t.get("id") + ], + } + node_states[nid] = {"skipped": False, "confidence": 1.0, "is_empty": False} + executed_trace.append(nid) + yield { + "event": "node", + "data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"}, + } + + if not final_answer_md: + final_answer_md = last_llm_output or _build_deterministic_fallback_markdown( + workflow_name=wf_name, + question=effective_question or question, + targets=clean_targets, + tool_results=tool_results, + ai_configured=ai_ready, + ) + yield {"event": "text", "data": {"delta": final_answer_md}} + + yield { + "event": "done", + "data": { + "run_id": run_id, + "workflow_id": wf_id, + "workflow_name": wf_name, + "status": "completed", + "generation_mode": generation_mode, + "zero_token": zero_token, + "provider": resolved_provider, + "model": resolved_model, + "nodes": executed_trace, + "evidence": evidence, + "scene_spec": scene_spec, + "answer_markdown": final_answer_md, + "reasoning_markdown": final_reasoning_md, + "text_length": len(final_answer_md), + }, + } diff --git a/backend/app/services/ai/stream_turn.py b/backend/app/services/ai/stream_turn.py index 2df4a572..d262ecce 100644 --- a/backend/app/services/ai/stream_turn.py +++ b/backend/app/services/ai/stream_turn.py @@ -12,10 +12,12 @@ from typing import Any import uuid from fastapi import HTTPException, Request, status +from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.core.logging import get_logger -from app.models.situational_assessment import InvestigationSession +from app.models.ai_workflow import AIWorkflow +from app.models.situational_assessment import InvestigationSession, WorkflowRun from app.schemas.ai import ChatMessage, SituationalAnalysisRequest from app.services.ai.access_policy import AccessContext from app.services.ai.conversation_memory import ( @@ -23,12 +25,15 @@ from app.services.ai.conversation_memory import ( sanitize_memory_notes, sanitize_pinned_summaries, ) +from app.services.ai.dag_executor import run_workflow_dag_stream from app.services.ai.thinking_sanitizer import prepare_situational_ai_call, strip_thinking_text from app.services.ai.tool_registry import ( TimeBasis, query_global_situational_tool, query_recent_earth_news_tool, ) +from app.services.ai.workflow_evolver import schedule_post_run_evolution +from app.services.ai.workflow_registry import _fallback_workflow_dict, ensure_builtin_workflows from app.services.ai.workflow_runtime import classify_turn_intent, execute_session_turn from app.services.ai_client import AIProviderClient @@ -271,6 +276,8 @@ async def stream_session_turn( conversation_summary: str | None = None, memory_notes: list[str] | None = None, pinned_summaries: list[str] | None = None, + workflow_id: str | None = None, + targets: list[dict[str, Any]] | None = None, ) -> AsyncIterator[str]: """Adaptive SSE generator: streams real LLM + thinking when AI is configured, else grounded baseline.""" check_stream_quota(access) @@ -335,6 +342,160 @@ async def stream_session_turn( compacted_flag = bool(compaction.get("compacted")) memory_used_flag = bool(compacted_summary or recent_history or clean_memory_notes or clean_pinned_summaries) + if workflow_id: + wf_dict: dict[str, Any] | None = None + try: + await ensure_builtin_workflows(db) + wf_row = ( + await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == workflow_id)) + ).scalar_one_or_none() + if wf_row is not None: + wf_dict = wf_row.to_dict() + except Exception: + wf_dict = None + if wf_dict is None: + wf_dict = _fallback_workflow_dict(workflow_id) + + if wf_dict is not None: + wf_started_at = datetime.now(UTC) + wf_trace: list[str] = [] + wf_status = "completed" + wf_error = "" + wf_answer = "" + wf_model = str(model_name or "") + wf_provider = str(provider_name or "") + wf_revision = int(wf_dict.get("active_revision") or 1) + try: + wf_earth_ctx: dict[str, Any] = { + **merged_ctx, + "domain": domain, + "selected_codes": codes, + "visible_layers": visible_layers, + "time_basis": time_basis, + "cutoff_at": cutoff_at, + } + if news_context: + wf_earth_ctx["news_context"] = news_context + if clean_memory_notes: + wf_earth_ctx["user_memory_notes"] = clean_memory_notes + + effective_client = ai_client + if ai_ready and ai_client is not None and type(ai_client) is AIProviderClient and ai_client.llm_config: + cur_max = int(ai_client.llm_config.get("max_tokens") or 0) + if cur_max < 3200: + effective_client, _ = prepare_situational_ai_call(ai_client, min_max_tokens=3200) + + allow_external = getattr(access, "access_tier", "public_zero_cost") == "admin" + async for item in run_workflow_dag_stream( + db=db, + workflow=wf_dict, + question=question, + use_draft=False, + targets=targets, + earth_context=wf_earth_ctx, + history=recent_history, + ai_client=effective_client, + request=request, + run_id=run_id, + allow_external_tools=allow_external, + extra_meta={ + "session_id": session_id_val, + "domain": domain, + "ai_enabled": ai_ready, + "provider": provider_name if ai_ready else None, + "model": model_name if ai_ready else None, + "compacted": compacted_flag, + "conversation_summary": compacted_summary, + "memory_used": memory_used_flag, + "context_state": {**merged_ctx, "domain": domain}, + **({"session_token": issued_session_token} if issued_session_token else {}), + }, + ): + ev_name = str(item.get("event") or "") + ev_data = dict(item.get("data") or {}) + if ev_name == "node" and ev_data.get("status") == "completed": + nid = str(ev_data.get("node_id") or "") + if nid and nid not in wf_trace: + wf_trace.append(nid) + elif ev_name == "done": + if isinstance(ev_data.get("nodes"), list): + wf_trace = [str(n) for n in ev_data["nodes"] if n] + if ev_data.get("model"): + wf_model = str(ev_data["model"]) + if ev_data.get("provider"): + wf_provider = str(ev_data["provider"]) + wf_answer = str(ev_data.get("answer_markdown") or "") + ev_data.setdefault("usage", {}) + ev_data["compacted"] = compacted_flag + ev_data["conversation_summary"] = compacted_summary + ev_data["memory_used"] = memory_used_flag + if session is not None and isinstance(session.context_state, dict): + updated_recent = [*recent_history, {"role": "user", "content": question}] + if wf_answer: + updated_recent.append({"role": "assistant", "content": wf_answer[:1800]}) + session.context_state = { + **session.context_state, + "conversation_summary": compacted_summary, + "recent_messages": updated_recent[-8:], + } + elif ev_name == "error": + wf_status = "failed" + wf_error = str(ev_data.get("message") or ev_data.get("detail") or "Workflow DAG error") + yield _format_sse(ev_name, ev_data) + except asyncio.CancelledError: + wf_status = "cancelled" + raise + except Exception as exc: + wf_status = "failed" + wf_error = str(exc) + logger.warning_event( + "Bound Earth workflow DAG stream failed", + event="ai_stream.workflow_dag.failed", + context={"workflow_id": workflow_id, "run_id": run_id, "error": wf_error}, + ) + yield _format_sse("error", {"detail": wf_error, "message": wf_error, "partial": bool(wf_answer)}) + finally: + try: + wf_completed_at = datetime.now(UTC) + wf_latency_ms = max(0, int((wf_completed_at - wf_started_at).total_seconds() * 1000)) + db.add( + WorkflowRun( + id=run_id, + session_id=session.id if session is not None else None, + workflow_id=workflow_id, + status=wf_status, + access_tier=getattr(access, "access_tier", "public_zero_cost"), + actor_key=getattr(access, "actor_key", "anonymous"), + question=question[:500], + input_params={ + "domain": domain, + "targets_count": len(targets or []), + "source": "earth_copilot", + }, + tool_trace=wf_trace, + budget_used={ + "steps": len(wf_trace), + "model_used": wf_model, + "provider": wf_provider, + "latency_ms": wf_latency_ms, + "workflow_revision": wf_revision, + }, + error_message=wf_error[:500], + started_at=wf_started_at, + completed_at=wf_completed_at, + ) + ) + if hasattr(db, "commit"): + await db.commit() + schedule_post_run_evolution(workflow_id, run_id) + except Exception: + if hasattr(db, "rollback"): + try: + await db.rollback() + except Exception: + pass + return + view_spec: dict[str, Any] | None = None scene_spec: dict[str, Any] | None = None evidence: dict[str, Any] = {} diff --git a/backend/app/services/ai/workflow_evolver.py b/backend/app/services/ai/workflow_evolver.py new file mode 100644 index 00000000..e0ecf6d2 --- /dev/null +++ b/backend/app/services/ai/workflow_evolver.py @@ -0,0 +1,2179 @@ +"""Lightweight, extensible 3-tier AI workflow self-evolution & meta-evolution engine. + +Tier 0 (Immutable Constitution Kernel in Python): + Enforces blast-radius limits, allowlisted tools, acyclic DAG integrity, + frozen meta-guardrail nodes, single-level meta recursion lock, cooldown & daily + auto-evolution budgets, and automatic canary rollback on regression. +Tier 1 (Business Workflow Optimization & Model Adaptation): + 0-token health/drift diagnostics, 👍/👎 feedback telemetry inside `WorkflowRun.budget_used`, + GEPA minimal-patch synthesis, DGM archive parent selection, AFlow positive/negative lessons, + optional Fixture A/B comparison, and workflow incubation from frequent `default.general` usage. +Tier 2 (Meta-Evolution): + Bootstraps `meta.workflow_evolver` (diag_node / patch_node) from objective ledger outcomes + under stricter cooldowns, constitution double-checks, and automatic meta-canary rollback. +""" + +from __future__ import annotations + +import asyncio +from collections import Counter +import copy +from dataclasses import dataclass, field +from datetime import UTC, datetime, timedelta +import os +from typing import Any, Protocol +from uuid import uuid4 + +from fastapi import HTTPException +from sqlalchemy import desc, select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.core.logging import get_logger +from app.db.session import async_session_factory +from app.models.ai_workflow import AIWorkflow, AIWorkflowFixture, AIWorkflowRevision +from app.models.situational_assessment import WorkflowRun +from app.models.system_setting import SystemSetting +from app.schemas.ai import SituationalAnalysisRequest +from app.services.ai.dag_executor import run_workflow_dag_stream +from app.services.ai.thinking_sanitizer import strip_thinking_text +from app.services.ai.workflow_registry import ( + ALLOWED_NODE_PATCH_FIELDS, + TOOL_CATALOG, + VALID_TOOL_IDS, + _apply_validated_node_patches, + _extract_first_json_object, + _validate_graph_payload, + build_starter_workflow_graph, + ensure_builtin_workflows, + publish_workflow, + resolve_runtime_workflow_node, + rollback_workflow, + save_workflow_draft, +) +from app.services.ai_client import get_ai_provider_client + +logger = get_logger(__name__, service="ai_evolver") + +# --------------------------------------------------------------------------- +# Tier 0: Immutable Constitution Constants (never AI-editable) +# --------------------------------------------------------------------------- + +META_WORKFLOW_ID = "meta.workflow_evolver" +FROZEN_META_NODE_IDS: frozenset[str] = frozenset({"verify_output"}) +POLICY_SETTING_CATEGORY = "ai_evolution_policy" +LEDGER_SETTING_CATEGORY = "ai_evolution_ledger" + +VALID_EVOLUTION_MODES: frozenset[str] = frozenset({"off", "draft", "auto"}) +MAX_LEDGER_ENTRIES = 50 +CANARY_OBSERVATION_RUNS = 5 +CANARY_CONSECUTIVE_FAILURES = 2 +CANARY_BAD_RATE_THRESHOLD = 0.40 +META_CANARY_WINDOW = 3 +META_CANARY_FAILURE_ROLLBACK = 2 +MIN_RUNS_FOR_AUTO = 5 +MIN_LEDGER_OUTCOMES_FOR_META = 5 +DEFAULT_DAILY_AUTO_BUDGET = 3 +MAX_AUTO_NODES_CHANGED = 2 +MAX_AUTO_NODE_RATIO = 0.40 + +DEFAULT_POLICY: dict[str, Any] = { + "business_mode": "draft", + "meta_mode": "off", + "daily_auto_budget": DEFAULT_DAILY_AUTO_BUDGET, + "business_cooldown_hours": 24, + "meta_cooldown_days": 7, + "locked_workflows": [], + "auto_adapt_on_model_change": True, +} + +# Keep track of active background tasks per workflow to avoid duplicate concurrent runs. +_PENDING_BG_WORKFLOWS: set[str] = set() + + +# --------------------------------------------------------------------------- +# Extensibility Protocols & Plug-In Registries +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class EvolutionSignal: + code: str + severity: str # "info" | "warn" | "critical" + message: str + suggested_mode: str = "optimize" # "optimize" | "model_adapt" | "incubate" + metadata: dict[str, Any] = field(default_factory=dict) + + def to_dict(self) -> dict[str, Any]: + return { + "code": self.code, + "severity": self.severity, + "message": self.message, + "suggested_mode": self.suggested_mode, + "metadata": dict(self.metadata), + } + + +class EvolutionSignalDetector(Protocol): + detector_id: str + + def detect(self, health_snapshot: dict[str, Any]) -> list[EvolutionSignal]: + ... + + +class EvolutionEvaluator(Protocol): + evaluator_id: str + + async def evaluate( + self, + db: AsyncSession, + workflow: dict[str, Any], + base_graph: dict[str, Any], + proposed_graph: dict[str, Any], + *, + max_fixtures: int = 3, + ) -> dict[str, Any]: + ... + + +class FailureRateSignalDetector: + detector_id = "failure_rate" + + def detect(self, health_snapshot: dict[str, Any]) -> list[EvolutionSignal]: + total = int(health_snapshot.get("total_runs") or 0) + failure_rate = float(health_snapshot.get("failure_rate") or 0.0) + failed = int(health_snapshot.get("failed_runs") or 0) + if total >= 3 and failure_rate >= 0.25: + return [ + EvolutionSignal( + code="high_failure_rate", + severity="critical" if failure_rate >= 0.4 else "warn", + message=f"近 {total} 次运行中有 {failed} 次失败(失败率 {round(failure_rate * 100)}%),建议调优工具或提示词。", + suggested_mode="optimize", + metadata={"failed_runs": failed, "total_runs": total, "failure_rate": failure_rate}, + ) + ] + return [] + + +class NegativeFeedbackSignalDetector: + detector_id = "negative_feedback" + + def detect(self, health_snapshot: dict[str, Any]) -> list[EvolutionSignal]: + downvotes = int(health_snapshot.get("downvotes") or 0) + rated = int(health_snapshot.get("rated_runs") or 0) + neg_rate = float(health_snapshot.get("negative_rate") or 0.0) + if downvotes >= 2 or (rated >= 3 and neg_rate >= 0.30): + return [ + EvolutionSignal( + code="negative_feedback_spike", + severity="warn", + message=f"收到 {downvotes} 次差评(占已评价 {round(neg_rate * 100)}%),可针对差评样本微调工作流。", + suggested_mode="optimize", + metadata={"downvotes": downvotes, "rated_runs": rated, "negative_rate": neg_rate}, + ) + ] + return [] + + +class ModelDriftSignalDetector: + detector_id = "model_drift" + + def detect(self, health_snapshot: dict[str, Any]) -> list[EvolutionSignal]: + if health_snapshot.get("model_drift_detected"): + active_model = str((health_snapshot.get("active_model_profile") or {}).get("model") or "") + recent_models = health_snapshot.get("recent_models") or [] + return [ + EvolutionSignal( + code="model_capability_drift", + severity="warn", + message=( + f"当前活跃模型({active_model or '已切换'})与近期运行模型({', '.join(recent_models[:2])})不一致," + "建议执行一次模型能力自适应。" + ), + suggested_mode="model_adapt", + metadata={"active_model": active_model, "recent_models": recent_models}, + ) + ] + return [] + + +class UnusedToolSignalDetector: + detector_id = "unused_tools" + + def detect(self, health_snapshot: dict[str, Any]) -> list[EvolutionSignal]: + unused = list(health_snapshot.get("unused_tools") or []) + total = int(health_snapshot.get("total_runs") or 0) + if unused and total >= 5: + return [ + EvolutionSignal( + code="unused_tools_detected", + severity="info", + message=f"以下已绑定工具在近期 {total} 次运行中均未实际触发:{', '.join(unused[:4])}。", + suggested_mode="optimize", + metadata={"unused_tools": unused}, + ) + ] + return [] + + +class FixtureABEvaluator: + evaluator_id = "fixture_ab" + + async def evaluate( + self, + db: AsyncSession, + workflow: dict[str, Any], + base_graph: dict[str, Any], + proposed_graph: dict[str, Any], + *, + max_fixtures: int = 3, + ) -> dict[str, Any]: + wf_id = str(workflow.get("workflow_id") or "") + rows = ( + await db.execute( + select(AIWorkflowFixture) + .where(AIWorkflowFixture.workflow_id == wf_id) + .order_by(desc(AIWorkflowFixture.id)) + .limit(max(1, min(int(max_fixtures or 3), 5))) + ) + ).scalars().all() + if not rows: + return { + "evaluator_id": self.evaluator_id, + "fixture_count": 0, + "verdict": "no_fixtures", + "summary": "当前工作流尚未保存测试样本(Fixtures),请在 Playground 挂载上下文后点击「存为样本」。", + "comparisons": [], + } + + ai_client = None + try: + ai_client = await get_ai_provider_client(db) + except Exception: + ai_client = None + + comparisons: list[dict[str, Any]] = [] + base_ok = 0 + prop_ok = 0 + for row in rows: + question = str(row.sample_question or "").strip() or f"请分析 {row.name}" + ctx = dict(row.context_json or {}) + base_res = await _run_graph_single_sample( + db=db, + workflow=workflow, + graph=base_graph, + question=question, + earth_context=ctx, + ai_client=ai_client, + ) + prop_res = await _run_graph_single_sample( + db=db, + workflow=workflow, + graph=proposed_graph, + question=question, + earth_context=ctx, + ai_client=ai_client, + ) + if base_res["ok"]: + base_ok += 1 + if prop_res["ok"]: + prop_ok += 1 + comparisons.append( + { + "fixture_id": row.id, + "fixture_name": row.name, + "question": question[:160], + "base": base_res, + "proposed": prop_res, + } + ) + + if prop_ok > base_ok: + verdict = "improved" + elif prop_ok < base_ok: + verdict = "regressed" + else: + avg_base_ms = sum(c["base"]["latency_ms"] for c in comparisons) / len(comparisons) + avg_prop_ms = sum(c["proposed"]["latency_ms"] for c in comparisons) / len(comparisons) + if avg_prop_ms > avg_base_ms * 1.35 and avg_prop_ms - avg_base_ms > 1500: + verdict = "slower" + else: + verdict = "neutral" + + return { + "evaluator_id": self.evaluator_id, + "fixture_count": len(comparisons), + "base_passed": base_ok, + "proposed_passed": prop_ok, + "verdict": verdict, + "summary": f"已对照 {len(comparisons)} 组样本:原版通过 {base_ok}/{len(comparisons)},新版通过 {prop_ok}/{len(comparisons)}(判定:{verdict})。", + "comparisons": comparisons, + } + + +SIGNAL_DETECTORS: list[EvolutionSignalDetector] = [ + FailureRateSignalDetector(), + NegativeFeedbackSignalDetector(), + ModelDriftSignalDetector(), + UnusedToolSignalDetector(), +] + +EVALUATORS: dict[str, EvolutionEvaluator] = { + "fixture_ab": FixtureABEvaluator(), +} + + +# --------------------------------------------------------------------------- +# Helpers & Direct SystemSetting JSON Storage +# --------------------------------------------------------------------------- + + +def _utc_now() -> datetime: + return datetime.now(UTC) + + +def _ensure_utc(dt: datetime | None) -> datetime | None: + if dt is None: + return None + if dt.tzinfo is None: + return dt.replace(tzinfo=UTC) + return dt.astimezone(UTC) + + +def _parse_iso(raw: Any) -> datetime | None: + if not raw: + return None + try: + parsed = datetime.fromisoformat(str(raw).replace("Z", "+00:00")) + return _ensure_utc(parsed) + except Exception: + return None + + +async def _read_setting_json(db: AsyncSession, category: str) -> dict[str, Any] | None: + if not hasattr(db, "execute"): + return None + stmt = select(SystemSetting).where(SystemSetting.category == category) + if hasattr(stmt, "execution_options"): + stmt = stmt.execution_options(populate_existing=True) + record = (await db.execute(stmt)).scalar_one_or_none() + if record is None or not isinstance(record.payload, dict): + return None + return copy.deepcopy(record.payload) + + +async def _write_setting_json( + db: AsyncSession, + category: str, + payload: dict[str, Any], +) -> dict[str, Any]: + stmt = select(SystemSetting).where(SystemSetting.category == category) + if hasattr(stmt, "execution_options"): + stmt = stmt.execution_options(populate_existing=True) + record = (await db.execute(stmt)).scalar_one_or_none() + clean_payload = copy.deepcopy(payload) + if record is None: + record = SystemSetting(category=category, payload=clean_payload) + db.add(record) + else: + record.payload = clean_payload + await db.commit() + await db.refresh(record) + return copy.deepcopy(record.payload) + + +def _normalize_policy(raw: dict[str, Any] | None) -> dict[str, Any]: + merged = copy.deepcopy(DEFAULT_POLICY) + if isinstance(raw, dict): + for k, v in raw.items(): + if k in merged: + merged[k] = copy.deepcopy(v) + if merged["business_mode"] not in VALID_EVOLUTION_MODES: + merged["business_mode"] = DEFAULT_POLICY["business_mode"] + if merged["meta_mode"] not in VALID_EVOLUTION_MODES: + merged["meta_mode"] = DEFAULT_POLICY["meta_mode"] + try: + merged["daily_auto_budget"] = max(1, min(int(merged["daily_auto_budget"]), 20)) + except (TypeError, ValueError): + merged["daily_auto_budget"] = DEFAULT_DAILY_AUTO_BUDGET + try: + merged["business_cooldown_hours"] = max(1, min(int(merged["business_cooldown_hours"]), 168)) + except (TypeError, ValueError): + merged["business_cooldown_hours"] = 24 + try: + merged["meta_cooldown_days"] = max(1, min(int(merged["meta_cooldown_days"]), 30)) + except (TypeError, ValueError): + merged["meta_cooldown_days"] = 7 + raw_locked = merged.get("locked_workflows") + merged["locked_workflows"] = sorted( + {str(w).strip() for w in (raw_locked if isinstance(raw_locked, list) else []) if str(w).strip()} + ) + merged["auto_adapt_on_model_change"] = bool(merged.get("auto_adapt_on_model_change", True)) + return merged + + +async def get_evolution_policy(db: AsyncSession) -> dict[str, Any]: + raw = await _read_setting_json(db, POLICY_SETTING_CATEGORY) + return _normalize_policy(raw) + + +async def update_evolution_policy(db: AsyncSession, updates: dict[str, Any]) -> dict[str, Any]: + current = await get_evolution_policy(db) + for key in DEFAULT_POLICY: + if key in updates and updates[key] is not None: + current[key] = updates[key] + normalized = _normalize_policy(current) + normalized["updated_at"] = _utc_now().isoformat() + await _write_setting_json(db, POLICY_SETTING_CATEGORY, normalized) + return _normalize_policy(normalized) + + +async def _load_ledger_entries(db: AsyncSession) -> list[dict[str, Any]]: + raw = await _read_setting_json(db, LEDGER_SETTING_CATEGORY) + entries = raw.get("entries") if isinstance(raw, dict) else None + if not isinstance(entries, list): + return [] + return [dict(item) for item in entries if isinstance(item, dict)] + + +async def get_evolution_ledger( + db: AsyncSession, + *, + workflow_id: str | None = None, + limit: int = 30, +) -> list[dict[str, Any]]: + entries = await _load_ledger_entries(db) + if workflow_id: + entries = [e for e in entries if str(e.get("workflow_id") or "") == workflow_id] + return entries[: max(1, min(int(limit or 30), MAX_LEDGER_ENTRIES))] + + +async def append_ledger_entry(db: AsyncSession, entry: dict[str, Any]) -> dict[str, Any]: + entries = await _load_ledger_entries(db) + clean = dict(entry) + clean.setdefault("id", f"evo_{uuid4().hex[:12]}") + clean.setdefault("created_at", _utc_now().isoformat()) + next_entries = [clean, *entries][:MAX_LEDGER_ENTRIES] + await _write_setting_json(db, LEDGER_SETTING_CATEGORY, {"entries": next_entries}) + return clean + + +async def update_ledger_entry( + db: AsyncSession, + entry_id: str, + updates: dict[str, Any], +) -> dict[str, Any] | None: + entries = await _load_ledger_entries(db) + updated: dict[str, Any] | None = None + next_entries: list[dict[str, Any]] = [] + for item in entries: + if str(item.get("id") or "") == entry_id: + merged = {**item, **updates, "updated_at": _utc_now().isoformat()} + updated = merged + next_entries.append(merged) + else: + next_entries.append(item) + if updated is not None: + await _write_setting_json(db, LEDGER_SETTING_CATEGORY, {"entries": next_entries}) + return updated + + +async def dismiss_ledger_entry( + db: AsyncSession, + entry_id: str, + *, + reason: str = "", +) -> dict[str, Any]: + updated = await update_ledger_entry( + db, + entry_id, + { + "status": "dismissed", + "dismiss_reason": reason.strip()[:300] or "Dismissed by admin", + }, + ) + if updated is None: + raise HTTPException(status_code=404, detail=f"Evolution ledger entry '{entry_id}' not found") + return updated + + +# --------------------------------------------------------------------------- +# Active Model Capability Profiler (0-Token) +# --------------------------------------------------------------------------- + + +def infer_model_capabilities(provider: str, model: str) -> dict[str, Any]: + p = str(provider or "").strip().lower() + m = str(model or "").strip().lower() + is_reasoning = any(tok in m for tok in ("r1", "reasoner", "o1", "o3", "o4", "thinking", "pro", "opus", "sonnet")) + is_fast = any(tok in m for tok in ("flash", "mini", "haiku", "nano", "lite", "fast", "turbo")) + if is_fast and not is_reasoning: + tier = "fast" + elif is_reasoning: + tier = "reasoning" + else: + tier = "standard" + + supports_thinking = is_reasoning or any(tok in m for tok in ("2.5", "gemini-3", "deepseek", "qwen3", "minimax")) + supports_native_search = any(tok in p for tok in ("gemini", "perplexity", "xai", "grok", "openai")) or any( + tok in m for tok in ("gemini", "sonar", "grok") + ) + supports_vision = any(tok in m for tok in ("vision", "vl", "gemini", "gpt-4o", "gpt-4.1", "claude", "sonnet", "opus", "haiku")) + return { + "provider": p or "unconfigured", + "model": str(model or "").strip(), + "tier": tier, + "supports_thinking": supports_thinking, + "supports_native_search": supports_native_search, + "supports_vision": supports_vision, + } + + +async def get_active_model_profile(db: AsyncSession, ai_client: Any = None) -> dict[str, Any]: + client = ai_client + if client is None: + try: + client = await get_ai_provider_client(db) + except Exception: + client = None + ready = False + provider = "" + model = "" + if client is not None and hasattr(client, "is_ready"): + try: + ready, provider, model = await client.is_ready() + except Exception: + ready = False + profile = infer_model_capabilities(provider, model) + profile["ready"] = bool(ready) + return profile + + +# --------------------------------------------------------------------------- +# Run Telemetry & Feedback +# --------------------------------------------------------------------------- + + +def _run_model(row: WorkflowRun) -> str: + bu = row.budget_used if isinstance(row.budget_used, dict) else {} + inp = row.input_params if isinstance(row.input_params, dict) else {} + return str(bu.get("model_used") or inp.get("model_override") or "").strip() + + +def _run_rating(row: WorkflowRun) -> int: + bu = row.budget_used if isinstance(row.budget_used, dict) else {} + try: + val = int(bu.get("user_rating") or 0) + return val if val in (-1, 0, 1) else 0 + except (TypeError, ValueError): + return 0 + + +def _run_latency_ms(row: WorkflowRun) -> int | None: + bu = row.budget_used if isinstance(row.budget_used, dict) else {} + raw = bu.get("latency_ms") + if isinstance(raw, (int, float)) and raw >= 0: + return int(raw) + started = _ensure_utc(row.started_at) + completed = _ensure_utc(row.completed_at) + if started and completed: + return max(0, int((completed - started).total_seconds() * 1000)) + return None + + +def _run_revision(row: WorkflowRun) -> int | None: + bu = row.budget_used if isinstance(row.budget_used, dict) else {} + raw = bu.get("workflow_revision") + if isinstance(raw, int) and raw >= 1: + return raw + return None + + +async def record_run_feedback( + db: AsyncSession, + run_id: str, + *, + rating: int, + note: str = "", + actor: str = "admin", +) -> dict[str, Any]: + if rating not in (-1, 0, 1): + raise HTTPException(status_code=422, detail="rating must be -1, 0, or 1") + row = (await db.execute(select(WorkflowRun).where(WorkflowRun.id == run_id))).scalar_one_or_none() + if row is None: + raise HTTPException(status_code=404, detail=f"Workflow run '{run_id}' not found") + + prev_budget = dict(row.budget_used) if isinstance(row.budget_used, dict) else {} + prev_budget["user_rating"] = int(rating) + if note.strip() or rating == 0: + prev_budget["feedback_note"] = note.strip()[:500] if rating != 0 else "" + prev_budget["feedback_at"] = _utc_now().isoformat() + prev_budget["feedback_by"] = actor + row.budget_used = prev_budget + await db.commit() + await db.refresh(row) + + canary_result = None + if rating == -1: + canary_result = await evaluate_canary_and_maybe_rollback(db, row.workflow_id) + + payload = row.to_dict() + if canary_result is not None: + payload["canary_evaluation"] = canary_result + return payload + + +# --------------------------------------------------------------------------- +# 0-Token Workflow Health Diagnostics & DGM Archive Selection +# --------------------------------------------------------------------------- + + +async def compute_workflow_health( + db: AsyncSession, + workflow_id: str, + *, + ai_client: Any = None, +) -> dict[str, Any]: + await ensure_builtin_workflows(db) + wf = ( + await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == workflow_id)) + ).scalar_one_or_none() + if wf is None: + raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found") + + cutoff = _utc_now() - timedelta(days=30) + runs = ( + await db.execute( + select(WorkflowRun) + .where(WorkflowRun.workflow_id == workflow_id) + .order_by(desc(WorkflowRun.started_at)) + .limit(200) + ) + ).scalars().all() + recent_runs = [ + r for r in runs if (_ensure_utc(r.started_at) or _utc_now()) >= cutoff + ] + + total = len(recent_runs) + completed = sum(1 for r in recent_runs if r.status == "completed") + failed = sum(1 for r in recent_runs if r.status == "failed") + latencies = [ms for ms in (_run_latency_ms(r) for r in recent_runs) if ms is not None] + avg_latency_ms = int(sum(latencies) / len(latencies)) if latencies else 0 + + upvotes = sum(1 for r in recent_runs if _run_rating(r) == 1) + downvotes = sum(1 for r in recent_runs if _run_rating(r) == -1) + rated_runs = upvotes + downvotes + success_rate = round(completed / total, 4) if total else 1.0 + failure_rate = round(failed / total, 4) if total else 0.0 + negative_rate = round(downvotes / rated_runs, 4) if rated_runs else 0.0 + + # Tool usage tracking from trace entries (`node_id:tool_id` or `tool_id`) + observed_tools: set[str] = set() + for r in recent_runs: + for step in r.tool_trace or []: + s = str(step or "") + if ":" in s: + observed_tools.add(s.split(":", 1)[1]) + elif s in VALID_TOOL_IDS: + observed_tools.add(s) + + configured_tools: set[str] = set() + active_graph = wf.draft_graph or wf.published_graph or {} + for node in active_graph.get("nodes") or []: + if isinstance(node, dict) and node.get("enabled", True): + for tid in node.get("tools") or []: + if str(tid) in VALID_TOOL_IDS: + configured_tools.add(str(tid)) + unused_tools = sorted(configured_tools - observed_tools) if total >= 5 else [] + + recent_models: list[str] = [] + for r in recent_runs[:20]: + m = _run_model(r) + if m and m not in recent_models: + recent_models.append(m) + + model_profile = await get_active_model_profile(db, ai_client=ai_client) + active_model = str(model_profile.get("model") or "").strip() + model_drift = bool( + model_profile.get("ready") + and active_model + and recent_models + and active_model not in recent_models[:3] + ) + + # DGM Revision Archive scoring + revisions = ( + await db.execute( + select(AIWorkflowRevision) + .where(AIWorkflowRevision.workflow_id == workflow_id) + .order_by(desc(AIWorkflowRevision.revision)) + .limit(20) + ) + ).scalars().all() + ledger = await get_evolution_ledger(db, workflow_id=workflow_id, limit=50) + rolled_back_revs = { + int(e["target_revision"]) + for e in ledger + if e.get("status") == "rolled_back" and isinstance(e.get("target_revision"), int) + } + + runs_by_rev: dict[int, list[WorkflowRun]] = {} + for r in recent_runs: + rev_num = _run_revision(r) + if rev_num is not None: + runs_by_rev.setdefault(rev_num, []).append(r) + + archive_scores: list[dict[str, Any]] = [] + for rev in revisions: + rev_runs = runs_by_rev.get(int(rev.revision), []) + r_total = len(rev_runs) + r_comp = sum(1 for r in rev_runs if r.status == "completed") + r_up = sum(1 for r in rev_runs if _run_rating(r) == 1) + r_down = sum(1 for r in rev_runs if _run_rating(r) == -1) + r_rated = r_up + r_down + r_succ = (r_comp / r_total) if r_total else 0.0 + r_neg = (r_down / r_rated) if r_rated else 0.0 + score = round(r_succ - 0.35 * r_neg, 4) if r_total >= 1 else None + archive_scores.append( + { + "revision": int(rev.revision), + "runs": r_total, + "success_rate": round(r_succ, 4) if r_total else None, + "downvotes": r_down, + "score": score, + "rolled_back": int(rev.revision) in rolled_back_revs, + "created_by": rev.created_by, + } + ) + + active_rev = int(wf.active_revision or 1) + active_entry = next((a for a in archive_scores if a["revision"] == active_rev), None) + best_parent = None + candidates = [ + a for a in archive_scores + if not a["rolled_back"] and a["runs"] >= 3 and a["score"] is not None + ] + if candidates: + best_cand = max(candidates, key=lambda x: (float(x["score"] or 0.0), -int(x["revision"]))) + if ( + best_cand["revision"] != active_rev + and active_entry is not None + and active_entry["runs"] >= 3 + and active_entry["score"] is not None + and float(best_cand["score"]) - float(active_entry["score"]) >= 0.15 + ): + best_parent = best_cand["revision"] + + policy = await get_evolution_policy(db) + is_locked = workflow_id in set(policy.get("locked_workflows") or []) + active_canary = next((e for e in ledger if e.get("status") == "canary"), None) + if active_canary is not None: + observed = _count_canary_observations(recent_runs, active_canary) + active_canary = { + **active_canary, + "observed_runs": observed["observed"], + "failed_runs": observed["failed"], + "downvoted_runs": observed["downvoted"], + } + + health: dict[str, Any] = { + "workflow_id": workflow_id, + "active_revision": active_rev, + "is_locked": is_locked, + "window_days": 30, + "total_runs": total, + "completed_runs": completed, + "failed_runs": failed, + "success_rate": success_rate, + "failure_rate": failure_rate, + "avg_latency_ms": avg_latency_ms, + "upvotes": upvotes, + "downvotes": downvotes, + "rated_runs": rated_runs, + "negative_rate": negative_rate, + "recent_models": recent_models[:5], + "active_model_profile": model_profile, + "model_drift_detected": model_drift, + "unused_tools": unused_tools, + "canary": active_canary, + "revision_archive": archive_scores[:10], + "recommended_parent_revision": best_parent, + "policy": policy, + } + signals: list[dict[str, Any]] = [] + for detector in SIGNAL_DETECTORS: + try: + for sig in detector.detect(health): + signals.append(sig.to_dict()) + except Exception: + continue + health["signals"] = signals + return health + + +# --------------------------------------------------------------------------- +# Tier 0: Constitution Patch Validation & Canary Auto-Rollback +# --------------------------------------------------------------------------- + + +def validate_evolution_patch( + base_graph: dict[str, Any], + proposed_graph: dict[str, Any], + diffs: list[dict[str, Any]], + *, + is_meta: bool = False, + is_auto: bool = False, +) -> tuple[bool, list[str]]: + """Immutable Tier-0 Constitution check; returns `(ok, violations)`.""" + violations: list[str] = [] + try: + validated = _validate_graph_payload(proposed_graph) + except HTTPException as exc: + return False, [f"图结构校验失败:{exc.detail}"] + + base_nodes = { + str(n.get("id")): n + for n in (base_graph.get("nodes") or []) + if isinstance(n, dict) and n.get("id") + } + prop_nodes = { + str(n.get("id")): n + for n in (validated.get("nodes") or []) + if isinstance(n, dict) and n.get("id") + } + + # 1. Preserve trigger/output presence if present in baseline + base_types = {str(n.get("node_type") or "") for n in base_nodes.values()} + prop_types = {str(n.get("node_type") or "") for n in prop_nodes.values()} + for required_type in ("trigger", "output"): + if required_type in base_types and required_type not in prop_types: + violations.append(f"不可移除基础 {required_type} 节点") + + # 2. Prevent blanking out non-empty system_prompt + for nid, bnode in base_nodes.items(): + pnode = prop_nodes.get(nid) + if not pnode: + continue + if str(bnode.get("system_prompt") or "").strip() and not str(pnode.get("system_prompt") or "").strip(): + violations.append(f"节点 {nid} 的 system_prompt 不可被清空") + + changed_node_ids = { + str(d.get("node_id") or "") + for d in diffs + if isinstance(d, dict) and d.get("node_id") + } + + # 3. Meta-workflow specific Constitution guards + if is_meta: + touched_frozen = changed_node_ids & FROZEN_META_NODE_IDS + if touched_frozen: + violations.append(f"元进化宪法节点不可修改:{', '.join(sorted(touched_frozen))}") + for frozen_id in FROZEN_META_NODE_IDS: + if frozen_id in base_nodes: + if frozen_id not in prop_nodes: + violations.append(f"不可删除宪法守护节点 {frozen_id}") + elif prop_nodes[frozen_id] != base_nodes[frozen_id]: + violations.append(f"宪法守护节点 {frozen_id} 内容受只读保护") + active_llm_count = sum( + 1 + for n in prop_nodes.values() + if n.get("node_type") in {"llm_agent", "tool_agent"} and n.get("enabled", True) + ) + if active_llm_count == 0: + violations.append("元引擎至少须保留一个启用的 LLM 推理节点") + patch_node = prop_nodes.get("patch_node") + if patch_node: + combined_prompt = f"{patch_node.get('system_prompt') or ''} {patch_node.get('prompt') or ''}" + if "json" not in combined_prompt.lower() or "node_patches" not in combined_prompt: + violations.append("patch_node 提示词必须保留 JSON node_patches 结构化输出约束") + + # 4. Auto-mode blast radius lock + if is_auto: + if set(base_nodes.keys()) != set(prop_nodes.keys()): + violations.append("自动发布模式禁止增删节点拓扑,仅允许节点字段微调") + max_allowed = 1 if is_meta else max(1, min(MAX_AUTO_NODES_CHANGED, int(len(base_nodes) * MAX_AUTO_NODE_RATIO) or 1)) + if len(changed_node_ids) > max_allowed: + violations.append(f"自动变更半径超限(最多允许修改 {max_allowed} 个节点,实际 {len(changed_node_ids)} 个)") + + return len(violations) == 0, violations + + +def _count_canary_observations(runs: list[WorkflowRun], canary_entry: dict[str, Any]) -> dict[str, Any]: + started_at = _parse_iso(canary_entry.get("created_at")) + target_rev = canary_entry.get("target_revision") + matched: list[WorkflowRun] = [] + for r in runs: + r_time = _ensure_utc(r.started_at) + if started_at and r_time and r_time < started_at: + continue + r_rev = _run_revision(r) + if isinstance(target_rev, int) and r_rev is not None and r_rev != target_rev: + continue + matched.append(r) + + # Sort ascending chronologically to measure consecutive failures properly + matched_asc = sorted(matched, key=lambda x: _ensure_utc(x.started_at) or _utc_now()) + observed = len(matched_asc) + failed = sum(1 for r in matched_asc if r.status == "failed") + downvoted = sum(1 for r in matched_asc if _run_rating(r) == -1) + + max_consec_fail = 0 + cur_consec = 0 + for r in matched_asc: + if r.status == "failed": + cur_consec += 1 + max_consec_fail = max(max_consec_fail, cur_consec) + else: + cur_consec = 0 + + return { + "observed": observed, + "failed": failed, + "downvoted": downvoted, + "max_consecutive_failures": max_consec_fail, + } + + +async def _evaluate_meta_canary(db: AsyncSession) -> None: + """Auto-verify or auto-rollback `meta.workflow_evolver` based on downstream ledger outcomes.""" + entries = await _load_ledger_entries(db) + meta_canary = next( + ( + e + for e in entries + if e.get("workflow_id") == META_WORKFLOW_ID and e.get("status") == "canary" + ), + None, + ) + if meta_canary is None: + return + meta_started = _parse_iso(meta_canary.get("created_at")) + downstream = [ + e + for e in entries + if e.get("workflow_id") != META_WORKFLOW_ID + and e.get("status") in {"verified", "rolled_back"} + and (_parse_iso(e.get("created_at")) or _utc_now()) >= (meta_started or _utc_now()) + ] + if not downstream: + return + recent_outcomes = downstream[:META_CANARY_WINDOW] + rollbacks = sum(1 for e in recent_outcomes if e.get("status") == "rolled_back") + if rollbacks >= META_CANARY_FAILURE_ROLLBACK and isinstance(meta_canary.get("base_revision"), int): + await rollback_workflow( + db, + META_WORKFLOW_ID, + int(meta_canary["base_revision"]), + actor="system:meta_canary_rollback", + ) + await update_ledger_entry( + db, + str(meta_canary["id"]), + { + "status": "rolled_back", + "rollback_reason": f"新元策略生效后连续 {rollbacks}/{len(recent_outcomes)} 次业务进化被回滚,已自动回退元引擎。", + }, + ) + elif len(recent_outcomes) >= META_CANARY_WINDOW and rollbacks < META_CANARY_FAILURE_ROLLBACK: + await update_ledger_entry( + db, + str(meta_canary["id"]), + { + "status": "verified", + "verified_summary": f"经 {len(recent_outcomes)} 次下游业务进化验证稳定(回滚 {rollbacks} 次)。", + }, + ) + + +async def evaluate_canary_and_maybe_rollback( + db: AsyncSession, + workflow_id: str, +) -> dict[str, Any] | None: + """Evaluate active canary window for `workflow_id`; roll back automatically on regression.""" + entries = await _load_ledger_entries(db) + canary = next( + ( + e + for e in entries + if e.get("workflow_id") == workflow_id and e.get("status") == "canary" + ), + None, + ) + if canary is None: + return None + + runs = ( + await db.execute( + select(WorkflowRun) + .where(WorkflowRun.workflow_id == workflow_id) + .order_by(desc(WorkflowRun.started_at)) + .limit(40) + ) + ).scalars().all() + stats = _count_canary_observations(runs, canary) + observed = stats["observed"] + bad_count = stats["failed"] + stats["downvoted"] + bad_rate = (bad_count / observed) if observed else 0.0 + baseline_fail = float(canary.get("baseline_failure_rate") or 0.0) + threshold = max(CANARY_BAD_RATE_THRESHOLD, baseline_fail + 0.15) + target_window = int(canary.get("canary_runs_target") or CANARY_OBSERVATION_RUNS) + + tripped_consecutive = stats["max_consecutive_failures"] >= CANARY_CONSECUTIVE_FAILURES + tripped_rate = observed >= 3 and bad_rate >= threshold + + if (tripped_consecutive or tripped_rate) and isinstance(canary.get("base_revision"), int): + base_rev = int(canary["base_revision"]) + reason = ( + f"灰度观察期触发自动回滚(观察 {observed} 次:连续失败 {stats['max_consecutive_failures']} 次," + f"失败 {stats['failed']} 次,差评 {stats['downvoted']} 次),已回退至 v{base_rev}。" + ) + await rollback_workflow(db, workflow_id, base_rev, actor="system:canary_rollback") + updated = await update_ledger_entry( + db, + str(canary["id"]), + { + "status": "rolled_back", + "rollback_reason": reason, + "observed_runs": observed, + }, + ) + logger.warning_event( + "Workflow canary auto-rolled back", + event="ai_evolver.canary.rollback", + context={"workflow_id": workflow_id, "base_revision": base_rev, "stats": stats}, + ) + await _evaluate_meta_canary(db) + return {"action": "rolled_back", "reason": reason, "entry": updated} + + if observed >= target_window: + updated = await update_ledger_entry( + db, + str(canary["id"]), + { + "status": "verified", + "verified_summary": f"通过 {observed} 次灰度运行观察(失败 {stats['failed']} 次,差评 {stats['downvoted']} 次)。", + "observed_runs": observed, + }, + ) + await _evaluate_meta_canary(db) + return {"action": "verified", "entry": updated} + + return {"action": "observing", "observed": observed, "target": target_window} + + +# --------------------------------------------------------------------------- +# Quota / Cooldown Guardrails +# --------------------------------------------------------------------------- + + +async def _check_auto_budget_and_cooldown( + db: AsyncSession, + workflow_id: str, + policy: dict[str, Any], + *, + is_meta: bool = False, + model_drift: bool = False, +) -> tuple[bool, str]: + if workflow_id in set(policy.get("locked_workflows") or []): + return False, "工作流已锁定,禁止自动修改" + + entries = await _load_ledger_entries(db) + now = _utc_now() + day_ago = now - timedelta(days=1) + + auto_today = sum( + 1 + for e in entries + if str(e.get("trigger") or "").startswith("auto") or e.get("trigger") == "meta_auto" + if (_parse_iso(e.get("created_at")) or now) >= day_ago + and e.get("status") in {"canary", "verified", "rolled_back", "draft_saved"} + ) + budget = int(policy.get("daily_auto_budget") or DEFAULT_DAILY_AUTO_BUDGET) + if auto_today >= budget: + return False, f"今日自动进化次数已达上限({auto_today}/{budget})" + + latest_for_wf = next( + ( + e + for e in entries + if e.get("workflow_id") == workflow_id + and e.get("status") in {"canary", "verified", "rolled_back", "draft_saved"} + ), + None, + ) + if latest_for_wf is not None: + last_dt = _parse_iso(latest_for_wf.get("created_at")) + if last_dt is not None: + if is_meta: + cd_days = int(policy.get("meta_cooldown_days") or 7) + if now - last_dt < timedelta(days=cd_days): + return False, f"元进化冷却期内({cd_days} 天冷却)" + else: + cd_hours = int(policy.get("business_cooldown_hours") or 24) + if not model_drift and (now - last_dt < timedelta(hours=cd_hours)): + return False, f"工作流处于冷却期内({cd_hours} 小时内仅自动调整一次)" + + return True, "" + + +# --------------------------------------------------------------------------- +# Tier 1: Business Workflow Self-Evolution & Model Adaptation +# --------------------------------------------------------------------------- + + +def _build_aflow_lessons(ledger: list[dict[str, Any]]) -> dict[str, list[dict[str, Any]]]: + positive = [ + { + "workflow_id": e.get("workflow_id"), + "mode": e.get("mode"), + "summary": e.get("summary"), + "changes": (e.get("changes") or [])[:3], + } + for e in ledger + if e.get("status") == "verified" + ][:5] + negative = [ + { + "workflow_id": e.get("workflow_id"), + "mode": e.get("mode"), + "summary": e.get("summary"), + "reason": e.get("rollback_reason") or e.get("dismiss_reason") or "", + "changes": (e.get("changes") or [])[:3], + } + for e in ledger + if e.get("status") in {"rolled_back", "dismissed"} + ][:5] + return {"verified_lessons": positive, "failed_lessons": negative} + + +def _deterministic_business_patches( + base_graph: dict[str, Any], + *, + mode: str, + instruction: str, + health: dict[str, Any], + bad_runs: list[dict[str, Any]], +) -> tuple[str, list[dict[str, Any]]]: + nodes = [n for n in (base_graph.get("nodes") or []) if isinstance(n, dict)] + llm_node = next((n for n in nodes if n.get("node_type") in {"llm_agent", "tool_agent"}), None) + if llm_node is None: + return "当前工作流无可扩展推理节点。", [] + + patches: list[dict[str, Any]] = [] + if mode == "model_adapt": + profile = health.get("active_model_profile") or {} + tier = str(profile.get("tier") or "standard") + cur_thinking = bool(llm_node.get("thinking_enabled", True)) + cur_search = bool(llm_node.get("native_web_search", False)) + cur_steps = int(llm_node.get("max_steps") or 2) + if not profile.get("supports_thinking") and cur_thinking: + patches.append( + { + "node_id": llm_node["id"], + "field": "thinking_enabled", + "after": False, + "reason": f"当前模型({profile.get('model') or profile.get('provider')})未声明深度思考模式,关闭无效开关以降低首字延迟。", + } + ) + elif profile.get("supports_thinking") and tier == "reasoning" and not cur_thinking: + patches.append( + { + "node_id": llm_node["id"], + "field": "thinking_enabled", + "after": True, + "reason": f"当前模型({profile.get('model')})支持深度推理,开启思维链以提高复杂研判准确率。", + } + ) + if tier == "fast" and cur_steps < 3 and "query_global_situational" in (llm_node.get("tools") or []): + patches.append( + { + "node_id": llm_node["id"], + "field": "max_steps", + "after": min(4, cur_steps + 1), + "reason": "轻量高速模型适当增加 1 步工具迭代容错空间,避免单轮遗漏事实。", + } + ) + if profile.get("supports_native_search") and not cur_search and any( + t in (llm_node.get("tools") or []) for t in ("web_search", "fetch_source_url") + ): + patches.append( + { + "node_id": llm_node["id"], + "field": "native_web_search", + "after": True, + "reason": f"供应商 {profile.get('provider')} 支持原生联网检索,开启后可协同补充最新一手信源。", + } + ) + if not patches: + base_sys = str(llm_node.get("system_prompt") or "").strip() + model_name = str(profile.get("model") or "当前模型").strip() + tag = f"[模型适配 {model_name}] 请优先依据工具返回的实测数值作答,禁止臆测缺失字段。" + if tag not in base_sys and base_sys: + patches.append( + { + "node_id": llm_node["id"], + "field": "system_prompt", + "after": f"{base_sys}\n{tag}", + "reason": f"针对当前模型({model_name})补强事实边界约束。", + } + ) + summary = f"针对当前模型 {profile.get('model') or profile.get('provider')} 生成自适应调整方案。" + return summary, patches + + inst_lower = instruction.lower() + err_text = " ".join(str(r.get("error_message") or "") + " " + str(r.get("feedback_note") or "") for r in bad_runs).lower() + cur_tools = list(llm_node.get("tools") or []) + if any(k in (inst_lower + " " + err_text) for k in ("search", "搜索", "取证", "证据", "fetch", "url", "事实不准")): + added = [t for t in ("fetch_source_url", "web_search") if t in VALID_TOOL_IDS and t not in cur_tools] + if added: + patches.append( + { + "node_id": llm_node["id"], + "field": "tools", + "after": [*cur_tools, *added], + "reason": "针对取证不足或事实误差问题,补充网页核查工具。", + } + ) + if any(k in (inst_lower + " " + err_text) for k in ("step", "步", "超时", "timeout", "深入", "多轮")): + patches.append( + { + "node_id": llm_node["id"], + "field": "max_steps", + "after": min(6, int(llm_node.get("max_steps") or 2) + 1), + "reason": "放宽最大工具调用步数,提升复杂问题召回率。", + } + ) + unused = [t for t in (health.get("unused_tools") or []) if t in cur_tools] + if not patches and unused and not instruction.strip(): + remaining = [t for t in cur_tools if t not in unused] + if remaining: + patches.append( + { + "node_id": llm_node["id"], + "field": "tools", + "after": remaining, + "reason": f"精简近期零调用的闲置工具({', '.join(unused[:3])}),减少无效上下文干扰。", + } + ) + if not patches: + base_sys = str(llm_node.get("system_prompt") or "").strip() + target_note = instruction.strip() or ( + "先明确区分已核验事实与待查证缺口,不确定的数值或来源须直接说明。" + ) + if target_note not in base_sys and base_sys: + patches.append( + { + "node_id": llm_node["id"], + "field": "system_prompt", + "after": f"{base_sys}\n[调优约束] {target_note}", + "reason": "基于近期负反馈或调优目标加固提示词护栏。", + } + ) + summary = ( + f"已针对「{instruction.strip()}」生成节点调优建议。" + if instruction.strip() + else "已结合近期运行失败/差评与健康度指标生成微调建议。" + ) + return summary, patches + + +async def propose_workflow_evolution( + db: AsyncSession, + workflow_id: str, + *, + mode: str = "optimize", + instruction: str = "", + run_id: str | None = None, + apply_mode: str = "preview", + trigger: str = "manual", + branch_from_best: bool = False, + ai_client: Any = None, + actor: str = "admin", +) -> dict[str, Any]: + """Generate (and optionally draft/auto-publish) a validated workflow evolution patch.""" + await ensure_builtin_workflows(db) + wf = ( + await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == workflow_id)) + ).scalar_one_or_none() + if wf is None: + raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found") + if workflow_id == META_WORKFLOW_ID: + return await propose_meta_evolution( + db, + instruction=instruction, + apply_mode=apply_mode, + trigger="meta_manual" if trigger == "manual" else trigger, + ai_client=ai_client, + actor=actor, + ) + + health = await compute_workflow_health(db, workflow_id, ai_client=ai_client) + parent_revision = int(wf.active_revision or 1) + base_graph = copy.deepcopy(wf.draft_graph or wf.published_graph or {}) + + # Optional DGM archive parent selection + if branch_from_best and health.get("recommended_parent_revision"): + best_rev = int(health["recommended_parent_revision"]) + rev_row = ( + await db.execute( + select(AIWorkflowRevision) + .where(AIWorkflowRevision.workflow_id == workflow_id) + .where(AIWorkflowRevision.revision == best_rev) + ) + ).scalar_one_or_none() + if rev_row is not None and isinstance(rev_row.graph_json, dict): + base_graph = copy.deepcopy(rev_row.graph_json) + parent_revision = best_rev + + # Collect bad/selected run context for GEPA diagnosis + bad_runs_rows = ( + await db.execute( + select(WorkflowRun) + .where(WorkflowRun.workflow_id == workflow_id) + .order_by(desc(WorkflowRun.started_at)) + .limit(40) + ) + ).scalars().all() + selected_run = next((r for r in bad_runs_rows if run_id and r.id == run_id), None) + bad_runs: list[dict[str, Any]] = [] + for r in bad_runs_rows: + rating = _run_rating(r) + if r.status == "failed" or rating == -1: + bu = r.budget_used if isinstance(r.budget_used, dict) else {} + bad_runs.append( + { + "id": r.id, + "status": r.status, + "question": r.question, + "error_message": r.error_message, + "rating": rating, + "feedback_note": bu.get("feedback_note") or "", + "tool_trace": r.tool_trace or [], + "model_used": _run_model(r), + } + ) + if len(bad_runs) >= 6: + break + + # Tier 2 integration: load live published prompts from `meta.workflow_evolver` + diag_node = await resolve_runtime_workflow_node(db, META_WORKFLOW_ID, "diag_node") or {} + patch_node = await resolve_runtime_workflow_node(db, META_WORKFLOW_ID, "patch_node") or {} + meta_wf = ( + await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == META_WORKFLOW_ID)) + ).scalar_one_or_none() + meta_revision = int(meta_wf.active_revision or 1) if meta_wf is not None else 1 + + ledger = await _load_ledger_entries(db) + lessons = _build_aflow_lessons([e for e in ledger if e.get("workflow_id") != META_WORKFLOW_ID]) + + client = ai_client + ai_ready = False + if client is None: + try: + client = await get_ai_provider_client(db) + except Exception: + client = None + if client is not None and hasattr(client, "is_ready"): + try: + ai_ready, _, _ = await client.is_ready() + except Exception: + ai_ready = False + + summary = "" + raw_patches: list[dict[str, Any]] = [] + if ai_ready and client is not None: + schema = { + "type": "object", + "properties": { + "summary": {"type": "string"}, + "node_patches": { + "type": "array", + "items": { + "type": "object", + "properties": { + "node_id": {"type": "string"}, + "field": {"type": "string", "enum": sorted(ALLOWED_NODE_PATCH_FIELDS)}, + "after": {}, + "reason": {"type": "string"}, + }, + "required": ["node_id", "field", "after", "reason"], + }, + }, + }, + "required": ["summary", "node_patches"], + } + diag_sys = str(diag_node.get("system_prompt") or "").strip() + patch_sys = str(patch_node.get("system_prompt") or "").strip() + combined_sys = ( + f"{patch_sys}\n\n[诊断要点]\n{diag_sys}".strip() + or "你是智能星球 AI 工作流架构调优引擎。仅输出严格 JSON:{summary, node_patches}。" + ) + objective = ( + f"进化模式:{mode}(optimize=运行优化 / model_adapt=新模型适配)\n" + f"工作流 ID:{workflow_id}\n" + f"管理员指令:{instruction.strip() or '无额外指定,请结合失败/差评样本与健康度指标主动调优。'}\n" + f"{str(patch_node.get('prompt') or '')}" + ).strip() + req = SituationalAnalysisRequest( + title=f"Evolve workflow {workflow_id}", + objective=objective[:16000], + system_prompt=combined_sys[:8000], + context={ + "workflow_id": workflow_id, + "parent_revision": parent_revision, + "current_graph": base_graph, + "available_tools": [{"id": t["id"], "description": t["description"]} for t in TOOL_CATALOG], + "health_summary": { + k: health[k] + for k in ("total_runs", "success_rate", "avg_latency_ms", "upvotes", "downvotes", "unused_tools", "model_drift_detected", "active_model_profile", "recent_models") + }, + "failed_or_downvoted_runs": bad_runs, + "selected_run": selected_run.to_dict() if selected_run else None, + "aflow_lessons": lessons, + }, + response_format={"type": "json_schema", "json_schema": {"name": "workflow_patch", "schema": schema}}, + ) + try: + resp = await client.analyze(req) + clean_text, _ = strip_thinking_text(str(getattr(resp, "content", "") or "")) + parsed = _extract_first_json_object(clean_text or getattr(resp, "content", "")) + if parsed: + summary = str(parsed.get("summary") or "").strip() + if isinstance(parsed.get("node_patches"), list): + raw_patches = parsed["node_patches"] + except Exception as exc: + logger.warning_event( + "AI evolution proposal failed; using deterministic fallback", + event="ai_evolver.propose.fallback", + context={"workflow_id": workflow_id, "mode": mode, "error": str(exc)}, + ) + + if not raw_patches: + summary, raw_patches = _deterministic_business_patches( + base_graph, + mode=mode, + instruction=instruction, + health=health, + bad_runs=bad_runs, + ) + + proposed_graph, diffs = _apply_validated_node_patches(base_graph, raw_patches) + is_auto_apply = apply_mode == "auto" + constitution_ok, violations = validate_evolution_patch( + base_graph, + proposed_graph, + diffs, + is_meta=False, + is_auto=is_auto_apply, + ) + + applied_status = "preview" + new_revision = None + blocked_reason = "" + ledger_entry: dict[str, Any] | None = None + + if apply_mode == "draft": + if not constitution_ok or not diffs: + applied_status = "blocked" + blocked_reason = ";".join(violations) if violations else "无可应用的有效节点改动" + else: + await save_workflow_draft( + db, + workflow_id, + proposed_graph, + actor=actor if trigger == "manual" else "system:auto_draft", + ) + applied_status = "draft_saved" + ledger_entry = await append_ledger_entry( + db, + { + "workflow_id": workflow_id, + "mode": mode, + "trigger": trigger, + "status": "draft_saved", + "base_revision": parent_revision, + "target_revision": None, + "meta_revision": meta_revision, + "summary": summary, + "changes": diffs, + }, + ) + elif apply_mode == "auto": + policy = health["policy"] + budget_ok, budget_msg = await _check_auto_budget_and_cooldown( + db, + workflow_id, + policy, + is_meta=False, + model_drift=bool(mode == "model_adapt" and health.get("model_drift_detected")), + ) + if not budget_ok: + applied_status = "blocked" + blocked_reason = budget_msg + elif not constitution_ok or not diffs: + applied_status = "blocked" + blocked_reason = ";".join(violations) if violations else "无可应用的有效节点改动" + else: + prev_active_rev = int(wf.active_revision or 1) + published = await publish_workflow( + db, + workflow_id, + graph=proposed_graph, + change_summary=f"[Auto-Evolve/{mode}] {summary[:120]}", + actor="system:auto_evolver", + ) + applied_status = "auto_published" + new_revision = int(published.get("active_revision") or (prev_active_rev + 1)) + ledger_entry = await append_ledger_entry( + db, + { + "workflow_id": workflow_id, + "mode": mode, + "trigger": trigger, + "status": "canary", + "base_revision": prev_active_rev, + "target_revision": new_revision, + "parent_revision": parent_revision, + "meta_revision": meta_revision, + "canary_runs_target": CANARY_OBSERVATION_RUNS, + "baseline_failure_rate": health["failure_rate"], + "summary": summary, + "changes": diffs, + }, + ) + if applied_status == "blocked": + ledger_entry = await append_ledger_entry( + db, + { + "workflow_id": workflow_id, + "mode": mode, + "trigger": trigger, + "status": "blocked", + "base_revision": int(wf.active_revision or 1), + "meta_revision": meta_revision, + "summary": summary or f"{mode} blocked", + "rollback_reason": blocked_reason, + "changes": diffs, + }, + ) + + return { + "workflow_id": workflow_id, + "mode": mode, + "base_revision": parent_revision, + "meta_revision": meta_revision, + "summary": summary or "暂无需要变更的字段。", + "changes": diffs, + "proposed_graph": proposed_graph, + "constitution_ok": constitution_ok, + "violations": violations, + "applied_status": applied_status, + "new_revision": new_revision, + "blocked_reason": blocked_reason, + "ledger_entry": ledger_entry, + "health": health, + } + + +# --------------------------------------------------------------------------- +# Fixture A/B Evaluation Helper +# --------------------------------------------------------------------------- + + +async def _run_graph_single_sample( + *, + db: AsyncSession, + workflow: dict[str, Any], + graph: dict[str, Any], + question: str, + earth_context: dict[str, Any], + ai_client: Any, +) -> dict[str, Any]: + started = _utc_now() + test_wf = { + **workflow, + "published_graph": graph, + "draft_graph": graph, + } + answer = "" + err = "" + nodes_done: list[str] = [] + try: + async for ev in run_workflow_dag_stream( + db=db, + workflow=test_wf, + question=question, + use_draft=True, + earth_context=earth_context, + ai_client=ai_client, + allow_external_tools=False, + ): + ev_name = str(ev.get("event") or "") + ev_data = ev.get("data") if isinstance(ev.get("data"), dict) else {} + if ev_name == "done": + answer = str(ev_data.get("answer_markdown") or "") + nodes_done = [str(x) for x in (ev_data.get("nodes") or [])] + elif ev_name == "error": + err = str(ev_data.get("message") or "DAG error") + except Exception as exc: + err = str(exc) + + latency_ms = max(0, int((_utc_now() - started).total_seconds() * 1000)) + return { + "ok": bool(answer.strip()) and not err, + "latency_ms": latency_ms, + "answer_length": len(answer.strip()), + "nodes": nodes_done, + "error": err, + } + + +async def run_fixture_ab_eval( + db: AsyncSession, + workflow_id: str, + proposed_graph: dict[str, Any], + *, + max_fixtures: int = 3, + evaluator_id: str = "fixture_ab", +) -> dict[str, Any]: + await ensure_builtin_workflows(db) + wf = ( + await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == workflow_id)) + ).scalar_one_or_none() + if wf is None: + raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found") + + evaluator = EVALUATORS.get(evaluator_id) + if evaluator is None: + raise HTTPException(status_code=400, detail=f"Unknown evaluator '{evaluator_id}'") + + validated_proposed = _validate_graph_payload(proposed_graph) + base_graph = copy.deepcopy(wf.published_graph or {}) + return await evaluator.evaluate( + db, + wf.to_dict(), + base_graph, + validated_proposed, + max_fixtures=max_fixtures, + ) + + +# --------------------------------------------------------------------------- +# Workflow Incubation from Frequent `default.general` Usage +# --------------------------------------------------------------------------- + +_INCUBATION_CLUSTERS: list[dict[str, Any]] = [ + { + "slug": "bgp_route_audit", + "keywords": ("bgp", "asn", "路由", "劫持", "泄漏", "前缀"), + "name": "BGP 路由异常专项排查", + "name_en": "BGP Route Anomaly Investigation", + "description": "针对高频 BGP/ASN 路由异常问询孵化:自动拉取 BGP 事故与全球态势快照进行核查。", + "description_en": "Incubated from frequent BGP/ASN queries with deterministic incident & anomaly tools.", + "tools": ["query_bgp_incidents", "query_global_situational"], + "entity_types": ["bgp", "bgp_collector"], + }, + { + "slug": "subsea_cable_watch", + "keywords": ("海缆", "光缆", "登陆站", "cable", "landing", "中断"), + "name": "海缆与登陆站韧性研判", + "name_en": "Subsea Cable Resilience Advisor", + "description": "针对高频海底光缆与登陆站拓扑问询孵化:串联海缆拓扑与船舶近邻工具。", + "description_en": "Incubated from frequent subsea cable questions combining cable and AIS vessel tools.", + "tools": ["query_cable_posture", "query_vessel_posture"], + "entity_types": ["cable", "landing_point"], + }, + { + "slug": "compute_cluster_compare", + "keywords": ("算力", "超算", "gpu", "数据中心", "cluster", "compute", "rpi"), + "name": "全球算力集群对比专题", + "name_en": "Compute Cluster Benchmark Advisor", + "description": "针对高频算力与集群规模对比问询孵化:预载算力多口径指标与新闻态势。", + "description_en": "Incubated from frequent compute cluster queries using multi-metric & news tools.", + "tools": ["query_compute_posture", "query_recent_earth_news"], + "entity_types": ["supercomputer", "gpu_cluster", "data_center", "compute_region"], + }, + { + "slug": "satellite_orbit_brief", + "keywords": ("卫星", "星链", "轨道", "satellite", "starlink", "orbit"), + "name": "在轨卫星星座态势跟踪", + "name_en": "Satellite Constellation Brief", + "description": "针对高频卫星与星座覆蓋问询孵化:自动结合卫星轨道工具进行专项推演。", + "description_en": "Incubated from frequent satellite questions with orbital telemetry lookup.", + "tools": ["query_satellite_posture", "query_global_situational"], + "entity_types": ["satellite"], + }, +] + + +async def incubate_workflow_from_runs( + db: AsyncSession, + *, + ai_client: Any = None, +) -> dict[str, Any]: + """Discover frequent unspecialized `default.general` intents and propose a custom workflow draft.""" + await ensure_builtin_workflows(db) + cutoff = _utc_now() - timedelta(days=30) + runs = ( + await db.execute( + select(WorkflowRun) + .where(WorkflowRun.workflow_id == "default.general") + .order_by(desc(WorkflowRun.started_at)) + .limit(120) + ) + ).scalars().all() + recent = [ + r for r in runs + if (_ensure_utc(r.started_at) or _utc_now()) >= cutoff and str(r.question or "").strip() + ] + + # Pick dominant cluster deterministically first + cluster_hits: Counter[str] = Counter() + cluster_samples: dict[str, list[str]] = {} + for r in recent: + q = str(r.question or "").strip() + ql = q.lower() + for cl in _INCUBATION_CLUSTERS: + if any(kw in ql for kw in cl["keywords"]): + cluster_hits[cl["slug"]] += 1 + cluster_samples.setdefault(cl["slug"], []) + if q not in cluster_samples[cl["slug"]] and len(cluster_samples[cl["slug"]]) < 5: + cluster_samples[cl["slug"]].append(q[:140]) + + selected_cluster = _INCUBATION_CLUSTERS[0] + if cluster_hits: + top_slug, _ = cluster_hits.most_common(1)[0] + selected_cluster = next(c for c in _INCUBATION_CLUSTERS if c["slug"] == top_slug) + sample_questions = cluster_samples.get(selected_cluster["slug"], []) or [ + str(r.question or "")[:140] for r in recent[:4] if str(r.question or "").strip() + ] + + slug = f"{selected_cluster['slug']}_{uuid4().hex[:4]}" + candidate: dict[str, Any] = { + "suggested_workflow_id": f"custom.{slug}", + "name": selected_cluster["name"], + "name_en": selected_cluster["name_en"], + "description": selected_cluster["description"], + "description_en": selected_cluster["description_en"], + "tools": [t for t in selected_cluster["tools"] if t in VALID_TOOL_IDS], + "entity_types": selected_cluster["entity_types"], + "sample_questions": sample_questions, + "observed_runs_analyzed": len(recent), + "rationale": ( + f"在近期 {len(recent)} 条通用参谋记录中识别到高频专项需求,建议沉淀为独立可调优工作流。" + if recent + else "基于系统核心态势领域生成标准专项工作流模板,可直接微调后创建。" + ), + } + + # Enrich via AI if ready + client = ai_client + ai_ready = False + if client is None: + try: + client = await get_ai_provider_client(db) + except Exception: + client = None + if client is not None and hasattr(client, "is_ready"): + try: + ai_ready, _, _ = await client.is_ready() + except Exception: + ai_ready = False + + if ai_ready and client is not None and len(recent) >= 4: + schema = { + "type": "object", + "properties": { + "name": {"type": "string"}, + "name_en": {"type": "string"}, + "description": {"type": "string"}, + "tools": {"type": "array", "items": {"type": "string"}}, + "system_prompt": {"type": "string"}, + "prompt": {"type": "string"}, + "rationale": {"type": "string"}, + }, + "required": ["name", "tools", "system_prompt", "prompt", "rationale"], + } + req = SituationalAnalysisRequest( + title="Incubate new AI workflow", + objective="请从以下高频通用参谋提问中提炼 1 个最具复用价值的专项工作流方案,输出严格 JSON。", + system_prompt="你是智能星球 AI 工作流架构师。仅输出符合 JSON schema 的专项工作流方案,tools 仅限白名单 ID。", + context={ + "recent_questions": [str(r.question or "")[:160] for r in recent[:25]], + "available_tools": [{"id": t["id"], "description": t["description"]} for t in TOOL_CATALOG], + }, + response_format={"type": "json_schema", "json_schema": {"name": "incubated_workflow", "schema": schema}}, + ) + try: + resp = await client.analyze(req) + clean_text, _ = strip_thinking_text(str(getattr(resp, "content", "") or "")) + parsed = _extract_first_json_object(clean_text or getattr(resp, "content", "")) + if parsed and str(parsed.get("name") or "").strip(): + valid_tools = [str(t).strip() for t in (parsed.get("tools") or []) if str(t).strip() in VALID_TOOL_IDS] + if valid_tools: + candidate["tools"] = valid_tools[:4] + candidate["name"] = str(parsed["name"]).strip()[:120] + if parsed.get("name_en"): + candidate["name_en"] = str(parsed["name_en"]).strip()[:120] + if parsed.get("description"): + candidate["description"] = str(parsed["description"]).strip()[:500] + if parsed.get("rationale"): + candidate["rationale"] = str(parsed["rationale"]).strip()[:500] + if parsed.get("system_prompt"): + candidate["_custom_system_prompt"] = str(parsed["system_prompt"]).strip()[:2000] + if parsed.get("prompt"): + candidate["_custom_prompt"] = str(parsed["prompt"]).strip()[:2000] + except Exception as exc: + logger.warning_event( + "AI workflow incubation failed; using deterministic cluster template", + event="ai_evolver.incubate.fallback", + context={"error": str(exc)}, + ) + + graph = build_starter_workflow_graph(candidate["name"]) + for node in graph.get("nodes") or []: + if isinstance(node, dict) and node.get("node_type") == "llm_agent": + node["tools"] = candidate["tools"] or ["query_global_situational"] + if candidate.get("_custom_system_prompt"): + node["system_prompt"] = candidate["_custom_system_prompt"] + if candidate.get("_custom_prompt"): + node["prompt"] = candidate["_custom_prompt"] + + candidate["graph"] = _validate_graph_payload(graph) + candidate["bindings"] = { + "enabled": False, + "surfaces": ["copilot_quick"], + "entity_types": candidate["entity_types"], + "action_label": candidate["name"][:24], + "action_label_en": candidate["name_en"][:32], + } + candidate.pop("_custom_system_prompt", None) + candidate.pop("_custom_prompt", None) + return candidate + + +# --------------------------------------------------------------------------- +# Tier 2: Meta-Evolution (Self-Bootstrapping of `meta.workflow_evolver`) +# --------------------------------------------------------------------------- + + +async def propose_meta_evolution( + db: AsyncSession, + *, + instruction: str = "", + apply_mode: str = "preview", + trigger: str = "meta_manual", + ai_client: Any = None, + actor: str = "admin", +) -> dict[str, Any]: + """Evolve `meta.workflow_evolver` prompts from objective evolution ledger outcomes.""" + await ensure_builtin_workflows(db) + meta_wf = ( + await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == META_WORKFLOW_ID)) + ).scalar_one_or_none() + if meta_wf is None: + raise HTTPException(status_code=404, detail=f"Workflow '{META_WORKFLOW_ID}' not found") + + base_graph = copy.deepcopy(meta_wf.draft_graph or meta_wf.published_graph or {}) + ledger = await _load_ledger_entries(db) + outcomes = [ + e + for e in ledger + if e.get("workflow_id") != META_WORKFLOW_ID + and e.get("status") in {"verified", "rolled_back", "dismissed"} + ] + verified_count = sum(1 for e in outcomes if e.get("status") == "verified") + rollback_count = sum(1 for e in outcomes if e.get("status") == "rolled_back") + dismissed_count = sum(1 for e in outcomes if e.get("status") == "dismissed") + + client = ai_client + ai_ready = False + if client is None: + try: + client = await get_ai_provider_client(db) + except Exception: + client = None + if client is not None and hasattr(client, "is_ready"): + try: + ai_ready, _, _ = await client.is_ready() + except Exception: + ai_ready = False + + summary = "" + raw_patches: list[dict[str, Any]] = [] + if ai_ready and client is not None: + schema = { + "type": "object", + "properties": { + "summary": {"type": "string"}, + "node_patches": { + "type": "array", + "items": { + "type": "object", + "properties": { + "node_id": {"type": "string", "enum": ["diag_node", "patch_node"]}, + "field": {"type": "string", "enum": ["system_prompt", "prompt", "thinking_enabled"]}, + "after": {}, + "reason": {"type": "string"}, + }, + "required": ["node_id", "field", "after", "reason"], + }, + }, + }, + "required": ["summary", "node_patches"], + } + req = SituationalAnalysisRequest( + title="Meta-evolve workflow evolver", + objective=( + f"管理员指示:{instruction.strip() or '基于进化台账中已验证与被回滚/忽略的案例,优化元引擎诊断与补丁合成精度。'}\n" + "仅允许修改 `diag_node` 或 `patch_node` 的提示词或 thinking_enabled;" + "严禁修改 `verify_output`,且 `patch_node` 必须保留 JSON `node_patches` 输出要求。" + ), + system_prompt="你是智能星球 AI 元进化策略师。仅输出严格 JSON:{summary, node_patches}。", + context={ + "meta_graph": base_graph, + "outcome_counts": { + "verified": verified_count, + "rolled_back": rollback_count, + "dismissed": dismissed_count, + }, + "lessons": _build_aflow_lessons(outcomes), + }, + response_format={"type": "json_schema", "json_schema": {"name": "meta_patch", "schema": schema}}, + ) + try: + resp = await client.analyze(req) + clean_text, _ = strip_thinking_text(str(getattr(resp, "content", "") or "")) + parsed = _extract_first_json_object(clean_text or getattr(resp, "content", "")) + if parsed: + summary = str(parsed.get("summary") or "").strip() + if isinstance(parsed.get("node_patches"), list): + raw_patches = parsed["node_patches"] + except Exception as exc: + logger.warning_event( + "AI meta-evolution request failed; using deterministic prompt refinement", + event="ai_evolver.meta.fallback", + context={"error": str(exc)}, + ) + + if not raw_patches: + target_node = next( + (n for n in (base_graph.get("nodes") or []) if n.get("id") == "patch_node"), + None, + ) + if target_node is not None: + base_sys = str(target_node.get("system_prompt") or "").strip() + if instruction.strip(): + clause = f"[元进化规则] {instruction.strip()}" + elif rollback_count > verified_count: + clause = ( + f"[元进化反思 · 历史回滚 {rollback_count} 次] 当近期存在回滚案例时," + "优先只调整单一高置信度字段(如 tools 或 max_steps),避免大段重写提示词。" + ) + else: + clause = ( + f"[元进化策略] 参考近 {len(outcomes)} 次进化台账结果,优先强化工具核验与模型能力边界说明。" + ) + if clause not in base_sys: + raw_patches.append( + { + "node_id": "patch_node", + "field": "system_prompt", + "after": f"{base_sys}\n{clause}".strip(), + "reason": "结合进化台账正负结果收敛补丁生成保守度与精准度。", + } + ) + summary = summary or ( + f"基于 {len(outcomes)} 条进化台账记录(验证有效 {verified_count},回滚 {rollback_count},忽略 {dismissed_count})生成元引擎自举方案。" + ) + + proposed_graph, diffs = _apply_validated_node_patches(base_graph, raw_patches) + is_auto_apply = apply_mode == "auto" + constitution_ok, violations = validate_evolution_patch( + base_graph, + proposed_graph, + diffs, + is_meta=True, + is_auto=is_auto_apply, + ) + + applied_status = "preview" + new_revision = None + blocked_reason = "" + ledger_entry: dict[str, Any] | None = None + policy = await get_evolution_policy(db) + + if apply_mode == "draft": + if not constitution_ok or not diffs: + applied_status = "blocked" + blocked_reason = ";".join(violations) if violations else "无可应用的元引擎改动" + else: + await save_workflow_draft( + db, + META_WORKFLOW_ID, + proposed_graph, + actor=actor if trigger == "meta_manual" else "system:meta_draft", + ) + applied_status = "draft_saved" + ledger_entry = await append_ledger_entry( + db, + { + "workflow_id": META_WORKFLOW_ID, + "mode": "meta", + "trigger": trigger, + "status": "draft_saved", + "base_revision": int(meta_wf.active_revision or 1), + "target_revision": None, + "summary": summary, + "changes": diffs, + }, + ) + elif apply_mode == "auto": + budget_ok, budget_msg = await _check_auto_budget_and_cooldown( + db, + META_WORKFLOW_ID, + policy, + is_meta=True, + ) + if policy.get("meta_mode") != "auto" and trigger != "meta_manual": + budget_ok = False + budget_msg = "元进化自动发布开关未开启" + elif trigger == "meta_auto" and len(outcomes) < MIN_LEDGER_OUTCOMES_FOR_META: + budget_ok = False + budget_msg = f"自动元进化至少需要 {MIN_LEDGER_OUTCOMES_FOR_META} 条业务进化结果(当前 {len(outcomes)} 条)" + + if not budget_ok: + applied_status = "blocked" + blocked_reason = budget_msg + elif not constitution_ok or not diffs: + applied_status = "blocked" + blocked_reason = ";".join(violations) if violations else "无可应用的元引擎改动" + else: + prev_rev = int(meta_wf.active_revision or 1) + published = await publish_workflow( + db, + META_WORKFLOW_ID, + graph=proposed_graph, + change_summary=f"[Meta-Evolve] {summary[:120]}", + actor="system:meta_evolver" if trigger != "meta_manual" else actor, + ) + applied_status = "auto_published" + new_revision = int(published.get("active_revision") or (prev_rev + 1)) + ledger_entry = await append_ledger_entry( + db, + { + "workflow_id": META_WORKFLOW_ID, + "mode": "meta", + "trigger": trigger, + "status": "canary", + "base_revision": prev_rev, + "target_revision": new_revision, + "canary_runs_target": META_CANARY_WINDOW, + "summary": summary, + "changes": diffs, + }, + ) + + return { + "workflow_id": META_WORKFLOW_ID, + "mode": "meta", + "base_revision": int(meta_wf.active_revision or 1), + "summary": summary, + "changes": diffs, + "proposed_graph": proposed_graph, + "constitution_ok": constitution_ok, + "violations": violations, + "applied_status": applied_status, + "new_revision": new_revision, + "blocked_reason": blocked_reason, + "ledger_entry": ledger_entry, + "outcomes_analyzed": len(outcomes), + } + + +# --------------------------------------------------------------------------- +# Non-Blocking Post-Run Hook +# --------------------------------------------------------------------------- + + +async def _post_run_evolution_worker(workflow_id: str, run_id: str) -> None: + try: + async with async_session_factory() as db: + canary_res = await evaluate_canary_and_maybe_rollback(db, workflow_id) + if canary_res and canary_res.get("action") == "rolled_back": + return + + policy = await get_evolution_policy(db) + biz_mode = str(policy.get("business_mode") or "off") + if biz_mode in {"draft", "auto"} and workflow_id not in set(policy.get("locked_workflows") or []): + health = await compute_workflow_health(db, workflow_id) + signals = health.get("signals") or [] + total_runs = int(health.get("total_runs") or 0) + drift = bool(health.get("model_drift_detected") and policy.get("auto_adapt_on_model_change", True)) + has_degradation = any(s.get("severity") in {"warn", "critical"} for s in signals) + + target_mode: str | None = None + if drift: + target_mode = "model_adapt" + elif has_degradation and total_runs >= MIN_RUNS_FOR_AUTO: + target_mode = "optimize" + + if target_mode: + budget_ok, _ = await _check_auto_budget_and_cooldown( + db, + workflow_id, + policy, + is_meta=False, + model_drift=(target_mode == "model_adapt"), + ) + if budget_ok: + await propose_workflow_evolution( + db, + workflow_id, + mode=target_mode, + run_id=run_id, + apply_mode=biz_mode, + trigger="auto_post_run", + branch_from_best=bool(health.get("recommended_parent_revision")), + actor="system:auto_evolver", + ) + + meta_mode = str(policy.get("meta_mode") or "off") + if meta_mode in {"draft", "auto"}: + meta_ok, _ = await _check_auto_budget_and_cooldown( + db, + META_WORKFLOW_ID, + policy, + is_meta=True, + ) + if meta_ok: + await propose_meta_evolution( + db, + apply_mode=meta_mode, + trigger="meta_auto", + actor="system:meta_evolver", + ) + except Exception as exc: + logger.warning_event( + "Background workflow post-run evolution check failed", + event="ai_evolver.post_run.failed", + context={"workflow_id": workflow_id, "run_id": run_id, "error": str(exc)}, + ) + finally: + _PENDING_BG_WORKFLOWS.discard(workflow_id) + + +def schedule_post_run_evolution(workflow_id: str, run_id: str) -> None: + """Schedule non-blocking post-run canary check & gated auto-evolution.""" + if not workflow_id or workflow_id == META_WORKFLOW_ID: + return + if os.getenv("PLANET_DISABLE_BG_EVOLUTION") == "1" or os.getenv("PYTEST_CURRENT_TEST"): + return + if workflow_id in _PENDING_BG_WORKFLOWS: + return + try: + loop = asyncio.get_running_loop() + except RuntimeError: + return + _PENDING_BG_WORKFLOWS.add(workflow_id) + loop.create_task(_post_run_evolution_worker(workflow_id, run_id)) diff --git a/backend/app/services/ai/workflow_registry.py b/backend/app/services/ai/workflow_registry.py index 4ab13fa0..b781ad99 100644 --- a/backend/app/services/ai/workflow_registry.py +++ b/backend/app/services/ai/workflow_registry.py @@ -2,15 +2,17 @@ from __future__ import annotations +from collections import deque import copy from datetime import UTC, datetime import inspect import json import re from typing import Any +from uuid import uuid4 from fastapi import HTTPException, status -from sqlalchemy import desc, select +from sqlalchemy import delete, desc, select from sqlalchemy.ext.asyncio import AsyncSession from app.core.logging import get_logger @@ -137,6 +139,120 @@ TOOL_CATALOG: list[dict[str, Any]] = [ ] VALID_TOOL_IDS: frozenset[str] = frozenset(item["id"] for item in TOOL_CATALOG) +MAX_WORKFLOW_NODES = 12 +VALID_NODE_TYPES: frozenset[str] = frozenset( + {"trigger", "deterministic", "llm_agent", "guardrail", "output"} +) +VALID_EDGE_CONDITIONS: frozenset[str] = frozenset( + {"always", "on_empty_or_low_confidence", "on_entity_type"} +) +PRESERVED_BUILTIN_EDGE_CONDITIONS: frozenset[str] = frozenset( + {"not_terminal", "high_confidence_hit", "fallback_to_agent", "ingest", "interactive"} +) +ALLOWED_EDGE_CONDITIONS: frozenset[str] = VALID_EDGE_CONDITIONS | PRESERVED_BUILTIN_EDGE_CONDITIONS + +EARTH_ENTITY_TYPES: list[dict[str, str]] = [ + {"id": "cable", "name": "海底光缆", "name_en": "Subsea Cable", "group": "infrastructure"}, + {"id": "landing_point", "name": "海缆登陆站", "name_en": "Landing Point", "group": "infrastructure"}, + {"id": "satellite", "name": "在轨卫星", "name_en": "Satellite", "group": "infrastructure"}, + {"id": "vessel", "name": "AIS 船舶", "name_en": "AIS Vessel", "group": "infrastructure"}, + {"id": "bgp", "name": "BGP 异常事件", "name_en": "BGP Incident", "group": "infrastructure"}, + {"id": "bgp_collector", "name": "BGP 观测站", "name_en": "BGP Collector", "group": "infrastructure"}, + {"id": "supercomputer", "name": "超级计算机", "name_en": "Supercomputer", "group": "compute"}, + {"id": "gpu_cluster", "name": "GPU 集群", "name_en": "GPU Cluster", "group": "compute"}, + {"id": "data_center", "name": "数据中心", "name_en": "Data Center", "group": "compute"}, + {"id": "cloud_center", "name": "云计算中心", "name_en": "Cloud Center", "group": "compute"}, + {"id": "edge_node", "name": "边缘计算节点", "name_en": "Edge Node", "group": "compute"}, + {"id": "compute_center_unresolved", "name": "待定位算力设施", "name_en": "Unresolved Compute Site", "group": "compute"}, + {"id": "news", "name": "全球态势新闻", "name_en": "Earth News", "group": "content"}, + {"id": "compute_region", "name": "国家/区域算力卡片", "name_en": "Compute Region Card", "group": "content"}, + {"id": "viewport", "name": "当前地球视口与图层", "name_en": "Current Earth Viewport", "group": "content"}, + {"id": "global", "name": "全球综合态势", "name_en": "Global Posture", "group": "content"}, + {"id": "earth_interactable", "name": "自定义交互点", "name_en": "Custom Interactable", "group": "custom"}, +] + +EARTH_SURFACES: list[dict[str, str]] = [ + {"id": "info_card", "name": "地球信息卡顶栏", "name_en": "Earth Info Card"}, + {"id": "news_card", "name": "新闻与区域新闻卡", "name_en": "News & Region Cards"}, + {"id": "topic_card", "name": "算力专题区域卡", "name_en": "Compute Topic Card"}, + {"id": "copilot_quick", "name": "AI 参谋快捷入口", "name_en": "Copilot Quick Actions"}, + {"id": "multi_select", "name": "多物件联合对比栏", "name_en": "Multi-Target Compare Tray"}, +] + +VALID_ENTITY_TYPE_IDS: frozenset[str] = frozenset(item["id"] for item in EARTH_ENTITY_TYPES) +VALID_SURFACE_IDS: frozenset[str] = frozenset(item["id"] for item in EARTH_SURFACES) +MATERIAL_ICON_RE = re.compile(r"^[a-z0-9_]{1,40}$") +WORKFLOW_ID_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{1,78}$") + + +def normalize_bindings(raw: dict[str, Any] | None) -> dict[str, Any]: + """Normalize declarative Earth interaction bindings with strict whitelists.""" + if not isinstance(raw, dict) or not raw: + return { + "enabled": False, + "surfaces": [], + "entity_types": [], + "interactable_kinds": [], + "min_targets": 1, + "max_targets": 5, + "action_label": "", + "action_label_en": "", + "icon": "forum", + "prompt_template": "", + "priority": 0, + } + + surfaces: list[str] = [] + for s in raw.get("surfaces") or []: + sid = str(s or "").strip() + if sid in VALID_SURFACE_IDS and sid not in surfaces: + surfaces.append(sid) + + entity_types: list[str] = [] + for e in raw.get("entity_types") or []: + eid = str(e or "").strip() + if eid in VALID_ENTITY_TYPE_IDS and eid not in entity_types: + entity_types.append(eid) + + interactable_kinds: list[str] = [] + for k in raw.get("interactable_kinds") or []: + kid = str(k or "").strip()[:60] + if kid and kid not in interactable_kinds: + interactable_kinds.append(kid) + if len(interactable_kinds) >= 20: + break + + try: + min_targets = max(1, min(int(raw.get("min_targets") or 1), 5)) + except (TypeError, ValueError): + min_targets = 1 + try: + max_targets = max(min_targets, min(int(raw.get("max_targets") or 5), 8)) + except (TypeError, ValueError): + max_targets = max(min_targets, 5) + try: + priority = max(-100, min(int(raw.get("priority") or 0), 100)) + except (TypeError, ValueError): + priority = 0 + + icon_raw = str(raw.get("icon") or "forum").strip() + icon = icon_raw if MATERIAL_ICON_RE.match(icon_raw) else "forum" + + return { + "enabled": bool(raw.get("enabled", False)), + "surfaces": surfaces, + "entity_types": entity_types, + "interactable_kinds": interactable_kinds, + "min_targets": min_targets, + "max_targets": max_targets, + "action_label": str(raw.get("action_label") or "").strip()[:48], + "action_label_en": str(raw.get("action_label_en") or "").strip()[:64], + "icon": icon, + "prompt_template": str(raw.get("prompt_template") or "").strip()[:1000], + "priority": priority, + } + + ALLOWED_NODE_PATCH_FIELDS: frozenset[str] = frozenset( { "enabled", @@ -206,6 +322,7 @@ def _edge( label: str = "", label_en: str = "", condition: str = "always", + condition_value: str = "", ) -> dict[str, Any]: return { "id": edge_id, @@ -214,6 +331,7 @@ def _edge( "label": label, "label_en": label_en or label, "condition": condition, + "condition_value": condition_value, } @@ -226,6 +344,30 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "description": "Playground 默认选项与地球通用追问入口,支持按需挂载五域只读数据与外部搜索。", "description_en": "Default Playground and general Earth Copilot flow with read-only telemetry and optional web search.", "is_default": True, + "bindings": { + "enabled": True, + "surfaces": ["copilot_quick", "info_card", "multi_select"], + "entity_types": [ + "global", + "viewport", + "cable", + "landing_point", + "satellite", + "vessel", + "bgp", + "bgp_collector", + "supercomputer", + "gpu_cluster", + "data_center", + "cloud_center", + "edge_node", + "earth_interactable", + ], + "action_label": "AI 参谋分析", + "action_label_en": "Analyze in AI Copilot", + "icon": "forum", + "priority": 0, + }, "graph": { "nodes": [ _node( @@ -234,7 +376,7 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "入口:问题与本地上下文接收", "Trigger: Query & Context", 40, - 120, + 140, description="接收用户提问、聚焦实体/新闻与客户端本地记忆备忘。", ), _node( @@ -242,8 +384,8 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "deterministic", "只读遥测快照装配", "Telemetry Snapshot", - 320, - 120, + 420, + 140, description="零额外费用装配五域结构化现状与近期新闻索引。", tools=["query_global_situational", "query_recent_earth_news"], ), @@ -252,8 +394,8 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "llm_agent", "AI 参谋推理与研判", "Advisor Reasoning", - 620, - 120, + 800, + 140, description="结合本地记忆与系统遥测输出结构化研判;区分事实与推演。", prompt_key="situational.copilot.reply", system_prompt="你是智能星球(Planet)首席态势参谋。仅基于传入事实与工具证据作答,严谨区分确认事实、概率推断与待核验缺口。", @@ -268,8 +410,8 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "output", "SSE 流式响应输出", "SSE Output", - 920, - 120, + 1180, + 140, description="推送思考过程与正文,并附带本次节点运行轨迹。", ), ], @@ -288,6 +430,15 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "description": "整合 builds_upon 继承、Wikidata、PeeringDB、可控 Tool-Calling 取证与地理编码硬校验的完整定位管线。", "description_en": "Tiered facility geolocation combining builds_upon, Wikidata, PeeringDB, controlled tool-calling evidence, and geocoder verification.", "is_default": False, + "bindings": { + "enabled": True, + "surfaces": ["info_card"], + "entity_types": ["compute_center_unresolved"], + "action_label": "AI 坐标定位核验", + "action_label_en": "Verify Coordinates", + "icon": "location_searching", + "priority": 25, + }, "graph": { "nodes": [ _node( @@ -296,7 +447,7 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "L0:实体归一化与终态短路", "L0: Normalize & Terminal Check", 40, - 140, + 160, description="切分 name_short、注入 Epoch Source 1..5/TOP500 一手链接与 builds_upon,若已标记 undisclosed/multi_site 则直接短路。", params={"short_circuit_terminal_statuses": True}, ), @@ -305,8 +456,8 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "deterministic", "L1:确定性设施知识库查询", "L1: Knowledge Resolvers", - 320, - 60, + 420, + 160, description="依次匹配 builds_upon 继承、Wikidata P625、PeeringDB /api/fac 及带商业云过滤的 ROR。", tools=["builds_upon_inherit", "wikidata_lookup", "peeringdb_fac_lookup", "ror_lookup"], params={"allow_low_confidence_short_circuit": False, "wikidata_enabled": True, "peeringdb_enabled": True}, @@ -316,8 +467,8 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "llm_agent", "L2:多步 Tool-Calling 取证 Agent", "L2: Tool-Calling Evidence Agent", - 320, - 250, + 800, + 300, description="优先读取一手 source_url/Source 1..5,必要时多轮改写短查询搜索并调用 geocode_verify 落点。", prompt_key="location.factcheck.resolve", system_prompt="你是基础设施物理位置核查 Agent。严禁直接猜测或编造经纬度!必须先通过 fetch_source_url(优先使用元数据自带一手链接)或 web_search 找到物理设施/园区地址证据,再调用 geocode_verify 获取候选坐标 ID,最后调用 submit_location_result 提交结果。若确认为跨地域多站点或未披露地址,提交 multi_site 或 undisclosed。", @@ -333,8 +484,8 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "guardrail", "L3:国家边界硬校验与证据核验", "L3: Geo Boundary Guardrail", - 640, - 140, + 1180, + 160, description="强制校验经纬度范围、国家匹配一致性、引用 URL 真实性及城市级回退降级。", guardrails={"min_confidence": 0.55, "enforce_country_match": True, "require_tool_cited_urls": True, "downgrade_geocoded_site_to_city": True}, ), @@ -343,8 +494,8 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "output", "L4:候选输出或终态落库", "L4: Candidate / Terminal State", - 940, - 140, + 1560, + 160, description="返回高可信待确认候选坐标,或写入 undisclosed/multi_site/anonymous 防重复消耗。", ), ], @@ -365,16 +516,25 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "description": "涵盖前台点击新闻卡触发的流式局势分析,以及后台 RSS 入库汉化定位任务。", "description_en": "Powers interactive news deep-dive streaming on Earth and background RSS enrichment/localization.", "is_default": False, + "bindings": { + "enabled": True, + "surfaces": ["news_card", "info_card", "copilot_quick"], + "entity_types": ["news"], + "action_label": "新闻深度研判", + "action_label_en": "Deep News Analysis", + "icon": "forum", + "priority": 20, + }, "graph": { "nodes": [ - _node("news_trigger", "trigger", "入口:聚焦新闻或 RSS 条目", "Trigger: News Context", 40, 140), + _node("news_trigger", "trigger", "入口:聚焦新闻或 RSS 条目", "Trigger: News Context", 40, 160), _node( "news_enrich_node", "llm_agent", "RSS 汉化与物理落点 (入库)", "Background RSS Enrichment", - 340, - 60, + 430, + 40, prompt_key="earth.news.enrich", system_prompt="", prompt="Return exactly one strict JSON object with a location object and a localizations object. Infer the most likely physical event location and produce a faithful Simplified Chinese title plus a one-sentence newswire-style Chinese summary based only on the supplied RSS headline, description, source, and date.", @@ -387,8 +547,8 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "llm_agent", "新闻深度局势研判 (前台流式)", "Interactive News Analysis", - 340, - 240, + 430, + 280, prompt_key="earth.news.analysis", system_prompt="你是智能星球的全球新闻与地缘基础设施分析师。严谨区分已报道事实与推演研判,禁止虚构未报道数据。", prompt="围绕聚焦新闻输出:1) 核心事实与背景;2) 对算力/海缆/航运/航天及地缘格局的影响;3) 后续观察信号与不确定边界。", @@ -397,7 +557,7 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ max_steps=2, timeout_seconds=60, ), - _node("news_output", "output", "新闻分析 / 汉化结构输出", "Output Result", 680, 140), + _node("news_output", "output", "新闻分析 / 汉化结构输出", "Output Result", 840, 160), ], "edges": [ _edge("nw-e1", "news_trigger", "news_enrich_node", "后台采集汉化", "Ingest enrich", "ingest"), @@ -415,16 +575,32 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "description": "负责中美及全球算力对比、双边 RPI 归因推演及报告候选观测值提取。", "description_en": "Drives bilateral/global compute comparison analysis, RPI attribution, and report evidence extraction.", "is_default": False, + "bindings": { + "enabled": True, + "surfaces": ["topic_card", "info_card", "multi_select", "copilot_quick"], + "entity_types": [ + "compute_region", + "supercomputer", + "gpu_cluster", + "data_center", + "cloud_center", + "edge_node", + ], + "action_label": "算力战略对比推演", + "action_label_en": "Compute Strategy Comparison", + "icon": "query_stats", + "priority": 15, + }, "graph": { "nodes": [ - _node("comp_trigger", "trigger", "入口:时间口径与国家焦点", "Trigger: Compute Query", 40, 130), + _node("comp_trigger", "trigger", "入口:时间口径与国家焦点", "Trigger: Compute Query", 40, 140), _node( "comp_series", "deterministic", "多口径算力与 RPI 确定性计算", "Deterministic Compute Series", - 310, - 130, + 420, + 140, tools=["query_compute_posture"], ), _node( @@ -432,8 +608,8 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "llm_agent", "算力战略参谋结论与候选提取", "Compute Strategic Synthesis", - 610, - 130, + 800, + 140, prompt_key="compute.posture.brief", system_prompt="你是国家级算力战略参谋分析师。仅输出严格符合约定 JSON 结构的分析结论,所有证据 ID 必须来自输入 evidence 字典。", prompt="基于多口径算力对比序列、RPI 与八大枢纽生成战略态势摘要。", @@ -441,7 +617,7 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ thinking_enabled=True, max_steps=2, ), - _node("comp_viewspec", "output", "ViewSpec / 地球镜头联动输出", "ViewSpec & Scene Output", 910, 130), + _node("comp_viewspec", "output", "ViewSpec / 地球镜头联动输出", "ViewSpec & Scene Output", 1180, 140), ], "edges": [ _edge("cp-e1", "comp_trigger", "comp_series", "按截止日期过滤", "Apply cutoff"), @@ -458,6 +634,15 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "description": "BGP、海缆、卫星、船舶四域空间异常取证推演与断缆/扰动边界守卫。", "description_en": "Multi-domain infrastructure incident investigation covering BGP, cables, satellites, and vessels.", "is_default": False, + "bindings": { + "enabled": True, + "surfaces": ["info_card", "multi_select", "copilot_quick"], + "entity_types": ["cable", "landing_point", "bgp", "vessel", "satellite", "global"], + "action_label": "多域兵棋推演", + "action_label_en": "Multi-Domain Wargame", + "icon": "hub", + "priority": 10, + }, "graph": { "nodes": [ _node("wg_trigger", "trigger", "入口:空间域与历史推演口径", "Trigger: Domain & TimeBasis", 40, 140), @@ -466,7 +651,7 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "deterministic", "多域拓扑与事件隔离快照", "Isolated Domain Snapshots", - 310, + 420, 140, tools=["query_bgp_incidents", "query_cable_posture", "query_satellite_posture", "query_vessel_posture"], ), @@ -475,7 +660,7 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "llm_agent", "基础设施取证与兵棋推演", "Wargame Investigator", - 600, + 800, 140, prompt_key="incident.investigator.brief", system_prompt="你是全球互联网与海缆基础设施取证参谋。严格区分 confirmed_facts、candidate_explanations、counter_evidence 与 open_gaps;无独立海缆告警证据时严禁将地理邻近推断为物理断缆。", @@ -485,7 +670,7 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ max_steps=3, guardrails={"disallow_unverified_cable_cut": True}, ), - _node("wg_output", "output", "推演矩阵与地球态势导览输出", "Topology & Tour Output", 900, 140), + _node("wg_output", "output", "推演矩阵与地球态势导览输出", "Topology & Tour Output", 1180, 140), ], "edges": [ _edge("wg-e1", "wg_trigger", "wg_snapshots", "时间遮蔽加载", "Mask future"), @@ -502,23 +687,32 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "description": "已从旧 BGP 页面收编进 AI 参谋 Playground(/bgp-brief),聚合采集器覆盖率与事故。", "description_en": "Consolidates BGP incidents, anomalies, and collector coverage into Playground shift briefs.", "is_default": False, + "bindings": { + "enabled": True, + "surfaces": ["info_card", "copilot_quick"], + "entity_types": ["bgp", "bgp_collector"], + "action_label": "BGP 态势值班简报", + "action_label_en": "BGP Duty Brief", + "icon": "lan", + "priority": 15, + }, "graph": { "nodes": [ - _node("bgp_agg", "deterministic", "BGP 事实与覆盖率聚合", "BGP Facts Collector", 60, 130, tools=["query_bgp_incidents"]), + _node("bgp_agg", "deterministic", "BGP 事实与覆盖率聚合", "BGP Facts Collector", 40, 140, tools=["query_bgp_incidents"]), _node( "bgp_brief_node", "llm_agent", "BGP 值班简报生成", "BGP Brief Writer", - 400, - 130, + 430, + 140, prompt_key="bgp.brief", system_prompt="你是 BGP 值班分析师。请直接输出面向值班人员的中文 Markdown 简报,只写最终研判内容。", prompt="基于当前 BGP incidents、anomalies、原始观测事件、观测站覆盖与 prefix geography 证据生成态势简报。", tools=["query_bgp_incidents"], thinking_enabled=True, ), - _node("bgp_out", "output", "Markdown 简报输出", "Brief Output", 740, 130), + _node("bgp_out", "output", "Markdown 简报输出", "Brief Output", 820, 140), ], "edges": [ _edge("bb-e1", "bgp_agg", "bgp_brief_node"), @@ -536,20 +730,20 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "is_default": False, "graph": { "nodes": [ - _node("alt_agg", "deterministic", "告警严重度与跨模块联动采样", "Alerts & Cross-Domain Facts", 60, 130, tools=["query_global_situational", "query_bgp_incidents"]), + _node("alt_agg", "deterministic", "告警严重度与跨模块联动采样", "Alerts & Cross-Domain Facts", 40, 140, tools=["query_global_situational", "query_bgp_incidents"]), _node( "alt_brief_node", "llm_agent", "值班告警研判生成", "Alert Brief Analyst", - 400, - 130, + 430, + 140, prompt_key="alerts.situational.brief", system_prompt="你是告警研判助手。请基于输入的告警事实、上下文与约束输出可执行的值班研判。", prompt="综合系统告警、BGP 事故/异常与近期简报,突出待处理风险与优先动作。", tools=["query_global_situational", "query_bgp_incidents"], ), - _node("alt_out", "output", "研判报告输出", "Alert Brief Output", 740, 130), + _node("alt_out", "output", "研判报告输出", "Alert Brief Output", 820, 140), ], "edges": [ _edge("ab-e1", "alt_agg", "alt_brief_node"), @@ -567,21 +761,21 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "is_default": False, "graph": { "nodes": [ - _node("col_in", "trigger", "入口:API 样本或数据源声明", "Trigger: Sample / Provider", 60, 130), + _node("col_in", "trigger", "入口:API 样本或数据源声明", "Trigger: Sample / Provider", 40, 140), _node( "col_map_node", "llm_agent", "字段映射 DSL / 官方凭据教程生成", "DSL & Guide Generator", - 400, - 130, + 430, + 140, prompt_key="datasource.mapping", system_prompt="根据用户样本返回合法 JSON 映射 DSL,或在生成凭据教程时仅引用已检出官方网页来源。", prompt="Return only JSON for a deterministic mapping DSL with source.items_path and fields, or a grounded setup tutorial.", tools=["web_search"], thinking_enabled=False, ), - _node("col_out", "output", "DSL Schema / Markdown 指南", "DSL / Guide Output", 740, 130), + _node("col_out", "output", "DSL Schema / Markdown 指南", "DSL / Guide Output", 820, 140), ], "edges": [ _edge("cl-e1", "col_in", "col_map_node"), @@ -604,25 +798,189 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [ "llm_agent", "连通性探针 / 滚动上下文压缩", "Probe & Compaction Node", - 240, - 130, + 120, + 140, prompt_key="ai.connection_test", system_prompt="如果是连通性测试只回复 OK;如果是对话压缩请输出不超过 280 字的中文要点摘要。", prompt="Reply OK.", thinking_enabled=False, timeout_seconds=15, ), - _node("diag_out", "output", "状态返回", "Status Output", 600, 130), + _node("diag_out", "output", "状态返回", "Status Output", 540, 140), ], "edges": [_edge("dg-e1", "diag_node", "diag_out")], }, }, + { + "workflow_id": "meta.workflow_evolver", + "name": "AI 工作流自进化元引擎", + "name_en": "AI Workflow Meta-Evolver", + "category": "meta", + "description": "负责诊断业务工作流失败/差评与模型漂移并生成最小补丁;可基于历史进化台账自我迭代,但受宪法硬校验与灰度回滚约束。", + "description_en": "Diagnoses workflow failures, feedback, and model drift to synthesize minimal patches; self-improves from evolution ledger outcomes under immutable constitution guardrails.", + "is_default": False, + "graph": { + "nodes": [ + _node( + "diag_node", + "llm_agent", + "诊断轨迹与模型画像", + "Diagnose Traces & Model Profile", + 80, + 140, + description="分析运行失败、用户差评原因、闲置工具与当前活跃模型能力特征,定位最需要改进的节点。", + system_prompt=( + "你是智能星球 AI 工作流诊断专家。请结合最近运行失败样本、用户差评说明、当前活跃模型能力画像以及历史进化正负经验," + "准确定位性能瓶颈或模型适配偏差,给出克制、具体的根因诊断。" + ), + prompt=( + "结合 workflow_id={{workflow_id}} 的失败/差评轨迹、闲置工具统计、活跃模型能力画像与历史台账正负经验," + "输出简洁清晰的节点级诊断重点。" + ), + thinking_enabled=True, + max_steps=1, + timeout_seconds=60, + ), + _node( + "patch_node", + "llm_agent", + "生成最小补丁方案", + "Synthesize Minimal Patch", + 460, + 140, + description="基于诊断结果生成最小化、允许字段白名单内的节点补丁 JSON,避免过度重写。", + system_prompt=( + "你是智能星球 AI 工作流架构调优引擎。仅输出严格 JSON:" + "{\"summary\": string, \"node_patches\": [{\"node_id\": string, \"field\": string, \"after\": any, \"reason\": string}]}。" + "坚持最小改动原则(单次最多调整 1~2 个关键节点),参考历史已验证有效经验并规避曾导致回滚的改法。" + ), + prompt=( + "依据诊断结论与允许字段白名单,为目标工作流输出严格 JSON 补丁。" + "严禁虚构工具 ID,严禁清空非空 system_prompt。" + ), + thinking_enabled=True, + max_steps=1, + timeout_seconds=60, + ), + _node( + "verify_output", + "guardrail", + "宪法硬校验与灰度输出", + "Constitution Gate & Output", + 840, + 140, + description="受 Python Tier-0 宪法代码保护,负责校验变更半径、防循环图、并触发灰度自动回滚监控。", + guardrails={ + "immutable_tier0": True, + "enforce_blast_radius": True, + "enforce_canary_rollback": True, + }, + ), + ], + "edges": [ + _edge("meta-e1", "diag_node", "patch_node", "诊断摘要", "Diagnosis"), + _edge("meta-e2", "patch_node", "verify_output", "宪法校验", "Constitution check"), + ], + }, + }, ] _BUILTIN_BY_ID: dict[str, dict[str, Any]] = { item["workflow_id"]: item for item in BUILTIN_WORKFLOWS } +# Exact coordinates shipped in v0.81.0 so untouched stock v1 rows can be upgraded safely. +_LEGACY_BUILTIN_POSITIONS: dict[str, dict[str, tuple[float, float]]] = { + "default.general": { + "intent_router": (40, 120), + "telemetry_context": (320, 120), + "advisor_agent": (620, 120), + "response_output": (920, 120), + }, + "location.resolve_unknown": { + "l0_normalize": (40, 140), + "l1_knowledge": (320, 60), + "l2_agent_research": (320, 250), + "l3_geo_guardrail": (640, 140), + "l4_persist_outcome": (940, 140), + }, + "earth.news.analysis": { + "news_trigger": (40, 140), + "news_enrich_node": (340, 60), + "news_analyst_node": (340, 240), + "news_output": (680, 140), + }, + "compute.comparison": { + "comp_trigger": (40, 130), + "comp_series": (310, 130), + "comp_brief_llm": (610, 130), + "comp_viewspec": (910, 130), + }, + "wargame.infrastructure": { + "wg_trigger": (40, 140), + "wg_snapshots": (310, 140), + "wg_investigator": (600, 140), + "wg_output": (900, 140), + }, + "brief.bgp": { + "bgp_agg": (60, 130), + "bgp_brief_node": (400, 130), + "bgp_out": (740, 130), + }, + "brief.alerts": { + "alt_agg": (60, 130), + "alt_brief_node": (400, 130), + "alt_out": (740, 130), + }, + "collection.assist": { + "col_in": (60, 130), + "col_map_node": (400, 130), + "col_out": (740, 130), + }, + "ops.diagnostics": { + "diag_node": (240, 130), + "diag_out": (600, 130), + }, +} + + +def _upgrade_untouched_legacy_positions(row: AIWorkflow, spec: dict[str, Any]) -> bool: + """Upgrade node coordinates only when the workflow is still an untouched stock v1 layout.""" + if row.active_revision != 1 or row.draft_graph is not None: + return False + legacy_map = _LEGACY_BUILTIN_POSITIONS.get(row.workflow_id) + graph = row.published_graph if isinstance(row.published_graph, dict) else None + if not legacy_map or not graph: + return False + nodes = graph.get("nodes") + if not isinstance(nodes, list) or len(nodes) != len(legacy_map): + return False + + for node in nodes: + if not isinstance(node, dict): + return False + expected = legacy_map.get(str(node.get("id") or "")) + pos = node.get("position") + if not expected or not isinstance(pos, dict): + return False + if pos.get("x") != expected[0] or pos.get("y") != expected[1]: + return False + + target_positions = { + str(n["id"]): copy.deepcopy(n["position"]) + for n in spec.get("graph", {}).get("nodes", []) + if isinstance(n, dict) and n.get("id") and isinstance(n.get("position"), dict) + } + if len(target_positions) != len(nodes): + return False + + updated_graph = copy.deepcopy(graph) + for node in updated_graph["nodes"]: + nid = str(node["id"]) + node["position"] = target_positions[nid] + row.published_graph = updated_graph + return True + async def ensure_builtin_workflows(db: AsyncSession) -> None: """Idempotently seed all 9 built-in workflows into `ai_workflows`.""" @@ -636,7 +994,14 @@ async def ensure_builtin_workflows(db: AsyncSession) -> None: changed = False for spec in BUILTIN_WORKFLOWS: wf_id = spec["workflow_id"] + default_bindings = normalize_bindings(spec.get("bindings")) if wf_id in existing_by_id: + existing_row = existing_by_id[wf_id] + if _upgrade_untouched_legacy_positions(existing_row, spec): + changed = True + if not existing_row.bindings and spec.get("bindings"): + existing_row.bindings = default_bindings + changed = True continue graph = copy.deepcopy(spec["graph"]) db.add( @@ -652,6 +1017,7 @@ async def ensure_builtin_workflows(db: AsyncSession) -> None: active_revision=1, published_graph=graph, draft_graph=None, + bindings=default_bindings, updated_by="system", ) ) @@ -688,6 +1054,7 @@ def _fallback_workflow_dict(workflow_id: str) -> dict[str, Any] | None: "has_draft": False, "published_graph": copy.deepcopy(spec["graph"]), "draft_graph": None, + "bindings": normalize_bindings(spec.get("bindings")), "updated_by": "system", "created_at": None, "updated_at": None, @@ -702,6 +1069,52 @@ async def list_workflows(db: AsyncSession) -> list[dict[str, Any]]: return [row.to_dict() for row in rows] if rows else [_fallback_workflow_dict(w["workflow_id"]) for w in BUILTIN_WORKFLOWS] +async def list_public_workflow_bindings(db: AsyncSession) -> list[dict[str, Any]]: + """Return strictly public-safe published workflow metadata & Earth bindings (no prompts/graphs).""" + await ensure_builtin_workflows(db) + rows: list[Any] = [] + if hasattr(db, "execute"): + try: + rows = ( + await db.execute(select(AIWorkflow).order_by(AIWorkflow.is_builtin.asc(), AIWorkflow.id.asc())) + ).scalars().all() + except Exception: + rows = [] + + raw_items = [row.to_dict() for row in rows] if rows else [ + _fallback_workflow_dict(w["workflow_id"]) for w in BUILTIN_WORKFLOWS + ] + public_items: list[dict[str, Any]] = [] + for item in raw_items: + if not item: + continue + bindings = normalize_bindings(item.get("bindings")) + if not bindings.get("enabled") or not bindings.get("surfaces"): + continue + public_items.append( + { + "workflow_id": item["workflow_id"], + "name": item["name"], + "name_en": item.get("name_en") or item["name"], + "description": item.get("description") or "", + "description_en": item.get("description_en") or item.get("description") or "", + "category": item.get("category") or "custom", + "is_default": bool(item.get("is_default")), + "is_builtin": bool(item.get("is_builtin", True)), + "active_revision": int(item.get("active_revision") or 1), + "bindings": bindings, + } + ) + public_items.sort( + key=lambda x: ( + -int(x["bindings"].get("priority") or 0), + 1 if x["is_builtin"] else 0, + x["workflow_id"], + ) + ) + return public_items + + async def get_workflow_detail(db: AsyncSession, workflow_id: str) -> dict[str, Any]: await ensure_builtin_workflows(db) row = ( @@ -730,6 +1143,8 @@ async def get_workflow_detail(db: AsyncSession, workflow_id: str) -> dict[str, A "revisions": [rev.to_dict() for rev in revisions], "fixtures": [fix.to_dict() for fix in fixtures], "tool_catalog": TOOL_CATALOG, + "earth_entity_types": EARTH_ENTITY_TYPES, + "earth_surfaces": EARTH_SURFACES, } @@ -740,6 +1155,11 @@ def _validate_graph_payload(graph: dict[str, Any]) -> dict[str, Any]: raw_edges = graph.get("edges") or [] if not isinstance(raw_nodes, list) or not raw_nodes: raise HTTPException(status_code=422, detail="Workflow graph requires at least one node") + if len(raw_nodes) > MAX_WORKFLOW_NODES: + raise HTTPException( + status_code=422, + detail=f"Workflow graph supports at most {MAX_WORKFLOW_NODES} nodes", + ) cleaned_nodes: list[dict[str, Any]] = [] seen_ids: set[str] = set() for item in raw_nodes: @@ -748,13 +1168,16 @@ def _validate_graph_payload(graph: dict[str, Any]) -> dict[str, Any]: nid = str(item.get("id") or "").strip() if not nid or nid in seen_ids: raise HTTPException(status_code=422, detail=f"Invalid or duplicate node id: {nid!r}") + node_type = str(item.get("node_type") or "llm_agent").strip() + if node_type not in VALID_NODE_TYPES: + raise HTTPException(status_code=422, detail=f"Unsupported node_type: {node_type!r}") seen_ids.add(nid) tools = [str(t).strip() for t in (item.get("tools") or []) if str(t).strip() in VALID_TOOL_IDS] pos = item.get("position") if isinstance(item.get("position"), dict) else {} cleaned_nodes.append( { "id": nid, - "node_type": str(item.get("node_type") or "llm_agent"), + "node_type": node_type, "title": str(item.get("title") or nid), "title_en": str(item.get("title_en") or item.get("title") or nid), "description": str(item.get("description") or ""), @@ -776,7 +1199,13 @@ def _validate_graph_payload(graph: dict[str, Any]) -> dict[str, Any]: "params": dict(item.get("params") or {}) if isinstance(item.get("params"), dict) else {}, } ) + if not cleaned_nodes: + raise HTTPException(status_code=422, detail="Workflow graph requires at least one valid node") + cleaned_edges: list[dict[str, Any]] = [] + adjacency: dict[str, list[str]] = {n["id"]: [] for n in cleaned_nodes} + indegree: dict[str, int] = {n["id"]: 0 for n in cleaned_nodes} + seen_pairs: set[tuple[str, str]] = set() for idx, edge in enumerate(raw_edges): if not isinstance(edge, dict): continue @@ -784,6 +1213,13 @@ def _validate_graph_payload(graph: dict[str, Any]) -> dict[str, Any]: tgt = str(edge.get("target") or "").strip() if src not in seen_ids or tgt not in seen_ids: continue + if src == tgt: + raise HTTPException(status_code=422, detail=f"Self-loop edge on node {src!r} is not allowed") + if (src, tgt) in seen_pairs: + continue + seen_pairs.add((src, tgt)) + raw_cond = str(edge.get("condition") or "always").strip() + cond = raw_cond if raw_cond in ALLOWED_EDGE_CONDITIONS else "always" cleaned_edges.append( { "id": str(edge.get("id") or f"e-{idx + 1}"), @@ -791,17 +1227,251 @@ def _validate_graph_payload(graph: dict[str, Any]) -> dict[str, Any]: "target": tgt, "label": str(edge.get("label") or ""), "label_en": str(edge.get("label_en") or edge.get("label") or ""), - "condition": str(edge.get("condition") or "always"), + "condition": cond, + "condition_value": str(edge.get("condition_value") or "").strip()[:200], } ) + adjacency[src].append(tgt) + indegree[tgt] += 1 + + # Enforce DAG invariant with Kahn's topological sort. + queue = deque(nid for nid, deg in indegree.items() if deg == 0) + visited = 0 + while queue: + cur = queue.popleft() + visited += 1 + for nxt in adjacency[cur]: + indegree[nxt] -= 1 + if indegree[nxt] == 0: + queue.append(nxt) + if visited != len(cleaned_nodes): + raise HTTPException(status_code=422, detail="Workflow graph cannot contain cycles") + return {"nodes": cleaned_nodes, "edges": cleaned_edges} +def build_starter_workflow_graph(name: str = "") -> dict[str, Any]: + """Build a minimal valid 3-node DAG skeleton for new custom workflows.""" + label = name.strip() or "自定义分析" + return { + "nodes": [ + _node( + "trigger_intake", + "trigger", + "入口:交互物件与上下文", + "Trigger: Target & Context", + 40, + 140, + description="接收地球交互物件或用户提问,装配基础上下文。", + ), + _node( + "llm_analyze", + "llm_agent", + f"AI 分析:{label}", + f"Analyze: {label}", + 420, + 140, + description="结合绑定的工具数据与目标物件进行研判。", + system_prompt="你是智能星球 AI 参谋。结合当前选中交互物件、遥测工具证据与用户问题,给出客观、可验证的结构化分析。", + prompt="围绕 {{targets_summary}},结合问题「{{question}}」进行研判,明确给出证据来源与不确定边界。", + tools=["query_global_situational"], + thinking_enabled=True, + max_steps=2, + timeout_seconds=60, + ), + _node( + "output_reply", + "output", + "流式输出与地球联动", + "Stream & Scene Output", + 800, + 140, + description="推送分析正文,并在存在明确坐标时联动地球镜头。", + params={"fly_to_target": True, "fly_zoom": 1.45}, + ), + ], + "edges": [ + _edge("e-start-1", "trigger_intake", "llm_analyze", "传入目标", "Target ready"), + _edge("e-start-2", "llm_analyze", "output_reply", "流式返回", "Stream output"), + ], + } + + +async def create_workflow( + db: AsyncSession, + *, + workflow_id: str | None = None, + name: str, + name_en: str = "", + category: str = "custom", + description: str = "", + description_en: str = "", + graph: dict[str, Any] | None = None, + bindings: dict[str, Any] | None = None, + actor: str = "admin", +) -> dict[str, Any]: + """Create a brand new custom workflow with initial published revision v1.""" + await ensure_builtin_workflows(db) + clean_name = name.strip() + if not clean_name: + raise HTTPException(status_code=422, detail="Workflow name is required") + wf_id = str(workflow_id or "").strip() or f"custom.{uuid4().hex[:8]}" + if wf_id.startswith("meta."): + raise HTTPException( + status_code=400, + detail="Custom workflows cannot use the reserved 'meta.' namespace", + ) + if not WORKFLOW_ID_RE.match(wf_id): + raise HTTPException( + status_code=422, + detail="workflow_id must start with a-z/0-9 and use only a-z, 0-9, '.', '-', '_'", + ) + existing = ( + await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == wf_id)) + ).scalar_one_or_none() + if existing is not None: + raise HTTPException(status_code=409, detail=f"Workflow '{wf_id}' already exists") + + validated_graph = _validate_graph_payload(graph or build_starter_workflow_graph(clean_name)) + normalized_bindings = normalize_bindings(bindings) + row = AIWorkflow( + workflow_id=wf_id, + name=clean_name[:160], + name_en=(name_en.strip() or clean_name)[:160], + category=(category.strip() or "custom")[:60], + description=description.strip(), + description_en=(description_en.strip() or description.strip()), + is_default=False, + is_builtin=False, + active_revision=1, + published_graph=validated_graph, + draft_graph=None, + bindings=normalized_bindings, + updated_by=actor, + ) + db.add(row) + db.add( + AIWorkflowRevision( + workflow_id=wf_id, + revision=1, + status="published", + graph_json=validated_graph, + change_summary="Created custom workflow", + created_by=actor, + ) + ) + await db.commit() + await db.refresh(row) + return row.to_dict() + + +async def clone_workflow( + db: AsyncSession, + source_workflow_id: str, + *, + workflow_id: str | None = None, + name: str | None = None, + name_en: str | None = None, + actor: str = "admin", +) -> dict[str, Any]: + """Clone an existing workflow into an editable custom workflow, stripping built-in prompt_keys.""" + await ensure_builtin_workflows(db) + src = ( + await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == source_workflow_id)) + ).scalar_one_or_none() + if src is None: + raise HTTPException(status_code=404, detail=f"Workflow '{source_workflow_id}' not found") + + cloned_graph = copy.deepcopy(src.draft_graph or src.published_graph or {}) + for node in cloned_graph.get("nodes") or []: + if isinstance(node, dict): + node["prompt_key"] = None + + cloned_bindings = normalize_bindings(copy.deepcopy(src.bindings or {})) + slug_base = re.sub(r"[^a-z0-9]+", "_", source_workflow_id.lower()).strip("_")[:32] or "wf" + target_id = str(workflow_id or "").strip() or f"custom.{slug_base}.{uuid4().hex[:6]}" + target_name = (name or "").strip() or f"{src.name} (副本)" + target_name_en = (name_en or "").strip() or f"{src.name_en or src.name} (Copy)" + + return await create_workflow( + db, + workflow_id=target_id, + name=target_name, + name_en=target_name_en, + category="custom", + description=src.description or "", + description_en=src.description_en or "", + graph=cloned_graph, + bindings=cloned_bindings, + actor=actor, + ) + + +async def update_workflow_metadata( + db: AsyncSession, + workflow_id: str, + *, + name: str | None = None, + name_en: str | None = None, + category: str | None = None, + description: str | None = None, + description_en: str | None = None, + bindings: dict[str, Any] | None = None, + actor: str = "admin", +) -> dict[str, Any]: + """Update mutable workflow metadata and Earth bindings without disturbing node revisions.""" + await ensure_builtin_workflows(db) + row = ( + await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == workflow_id)) + ).scalar_one_or_none() + if row is None: + raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found") + if name is not None and name.strip(): + row.name = name.strip()[:160] + if name_en is not None and name_en.strip(): + row.name_en = name_en.strip()[:160] + if category is not None and category.strip(): + row.category = category.strip()[:60] + if description is not None: + row.description = description.strip() + if description_en is not None: + row.description_en = description_en.strip() + if bindings is not None: + row.bindings = normalize_bindings(bindings) + row.updated_by = actor + await db.commit() + await db.refresh(row) + return row.to_dict() + + +async def delete_workflow(db: AsyncSession, workflow_id: str) -> dict[str, Any]: + """Delete a non-builtin custom workflow and its revisions/fixtures.""" + await ensure_builtin_workflows(db) + row = ( + await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == workflow_id)) + ).scalar_one_or_none() + if row is None: + raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found") + if bool(row.is_builtin) or bool(row.is_default): + raise HTTPException( + status_code=400, + detail="Built-in or default workflows cannot be deleted; clone it instead.", + ) + await db.execute(delete(AIWorkflowFixture).where(AIWorkflowFixture.workflow_id == workflow_id)) + await db.execute(delete(AIWorkflowRevision).where(AIWorkflowRevision.workflow_id == workflow_id)) + await db.delete(row) + await db.commit() + return {"deleted": True, "workflow_id": workflow_id} + + async def save_workflow_draft( db: AsyncSession, workflow_id: str, graph: dict[str, Any], *, + bindings: dict[str, Any] | None = None, + name: str | None = None, + description: str | None = None, actor: str, ) -> dict[str, Any]: await ensure_builtin_workflows(db) @@ -811,6 +1481,32 @@ async def save_workflow_draft( if row is None: raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found") row.draft_graph = _validate_graph_payload(graph) + if bindings is not None: + row.bindings = normalize_bindings(bindings) + if name is not None and name.strip(): + row.name = name.strip()[:160] + if description is not None: + row.description = description.strip() + row.updated_by = actor + await db.commit() + await db.refresh(row) + return row.to_dict() + + +async def discard_workflow_draft( + db: AsyncSession, + workflow_id: str, + *, + actor: str = "admin", +) -> dict[str, Any]: + """Discard pending draft changes and restore the active published workflow.""" + await ensure_builtin_workflows(db) + row = ( + await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == workflow_id)) + ).scalar_one_or_none() + if row is None: + raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found") + row.draft_graph = None row.updated_by = actor await db.commit() await db.refresh(row) @@ -822,6 +1518,9 @@ async def publish_workflow( workflow_id: str, *, graph: dict[str, Any] | None = None, + bindings: dict[str, Any] | None = None, + name: str | None = None, + description: str | None = None, change_summary: str = "", actor: str = "admin", ) -> dict[str, Any]: @@ -837,6 +1536,12 @@ async def publish_workflow( row.published_graph = validated row.draft_graph = None row.active_revision = next_rev + if bindings is not None: + row.bindings = normalize_bindings(bindings) + if name is not None and name.strip(): + row.name = name.strip()[:160] + if description is not None: + row.description = description.strip() row.updated_by = actor db.add( AIWorkflowRevision( diff --git a/backend/app/services/alert_ai_brief.py b/backend/app/services/alert_ai_brief.py index 55e30674..eedadd7b 100644 --- a/backend/app/services/alert_ai_brief.py +++ b/backend/app/services/alert_ai_brief.py @@ -1,13 +1,16 @@ from __future__ import annotations from collections import Counter +from datetime import UTC, datetime, timedelta from typing import Any from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession -from app.models.alert import Alert, AlertSeverity, AlertStatus -from app.schemas.ai import AlertBriefRequest, SituationalAnalysisRequest +from app.models.alert import Alert, AlertStatus +from app.models.datasource import DataSource +from app.models.task import CollectionTask +from app.schemas.ai import SituationalAnalysisRequest from app.ai_tasks.prompts import get_effective_prompt ALERT_BRIEF_PROMPT_KEY = "alerts.brief" @@ -19,6 +22,50 @@ def _format_counter(counter: Counter[str], empty_text: str = "无") -> str: return ",".join(f"{key} {value}" for key, value in counter.items()) +async def _collect_operational_health(db: AsyncSession) -> dict[str, Any]: + """Query failed collection tasks and unhealthy data sources, degrading safely.""" + summary: dict[str, Any] = { + "failed_tasks_24h": 0, + "recent_failed_tasks": [], + "failed_datasources": [], + } + try: + cutoff = datetime.now(UTC) - timedelta(hours=24) + failed_24h_count = await db.execute( + select(func.count(CollectionTask.id)) + .where(CollectionTask.status == "failed") + .where(CollectionTask.created_at >= cutoff) + ) + failed_tasks_rows = await db.execute( + select(CollectionTask) + .where(CollectionTask.status == "failed") + .order_by(CollectionTask.created_at.desc(), CollectionTask.id.desc()) + .limit(6) + ) + failed_sources_rows = await db.execute( + select(DataSource) + .where(DataSource.is_active.is_(True)) + .where(DataSource.last_status.in_(["failed", "error"])) + ) + summary["failed_tasks_24h"] = int(failed_24h_count.scalar() or 0) + summary["recent_failed_tasks"] = [ + { + "source": task.source or f"datasource:{task.datasource_id}", + "task_type": task.task_type, + "error": (task.error_message or "")[:160], + } + for task in failed_tasks_rows.scalars().all() + ] + summary["failed_datasources"] = [ + {"source": ds.source, "name": ds.name, "status": ds.last_status} + for ds in failed_sources_rows.scalars().all() + ] + except Exception: + # Keep brief generation resilient even in minimal test DB fixtures. + pass + return summary + + async def build_alert_brief_request( db: AsyncSession, *, @@ -76,6 +123,28 @@ async def build_alert_brief_request( ) ) + health = await _collect_operational_health(db) + failed_sources = health["failed_datasources"] + failed_tasks = health["recent_failed_tasks"] + facts.append( + f"近 24 小时采集任务失败 {health['failed_tasks_24h']} 次," + f"当前处于异常/失败状态的活跃数据源 {len(failed_sources)} 个。" + ) + if failed_sources: + facts.append( + "异常数据源:" + + "、".join(f"{item['name']} ({item['source']})" for item in failed_sources[:6]) + + "。" + ) + if failed_tasks: + facts.append( + "最近失败任务摘录:" + + ";".join( + f"{item['source']} [{item['task_type']}] {item['error'] or 'failed'}" + for item in failed_tasks[:4] + ) + ) + context = { "source": "alerts", "total_alerts": total_alerts, @@ -86,6 +155,9 @@ async def build_alert_brief_request( "status_distribution": dict(status_counts), "top_datasources": dict(datasource_counts.most_common(6)), "top_active_datasources": dict(active_datasource_counts.most_common(5)), + "failed_tasks_24h": health["failed_tasks_24h"], + "recent_failed_tasks": failed_tasks, + "failed_datasources": failed_sources, } prompt = await get_effective_prompt(db, ALERT_BRIEF_PROMPT_KEY) diff --git a/backend/app/services/location/agent_resolver.py b/backend/app/services/location/agent_resolver.py index 758efb55..20a267ae 100644 --- a/backend/app/services/location/agent_resolver.py +++ b/backend/app/services/location/agent_resolver.py @@ -413,8 +413,21 @@ async def run_controlled_location_agent( place_q = coerce_str(args.get("place_query")) expected_c = normalize_country_text(args.get("country") or query.country) agent_attempts.append(f"geocode_verify:{place_q}") - geo_res = await asyncio.to_thread(_agent_geocoder, place_q) - if not isinstance(geo_res, dict): + try: + geo_res = await asyncio.to_thread(_agent_geocoder, place_q) + except Exception as exc: + logger.warning_event( + "Location agent geocode_verify failed", + event="location_agent.geocode_verify.failed", + context={"place_query": place_q, "error": str(exc)}, + ) + geo_res = None + geocode_error = f"geocoder request failed: {exc}" + else: + geocode_error = "" + if geocode_error: + tool_output = {"found": False, "error": geocode_error, "retryable": True} + elif not isinstance(geo_res, dict): tool_output = {"found": False, "reason": "No geocoder match"} else: lat = parse_float(geo_res.get("lat") if geo_res.get("lat") is not None else geo_res.get("latitude")) diff --git a/backend/app/services/location/resolvers/nominatim.py b/backend/app/services/location/resolvers/nominatim.py index 59030961..3f5f04a2 100644 --- a/backend/app/services/location/resolvers/nominatim.py +++ b/backend/app/services/location/resolvers/nominatim.py @@ -14,12 +14,15 @@ can swap the geocoder behavior without touching pipeline construction. from __future__ import annotations +import ssl import time from functools import lru_cache from typing import Any, Callable import httpx +from app.core.logging import get_logger + from ..models import LocationCandidate, LocationQuery, ResolverOutput from ..text import ( coerce_str, @@ -28,6 +31,9 @@ from ..text import ( parse_float, ) +logger = get_logger(__name__, service="location_geocoder") +_RETRYABLE_STATUS_CODES: frozenset[int] = frozenset({429, 502, 503, 504}) + NOMINATIM_SEARCH_URL = "https://nominatim.openstreetmap.org/search" DEFAULT_USER_AGENT = "planet-earth-location-resolver/1.0" DEFAULT_MIN_INTERVAL_SECONDS = 1.1 @@ -40,8 +46,10 @@ def build_default_nominatim_geocoder( min_interval_seconds: float = DEFAULT_MIN_INTERVAL_SECONDS, timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS, cache_size: int = 512, + max_retries: int = 2, + retry_backoff_seconds: float = 0.6, ) -> Callable[[str], dict[str, Any] | None]: - """Return a cached, rate-limited Nominatim geocoder.""" + """Return a cached, rate-limited Nominatim geocoder with transient retry.""" last_request_at = [0.0] @@ -49,29 +57,52 @@ def build_default_nominatim_geocoder( def geocode(query: str) -> dict[str, Any] | None: if not query: return None - elapsed = time.monotonic() - last_request_at[0] - if elapsed < min_interval_seconds: - time.sleep(min_interval_seconds - elapsed) - last_request_at[0] = time.monotonic() - response = httpx.get( - NOMINATIM_SEARCH_URL, - params={ - "q": query, - "format": "jsonv2", - "limit": 1, - "addressdetails": 1, - }, - headers={"User-Agent": user_agent}, - timeout=timeout_seconds, - ) - response.raise_for_status() - payload = response.json() - if not isinstance(payload, list) or not payload: - return None - result = payload[0] - if not isinstance(result, dict): - return None - return result + attempts = max(0, int(max_retries)) + 1 + for attempt in range(attempts): + elapsed = time.monotonic() - last_request_at[0] + if elapsed < min_interval_seconds: + time.sleep(min_interval_seconds - elapsed) + last_request_at[0] = time.monotonic() + try: + response = httpx.get( + NOMINATIM_SEARCH_URL, + params={ + "q": query, + "format": "jsonv2", + "limit": 1, + "addressdetails": 1, + }, + headers={"User-Agent": user_agent}, + timeout=timeout_seconds, + ) + response.raise_for_status() + payload = response.json() + if not isinstance(payload, list) or not payload: + return None + result = payload[0] + if not isinstance(result, dict): + return None + return result + except httpx.HTTPStatusError as exc: + status_code = exc.response.status_code if exc.response is not None else 0 + if status_code not in _RETRYABLE_STATUS_CODES or attempt >= attempts - 1: + raise + logger.warning_event( + "Nominatim HTTP status transient failure, retrying", + event="location.nominatim.retry", + context={"attempt": attempt + 1, "max_attempts": attempts, "status_code": status_code, "error": str(exc)}, + ) + except (httpx.TransportError, ssl.SSLError, OSError) as exc: + if attempt >= attempts - 1: + raise + logger.warning_event( + "Nominatim transport/SSL transient failure, retrying", + event="location.nominatim.retry", + context={"attempt": attempt + 1, "max_attempts": attempts, "error": str(exc)}, + ) + if retry_backoff_seconds > 0: + time.sleep(retry_backoff_seconds * (attempt + 1)) + return None return geocode diff --git a/backend/tests/test_ai_workflows.py b/backend/tests/test_ai_workflows.py index 6c413174..59b262a2 100644 --- a/backend/tests/test_ai_workflows.py +++ b/backend/tests/test_ai_workflows.py @@ -17,7 +17,11 @@ from app.main import app from app.models.ai_workflow import AIWorkflow, AIWorkflowFixture, AIWorkflowRevision from app.models.situational_assessment import WorkflowRun from app.models.system_setting import SystemSetting -from app.services.ai.workflow_registry import BUILTIN_WORKFLOWS +from app.services.ai.workflow_registry import ( + BUILTIN_WORKFLOWS, + _LEGACY_BUILTIN_POSITIONS, + ensure_builtin_workflows, +) class _SyncAsAsyncSession: @@ -53,7 +57,14 @@ class _SyncAsAsyncSession: async def _make_sqlite_session(): + from sqlalchemy import event + engine = create_engine("sqlite:///:memory:") + event.listen( + engine, + "connect", + lambda conn, _: conn.create_function("btrim", 1, lambda v: v.strip() if isinstance(v, str) else v), + ) Base.metadata.create_all( engine, tables=[ @@ -171,7 +182,6 @@ async def test_ai_workflows_seed_draft_publish_rollback_and_fixtures(monkeypatch app.dependency_overrides.clear() engine.dispose() - @pytest.mark.asyncio async def test_ai_workflow_optimize_whitelist_and_playground_sse_runs(monkeypatch): engine, factory = await _make_sqlite_session() @@ -271,3 +281,417 @@ async def test_ai_workflow_optimize_whitelist_and_playground_sse_runs(monkeypatc finally: app.dependency_overrides.clear() engine.dispose() + +def test_builtin_workflows_have_spacious_left_to_right_layout(): + for spec in BUILTIN_WORKFLOWS: + wf_id = spec["workflow_id"] + nodes_by_id = {n["id"]: n for n in spec["graph"]["nodes"]} + for edge in spec["graph"]["edges"]: + src = nodes_by_id[edge["source"]]["position"] + tgt = nodes_by_id[edge["target"]]["position"] + dx = tgt["x"] - src["x"] + assert dx >= 320, ( + f"{wf_id} edge {edge['id']} ({edge['source']} -> {edge['target']}) " + f"has cramped or backwards dx={dx}" + ) + + +@pytest.mark.asyncio +async def test_ensure_builtin_workflows_upgrades_untouched_legacy_positions_only(): + import copy + + engine, factory = await _make_sqlite_session() + try: + async with factory() as session: + loc_spec = next( + item for item in BUILTIN_WORKFLOWS if item["workflow_id"] == "location.resolve_unknown" + ) + legacy_loc_graph = copy.deepcopy(loc_spec["graph"]) + for node in legacy_loc_graph["nodes"]: + lx, ly = _LEGACY_BUILTIN_POSITIONS["location.resolve_unknown"][node["id"]] + node["position"] = {"x": lx, "y": ly} + + gen_spec = next( + item for item in BUILTIN_WORKFLOWS if item["workflow_id"] == "default.general" + ) + custom_gen_graph = copy.deepcopy(gen_spec["graph"]) + custom_gen_graph["nodes"][0]["position"] = {"x": 99, "y": 222} + + session.add( + AIWorkflow( + workflow_id="location.resolve_unknown", + name=loc_spec["name"], + name_en=loc_spec["name_en"], + category=loc_spec["category"], + description=loc_spec["description"], + description_en=loc_spec["description_en"], + is_default=False, + is_builtin=True, + active_revision=1, + published_graph=legacy_loc_graph, + draft_graph=None, + updated_by="system", + ) + ) + session.add( + AIWorkflow( + workflow_id="default.general", + name=gen_spec["name"], + name_en=gen_spec["name_en"], + category=gen_spec["category"], + description=gen_spec["description"], + description_en=gen_spec["description_en"], + is_default=True, + is_builtin=True, + active_revision=1, + published_graph=custom_gen_graph, + draft_graph=None, + updated_by="admin", + ) + ) + await session.commit() + + await ensure_builtin_workflows(session) + + from sqlalchemy import select + + upgraded_loc = ( + await session.execute( + select(AIWorkflow).where(AIWorkflow.workflow_id == "location.resolve_unknown") + ) + ).scalar_one() + l1 = next(n for n in upgraded_loc.published_graph["nodes"] if n["id"] == "l1_knowledge") + l2 = next(n for n in upgraded_loc.published_graph["nodes"] if n["id"] == "l2_agent_research") + assert l2["position"]["x"] > l1["position"]["x"] + + untouched_gen = ( + await session.execute( + select(AIWorkflow).where(AIWorkflow.workflow_id == "default.general") + ) + ).scalar_one() + assert untouched_gen.published_graph["nodes"][0]["position"] == {"x": 99, "y": 222} + finally: + engine.dispose() + + +@pytest.mark.asyncio +async def test_playground_slash_briefs_map_to_registered_workflow_ids(): + from app.api.v1.ai_workflows import _resolve_playground_slash_or_workflow + from app.models.alert import Alert + from app.models.bgp_anomaly import BGPAnomaly + from app.models.bgp_incident import BGPIncident + from app.models.bgp_observation import BGPObservation + from app.models.datasource import DataSource + from app.models.task import CollectionTask + + from sqlalchemy import event + + engine = create_engine("sqlite:///:memory:") + event.listen( + engine, + "connect", + lambda conn, _: conn.create_function("btrim", 1, lambda v: v.strip() if isinstance(v, str) else v), + ) + Base.metadata.create_all( + engine, + tables=[ + AIWorkflow.__table__, + AIWorkflowRevision.__table__, + AIWorkflowFixture.__table__, + WorkflowRun.__table__, + SystemSetting.__table__, + Alert.__table__, + BGPIncident.__table__, + BGPAnomaly.__table__, + BGPObservation.__table__, + DataSource.__table__, + CollectionTask.__table__, + ], + ) + sync_factory = sessionmaker(engine, expire_on_commit=False) + registered_ids = {spec["workflow_id"] for spec in BUILTIN_WORKFLOWS} + try: + sess = _SyncAsAsyncSession(sync_factory()) + sess.add( + DataSource( + name="Test Unhealthy Source", + source="unhealthy_test", + module="L1", + collector_class="TestCollector", + is_active=True, + last_status="failed", + ) + ) + sess.add( + CollectionTask( + datasource_id=1, + source="unhealthy_test", + task_type="collect", + status="failed", + error_message="connection timeout", + ) + ) + await sess.commit() + + wf_bgp, _, _, _ = await _resolve_playground_slash_or_workflow( + db=sess, + workflow_id="default.general", + message="/bgp-brief", + use_draft=False, + earth_context=None, + ) + assert wf_bgp == "brief.bgp" + assert wf_bgp in registered_ids + + wf_alerts, _, req_alerts, _ = await _resolve_playground_slash_or_workflow( + db=sess, + workflow_id="default.general", + message="/alerts-brief", + use_draft=False, + earth_context=None, + ) + assert wf_alerts == "brief.alerts" + assert wf_alerts in registered_ids + assert req_alerts is not None + assert req_alerts.context["failed_tasks_24h"] == 1 + assert len(req_alerts.context["failed_datasources"]) == 1 + + wf_sit, _, _, _ = await _resolve_playground_slash_or_workflow( + db=sess, + workflow_id="default.general", + message="/situational-brief", + use_draft=False, + earth_context=None, + ) + assert wf_sit == "brief.alerts" + assert wf_sit in registered_ids + await sess.close() + finally: + engine.dispose() + + +@pytest.mark.asyncio +async def test_custom_workflow_crud_clone_cycle_guard_and_public_bindings(): + engine, factory = await _make_sqlite_session() + + async def override_db(): + async with factory() as session: + yield session + + def override_admin(): + return SimpleNamespace(id=1, username="admin", role="admin", email="admin@test") + + app.dependency_overrides[get_db] = override_db + app.dependency_overrides[require_admin_user] = override_admin + transport = ASGITransport(app=app) + try: + async with AsyncClient(transport=transport, base_url="http://test") as client: + # 1. Create custom workflow with Earth bindings + create_resp = await client.post( + "/api/v1/ai/workflows", + json={ + "workflow_id": "custom.cable_vessel_check", + "name": "海缆与近邻船舶排查", + "description": "排查断缆周边船舶与路由异动", + "bindings": { + "enabled": True, + "surfaces": ["info_card", "multi_select"], + "entity_types": ["cable", "vessel"], + "action_label": "断缆与船舶联动", + "icon": "troubleshoot", + "priority": 40, + "prompt_template": "排查 {{targets_summary}} 风险", + }, + }, + ) + assert create_resp.status_code == 200 + created = create_resp.json() + assert created["workflow_id"] == "custom.cable_vessel_check" + assert created["is_builtin"] is False + assert created["bindings"]["enabled"] is True + + # 2. Reject deleting built-in workflow (400) + del_builtin = await client.delete("/api/v1/ai/workflows/default.general") + assert del_builtin.status_code == 400 + + # 3. Clone built-in workflow and verify prompt_key is stripped on cloned nodes + clone_resp = await client.post( + "/api/v1/ai/workflows/earth.news.analysis/clone", + json={"workflow_id": "custom.my_news", "name": "我的新闻研判"}, + ) + assert clone_resp.status_code == 200 + cloned = clone_resp.json() + assert cloned["is_builtin"] is False + for node in cloned["published_graph"]["nodes"]: + assert node.get("prompt_key") is None + + # 4. PATCH metadata + bindings + patch_resp = await client.patch( + "/api/v1/ai/workflows/custom.my_news", + json={ + "name": "我的新闻研判 V2", + "bindings": { + "enabled": True, + "surfaces": ["news_card"], + "entity_types": ["news"], + "action_label": "定制新闻研判", + }, + }, + ) + assert patch_resp.status_code == 200 + assert patch_resp.json()["name"] == "我的新闻研判 V2" + + # 5. Reject cyclic graph (422) + cyclic_graph = { + "nodes": [ + {"id": "a", "node_type": "trigger", "title": "A", "position": {"x": 0, "y": 0}}, + {"id": "b", "node_type": "llm_agent", "title": "B", "position": {"x": 300, "y": 0}}, + ], + "edges": [ + {"id": "e1", "source": "a", "target": "b"}, + {"id": "e2", "source": "b", "target": "a"}, + ], + } + cycle_resp = await client.put( + "/api/v1/ai/workflows/custom.my_news/draft", + json={"graph": cyclic_graph}, + ) + assert cycle_resp.status_code == 422 + + # 6. Reject >12 nodes (422) + too_many = { + "nodes": [ + {"id": f"n{i}", "node_type": "llm_agent", "title": f"N{i}", "position": {"x": i * 100, "y": 0}} + for i in range(13) + ], + "edges": [], + } + max_resp = await client.put( + "/api/v1/ai/workflows/custom.my_news/draft", + json={"graph": too_many}, + ) + assert max_resp.status_code == 422 + + # 7. Public /workflows/bindings must work WITHOUT admin auth & leak ZERO prompts/graphs + app.dependency_overrides.pop(require_admin_user, None) + bindings_resp = await client.get("/api/v1/ai/workflows/bindings") + assert bindings_resp.status_code == 200 + b_items = bindings_resp.json()["items"] + assert any(item["workflow_id"] == "custom.cable_vessel_check" for item in b_items) + for item in b_items: + assert "published_graph" not in item + assert "draft_graph" not in item + assert "system_prompt" not in item + assert "updated_by" not in item + + # 7b. Re-enable admin and test discard draft restores published workflow cleanly + app.dependency_overrides[require_admin_user] = override_admin + discard_draft_graph = { + "nodes": [ + {"id": "only_trigger", "node_type": "trigger", "title": "Draft Trigger", "position": {"x": 0, "y": 0}}, + ], + "edges": [], + } + draft_put = await client.put( + "/api/v1/ai/workflows/earth.news.analysis/draft", + json={"graph": discard_draft_graph}, + ) + assert draft_put.status_code == 200 + assert draft_put.json()["has_draft"] is True + + discard_resp = await client.delete("/api/v1/ai/workflows/earth.news.analysis/draft") + assert discard_resp.status_code == 200 + discarded = discard_resp.json() + assert discarded["has_draft"] is False + assert discarded["draft_graph"] is None + assert len(discarded["published_graph"]["nodes"]) == 4 + + # 8. Delete custom workflow + del_custom = await client.delete("/api/v1/ai/workflows/custom.my_news") + assert del_custom.status_code == 200 + assert del_custom.json()["deleted"] is True + finally: + app.dependency_overrides.clear() + engine.dispose() + + +@pytest.mark.asyncio +async def test_playground_link_parser_ssrf_guard_and_multimodal_attachments(monkeypatch): + from app.api.v1 import ai_workflows as ai_wf_api + from app.services.ai.tool_registry import FetchedEvidence + + app.dependency_overrides[require_admin_user] = lambda: SimpleNamespace( + id=1, username="admin", role="admin" + ) + try: + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as client: + blocked = await client.post( + "/api/v1/ai/playground/parse-link", + json={"url": "http://127.0.0.1:8000/secret"}, + ) + assert blocked.status_code == 400 + + async def fake_fetch(url: str, *, timeout_seconds: int = 10): + return FetchedEvidence( + url=url, + final_url="https://example.com/article", + title="Example Report", + text="Subsea cable resilience analysis text body.", + content_hash="abc123", + extractor="ssrf_guarded_html", + ) + + monkeypatch.setattr(ai_wf_api, "safe_web_fetch", fake_fetch) + ok = await client.post( + "/api/v1/ai/playground/parse-link", + json={"url": "https://example.com/article"}, + ) + assert ok.status_code == 200 + body = ok.json() + assert body["title"] == "Example Report" + assert "Subsea cable resilience" in body["text"] + assert body["char_count"] == len("Subsea cable resilience analysis text body.") + finally: + app.dependency_overrides.clear() + + structured, images = ai_wf_api._normalize_playground_attachments( + [ + ai_wf_api.PlaygroundAttachmentInput( + kind="video", + name="clip.mp4", + mime_type="video/mp4", + metadata={"duration_seconds": 12.4}, + images=[ + ai_wf_api.ImageAttachment( + mime_type="image/jpeg", + data_base64="dGVzdGltYWdlZGF0YQ==", + name="frame-1.jpg", + ) + ], + ), + ai_wf_api.PlaygroundAttachmentInput( + kind="link", + name="Example Report", + url="https://example.com/article", + text_content="Summary text", + ), + ] + ) + assert len(structured) == 2 + assert structured[0]["image_frames_attached"] == 1 + assert "fetched_content" in structured[1] + assert len(images) == 1 + assert images[0]["mime_type"] == "image/jpeg" + + from aiprovider.provider_service import ProviderService + + openai_msgs = [{"role": "user", "content": "Inspect this frame"}] + ProviderService._apply_images_to_messages(openai_msgs, images, "openai-completions") + assert isinstance(openai_msgs[0]["content"], list) + assert openai_msgs[0]["content"][1]["type"] == "image_url" + + anthropic_msgs = [{"role": "user", "content": [{"type": "text", "text": "Inspect"}]}] + ProviderService._apply_images_to_messages(anthropic_msgs, images, "anthropic") + assert anthropic_msgs[0]["content"][1]["type"] == "image" + assert anthropic_msgs[0]["content"][1]["source"]["media_type"] == "image/jpeg" diff --git a/backend/tests/test_dag_executor.py b/backend/tests/test_dag_executor.py new file mode 100644 index 00000000..a566d7a8 --- /dev/null +++ b/backend/tests/test_dag_executor.py @@ -0,0 +1,364 @@ +"""Tests for topological DAG workflow execution, edge branching, and Earth stateless routing.""" + +from __future__ import annotations + +import json +from types import SimpleNamespace + +import pytest +from httpx import ASGITransport, AsyncClient +from sqlalchemy import create_engine, event +from sqlalchemy.orm import sessionmaker + +from app.db.session import Base, get_db +from app.main import app +from app.models.ai_workflow import AIWorkflow, AIWorkflowFixture, AIWorkflowRevision +from app.models.bgp_incident import BGPIncident +from app.models.collected_data import CollectedData +from app.models.earth_news import EarthNewsItem +from app.models.situational_assessment import InvestigationSession, WorkflowRun +from app.models.system_setting import SystemSetting +from app.services.ai.dag_executor import render_workflow_template, run_workflow_dag_stream + + +class _SyncAsAsyncSession: + def __init__(self, sync_session): + self._s = sync_session + + def add(self, obj): + return self._s.add(obj) + + async def execute(self, stmt, *args, **kwargs): + return self._s.execute(stmt, *args, **kwargs) + + async def scalar(self, stmt, *args, **kwargs): + return self._s.scalar(stmt, *args, **kwargs) + + async def get(self, model, ident): + return self._s.get(model, ident) + + async def delete(self, obj): + return self._s.delete(obj) + + async def commit(self): + return self._s.commit() + + async def rollback(self): + return self._s.rollback() + + async def refresh(self, obj): + return self._s.refresh(obj) + + async def close(self): + return self._s.close() + + +def _make_db_factory(): + engine = create_engine("sqlite:///:memory:") + event.listen( + engine, + "connect", + lambda conn, _: conn.create_function("btrim", 1, lambda v: v.strip() if isinstance(v, str) else v), + ) + Base.metadata.create_all( + engine, + tables=[ + AIWorkflow.__table__, + AIWorkflowRevision.__table__, + AIWorkflowFixture.__table__, + WorkflowRun.__table__, + InvestigationSession.__table__, + SystemSetting.__table__, + BGPIncident.__table__, + CollectedData.__table__, + EarthNewsItem.__table__, + ], + ) + sync_factory = sessionmaker(engine, expire_on_commit=False) + + class _Ctx: + def __call__(self): + return self + + async def __aenter__(self): + self._sess = _SyncAsAsyncSession(sync_factory()) + return self._sess + + async def __aexit__(self, *_args): + await self._sess.close() + + return engine, _Ctx() + + +def test_render_workflow_template_safely_interpolates_targets_and_nodes(): + rendered = render_workflow_template( + "检查 {{target.label}} ({{target.lat}}, {{target.lon}});前序={{node.step1}};全部={{targets_summary}};未知={{evil.__class__}}", + question="有什么异常", + targets=[ + { + "entity_type": "cable", + "entity_id": "cable-peace", + "label": "PEACE Cable", + "latitude": 12.3456, + "longitude": 43.21, + } + ], + node_outputs={"step1": "周边发现2艘锚泊船"}, + ) + assert "PEACE Cable" in rendered + assert "12.3456" in rendered + assert "周边发现2艘锚泊船" in rendered + assert "unknown" not in rendered and "__class__" not in rendered + + +@pytest.mark.asyncio +async def test_dag_executor_multi_llm_chain_edge_conditions_and_fly_to(): + engine, factory = _make_db_factory() + calls: list[dict] = [] + + class _FakeMultiAIClient: + async def is_ready(self): + return True, "openai", "gpt-test" + + async def analyze(self, req): + calls.append({"mode": "analyze", "objective": req.objective}) + return SimpleNamespace( + content="初筛摘要:已提取海缆坐标与船舶轨迹要点", + provider="openai", + model="gpt-fast", + ) + + async def stream_analyze(self, req, request_id=None): + calls.append({"mode": "stream", "objective": req.objective, "context": req.context}) + yield {"event": "reasoning", "delta": "正在交叉比对阶段一结论…"} + yield {"event": "text", "delta": "最终研判:海缆周边态势稳定。"} + + workflow = { + "workflow_id": "custom.multi_stage", + "name": "多阶段研判", + "active_revision": 1, + "bindings": {"prompt_template": "围绕 {{targets_summary}} 分析"}, + "published_graph": { + "nodes": [ + {"id": "trig", "node_type": "trigger", "title": "触发"}, + { + "id": "det_bgp", + "node_type": "deterministic", + "title": "BGP 快照", + "tools": ["query_bgp_incidents"], + }, + { + "id": "branch_cable_only", + "node_type": "deterministic", + "title": "海缆分支", + "tools": ["query_cable_posture"], + }, + { + "id": "branch_sat_skip", + "node_type": "deterministic", + "title": "卫星分支(应跳过)", + "tools": ["query_satellite_posture"], + }, + { + "id": "llm_stage1", + "node_type": "llm_agent", + "title": "阶段一摘要", + "system_prompt": "做初步梳理", + "prompt": "梳理 {{target.label}}", + }, + { + "id": "llm_final", + "node_type": "llm_agent", + "title": "阶段二定论", + "system_prompt": "综合定论", + "prompt": "依据阶段一结论:{{node.llm_stage1}}", + }, + { + "id": "guard", + "node_type": "guardrail", + "title": "核验声明", + "guardrails": {"append_disclaimer": "以上结论基于内置遥测实时快照。"}, + }, + { + "id": "out", + "node_type": "output", + "title": "输出联动", + "params": {"fly_to_target": True, "fly_zoom": 1.6}, + }, + ], + "edges": [ + {"id": "e1", "source": "trig", "target": "det_bgp", "condition": "always"}, + { + "id": "e2", + "source": "det_bgp", + "target": "branch_cable_only", + "condition": "on_entity_type", + "condition_value": "cable", + }, + { + "id": "e3", + "source": "det_bgp", + "target": "branch_sat_skip", + "condition": "on_entity_type", + "condition_value": "satellite", + }, + {"id": "e4", "source": "branch_cable_only", "target": "llm_stage1", "condition": "always"}, + {"id": "e5", "source": "llm_stage1", "target": "llm_final", "condition": "always"}, + {"id": "e6", "source": "llm_final", "target": "guard", "condition": "always"}, + {"id": "e7", "source": "guard", "target": "out", "condition": "always"}, + ], + }, + } + + try: + async with factory() as db: + events: list[dict] = [] + async for ev in run_workflow_dag_stream( + db=db, + workflow=workflow, + question="", + targets=[ + { + "entity_type": "cable", + "entity_id": "cable-2", + "label": "2Africa", + "latitude": 15.5, + "longitude": 41.2, + } + ], + ai_client=_FakeMultiAIClient(), + run_id="run-dag-test", + allow_external_tools=False, + ): + events.append(ev) + + skipped_nodes = [ + e["data"]["node_id"] + for e in events + if e["event"] == "node" and e["data"].get("status") == "skipped" + ] + assert "branch_sat_skip" in skipped_nodes + assert "branch_cable_only" not in skipped_nodes + + # Verify multi-LLM chaining: stage1 used analyze(), stage2 received stage1 output and used stream_analyze() + assert len(calls) == 2 + assert calls[0]["mode"] == "analyze" + assert calls[1]["mode"] == "stream" + assert "初筛摘要:已提取海缆坐标与船舶轨迹要点" in calls[1]["objective"] + + done_ev = next(e["data"] for e in events if e["event"] == "done") + assert "最终研判:海缆周边态势稳定。" in done_ev["answer_markdown"] + assert "以上结论基于内置遥测实时快照。" in done_ev["answer_markdown"] + assert done_ev["scene_spec"] == { + "fly_to": {"lat": 15.5, "lon": 41.2, "zoom": 1.6}, + "highlight_entities": ["cable-2"], + } + finally: + engine.dispose() + + +@pytest.mark.asyncio +async def test_earth_stateless_stream_executes_published_custom_workflow_and_blocks_external_tools(monkeypatch): + engine, factory = _make_db_factory() + + class _FakePublicAIClient: + llm_config = {"provider": "openai", "model": "gpt-test", "max_tokens": 4096} + + async def is_ready(self): + return True, "openai", "gpt-test" + + async def stream_analyze(self, req, request_id=None): + yield {"event": "text", "delta": f"已用已发布图回答(外部搜索跳过={req.context.get('tool_results', {}).get('web_search', {}).get('skipped')})"} + + from app.services.ai_client import get_ai_provider_client + + async def override_db(): + async with factory() as session: + yield session + + async def fake_client(): + return _FakePublicAIClient() + + app.dependency_overrides[get_db] = override_db + app.dependency_overrides[get_ai_provider_client] = fake_client + + try: + async with factory() as session: + session.add( + AIWorkflow( + workflow_id="custom.earth_pub_only", + name="公开海缆研判", + name_en="Public Cable Check", + category="custom", + is_default=False, + is_builtin=False, + active_revision=1, + published_graph={ + "nodes": [ + {"id": "t", "node_type": "trigger", "title": "Trigger"}, + { + "id": "d", + "node_type": "deterministic", + "title": "Tools", + "tools": ["web_search"], + }, + { + "id": "l", + "node_type": "llm_agent", + "title": "Published LLM", + "system_prompt": "Published prompt", + "prompt": "{{target.label}} {{question}}", + }, + ], + "edges": [ + {"id": "e1", "source": "t", "target": "d"}, + {"id": "e2", "source": "d", "target": "l"}, + ], + }, + draft_graph={ + "nodes": [ + { + "id": "l_draft", + "node_type": "llm_agent", + "title": "Draft Secret", + "system_prompt": "SHOULD NOT RUN FOR PUBLIC CALLER", + "prompt": "Draft", + } + ], + "edges": [], + }, + bindings={ + "enabled": True, + "surfaces": ["info_card"], + "entity_types": ["cable"], + "action_label": "海缆排查", + }, + ) + ) + await session.commit() + + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as client: + resp = await client.post( + "/api/v1/situational-awareness/sessions/stateless/turns/stream", + json={ + "question": "分析周边风险", + "workflow_id": "custom.earth_pub_only", + "targets": [ + { + "entity_type": "cable", + "entity_id": "cable-1", + "label": "FLAG Cable", + "latitude": 30.0, + "longitude": 32.0, + } + ], + }, + ) + assert resp.status_code == 200 + body = resp.text + assert "external_web_search_admin_only" in body + assert "l_draft" not in body + finally: + app.dependency_overrides.clear() + engine.dispose() diff --git a/backend/tests/test_location_agent_workflow.py b/backend/tests/test_location_agent_workflow.py index 2bc5f176..595ef667 100644 --- a/backend/tests/test_location_agent_workflow.py +++ b/backend/tests/test_location_agent_workflow.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +import ssl from types import SimpleNamespace import pytest @@ -363,3 +364,144 @@ async def test_tool_calling_agent_rejects_unobserved_citations_and_persists_term assert saved.verification_status == "undisclosed" finally: engine.dispose() + + +def test_nominatim_geocoder_retries_transient_ssl_eof(monkeypatch): + from app.services.location.resolvers import nominatim + + calls = {"count": 0} + + class _FakeResp: + def raise_for_status(self): + return None + + def json(self): + return [{"lat": "35.1495", "lon": "-90.0490", "display_name": "Memphis, TN", "address": {"city": "Memphis", "country": "United States"}}] + + def _fake_get(*_args, **_kwargs): + calls["count"] += 1 + if calls["count"] == 1: + raise ssl.SSLError("[SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol (_ssl.c:1081)") + return _FakeResp() + + monkeypatch.setattr(nominatim.httpx, "get", _fake_get) + geocoder = nominatim.build_default_nominatim_geocoder( + min_interval_seconds=0.0, + retry_backoff_seconds=0.0, + max_retries=2, + ) + res = geocoder("Memphis, United States") + assert res is not None + assert res["lat"] == "35.1495" + assert calls["count"] == 2 + + +@pytest.mark.asyncio +async def test_location_agent_recovers_from_geocode_verify_exception(monkeypatch): + from app.services.location import agent_resolver + + geo_calls = {"count": 0} + + def _flaky_geocoder(place_query: str): + geo_calls["count"] += 1 + if geo_calls["count"] == 1: + raise ssl.SSLError("[SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol (_ssl.c:1081)") + return { + "lat": "35.1495", + "lon": "-90.0490", + "display_name": place_query, + "city": "Memphis", + "region": "Tennessee", + "country": "United States", + } + + monkeypatch.setattr(agent_resolver, "_agent_geocoder", _flaky_geocoder) + monkeypatch.setattr( + agent_resolver, + "safe_web_fetch", + lambda url, **_kwargs: _async_val( + SimpleNamespace(url=url, final_url=url, title="Colossus", text="3231 Paul R Lowry Road, Memphis, Tennessee") + ), + ) + + class _RecoveringProvider: + def __init__(self): + self.turn = 0 + self.saw_retryable_error = False + + async def analyze(self, req): + self.turn += 1 + if self.turn == 1: + return SimpleNamespace( + content="", + tool_calls=[ + SimpleNamespace( + id="c1", + name="fetch_source_url", + arguments=json.dumps({"url": "https://example.com/colossus"}), + ) + ], + ) + if self.turn == 2: + return SimpleNamespace( + content="", + tool_calls=[ + SimpleNamespace( + id="c2", + name="geocode_verify", + arguments=json.dumps({"place_query": "3231 Paul R Lowry Road, Memphis", "country": "United States"}), + ) + ], + ) + if self.turn == 3: + last_msg = req.messages[-1].content if req.messages else "" + if "geocoder request failed" in str(last_msg): + self.saw_retryable_error = True + return SimpleNamespace( + content="", + tool_calls=[ + SimpleNamespace( + id="c3", + name="geocode_verify", + arguments=json.dumps({"place_query": "Memphis, Tennessee", "country": "United States"}), + ) + ], + ) + return SimpleNamespace( + content="", + tool_calls=[ + SimpleNamespace( + id="c4", + name="submit_location_result", + arguments=json.dumps( + { + "status": "located", + "facility_name": "Colossus Memphis", + "city": "Memphis", + "region": "Tennessee", + "country": "United States", + "precision": "city", + "geocode_candidate_id": "geo_1", + "citations": ["https://example.com/colossus"], + "confidence": 0.9, + "reasoning": "Recovered after geocode retry", + } + ), + ) + ], + ) + + provider = _RecoveringProvider() + res, term = await run_controlled_location_agent( + provider_client=provider, + web_search_client=None, + query=LocationQuery(name="Colossus Memphis", country="United States"), + ) + assert provider.saw_retryable_error is True + assert term is None + assert len(res.candidates) == 1 + assert res.candidates[0].city == "Memphis" + + +async def _async_val(val): + return val diff --git a/backend/tests/test_workflow_evolver.py b/backend/tests/test_workflow_evolver.py new file mode 100644 index 00000000..1be3938c --- /dev/null +++ b/backend/tests/test_workflow_evolver.py @@ -0,0 +1,672 @@ +"""Tests for 3-tier AI workflow self-evolution, constitution kernel, canary rollback, and meta-evolution.""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta +from types import SimpleNamespace + +import pytest +from httpx import ASGITransport, AsyncClient +from sqlalchemy import create_engine, select +from sqlalchemy.orm import sessionmaker + +from app.core.access_gate import require_admin_user +from app.db.session import Base, get_db +from app.main import app +from app.models.ai_workflow import AIWorkflow, AIWorkflowFixture, AIWorkflowRevision +from app.models.bgp_incident import BGPIncident +from app.models.collected_data import CollectedData +from app.models.earth_news import EarthNewsItem +from app.models.situational_assessment import WorkflowRun +from app.models.system_setting import SystemSetting +from app.services.ai.workflow_evolver import ( + META_WORKFLOW_ID, + append_ledger_entry, + evaluate_canary_and_maybe_rollback, + validate_evolution_patch, +) +from app.services.ai.workflow_registry import ( + create_workflow, + ensure_builtin_workflows, + list_public_workflow_bindings, +) + + +class _SyncAsAsyncSession: + def __init__(self, sync_session): + self._s = sync_session + + def add(self, obj): + return self._s.add(obj) + + async def execute(self, stmt, *args, **kwargs): + return self._s.execute(stmt, *args, **kwargs) + + async def scalar(self, stmt, *args, **kwargs): + return self._s.scalar(stmt, *args, **kwargs) + + async def get(self, model, ident): + return self._s.get(model, ident) + + async def delete(self, obj): + return self._s.delete(obj) + + async def commit(self): + return self._s.commit() + + async def rollback(self): + return self._s.rollback() + + async def refresh(self, obj): + return self._s.refresh(obj) + + async def close(self): + return self._s.close() + + +async def _make_sqlite_session(): + from sqlalchemy import event + + engine = create_engine("sqlite:///:memory:") + event.listen( + engine, + "connect", + lambda conn, _: conn.create_function("btrim", 1, lambda v: v.strip() if isinstance(v, str) else v), + ) + Base.metadata.create_all( + engine, + tables=[ + AIWorkflow.__table__, + AIWorkflowRevision.__table__, + AIWorkflowFixture.__table__, + WorkflowRun.__table__, + SystemSetting.__table__, + BGPIncident.__table__, + CollectedData.__table__, + EarthNewsItem.__table__, + ], + ) + sync_factory = sessionmaker(engine, expire_on_commit=False) + + class _Ctx: + def __call__(self): + return self + + async def __aenter__(self): + self._sess = _SyncAsAsyncSession(sync_factory()) + return self._sess + + async def __aexit__(self, *_args): + await self._sess.close() + + return engine, _Ctx() + + +@pytest.mark.asyncio +async def test_meta_workflow_seeded_excluded_from_public_and_single_level_recursion_locked(): + engine, factory = await _make_sqlite_session() + try: + async with factory() as db: + await ensure_builtin_workflows(db) + meta_row = ( + await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == META_WORKFLOW_ID)) + ).scalar_one_or_none() + assert meta_row is not None + assert meta_row.category == "meta" + node_ids = [n["id"] for n in meta_row.published_graph["nodes"]] + assert node_ids == ["diag_node", "patch_node", "verify_output"] + + public_items = await list_public_workflow_bindings(db) + assert all(item["workflow_id"] != META_WORKFLOW_ID for item in public_items) + + # Single-level recursion lock: custom `meta.*` workflows are forbidden + with pytest.raises(Exception) as exc_info: + await create_workflow(db, workflow_id="meta.nested_evolver", name="Nested Meta") + assert getattr(exc_info.value, "status_code", None) == 400 + finally: + engine.dispose() + + +def test_tier0_constitution_validator_enforces_meta_freeze_and_blast_radius(): + base_meta_graph = { + "nodes": [ + { + "id": "diag_node", + "node_type": "llm_agent", + "title": "Diag", + "position": {"x": 80, "y": 140}, + "enabled": True, + "system_prompt": "Diagnose traces cleanly.", + "prompt": "Check traces.", + "tools": [], + "thinking_enabled": True, + "max_steps": 1, + "timeout_seconds": 60, + }, + { + "id": "patch_node", + "node_type": "llm_agent", + "title": "Patch", + "position": {"x": 460, "y": 140}, + "enabled": True, + "system_prompt": "Output strict JSON with node_patches.", + "prompt": "Produce JSON.", + "tools": [], + "thinking_enabled": True, + "max_steps": 1, + "timeout_seconds": 60, + }, + { + "id": "verify_output", + "node_type": "guardrail", + "title": "Constitution", + "position": {"x": 840, "y": 140}, + "enabled": True, + "system_prompt": "", + "prompt": "", + "tools": [], + "thinking_enabled": False, + "max_steps": 1, + "timeout_seconds": 60, + "guardrails": {"immutable_tier0": True}, + }, + ], + "edges": [ + {"id": "e1", "source": "diag_node", "target": "patch_node"}, + {"id": "e2", "source": "patch_node", "target": "verify_output"}, + ], + } + + # 1. Touching frozen `verify_output` is blocked + bad_meta = {**base_meta_graph, "nodes": list(base_meta_graph["nodes"])} + ok, violations = validate_evolution_patch( + base_meta_graph, + bad_meta, + [{"node_id": "verify_output", "field": "enabled", "before": True, "after": False}], + is_meta=True, + is_auto=True, + ) + assert not ok + assert any("verify_output" in v for v in violations) + + # 2. Removing JSON output constraint from `patch_node` is blocked + bad_json_meta = { + "nodes": [ + base_meta_graph["nodes"][0], + {**base_meta_graph["nodes"][1], "system_prompt": "Just talk freely", "prompt": "Write prose"}, + base_meta_graph["nodes"][2], + ], + "edges": base_meta_graph["edges"], + } + ok2, violations2 = validate_evolution_patch( + base_meta_graph, + bad_json_meta, + [{"node_id": "patch_node", "field": "system_prompt"}], + is_meta=True, + is_auto=True, + ) + assert not ok2 + assert any("node_patches" in v for v in violations2) + + # 3. Auto-mode blast radius (> 1 node on meta) is blocked + ok3, violations3 = validate_evolution_patch( + base_meta_graph, + base_meta_graph, + [ + {"node_id": "diag_node", "field": "prompt"}, + {"node_id": "patch_node", "field": "prompt"}, + ], + is_meta=True, + is_auto=True, + ) + assert not ok3 + assert any("半径" in v for v in violations3) + + +@pytest.mark.asyncio +async def test_evolution_policy_feedback_health_model_drift_and_dgm_archive(monkeypatch): + engine, factory = await _make_sqlite_session() + + class _FakeAI: + async def is_ready(self): + return True, "gemini", "gemini-2.5-flash" + + async def analyze(self, req): + return SimpleNamespace( + content='{"summary": "Mocked proposal", "node_patches": []}' + ) + + async def fake_get_ai_client(_db): + return _FakeAI() + + monkeypatch.setattr("app.api.v1.ai_workflows.get_ai_provider_client", fake_get_ai_client) + monkeypatch.setattr("app.services.ai.workflow_evolver.get_ai_provider_client", fake_get_ai_client) + + async def override_db(): + async with factory() as session: + yield session + + def override_admin(): + return SimpleNamespace(id=1, username="admin", role="admin", email="admin@test") + + app.dependency_overrides[get_db] = override_db + app.dependency_overrides[require_admin_user] = override_admin + transport = ASGITransport(app=app) + try: + async with factory() as db: + await ensure_builtin_workflows(db) + # Seed runs: 5 runs under older model at v1, plus 1 failure + now = datetime.now(UTC) + for idx in range(5): + db.add( + WorkflowRun( + id=f"run_seed_{idx}", + workflow_id="default.general", + status="failed" if idx == 4 else "completed", + access_tier="admin", + actor_key="admin", + question=f"BGP AS4837 路由异常查询 #{idx}", + input_params={}, + tool_trace=["intent_router", "advisor_agent"], + budget_used={ + "steps": 2, + "model_used": "MiniMax-M3.1-Flash", + "latency_ms": 620 + idx * 50, + "workflow_revision": 1, + }, + error_message="missing citation URL" if idx == 4 else "", + started_at=now - timedelta(minutes=20 - idx), + completed_at=now - timedelta(minutes=19 - idx), + ) + ) + await db.commit() + + async with AsyncClient(transport=transport, base_url="http://test") as client: + # 1. Submit negative & positive feedback + fb_resp = await client.post( + "/api/v1/ai/runs/run_seed_1/feedback", + json={"rating": -1, "note": "缺少一手链接取证"}, + ) + assert fb_resp.status_code == 200 + assert fb_resp.json()["budget_used"]["user_rating"] == -1 + assert fb_resp.json()["budget_used"]["feedback_note"] == "缺少一手链接取证" + + neg_runs = await client.get("/api/v1/ai/runs", params={"feedback": "negative"}) + assert neg_runs.status_code == 200 + neg_ids = {item["id"] for item in neg_runs.json()["items"]} + assert "run_seed_1" in neg_ids + assert "run_seed_4" in neg_ids + + # 2. Policy get/update + pol_resp = await client.put( + "/api/v1/ai/evolution/policy", + json={"business_mode": "auto", "meta_mode": "draft", "daily_auto_budget": 5}, + ) + assert pol_resp.status_code == 200 + assert pol_resp.json()["business_mode"] == "auto" + assert pol_resp.json()["meta_mode"] == "draft" + assert pol_resp.json()["daily_auto_budget"] == 5 + + # 3. 0-Token Health Check: detects model drift + unused tool + signals + health_resp = await client.get("/api/v1/ai/evolution/health/default.general") + assert health_resp.status_code == 200 + health = health_resp.json() + assert health["total_runs"] == 5 + assert health["downvotes"] == 1 + assert health["model_drift_detected"] is True + assert "query_global_situational" in health["unused_tools"] + + # 4. Propose `model_adapt` (deterministic fallback fills minimal patch) + prop_resp = await client.post( + "/api/v1/ai/evolution/propose/default.general", + json={"mode": "model_adapt", "apply_mode": "preview"}, + ) + assert prop_resp.status_code == 200 + prop = prop_resp.json() + assert prop["constitution_ok"] is True + assert len(prop["changes"]) >= 1 + + # 5. Incubate new custom workflow from `default.general` BGP runs + inc_resp = await client.post("/api/v1/ai/evolution/incubate") + assert inc_resp.status_code == 200 + inc = inc_resp.json() + assert inc["suggested_workflow_id"].startswith("custom.") + assert "bgp" in inc["suggested_workflow_id"] + assert len(inc["graph"]["nodes"]) == 3 + finally: + app.dependency_overrides.clear() + engine.dispose() + + +@pytest.mark.asyncio +async def test_canary_auto_rollback_and_meta_canary_rollback(monkeypatch): + engine, factory = await _make_sqlite_session() + + class _NoAIClient: + async def is_ready(self): + return False, "unconfigured", "" + + async def fake_get_ai_client(_db): + return _NoAIClient() + + monkeypatch.setattr("app.api.v1.ai_workflows.get_ai_provider_client", fake_get_ai_client) + monkeypatch.setattr("app.services.ai.workflow_evolver.get_ai_provider_client", fake_get_ai_client) + + async def override_db(): + async with factory() as session: + yield session + + def override_admin(): + return SimpleNamespace(id=1, username="admin", role="admin", email="admin@test") + + app.dependency_overrides[get_db] = override_db + app.dependency_overrides[require_admin_user] = override_admin + transport = ASGITransport(app=app) + try: + async with AsyncClient(transport=transport, base_url="http://test") as client: + # First run a meta-evolution in `auto` mode so meta v2 enters canary window + await client.put( + "/api/v1/ai/evolution/policy", + json={"business_mode": "auto", "meta_mode": "auto"}, + ) + meta_pub = await client.post( + "/api/v1/ai/evolution/meta-evolve", + json={"instruction": "Prefer minimal single-node changes.", "apply_mode": "auto"}, + ) + assert meta_pub.status_code == 200 + assert meta_pub.json()["applied_status"] == "auto_published" + assert meta_pub.json()["new_revision"] == 2 + + # Auto-publish default.general v2 (uses live meta v2) + evo_pub = await client.post( + "/api/v1/ai/evolution/propose/default.general", + json={ + "mode": "optimize", + "instruction": "Require primary search verification", + "apply_mode": "auto", + }, + ) + assert evo_pub.status_code == 200 + assert evo_pub.json()["applied_status"] == "auto_published" + assert evo_pub.json()["new_revision"] == 2 + + # Simulate 2 consecutive failed runs on v2 -> canary triggers rollback to v1 + async with factory() as db: + now = datetime.now(UTC) + timedelta(seconds=2) + for idx in range(2): + db.add( + WorkflowRun( + id=f"run_canary_fail_{idx}", + workflow_id="default.general", + status="failed", + access_tier="admin", + actor_key="admin", + question="fail test", + input_params={}, + tool_trace=["intent_router"], + budget_used={"workflow_revision": 2}, + error_message="boom", + started_at=now + timedelta(seconds=idx), + completed_at=now + timedelta(seconds=idx + 1), + ) + ) + await db.commit() + res = await evaluate_canary_and_maybe_rollback(db, "default.general") + assert res is not None and res["action"] == "rolled_back" + + wf_row = ( + await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == "default.general")) + ).scalar_one() + # Rollback publishes a new revision v3 carrying v1 graph + assert wf_row.active_revision == 3 + + # Add a 2nd rolled_back downstream outcome in ledger -> meta-canary rolls back meta v2! + await append_ledger_entry( + db, + { + "workflow_id": "brief.bgp", + "mode": "optimize", + "trigger": "auto_post_run", + "status": "rolled_back", + "base_revision": 1, + "target_revision": 2, + "summary": "second failure under meta v2", + "created_at": (now + timedelta(seconds=5)).isoformat(), + }, + ) + # Re-run meta canary check via another canary evaluation + from app.services.ai.workflow_evolver import _evaluate_meta_canary + + await _evaluate_meta_canary(db) + meta_row = ( + await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == META_WORKFLOW_ID)) + ).scalar_one() + assert meta_row.active_revision == 3 + + # Cooldown / ledger inspectable & dismissible + led_resp = await client.get("/api/v1/ai/evolution/ledger") + assert led_resp.status_code == 200 + entries = led_resp.json()["items"] + assert any(e["workflow_id"] == META_WORKFLOW_ID and e["status"] == "rolled_back" for e in entries) + finally: + app.dependency_overrides.clear() + engine.dispose() + + +@pytest.mark.asyncio +async def test_fixture_ab_eval_endpoint(monkeypatch): + engine, factory = await _make_sqlite_session() + + class _FakeStreamAI: + async def is_ready(self): + return True, "minimax", "MiniMax-M3.1-Flash" + + async def stream_analyze(self, _req, request_id=None): + yield {"event": "text", "delta": "全球态势核心节点运行稳定。"} + + async def fake_get_ai_client(_db): + return _FakeStreamAI() + + monkeypatch.setattr("app.services.ai.workflow_evolver.get_ai_provider_client", fake_get_ai_client) + + async def override_db(): + async with factory() as session: + yield session + + def override_admin(): + return SimpleNamespace(id=1, username="admin", role="admin", email="admin@test") + + app.dependency_overrides[get_db] = override_db + app.dependency_overrides[require_admin_user] = override_admin + transport = ASGITransport(app=app) + try: + async with AsyncClient(transport=transport, base_url="http://test") as client: + fix = await client.post( + "/api/v1/ai/workflows/default.general/fixtures", + json={"name": "Sample Global", "sample_question": "全球态势摘要", "context_json": {"domain": "global"}}, + ) + assert fix.status_code == 200 + detail = (await client.get("/api/v1/ai/workflows/default.general")).json() + graph = detail["workflow"]["published_graph"] + + eval_resp = await client.post( + "/api/v1/ai/evolution/eval/default.general", + json={"proposed_graph": graph, "max_fixtures": 2}, + ) + assert eval_resp.status_code == 200 + ev = eval_resp.json() + assert ev["fixture_count"] == 1 + assert ev["base_passed"] == 1 + assert ev["proposed_passed"] == 1 + assert ev["verdict"] in {"neutral", "improved", "slower"} + finally: + app.dependency_overrides.clear() + engine.dispose() + + +@pytest.mark.asyncio +async def test_lock_quota_cooldown_dgm_branching_canary_verify_and_ledger_dismiss(monkeypatch): + engine, factory = await _make_sqlite_session() + + class _NoAIClient: + async def is_ready(self): + return False, "unconfigured", "" + + async def fake_get_ai_client(_db): + return _NoAIClient() + + monkeypatch.setattr("app.api.v1.ai_workflows.get_ai_provider_client", fake_get_ai_client) + monkeypatch.setattr("app.services.ai.workflow_evolver.get_ai_provider_client", fake_get_ai_client) + + async def override_db(): + async with factory() as session: + yield session + + def override_admin(): + return SimpleNamespace(id=1, username="admin", role="admin", email="admin@test") + + app.dependency_overrides[get_db] = override_db + app.dependency_overrides[require_admin_user] = override_admin + transport = ASGITransport(app=app) + try: + async with AsyncClient(transport=transport, base_url="http://test") as client: + # 1. Locked workflow blocks `apply_mode="auto"` + await client.put( + "/api/v1/ai/evolution/policy", + json={"business_mode": "auto", "locked_workflows": ["default.general"], "daily_auto_budget": 2}, + ) + locked_resp = await client.post( + "/api/v1/ai/evolution/propose/default.general", + json={"mode": "optimize", "instruction": "Tighten citations", "apply_mode": "auto"}, + ) + assert locked_resp.status_code == 200 + assert locked_resp.json()["applied_status"] == "blocked" + assert "锁定" in locked_resp.json()["blocked_reason"] + + # Unlock and set daily_auto_budget=1 so 2nd auto run hits budget cap + await client.put( + "/api/v1/ai/evolution/policy", + json={"locked_workflows": [], "daily_auto_budget": 2}, + ) + pub1 = await client.post( + "/api/v1/ai/evolution/propose/default.general", + json={"mode": "optimize", "instruction": "Always cite verified telemetry", "apply_mode": "auto"}, + ) + assert pub1.status_code == 200 + assert pub1.json()["applied_status"] == "auto_published" + rev_v2 = pub1.json()["new_revision"] + assert rev_v2 == 2 + + # Seed 5 good runs on v2 -> Canary verifies cleanly + async with factory() as db: + now = datetime.now(UTC) + timedelta(seconds=2) + for idx in range(5): + db.add( + WorkflowRun( + id=f"run_ok_v2_{idx}", + workflow_id="default.general", + status="completed", + access_tier="admin", + actor_key="admin", + question=f"Verified query {idx}", + input_params={}, + tool_trace=["intent_router", "advisor_agent"], + budget_used={"workflow_revision": rev_v2, "user_rating": 1}, + error_message="", + started_at=now + timedelta(seconds=idx), + completed_at=now + timedelta(seconds=idx + 1), + ) + ) + await db.commit() + canary_ok = await evaluate_canary_and_maybe_rollback(db, "default.general") + assert canary_ok is not None and canary_ok["action"] == "verified" + + # Now seed 4 good runs on v1 and 3 failed runs on a degraded v3 to trigger DGM parent recommendation + v1_rev = ( + await db.execute( + select(AIWorkflowRevision) + .where(AIWorkflowRevision.workflow_id == "default.general") + .where(AIWorkflowRevision.revision == 1) + ) + ).scalar_one() + from app.services.ai.workflow_registry import publish_workflow + + await publish_workflow( + db, + "default.general", + graph=v1_rev.graph_json, + change_summary="manual degraded v3", + actor="admin", + ) + for idx in range(4): + db.add( + WorkflowRun( + id=f"run_v1_best_{idx}", + workflow_id="default.general", + status="completed", + access_tier="admin", + actor_key="admin", + question="v1 baseline", + input_params={}, + tool_trace=["intent_router"], + budget_used={"workflow_revision": 1, "user_rating": 1}, + error_message="", + started_at=now + timedelta(seconds=10 + idx), + completed_at=now + timedelta(seconds=11 + idx), + ) + ) + for idx in range(3): + db.add( + WorkflowRun( + id=f"run_v3_bad_{idx}", + workflow_id="default.general", + status="failed", + access_tier="admin", + actor_key="admin", + question="v3 degraded", + input_params={}, + tool_trace=["intent_router"], + budget_used={"workflow_revision": 3, "user_rating": -1}, + error_message="degraded", + started_at=now + timedelta(seconds=20 + idx), + completed_at=now + timedelta(seconds=21 + idx), + ) + ) + await db.commit() + + # Health recommends parent v2 (or v1) over degraded v3, and branch_from_best picks it + h = (await client.get("/api/v1/ai/evolution/health/default.general")).json() + assert h["recommended_parent_revision"] in {1, 2} + branch_prop = ( + await client.post( + "/api/v1/ai/evolution/propose/default.general", + json={"mode": "optimize", "instruction": "Recovery patch", "apply_mode": "preview", "branch_from_best": True}, + ) + ).json() + assert branch_prop["base_revision"] == h["recommended_parent_revision"] + + # Cooldown blocks immediate 2nd `auto` propose while recent ledger entry is active + cd_resp = ( + await client.post( + "/api/v1/ai/evolution/propose/default.general", + json={"mode": "optimize", "instruction": "Another auto change", "apply_mode": "auto"}, + ) + ).json() + assert cd_resp["applied_status"] == "blocked" + assert "冷却" in cd_resp["blocked_reason"] + + # Check ledger & dismiss an entry + ledger_items = (await client.get("/api/v1/ai/evolution/ledger")).json()["items"] + target_entry = next( + e for e in ledger_items if e["workflow_id"] == "default.general" and e["status"] == "verified" + ) + dis = await client.post( + f"/api/v1/ai/evolution/ledger/{target_entry['id']}/dismiss", + json={"reason": "Not needed right now"}, + ) + assert dis.status_code == 200 + assert dis.json()["status"] == "dismissed" + finally: + app.dependency_overrides.clear() + engine.dispose() + diff --git a/client/package.json b/client/package.json index e7bd0f49..33da7b2d 100644 --- a/client/package.json +++ b/client/package.json @@ -1,6 +1,6 @@ { "name": "planet-client", - "version": "0.81.0", + "version": "0.82.0", "description": "Intelligent Planet Program - Native Electron Earth Viewer", "private": true, "packageManager": "bun@1", diff --git a/client/src/main/gpu-monitor.ts b/client/src/main/gpu-monitor.ts index a16dad64..138db31b 100644 --- a/client/src/main/gpu-monitor.ts +++ b/client/src/main/gpu-monitor.ts @@ -18,6 +18,7 @@ import { type StartupGpuDecision, type StartupGpuDecisionReason, } from './gpu-policy' +import { tClient } from './i18n' const execFileAsync = promisify(execFile) @@ -296,14 +297,20 @@ export function createAdaptiveGpuMonitor(options: { } if (record.reason === 'low-fps-low-vram') { return record.target === 'software' - ? { message: '独显显存不足且帧率偏低,已自动切换至 CPU 软渲染', type: 'info' } + ? { + message: tClient('独显显存不足且帧率偏低,已自动切换至软件兼容渲染', 'Low VRAM and FPS; switched to software rendering'), + type: 'info', + } : { - message: '独显显存不足且帧率偏低,已自动切换至集成核显渲染(保留全部特效)', + message: tClient('独显显存不足且帧率偏低,已自动切换至节能核显', 'Low VRAM and FPS; switched to integrated GPU'), type: 'info', } } if (record.reason === 'vram-recovered') { - return { message: '独显显存已充足,已自动切回独立显卡渲染', type: 'success' } + return { + message: tClient('独显显存已充足,已自动切回高性能显卡', 'VRAM recovered; switched back to high-performance GPU'), + type: 'success', + } } return null }, diff --git a/client/src/main/hot-updater.ts b/client/src/main/hot-updater.ts index 705f66e2..a2f593c1 100644 --- a/client/src/main/hot-updater.ts +++ b/client/src/main/hot-updater.ts @@ -12,6 +12,7 @@ import { shouldSuppressUpdatePrompt, type ClientUpdateManifest, } from './hot-update-core' +import { tClient } from './i18n' export interface HotUpdateVersionInfo { shellVersion: string @@ -129,7 +130,10 @@ export function createHotUpdateController(options: { pendingVerification = false markHotfixVerified(options.userDataDir) options.onOverlayChanged(overlayRoot, activeBundleVersion) - notifyStatus(`热更新已生效 / Hotfix v${activeBundleVersion} active`, 'success') + notifyStatus( + tClient(`更新已生效 (v${activeBundleVersion})`, `Update v${activeBundleVersion} active`), + 'success', + ) } const handleRendererCrash = () => { @@ -146,7 +150,10 @@ export function createHotUpdateController(options: { } const applyHotfixBundle = async (bundleUrl: string, version: string, expectedSha256: string) => { - notifyStatus(`正在下载热更新 v${version}… / Downloading hotfix v${version}…`, 'info') + notifyStatus( + tClient(`正在下载更新 v${version}…`, `Downloading update v${version}…`), + 'info', + ) const response = await fetchWithTimeout(fetchImpl, bundleUrl, DOWNLOAD_TIMEOUT_MS, { cache: 'no-store', }) @@ -198,10 +205,10 @@ export function createHotUpdateController(options: { if (manual) { await showBox({ type: 'warning', - title: '检查更新失败 / Update Check Failed', - message: '无法获取版本清单,请确认服务端连接正常。', + title: tClient('检查更新失败', 'Update Check Failed'), + message: tClient('无法获取版本清单,请确认网络连接正常。', 'Unable to fetch update manifest. Please check your connection.'), detail, - buttons: ['确定 / OK'], + buttons: [tClient('确定', 'OK')], }) } else { console.warn('[planet-client] Startup update check skipped:', detail) @@ -221,10 +228,13 @@ export function createHotUpdateController(options: { if (manual) { await showBox({ type: 'info', - title: '当前已是最新版本 / Up to Date', - message: 'Planet Earth 客户端已是最新版本。', - detail: `外壳版本 / Shell: v${options.shellVersion}\n地球业务包 / Earth Bundle: v${activeBundleVersion}`, - buttons: ['确定 / OK'], + title: tClient('当前已是最新版本', 'Up to Date'), + message: tClient('智能星球客户端已是最新版本。', 'Intelligent Planet is up to date.'), + detail: tClient( + `当前版本:v${activeBundleVersion}`, + `Version: v${activeBundleVersion}`, + ), + buttons: [tClient('确定', 'OK')], }) } return @@ -238,13 +248,18 @@ export function createHotUpdateController(options: { if (decision.kind === 'hotfix-update') { const { bundle } = decision - const notes = bundle.releaseNotes?.trim() ? `\n\n更新内容:\n${bundle.releaseNotes.trim()}` : '' + const rawNotes = bundle.releaseNotes?.trim() || '' + const notesZh = rawNotes ? `\n\n更新内容:\n${rawNotes}` : '' + const notesEn = rawNotes ? `\n\nRelease notes:\n${rawNotes}` : '' const { response } = await showBox({ type: 'info', - title: '发现新版本 / Update Available', - message: `发现 Planet Earth 增量热更新 v${bundle.version}`, - detail: `当前地球版本 v${activeBundleVersion} → 最新版本 v${bundle.version}\n更新方式:轻量热更新(无需重新安装,应用后自动生效)${notes}`, - buttons: ['立即更新 / Update Now', '稍后提醒 / Later'], + title: tClient('发现新版本', 'Update Available'), + message: tClient(`发现新版本更新 v${bundle.version}`, `Update v${bundle.version} available`), + detail: tClient( + `当前版本 v${activeBundleVersion} → 最新版本 v${bundle.version}\n支持在线更新,无需重新安装。${notesZh}`, + `Current v${activeBundleVersion} → Latest v${bundle.version}\nOnline update ready, no reinstall required.${notesEn}`, + ), + buttons: [tClient('立即更新', 'Update Now'), tClient('稍后提醒', 'Later')], defaultId: 0, cancelId: 1, }) @@ -261,25 +276,33 @@ export function createHotUpdateController(options: { console.error('[planet-client] Hotfix installation failed:', detail) await showBox({ type: 'error', - title: '热更新失败 / Hotfix Failed', - message: `热更新包 v${bundle.version} 下载或校验失败,已保留当前版本运行。`, + title: tClient('更新失败', 'Update Failed'), + message: tClient( + `更新包 v${bundle.version} 下载或校验失败,将继续使用当前版本。`, + `Failed to download or verify update v${bundle.version}. Keeping current version.`, + ), detail, - buttons: ['确定 / OK'], + buttons: [tClient('确定', 'OK')], }) } return } const { shell: shellInfo, mandatory } = decision - const notes = shellInfo.releaseNotes?.trim() ? `\n\n更新说明:\n${shellInfo.releaseNotes.trim()}` : '' + const rawNotes = shellInfo.releaseNotes?.trim() || '' + const notesZh = rawNotes ? `\n\n更新说明:\n${rawNotes}` : '' + const notesEn = rawNotes ? `\n\nRelease notes:\n${rawNotes}` : '' const { response } = await showBox({ type: mandatory ? 'warning' : 'info', - title: '发现客户端大版本更新 / Major Client Update', + title: tClient('发现客户端重要更新', 'Major Update Available'), message: mandatory - ? `当前客户端版本 v${options.shellVersion} 过低,需升级至 v${shellInfo.version}` - : `发现客户端新版本 v${shellInfo.version}`, - detail: `当前客户端外壳:v${options.shellVersion}\n最新版本:v${shellInfo.version}\n该版本包含底层架构或原生壳变更,需下载安装包覆盖更新。${notes}`, - buttons: ['前往下载 / Download', '稍后提醒 / Later'], + ? tClient(`当前版本 v${options.shellVersion} 过低,需升级至 v${shellInfo.version}`, `Current version v${options.shellVersion} requires upgrading to v${shellInfo.version}`) + : tClient(`发现客户端新版本 v${shellInfo.version}`, `New version v${shellInfo.version} available`), + detail: tClient( + `当前版本:v${options.shellVersion}\n最新版本:v${shellInfo.version}\n请下载新版安装包完成升级。${notesZh}`, + `Current version: v${options.shellVersion}\nLatest version: v${shellInfo.version}\nPlease download the installer to upgrade.${notesEn}`, + ), + buttons: [tClient('前往下载', 'Download'), tClient('稍后提醒', 'Later')], defaultId: 0, cancelId: 1, }) diff --git a/client/src/main/i18n.ts b/client/src/main/i18n.ts new file mode 100644 index 00000000..b2fe5c4c --- /dev/null +++ b/client/src/main/i18n.ts @@ -0,0 +1,46 @@ +export type ClientLocale = 'zh-CN' | 'en-US' + +let overrideLocale: ClientLocale | null = null + +/** + * Normalize any Electron / BCP-47 locale tag to our two supported UI locales. + */ +export function normalizeClientLocale(raw: unknown): ClientLocale { + if (typeof raw !== 'string') return 'zh-CN' + const normalized = raw.trim().toLowerCase() + if (normalized.startsWith('en')) return 'en-US' + return 'zh-CN' +} + +/** + * Resolve the active Electron desktop UI locale from explicit override, + * environment hint, or Electron app locale when running inside the main process. + */ +export function getClientLocale(): ClientLocale { + if (overrideLocale) return overrideLocale + const envLocale = process.env.PLANET_LOCALE || process.env.LANG + if (envLocale && envLocale.trim().toLowerCase().startsWith('en')) { + return 'en-US' + } + try { + // eslint-disable-next-line @typescript-eslint/no-require-imports + const electronMod = require('electron') as { app?: { getLocale?: () => string; isReady?: () => boolean } } + const appLocale = electronMod?.app?.getLocale?.() + if (appLocale) return normalizeClientLocale(appLocale) + } catch { + // Allow importing in pure Bun unit tests outside Electron runtime. + } + return 'zh-CN' +} + +export function setClientLocale(raw: unknown): ClientLocale { + overrideLocale = normalizeClientLocale(raw) + return overrideLocale +} + +/** + * Select pure Chinese or pure English copy for Electron native chrome and dialogs. + */ +export function tClient(zh: string, en: string): string { + return getClientLocale() === 'en-US' ? en : zh +} diff --git a/client/src/main/index.ts b/client/src/main/index.ts index f31cc2ed..2eadec2a 100644 --- a/client/src/main/index.ts +++ b/client/src/main/index.ts @@ -10,6 +10,7 @@ import { createAdaptiveGpuMonitor, probeWindowsGpuEnvironmentSync } from './gpu- import { buildGpuHandoffArgs, chooseStartupGpuTarget, isGpuProcessCrash, resolveChromiumGpuSwitches, stripGpuOverrideArgs, type ResolvedGpuTarget } from './gpu-policy' import { PERIODIC_UPDATE_CHECK_INTERVAL_MS } from './hot-update-core' import { createHotUpdateController } from './hot-updater' +import { tClient } from './i18n' import { buildApplicationMenu } from './menu' import { EARTH_ORIGIN, installEarthSessionHandlers, registerEarthScheme } from './protocol' import { createScreenRecorderController } from './screen-recorder' @@ -250,10 +251,10 @@ if (!singleInstanceLock) { const targetWin = mainWindow && !mainWindow.isDestroyed() ? mainWindow : undefined const boxOptions = { type: 'info' as const, - title: '渲染设备设置 / GPU Mode', - message: '渲染设备模式已更新,需重启客户端生效', - detail: '是否立即重启 Planet Earth?(重启约需 1-2 秒,将保留全部视觉特效)', - buttons: ['立即重启 / Restart Now', '稍后手动重启 / Later'], + title: tClient('渲染模式设置', 'Graphics Mode'), + message: tClient('渲染模式已更改,需重启应用生效', 'Graphics mode updated. Restart to apply.'), + detail: tClient('是否立即重启?重启约需 1-2 秒。', 'Restart now? This takes about 1–2 seconds.'), + buttons: [tClient('立即重启', 'Restart Now'), tClient('稍后重启', 'Later')], defaultId: 0, cancelId: 1, } diff --git a/client/src/main/menu.ts b/client/src/main/menu.ts index 16234d27..df7375b8 100644 --- a/client/src/main/menu.ts +++ b/client/src/main/menu.ts @@ -3,23 +3,27 @@ import { app, Menu, shell, type BrowserWindow, type MenuItemConstructorOptions } import type { DesktopConfigStore, GpuRenderMode, SplashTheme } from './config' import type { GpuRuntimeSummary } from './gpu-monitor' import type { HotUpdateVersionInfo } from './hot-updater' +import { tClient } from './i18n' import type { RecordingStatusSnapshot } from './recording-core' import { openServerSettingsDialog, toggleWindowOrientation } from './window' function formatGpuSummaryLabel(summary: GpuRuntimeSummary): string { const targetLabel = summary.activeTarget === 'low-power' - ? '集成核显' + ? tClient('节能核显', 'Integrated GPU') : summary.activeTarget === 'software' - ? 'CPU 软渲染' + ? tClient('软件兼容渲染', 'Software Rendering') : summary.activeTarget === 'high-performance' || summary.latestVramSample - ? '独立显卡' - : '硬件 GPU' - const modeTag = summary.requestedMode === 'auto' ? '自动' : '手动' + ? tClient('高性能显卡', 'High-Performance GPU') + : tClient('硬件加速', 'Hardware GPU') + const modeTag = summary.requestedMode === 'auto' ? tClient('自动', 'Auto') : tClient('手动', 'Manual') const vramTag = summary.latestVramSample - ? ` · 独显空闲 ${(summary.latestVramSample.freeMiB / 1024).toFixed(1)} GB` + ? tClient( + ` · 可用显存 ${(summary.latestVramSample.freeMiB / 1024).toFixed(1)} GB`, + ` · ${(summary.latestVramSample.freeMiB / 1024).toFixed(1)} GB free`, + ) : '' - return `当前生效: ${targetLabel} (${modeTag}${vramTag})` + return tClient(`当前运行: ${targetLabel} (${modeTag}${vramTag})`, `Active: ${targetLabel} (${modeTag}${vramTag})`) } export function buildApplicationMenu(options: { @@ -89,15 +93,15 @@ export function buildApplicationMenu(options: { ] : []), { - label: 'Planet Earth', + label: tClient('智能星球', 'Intelligent Planet'), submenu: [ { - label: '重新加载数据 / Reload Data', + label: tClient('重新加载数据', 'Reload Data'), accelerator: 'CmdOrCtrl+R', click: () => sendAction('reload-data'), }, { - label: '服务端连接设置 / Server Settings...', + label: tClient('服务器连接设置...', 'Server Settings...'), click: () => { openServerSettingsDialog(options.mainWindow, options.configStore, () => { if (!options.mainWindow.isDestroyed()) { @@ -107,24 +111,24 @@ export function buildApplicationMenu(options: { }, }, { - label: '启动画面 / Splash Screen', + label: tClient('启动动画', 'Splash Screen'), submenu: [ { - label: '启用启动画面 / Enable Splash Screen', + label: tClient('启用启动动画', 'Enable Splash Screen'), type: 'checkbox', checked: currentSplashTheme !== 'off', click: () => selectSplashTheme(currentSplashTheme === 'off' ? 'singularity' : 'off'), }, { type: 'separator' }, { - label: '立即重播启动画面 / Replay Splash Screen', + label: tClient('立即重播启动动画', 'Replay Splash Screen'), accelerator: 'CmdOrCtrl+Shift+S', click: replayActiveSplash, }, ], }, { - label: '渲染设备 / GPU Mode', + label: tClient('渲染模式', 'Graphics Mode'), submenu: [ ...(gpuSummary ? [ @@ -136,7 +140,7 @@ export function buildApplicationMenu(options: { ] : []), { - label: '自动(卡顿缺显存切核显,显存空出自动回独显) / Auto', + label: tClient('自动切换(推荐)', 'Automatic (Recommended)'), type: 'radio', checked: currentGpuMode === 'auto', click: () => { @@ -144,7 +148,7 @@ export function buildApplicationMenu(options: { }, }, { - label: '独立显卡(高性能) / Discrete GPU', + label: tClient('高性能显卡', 'High-Performance GPU'), type: 'radio', checked: currentGpuMode === 'high-performance', click: () => { @@ -152,7 +156,7 @@ export function buildApplicationMenu(options: { }, }, { - label: '集成核显(不占独显显存) / Integrated GPU', + label: tClient('节能核显', 'Integrated GPU'), type: 'radio', checked: currentGpuMode === 'low-power', click: () => { @@ -160,7 +164,7 @@ export function buildApplicationMenu(options: { }, }, { - label: '纯 CPU 软渲染 / Software GL', + label: tClient('软件兼容渲染', 'Software Rendering'), type: 'radio', checked: currentGpuMode === 'software', click: () => { @@ -170,14 +174,14 @@ export function buildApplicationMenu(options: { ], }, { - label: '录屏 / Screen Recording', + label: tClient('录屏', 'Screen Recording'), submenu: [ { label: isRecordingOrStopping - ? '停止录屏 / Stop Recording' + ? tClient('停止录屏', 'Stop Recording') : recordingState === 'starting' - ? '正在启动录屏… / Starting…' - : '开始录屏 / Start Recording', + ? tClient('正在启动录屏…', 'Starting Recording…') + : tClient('开始录屏', 'Start Recording'), accelerator: 'CmdOrCtrl+Shift+F9', enabled: recordingState === 'idle' || recordingState === 'recording', click: () => { @@ -185,7 +189,7 @@ export function buildApplicationMenu(options: { }, }, { - label: '录制声音 / Include Audio', + label: tClient('录制音频', 'Include Audio'), type: 'checkbox', checked: currentRecordAudio, enabled: recordingState === 'idle', @@ -194,7 +198,7 @@ export function buildApplicationMenu(options: { }, }, { - label: '隐藏光标 / Hide Cursor', + label: tClient('隐藏光标', 'Hide Cursor'), type: 'checkbox', checked: currentRecordHideCursor, enabled: recordingState === 'idle', @@ -204,7 +208,7 @@ export function buildApplicationMenu(options: { }, { type: 'separator' }, { - label: '打开录屏目录 / Open Recordings Folder', + label: tClient('打开录屏目录', 'Open Recordings Folder'), click: () => { options.onOpenRecordingsFolder?.() }, @@ -213,59 +217,62 @@ export function buildApplicationMenu(options: { }, { type: 'separator' }, { - label: '打开运维控制台 / Open Admin Console', + label: tClient('打开管理控制台', 'Open Admin Console'), click: () => openAdminPath('/admin'), }, { - label: '打开操作文档 / Open Documentation', + label: tClient('打开帮助文档', 'Open Documentation'), click: () => openAdminPath('/docs/manual'), }, { type: 'separator' }, { - label: '检查更新 / Check for Updates...', + label: tClient('检查更新...', 'Check for Updates...'), click: () => options.onCheckForUpdates?.(), }, ...(options.getVersionInfo ? [ (() => { const info = options.getVersionInfo!() - const suffix = info.usingHotfix ? ' (热更 / Hotfix)' : '' + const suffix = info.usingHotfix ? tClient('(已更新)', ' (Updated)') : '' return { - label: `当前版本: Shell v${info.shellVersion} · Earth v${info.activeBundleVersion}${suffix}`, + label: tClient( + `当前版本: v${info.activeBundleVersion}${suffix}`, + `Version: v${info.activeBundleVersion}${suffix}`, + ), enabled: false, } })(), ] : []), { type: 'separator' }, - { role: 'quit', label: '退出 / Quit' }, + { role: 'quit', label: tClient('退出', 'Quit') }, ], }, { - label: '视图 / View', + label: tClient('视图', 'View'), submenu: [ { - label: '放大视角 / Zoom In', + label: tClient('放大视角', 'Zoom In'), accelerator: 'CmdOrCtrl+=', click: () => sendAction('zoom-in'), }, { - label: '缩小视角 / Zoom Out', + label: tClient('缩小视角', 'Zoom Out'), accelerator: 'CmdOrCtrl+-', click: () => sendAction('zoom-out'), }, { - label: '重置缩放 / Reset Zoom (100%)', + label: tClient('重置缩放 (100%)', 'Reset Zoom (100%)'), accelerator: 'CmdOrCtrl+0', click: () => sendAction('zoom-reset'), }, { - label: '重置地球视角 / Reset View', + label: tClient('重置地球视角', 'Reset View'), click: () => sendAction('reset-view'), }, { type: 'separator' }, { - label: '切换横竖屏 / Toggle Portrait & Landscape', + label: tClient('切换横竖屏', 'Toggle Portrait & Landscape'), accelerator: 'CmdOrCtrl+Shift+M', click: () => { if (!options.mainWindow.isDestroyed()) { @@ -274,7 +281,9 @@ export function buildApplicationMenu(options: { }, }, { - label: '切换全屏 / Toggle Fullscreen (F11)', + label: process.platform === 'darwin' + ? tClient('切换全屏', 'Toggle Fullscreen') + : tClient('切换全屏 (F11)', 'Toggle Fullscreen (F11)'), // Keep accelerator unregistered on Win/Linux so controls.js F11 shortcut never double-toggles. ...(process.platform === 'darwin' ? { accelerator: 'Ctrl+Command+F' } : {}), click: () => { @@ -284,12 +293,12 @@ export function buildApplicationMenu(options: { }, }, { - label: '显示/隐藏帧率 / Toggle FPS', + label: tClient('显示或隐藏帧率', 'Toggle FPS'), click: () => sendAction('toggle-fps'), }, { type: 'separator' }, { - label: '开发者工具 / Toggle DevTools', + label: tClient('开发者工具', 'Toggle DevTools'), accelerator: 'F12', click: () => { if (!options.mainWindow.isDestroyed()) { diff --git a/client/src/main/recording-core.ts b/client/src/main/recording-core.ts index 891675bd..4117de63 100644 --- a/client/src/main/recording-core.ts +++ b/client/src/main/recording-core.ts @@ -119,9 +119,13 @@ export function computeIndicatorBounds(options: { /** * Render self-contained HTML for the transparent floating recording indicator pill. */ -export function buildRecordingIndicatorHtml(): string { +export function buildRecordingIndicatorHtml(locale: 'zh-CN' | 'en-US' = 'zh-CN'): string { + const isEn = locale === 'en-US' + const shortcut = process.platform === 'darwin' ? 'Cmd+Shift+F9' : 'Ctrl+Shift+F9' + const stopTitle = isEn ? `Stop recording (${shortcut})` : `点击停止录屏 (${shortcut})` + const stopAria = isEn ? 'Stop recording' : '停止录屏' return ` - + - diff --git a/client/src/main/recording-indicator.ts b/client/src/main/recording-indicator.ts index 60b206e7..57066234 100644 --- a/client/src/main/recording-indicator.ts +++ b/client/src/main/recording-indicator.ts @@ -1,5 +1,6 @@ -import { BrowserWindow } from 'electron' +import { BrowserWindow, screen, type Display } from 'electron' +import { getClientLocale } from './i18n' import { buildRecordingIndicatorHtml, computeIndicatorBounds, formatRecordingDuration } from './recording-core' export interface RecordingIndicatorController { @@ -162,7 +163,9 @@ export function createRecordingIndicatorController(options: { syncBoundsAndLevel() } }) - void indicatorWin.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(buildRecordingIndicatorHtml())}`) + void indicatorWin.loadURL( + `data:text/html;charset=utf-8,${encodeURIComponent(buildRecordingIndicatorHtml(getClientLocale()))}`, + ) return indicatorWin } diff --git a/client/src/main/screen-recorder.ts b/client/src/main/screen-recorder.ts index b1fc8a24..f326437a 100644 --- a/client/src/main/screen-recorder.ts +++ b/client/src/main/screen-recorder.ts @@ -11,6 +11,7 @@ import { } from 'electron' import type { DesktopConfigStore } from './config' +import { tClient } from './i18n' import { buildRecordingFilename, resolveRecordingExtension, @@ -230,7 +231,7 @@ export function createScreenRecorderController(options: { writeChain = Promise.resolve() writeStream = fs.createWriteStream(filePath) writeStream.on('error', (err) => { - notifyStatus(`录屏写入失败:${err.message}`, 'error') + notifyStatus(tClient(`录屏写入失败:${err.message}`, `Recording write failed: ${err.message}`), 'error') }) startedAtMs = Date.now() @@ -298,15 +299,15 @@ export function createScreenRecorderController(options: { if (result.savedPath && result.savedName && result.hadData) { lastSavedFilePath = result.savedPath notifyStatus({ - message: `已保存录屏:${result.savedPath}`, + message: tClient(`已保存录屏:${result.savedPath}`, `Recording saved: ${result.savedPath}`), type: 'success', fullText: true, durationMs: 6000, - actionLabel: '打开目录', + actionLabel: tClient('打开目录', 'Open Folder'), action: 'open-recordings-folder', }) } else if (state !== 'idle') { - notifyStatus('录屏已停止(未采集到有效画面帧)', 'info') + notifyStatus(tClient('录屏已停止(未采集到有效画面帧)', 'Recording stopped (no valid frames captured)'), 'info') } resetToIdle() return result @@ -315,14 +316,14 @@ export function createScreenRecorderController(options: { const onAbort = async (_event: Electron.IpcMainInvokeEvent, payload?: { error?: string }) => { await closeWriteStream() if (payload?.error) { - notifyStatus(`启动录屏失败:${payload.error}`, 'error') + notifyStatus(tClient(`启动录屏失败:${payload.error}`, `Failed to start recording: ${payload.error}`), 'error') } resetToIdle() } const onAudioFallback = () => { includeAudio = false - notifyStatus('当前设备不支持内录音频,已切换为静音录屏', 'info') + notifyStatus(tClient('当前设备不支持音频录制,已切换为静音录屏', 'System audio capture unavailable; recording muted'), 'info') } const onIndicatorStop = () => { diff --git a/client/src/main/window.ts b/client/src/main/window.ts index 9cf63b12..b3c2966f 100644 --- a/client/src/main/window.ts +++ b/client/src/main/window.ts @@ -6,6 +6,7 @@ import { BrowserWindow, ipcMain, nativeTheme, screen, shell, type Display } from import { createSoloAltMenuTracker } from './alt-menu' import { DEFAULT_ENDPOINTS, type DesktopConfigStore, type DesktopRuntimeConfig } from './config' import { resolveExternalTargetUrl } from './external-links' +import { getClientLocale, tClient } from './i18n' import { createWindowShowGate } from './show-gate' import { clampBoundsToWorkArea, @@ -496,7 +497,7 @@ export function openServerSettingsDialog( maximizable: false, autoHideMenuBar: true, backgroundColor: '#091522', - title: 'Planet Earth — Server Connection', + title: tClient('服务器连接设置', 'Server Connection Settings'), webPreferences: { contextIsolation: true, nodeIntegration: false, @@ -509,7 +510,7 @@ export function openServerSettingsDialog( value.replace(/&/g, '&').replace(/"/g, '"').replace(//g, '>') const html = ` - + -

服务端连接配置 / Server Connection

+

${tClient('服务器连接设置', 'Server Connection Settings')}

-