Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
04cebdc504 | ||
|
|
b3d2d9e9f1 |
No files matched your search
@@ -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 (`<prev_tag>`):
|
||||
|
||||
```bash
|
||||
git diff --name-only <prev_tag>..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
|
||||
|
||||
@@ -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:<tag>` 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:<tag>`.
|
||||
- **Release Publish vs. Production Deployment (`发版 ≠ 已部署`)**:
|
||||
`scripts/release_publish.py` only publishes container images, OCI
|
||||
`release-manifest:<tag>`, 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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -40,6 +40,10 @@ AI_ANTHROPIC_VERSION=2023-06-01
|
||||
# DEEPSEEK_API_KEY=replace-with-deepseek-key
|
||||
# DASHSCOPE_API_KEY=replace-with-dashscope-key
|
||||
# MOONSHOT_API_KEY=replace-with-moonshot-key
|
||||
# ZHIPU_API_KEY=replace-with-zhipu-key
|
||||
# META_MODEL_API_KEY=replace-with-meta-key
|
||||
# GEMINI_API_KEY=replace-with-gemini-key
|
||||
# XAI_API_KEY=replace-with-xai-key
|
||||
# OPENROUTER_API_KEY=replace-with-openrouter-key
|
||||
|
||||
# OpenAI-compatible example (vLLM / LM Studio / One API / local gateway)
|
||||
|
||||
+589
-45
@@ -15,6 +15,7 @@ from aiprovider.schemas import (
|
||||
AIProviderStatusResponse,
|
||||
SituationalAnalysisRequest,
|
||||
SituationalAnalysisResponse,
|
||||
ToolCallRecord,
|
||||
)
|
||||
|
||||
def _normalize_provider(value: str) -> str:
|
||||
@@ -29,7 +30,23 @@ def _resolve_provider_api(provider: str, configured_api: str) -> str:
|
||||
if configured_api and configured_api != "auto":
|
||||
return configured_api
|
||||
|
||||
if provider in {"openai", "openai-compatible", "openai_compatible"}:
|
||||
if provider in {
|
||||
"openai",
|
||||
"openai-compatible",
|
||||
"openai_compatible",
|
||||
"deepseek",
|
||||
"alibaba",
|
||||
"moonshotai",
|
||||
"glm",
|
||||
"zhipuai",
|
||||
"meta",
|
||||
"gemini",
|
||||
"google",
|
||||
"grok",
|
||||
"xai",
|
||||
"openrouter",
|
||||
"opencode-go",
|
||||
}:
|
||||
return "openai-completions"
|
||||
if provider in {
|
||||
"anthropic",
|
||||
@@ -103,19 +120,47 @@ class ProviderService:
|
||||
self.session_id = str(uuid5(NAMESPACE_URL, f"planet:{payload.context['session_id']}"))
|
||||
|
||||
provider_api = self._resolve_model_provider_api(model)
|
||||
tools = getattr(payload, "tools", None)
|
||||
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
|
||||
|
||||
if provider_api == "openai-completions":
|
||||
data = await self._request_openai_compatible(
|
||||
model, prompt, payload.system_prompt, conversation_messages=conversation_messages
|
||||
model,
|
||||
prompt,
|
||||
payload.system_prompt,
|
||||
conversation_messages=conversation_messages,
|
||||
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)
|
||||
tool_calls = self._extract_openai_tool_calls(data)
|
||||
choices = data.get("choices") or []
|
||||
if choices and isinstance(choices[0], dict):
|
||||
stop_reason = choices[0].get("finish_reason")
|
||||
elif provider_api == "openai-responses":
|
||||
data = await self._request_openai_responses(
|
||||
model, prompt, payload.system_prompt, conversation_messages=conversation_messages
|
||||
model,
|
||||
prompt,
|
||||
payload.system_prompt,
|
||||
conversation_messages=conversation_messages,
|
||||
tools=tools,
|
||||
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)
|
||||
tool_calls = self._extract_responses_tool_calls(data)
|
||||
stop_reason = str(data.get("status") or "") or None
|
||||
elif provider_api == "anthropic-messages":
|
||||
data = await self._request_anthropic_messages(
|
||||
model,
|
||||
@@ -123,15 +168,28 @@ class ProviderService:
|
||||
payload.thinking,
|
||||
payload.system_prompt,
|
||||
conversation_messages=conversation_messages,
|
||||
tools=tools,
|
||||
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)
|
||||
tool_calls = self._extract_anthropic_tool_calls(data)
|
||||
stop_reason = str(data.get("stop_reason") or "") or None
|
||||
elif provider_api == "ollama-generate":
|
||||
data = await self._request_ollama(
|
||||
model, prompt, payload.system_prompt, conversation_messages=conversation_messages
|
||||
model,
|
||||
prompt,
|
||||
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)
|
||||
stop_reason = "stop" if data.get("done") else None
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
@@ -148,6 +206,8 @@ class ProviderService:
|
||||
content_blocks=content_blocks,
|
||||
text_blocks=text_blocks,
|
||||
thinking_blocks=thinking_blocks,
|
||||
tool_calls=tool_calls,
|
||||
stop_reason=stop_reason,
|
||||
raw_response=data,
|
||||
)
|
||||
|
||||
@@ -175,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":
|
||||
@@ -184,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
|
||||
@@ -248,15 +322,63 @@ class ProviderService:
|
||||
system_prompt: str | None = None,
|
||||
*,
|
||||
stream: bool = False,
|
||||
conversation_messages: list[dict[str, str]] | None = None,
|
||||
conversation_messages: list[dict[str, Any]] | None = None,
|
||||
tools: list[dict[str, Any]] | None = None,
|
||||
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]]:
|
||||
if conversation_messages and len(conversation_messages) > 1:
|
||||
anthropic_messages = [
|
||||
{"role": m["role"], "content": [{"type": "text", "text": m["content"]}]}
|
||||
for m in conversation_messages
|
||||
]
|
||||
else:
|
||||
anthropic_messages = [{"role": "user", "content": [{"type": "text", "text": prompt}]}]
|
||||
anthropic_messages: list[dict[str, Any]] = []
|
||||
source_messages = (
|
||||
conversation_messages
|
||||
if (conversation_messages and (len(conversation_messages) > 1 or any(m.get("role") == "tool" or m.get("tool_calls") for m in conversation_messages)))
|
||||
else [{"role": "user", "content": prompt}]
|
||||
)
|
||||
for msg in source_messages:
|
||||
role = msg.get("role")
|
||||
if role == "tool":
|
||||
block = {
|
||||
"type": "tool_result",
|
||||
"tool_use_id": str(msg.get("tool_call_id") or ""),
|
||||
"content": str(msg.get("content") or ""),
|
||||
}
|
||||
if (
|
||||
anthropic_messages
|
||||
and anthropic_messages[-1]["role"] == "user"
|
||||
and isinstance(anthropic_messages[-1]["content"], list)
|
||||
and anthropic_messages[-1]["content"]
|
||||
and anthropic_messages[-1]["content"][0].get("type") == "tool_result"
|
||||
):
|
||||
anthropic_messages[-1]["content"].append(block)
|
||||
else:
|
||||
anthropic_messages.append({"role": "user", "content": [block]})
|
||||
continue
|
||||
if role == "assistant" and msg.get("tool_calls"):
|
||||
blocks: list[dict[str, Any]] = []
|
||||
text = str(msg.get("content") or "").strip()
|
||||
if text:
|
||||
blocks.append({"type": "text", "text": text})
|
||||
for tc in msg.get("tool_calls") or []:
|
||||
if not isinstance(tc, dict):
|
||||
continue
|
||||
blocks.append(
|
||||
{
|
||||
"type": "tool_use",
|
||||
"id": str(tc.get("id") or ""),
|
||||
"name": str(tc.get("name") or ""),
|
||||
"input": tc.get("arguments") if isinstance(tc.get("arguments"), dict) else {},
|
||||
}
|
||||
)
|
||||
if blocks:
|
||||
anthropic_messages.append({"role": "assistant", "content": blocks})
|
||||
continue
|
||||
anthropic_messages.append(
|
||||
{"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
|
||||
@@ -284,6 +406,45 @@ class ProviderService:
|
||||
request_body["thinking"] = resolved_thinking
|
||||
if resolved_output_config:
|
||||
request_body["output_config"] = resolved_output_config
|
||||
elif (
|
||||
self.provider == "anthropic"
|
||||
and isinstance(response_format, dict)
|
||||
and isinstance(response_format.get("json_schema"), dict)
|
||||
):
|
||||
schema_cfg = response_format["json_schema"]
|
||||
schema_obj = schema_cfg.get("schema") if isinstance(schema_cfg.get("schema"), dict) else schema_cfg
|
||||
request_body["output_config"] = {
|
||||
"format": {
|
||||
"type": "json_schema",
|
||||
"schema": schema_obj,
|
||||
}
|
||||
}
|
||||
|
||||
anthropic_tools: list[dict[str, Any]] = []
|
||||
for tool in tools or []:
|
||||
if not isinstance(tool, dict) or not tool.get("name"):
|
||||
continue
|
||||
anthropic_tools.append(
|
||||
{
|
||||
"name": str(tool["name"]),
|
||||
"description": str(tool.get("description") or ""),
|
||||
"input_schema": tool.get("parameters") or {"type": "object", "properties": {}},
|
||||
}
|
||||
)
|
||||
if native_web_search:
|
||||
anthropic_tools.append({"type": "web_search_20250305", "name": "web_search", "max_uses": 3})
|
||||
if anthropic_tools:
|
||||
request_body["tools"] = anthropic_tools
|
||||
if isinstance(tool_choice, str):
|
||||
if tool_choice == "required":
|
||||
request_body["tool_choice"] = {"type": "any"}
|
||||
elif tool_choice == "auto":
|
||||
request_body["tool_choice"] = {"type": "auto"}
|
||||
elif tool_choice not in {"none", ""}:
|
||||
request_body["tool_choice"] = {"type": "tool", "name": tool_choice}
|
||||
elif isinstance(tool_choice, dict) and tool_choice.get("name"):
|
||||
request_body["tool_choice"] = {"type": "tool", "name": str(tool_choice["name"])}
|
||||
|
||||
path = "/v1/messages" if self.provider == "minimax" and self.base_url.endswith("/anthropic") else "/messages"
|
||||
headers = {
|
||||
"x-api-key": self.api_key,
|
||||
@@ -299,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,
|
||||
@@ -308,6 +470,7 @@ class ProviderService:
|
||||
system_prompt,
|
||||
stream=True,
|
||||
conversation_messages=conversation_messages,
|
||||
images=images,
|
||||
)
|
||||
resolved_model = model
|
||||
usage: dict[str, Any] = {}
|
||||
@@ -370,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,
|
||||
@@ -438,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,
|
||||
@@ -500,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] = {
|
||||
@@ -509,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
|
||||
@@ -566,10 +736,53 @@ class ProviderService:
|
||||
self,
|
||||
payload: SituationalAnalysisRequest,
|
||||
final_prompt: str,
|
||||
) -> list[dict[str, str]]:
|
||||
"""Normalize multi-turn history + current prompt into alternating user/assistant messages."""
|
||||
normalized: list[dict[str, str]] = []
|
||||
for item in getattr(payload, "messages", None) or []:
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Normalize multi-turn history + current prompt (including tool turns) into messages."""
|
||||
raw_items = getattr(payload, "messages", None) or []
|
||||
has_tool_turns = any(
|
||||
(
|
||||
str(
|
||||
getattr(item, "role", None)
|
||||
or (item.get("role") if isinstance(item, dict) else "")
|
||||
).strip().lower()
|
||||
== "tool"
|
||||
or bool(
|
||||
getattr(item, "tool_calls", None)
|
||||
if not isinstance(item, dict)
|
||||
else item.get("tool_calls")
|
||||
)
|
||||
)
|
||||
for item in raw_items
|
||||
)
|
||||
if has_tool_turns:
|
||||
preserved: list[dict[str, Any]] = []
|
||||
for item in raw_items:
|
||||
if isinstance(item, dict):
|
||||
role = str(item.get("role") or "").strip().lower()
|
||||
content = str(item.get("content") or "")
|
||||
tool_call_id = item.get("tool_call_id")
|
||||
name = item.get("name")
|
||||
tool_calls = item.get("tool_calls")
|
||||
else:
|
||||
role = str(getattr(item, "role", "") or "").strip().lower()
|
||||
content = str(getattr(item, "content", "") or "")
|
||||
tool_call_id = getattr(item, "tool_call_id", None)
|
||||
name = getattr(item, "name", None)
|
||||
tool_calls = getattr(item, "tool_calls", None)
|
||||
if role not in {"user", "assistant", "tool"}:
|
||||
continue
|
||||
entry: dict[str, Any] = {"role": role, "content": content}
|
||||
if tool_call_id:
|
||||
entry["tool_call_id"] = str(tool_call_id)
|
||||
if name:
|
||||
entry["name"] = str(name)
|
||||
if tool_calls:
|
||||
entry["tool_calls"] = list(tool_calls)
|
||||
preserved.append(entry)
|
||||
return preserved or [{"role": "user", "content": final_prompt}]
|
||||
|
||||
normalized: list[dict[str, Any]] = []
|
||||
for item in raw_items:
|
||||
role = str(getattr(item, "role", None) or (item.get("role") if isinstance(item, dict) else "")).strip().lower()
|
||||
content = str(getattr(item, "content", None) or (item.get("content") if isinstance(item, dict) else "")).strip()
|
||||
if role not in {"user", "assistant"} or not content:
|
||||
@@ -590,15 +803,15 @@ class ProviderService:
|
||||
@staticmethod
|
||||
def _format_ollama_prompt(
|
||||
prompt: str,
|
||||
conversation_messages: list[dict[str, str]] | None,
|
||||
conversation_messages: list[dict[str, Any]] | None,
|
||||
) -> str:
|
||||
if not conversation_messages or len(conversation_messages) <= 1:
|
||||
return prompt
|
||||
history_lines = []
|
||||
for m in conversation_messages[:-1]:
|
||||
prefix = "用户" if m["role"] == "user" else "助手"
|
||||
history_lines.append(f"{prefix}: {m['content']}")
|
||||
return "历史对话:\n" + "\n".join(history_lines) + f"\n\n当前任务:\n{conversation_messages[-1]['content']}"
|
||||
prefix = "用户" if m.get("role") == "user" else "助手"
|
||||
history_lines.append(f"{prefix}: {m.get('content', '')}")
|
||||
return "历史对话:\n" + "\n".join(history_lines) + f"\n\n当前任务:\n{conversation_messages[-1].get('content', prompt)}"
|
||||
|
||||
def _build_prompt(self, payload: SituationalAnalysisRequest) -> str:
|
||||
sections = [
|
||||
@@ -610,9 +823,104 @@ class ProviderService:
|
||||
if payload.constraints:
|
||||
sections.append("约束条件:\n" + "\n".join(f"- {item}" for item in payload.constraints))
|
||||
if payload.context:
|
||||
sections.append(f"附加上下文:\n{payload.context}")
|
||||
context_json = json.dumps(payload.context, ensure_ascii=False, default=str)
|
||||
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
|
||||
@@ -623,22 +931,95 @@ 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,
|
||||
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 = []
|
||||
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)
|
||||
else:
|
||||
messages.append({"role": "user", "content": prompt})
|
||||
request_body = {
|
||||
source_messages = (
|
||||
conversation_messages
|
||||
if (conversation_messages and (len(conversation_messages) > 1 or any(m.get("role") == "tool" or m.get("tool_calls") for m in conversation_messages)))
|
||||
else [{"role": "user", "content": prompt}]
|
||||
)
|
||||
for msg in source_messages:
|
||||
role = msg.get("role") or "user"
|
||||
if role == "tool":
|
||||
messages.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": str(msg.get("tool_call_id") or ""),
|
||||
"content": str(msg.get("content") or ""),
|
||||
}
|
||||
)
|
||||
elif role == "assistant" and msg.get("tool_calls"):
|
||||
openai_tcs = []
|
||||
for tc in msg.get("tool_calls") or []:
|
||||
if not isinstance(tc, dict):
|
||||
continue
|
||||
args = tc.get("arguments")
|
||||
args_str = args if isinstance(args, str) else json.dumps(args or {}, ensure_ascii=False)
|
||||
openai_tcs.append(
|
||||
{
|
||||
"id": str(tc.get("id") or ""),
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": str(tc.get("name") or ""),
|
||||
"arguments": args_str,
|
||||
},
|
||||
}
|
||||
)
|
||||
messages.append(
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": msg.get("content") or "",
|
||||
"tool_calls": openai_tcs,
|
||||
}
|
||||
)
|
||||
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,
|
||||
"temperature": 0.2,
|
||||
"max_tokens": self.max_tokens,
|
||||
}
|
||||
if tools:
|
||||
request_body["tools"] = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": str(t["name"]),
|
||||
"description": str(t.get("description") or ""),
|
||||
"parameters": t.get("parameters") or {"type": "object", "properties": {}},
|
||||
},
|
||||
}
|
||||
for t in tools
|
||||
if isinstance(t, dict) and t.get("name")
|
||||
]
|
||||
if tool_choice:
|
||||
if isinstance(tool_choice, str) and tool_choice in {"auto", "required", "none"}:
|
||||
request_body["tool_choice"] = tool_choice
|
||||
elif isinstance(tool_choice, dict) and tool_choice.get("name"):
|
||||
request_body["tool_choice"] = {
|
||||
"type": "function",
|
||||
"function": {"name": str(tool_choice["name"])},
|
||||
}
|
||||
elif isinstance(tool_choice, str):
|
||||
request_body["tool_choice"] = {
|
||||
"type": "function",
|
||||
"function": {"name": tool_choice},
|
||||
}
|
||||
if isinstance(response_format, dict) and response_format:
|
||||
request_body["response_format"] = response_format
|
||||
|
||||
return await self._post(
|
||||
path="/chat/completions",
|
||||
headers={
|
||||
@@ -654,13 +1035,57 @@ 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,
|
||||
tools: list[dict[str, Any]] | None = None,
|
||||
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]:
|
||||
responses_input: Any = (
|
||||
[{"role": m["role"], "content": m["content"]} for m in conversation_messages]
|
||||
if (conversation_messages and len(conversation_messages) > 1)
|
||||
else prompt
|
||||
has_multi_or_tools = bool(
|
||||
conversation_messages
|
||||
and (
|
||||
len(conversation_messages) > 1
|
||||
or any(m.get("role") == "tool" or m.get("tool_calls") for m in conversation_messages)
|
||||
)
|
||||
)
|
||||
if has_multi_or_tools and conversation_messages:
|
||||
responses_items: list[dict[str, Any]] = []
|
||||
for msg in conversation_messages:
|
||||
role = msg.get("role") or "user"
|
||||
if role == "tool":
|
||||
responses_items.append(
|
||||
{
|
||||
"type": "function_call_output",
|
||||
"call_id": str(msg.get("tool_call_id") or ""),
|
||||
"output": str(msg.get("content") or ""),
|
||||
}
|
||||
)
|
||||
elif role == "assistant" and msg.get("tool_calls"):
|
||||
text_val = str(msg.get("content") or "").strip()
|
||||
if text_val:
|
||||
responses_items.append({"role": "assistant", "content": text_val})
|
||||
for tc in msg.get("tool_calls") or []:
|
||||
if not isinstance(tc, dict):
|
||||
continue
|
||||
args = tc.get("arguments")
|
||||
args_str = args if isinstance(args, str) else json.dumps(args or {}, ensure_ascii=False)
|
||||
responses_items.append(
|
||||
{
|
||||
"type": "function_call",
|
||||
"call_id": str(tc.get("id") or ""),
|
||||
"name": str(tc.get("name") or ""),
|
||||
"arguments": args_str,
|
||||
}
|
||||
)
|
||||
else:
|
||||
responses_items.append({"role": role, "content": str(msg.get("content") or "")})
|
||||
responses_input: Any = responses_items
|
||||
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,
|
||||
@@ -670,6 +1095,46 @@ class ProviderService:
|
||||
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
|
||||
if resolved_system_prompt:
|
||||
request_body["instructions"] = resolved_system_prompt
|
||||
|
||||
responses_tools: list[dict[str, Any]] = []
|
||||
if native_web_search:
|
||||
responses_tools.append({"type": "web_search"})
|
||||
for t in tools or []:
|
||||
if not isinstance(t, dict) or not t.get("name"):
|
||||
continue
|
||||
responses_tools.append(
|
||||
{
|
||||
"type": "function",
|
||||
"name": str(t["name"]),
|
||||
"description": str(t.get("description") or ""),
|
||||
"parameters": t.get("parameters") or {"type": "object", "properties": {}},
|
||||
}
|
||||
)
|
||||
if responses_tools:
|
||||
request_body["tools"] = responses_tools
|
||||
if isinstance(tool_choice, str) and tool_choice:
|
||||
if tool_choice in {"auto", "required", "none"}:
|
||||
request_body["tool_choice"] = tool_choice
|
||||
else:
|
||||
request_body["tool_choice"] = {"type": "function", "name": tool_choice}
|
||||
elif isinstance(tool_choice, dict) and tool_choice.get("name"):
|
||||
request_body["tool_choice"] = {"type": "function", "name": str(tool_choice["name"])}
|
||||
|
||||
if isinstance(response_format, dict) and response_format:
|
||||
rf_type = str(response_format.get("type") or "").strip()
|
||||
if rf_type == "json_schema" and isinstance(response_format.get("json_schema"), dict):
|
||||
js = response_format["json_schema"]
|
||||
request_body["text"] = {
|
||||
"format": {
|
||||
"type": "json_schema",
|
||||
"name": str(js.get("name") or "structured_output"),
|
||||
"schema": js.get("schema") if isinstance(js.get("schema"), dict) else js,
|
||||
"strict": bool(js.get("strict", True)),
|
||||
}
|
||||
}
|
||||
elif rf_type == "json_object":
|
||||
request_body["text"] = {"format": {"type": "json_object"}}
|
||||
|
||||
return await self._post(
|
||||
path="/responses",
|
||||
headers={"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"},
|
||||
@@ -701,7 +1166,12 @@ 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,
|
||||
tools: list[dict[str, Any]] | None = None,
|
||||
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,
|
||||
@@ -710,6 +1180,11 @@ class ProviderService:
|
||||
system_prompt,
|
||||
stream=False,
|
||||
conversation_messages=conversation_messages,
|
||||
tools=tools,
|
||||
tool_choice=tool_choice,
|
||||
response_format=response_format,
|
||||
native_web_search=native_web_search,
|
||||
images=images,
|
||||
)
|
||||
return await self._post(
|
||||
path=path,
|
||||
@@ -762,9 +1237,11 @@ 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,
|
||||
response_format: dict[str, Any] | None = None,
|
||||
images: list[dict[str, str]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
request_body = {
|
||||
request_body: dict[str, Any] = {
|
||||
"model": model,
|
||||
"stream": False,
|
||||
"prompt": self._format_ollama_prompt(prompt, conversation_messages),
|
||||
@@ -773,9 +1250,17 @@ 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
|
||||
if isinstance(response_format, dict) and response_format:
|
||||
if isinstance(response_format.get("json_schema"), dict):
|
||||
js = response_format["json_schema"]
|
||||
request_body["format"] = js.get("schema") if isinstance(js.get("schema"), dict) else "json"
|
||||
else:
|
||||
request_body["format"] = "json"
|
||||
return await self._post(
|
||||
path="/api/generate",
|
||||
headers={
|
||||
@@ -936,3 +1421,62 @@ class ProviderService:
|
||||
if isinstance(response, str) and response:
|
||||
return [AIContentBlock(type="text", text=response)]
|
||||
return []
|
||||
|
||||
@staticmethod
|
||||
def _parse_tool_arguments(raw: Any) -> dict[str, Any]:
|
||||
if isinstance(raw, dict):
|
||||
return raw
|
||||
if isinstance(raw, str) and raw.strip():
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
return parsed if isinstance(parsed, dict) else {"value": parsed}
|
||||
except json.JSONDecodeError:
|
||||
return {"raw": raw}
|
||||
return {}
|
||||
|
||||
def _extract_openai_tool_calls(self, payload: dict[str, Any]) -> list[ToolCallRecord]:
|
||||
choices = payload.get("choices") or []
|
||||
if not choices or not isinstance(choices[0], dict):
|
||||
return []
|
||||
message = choices[0].get("message") or {}
|
||||
records: list[ToolCallRecord] = []
|
||||
for idx, tc in enumerate(message.get("tool_calls") or []):
|
||||
if not isinstance(tc, dict):
|
||||
continue
|
||||
fn = tc.get("function") or {}
|
||||
name = str(fn.get("name") or tc.get("name") or "").strip()
|
||||
if not name:
|
||||
continue
|
||||
call_id = str(tc.get("id") or f"call_{idx + 1}")
|
||||
args = self._parse_tool_arguments(fn.get("arguments") if fn else tc.get("arguments"))
|
||||
records.append(ToolCallRecord(id=call_id, name=name, arguments=args))
|
||||
return records
|
||||
|
||||
def _extract_responses_tool_calls(self, payload: dict[str, Any]) -> list[ToolCallRecord]:
|
||||
records: list[ToolCallRecord] = []
|
||||
for idx, item in enumerate(payload.get("output") or []):
|
||||
if not isinstance(item, dict) or item.get("type") != "function_call":
|
||||
continue
|
||||
name = str(item.get("name") or "").strip()
|
||||
if not name:
|
||||
continue
|
||||
call_id = str(item.get("call_id") or item.get("id") or f"call_{idx + 1}")
|
||||
args = self._parse_tool_arguments(item.get("arguments"))
|
||||
records.append(ToolCallRecord(id=call_id, name=name, arguments=args))
|
||||
return records
|
||||
|
||||
def _extract_anthropic_tool_calls(self, payload: dict[str, Any]) -> list[ToolCallRecord]:
|
||||
content = payload.get("content")
|
||||
if not isinstance(content, list):
|
||||
return []
|
||||
records: list[ToolCallRecord] = []
|
||||
for idx, item in enumerate(content):
|
||||
if not isinstance(item, dict) or item.get("type") != "tool_use":
|
||||
continue
|
||||
name = str(item.get("name") or "").strip()
|
||||
if not name:
|
||||
continue
|
||||
call_id = str(item.get("id") or f"call_{idx + 1}")
|
||||
args = self._parse_tool_arguments(item.get("input"))
|
||||
records.append(ToolCallRecord(id=call_id, name=name, arguments=args))
|
||||
return records
|
||||
+26
-4
@@ -4,8 +4,23 @@ from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class ChatMessage(BaseModel):
|
||||
role: Literal["user", "assistant"]
|
||||
content: str = Field(..., min_length=1, max_length=12000)
|
||||
role: Literal["user", "assistant", "tool"]
|
||||
content: str = Field(default="", max_length=24000)
|
||||
tool_call_id: str | None = Field(default=None, max_length=200)
|
||||
name: str | None = Field(default=None, max_length=200)
|
||||
tool_calls: list[dict[str, Any]] | None = None
|
||||
|
||||
|
||||
class ToolCallRecord(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
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):
|
||||
@@ -18,14 +33,19 @@ class AIContentBlock(BaseModel):
|
||||
|
||||
class SituationalAnalysisRequest(BaseModel):
|
||||
title: str = Field(..., min_length=1, max_length=200)
|
||||
objective: str = Field(..., min_length=1, max_length=20000)
|
||||
objective: str = Field(..., min_length=1, max_length=24000)
|
||||
context: dict[str, Any] = Field(default_factory=dict)
|
||||
observations: list[str] = Field(default_factory=list)
|
||||
constraints: list[str] = Field(default_factory=list)
|
||||
system_prompt: str | None = Field(default=None, max_length=8000)
|
||||
preferred_model: str | None = Field(default=None, max_length=200)
|
||||
thinking: dict[str, Any] | None = None
|
||||
messages: list[ChatMessage] = Field(default_factory=list, max_length=32)
|
||||
messages: list[ChatMessage] = Field(default_factory=list, max_length=48)
|
||||
tools: list[dict[str, Any]] | None = None
|
||||
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):
|
||||
@@ -35,6 +55,8 @@ class SituationalAnalysisResponse(BaseModel):
|
||||
content_blocks: list[AIContentBlock] = Field(default_factory=list)
|
||||
text_blocks: list[str] = Field(default_factory=list)
|
||||
thinking_blocks: list[str] = Field(default_factory=list)
|
||||
tool_calls: list[ToolCallRecord] = Field(default_factory=list)
|
||||
stop_reason: str | None = None
|
||||
raw_response: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
|
||||
@@ -102,5 +102,21 @@
|
||||
"version": "2026-11-11.1",
|
||||
"system_prompt": "你是算力白皮书数据核验提取器。仅提取原文明确写出的国家算力份额、FP32 规模或内部结构数值,输出严格 JSON 候选数组供管理员审核,严禁估算或补齐未出现的国家。",
|
||||
"prompt": "从提供的报告摘录与来源元数据中提取待审核的算力观测候选记录。"
|
||||
},
|
||||
{
|
||||
"key": "earth.news.analysis",
|
||||
"label": "Earth 新闻深层分析",
|
||||
"group": "Earth 新闻",
|
||||
"version": "2026-11-30.1",
|
||||
"system_prompt": "你是智能星球地球热点新闻与地缘基础设施分析师。请基于新闻全文、位置上下文与基础设施邻近关系,给出客观、可溯源的深层研判(Markdown,包含事实摘要、影响范围、关联基础设施与观察建议)。",
|
||||
"prompt": "围绕选中的新闻事件与关联空间坐标展开深度分析,突出对海底光缆、算力枢纽与跨境路由的潜在影响。"
|
||||
},
|
||||
{
|
||||
"key": "memory.compact",
|
||||
"label": "Earth Copilot 会话记忆压缩",
|
||||
"group": "态势参谋",
|
||||
"version": "2026-11-30.1",
|
||||
"system_prompt": "你是对话上下文压缩器。提取已确认事实、关注实体 ID、时间范围与未决问题,输出简洁要点以供后续多轮追问继承。",
|
||||
"prompt": "将较早的多轮地球参谋对话历史压缩为高信息密度记忆摘要,保留实体键与核心结论。"
|
||||
}
|
||||
]
|
||||
@@ -124,7 +124,26 @@ async def get_effective_prompt(db: AsyncSession | None, task_key: str) -> Effect
|
||||
if db is None:
|
||||
return _effective_prompt(definition, None)
|
||||
overrides = await get_prompt_overrides(db)
|
||||
return _effective_prompt(definition, overrides.get(task_key))
|
||||
override = overrides.get(task_key)
|
||||
if not override:
|
||||
try:
|
||||
from app.services.ai.workflow_registry import resolve_prompt_override_from_workflows
|
||||
|
||||
wf_prompt = await resolve_prompt_override_from_workflows(db, task_key)
|
||||
except Exception:
|
||||
wf_prompt = None
|
||||
if wf_prompt is not None:
|
||||
sys_p, user_p = wf_prompt
|
||||
has_wf = bool((sys_p or "").strip() or (user_p or "").strip())
|
||||
if has_wf and (
|
||||
sys_p != definition.system_prompt or user_p != definition.prompt
|
||||
):
|
||||
override = {
|
||||
"system_prompt": sys_p,
|
||||
"prompt": user_p,
|
||||
"updated_at": "",
|
||||
}
|
||||
return _effective_prompt(definition, override)
|
||||
|
||||
|
||||
async def save_prompt_override(
|
||||
|
||||
@@ -2,6 +2,7 @@ from app.api.v1 import card_images
|
||||
from fastapi import APIRouter
|
||||
from app.api.v1 import (
|
||||
ai,
|
||||
api_keys,
|
||||
auth,
|
||||
users,
|
||||
datasource_config,
|
||||
@@ -47,6 +48,7 @@ api_router.include_router(dashboard.router, prefix="/dashboard", tags=["dashboar
|
||||
api_router.include_router(alerts.router, prefix="/alerts", tags=["alerts"])
|
||||
api_router.include_router(settings.router, prefix="/settings", tags=["settings"])
|
||||
api_router.include_router(system_control.router, prefix="/system", tags=["system"])
|
||||
api_router.include_router(api_keys.router, prefix="/system/api-keys", tags=["api-keys"])
|
||||
api_router.include_router(data_products.router, prefix="/data-products", tags=["data-products"])
|
||||
api_router.include_router(compute_intelligence.router, prefix="/data-products/compute", tags=["compute"])
|
||||
api_router.include_router(
|
||||
|
||||
@@ -49,8 +49,10 @@ from app.services.playground_chat_service import (
|
||||
)
|
||||
from app.services.situational_alert_ai_brief import build_situational_alert_brief_request
|
||||
from app.services.business_logs import emit_business_log, exception_context
|
||||
from app.api.v1.ai_workflows import router as ai_workflows_router
|
||||
|
||||
router = APIRouter()
|
||||
router.include_router(ai_workflows_router)
|
||||
logger = get_logger(__name__, service="api")
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,85 @@
|
||||
"""Admin endpoints for managing internal UE5 and external partner API keys."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, status
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.access_gate import require_admin_user
|
||||
from app.db.session import get_db
|
||||
from app.models.user import User
|
||||
from app.services.api_keys import (
|
||||
EARTH_ALL_READ_SCOPE,
|
||||
EARTH_READ_SCOPES,
|
||||
create_api_key,
|
||||
delete_api_key,
|
||||
list_api_keys,
|
||||
revoke_api_key,
|
||||
serialize_api_key,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class ApiKeyCreateRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||
|
||||
name: str = Field(min_length=1, max_length=120)
|
||||
scopes: list[str] = Field(default_factory=lambda: [EARTH_ALL_READ_SCOPE])
|
||||
rate_limit_per_minute: Optional[int] = Field(default=None, ge=0, le=100_000)
|
||||
expires_in_days: Optional[int] = Field(default=None, ge=0, le=3650)
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def get_api_keys(
|
||||
_admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
items = [serialize_api_key(record) for record in await list_api_keys(db)]
|
||||
return {
|
||||
"items": items,
|
||||
"available_scopes": [EARTH_ALL_READ_SCOPE, *sorted(EARTH_READ_SCOPES)],
|
||||
}
|
||||
|
||||
|
||||
@router.post("", status_code=status.HTTP_201_CREATED)
|
||||
async def create_new_api_key(
|
||||
payload: ApiKeyCreateRequest,
|
||||
admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
record, raw_key = await create_api_key(
|
||||
db,
|
||||
name=payload.name,
|
||||
scopes=payload.scopes,
|
||||
rate_limit_per_minute=payload.rate_limit_per_minute,
|
||||
expires_in_days=payload.expires_in_days,
|
||||
created_by_user_id=admin.id,
|
||||
)
|
||||
return {
|
||||
"item": serialize_api_key(record),
|
||||
"api_key": raw_key,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/{key_id}/revoke")
|
||||
async def revoke_existing_api_key(
|
||||
key_id: int,
|
||||
_admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
record = await revoke_api_key(db, key_id)
|
||||
return {"item": serialize_api_key(record)}
|
||||
|
||||
|
||||
@router.delete("/{key_id}")
|
||||
async def delete_existing_api_key(
|
||||
key_id: int,
|
||||
_admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
await delete_api_key(db, key_id)
|
||||
return {"status": "deleted", "id": key_id}
|
||||
@@ -2,14 +2,23 @@ import asyncio
|
||||
from hashlib import sha256
|
||||
import ipaddress
|
||||
import time
|
||||
from typing import Optional
|
||||
from typing import Literal, Optional
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, HTTPException, Request, status
|
||||
from fastapi import APIRouter, Body, Depends, HTTPException, Request, Response, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer, OAuth2PasswordRequestForm
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.core.access_gate import (
|
||||
EARTH_SESSION_COOKIE,
|
||||
check_sliding_rate_limit,
|
||||
create_earth_session_token,
|
||||
verify_desktop_handshake,
|
||||
verify_turnstile_token,
|
||||
verify_web_same_origin,
|
||||
)
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.enums import OtpPurpose, UserRole
|
||||
from app.core.logging import get_logger
|
||||
@@ -487,3 +496,66 @@ async def reset_password(payload: ResetPasswordRequest, db: AsyncSession = Depen
|
||||
)
|
||||
await db.commit()
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
class EarthSessionRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
client_type: Literal["web", "desktop"] = "web"
|
||||
turnstile_token: Optional[str] = None
|
||||
|
||||
|
||||
def _is_https_request(request: Request) -> bool:
|
||||
forwarded_proto = (request.headers.get("x-forwarded-proto") or "").split(",")[0].strip().lower()
|
||||
return forwarded_proto == "https" or request.url.scheme == "https"
|
||||
|
||||
|
||||
@router.post("/earth-session")
|
||||
async def create_earth_session(
|
||||
request: Request,
|
||||
response: Response,
|
||||
payload: EarthSessionRequest | None = Body(default=None),
|
||||
):
|
||||
"""Mint a short-lived Earth session credential for zero-login Web or Desktop Earth."""
|
||||
body = payload or EarthSessionRequest()
|
||||
client_ip = _client_ip(request)
|
||||
|
||||
if body.client_type == "desktop":
|
||||
await check_sliding_rate_limit(
|
||||
f"earth_session:desktop:{client_ip}",
|
||||
limit=120,
|
||||
window_seconds=3600,
|
||||
detail="Too many desktop Earth session requests",
|
||||
)
|
||||
client_header = await verify_desktop_handshake(request)
|
||||
token, ttl_seconds = create_earth_session_token("desktop", client_id=client_header)
|
||||
return {
|
||||
"token": token,
|
||||
"expires_in": ttl_seconds,
|
||||
"client_type": "desktop",
|
||||
}
|
||||
|
||||
await check_sliding_rate_limit(
|
||||
f"earth_session:web:{client_ip}",
|
||||
limit=60,
|
||||
window_seconds=3600,
|
||||
detail="Too many web Earth session requests",
|
||||
)
|
||||
verify_web_same_origin(request)
|
||||
await verify_turnstile_token(body.turnstile_token, client_ip)
|
||||
token, ttl_seconds = create_earth_session_token("web", client_id=client_ip)
|
||||
response.set_cookie(
|
||||
key=EARTH_SESSION_COOKIE,
|
||||
value=token,
|
||||
max_age=ttl_seconds,
|
||||
httponly=True,
|
||||
samesite="strict",
|
||||
secure=_is_https_request(request),
|
||||
path="/",
|
||||
)
|
||||
return {
|
||||
"expires_in": ttl_seconds,
|
||||
"ws_token": token,
|
||||
"client_type": "web",
|
||||
"turnstile_required": bool(str(settings.TURNSTILE_SECRET_KEY or "").strip()),
|
||||
}
|
||||
@@ -5,6 +5,7 @@ from fastapi.responses import FileResponse
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.core.enums import UserRole
|
||||
from app.core.security import get_current_user
|
||||
from app.db.session import get_db
|
||||
@@ -57,7 +58,7 @@ async def upload_image(file: UploadFile = File(...), _actor: User = Depends(imag
|
||||
return await run_in_threadpool(store_image, content, (file.filename or "Image")[:200])
|
||||
|
||||
|
||||
@router.get("/files/{filename}")
|
||||
@router.get("/files/{filename}", dependencies=[Depends(require_earth_or_api_access("earth:read", allow_query_api_key=True))])
|
||||
async def image_file(filename: str):
|
||||
path = uploaded_path(filename)
|
||||
if not path.is_file():
|
||||
@@ -83,7 +84,7 @@ async def targets(
|
||||
return {"items": await search_targets(db, entity_type, scope, q.strip(), limit)}
|
||||
|
||||
|
||||
@router.get("/resolve")
|
||||
@router.get("/resolve", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
|
||||
async def resolve(
|
||||
response: Response,
|
||||
entity_type: EntityType,
|
||||
|
||||
@@ -5,6 +5,7 @@ from typing import Literal
|
||||
|
||||
from app.core.compute_types import COMPUTE_SITE_TYPES, compute_record_filter, compute_site_type_expression
|
||||
from app.api.v1.visualization import convert_compute_centers_to_geojson
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.core.earth_geography_policy import display_country
|
||||
from app.core.enums import UserRole
|
||||
from app.core.logging import get_logger
|
||||
@@ -64,7 +65,7 @@ def selected_countries(countries: str) -> list[str]:
|
||||
return codes
|
||||
|
||||
|
||||
@router.get("/series")
|
||||
@router.get("/series", dependencies=[Depends(require_earth_or_api_access("data_products:read"))])
|
||||
async def get_series(
|
||||
response: Response,
|
||||
countries: str = "CN,US",
|
||||
@@ -182,7 +183,7 @@ async def sample_query(db: AsyncSession, countries: list[str], year: int | None)
|
||||
return query
|
||||
|
||||
|
||||
@router.get("/facilities")
|
||||
@router.get("/facilities", dependencies=[Depends(require_earth_or_api_access("data_products:read"))])
|
||||
async def get_facilities(
|
||||
countries: str = "CN,US",
|
||||
year: int | None = Query(None, ge=2000, le=2100),
|
||||
|
||||
@@ -4,10 +4,11 @@ from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.api.v1.visualization import get_visualization_geo_summary
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.db.session import get_db
|
||||
|
||||
router = APIRouter()
|
||||
router = APIRouter(dependencies=[Depends(require_earth_or_api_access("data_products:read"))])
|
||||
|
||||
PRODUCT_DEFINITIONS: dict[str, dict] = {
|
||||
"vessels": {
|
||||
|
||||
@@ -12,6 +12,7 @@ from pydantic import BaseModel, Field
|
||||
from sqlalchemy import delete, func, select, text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.core.config import settings as app_settings
|
||||
from app.core.logging import get_logger
|
||||
from app.core.security import (
|
||||
@@ -296,7 +297,7 @@ async def _broadcast_earth_config_update(layer: str) -> None:
|
||||
logger.warning("Failed to broadcast %s update: %s", layer, exc)
|
||||
|
||||
|
||||
@router.get("/brand")
|
||||
@router.get("/brand", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
|
||||
async def get_earth_brand(db: AsyncSession = Depends(get_db)):
|
||||
return await _get_earth_brand_payload(db)
|
||||
|
||||
@@ -366,7 +367,7 @@ async def upload_earth_brand_asset(
|
||||
return {"url": asset_url, "filename": safe_name, "content_type": file.content_type}
|
||||
|
||||
|
||||
@router.get("/about")
|
||||
@router.get("/about", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
|
||||
async def get_earth_about(db: AsyncSession = Depends(get_db)):
|
||||
return await _get_earth_about_payload(db)
|
||||
|
||||
@@ -401,7 +402,7 @@ async def reset_earth_about(
|
||||
return {"status": "reset", "about": _normalize_earth_about_payload(None), "is_default": True}
|
||||
|
||||
|
||||
@router.get("/news-sources")
|
||||
@router.get("/news-sources", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
|
||||
async def get_earth_news_sources(db: AsyncSession = Depends(get_db)):
|
||||
return await get_earth_news_sources_payload(db)
|
||||
|
||||
@@ -606,7 +607,7 @@ async def reprocess_earth_news_item_admin(
|
||||
return {"status": "queued" if queued else "not_queued", "queued": queued, "id": item_id}
|
||||
|
||||
|
||||
@router.get("/oobe-status")
|
||||
@router.get("/oobe-status", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
|
||||
async def get_earth_oobe_status(
|
||||
current_user: User | None = Depends(_get_optional_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
@@ -671,7 +672,7 @@ async def get_earth_oobe_status(
|
||||
}
|
||||
|
||||
|
||||
@router.get("/boundaries/status")
|
||||
@router.get("/boundaries/status", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
|
||||
async def get_earth_boundary_status():
|
||||
return get_boundary_status()
|
||||
|
||||
@@ -718,6 +719,6 @@ async def build_earth_boundary_assets(
|
||||
) from exc
|
||||
|
||||
|
||||
@router.get("/boundaries/build/status")
|
||||
@router.get("/boundaries/build/status", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
|
||||
async def get_earth_boundary_build_status():
|
||||
return get_boundary_build_status()
|
||||
@@ -9,6 +9,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.core.security import get_current_user
|
||||
from app.db.session import get_db
|
||||
from app.models.earth_interactable import EarthInteractable
|
||||
@@ -67,7 +68,7 @@ class InteractableUpdate(BaseModel):
|
||||
properties: dict[str, Any] | None = None
|
||||
|
||||
|
||||
@router.get("")
|
||||
@router.get("", dependencies=[Depends(require_earth_or_api_access("interactables:read"))])
|
||||
async def get_interactables(
|
||||
response: Response,
|
||||
layer: str | None = Query(default=None),
|
||||
@@ -79,7 +80,7 @@ async def get_interactables(
|
||||
return {"items": [serialize_interactable(item) for item in items]}
|
||||
|
||||
|
||||
@router.get("/geojson")
|
||||
@router.get("/geojson", dependencies=[Depends(require_earth_or_api_access("interactables:read"))])
|
||||
async def get_interactables_geojson(
|
||||
response: Response,
|
||||
layer: str | None = Query(default=None),
|
||||
@@ -135,7 +136,7 @@ async def create_interactable(
|
||||
return {"item": serialize_interactable(record)}
|
||||
|
||||
|
||||
@router.get("/{interactable_id}")
|
||||
@router.get("/{interactable_id}", dependencies=[Depends(require_earth_or_api_access("interactables:read"))])
|
||||
async def get_interactable(interactable_id: str, db: AsyncSession = Depends(get_db)):
|
||||
record = await db.get(EarthInteractable, interactable_id)
|
||||
if record is None or record.is_deleted:
|
||||
|
||||
@@ -13,9 +13,10 @@ from app.api.v1.visualization import (
|
||||
get_satellites_geojson,
|
||||
)
|
||||
from app.api.v1.vessels import build_vessel_snapshot_response
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.db.session import get_db
|
||||
|
||||
router = APIRouter()
|
||||
router = APIRouter(dependencies=[Depends(require_earth_or_api_access("layers:read"))])
|
||||
|
||||
DEFAULT_LAYER_LIMIT = 1000
|
||||
MAX_LAYER_LIMIT = 5000
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from uuid import UUID
|
||||
|
||||
from app.core.access_gate import (
|
||||
EarthAccessContext,
|
||||
check_sliding_rate_limit,
|
||||
require_earth_or_api_access,
|
||||
)
|
||||
from app.db.session import get_db
|
||||
from app.services.earth_news import (
|
||||
ALLOWED_NEWS_CATEGORY_KEYS,
|
||||
@@ -70,7 +75,24 @@ def _parse_locale(raw: str | None) -> str:
|
||||
return requested
|
||||
|
||||
|
||||
@router.post("/refresh", status_code=status.HTTP_202_ACCEPTED)
|
||||
async def _require_news_refresh_cooldown(
|
||||
request: Request,
|
||||
access: EarthAccessContext = Depends(require_earth_or_api_access("news:read")),
|
||||
) -> None:
|
||||
peer = request.client.host if (request.client and request.client.host) else "unknown"
|
||||
await check_sliding_rate_limit(
|
||||
f"news_refresh:{access.actor_key}:{peer}",
|
||||
limit=3,
|
||||
window_seconds=60,
|
||||
detail="News refresh cooldown active; please retry shortly.",
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/refresh",
|
||||
status_code=status.HTTP_202_ACCEPTED,
|
||||
dependencies=[Depends(_require_news_refresh_cooldown)],
|
||||
)
|
||||
async def request_earth_news_refresh(payload: EarthNewsRefreshRequest):
|
||||
requested_region = payload.region.strip().lower() if payload.region else None
|
||||
if requested_region and requested_region not in REGION_ANCHORS:
|
||||
@@ -97,7 +119,10 @@ async def request_earth_news_refresh(payload: EarthNewsRefreshRequest):
|
||||
) from exc
|
||||
|
||||
|
||||
@router.get("/refresh/{refresh_id}")
|
||||
@router.get(
|
||||
"/refresh/{refresh_id}",
|
||||
dependencies=[Depends(require_earth_or_api_access("news:read"))],
|
||||
)
|
||||
async def get_earth_news_refresh(refresh_id: UUID):
|
||||
from app.services.earth_news_refresh import get_earth_news_refresh_status
|
||||
|
||||
@@ -124,7 +149,10 @@ async def get_earth_news_refresh(refresh_id: UUID):
|
||||
}
|
||||
|
||||
|
||||
@router.get("/earth-feed")
|
||||
@router.get(
|
||||
"/earth-feed",
|
||||
dependencies=[Depends(require_earth_or_api_access("news:read"))],
|
||||
)
|
||||
async def get_earth_feed(
|
||||
lat: float | None = Query(None, description="Current Earth view center latitude"),
|
||||
lon: float | None = Query(None, description="Current Earth view center longitude"),
|
||||
|
||||
@@ -68,6 +68,7 @@ from app.services.llm_provider_catalog import (
|
||||
)
|
||||
from app.services.llm_model_catalog import (
|
||||
LLMProviderCatalogConfigError,
|
||||
can_refresh_catalog_without_api_key,
|
||||
catalog_error_message,
|
||||
catalog_requires_api_key,
|
||||
fetch_model_catalog,
|
||||
@@ -2159,7 +2160,7 @@ async def refresh_public_llm_provider_presets(db: AsyncSession) -> dict:
|
||||
provider_config = ai_payload["providers"].get(provider_id) or _provider_defaults(provider_id)
|
||||
base_url = str(provider_config.get("base_url") or preset["base_url"] or "")
|
||||
provider_api = str(provider_config.get("provider_api") or preset["provider_api"] or "")
|
||||
if catalog_requires_api_key(provider_id, base_url, provider_api):
|
||||
if not can_refresh_catalog_without_api_key(provider_id, base_url, provider_api):
|
||||
continue
|
||||
try:
|
||||
refreshed = await refresh_llm_provider_preset(
|
||||
@@ -2243,7 +2244,9 @@ async def refresh_ai_provider_preset(
|
||||
resolved_base_url = str(provider_config.get("base_url") or fallback["base_url"] or "")
|
||||
resolved_api = str(provider_config.get("provider_api") or fallback["provider_api"] or "")
|
||||
api_key, _api_key_source = _resolve_provider_api_key(provider_id, provider_config)
|
||||
if not api_key and catalog_requires_api_key(provider_id, resolved_base_url, resolved_api):
|
||||
if not api_key and not can_refresh_catalog_without_api_key(
|
||||
provider_id, resolved_base_url, resolved_api
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=400, detail="请先配置当前供应商的 API Key,再刷新模型列表。",
|
||||
)
|
||||
|
||||
@@ -14,6 +14,7 @@ from sqlalchemy import desc, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.api.v1.compute_intelligence import configuration_admin, selected_countries
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.db.session import get_db
|
||||
from app.models.situational_assessment import (
|
||||
ComputeEvidenceCandidate,
|
||||
@@ -88,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
|
||||
@@ -406,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,
|
||||
@@ -494,7 +512,10 @@ async def cancel_workflow_run(
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.get("/results/{result_id:path}/revisions/{revision}")
|
||||
@router.get(
|
||||
"/results/{result_id:path}/revisions/{revision}",
|
||||
dependencies=[Depends(require_earth_or_api_access("situational:read"))],
|
||||
)
|
||||
async def get_frozen_result_revision(
|
||||
result_id: str,
|
||||
revision: int,
|
||||
@@ -518,7 +539,10 @@ async def get_frozen_result_revision(
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.get("/presentations")
|
||||
@router.get(
|
||||
"/presentations",
|
||||
dependencies=[Depends(require_earth_or_api_access("situational:read"))],
|
||||
)
|
||||
async def get_presentations(
|
||||
response: Response,
|
||||
after_cursor: int = Query(0, ge=0),
|
||||
@@ -541,7 +565,10 @@ async def get_presentations(
|
||||
)
|
||||
|
||||
|
||||
@router.get("/presentations/{presentation_key:path}")
|
||||
@router.get(
|
||||
"/presentations/{presentation_key:path}",
|
||||
dependencies=[Depends(require_earth_or_api_access("situational:read"))],
|
||||
)
|
||||
async def get_presentation_by_key(
|
||||
presentation_key: str,
|
||||
response: Response,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import os
|
||||
import secrets
|
||||
import subprocess
|
||||
@@ -12,6 +13,7 @@ from pydantic import BaseModel
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import ROOT_DIR, settings
|
||||
from app.core.enums import UserRole
|
||||
from app.core.security import get_current_user
|
||||
from app.db.session import get_db
|
||||
from app.models.user import User
|
||||
@@ -634,3 +636,113 @@ async def ingest_admin_client_log(
|
||||
payload=payload,
|
||||
request=request,
|
||||
)
|
||||
|
||||
|
||||
_EXTERNAL_OPENAPI_PREFIXES = (
|
||||
"/health",
|
||||
"/api/v1/auth/login",
|
||||
"/api/v1/auth/refresh",
|
||||
"/api/v1/visualization/",
|
||||
"/api/v1/layers/",
|
||||
"/api/v1/vessels/",
|
||||
"/api/v1/news/",
|
||||
"/api/v1/data-products",
|
||||
"/api/v1/earth/",
|
||||
"/api/v1/interactables",
|
||||
"/api/v1/tv/",
|
||||
"/api/v1/client/update-manifest",
|
||||
)
|
||||
_EXTERNAL_OPENAPI_EXCLUDED_SUBSTRINGS = (
|
||||
"collect-location",
|
||||
"/location",
|
||||
"/configuration",
|
||||
"/upload",
|
||||
"/preview",
|
||||
"/targets",
|
||||
"/brand/assets",
|
||||
"/boundaries/build",
|
||||
"/boundaries/config",
|
||||
"/news-groups",
|
||||
"/news-items",
|
||||
)
|
||||
_EXTERNAL_ALLOWED_POST_PATHS = frozenset(
|
||||
{
|
||||
"/api/v1/auth/login",
|
||||
"/api/v1/auth/refresh",
|
||||
"/api/v1/visualization/terrain/terrarium/batch",
|
||||
"/api/v1/visualization/geo/path",
|
||||
"/api/v1/news/refresh",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _require_docs_developer_or_admin(current_user: User = Depends(get_current_user)) -> User:
|
||||
role = (
|
||||
current_user.role.value
|
||||
if hasattr(current_user.role, "value")
|
||||
else str(current_user.role or "")
|
||||
)
|
||||
groups = {str(g).strip() for g in (current_user.gatekeeper_groups or []) if g}
|
||||
if (
|
||||
role in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}
|
||||
or "docs_developer" in groups
|
||||
or "docs_admin" in groups
|
||||
):
|
||||
return current_user
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Developer docs or administrator permission required",
|
||||
)
|
||||
|
||||
|
||||
def _build_external_openapi_schema(raw_schema: dict) -> dict:
|
||||
schema = copy.deepcopy(raw_schema)
|
||||
raw_paths = schema.get("paths") or {}
|
||||
filtered_paths: dict = {}
|
||||
for path, path_item in raw_paths.items():
|
||||
if not isinstance(path_item, dict):
|
||||
continue
|
||||
if not any(path.startswith(prefix) for prefix in _EXTERNAL_OPENAPI_PREFIXES):
|
||||
continue
|
||||
if any(sub in path for sub in _EXTERNAL_OPENAPI_EXCLUDED_SUBSTRINGS):
|
||||
continue
|
||||
allowed_methods: dict = {}
|
||||
for method, operation in path_item.items():
|
||||
lower_method = str(method).lower()
|
||||
if lower_method == "get":
|
||||
allowed_methods[method] = operation
|
||||
elif lower_method == "post" and path in _EXTERNAL_ALLOWED_POST_PATHS:
|
||||
allowed_methods[method] = operation
|
||||
if allowed_methods:
|
||||
filtered_paths[path] = allowed_methods
|
||||
|
||||
schema["paths"] = filtered_paths
|
||||
components = schema.setdefault("components", {})
|
||||
security_schemes = components.setdefault("securitySchemes", {})
|
||||
security_schemes["ApiKeyAuth"] = {
|
||||
"type": "apiKey",
|
||||
"in": "header",
|
||||
"name": "X-API-Key",
|
||||
}
|
||||
schema["security"] = [{"ApiKeyAuth": []}]
|
||||
info = schema.setdefault("info", {})
|
||||
info["title"] = f"{info.get('title', 'Planet API')} (External & UE5 Read-Only)"
|
||||
return schema
|
||||
|
||||
|
||||
@router.get("/openapi.json")
|
||||
async def get_controlled_openapi_schema(
|
||||
request: Request,
|
||||
_user: User = Depends(_require_docs_developer_or_admin),
|
||||
):
|
||||
"""Return full OpenAPI schema for authenticated administrators and docs_developer users."""
|
||||
return request.app.openapi()
|
||||
|
||||
|
||||
@router.get("/openapi-external.json")
|
||||
async def get_external_openapi_schema(
|
||||
request: Request,
|
||||
_user: User = Depends(_require_docs_developer_or_admin),
|
||||
):
|
||||
"""Return curated external/UE5 OpenAPI schema excluding internal admin endpoints."""
|
||||
return _build_external_openapi_schema(request.app.openapi())
|
||||
@@ -6,6 +6,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from fastapi.responses import Response
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.db.session import get_db
|
||||
from app.services.tv_catalog import get_tv_catalog_page
|
||||
from app.services.tv_streams import get_public_tv_payload, is_allowed_tv_proxy_url
|
||||
@@ -33,7 +34,7 @@ def _should_strip_hls_metadata_line(line: str) -> bool:
|
||||
return normalized.startswith("#EXT-X-MEDIA:") and "TYPE=SUBTITLES" in normalized
|
||||
|
||||
|
||||
@router.get("/streams")
|
||||
@router.get("/streams", dependencies=[Depends(require_earth_or_api_access("tv:read"))])
|
||||
async def list_public_tv_streams(
|
||||
offset: int = Query(0, ge=0),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
@@ -44,7 +45,7 @@ async def list_public_tv_streams(
|
||||
return await get_tv_catalog_page(db, offset=offset, limit=limit, q=q, selected_id=selected_id)
|
||||
|
||||
|
||||
@router.get("/proxy")
|
||||
@router.get("/proxy", dependencies=[Depends(require_earth_or_api_access("tv:read", allow_query_api_key=True))])
|
||||
async def proxy_tv_stream(
|
||||
url: str = Query(..., description="Upstream TV stream or manifest URL"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
|
||||
@@ -13,7 +13,7 @@ from app.schemas.user import UserCreate, UserUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
VALID_GATEKEEPER_GROUPS = {"docs_user", "docs_developer", "docs_admin"}
|
||||
VALID_GATEKEEPER_GROUPS = {"docs_user", "docs_developer", "docs_admin", "api_access"}
|
||||
ADMIN_ROLES = [UserRole.SUPER_ADMIN.value, UserRole.ADMIN.value]
|
||||
SUPER_ADMIN_ROLES = [UserRole.SUPER_ADMIN.value]
|
||||
|
||||
|
||||
@@ -6,13 +6,14 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Response
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.api.v1.visualization import _parse_bbox, build_vessel_snapshot_response
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.db.session import get_db
|
||||
from app.services.vessel_ais_aggregation import MAX_SNAPSHOT_LIMIT
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/snapshot")
|
||||
@router.get("/snapshot", dependencies=[Depends(require_earth_or_api_access("vessels:read"))])
|
||||
async def get_vessel_snapshot(
|
||||
bbox: Optional[str] = Query(None, description="Snapshot bbox as lon_min,lat_min,lon_max,lat_max"),
|
||||
zoom: float = Query(..., ge=1, le=20, description="Current map zoom level"),
|
||||
|
||||
@@ -18,6 +18,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select, func
|
||||
from typing import List, Dict, Any, Optional
|
||||
|
||||
from app.core.access_gate import require_admin_user, require_earth_or_api_access
|
||||
from app.core.compute_types import COMPUTE_SITE_TYPES, COMPUTE_SOURCES, compute_site_type, compute_record_filter, compute_site_type_expression
|
||||
from app.core.collected_data_fields import get_record_field
|
||||
from app.core.enums import BGPStatus
|
||||
@@ -29,6 +30,7 @@ from app.models.bgp_anomaly import BGPAnomaly
|
||||
from app.models.bgp_incident import BGPIncident
|
||||
from app.models.bgp_observation import BGPObservation
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.user import User
|
||||
from app.models.vessel import AISSourceHealth, VesselCurrentState, VesselPosition, VesselStatic
|
||||
from app.services.bgp_collectors import build_bgp_collector_coverage
|
||||
from app.services.cable_graph import build_graph_from_data, CableGraph, haversine_distance
|
||||
@@ -37,6 +39,7 @@ from app.services.compute_center_locations import (
|
||||
ResolutionDiagnostic,
|
||||
build_compute_center_location_query,
|
||||
collect_location_candidates,
|
||||
get_compute_center_location_dict,
|
||||
refresh_compute_center_location_cache,
|
||||
resolve_compute_center_location_full,
|
||||
upsert_compute_center_location,
|
||||
@@ -48,6 +51,10 @@ from app.services.location.llm_fallback import (
|
||||
collect_llm_location_fallback_candidate,
|
||||
collect_location_search_evidence,
|
||||
)
|
||||
from app.services.location.agent_resolver import (
|
||||
run_controlled_location_agent,
|
||||
run_l1_structured_facility_resolvers,
|
||||
)
|
||||
from app.services.persistent_logs import record_system_log
|
||||
from app.services.vessel_ais_aggregation import (
|
||||
build_field_conflict_candidates,
|
||||
@@ -71,6 +78,7 @@ from app.core.logging import get_logger
|
||||
|
||||
router = APIRouter()
|
||||
logger = get_logger(__name__, service="api")
|
||||
_vis_read_dep = Depends(require_earth_or_api_access("visualization:read"))
|
||||
TERRAIN_TILE_URL_TEMPLATE = (
|
||||
"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"
|
||||
)
|
||||
@@ -1592,7 +1600,7 @@ def convert_bgp_incidents_to_geojson(
|
||||
# ============== API Endpoints ==============
|
||||
|
||||
|
||||
@router.get("/geo/cables")
|
||||
@router.get("/geo/cables", dependencies=[_vis_read_dep])
|
||||
async def get_cables_geojson(db: AsyncSession = Depends(get_db), response: Response = None):
|
||||
"""获取海底电缆 GeoJSON 数据 (LineString)"""
|
||||
async def build_payload() -> dict[str, Any]:
|
||||
@@ -1630,7 +1638,7 @@ async def _build_cables_geojson(db: AsyncSession) -> dict[str, Any]:
|
||||
raise HTTPException(status_code=500, detail=f"Internal error: {str(e)}")
|
||||
|
||||
|
||||
@router.get("/geo/landing-points")
|
||||
@router.get("/geo/landing-points", dependencies=[_vis_read_dep])
|
||||
async def get_landing_points_geojson(db: AsyncSession = Depends(get_db), response: Response = None):
|
||||
async def build_payload() -> dict[str, Any]:
|
||||
return await _build_landing_points_geojson(db)
|
||||
@@ -1685,7 +1693,7 @@ async def _build_landing_points_geojson(db: AsyncSession) -> dict[str, Any]:
|
||||
raise HTTPException(status_code=500, detail=f"Internal error: {str(e)}")
|
||||
|
||||
|
||||
@router.get("/terrain/terrarium/{z}/{x}/{y}.png")
|
||||
@router.get("/terrain/terrarium/{z}/{x}/{y}.png", dependencies=[_vis_read_dep])
|
||||
async def get_terrarium_tile(z: int, x: int, y: int):
|
||||
"""Proxy Terrarium elevation tiles through the backend to avoid browser CORS issues."""
|
||||
if not _is_valid_terrain_tile(z, x, y):
|
||||
@@ -1775,7 +1783,7 @@ async def _fetch_terrain_tile(
|
||||
return content, content_type, dict(headers)
|
||||
|
||||
|
||||
@router.post("/terrain/terrarium/batch")
|
||||
@router.post("/terrain/terrarium/batch", dependencies=[_vis_read_dep])
|
||||
async def get_terrarium_tile_batch(payload: TerrariumTileBatchRequest):
|
||||
"""Fetch Terrarium elevation tiles in batches so the browser avoids many tiny requests."""
|
||||
unique_tiles: list[TerrariumTileRequest] = []
|
||||
@@ -1841,7 +1849,7 @@ async def get_terrarium_tile_batch(payload: TerrariumTileBatchRequest):
|
||||
}
|
||||
|
||||
|
||||
@router.get("/geo/all")
|
||||
@router.get("/geo/all", dependencies=[_vis_read_dep])
|
||||
async def get_all_geojson(db: AsyncSession = Depends(get_db)):
|
||||
records_by_source = await _load_current_collected_data_by_sources(
|
||||
db,
|
||||
@@ -1880,7 +1888,7 @@ async def get_all_geojson(db: AsyncSession = Depends(get_db)):
|
||||
}
|
||||
|
||||
|
||||
@router.get("/geo/satellites")
|
||||
@router.get("/geo/satellites", dependencies=[_vis_read_dep])
|
||||
async def get_satellites_geojson(
|
||||
request: Request = None,
|
||||
limit: Optional[int] = Query(
|
||||
@@ -2002,7 +2010,7 @@ async def _build_satellites_compact(
|
||||
}
|
||||
|
||||
|
||||
@router.get("/geo/supercomputers")
|
||||
@router.get("/geo/supercomputers", dependencies=[_vis_read_dep])
|
||||
async def get_supercomputers_geojson(
|
||||
limit: int = 500,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
@@ -2025,7 +2033,7 @@ async def get_supercomputers_geojson(
|
||||
}
|
||||
|
||||
|
||||
@router.get("/geo/gpu-clusters")
|
||||
@router.get("/geo/gpu-clusters", dependencies=[_vis_read_dep])
|
||||
async def get_gpu_clusters_geojson(
|
||||
limit: int = 100,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
@@ -2048,7 +2056,7 @@ async def get_gpu_clusters_geojson(
|
||||
}
|
||||
|
||||
|
||||
@router.get("/geo/compute-centers")
|
||||
@router.get("/geo/compute-centers", dependencies=[_vis_read_dep])
|
||||
async def get_compute_centers_geojson(
|
||||
limit: int = Query(200, ge=1, le=1000),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
@@ -2157,6 +2165,7 @@ class CollectComputeCenterLocationRequest(BaseModel):
|
||||
organization: Optional[str] = None
|
||||
city: Optional[str] = None
|
||||
country: Optional[str] = None
|
||||
force: bool = False
|
||||
record_id: Optional[int] = Field(default=None, alias="id")
|
||||
|
||||
model_config = {"populate_by_name": True}
|
||||
@@ -2193,12 +2202,12 @@ async def _compute_center_location_web_search_capability(db: AsyncSession) -> Di
|
||||
"reason": f"WebSearch 配置读取失败:{exc}",
|
||||
}
|
||||
provider_config = config.active_provider_config
|
||||
has_api_key = bool((provider_config.api_key or "").strip())
|
||||
has_api_key = bool((provider_config.api_key or "").strip()) or not provider_config.api_key_env
|
||||
if not config.enabled:
|
||||
return {
|
||||
"enabled": False,
|
||||
"provider": config.default_provider,
|
||||
"reason": "WebSearch 未开启,无法进行事实核查定位。",
|
||||
"reason": "WebSearch 未开启,将仅使用确定性设施知识库与地理编码。",
|
||||
}
|
||||
if not has_api_key:
|
||||
return {
|
||||
@@ -2213,7 +2222,7 @@ async def _compute_center_location_web_search_capability(db: AsyncSession) -> Di
|
||||
}
|
||||
|
||||
|
||||
@router.get("/compute-centers/location-capability")
|
||||
@router.get("/compute-centers/location-capability", dependencies=[_vis_read_dep])
|
||||
async def get_compute_center_location_capability(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
@@ -2221,27 +2230,19 @@ async def get_compute_center_location_capability(
|
||||
return await _compute_center_location_web_search_capability(db)
|
||||
|
||||
|
||||
_TERMINAL_UNLOCATABLE_STATUSES = frozenset({"undisclosed", "multi_site", "anonymous"})
|
||||
|
||||
|
||||
@router.post("/compute-centers/{source_id}/collect-location")
|
||||
async def collect_compute_center_location(
|
||||
source_id: str,
|
||||
payload: CollectComputeCenterLocationRequest,
|
||||
_admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Run the full multi-query location collection pipeline for a record.
|
||||
|
||||
The endpoint accepts the source_id of a compute center plus contextual
|
||||
fields (name/operator/site/city/country/...) and returns ranked candidate
|
||||
locations from source coordinates, open organization lookups, and online
|
||||
geocoding combinations. The caller never has to type coordinates by hand:
|
||||
if any candidate is accepted it can be applied directly. If no candidate
|
||||
can reach city-level precision the response includes an explicit
|
||||
``failure_reason`` and the list of attempted queries.
|
||||
"""
|
||||
"""Run deterministic facility lookups, Wikidata/PeeringDB, and controlled Tool-Calling location resolution."""
|
||||
if not source_id or not source_id.strip():
|
||||
raise HTTPException(status_code=400, detail="source_id is required")
|
||||
capability = await _compute_center_location_web_search_capability(db)
|
||||
if not capability.get("enabled"):
|
||||
raise HTTPException(status_code=409, detail=capability)
|
||||
|
||||
record = await _load_compute_center_record(db, source_id)
|
||||
name = payload.name or (record.name if record else None)
|
||||
@@ -2254,8 +2255,36 @@ async def collect_compute_center_location(
|
||||
country = payload.country or (get_record_field(record, "country") if record else None)
|
||||
source = payload.source or (record.source if record else None)
|
||||
record_id = payload.record_id or (record.id if record else None)
|
||||
raw_sources = metadata.get("sources") if isinstance(metadata.get("sources"), list) else []
|
||||
source_url = metadata.get("source_url") or metadata.get("detail_url")
|
||||
builds_upon = metadata.get("builds_upon")
|
||||
source_raw_country = metadata.get("raw_country")
|
||||
|
||||
candidates, attempted_queries = collect_location_candidates(
|
||||
if not payload.force and source and source_id:
|
||||
cached = get_compute_center_location_dict(source, source_id)
|
||||
cached_status = str(cached.get("verification_status") or "").strip().lower()
|
||||
if cached_status in _TERMINAL_UNLOCATABLE_STATUSES:
|
||||
return {
|
||||
"source_id": source_id,
|
||||
"record_id": record_id,
|
||||
"name": name,
|
||||
"success": False,
|
||||
"terminal_status": cached_status,
|
||||
"failure_reason": cached.get("source_note") or f"Marked as {cached_status}",
|
||||
"candidates": [],
|
||||
"attempted_queries": [],
|
||||
"llm_failure_reason": None,
|
||||
"context": {
|
||||
"name": name,
|
||||
"operator": operator,
|
||||
"site": site,
|
||||
"city": city,
|
||||
"country": country,
|
||||
},
|
||||
}
|
||||
|
||||
candidates, attempted_queries = await asyncio.to_thread(
|
||||
collect_location_candidates,
|
||||
name=name,
|
||||
source=source,
|
||||
source_id=source_id,
|
||||
@@ -2265,52 +2294,103 @@ async def collect_compute_center_location(
|
||||
city=city,
|
||||
country=country,
|
||||
record_id=record_id,
|
||||
sources=raw_sources,
|
||||
source_url=source_url,
|
||||
builds_upon=builds_upon,
|
||||
source_raw_country=source_raw_country,
|
||||
)
|
||||
llm_failure_reason = None
|
||||
terminal_status: str | None = None
|
||||
query = build_compute_center_location_query(
|
||||
name=name,
|
||||
source=source,
|
||||
source_id=source_id,
|
||||
operator=operator,
|
||||
site=site,
|
||||
organization=organization,
|
||||
city=city,
|
||||
country=country,
|
||||
sources=raw_sources,
|
||||
source_url=source_url,
|
||||
builds_upon=builds_upon,
|
||||
source_raw_country=source_raw_country,
|
||||
)
|
||||
if not candidates:
|
||||
query = build_compute_center_location_query(
|
||||
name=name,
|
||||
source=source,
|
||||
source_id=source_id,
|
||||
operator=operator,
|
||||
site=site,
|
||||
organization=organization,
|
||||
city=city,
|
||||
country=country,
|
||||
l1_candidates, l1_queries, _allow_low_short_circuit = await run_l1_structured_facility_resolvers(
|
||||
query, db=db
|
||||
)
|
||||
if l1_candidates:
|
||||
candidates = l1_candidates
|
||||
attempted_queries = [*attempted_queries, *l1_queries]
|
||||
|
||||
if not candidates:
|
||||
capability = await _compute_center_location_web_search_capability(db)
|
||||
llm_result = None
|
||||
try:
|
||||
web_search_client = await get_web_search_client(db)
|
||||
search_result = await collect_location_search_evidence(
|
||||
web_search_client=web_search_client,
|
||||
query=query,
|
||||
entity_type="compute_center",
|
||||
)
|
||||
attempted_queries = [*attempted_queries, *search_result.attempted_queries]
|
||||
if not search_result.evidence:
|
||||
llm_failure_reason = search_result.failure_reason
|
||||
raise RuntimeError(search_result.failure_reason or "no WebSearch evidence")
|
||||
provider_client = await get_ai_provider_client(db)
|
||||
llm_result = await collect_llm_location_fallback_candidate(
|
||||
provider_client=provider_client,
|
||||
query=query,
|
||||
entity_type="compute_center",
|
||||
db=db,
|
||||
attempted_queries=attempted_queries,
|
||||
search_evidence=search_result.evidence,
|
||||
)
|
||||
except Exception as exc:
|
||||
if llm_failure_reason is None:
|
||||
llm_failure_reason = f"LLM location factcheck unavailable: {exc}"
|
||||
attempted_queries = [
|
||||
*attempted_queries,
|
||||
f"llm_factcheck:compute_center:{name or source_id or 'unknown'}",
|
||||
]
|
||||
if not capability.get("enabled") and not raw_sources and not source_url:
|
||||
llm_failure_reason = str(capability.get("reason") or "WebSearch unavailable")
|
||||
else:
|
||||
try:
|
||||
provider_client = await get_ai_provider_client(db)
|
||||
web_search_client = await get_web_search_client(db)
|
||||
if hasattr(provider_client, "analyze"):
|
||||
llm_result, terminal_status = await run_controlled_location_agent(
|
||||
provider_client=provider_client,
|
||||
web_search_client=web_search_client,
|
||||
query=query,
|
||||
entity_type="compute_center",
|
||||
db=db,
|
||||
attempted_queries=[],
|
||||
)
|
||||
else:
|
||||
search_result = await collect_location_search_evidence(
|
||||
web_search_client=web_search_client,
|
||||
query=query,
|
||||
entity_type="compute_center",
|
||||
)
|
||||
attempted_queries = [*attempted_queries, *search_result.attempted_queries]
|
||||
if not search_result.evidence:
|
||||
llm_failure_reason = search_result.failure_reason
|
||||
raise RuntimeError(search_result.failure_reason or "no WebSearch evidence")
|
||||
llm_result = await collect_llm_location_fallback_candidate(
|
||||
provider_client=provider_client,
|
||||
query=query,
|
||||
entity_type="compute_center",
|
||||
db=db,
|
||||
attempted_queries=attempted_queries,
|
||||
search_evidence=search_result.evidence,
|
||||
)
|
||||
except Exception as exc:
|
||||
if llm_failure_reason is None:
|
||||
llm_failure_reason = f"LLM location factcheck unavailable: {exc}"
|
||||
attempted_queries = [
|
||||
*attempted_queries,
|
||||
f"llm_factcheck:compute_center:{name or source_id or 'unknown'}",
|
||||
]
|
||||
if llm_result is not None:
|
||||
attempted_queries = [*attempted_queries, *llm_result.attempted_queries]
|
||||
candidates = llm_result.candidates
|
||||
llm_failure_reason = llm_result.failure_reason
|
||||
|
||||
if terminal_status in _TERMINAL_UNLOCATABLE_STATUSES:
|
||||
return {
|
||||
"source_id": source_id,
|
||||
"record_id": record_id,
|
||||
"name": name,
|
||||
"success": False,
|
||||
"terminal_status": terminal_status,
|
||||
"failure_reason": llm_failure_reason or f"Marked as {terminal_status}",
|
||||
"candidates": [],
|
||||
"attempted_queries": list(attempted_queries),
|
||||
"llm_failure_reason": llm_failure_reason,
|
||||
"context": {
|
||||
"name": name,
|
||||
"operator": operator,
|
||||
"site": site,
|
||||
"city": city,
|
||||
"country": country,
|
||||
},
|
||||
}
|
||||
|
||||
if not candidates:
|
||||
logger.warning_event(
|
||||
"Compute center location collection returned no candidates",
|
||||
@@ -2394,6 +2474,7 @@ async def collect_compute_center_location(
|
||||
async def save_compute_center_location(
|
||||
source_id: str,
|
||||
payload: SaveComputeCenterLocationRequest,
|
||||
_admin: User = Depends(require_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Persist the user-selected compute-center location candidate."""
|
||||
@@ -2500,7 +2581,7 @@ async def _load_raw_vessel_snapshot_features(
|
||||
"legacy_fallback_used": False,
|
||||
}
|
||||
|
||||
@router.get("/vessels/custom-supplements")
|
||||
@router.get("/vessels/custom-supplements", dependencies=[_vis_read_dep])
|
||||
async def get_vessel_custom_supplements(db: AsyncSession = Depends(get_db)):
|
||||
"""Group custom vessel_ais sources by their declared merge target for diagnostics."""
|
||||
|
||||
@@ -2519,7 +2600,7 @@ async def get_vessel_custom_supplements(db: AsyncSession = Depends(get_db)):
|
||||
return {"groups": list(grouped.values())}
|
||||
|
||||
|
||||
@router.get("/vessels/name-fallbacks")
|
||||
@router.get("/vessels/name-fallbacks", dependencies=[_vis_read_dep])
|
||||
async def get_vessel_name_fallbacks(
|
||||
limit: int = Query(500, ge=0, description="Maximum fallback-name vessels to return. 0 means no limit."),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
@@ -2588,7 +2669,7 @@ async def get_vessel_name_fallbacks(
|
||||
}
|
||||
|
||||
|
||||
@router.get("/vessels/{mmsi}")
|
||||
@router.get("/vessels/{mmsi}", dependencies=[_vis_read_dep])
|
||||
async def get_vessel_detail(mmsi: int, db: AsyncSession = Depends(get_db)):
|
||||
from app.services.vessel_enrichment import get_vessel_enrichment_bundle
|
||||
|
||||
@@ -2623,7 +2704,7 @@ async def get_vessel_detail(mmsi: int, db: AsyncSession = Depends(get_db)):
|
||||
}
|
||||
|
||||
|
||||
@router.get("/vessels/{mmsi}/track")
|
||||
@router.get("/vessels/{mmsi}/track", dependencies=[_vis_read_dep])
|
||||
async def get_vessel_track(
|
||||
mmsi: int,
|
||||
hours: int = Query(6, ge=1, le=24),
|
||||
@@ -2690,7 +2771,7 @@ async def get_vessel_track(
|
||||
}
|
||||
|
||||
|
||||
@router.get("/vessels/{mmsi}/observations")
|
||||
@router.get("/vessels/{mmsi}/observations", dependencies=[_vis_read_dep])
|
||||
async def get_vessel_observations(
|
||||
mmsi: int,
|
||||
limit: int = Query(100, ge=1, le=500),
|
||||
@@ -2707,7 +2788,7 @@ async def get_vessel_observations(
|
||||
}
|
||||
|
||||
|
||||
@router.get("/vessels/{mmsi}/conflicts")
|
||||
@router.get("/vessels/{mmsi}/conflicts", dependencies=[_vis_read_dep])
|
||||
async def get_vessel_conflicts(mmsi: int, db: AsyncSession = Depends(get_db)):
|
||||
"""Return recorded AIS conflicts plus current raw-observation candidates."""
|
||||
|
||||
@@ -2721,7 +2802,7 @@ async def get_vessel_conflicts(mmsi: int, db: AsyncSession = Depends(get_db)):
|
||||
}
|
||||
|
||||
|
||||
@router.get("/geo/bgp-anomalies")
|
||||
@router.get("/geo/bgp-anomalies", dependencies=[_vis_read_dep])
|
||||
async def get_bgp_anomalies_geojson(
|
||||
severity: Optional[str] = Query(None),
|
||||
status: Optional[str] = Query("active"),
|
||||
@@ -2765,7 +2846,7 @@ async def _build_bgp_anomalies_geojson(
|
||||
return {**geojson, "count": len(geojson.get("features", []))}
|
||||
|
||||
|
||||
@router.get("/geo/bgp-incidents")
|
||||
@router.get("/geo/bgp-incidents", dependencies=[_vis_read_dep])
|
||||
async def get_bgp_incidents_geojson(
|
||||
severity: Optional[str] = Query(None),
|
||||
status: Optional[str] = Query("active"),
|
||||
@@ -2809,7 +2890,7 @@ async def _build_bgp_incidents_geojson(
|
||||
return {**geojson, "count": len(geojson.get("features", []))}
|
||||
|
||||
|
||||
@router.get("/geo/bgp-collectors")
|
||||
@router.get("/geo/bgp-collectors", dependencies=[_vis_read_dep])
|
||||
async def get_bgp_collectors_geojson(db: AsyncSession = Depends(get_db), response: Response = None):
|
||||
async def build_payload() -> dict[str, Any]:
|
||||
return await _build_bgp_collectors_geojson(db)
|
||||
@@ -2838,7 +2919,7 @@ async def _build_bgp_collectors_geojson(db: AsyncSession) -> dict[str, Any]:
|
||||
return {**geojson, "count": len(geojson.get("features", []))}
|
||||
|
||||
|
||||
@router.get("/geo/summary")
|
||||
@router.get("/geo/summary", dependencies=[_vis_read_dep])
|
||||
async def get_visualization_geo_summary(db: AsyncSession = Depends(get_db), response: Response = None):
|
||||
"""Return lightweight Earth HUD counts without loading layer GeoJSON payloads."""
|
||||
async def build_payload() -> dict[str, Any]:
|
||||
@@ -2948,7 +3029,7 @@ async def _build_visualization_geo_summary(db: AsyncSession) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
@router.get("/all")
|
||||
@router.get("/all", dependencies=[_vis_read_dep])
|
||||
async def get_all_visualization_data(db: AsyncSession = Depends(get_db)):
|
||||
"""获取所有可视化数据的统一端点
|
||||
|
||||
@@ -3054,7 +3135,7 @@ async def get_cable_graph(db: AsyncSession) -> CableGraph:
|
||||
return _cable_graph
|
||||
|
||||
|
||||
@router.post("/geo/path")
|
||||
@router.post("/geo/path", dependencies=[_vis_read_dep])
|
||||
async def find_path(
|
||||
start: List[float],
|
||||
end: List[float],
|
||||
|
||||
@@ -4,17 +4,18 @@ import asyncio
|
||||
from datetime import UTC, datetime
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Query
|
||||
from fastapi import APIRouter, HTTPException, Query, WebSocket, WebSocketDisconnect
|
||||
from jose import jwt, JWTError
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.core.access_gate import authenticate_ws_earth_or_api_key
|
||||
from app.core.config import settings
|
||||
from app.core.enums import UserRole
|
||||
from app.core.logging import get_logger
|
||||
from app.core.security import is_token_blacklisted
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.core.websocket.manager import manager
|
||||
from app.db.session import async_session_factory
|
||||
from app.db.session import async_session_factory, get_db
|
||||
from app.services.log_tail import LOG_TAIL_CHANNEL, log_tail_manager
|
||||
|
||||
logger = get_logger(__name__, service="api")
|
||||
@@ -74,12 +75,24 @@ async def load_websocket_user_role(user_id: str | None) -> str | None:
|
||||
async def websocket_endpoint(
|
||||
websocket: WebSocket,
|
||||
token: str | None = Query(None),
|
||||
api_key: str | None = Query(None),
|
||||
earth_token: str | None = Query(None),
|
||||
):
|
||||
"""WebSocket endpoint for real-time data"""
|
||||
logger.info_event(
|
||||
"WebSocket connection attempt",
|
||||
event="auth.websocket.connection_attempt",
|
||||
context={"token_preview": f"{token[:8]}..." if token else "anonymous"},
|
||||
context={
|
||||
"token_preview": f"{token[:8]}..." if token else (
|
||||
"api_key" if (api_key or websocket.headers.get("X-API-Key")) else (
|
||||
"earth_session" if (
|
||||
earth_token
|
||||
or websocket.headers.get("X-Planet-Earth-Token")
|
||||
or websocket.cookies.get("planet_earth_session")
|
||||
) else "anonymous"
|
||||
)
|
||||
)
|
||||
},
|
||||
)
|
||||
payload = await authenticate_token(token) if token else None
|
||||
if token and payload is None:
|
||||
@@ -90,8 +103,61 @@ async def websocket_endpoint(
|
||||
await websocket.close(code=4001)
|
||||
return
|
||||
|
||||
ws_earth_or_key_actor: str | None = None
|
||||
if payload is None:
|
||||
has_api_key = bool((api_key or "").strip() or (websocket.headers.get("X-API-Key") or "").strip())
|
||||
try:
|
||||
if has_api_key:
|
||||
override_get_db = websocket.app.dependency_overrides.get(get_db)
|
||||
if override_get_db is not None:
|
||||
db_gen = override_get_db()
|
||||
db = await anext(db_gen)
|
||||
try:
|
||||
authed, ws_earth_or_key_actor = await authenticate_ws_earth_or_api_key(
|
||||
websocket,
|
||||
api_key_query=api_key,
|
||||
earth_token_query=earth_token,
|
||||
db=db,
|
||||
)
|
||||
finally:
|
||||
await db_gen.aclose()
|
||||
else:
|
||||
async with async_session_factory() as db:
|
||||
authed, ws_earth_or_key_actor = await authenticate_ws_earth_or_api_key(
|
||||
websocket,
|
||||
api_key_query=api_key,
|
||||
earth_token_query=earth_token,
|
||||
db=db,
|
||||
)
|
||||
else:
|
||||
authed, ws_earth_or_key_actor = await authenticate_ws_earth_or_api_key(
|
||||
websocket,
|
||||
api_key_query=None,
|
||||
earth_token_query=earth_token,
|
||||
db=None, # type: ignore[arg-type]
|
||||
)
|
||||
except HTTPException:
|
||||
logger.warning_event(
|
||||
"WebSocket API key or Earth session rejected",
|
||||
event="auth.websocket.connection_rejected",
|
||||
)
|
||||
await websocket.close(code=4001)
|
||||
return
|
||||
|
||||
if not authed and settings.effective_earth_api_auth_mode == "enforce":
|
||||
logger.warning_event(
|
||||
"Unauthenticated WebSocket connection rejected in enforce mode",
|
||||
event="auth.websocket.unauthenticated_rejected",
|
||||
)
|
||||
await websocket.close(code=4001)
|
||||
return
|
||||
|
||||
is_anonymous = payload is None
|
||||
user_id = str(payload.get("sub")) if payload else f"anonymous:{id(websocket)}"
|
||||
user_id = (
|
||||
str(payload.get("sub"))
|
||||
if payload
|
||||
else (ws_earth_or_key_actor or f"anonymous:{id(websocket)}")
|
||||
)
|
||||
user_role = await load_websocket_user_role(user_id) if payload else None
|
||||
supported_channels = ["vessels", "earth_news", EARTH_UPDATES_CHANNEL] if is_anonymous else [
|
||||
"gpu_clusters",
|
||||
|
||||
@@ -0,0 +1,492 @@
|
||||
"""Unified access gate for first-party Earth sessions, API keys, and authorized JWT callers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections import defaultdict, deque
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
import time
|
||||
from typing import Any, Literal
|
||||
from urllib.parse import urlsplit
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import Depends, HTTPException, Request, WebSocket, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
import httpx
|
||||
from jose import JWTError, jwt
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.enums import UserRole
|
||||
from app.core.logging import get_logger
|
||||
from app.core.security import (
|
||||
REDIS_OP_TIMEOUT_SECONDS,
|
||||
_AsyncRedisClient,
|
||||
_load_active_user,
|
||||
decode_token,
|
||||
get_current_user,
|
||||
is_token_blacklisted,
|
||||
)
|
||||
from app.db.session import get_db
|
||||
from app.models.user import User
|
||||
from app.services.api_keys import authenticate_api_key
|
||||
|
||||
logger = get_logger(__name__, service="access_gate")
|
||||
|
||||
EARTH_SESSION_COOKIE = "planet_earth_session"
|
||||
EARTH_TOKEN_HEADER = "X-Planet-Earth-Token"
|
||||
API_KEY_HEADER = "X-API-Key"
|
||||
API_ACCESS_GROUP = "api_access"
|
||||
DESKTOP_CLIENT_PREFIX = "planet-earth-desktop/"
|
||||
TURNSTILE_VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify"
|
||||
|
||||
_EARTH_SESSION_TOKEN_TYPE = "earth_session"
|
||||
_MAX_DESKTOP_CLOCK_SKEW_SECONDS = 300
|
||||
_EARTH_SESSION_RATE_LIMIT_PER_MIN = 600
|
||||
_LOCAL_SLIDING_WINDOWS: dict[str, deque[float]] = defaultdict(deque)
|
||||
_LOCAL_NONCES: dict[str, float] = {}
|
||||
_MAX_LOCAL_ENTRIES = 20_000
|
||||
|
||||
optional_bearer = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class EarthAccessContext:
|
||||
"""Resolved caller identity for Earth data and external API routes."""
|
||||
|
||||
channel: Literal["api_key", "jwt", "earth_web", "earth_desktop", "dev_open"]
|
||||
actor_key: str
|
||||
user: User | None = None
|
||||
api_key_id: int | None = None
|
||||
|
||||
|
||||
def reset_access_gate_caches() -> None:
|
||||
"""Clear in-process rate-limit and nonce caches (used by tests)."""
|
||||
_LOCAL_SLIDING_WINDOWS.clear()
|
||||
_LOCAL_NONCES.clear()
|
||||
|
||||
|
||||
def _prune_local_nonces(now: float) -> None:
|
||||
expired = [key for key, exp in _LOCAL_NONCES.items() if exp <= now]
|
||||
for key in expired:
|
||||
_LOCAL_NONCES.pop(key, None)
|
||||
while len(_LOCAL_NONCES) > _MAX_LOCAL_ENTRIES:
|
||||
_LOCAL_NONCES.pop(next(iter(_LOCAL_NONCES)), None)
|
||||
|
||||
|
||||
async def check_sliding_rate_limit(
|
||||
bucket: str,
|
||||
*,
|
||||
limit: int,
|
||||
window_seconds: int,
|
||||
detail: str = "Rate limit exceeded",
|
||||
) -> None:
|
||||
"""Enforce a bounded sliding/fixed window limit via Redis with local fallback."""
|
||||
if limit <= 0 or window_seconds <= 0:
|
||||
return
|
||||
redis_key = f"access_gate:{bucket}"
|
||||
try:
|
||||
client = _AsyncRedisClient.get_client()
|
||||
count = await asyncio.wait_for(
|
||||
client.incr(redis_key),
|
||||
timeout=REDIS_OP_TIMEOUT_SECONDS,
|
||||
)
|
||||
if int(count) == 1:
|
||||
await asyncio.wait_for(
|
||||
client.expire(redis_key, window_seconds),
|
||||
timeout=REDIS_OP_TIMEOUT_SECONDS,
|
||||
)
|
||||
if int(count) > limit:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail=detail,
|
||||
)
|
||||
return
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
now = time.monotonic()
|
||||
dq = _LOCAL_SLIDING_WINDOWS[bucket]
|
||||
cutoff = now - float(window_seconds)
|
||||
while dq and dq[0] <= cutoff:
|
||||
dq.popleft()
|
||||
if len(dq) >= limit:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail=detail,
|
||||
)
|
||||
dq.append(now)
|
||||
if len(_LOCAL_SLIDING_WINDOWS) > _MAX_LOCAL_ENTRIES:
|
||||
_LOCAL_SLIDING_WINDOWS.pop(next(iter(_LOCAL_SLIDING_WINDOWS)), None)
|
||||
|
||||
|
||||
async def _register_nonce_once(nonce: str, ttl_seconds: int) -> bool:
|
||||
key = f"earth_nonce:{hashlib.sha256(nonce.encode('utf-8')).hexdigest()}"
|
||||
try:
|
||||
client = _AsyncRedisClient.get_client()
|
||||
stored = await asyncio.wait_for(
|
||||
client.set(key, "1", ex=ttl_seconds, nx=True),
|
||||
timeout=REDIS_OP_TIMEOUT_SECONDS,
|
||||
)
|
||||
return bool(stored)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
now = time.monotonic()
|
||||
_prune_local_nonces(now)
|
||||
if key in _LOCAL_NONCES and _LOCAL_NONCES[key] > now:
|
||||
return False
|
||||
_LOCAL_NONCES[key] = now + float(ttl_seconds)
|
||||
return True
|
||||
|
||||
|
||||
def create_earth_session_token(
|
||||
channel: Literal["web", "desktop"],
|
||||
client_id: str | None = None,
|
||||
) -> tuple[str, int]:
|
||||
"""Mint a short-lived signed JWT for Web Earth or Desktop Earth zero-login access."""
|
||||
ttl_minutes = max(5, int(settings.EARTH_SESSION_TTL_MINUTES or 30))
|
||||
ttl_seconds = ttl_minutes * 60
|
||||
expire = datetime.now(UTC) + timedelta(seconds=ttl_seconds)
|
||||
cid = (client_id or uuid4().hex[:16]).strip()[:64]
|
||||
payload = {
|
||||
"type": _EARTH_SESSION_TOKEN_TYPE,
|
||||
"channel": channel,
|
||||
"cid": cid,
|
||||
"jti": uuid4().hex,
|
||||
"exp": expire,
|
||||
}
|
||||
token = jwt.encode(payload, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
||||
return token, ttl_seconds
|
||||
|
||||
|
||||
def verify_earth_session_token(token: str) -> dict[str, Any] | None:
|
||||
"""Verify a signed Earth session token and return its claims or None."""
|
||||
cleaned = str(token or "").strip()
|
||||
if not cleaned:
|
||||
return None
|
||||
try:
|
||||
payload = jwt.decode(cleaned, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
|
||||
except JWTError:
|
||||
return None
|
||||
if payload.get("type") != _EARTH_SESSION_TOKEN_TYPE:
|
||||
return None
|
||||
if payload.get("channel") not in {"web", "desktop"}:
|
||||
return None
|
||||
return payload
|
||||
|
||||
|
||||
def _extract_host_port(raw_url_or_host: str) -> str:
|
||||
value = str(raw_url_or_host or "").strip()
|
||||
if not value:
|
||||
return ""
|
||||
if "://" in value:
|
||||
parsed = urlsplit(value)
|
||||
return (parsed.netloc or "").lower()
|
||||
return value.lower()
|
||||
|
||||
|
||||
def _allowed_web_origins(request: Request) -> set[str]:
|
||||
allowed: set[str] = set()
|
||||
req_host = _extract_host_port(request.headers.get("host") or request.url.netloc or "")
|
||||
if req_host:
|
||||
allowed.add(req_host)
|
||||
for raw in [*(settings.EARTH_WEB_ALLOWED_ORIGINS or []), *(settings.CORS_ORIGINS or [])]:
|
||||
host = _extract_host_port(str(raw))
|
||||
if host and host != "*":
|
||||
allowed.add(host)
|
||||
return allowed
|
||||
|
||||
|
||||
def verify_web_same_origin(request: Request) -> None:
|
||||
"""Require first-party browser same-origin / allowed-origin headers for web session minting."""
|
||||
sec_fetch_site = (request.headers.get("sec-fetch-site") or "").strip().lower()
|
||||
if sec_fetch_site in {"cross-site"}:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Cross-site Earth session requests are forbidden",
|
||||
)
|
||||
|
||||
origin_host = _extract_host_port(request.headers.get("origin") or "")
|
||||
referer_host = _extract_host_port(request.headers.get("referer") or "")
|
||||
allowed = _allowed_web_origins(request)
|
||||
|
||||
if origin_host:
|
||||
if origin_host not in allowed:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Origin not permitted for Earth web session",
|
||||
)
|
||||
return
|
||||
|
||||
if referer_host:
|
||||
if referer_host not in allowed:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Referer not permitted for Earth web session",
|
||||
)
|
||||
return
|
||||
|
||||
if sec_fetch_site in {"same-origin", "same-site"}:
|
||||
return
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Same-origin browser headers required for Earth web session",
|
||||
)
|
||||
|
||||
|
||||
async def verify_turnstile_token(token: str | None, remote_ip: str) -> None:
|
||||
"""Verify Cloudflare Turnstile token when `TURNSTILE_SECRET_KEY` is configured."""
|
||||
secret = str(settings.TURNSTILE_SECRET_KEY or "").strip()
|
||||
if not secret:
|
||||
return
|
||||
cleaned = str(token or "").strip()
|
||||
if not cleaned:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Turnstile verification token is required",
|
||||
)
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=5.0) as client:
|
||||
resp = await client.post(
|
||||
TURNSTILE_VERIFY_URL,
|
||||
data={
|
||||
"secret": secret,
|
||||
"response": cleaned,
|
||||
"remoteip": remote_ip,
|
||||
},
|
||||
)
|
||||
resp.raise_for_status()
|
||||
body = resp.json()
|
||||
except httpx.HTTPError as exc:
|
||||
logger.warning_event(
|
||||
"Turnstile verification request failed",
|
||||
event="access_gate.turnstile.error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Human verification service temporarily unavailable",
|
||||
) from exc
|
||||
|
||||
if not bool(body.get("success")):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Turnstile verification failed",
|
||||
)
|
||||
|
||||
|
||||
async def verify_desktop_handshake(request: Request) -> str:
|
||||
"""Verify Planet Earth Desktop client identity and optional HMAC handshake."""
|
||||
client_header = (request.headers.get("X-Planet-Client") or "").strip()
|
||||
if not client_header.startswith(DESKTOP_CLIENT_PREFIX) or len(client_header) <= len(
|
||||
DESKTOP_CLIENT_PREFIX
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Desktop client header is required",
|
||||
)
|
||||
|
||||
secret = str(settings.EARTH_DESKTOP_HANDSHAKE_SECRET or "").strip()
|
||||
if not secret:
|
||||
return client_header
|
||||
|
||||
ts_raw = (request.headers.get("X-Planet-Client-Timestamp") or "").strip()
|
||||
nonce = (request.headers.get("X-Planet-Client-Nonce") or "").strip()
|
||||
signature = (request.headers.get("X-Planet-Client-Signature") or "").strip().lower()
|
||||
if not ts_raw or not nonce or not signature or len(nonce) > 128:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Desktop handshake signature headers required",
|
||||
)
|
||||
|
||||
try:
|
||||
ts_val = int(ts_raw)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Invalid desktop handshake timestamp",
|
||||
) from exc
|
||||
|
||||
now_ts = int(time.time())
|
||||
if abs(now_ts - ts_val) > _MAX_DESKTOP_CLOCK_SKEW_SECONDS:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Desktop handshake timestamp expired",
|
||||
)
|
||||
|
||||
expected = hmac.new(
|
||||
secret.encode("utf-8"),
|
||||
f"{ts_raw}.{nonce}.{client_header}".encode("utf-8"),
|
||||
hashlib.sha256,
|
||||
).hexdigest()
|
||||
if not hmac.compare_digest(signature, expected):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Invalid desktop handshake signature",
|
||||
)
|
||||
|
||||
fresh = await _register_nonce_once(nonce, _MAX_DESKTOP_CLOCK_SKEW_SECONDS)
|
||||
if not fresh:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Replay desktop handshake nonce rejected",
|
||||
)
|
||||
return client_header
|
||||
|
||||
|
||||
def user_has_api_access(user: User) -> bool:
|
||||
"""Return True if the authenticated user is allowed to call Earth/external APIs."""
|
||||
role = user.role.value if hasattr(user.role, "value") else str(user.role or "")
|
||||
if role in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}:
|
||||
return True
|
||||
groups = {str(g).strip() for g in (user.gatekeeper_groups or []) if g}
|
||||
return API_ACCESS_GROUP in groups
|
||||
|
||||
|
||||
async def require_admin_user(current_user: User = Depends(get_current_user)) -> User:
|
||||
"""FastAPI dependency requiring `admin` or `super_admin` role."""
|
||||
role = current_user.role.value if hasattr(current_user.role, "value") else str(current_user.role or "")
|
||||
if role not in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Administrator privileges required",
|
||||
)
|
||||
return current_user
|
||||
|
||||
|
||||
async def _validate_bearer_api_user(
|
||||
token: str,
|
||||
db: AsyncSession,
|
||||
) -> User:
|
||||
if await is_token_blacklisted(token):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Token has been revoked",
|
||||
)
|
||||
payload = decode_token(token)
|
||||
if payload is None or payload.get("type") != "access" or payload.get("sub") is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid token",
|
||||
)
|
||||
user = await _load_active_user(str(payload["sub"]), db)
|
||||
if not user_has_api_access(user):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Account lacks api_access permission",
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
def require_earth_or_api_access(
|
||||
scope: str,
|
||||
*,
|
||||
allow_query_api_key: bool = False,
|
||||
):
|
||||
"""Build a FastAPI dependency allowing API Keys, authorized JWT users, or Earth sessions."""
|
||||
|
||||
async def _dependency(
|
||||
request: Request,
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(optional_bearer),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> EarthAccessContext:
|
||||
raw_api_key = (request.headers.get(API_KEY_HEADER) or "").strip()
|
||||
if not raw_api_key and allow_query_api_key:
|
||||
raw_api_key = (request.query_params.get("api_key") or "").strip()
|
||||
if raw_api_key:
|
||||
record = await authenticate_api_key(db, raw_api_key, scope)
|
||||
return EarthAccessContext(
|
||||
channel="api_key",
|
||||
actor_key=f"api_key:{record.id}",
|
||||
api_key_id=int(record.id),
|
||||
)
|
||||
|
||||
if credentials is not None and credentials.credentials:
|
||||
user = await _validate_bearer_api_user(credentials.credentials, db)
|
||||
return EarthAccessContext(
|
||||
channel="jwt",
|
||||
actor_key=f"user:{user.id}",
|
||||
user=user,
|
||||
)
|
||||
|
||||
earth_header = (request.headers.get(EARTH_TOKEN_HEADER) or "").strip()
|
||||
earth_cookie = (request.cookies.get(EARTH_SESSION_COOKIE) or "").strip()
|
||||
earth_token = earth_header or earth_cookie
|
||||
if earth_token:
|
||||
claims = verify_earth_session_token(earth_token)
|
||||
if claims is not None:
|
||||
channel = "earth_desktop" if claims.get("channel") == "desktop" else "earth_web"
|
||||
cid = str(claims.get("cid") or "anon")
|
||||
await check_sliding_rate_limit(
|
||||
f"earth:{channel}:{cid}",
|
||||
limit=_EARTH_SESSION_RATE_LIMIT_PER_MIN,
|
||||
window_seconds=60,
|
||||
detail="Earth session rate limit exceeded",
|
||||
)
|
||||
return EarthAccessContext(
|
||||
channel=channel,
|
||||
actor_key=f"{channel}:{cid}",
|
||||
)
|
||||
if settings.effective_earth_api_auth_mode == "enforce":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired Earth session",
|
||||
)
|
||||
|
||||
if settings.effective_earth_api_auth_mode == "enforce":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Authentication required",
|
||||
)
|
||||
|
||||
return EarthAccessContext(channel="dev_open", actor_key="dev:open")
|
||||
|
||||
return _dependency
|
||||
|
||||
|
||||
async def authenticate_ws_earth_or_api_key(
|
||||
websocket: WebSocket,
|
||||
*,
|
||||
api_key_query: str | None,
|
||||
earth_token_query: str | None,
|
||||
db: AsyncSession,
|
||||
) -> tuple[bool, str | None]:
|
||||
"""Authenticate non-JWT WebSocket connections via API key or Earth session token.
|
||||
|
||||
Returns `(authenticated, actor_id)`. Raises HTTPException on explicit invalid credentials.
|
||||
"""
|
||||
raw_api_key = (
|
||||
(websocket.headers.get(API_KEY_HEADER) or "").strip()
|
||||
or (api_key_query or "").strip()
|
||||
)
|
||||
if raw_api_key:
|
||||
record = await authenticate_api_key(db, raw_api_key, "ws:connect")
|
||||
return True, f"api_key:{record.id}"
|
||||
|
||||
raw_earth_token = (
|
||||
(websocket.headers.get(EARTH_TOKEN_HEADER) or "").strip()
|
||||
or (earth_token_query or "").strip()
|
||||
or (websocket.cookies.get(EARTH_SESSION_COOKIE) or "").strip()
|
||||
)
|
||||
if raw_earth_token:
|
||||
claims = verify_earth_session_token(raw_earth_token)
|
||||
if claims is None:
|
||||
if settings.effective_earth_api_auth_mode == "enforce":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired Earth WebSocket session",
|
||||
)
|
||||
return False, None
|
||||
channel = str(claims.get("channel") or "web")
|
||||
cid = str(claims.get("cid") or secrets.token_hex(4))
|
||||
return True, f"earth_{channel}:{cid}"
|
||||
|
||||
return False, None
|
||||
@@ -92,10 +92,23 @@ class Settings(BaseSettings):
|
||||
CLIENT_MIN_SHELL_VERSION: str = "0.78.0"
|
||||
CLIENT_RELEASE_PAGE_URL: str = "https://gitea.rclaw.top/linkong/planet/releases"
|
||||
|
||||
EARTH_API_AUTH_MODE: str = ""
|
||||
EARTH_SESSION_TTL_MINUTES: int = 30
|
||||
EARTH_WEB_ALLOWED_ORIGINS: List[str] = []
|
||||
EARTH_DESKTOP_HANDSHAKE_SECRET: str = ""
|
||||
TURNSTILE_SECRET_KEY: str = ""
|
||||
|
||||
@property
|
||||
def is_production(self) -> bool:
|
||||
return str(self.APP_ENV or "").strip().lower() == "production"
|
||||
|
||||
@property
|
||||
def effective_earth_api_auth_mode(self) -> str:
|
||||
raw = str(self.EARTH_API_AUTH_MODE or "").strip().lower()
|
||||
if raw in {"enforce", "off"}:
|
||||
return raw
|
||||
return "enforce" if self.is_production else "off"
|
||||
|
||||
@property
|
||||
def normalized_role(self) -> str:
|
||||
role = str(self.PLANET_ROLE or "all").strip().lower()
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Create api_keys table for external and internal UE5 API key authentication."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
VERSION = "0004"
|
||||
NAME = "add_api_keys_table"
|
||||
|
||||
|
||||
async def upgrade(conn) -> None:
|
||||
"""Create api_keys table and indexes idempotently across PostgreSQL and SQLite."""
|
||||
dialect = getattr(getattr(conn, "dialect", None), "name", "")
|
||||
if dialect == "postgresql":
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS api_keys (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(120) NOT NULL,
|
||||
key_prefix VARCHAR(32) NOT NULL,
|
||||
key_hash VARCHAR(64) NOT NULL UNIQUE,
|
||||
scopes JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
rate_limit_per_minute INTEGER NULL,
|
||||
expires_at TIMESTAMP WITH TIME ZONE NULL,
|
||||
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_by_user_id INTEGER NULL,
|
||||
last_used_at TIMESTAMP WITH TIME ZONE NULL,
|
||||
revoked_at TIMESTAMP WITH TIME ZONE NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
else:
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS api_keys (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name VARCHAR(120) NOT NULL,
|
||||
key_prefix VARCHAR(32) NOT NULL,
|
||||
key_hash VARCHAR(64) NOT NULL UNIQUE,
|
||||
scopes JSON NOT NULL DEFAULT '[]',
|
||||
rate_limit_per_minute INTEGER NULL,
|
||||
expires_at TIMESTAMP NULL,
|
||||
is_active BOOLEAN NOT NULL DEFAULT 1,
|
||||
created_by_user_id INTEGER NULL,
|
||||
last_used_at TIMESTAMP NULL,
|
||||
revoked_at TIMESTAMP NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
await conn.execute(
|
||||
text("CREATE INDEX IF NOT EXISTS ix_api_keys_key_prefix ON api_keys (key_prefix)")
|
||||
)
|
||||
await conn.execute(
|
||||
text("CREATE UNIQUE INDEX IF NOT EXISTS ix_api_keys_key_hash ON api_keys (key_hash)")
|
||||
)
|
||||
await conn.execute(
|
||||
text("CREATE INDEX IF NOT EXISTS ix_api_keys_is_active ON api_keys (is_active)")
|
||||
)
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Create ai_workflows, ai_workflow_revisions, and ai_workflow_fixtures tables."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
VERSION = "0005"
|
||||
NAME = "add_ai_workflows"
|
||||
|
||||
|
||||
async def upgrade(conn) -> None:
|
||||
"""Create workflow management tables and indexes idempotently across PostgreSQL and SQLite."""
|
||||
dialect = getattr(getattr(conn, "dialect", None), "name", "")
|
||||
if dialect == "postgresql":
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS ai_workflows (
|
||||
id SERIAL PRIMARY KEY,
|
||||
workflow_id VARCHAR(80) NOT NULL UNIQUE,
|
||||
name VARCHAR(160) NOT NULL,
|
||||
name_en VARCHAR(160) NOT NULL DEFAULT '',
|
||||
category VARCHAR(60) NOT NULL DEFAULT 'advisor',
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
description_en TEXT NOT NULL DEFAULT '',
|
||||
is_default BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
is_builtin BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
active_revision INTEGER NOT NULL DEFAULT 1,
|
||||
published_graph JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
draft_graph JSONB NULL,
|
||||
updated_by VARCHAR(120) NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS ai_workflow_revisions (
|
||||
id SERIAL PRIMARY KEY,
|
||||
workflow_id VARCHAR(80) NOT NULL,
|
||||
revision INTEGER NOT NULL,
|
||||
status VARCHAR(24) NOT NULL DEFAULT 'published',
|
||||
graph_json JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
change_summary TEXT NOT NULL DEFAULT '',
|
||||
created_by VARCHAR(120) NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS ai_workflow_fixtures (
|
||||
id SERIAL PRIMARY KEY,
|
||||
workflow_id VARCHAR(80) NOT NULL,
|
||||
name VARCHAR(160) NOT NULL,
|
||||
sample_question TEXT NOT NULL DEFAULT '',
|
||||
context_json JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
created_by VARCHAR(120) NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
else:
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS ai_workflows (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
workflow_id VARCHAR(80) NOT NULL UNIQUE,
|
||||
name VARCHAR(160) NOT NULL,
|
||||
name_en VARCHAR(160) NOT NULL DEFAULT '',
|
||||
category VARCHAR(60) NOT NULL DEFAULT 'advisor',
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
description_en TEXT NOT NULL DEFAULT '',
|
||||
is_default BOOLEAN NOT NULL DEFAULT 0,
|
||||
is_builtin BOOLEAN NOT NULL DEFAULT 1,
|
||||
active_revision INTEGER NOT NULL DEFAULT 1,
|
||||
published_graph JSON NOT NULL DEFAULT '{}',
|
||||
draft_graph JSON NULL,
|
||||
updated_by VARCHAR(120) NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS ai_workflow_revisions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
workflow_id VARCHAR(80) NOT NULL,
|
||||
revision INTEGER NOT NULL,
|
||||
status VARCHAR(24) NOT NULL DEFAULT 'published',
|
||||
graph_json JSON NOT NULL DEFAULT '{}',
|
||||
change_summary TEXT NOT NULL DEFAULT '',
|
||||
created_by VARCHAR(120) NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS ai_workflow_fixtures (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
workflow_id VARCHAR(80) NOT NULL,
|
||||
name VARCHAR(160) NOT NULL,
|
||||
sample_question TEXT NOT NULL DEFAULT '',
|
||||
context_json JSON NOT NULL DEFAULT '{}',
|
||||
created_by VARCHAR(120) NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_ai_workflows_category ON ai_workflows (category)"))
|
||||
await conn.execute(text("CREATE INDEX IF NOT EXISTS idx_ai_workflow_revisions_wf_rev ON ai_workflow_revisions (workflow_id, revision)"))
|
||||
await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_ai_workflow_fixtures_wf ON ai_workflow_fixtures (workflow_id)"))
|
||||
@@ -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 '{}'")
|
||||
)
|
||||
@@ -470,6 +470,8 @@ async def ensure_default_admin_user(session: AsyncSession):
|
||||
|
||||
async def init_db():
|
||||
import app.models.user # noqa: F401
|
||||
import app.models.api_key # noqa: F401
|
||||
import app.models.ai_workflow # noqa: F401
|
||||
import app.models.gpu_cluster # noqa: F401
|
||||
import app.models.task # noqa: F401
|
||||
import app.models.data_snapshot # noqa: F401
|
||||
@@ -909,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(
|
||||
"""
|
||||
@@ -1121,3 +1131,6 @@ async def _init_db_ddl_and_seed():
|
||||
await purge_legacy_earth_boundary_datasources(session)
|
||||
await ensure_default_admin_user(session)
|
||||
await ensure_default_storage_policy(session)
|
||||
from app.services.ai.workflow_registry import ensure_builtin_workflows
|
||||
|
||||
await ensure_builtin_workflows(session)
|
||||
+3
-4
@@ -182,8 +182,8 @@ app = FastAPI(
|
||||
description="智能星球计划 - 态势感知系统\n\n## 功能模块\n\n- **用户认证**: JWT-based authentication\n- **数据源管理**: 多源数据采集器管理\n- **任务调度**: 定时任务调度与监控\n- **实时更新**: WebSocket实时数据推送\n- **告警系统**: 多级告警管理\n\n## 数据层级\n\n- **L1**: 核心数据 (TOP500, Epoch AI GPU)\n- **L2**: 扩展数据 (HuggingFace, PeeringDB, 海缆)\n- **L3**: 分析数据\n- **L4**: 决策支持",
|
||||
lifespan=lifespan,
|
||||
docs_url=None,
|
||||
redoc_url="/docs",
|
||||
openapi_url="/openapi.json",
|
||||
redoc_url=None if settings.is_production else "/docs",
|
||||
openapi_url=None if settings.is_production else "/openapi.json",
|
||||
)
|
||||
|
||||
class NonStreamingGZipMiddleware:
|
||||
@@ -274,8 +274,7 @@ async def root():
|
||||
return {
|
||||
"name": settings.PROJECT_NAME,
|
||||
"version": settings.VERSION,
|
||||
"docs": "/docs",
|
||||
"redoc": "/redoc",
|
||||
"docs": None if settings.is_production else "/docs",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
from app.models.user import User
|
||||
from app.models.api_key import ApiKey
|
||||
from app.models.ai_workflow import AIWorkflow, AIWorkflowFixture, AIWorkflowRevision
|
||||
from app.models.gpu_cluster import GPUCluster
|
||||
from app.models.task import CollectionTask
|
||||
from app.models.data_snapshot import DataSnapshot
|
||||
@@ -29,6 +31,10 @@ from app.models.situational_assessment import (
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"AIWorkflow",
|
||||
"AIWorkflowFixture",
|
||||
"AIWorkflowRevision",
|
||||
"ApiKey",
|
||||
"User",
|
||||
"GPUCluster",
|
||||
"CollectionTask",
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Persistent AI workflow definitions, versioned revisions, and local test fixtures."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import Boolean, Column, DateTime, Index, Integer, JSON, String, Text
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.db.session import Base
|
||||
|
||||
|
||||
class AIWorkflow(Base):
|
||||
"""Managed AI Advisor workflow graph (published + optional draft revision)."""
|
||||
|
||||
__tablename__ = "ai_workflows"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True, index=True)
|
||||
workflow_id = Column(String(80), nullable=False, unique=True, index=True)
|
||||
name = Column(String(160), nullable=False)
|
||||
name_en = Column(String(160), nullable=False, default="")
|
||||
category = Column(String(60), nullable=False, default="advisor", index=True)
|
||||
description = Column(Text, nullable=False, default="")
|
||||
description_en = Column(Text, nullable=False, default="")
|
||||
is_default = Column(Boolean, nullable=False, default=False, index=True)
|
||||
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(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(
|
||||
DateTime(timezone=True),
|
||||
server_default=func.now(),
|
||||
onupdate=func.now(),
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"workflow_id": self.workflow_id,
|
||||
"name": self.name,
|
||||
"name_en": self.name_en or self.name,
|
||||
"category": self.category,
|
||||
"description": self.description or "",
|
||||
"description_en": self.description_en or self.description or "",
|
||||
"is_default": bool(self.is_default),
|
||||
"is_builtin": bool(self.is_builtin),
|
||||
"active_revision": int(self.active_revision or 1),
|
||||
"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),
|
||||
}
|
||||
|
||||
|
||||
class AIWorkflowRevision(Base):
|
||||
"""Immutable revision history for AI workflows enabling safe rollback."""
|
||||
|
||||
__tablename__ = "ai_workflow_revisions"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True, index=True)
|
||||
workflow_id = Column(String(80), nullable=False, index=True)
|
||||
revision = Column(Integer, nullable=False)
|
||||
status = Column(String(24), nullable=False, default="published", index=True)
|
||||
graph_json = Column(JSON, nullable=False, default=dict)
|
||||
change_summary = Column(Text, nullable=False, default="")
|
||||
created_by = Column(String(120), nullable=True)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
|
||||
__table_args__ = (
|
||||
Index("idx_ai_workflow_revisions_wf_rev", "workflow_id", "revision"),
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"workflow_id": self.workflow_id,
|
||||
"revision": int(self.revision),
|
||||
"status": self.status,
|
||||
"graph_json": self.graph_json or {},
|
||||
"change_summary": self.change_summary or "",
|
||||
"created_by": self.created_by,
|
||||
"created_at": to_iso8601_utc(self.created_at),
|
||||
}
|
||||
|
||||
|
||||
class AIWorkflowFixture(Base):
|
||||
"""Explicitly saved anonymized regression test fixture for an AI workflow."""
|
||||
|
||||
__tablename__ = "ai_workflow_fixtures"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True, index=True)
|
||||
workflow_id = Column(String(80), nullable=False, index=True)
|
||||
name = Column(String(160), nullable=False)
|
||||
sample_question = Column(Text, nullable=False, default="")
|
||||
context_json = Column(JSON, nullable=False, default=dict)
|
||||
created_by = Column(String(120), nullable=True)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"workflow_id": self.workflow_id,
|
||||
"name": self.name,
|
||||
"sample_question": self.sample_question or "",
|
||||
"context_json": self.context_json or {},
|
||||
"created_by": self.created_by,
|
||||
"created_at": to_iso8601_utc(self.created_at),
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Database model for internal/external API keys."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import Boolean, Column, DateTime, Integer, JSON, String
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.db.session import Base
|
||||
|
||||
|
||||
class ApiKey(Base):
|
||||
"""Hashed API key for UE5, internal scripts, and external partner integrations."""
|
||||
|
||||
__tablename__ = "api_keys"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True, index=True)
|
||||
name = Column(String(120), nullable=False)
|
||||
key_prefix = Column(String(32), nullable=False, index=True)
|
||||
key_hash = Column(String(64), nullable=False, unique=True, index=True)
|
||||
scopes = Column(JSON, nullable=False, default=list)
|
||||
rate_limit_per_minute = Column(Integer, nullable=True)
|
||||
expires_at = Column(DateTime(timezone=True), nullable=True)
|
||||
is_active = Column(Boolean, nullable=False, default=True, index=True)
|
||||
created_by_user_id = Column(Integer, nullable=True)
|
||||
last_used_at = Column(DateTime(timezone=True), nullable=True)
|
||||
revoked_at = Column(DateTime(timezone=True), nullable=True)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<ApiKey id={self.id} name={self.name!r} prefix={self.key_prefix!r}>"
|
||||
@@ -6,8 +6,23 @@ from app.core.enums import PlaygroundMessageKind, PlaygroundMessageRole, Playgro
|
||||
|
||||
|
||||
class ChatMessage(BaseModel):
|
||||
role: Literal["user", "assistant"]
|
||||
content: str = Field(..., min_length=1, max_length=12000)
|
||||
role: Literal["user", "assistant", "tool"]
|
||||
content: str = Field(default="", max_length=24000)
|
||||
tool_call_id: str | None = Field(default=None, max_length=200)
|
||||
name: str | None = Field(default=None, max_length=200)
|
||||
tool_calls: list[dict[str, Any]] | None = None
|
||||
|
||||
|
||||
class ToolCallRecord(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
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):
|
||||
@@ -20,14 +35,19 @@ class AIContentBlock(BaseModel):
|
||||
|
||||
class SituationalAnalysisRequest(BaseModel):
|
||||
title: str = Field(..., min_length=1, max_length=200)
|
||||
objective: str = Field(..., min_length=1, max_length=20000)
|
||||
objective: str = Field(..., min_length=1, max_length=24000)
|
||||
context: dict[str, Any] = Field(default_factory=dict)
|
||||
observations: list[str] = Field(default_factory=list)
|
||||
constraints: list[str] = Field(default_factory=list)
|
||||
system_prompt: str | None = Field(default=None, max_length=8000)
|
||||
preferred_model: str | None = Field(default=None, max_length=200)
|
||||
thinking: dict[str, Any] | None = None
|
||||
messages: list[ChatMessage] = Field(default_factory=list, max_length=32)
|
||||
messages: list[ChatMessage] = Field(default_factory=list, max_length=48)
|
||||
tools: list[dict[str, Any]] | None = None
|
||||
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):
|
||||
@@ -56,6 +76,8 @@ class SituationalAnalysisResponse(BaseModel):
|
||||
content_blocks: list[AIContentBlock] = Field(default_factory=list)
|
||||
text_blocks: list[str] = Field(default_factory=list)
|
||||
thinking_blocks: list[str] = Field(default_factory=list)
|
||||
tool_calls: list[ToolCallRecord] = Field(default_factory=list)
|
||||
stop_reason: str | None = None
|
||||
raw_response: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
|
||||
@@ -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),
|
||||
},
|
||||
}
|
||||
@@ -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] = {}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -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)
|
||||
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
"""API key lifecycle, scope evaluation, hashing, and rate-limited validation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections import defaultdict, deque
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import hashlib
|
||||
import secrets
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.core.security import REDIS_OP_TIMEOUT_SECONDS, _AsyncRedisClient
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.models.api_key import ApiKey
|
||||
|
||||
logger = get_logger(__name__, service="api_keys")
|
||||
|
||||
API_KEY_PREFIX = "plt_live_"
|
||||
EARTH_ALL_READ_SCOPE = "earth:all_read"
|
||||
|
||||
EARTH_READ_SCOPES: frozenset[str] = frozenset(
|
||||
{
|
||||
"visualization:read",
|
||||
"layers:read",
|
||||
"vessels:read",
|
||||
"news:read",
|
||||
"data_products:read",
|
||||
"situational:read",
|
||||
"earth:read",
|
||||
"interactables:read",
|
||||
"tv:read",
|
||||
"ws:connect",
|
||||
}
|
||||
)
|
||||
|
||||
VALID_API_KEY_SCOPES: frozenset[str] = frozenset({EARTH_ALL_READ_SCOPE, *EARTH_READ_SCOPES})
|
||||
|
||||
_LAST_USED_TOUCH_CACHE: dict[int, float] = {}
|
||||
_LOCAL_KEY_RATE_WINDOWS: dict[str, deque[float]] = defaultdict(deque)
|
||||
_LAST_USED_MIN_INTERVAL_SECONDS = 60.0
|
||||
|
||||
|
||||
def reset_api_key_runtime_caches() -> None:
|
||||
"""Clear in-process caches (intended for deterministic tests)."""
|
||||
_LAST_USED_TOUCH_CACHE.clear()
|
||||
_LOCAL_KEY_RATE_WINDOWS.clear()
|
||||
|
||||
|
||||
def hash_api_key(raw_key: str) -> str:
|
||||
"""Compute SHA-256 hex digest of a raw API key."""
|
||||
return hashlib.sha256(raw_key.strip().encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def mask_api_key_prefix(raw_key: str) -> str:
|
||||
"""Return a short non-sensitive prefix for UI display and logging."""
|
||||
cleaned = raw_key.strip()
|
||||
return f"{cleaned[:16]}..." if len(cleaned) > 16 else f"{cleaned[:8]}..."
|
||||
|
||||
|
||||
def normalize_api_key_scopes(scopes: list[str] | None) -> list[str]:
|
||||
"""Validate and deduplicate requested API key scopes."""
|
||||
if not scopes:
|
||||
return [EARTH_ALL_READ_SCOPE]
|
||||
normalized: list[str] = []
|
||||
seen: set[str] = set()
|
||||
invalid: list[str] = []
|
||||
for raw in scopes:
|
||||
scope = str(raw or "").strip()
|
||||
if not scope:
|
||||
continue
|
||||
if scope not in VALID_API_KEY_SCOPES:
|
||||
invalid.append(scope)
|
||||
continue
|
||||
if scope not in seen:
|
||||
seen.add(scope)
|
||||
normalized.append(scope)
|
||||
if invalid:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Unsupported API key scope(s): {', '.join(invalid)}",
|
||||
)
|
||||
if not normalized:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="At least one valid scope is required",
|
||||
)
|
||||
return normalized
|
||||
|
||||
|
||||
def api_key_allows_scope(key_scopes: list[str] | None, required_scope: str) -> bool:
|
||||
"""Return True if the key scopes authorize `required_scope`."""
|
||||
scopes = {str(item).strip() for item in (key_scopes or []) if item}
|
||||
if required_scope in scopes:
|
||||
return True
|
||||
if EARTH_ALL_READ_SCOPE in scopes and required_scope in EARTH_READ_SCOPES:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
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 serialize_api_key(record: ApiKey) -> dict[str, Any]:
|
||||
"""Serialize ApiKey metadata safely without exposing key_hash or raw secret."""
|
||||
now = datetime.now(UTC)
|
||||
expires_at = _ensure_utc(record.expires_at)
|
||||
is_expired = bool(expires_at is not None and expires_at <= now)
|
||||
status_label = "revoked" if not record.is_active else ("expired" if is_expired else "active")
|
||||
return {
|
||||
"id": record.id,
|
||||
"name": record.name,
|
||||
"key_prefix": record.key_prefix,
|
||||
"scopes": list(record.scopes or []),
|
||||
"rate_limit_per_minute": record.rate_limit_per_minute,
|
||||
"expires_at": to_iso8601_utc(expires_at),
|
||||
"is_active": bool(record.is_active),
|
||||
"is_expired": is_expired,
|
||||
"status": status_label,
|
||||
"created_by_user_id": record.created_by_user_id,
|
||||
"last_used_at": to_iso8601_utc(_ensure_utc(record.last_used_at)),
|
||||
"revoked_at": to_iso8601_utc(_ensure_utc(record.revoked_at)),
|
||||
"created_at": to_iso8601_utc(_ensure_utc(record.created_at)),
|
||||
}
|
||||
|
||||
|
||||
async def _enforce_api_key_rate_limit(key_id: int, limit_per_minute: int | None) -> None:
|
||||
if limit_per_minute is None or int(limit_per_minute) <= 0:
|
||||
return
|
||||
limit = int(limit_per_minute)
|
||||
window = 60
|
||||
bucket = f"rate:api_key:{key_id}"
|
||||
try:
|
||||
client = _AsyncRedisClient.get_client()
|
||||
current_count = await asyncio.wait_for(
|
||||
client.incr(bucket),
|
||||
timeout=REDIS_OP_TIMEOUT_SECONDS,
|
||||
)
|
||||
if int(current_count) == 1:
|
||||
await asyncio.wait_for(client.expire(bucket, window), timeout=REDIS_OP_TIMEOUT_SECONDS)
|
||||
if int(current_count) > limit:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="API key rate limit exceeded",
|
||||
)
|
||||
return
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
now = time.monotonic()
|
||||
dq = _LOCAL_KEY_RATE_WINDOWS[bucket]
|
||||
cutoff = now - float(window)
|
||||
while dq and dq[0] <= cutoff:
|
||||
dq.popleft()
|
||||
if len(dq) >= limit:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="API key rate limit exceeded",
|
||||
)
|
||||
dq.append(now)
|
||||
|
||||
|
||||
async def create_api_key(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
name: str,
|
||||
scopes: list[str] | None,
|
||||
rate_limit_per_minute: int | None,
|
||||
expires_in_days: int | None,
|
||||
created_by_user_id: int | None,
|
||||
) -> tuple[ApiKey, str]:
|
||||
"""Create and persist a new API key, returning `(record, raw_plaintext_once)`."""
|
||||
cleaned_name = str(name or "").strip()
|
||||
if not cleaned_name:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="API key name is required",
|
||||
)
|
||||
normalized_scopes = normalize_api_key_scopes(scopes)
|
||||
normalized_limit = (
|
||||
int(rate_limit_per_minute)
|
||||
if rate_limit_per_minute is not None and int(rate_limit_per_minute) > 0
|
||||
else None
|
||||
)
|
||||
expires_at: datetime | None = None
|
||||
if expires_in_days is not None and int(expires_in_days) > 0:
|
||||
expires_at = datetime.now(UTC) + timedelta(days=int(expires_in_days))
|
||||
|
||||
raw_key = f"{API_KEY_PREFIX}{secrets.token_urlsafe(32)}"
|
||||
record = ApiKey(
|
||||
name=cleaned_name[:120],
|
||||
key_prefix=mask_api_key_prefix(raw_key),
|
||||
key_hash=hash_api_key(raw_key),
|
||||
scopes=normalized_scopes,
|
||||
rate_limit_per_minute=normalized_limit,
|
||||
expires_at=expires_at,
|
||||
is_active=True,
|
||||
created_by_user_id=created_by_user_id,
|
||||
)
|
||||
db.add(record)
|
||||
await db.commit()
|
||||
await db.refresh(record)
|
||||
logger.info_event(
|
||||
"Created API key",
|
||||
event="api_key.created",
|
||||
context={
|
||||
"key_id": record.id,
|
||||
"key_prefix": record.key_prefix,
|
||||
"scopes": normalized_scopes,
|
||||
"has_expiry": expires_at is not None,
|
||||
"rate_limit_per_minute": normalized_limit,
|
||||
"created_by_user_id": created_by_user_id,
|
||||
},
|
||||
)
|
||||
return record, raw_key
|
||||
|
||||
|
||||
async def list_api_keys(db: AsyncSession) -> list[ApiKey]:
|
||||
result = await db.execute(select(ApiKey).order_by(ApiKey.created_at.desc(), ApiKey.id.desc()))
|
||||
return list(result.scalars().all())
|
||||
|
||||
|
||||
async def revoke_api_key(db: AsyncSession, key_id: int) -> ApiKey:
|
||||
result = await db.execute(select(ApiKey).where(ApiKey.id == key_id))
|
||||
record = result.scalar_one_or_none()
|
||||
if record is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="API key not found")
|
||||
if record.is_active:
|
||||
record.is_active = False
|
||||
record.revoked_at = datetime.now(UTC)
|
||||
await db.commit()
|
||||
await db.refresh(record)
|
||||
logger.info_event(
|
||||
"Revoked API key",
|
||||
event="api_key.revoked",
|
||||
context={"key_id": record.id, "key_prefix": record.key_prefix},
|
||||
)
|
||||
return record
|
||||
|
||||
|
||||
async def delete_api_key(db: AsyncSession, key_id: int) -> None:
|
||||
result = await db.execute(select(ApiKey).where(ApiKey.id == key_id))
|
||||
record = result.scalar_one_or_none()
|
||||
if record is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="API key not found")
|
||||
prefix = record.key_prefix
|
||||
await db.delete(record)
|
||||
await db.commit()
|
||||
logger.info_event(
|
||||
"Deleted API key",
|
||||
event="api_key.deleted",
|
||||
context={"key_id": key_id, "key_prefix": prefix},
|
||||
)
|
||||
|
||||
|
||||
async def authenticate_api_key(
|
||||
db: AsyncSession,
|
||||
raw_key: str,
|
||||
required_scope: str,
|
||||
) -> ApiKey:
|
||||
"""Validate an incoming raw API key for active status, expiration, scope, and rate limit."""
|
||||
cleaned = str(raw_key or "").strip()
|
||||
if not cleaned:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid API key",
|
||||
)
|
||||
|
||||
digest = hash_api_key(cleaned)
|
||||
result = await db.execute(select(ApiKey).where(ApiKey.key_hash == digest))
|
||||
record = result.scalar_one_or_none()
|
||||
if record is None or not record.is_active:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or revoked API key",
|
||||
)
|
||||
|
||||
expires_at = _ensure_utc(record.expires_at)
|
||||
if expires_at is not None and expires_at <= datetime.now(UTC):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="API key has expired",
|
||||
)
|
||||
|
||||
if not api_key_allows_scope(list(record.scopes or []), required_scope):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f"API key lacks required scope: {required_scope}",
|
||||
)
|
||||
|
||||
await _enforce_api_key_rate_limit(int(record.id), record.rate_limit_per_minute)
|
||||
|
||||
now_mono = time.monotonic()
|
||||
last_touched = _LAST_USED_TOUCH_CACHE.get(int(record.id), 0.0)
|
||||
if now_mono - last_touched >= _LAST_USED_MIN_INTERVAL_SECONDS:
|
||||
_LAST_USED_TOUCH_CACHE[int(record.id)] = now_mono
|
||||
try:
|
||||
record.last_used_at = datetime.now(UTC)
|
||||
await db.commit()
|
||||
except Exception:
|
||||
await db.rollback()
|
||||
|
||||
return record
|
||||
@@ -276,6 +276,66 @@ def _organization_label(organization: dict[str, Any], fallback: str) -> str:
|
||||
return fallback
|
||||
|
||||
|
||||
_COMMERCIAL_HYPERSCALER_TOKENS = frozenset(
|
||||
{
|
||||
"amazon",
|
||||
"aws",
|
||||
"microsoft",
|
||||
"azure",
|
||||
"google",
|
||||
"alphabet",
|
||||
"meta",
|
||||
"facebook",
|
||||
"openai",
|
||||
"xai",
|
||||
"oracle",
|
||||
"alibaba",
|
||||
"tencent",
|
||||
"bytedance",
|
||||
"nvidia",
|
||||
"apple",
|
||||
"coreweave",
|
||||
"lambda",
|
||||
}
|
||||
)
|
||||
_ROR_SIMILARITY_STOPWORDS = frozenset({"the", "of", "for", "and", "inc", "ltd", "corp", "llc", "co"})
|
||||
|
||||
|
||||
def _ror_is_plausible_facility_match(
|
||||
ror_query: str,
|
||||
organization: dict[str, Any],
|
||||
display_name: str,
|
||||
) -> bool:
|
||||
query_norm = normalize_text(ror_query)
|
||||
if not query_norm:
|
||||
return False
|
||||
query_tokens = {
|
||||
tok
|
||||
for tok in query_norm.split()
|
||||
if len(tok) >= 3 and tok not in _ROR_SIMILARITY_STOPWORDS
|
||||
}
|
||||
org_types = {str(t).strip().lower() for t in (organization.get("types") or []) if t}
|
||||
is_commercial = "company" in org_types or any(
|
||||
tok in query_tokens for tok in _COMMERCIAL_HYPERSCALER_TOKENS
|
||||
)
|
||||
if is_commercial:
|
||||
return False
|
||||
|
||||
candidate_labels = [display_name]
|
||||
for entry in organization.get("names") or []:
|
||||
if isinstance(entry, dict) and entry.get("value"):
|
||||
candidate_labels.append(str(entry["value"]))
|
||||
combined_norm = normalize_text(" ".join(candidate_labels))
|
||||
if not combined_norm:
|
||||
return False
|
||||
if query_norm in combined_norm or combined_norm in query_norm:
|
||||
return True
|
||||
if not query_tokens:
|
||||
return False
|
||||
label_tokens = set(combined_norm.split())
|
||||
return bool(query_tokens & label_tokens)
|
||||
|
||||
|
||||
class ROROrganizationResolver:
|
||||
"""Resolve source-provided organization/site text through the open ROR API."""
|
||||
|
||||
@@ -308,6 +368,9 @@ class ROROrganizationResolver:
|
||||
continue
|
||||
if not isinstance(organization, dict):
|
||||
continue
|
||||
display_name = _organization_label(organization, ror_query)
|
||||
if not _ror_is_plausible_facility_match(ror_query, organization, display_name):
|
||||
continue
|
||||
locations = organization.get("locations")
|
||||
if not isinstance(locations, list) or not locations:
|
||||
continue
|
||||
@@ -328,7 +391,6 @@ class ROROrganizationResolver:
|
||||
|
||||
city = coerce_str(details.get("name")) or None
|
||||
region = coerce_str(details.get("country_subdivision_name")) or None
|
||||
display_name = _organization_label(organization, ror_query)
|
||||
ror_id = coerce_str(organization.get("id"))
|
||||
geonames_id = location.get("geonames_id")
|
||||
source_note = (
|
||||
@@ -551,6 +613,9 @@ def _record_context(record: Any, metadata: dict[str, Any]) -> dict[str, Any]:
|
||||
"organization": coerce_str(metadata.get("organization")),
|
||||
"source_location": metadata.get("location"),
|
||||
"source_raw_country": metadata.get("raw_country"),
|
||||
"sources": metadata.get("sources") if isinstance(metadata.get("sources"), list) else [],
|
||||
"source_url": coerce_str(metadata.get("source_url") or metadata.get("detail_url")),
|
||||
"builds_upon": coerce_str(metadata.get("builds_upon")),
|
||||
}
|
||||
|
||||
|
||||
@@ -580,6 +645,9 @@ def _context_to_query(
|
||||
"organization": context.get("organization") or "",
|
||||
"source_location": context.get("source_location"),
|
||||
"source_raw_country": context.get("source_raw_country"),
|
||||
"sources": list(context.get("sources") or []),
|
||||
"source_url": context.get("source_url") or "",
|
||||
"builds_upon": context.get("builds_upon") or "",
|
||||
},
|
||||
)
|
||||
|
||||
@@ -656,6 +724,61 @@ def _compute_center_candidate_sort_key(candidate: LocationCandidate) -> tuple[in
|
||||
return (source_rank, precision_rank, -float(candidate.confidence or 0))
|
||||
|
||||
|
||||
class BuildsUponComputeCenterResolver:
|
||||
"""Inherit coordinates from a previously resolved parent cluster via `builds_upon`."""
|
||||
|
||||
name = "inherited"
|
||||
|
||||
def resolve(self, query: LocationQuery) -> ResolverOutput:
|
||||
extra = query.extra or {}
|
||||
parent_ref = coerce_str(extra.get("builds_upon"))
|
||||
if not parent_ref:
|
||||
return ResolverOutput()
|
||||
|
||||
parent_norm = normalize_text(parent_ref)
|
||||
candidates: list[LocationCandidate] = []
|
||||
seen_coords: set[tuple[str, str]] = set()
|
||||
for entry in COMPUTE_CENTER_LOCATION_CACHE.values():
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
prec = coerce_str(entry.get("precision"))
|
||||
if prec not in RENDERABLE_PRECISIONS:
|
||||
continue
|
||||
lat = parse_float(entry.get("latitude"))
|
||||
lon = parse_float(entry.get("longitude"))
|
||||
if lat in (None, 0.0) or lon in (None, 0.0):
|
||||
continue
|
||||
entry_id = normalize_text(entry.get("source_id"))
|
||||
entry_name = normalize_text(entry.get("name"))
|
||||
if parent_norm not in {entry_id, entry_name}:
|
||||
continue
|
||||
coord_key = (f"{lat:.4f}", f"{lon:.4f}")
|
||||
if coord_key in seen_coords:
|
||||
continue
|
||||
seen_coords.add(coord_key)
|
||||
candidates.append(
|
||||
LocationCandidate(
|
||||
latitude=lat,
|
||||
longitude=lon,
|
||||
display_name=coerce_str(entry.get("name")) or parent_ref,
|
||||
precision="site" if prec == "precise" else prec,
|
||||
confidence=0.82 if not entry.get("needs_confirmation") else 0.72,
|
||||
query=f"builds_upon:{parent_ref}",
|
||||
source=self.name,
|
||||
source_note=f"Inherited from parent cluster '{coerce_str(entry.get('name')) or parent_ref}' via builds_upon",
|
||||
matched_fields=("builds_upon",),
|
||||
needs_confirmation=True,
|
||||
city=coerce_str(entry.get("city")) or None,
|
||||
country=coerce_str(entry.get("country")) or query.country,
|
||||
matched_location_name=coerce_str(entry.get("name")) or parent_ref,
|
||||
)
|
||||
)
|
||||
return ResolverOutput(
|
||||
candidates=tuple(candidates),
|
||||
attempted_queries=(f"builds_upon:{parent_ref}",),
|
||||
)
|
||||
|
||||
|
||||
COMPUTE_CENTER_PIPELINE = LocationPipeline(
|
||||
[
|
||||
ComputeCenterSourceCoordinatesResolver(),
|
||||
@@ -673,6 +796,7 @@ COMPUTE_CENTER_COLLECTION_PIPELINE = LocationPipeline(
|
||||
[
|
||||
ComputeCenterSourceCoordinatesResolver(),
|
||||
VerifiedComputeSiteResolver(),
|
||||
BuildsUponComputeCenterResolver(),
|
||||
ROROrganizationResolver(),
|
||||
NominatimResolver(
|
||||
query_plan_builder=_compute_center_query_plan,
|
||||
@@ -871,12 +995,12 @@ def collect_location_candidates(
|
||||
country: str | None = None,
|
||||
organization: str | None = None,
|
||||
record_id: int | None = None,
|
||||
sources: list[str] | None = None,
|
||||
source_url: str | None = None,
|
||||
builds_upon: str | None = None,
|
||||
source_raw_country: str | None = None,
|
||||
) -> tuple[list[LocationCandidate], list[str]]:
|
||||
"""Run the full resolution chain and return ranked candidates with attempted queries.
|
||||
|
||||
The unused ``source`` / ``source_id`` / ``record_id`` arguments are kept
|
||||
for backward compatibility with the API handler that calls this function.
|
||||
"""
|
||||
"""Run the full resolution chain and return ranked candidates with attempted queries."""
|
||||
query = build_compute_center_location_query(
|
||||
name=name,
|
||||
source=source,
|
||||
@@ -886,6 +1010,10 @@ def collect_location_candidates(
|
||||
city=city,
|
||||
country=country,
|
||||
organization=organization,
|
||||
sources=sources,
|
||||
source_url=source_url,
|
||||
builds_upon=builds_upon,
|
||||
source_raw_country=source_raw_country,
|
||||
)
|
||||
return COMPUTE_CENTER_COLLECTION_PIPELINE.collect_candidates(query)
|
||||
|
||||
@@ -900,6 +1028,10 @@ def build_compute_center_location_query(
|
||||
city: str | None = None,
|
||||
country: str | None = None,
|
||||
organization: str | None = None,
|
||||
sources: list[str] | None = None,
|
||||
source_url: str | None = None,
|
||||
builds_upon: str | None = None,
|
||||
source_raw_country: str | None = None,
|
||||
) -> LocationQuery:
|
||||
name_value = coerce_str(name)
|
||||
context: dict[str, Any] = {
|
||||
@@ -912,6 +1044,10 @@ def build_compute_center_location_query(
|
||||
"site": coerce_str(site or organization),
|
||||
"operator": coerce_str(operator or organization),
|
||||
"organization": coerce_str(organization),
|
||||
"sources": [str(item).strip() for item in (sources or []) if item],
|
||||
"source_url": coerce_str(source_url),
|
||||
"builds_upon": coerce_str(builds_upon),
|
||||
"source_raw_country": coerce_str(source_raw_country),
|
||||
}
|
||||
return _context_to_query(context)
|
||||
|
||||
|
||||
@@ -59,6 +59,7 @@ DOCS_METADATA: tuple[DocsMetadata, ...] = (
|
||||
DocsMetadata("location-pipeline-development.md", "location-pipeline-development", "docs_developer", "Backend", 35, "通用位置估算管线开发说明", "Shared Location Resolution Pipeline Development Guide"),
|
||||
DocsMetadata("earth-news-live-streams-collector-format.md", "earth-news-live-streams-collector-format", "docs_developer", "Backend", 36, "新闻直播采集格式", "News Live Streams Collector Format"),
|
||||
DocsMetadata("docs-gatekeeper-development.md", "docs-gatekeeper-development", "docs_developer", "Backend", 37, "Docs Gatekeeper 开发说明", "Docs Gatekeeper Development Guide"),
|
||||
DocsMetadata("api-integration-guide.md", "api-integration-guide", "docs_developer", "Backend", 38, "API 接入与鉴权指南", "API Integration and Authentication Guide"),
|
||||
DocsMetadata("agents-aiprovider.md", "agents-aiprovider", "docs_developer", "Agents", 40, "AI Provider 指南", "AI Provider Guide"),
|
||||
DocsMetadata("ops-runbook.md", "ops-runbook", "docs_admin", "Ops", 49, "智能星球运维手册", "Intelligent Planet Ops Runbook"),
|
||||
DocsMetadata("ops-docker-compose-buildx-upgrade.md", "ops-docker-compose-buildx-upgrade", "docs_admin", "Ops", 50, "Docker + Compose + Buildx 升级", "Docker + Compose + Buildx Upgrade"),
|
||||
|
||||
@@ -5,7 +5,9 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
import time
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
from weakref import WeakKeyDictionary
|
||||
|
||||
import httpx
|
||||
|
||||
@@ -14,6 +16,9 @@ CATALOG_MAX_PAGES = 100
|
||||
CATALOG_PAGE_SIZE = 100
|
||||
CATALOG_REQUEST_ATTEMPTS = 2
|
||||
CATALOG_RETRY_DELAY_SECONDS = 0.2
|
||||
MODELS_DEV_CATALOG_URL = "https://models.dev/api.json"
|
||||
OPENROUTER_CATALOG_URL = "https://openrouter.ai/api/v1/models"
|
||||
AGGREGATOR_CACHE_TTL_SECONDS = 300
|
||||
SUPPORTED_PROVIDER_APIS = {
|
||||
"openai-completions",
|
||||
"openai-responses",
|
||||
@@ -24,6 +29,33 @@ OFFICIAL_PUBLIC_CATALOG_HOSTS: dict[str, frozenset[str]] = {
|
||||
"openrouter": frozenset({"openrouter.ai"}),
|
||||
"opencode-go": frozenset({"opencode.ai"}),
|
||||
}
|
||||
OFFICIAL_PROVIDER_HOSTS: dict[str, frozenset[str]] = {
|
||||
"minimax": frozenset({"api.minimaxi.com", "api.minimax.cn", "api.minimax.io"}),
|
||||
"openai": frozenset({"api.openai.com"}),
|
||||
"anthropic": frozenset({"api.anthropic.com"}),
|
||||
"deepseek": frozenset({"api.deepseek.com"}),
|
||||
"alibaba": frozenset({"dashscope.aliyuncs.com", "dashscope-intl.aliyuncs.com"}),
|
||||
"moonshotai": frozenset({"api.moonshot.ai", "api.moonshot.cn"}),
|
||||
"glm": frozenset({"open.bigmodel.cn", "api.z.ai"}),
|
||||
"meta": frozenset({"api.meta.ai", "api.llama.com"}),
|
||||
"gemini": frozenset({"generativelanguage.googleapis.com"}),
|
||||
"grok": frozenset({"api.x.ai"}),
|
||||
**OFFICIAL_PUBLIC_CATALOG_HOSTS,
|
||||
}
|
||||
AGGREGATOR_OPENROUTER_PREFIXES: dict[str, str] = {
|
||||
"minimax": "minimax/",
|
||||
"openai": "openai/",
|
||||
"anthropic": "anthropic/",
|
||||
"deepseek": "deepseek/",
|
||||
"alibaba": "qwen/",
|
||||
"moonshotai": "moonshotai/",
|
||||
"glm": "z-ai/",
|
||||
"meta": "meta-llama/",
|
||||
"gemini": "google/",
|
||||
"grok": "x-ai/",
|
||||
}
|
||||
_AGGREGATOR_CACHE: dict[str, tuple[float, object]] = {}
|
||||
_AGGREGATOR_LOOP_LOCKS: WeakKeyDictionary[asyncio.AbstractEventLoop, asyncio.Lock] = WeakKeyDictionary()
|
||||
|
||||
|
||||
class LLMProviderCatalogError(RuntimeError):
|
||||
@@ -46,6 +78,16 @@ def is_official_public_catalog(provider: str, base_url: str) -> bool:
|
||||
return host in OFFICIAL_PUBLIC_CATALOG_HOSTS.get(provider_key, frozenset())
|
||||
|
||||
|
||||
def is_official_provider_host(provider: str, base_url: str) -> bool:
|
||||
provider_key = provider.strip().lower()
|
||||
host = (urlsplit(base_url.strip()).hostname or "").lower()
|
||||
if not host:
|
||||
return False
|
||||
if host in OFFICIAL_PROVIDER_HOSTS.get(provider_key, frozenset()):
|
||||
return True
|
||||
return provider_key == "alibaba" and (host == "aliyuncs.com" or host.endswith(".aliyuncs.com"))
|
||||
|
||||
|
||||
def catalog_requires_api_key(provider: str, base_url: str, provider_api: str) -> bool:
|
||||
provider_key = provider.strip().lower()
|
||||
if provider_key == "ollama" or provider_api == "ollama-generate":
|
||||
@@ -53,6 +95,30 @@ def catalog_requires_api_key(provider: str, base_url: str, provider_api: str) ->
|
||||
return not is_official_public_catalog(provider_key, base_url)
|
||||
|
||||
|
||||
def catalog_supports_aggregator_fallback(
|
||||
provider: str, base_url: str, provider_api: str
|
||||
) -> bool:
|
||||
provider_key = provider.strip().lower()
|
||||
return (
|
||||
provider_key in AGGREGATOR_OPENROUTER_PREFIXES
|
||||
and provider_api in SUPPORTED_PROVIDER_APIS
|
||||
and provider_api != "ollama-generate"
|
||||
and is_official_provider_host(provider_key, base_url)
|
||||
)
|
||||
|
||||
|
||||
def can_refresh_catalog_without_api_key(
|
||||
provider: str, base_url: str, provider_api: str
|
||||
) -> bool:
|
||||
return not catalog_requires_api_key(
|
||||
provider, base_url, provider_api
|
||||
) or catalog_supports_aggregator_fallback(provider, base_url, provider_api)
|
||||
|
||||
|
||||
def clear_aggregator_catalog_cache() -> None:
|
||||
_AGGREGATOR_CACHE.clear()
|
||||
|
||||
|
||||
def model_catalog_url(provider: str, base_url: str, provider_api: str) -> str:
|
||||
parts = urlsplit(base_url.strip())
|
||||
if parts.scheme not in {"http", "https"} or not parts.hostname:
|
||||
@@ -106,11 +172,14 @@ def _model_rows(payload: object) -> tuple[list[dict[str, object]], dict[str, obj
|
||||
return rows, envelope
|
||||
|
||||
|
||||
def _model_id(row: dict[str, object]) -> str:
|
||||
def _model_id(row: dict[str, object], provider: str = "") -> str:
|
||||
value = row.get("id") or row.get("model") or row.get("name")
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise LLMProviderCatalogError("供应商返回了缺少 ID 的模型条目。")
|
||||
return value.strip()
|
||||
normalized = value.strip()
|
||||
if provider.strip().lower() == "gemini" and normalized.startswith("models/"):
|
||||
normalized = normalized.removeprefix("models/")
|
||||
return normalized
|
||||
|
||||
|
||||
def _model_date(row: dict[str, object]) -> float:
|
||||
@@ -183,7 +252,7 @@ async def fetch_model_catalog(
|
||||
rows, envelope = _model_rows(payload)
|
||||
previous_count = len(rows_by_id)
|
||||
for row in rows:
|
||||
rows_by_id[_model_id(row)] = row
|
||||
rows_by_id[_model_id(row, provider)] = row
|
||||
has_more = envelope.get("has_more") is True
|
||||
if native_dashscope:
|
||||
total = envelope.get("total")
|
||||
@@ -207,3 +276,200 @@ async def fetch_model_catalog(
|
||||
if len(rows_by_id) == previous_count:
|
||||
raise LLMProviderCatalogError("供应商模型目录分页没有进展。")
|
||||
raise LLMProviderCatalogError("供应商模型目录分页超过限制。")
|
||||
|
||||
|
||||
def _aggregator_lock() -> asyncio.Lock:
|
||||
loop = asyncio.get_running_loop()
|
||||
lock = _AGGREGATOR_LOOP_LOCKS.get(loop)
|
||||
if lock is None:
|
||||
lock = asyncio.Lock()
|
||||
_AGGREGATOR_LOOP_LOCKS[loop] = lock
|
||||
return lock
|
||||
|
||||
|
||||
async def _fetch_aggregator_json(url: str, timeout_seconds: int) -> object:
|
||||
now = time.monotonic()
|
||||
cached = _AGGREGATOR_CACHE.get(url)
|
||||
if cached is not None and cached[0] > now:
|
||||
return cached[1]
|
||||
async with _aggregator_lock():
|
||||
now = time.monotonic()
|
||||
cached = _AGGREGATOR_CACHE.get(url)
|
||||
if cached is not None and cached[0] > now:
|
||||
return cached[1]
|
||||
timeout = max(1, min(timeout_seconds, CATALOG_TIMEOUT_SECONDS))
|
||||
headers = {
|
||||
"User-Agent": "Planet/1.0",
|
||||
"Accept": "application/json",
|
||||
"Accept-Encoding": "gzip",
|
||||
}
|
||||
async with asyncio.timeout(timeout), httpx.AsyncClient(timeout=timeout) as client:
|
||||
payload = await _get_catalog_page(client, url, headers, {})
|
||||
_AGGREGATOR_CACHE[url] = (time.monotonic() + AGGREGATOR_CACHE_TTL_SECONDS, payload)
|
||||
return payload
|
||||
|
||||
|
||||
def _models_dev_candidate_keys(provider: str, base_url: str) -> tuple[str, ...]:
|
||||
provider_key = provider.strip().lower()
|
||||
host = (urlsplit(base_url.strip()).hostname or "").lower()
|
||||
if provider_key == "minimax":
|
||||
if host in {"api.minimaxi.com", "api.minimax.cn"}:
|
||||
return ("minimax-cn", "minimax")
|
||||
return ("minimax", "minimax-cn")
|
||||
if provider_key == "alibaba":
|
||||
if "intl" in host:
|
||||
return ("alibaba", "alibaba-cn")
|
||||
return ("alibaba-cn", "alibaba")
|
||||
if provider_key == "moonshotai":
|
||||
if host.endswith(".cn"):
|
||||
return ("moonshotai-cn", "moonshotai")
|
||||
return ("moonshotai", "moonshotai-cn")
|
||||
fixed: dict[str, tuple[str, ...]] = {
|
||||
"glm": ("zhipuai",),
|
||||
"meta": ("meta",),
|
||||
"gemini": ("google",),
|
||||
"grok": ("xai",),
|
||||
"openai": ("openai",),
|
||||
"anthropic": ("anthropic",),
|
||||
"deepseek": ("deepseek",),
|
||||
}
|
||||
return fixed.get(provider_key, (provider_key,))
|
||||
|
||||
|
||||
def _is_aggregator_chat_model(model_id: str, output_modalities: object = None) -> bool:
|
||||
"""Exclude embeddings, image/audio/video generators, and consumer chat aliases."""
|
||||
lower = model_id.strip().lower()
|
||||
if not lower:
|
||||
return False
|
||||
if isinstance(output_modalities, list) and output_modalities:
|
||||
mods = {str(item).strip().lower() for item in output_modalities if str(item).strip()}
|
||||
if "text" not in mods or (mods & {"image", "video", "audio"}):
|
||||
return False
|
||||
if "embedding" in lower:
|
||||
return False
|
||||
if lower.startswith(
|
||||
(
|
||||
"chatgpt-",
|
||||
"dall-e",
|
||||
"whisper",
|
||||
"tts-",
|
||||
"gpt-image",
|
||||
"gpt-audio",
|
||||
"gpt-realtime",
|
||||
"grok-imagine",
|
||||
"qwen-mt-",
|
||||
)
|
||||
):
|
||||
return False
|
||||
if lower == "gpt-chat-latest" or (lower.startswith("gpt-") and lower.endswith("-chat")):
|
||||
return False
|
||||
if any(token in lower for token in ("-image", "-tts", "-asr", "-live-", "-realtime", "-video")):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _is_general_aggregator_model(model_id: str) -> bool:
|
||||
"""Rank general-purpose flagship chat models ahead of vertical or experimental variants."""
|
||||
lower = model_id.strip().lower()
|
||||
if lower.startswith(("gpt-daybreak-", "deep-research-")):
|
||||
return False
|
||||
if lower.endswith(("-healthcare", "-legal", "-contributor", "-exp")):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _extract_models_dev_models(
|
||||
payload: object, provider: str, base_url: str
|
||||
) -> ModelCatalog | None:
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
for key in _models_dev_candidate_keys(provider, base_url):
|
||||
entry = payload.get(key)
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
raw_models = entry.get("models")
|
||||
if not isinstance(raw_models, dict):
|
||||
continue
|
||||
candidates: list[tuple[bool, bool, str, str]] = []
|
||||
for model_id, meta in raw_models.items():
|
||||
if not isinstance(model_id, str) or not model_id.strip() or not isinstance(meta, dict):
|
||||
continue
|
||||
modalities = meta.get("modalities")
|
||||
output_mods = modalities.get("output") if isinstance(modalities, dict) else None
|
||||
if not _is_aggregator_chat_model(model_id, output_mods):
|
||||
continue
|
||||
active = str(meta.get("status") or "").strip().lower() != "deprecated"
|
||||
release_date = str(meta.get("release_date") or "")
|
||||
candidates.append(
|
||||
(active, _is_general_aggregator_model(model_id), release_date, model_id.strip())
|
||||
)
|
||||
if candidates:
|
||||
candidates.sort(key=lambda item: (item[0], item[1], item[2], item[3]), reverse=True)
|
||||
return ModelCatalog(
|
||||
url=f"{MODELS_DEV_CATALOG_URL}#{key}",
|
||||
models=[item[3] for item in candidates],
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _extract_openrouter_models(payload: object, provider: str) -> ModelCatalog | None:
|
||||
provider_key = provider.strip().lower()
|
||||
prefix = AGGREGATOR_OPENROUTER_PREFIXES.get(provider_key, "")
|
||||
if not prefix:
|
||||
return None
|
||||
try:
|
||||
rows, _ = _model_rows(payload)
|
||||
except LLMProviderCatalogError:
|
||||
return None
|
||||
dated: list[tuple[bool, float, str]] = []
|
||||
seen: set[str] = set()
|
||||
for row in rows:
|
||||
raw_id = row.get("id")
|
||||
if not isinstance(raw_id, str) or not raw_id.startswith(prefix):
|
||||
continue
|
||||
model_id = raw_id[len(prefix) :].strip()
|
||||
if not model_id or ":" in model_id or model_id in seen:
|
||||
continue
|
||||
arch = row.get("architecture")
|
||||
output_mods = arch.get("output_modalities") if isinstance(arch, dict) else None
|
||||
if not _is_aggregator_chat_model(model_id, output_mods):
|
||||
continue
|
||||
seen.add(model_id)
|
||||
dated.append((_is_general_aggregator_model(model_id), _model_date(row), model_id))
|
||||
if not dated:
|
||||
return None
|
||||
dated.sort(key=lambda item: (item[0], item[1], item[2]), reverse=True)
|
||||
return ModelCatalog(
|
||||
url=f"{OPENROUTER_CATALOG_URL}#{provider_key}",
|
||||
models=[item[2] for item in dated],
|
||||
)
|
||||
|
||||
|
||||
async def fetch_aggregator_model_catalog(
|
||||
provider: str,
|
||||
base_url: str,
|
||||
provider_api: str,
|
||||
timeout_seconds: int = CATALOG_TIMEOUT_SECONDS,
|
||||
) -> ModelCatalog:
|
||||
"""Fetch public model catalog for a keyless official-host provider via aggregators."""
|
||||
model_catalog_url(provider, base_url, provider_api)
|
||||
if not catalog_supports_aggregator_fallback(provider, base_url, provider_api):
|
||||
raise LLMProviderCatalogConfigError("请先配置当前供应商的 API Key,再刷新模型列表。")
|
||||
|
||||
try:
|
||||
models_dev_payload = await _fetch_aggregator_json(MODELS_DEV_CATALOG_URL, timeout_seconds)
|
||||
catalog = _extract_models_dev_models(models_dev_payload, provider, base_url)
|
||||
if catalog is not None and catalog.models:
|
||||
return catalog
|
||||
except (httpx.HTTPError, TimeoutError, LLMProviderCatalogError, ValueError):
|
||||
pass
|
||||
|
||||
try:
|
||||
openrouter_payload = await _fetch_aggregator_json(OPENROUTER_CATALOG_URL, timeout_seconds)
|
||||
catalog = _extract_openrouter_models(openrouter_payload, provider)
|
||||
if catalog is not None and catalog.models:
|
||||
return catalog
|
||||
except (httpx.HTTPError, TimeoutError, LLMProviderCatalogError, ValueError):
|
||||
pass
|
||||
|
||||
raise LLMProviderCatalogError("公共聚合模型目录暂不可用,请稍后重试或配置 API Key。")
|
||||
@@ -2,10 +2,21 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from app.services.llm_model_catalog import fetch_model_catalog, is_official_public_catalog
|
||||
import httpx
|
||||
|
||||
from app.services.llm_model_catalog import (
|
||||
catalog_requires_api_key,
|
||||
catalog_supports_aggregator_fallback,
|
||||
fetch_aggregator_model_catalog,
|
||||
fetch_model_catalog,
|
||||
is_official_public_catalog,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
OPENCODE_GO_MODEL_PROVIDER_APIS = {
|
||||
"minimax-m3": "anthropic-messages",
|
||||
@@ -53,7 +64,13 @@ OPENCODE_GO_FALLBACK_MODELS = [
|
||||
OPENAI_MODEL_PROVIDER_APIS = {
|
||||
model: "openai-responses"
|
||||
for model in [
|
||||
"gpt-6.2-astra",
|
||||
"gpt-6.2-sol",
|
||||
"gpt-6.1-terra",
|
||||
"gpt-6.1-sol",
|
||||
"gpt-6-astra",
|
||||
"gpt-6-sol",
|
||||
"gpt-6-luna",
|
||||
"gpt-5.6-sol",
|
||||
"gpt-5.6-terra",
|
||||
"gpt-5.6-luna",
|
||||
@@ -88,8 +105,18 @@ FALLBACK_LLM_PROVIDER_PRESETS: dict[str, dict[str, Any]] = {
|
||||
"label": "OpenAI",
|
||||
"provider_api": "openai-responses",
|
||||
"base_url": "https://api.openai.com/v1",
|
||||
"model": "gpt-6-astra",
|
||||
"models": ["gpt-6-astra", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-4.1"],
|
||||
"model": "gpt-6.2-astra",
|
||||
"models": [
|
||||
"gpt-6.2-astra",
|
||||
"gpt-6.2-sol",
|
||||
"gpt-6.1-terra",
|
||||
"gpt-6.1-sol",
|
||||
"gpt-6-astra",
|
||||
"gpt-6-sol",
|
||||
"gpt-6-luna",
|
||||
"gpt-5.6-sol",
|
||||
"gpt-4.1",
|
||||
],
|
||||
"model_provider_apis": OPENAI_MODEL_PROVIDER_APIS,
|
||||
"api_key_env": "OPENAI_API_KEY",
|
||||
"source": "fallback",
|
||||
@@ -134,6 +161,53 @@ FALLBACK_LLM_PROVIDER_PRESETS: dict[str, dict[str, Any]] = {
|
||||
"api_key_env": "MOONSHOT_API_KEY",
|
||||
"source": "fallback",
|
||||
},
|
||||
"glm": {
|
||||
"provider": "glm",
|
||||
"label": "Zhipu AI / GLM (CN)",
|
||||
"provider_api": "openai-completions",
|
||||
"base_url": "https://open.bigmodel.cn/api/paas/v4",
|
||||
"model": "glm-5.3",
|
||||
"models": ["glm-5.3", "glm-5.3-flash", "glm-5.3-flashx", "glm-5.2", "glm-5.1", "glm-5"],
|
||||
"api_key_env": "ZHIPU_API_KEY",
|
||||
"source": "fallback",
|
||||
},
|
||||
"meta": {
|
||||
"provider": "meta",
|
||||
"label": "Meta AI",
|
||||
"provider_api": "openai-completions",
|
||||
"base_url": "https://api.meta.ai/v1",
|
||||
"model": "muse-ember-1.0",
|
||||
"models": ["muse-ember-1.0", "muse-wonder-1.0", "muse-spark-1.3", "muse-spark-1.2", "muse-spark-1.1"],
|
||||
"api_key_env": "META_MODEL_API_KEY",
|
||||
"source": "fallback",
|
||||
},
|
||||
"gemini": {
|
||||
"provider": "gemini",
|
||||
"label": "Google Gemini",
|
||||
"provider_api": "openai-completions",
|
||||
"base_url": "https://generativelanguage.googleapis.com/v1beta/openai",
|
||||
"model": "gemini-4-neon",
|
||||
"models": [
|
||||
"gemini-4-neon",
|
||||
"gemini-4-hydrogen",
|
||||
"gemini-4-carbon",
|
||||
"gemini-4-argon",
|
||||
"gemini-3.8-flash",
|
||||
"gemini-2.5-flash",
|
||||
],
|
||||
"api_key_env": "GEMINI_API_KEY",
|
||||
"source": "fallback",
|
||||
},
|
||||
"grok": {
|
||||
"provider": "grok",
|
||||
"label": "xAI Grok",
|
||||
"provider_api": "openai-completions",
|
||||
"base_url": "https://api.x.ai/v1",
|
||||
"model": "grok-4.7",
|
||||
"models": ["grok-4.7", "grok-4.6", "grok-4.5", "grok-4.3", "grok-4.20-0309-reasoning"],
|
||||
"api_key_env": "XAI_API_KEY",
|
||||
"source": "fallback",
|
||||
},
|
||||
"openrouter": {
|
||||
"provider": "openrouter",
|
||||
"label": "OpenRouter",
|
||||
@@ -192,6 +266,15 @@ def _opencode_go_model_provider_apis(model_ids: list[str]) -> dict[str, str]:
|
||||
}
|
||||
|
||||
|
||||
def _openai_model_provider_apis(model_ids: list[str]) -> dict[str, str]:
|
||||
mapping: dict[str, str] = {}
|
||||
for model_id in model_ids:
|
||||
lower = model_id.strip().lower()
|
||||
if model_id in OPENAI_MODEL_PROVIDER_APIS or lower.startswith(("gpt-6", "gpt-5", "o3", "o4")):
|
||||
mapping[model_id] = OPENAI_MODEL_PROVIDER_APIS.get(model_id, "openai-responses")
|
||||
return mapping
|
||||
|
||||
|
||||
async def refresh_llm_provider_preset(
|
||||
provider: str,
|
||||
api_key: str | None = None,
|
||||
@@ -203,24 +286,69 @@ async def refresh_llm_provider_preset(
|
||||
fallback = get_fallback_llm_provider_preset(provider)
|
||||
resolved_base_url = base_url or fallback["base_url"]
|
||||
resolved_api = provider_api or fallback["provider_api"]
|
||||
catalog = await fetch_model_catalog(
|
||||
fallback["provider"],
|
||||
resolved_base_url,
|
||||
resolved_api,
|
||||
api_key or "",
|
||||
anthropic_version,
|
||||
include_auth=not is_official_public_catalog(fallback["provider"], resolved_base_url),
|
||||
)
|
||||
model_provider_apis = (
|
||||
_opencode_go_model_provider_apis(catalog.models)
|
||||
if fallback["provider"] == "opencode-go"
|
||||
else fallback.get("model_provider_apis", {})
|
||||
resolved_api_key = (api_key or "").strip()
|
||||
supports_aggregator = catalog_supports_aggregator_fallback(
|
||||
fallback["provider"], resolved_base_url, resolved_api
|
||||
)
|
||||
if (
|
||||
fallback["provider"] == "openai"
|
||||
and urlsplit(resolved_base_url).hostname != "api.openai.com"
|
||||
not resolved_api_key
|
||||
and catalog_requires_api_key(fallback["provider"], resolved_base_url, resolved_api)
|
||||
and supports_aggregator
|
||||
):
|
||||
model_provider_apis = {}
|
||||
catalog = await fetch_aggregator_model_catalog(
|
||||
fallback["provider"],
|
||||
resolved_base_url,
|
||||
resolved_api,
|
||||
)
|
||||
else:
|
||||
try:
|
||||
catalog = await fetch_model_catalog(
|
||||
fallback["provider"],
|
||||
resolved_base_url,
|
||||
resolved_api,
|
||||
resolved_api_key,
|
||||
anthropic_version,
|
||||
include_auth=not is_official_public_catalog(
|
||||
fallback["provider"], resolved_base_url
|
||||
),
|
||||
)
|
||||
except (httpx.HTTPError, TimeoutError) as official_exc:
|
||||
if not resolved_api_key or not supports_aggregator:
|
||||
raise
|
||||
logger.warning(
|
||||
"Official LLM catalog request failed; falling back to public aggregator",
|
||||
extra={
|
||||
"event": "settings.ai_provider.catalog.official_fallback",
|
||||
"context": {
|
||||
"provider": fallback["provider"],
|
||||
"error_type": type(official_exc).__name__,
|
||||
"status_code": (
|
||||
official_exc.response.status_code
|
||||
if isinstance(official_exc, httpx.HTTPStatusError)
|
||||
else None
|
||||
),
|
||||
},
|
||||
},
|
||||
)
|
||||
try:
|
||||
catalog = await fetch_aggregator_model_catalog(
|
||||
fallback["provider"],
|
||||
resolved_base_url,
|
||||
resolved_api,
|
||||
)
|
||||
except Exception:
|
||||
# Preserve the original official error (e.g. 401 invalid API key) if public aggregators also fail.
|
||||
raise official_exc from None
|
||||
if fallback["provider"] == "opencode-go":
|
||||
model_provider_apis = _opencode_go_model_provider_apis(catalog.models)
|
||||
elif fallback["provider"] == "openai":
|
||||
model_provider_apis = (
|
||||
{}
|
||||
if urlsplit(resolved_base_url).hostname != "api.openai.com"
|
||||
else _openai_model_provider_apis(catalog.models)
|
||||
)
|
||||
else:
|
||||
model_provider_apis = fallback.get("model_provider_apis", {})
|
||||
return {
|
||||
**fallback,
|
||||
"base_url": resolved_base_url,
|
||||
|
||||
@@ -0,0 +1,664 @@
|
||||
"""Controlled multi-step Tool-Calling agent & L1 resolvers for unknown facility locations."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from datetime import UTC, datetime
|
||||
import json
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.models.compute_center_location import ComputeCenterLocationRecord
|
||||
from app.models.situational_assessment import WorkflowRun
|
||||
from app.schemas.ai import SituationalAnalysisRequest
|
||||
from app.services.ai.tool_registry import isolate_untrusted_external_text, safe_web_fetch
|
||||
from app.services.ai.workflow_registry import resolve_runtime_workflow_node
|
||||
from app.services.location.llm_fallback import (
|
||||
DEFAULT_MIN_CONFIDENCE,
|
||||
LocationLLMFallbackResult,
|
||||
collect_llm_location_fallback_candidate,
|
||||
)
|
||||
from app.services.location.models import LocationCandidate, LocationQuery
|
||||
from app.services.location.resolvers.nominatim import build_default_nominatim_geocoder
|
||||
from app.services.location.resolvers.peeringdb_facility import lookup_peeringdb_facility
|
||||
from app.services.location.resolvers.wikidata import lookup_wikidata_facility
|
||||
from app.services.location.text import coerce_str, normalize_country_text, normalize_text, parse_float
|
||||
|
||||
logger = get_logger(__name__, service="location_agent")
|
||||
|
||||
TERMINAL_UNLOCATABLE_STATUSES: frozenset[str] = frozenset({"undisclosed", "multi_site", "anonymous"})
|
||||
_agent_geocoder = build_default_nominatim_geocoder()
|
||||
|
||||
LOCATION_AGENT_TOOLS: list[dict[str, Any]] = [
|
||||
{
|
||||
"name": "fetch_source_url",
|
||||
"description": "Fetch and read a primary source webpage (especially Epoch Source 1..5 or TOP500 detail URL) cleanly with prompt-injection isolation.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"url": {"type": "string", "description": "Public http/https URL"}},
|
||||
"required": ["url"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "web_search",
|
||||
"description": "Search the web using concise English or local-language queries (do not chain long hardware suffixes).",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"query": {"type": "string", "description": "Concise search query"}},
|
||||
"required": ["query"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "geocode_verify",
|
||||
"description": "Verify a physical facility address or city via geocoder and receive a verified geocode_candidate_id with coordinates and country.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"place_query": {"type": "string", "description": "Address, campus, or city + country"},
|
||||
"country": {"type": "string", "description": "Expected country name"},
|
||||
},
|
||||
"required": ["place_query"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "submit_location_result",
|
||||
"description": "Finalize location verification using a geocode_candidate_id from geocode_verify, or report a terminal status (undisclosed/multi_site/anonymous/unresolved).",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": ["located", "undisclosed", "multi_site", "anonymous", "unresolved"],
|
||||
},
|
||||
"facility_name": {"type": "string"},
|
||||
"address": {"type": "string"},
|
||||
"city": {"type": "string"},
|
||||
"region": {"type": "string"},
|
||||
"country": {"type": "string"},
|
||||
"precision": {"type": "string", "enum": ["precise", "site", "city"]},
|
||||
"geocode_candidate_id": {"type": "string"},
|
||||
"citations": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "URLs directly observed in fetch_source_url or web_search outputs",
|
||||
},
|
||||
"confidence": {"type": "number"},
|
||||
"reasoning": {"type": "string"},
|
||||
},
|
||||
"required": ["status", "reasoning"],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
async def run_l1_structured_facility_resolvers(
|
||||
query: LocationQuery,
|
||||
*,
|
||||
db: AsyncSession | None = None,
|
||||
) -> tuple[list[LocationCandidate], list[str], bool]:
|
||||
"""Run async L1 Wikidata & PeeringDB lookups respecting `location.resolve_unknown` config."""
|
||||
l1_node = await resolve_runtime_workflow_node(db, "location.resolve_unknown", "l1_knowledge")
|
||||
params = (l1_node or {}).get("params") or {}
|
||||
enabled_tools = set((l1_node or {}).get("tools") or [])
|
||||
allow_low_short_circuit = bool(params.get("allow_low_confidence_short_circuit", False))
|
||||
|
||||
tasks = []
|
||||
if params.get("wikidata_enabled", True) and (not enabled_tools or "wikidata_lookup" in enabled_tools):
|
||||
tasks.append(lookup_wikidata_facility(query))
|
||||
if params.get("peeringdb_enabled", True) and (not enabled_tools or "peeringdb_fac_lookup" in enabled_tools):
|
||||
tasks.append(lookup_peeringdb_facility(query))
|
||||
|
||||
candidates: list[LocationCandidate] = []
|
||||
attempted: list[str] = []
|
||||
if tasks:
|
||||
results = await asyncio.gather(*tasks, return_exceptions=True)
|
||||
for out in results:
|
||||
if isinstance(out, Exception):
|
||||
continue
|
||||
attempted.extend(out.attempted_queries)
|
||||
candidates.extend(out.candidates)
|
||||
return candidates, attempted, allow_low_short_circuit
|
||||
|
||||
|
||||
async def _persist_terminal_location_status(
|
||||
db: AsyncSession | None,
|
||||
*,
|
||||
query: LocationQuery,
|
||||
terminal_status: str,
|
||||
reasoning: str,
|
||||
) -> None:
|
||||
if db is None or not hasattr(db, "execute"):
|
||||
return
|
||||
extra = query.extra or {}
|
||||
source = coerce_str(extra.get("source"))
|
||||
source_id = coerce_str(extra.get("source_id"))
|
||||
if not source or not source_id:
|
||||
return
|
||||
try:
|
||||
from app.services.compute_center_locations import refresh_compute_center_location_cache
|
||||
|
||||
existing = await db.scalar(
|
||||
select(ComputeCenterLocationRecord)
|
||||
.where(ComputeCenterLocationRecord.source == source)
|
||||
.where(ComputeCenterLocationRecord.source_id == source_id)
|
||||
)
|
||||
if existing is None:
|
||||
existing = ComputeCenterLocationRecord(
|
||||
source=source,
|
||||
source_id=source_id,
|
||||
name=query.name,
|
||||
operator=coerce_str(extra.get("operator")) or None,
|
||||
site=coerce_str(extra.get("site")) or None,
|
||||
city=query.city,
|
||||
country=query.country,
|
||||
latitude=None,
|
||||
longitude=None,
|
||||
precision="unknown",
|
||||
confidence=0.0,
|
||||
location_source=f"agent_terminal_{terminal_status}",
|
||||
source_note=reasoning[:500] or f"Marked {terminal_status} by location agent",
|
||||
needs_confirmation=False,
|
||||
verification_status=terminal_status,
|
||||
verified_at=datetime.now(UTC),
|
||||
)
|
||||
db.add(existing)
|
||||
else:
|
||||
existing.precision = "unknown"
|
||||
existing.latitude = None
|
||||
existing.longitude = None
|
||||
existing.verification_status = terminal_status
|
||||
existing.location_source = f"agent_terminal_{terminal_status}"
|
||||
existing.source_note = reasoning[:500] or existing.source_note
|
||||
existing.verified_at = datetime.now(UTC)
|
||||
await db.commit()
|
||||
await refresh_compute_center_location_cache(db)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to persist terminal unlocatable status",
|
||||
event="location.agent.persist_terminal_failed",
|
||||
context={"source_id": source_id, "status": terminal_status, "error": str(exc)},
|
||||
)
|
||||
|
||||
|
||||
async def _record_location_workflow_run(
|
||||
db: AsyncSession | None,
|
||||
*,
|
||||
question: str,
|
||||
status_value: str,
|
||||
tool_trace: list[str],
|
||||
steps_used: int,
|
||||
error_message: str = "",
|
||||
) -> None:
|
||||
if db is None or not hasattr(db, "add"):
|
||||
return
|
||||
try:
|
||||
db.add(
|
||||
WorkflowRun(
|
||||
id=f"run_{uuid4().hex[:16]}",
|
||||
workflow_id="location.resolve_unknown",
|
||||
status=status_value,
|
||||
access_tier="admin",
|
||||
actor_key="admin:collect-location",
|
||||
question=question[:500],
|
||||
tool_trace=tool_trace,
|
||||
budget_used={"steps": steps_used},
|
||||
error_message=error_message[:500],
|
||||
completed_at=datetime.now(UTC),
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
except Exception:
|
||||
try:
|
||||
await db.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
async def run_controlled_location_agent(
|
||||
*,
|
||||
provider_client: Any,
|
||||
web_search_client: Any | None,
|
||||
query: LocationQuery,
|
||||
entity_type: str = "compute_center",
|
||||
db: AsyncSession | None = None,
|
||||
attempted_queries: list[str] | None = None,
|
||||
) -> tuple[LocationLLMFallbackResult, str | None]:
|
||||
"""Run the 3-4 step Tool-Calling location agent and return `(result, terminal_status)`."""
|
||||
extra = query.extra or {}
|
||||
l2_node = await resolve_runtime_workflow_node(db, "location.resolve_unknown", "l2_agent_research")
|
||||
l3_node = await resolve_runtime_workflow_node(db, "location.resolve_unknown", "l3_geo_guardrail")
|
||||
if l2_node and not l2_node.get("enabled", True):
|
||||
return (
|
||||
LocationLLMFallbackResult(
|
||||
candidates=[],
|
||||
attempted_queries=list(attempted_queries or []),
|
||||
failure_reason="Location agent node is disabled by workflow configuration.",
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
max_steps = max(1, min(int((l2_node or {}).get("max_steps") or 4), 6))
|
||||
allowed_tool_names = set((l2_node or {}).get("tools") or [t["name"] for t in LOCATION_AGENT_TOOLS])
|
||||
min_confidence = float(((l3_node or {}).get("guardrails") or {}).get("min_confidence") or DEFAULT_MIN_CONFIDENCE)
|
||||
require_tool_urls = bool(((l3_node or {}).get("guardrails") or {}).get("require_tool_cited_urls", True))
|
||||
|
||||
active_tools = [t for t in LOCATION_AGENT_TOOLS if t["name"] in allowed_tool_names]
|
||||
if not any(t["name"] == "submit_location_result" for t in active_tools):
|
||||
active_tools.append(LOCATION_AGENT_TOOLS[-1])
|
||||
|
||||
observed_urls: set[str] = set()
|
||||
geocode_candidates: dict[str, dict[str, Any]] = {}
|
||||
tool_trace: list[str] = ["l0_normalize", "l1_knowledge"]
|
||||
agent_attempts: list[str] = []
|
||||
source_urls = [
|
||||
str(u).strip()
|
||||
for u in [*([extra.get("source_url")] if extra.get("source_url") else []), *(extra.get("sources") or [])]
|
||||
if str(u or "").strip().startswith(("http://", "https://"))
|
||||
]
|
||||
|
||||
system_prompt = (l2_node or {}).get("system_prompt") or (
|
||||
"你是算力与网络基础设施物理位置查证 Agent。严禁编造经纬度!"
|
||||
"1) 若存在 primary_source_urls,优先调用 fetch_source_url;"
|
||||
"2) 否则调用 web_search 查询物理地址;"
|
||||
"3) 将查到的物理地址/城市传入 geocode_verify 获取 candidate_id;"
|
||||
"4) 最后调用 submit_location_result 提交结果。"
|
||||
)
|
||||
user_objective = (l2_node or {}).get("prompt") or (
|
||||
f"请查证目标设施 {query.name or extra.get('source_id')} 的物理所在城市或园区。"
|
||||
)
|
||||
context_payload = {
|
||||
"name": query.name,
|
||||
"name_short": query.aliases[0] if query.aliases else query.name,
|
||||
"operator": extra.get("operator") or None,
|
||||
"site": extra.get("site") or None,
|
||||
"city": query.city,
|
||||
"country": query.country,
|
||||
"raw_country": extra.get("source_raw_country"),
|
||||
"primary_source_urls": source_urls[:5],
|
||||
}
|
||||
|
||||
messages: list[dict[str, Any]] = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": (
|
||||
f"{user_objective}\n\n目标上下文 JSON:\n"
|
||||
f"{json.dumps(context_payload, ensure_ascii=False)}"
|
||||
),
|
||||
}
|
||||
]
|
||||
submitted_payload: dict[str, Any] | None = None
|
||||
last_text_response = ""
|
||||
steps_taken = 0
|
||||
|
||||
for step in range(1, max_steps + 1):
|
||||
steps_taken = step
|
||||
req = SituationalAnalysisRequest(
|
||||
title=f"Location agent step {step}",
|
||||
objective=user_objective,
|
||||
system_prompt=system_prompt,
|
||||
context=context_payload,
|
||||
preferred_model=(l2_node or {}).get("model_override"),
|
||||
messages=messages,
|
||||
tools=active_tools,
|
||||
tool_choice="auto" if step < max_steps else {"type": "function", "name": "submit_location_result"},
|
||||
native_web_search=bool((l2_node or {}).get("native_web_search", False)),
|
||||
)
|
||||
try:
|
||||
resp = await provider_client.analyze(req)
|
||||
except Exception as exc:
|
||||
await _record_location_workflow_run(
|
||||
db,
|
||||
question=str(query.name or ""),
|
||||
status_value="failed",
|
||||
tool_trace=tool_trace,
|
||||
steps_used=steps_taken,
|
||||
error_message=str(exc),
|
||||
)
|
||||
return (
|
||||
LocationLLMFallbackResult(
|
||||
candidates=[],
|
||||
attempted_queries=[*(attempted_queries or []), *agent_attempts],
|
||||
failure_reason=f"Location agent failed: {exc}",
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
last_text_response = str(getattr(resp, "content", "") or "")
|
||||
tool_calls = list(getattr(resp, "tool_calls", None) or [])
|
||||
if not tool_calls:
|
||||
# Provider returned plain text (no tool calling support); break cleanly into deterministic fallback.
|
||||
break
|
||||
|
||||
messages.append(
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": last_text_response,
|
||||
"tool_calls": [
|
||||
{"id": tc.id, "name": tc.name, "arguments": tc.arguments}
|
||||
for tc in tool_calls
|
||||
],
|
||||
}
|
||||
)
|
||||
|
||||
for tc in tool_calls:
|
||||
raw_args = tc.arguments
|
||||
if isinstance(raw_args, str):
|
||||
try:
|
||||
raw_args = json.loads(raw_args)
|
||||
except json.JSONDecodeError:
|
||||
raw_args = {}
|
||||
args = raw_args if isinstance(raw_args, dict) else {}
|
||||
tool_trace.append(f"l2_agent_research:{tc.name}")
|
||||
if tc.name == "fetch_source_url":
|
||||
target_url = coerce_str(args.get("url"))
|
||||
agent_attempts.append(f"fetch_url:{target_url}")
|
||||
try:
|
||||
fetched = await asyncio.wait_for(safe_web_fetch(target_url, timeout_seconds=8), timeout=10.0)
|
||||
final_url = (
|
||||
coerce_str(fetched.get("final_url") or fetched.get("url"))
|
||||
if isinstance(fetched, dict)
|
||||
else coerce_str(getattr(fetched, "final_url", None) or getattr(fetched, "url", None))
|
||||
) or target_url
|
||||
title = fetched.get("title", "") if isinstance(fetched, dict) else getattr(fetched, "title", "")
|
||||
text = fetched.get("content", "") if isinstance(fetched, dict) else getattr(fetched, "text", "")
|
||||
observed_urls.add(target_url)
|
||||
observed_urls.add(final_url)
|
||||
tool_output = isolate_untrusted_external_text(final_url, title, text, max_chars=2400)
|
||||
except Exception as exc:
|
||||
tool_output = {"error": f"fetch failed: {exc}", "url": target_url}
|
||||
messages.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": tc.id,
|
||||
"name": tc.name,
|
||||
"content": json.dumps(tool_output, ensure_ascii=False),
|
||||
}
|
||||
)
|
||||
elif tc.name == "web_search":
|
||||
q_str = coerce_str(args.get("query"))
|
||||
agent_attempts.append(f"web_search:{q_str}")
|
||||
if web_search_client is None:
|
||||
tool_output = {"error": "WebSearch is not enabled or missing API key"}
|
||||
else:
|
||||
try:
|
||||
evidences = await web_search_client.search(q_str, max_results=5)
|
||||
items = []
|
||||
for ev in evidences:
|
||||
u = coerce_str(getattr(ev, "url", ""))
|
||||
if u:
|
||||
observed_urls.add(u)
|
||||
items.append(
|
||||
{
|
||||
"title": getattr(ev, "title", ""),
|
||||
"url": u,
|
||||
"snippet": getattr(ev, "snippet", "")[:400],
|
||||
}
|
||||
)
|
||||
tool_output = {"results": items}
|
||||
except Exception as exc:
|
||||
tool_output = {"error": str(exc)}
|
||||
messages.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": tc.id,
|
||||
"name": tc.name,
|
||||
"content": json.dumps(tool_output, ensure_ascii=False),
|
||||
}
|
||||
)
|
||||
elif tc.name == "geocode_verify":
|
||||
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}")
|
||||
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"))
|
||||
lon = parse_float(geo_res.get("lon") if geo_res.get("lon") is not None else geo_res.get("longitude"))
|
||||
addr = geo_res.get("address") if isinstance(geo_res.get("address"), dict) else {}
|
||||
res_country = normalize_country_text(addr.get("country") or geo_res.get("country"))
|
||||
if (
|
||||
lat in (None, 0.0)
|
||||
or lon in (None, 0.0)
|
||||
or not (-90.0 <= lat <= 90.0)
|
||||
or not (-180.0 <= lon <= 180.0)
|
||||
):
|
||||
tool_output = {"found": False, "reason": "Invalid geocoder coordinates"}
|
||||
elif expected_c and res_country and normalize_text(res_country) != normalize_text(expected_c):
|
||||
tool_output = {
|
||||
"found": False,
|
||||
"reason": f"Country mismatch: got {res_country}, expected {expected_c}",
|
||||
}
|
||||
else:
|
||||
cid = f"geo_{len(geocode_candidates) + 1}"
|
||||
geocode_candidates[cid] = {
|
||||
"latitude": lat,
|
||||
"longitude": lon,
|
||||
"display_name": coerce_str(geo_res.get("display_name")) or place_q,
|
||||
"city": coerce_str(
|
||||
addr.get("city")
|
||||
or addr.get("town")
|
||||
or addr.get("village")
|
||||
or addr.get("municipality")
|
||||
or geo_res.get("city")
|
||||
),
|
||||
"region": coerce_str(addr.get("state") or addr.get("region") or geo_res.get("region")),
|
||||
"country": res_country or expected_c or query.country,
|
||||
}
|
||||
tool_output = {"found": True, "geocode_candidate_id": cid, **geocode_candidates[cid]}
|
||||
messages.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": tc.id,
|
||||
"name": tc.name,
|
||||
"content": json.dumps(tool_output, ensure_ascii=False),
|
||||
}
|
||||
)
|
||||
elif tc.name == "submit_location_result":
|
||||
submitted_payload = dict(args)
|
||||
tool_trace.append("l3_geo_guardrail")
|
||||
messages.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": tc.id,
|
||||
"name": tc.name,
|
||||
"content": json.dumps({"accepted": True}),
|
||||
}
|
||||
)
|
||||
if submitted_payload is not None:
|
||||
break
|
||||
|
||||
if submitted_payload is None:
|
||||
# Fallback for providers/mocks without tool_calls support
|
||||
evidence_list = []
|
||||
if web_search_client is not None:
|
||||
from app.services.location.llm_fallback import collect_location_search_evidence
|
||||
|
||||
search_res = await collect_location_search_evidence(
|
||||
web_search_client=web_search_client,
|
||||
query=query,
|
||||
entity_type=entity_type,
|
||||
)
|
||||
agent_attempts.extend(search_res.attempted_queries)
|
||||
evidence_list = search_res.evidence
|
||||
if evidence_list or last_text_response:
|
||||
fallback_res = await collect_llm_location_fallback_candidate(
|
||||
provider_client=provider_client,
|
||||
query=query,
|
||||
entity_type=entity_type,
|
||||
db=db,
|
||||
attempted_queries=[*(attempted_queries or []), *agent_attempts],
|
||||
search_evidence=evidence_list,
|
||||
min_confidence=min_confidence,
|
||||
)
|
||||
await _record_location_workflow_run(
|
||||
db,
|
||||
question=str(query.name or ""),
|
||||
status_value="completed" if fallback_res.candidates else "failed",
|
||||
tool_trace=[*tool_trace, "llm_fallback"],
|
||||
steps_used=steps_taken,
|
||||
error_message=fallback_res.failure_reason or "",
|
||||
)
|
||||
return fallback_res, None
|
||||
await _record_location_workflow_run(
|
||||
db,
|
||||
question=str(query.name or ""),
|
||||
status_value="failed",
|
||||
tool_trace=tool_trace,
|
||||
steps_used=steps_taken,
|
||||
error_message="Agent did not submit location result",
|
||||
)
|
||||
return (
|
||||
LocationLLMFallbackResult(
|
||||
candidates=[],
|
||||
attempted_queries=[*(attempted_queries or []), *agent_attempts],
|
||||
failure_reason="Location agent reached step budget without submitting a verified location.",
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
sub_status = str(submitted_payload.get("status") or "unresolved").strip().lower()
|
||||
reasoning = coerce_str(submitted_payload.get("reasoning"))
|
||||
if sub_status in TERMINAL_UNLOCATABLE_STATUSES:
|
||||
await _persist_terminal_location_status(
|
||||
db,
|
||||
query=query,
|
||||
terminal_status=sub_status,
|
||||
reasoning=reasoning,
|
||||
)
|
||||
await _record_location_workflow_run(
|
||||
db,
|
||||
question=str(query.name or ""),
|
||||
status_value="completed",
|
||||
tool_trace=[*tool_trace, f"l4_persist_outcome:{sub_status}"],
|
||||
steps_used=steps_taken,
|
||||
)
|
||||
return (
|
||||
LocationLLMFallbackResult(
|
||||
candidates=[],
|
||||
attempted_queries=[*(attempted_queries or []), *agent_attempts],
|
||||
failure_reason=reasoning or f"Facility confirmed as {sub_status}.",
|
||||
),
|
||||
sub_status,
|
||||
)
|
||||
|
||||
geo_cid = coerce_str(submitted_payload.get("geocode_candidate_id"))
|
||||
geo_entry = geocode_candidates.get(geo_cid)
|
||||
if sub_status != "located" or geo_entry is None:
|
||||
reason = reasoning or "Submitted result missing verified geocode_candidate_id"
|
||||
await _record_location_workflow_run(
|
||||
db,
|
||||
question=str(query.name or ""),
|
||||
status_value="failed",
|
||||
tool_trace=tool_trace,
|
||||
steps_used=steps_taken,
|
||||
error_message=reason,
|
||||
)
|
||||
return (
|
||||
LocationLLMFallbackResult(
|
||||
candidates=[],
|
||||
attempted_queries=[*(attempted_queries or []), *agent_attempts],
|
||||
failure_reason=reason,
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
citations = [
|
||||
str(c).strip()
|
||||
for c in (submitted_payload.get("citations") or [])
|
||||
if str(c or "").strip()
|
||||
]
|
||||
verified_citations = [c for c in citations if c in observed_urls]
|
||||
if require_tool_urls and not verified_citations:
|
||||
reason = "No verified citation URLs observed in tool outputs"
|
||||
await _record_location_workflow_run(
|
||||
db,
|
||||
question=str(query.name or ""),
|
||||
status_value="failed",
|
||||
tool_trace=tool_trace,
|
||||
steps_used=steps_taken,
|
||||
error_message=reason,
|
||||
)
|
||||
return (
|
||||
LocationLLMFallbackResult(
|
||||
candidates=[],
|
||||
attempted_queries=[*(attempted_queries or []), *agent_attempts],
|
||||
failure_reason=reason,
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
expected_country = normalize_country_text(query.country)
|
||||
resolved_country = normalize_country_text(submitted_payload.get("country") or geo_entry.get("country"))
|
||||
if expected_country and resolved_country and normalize_text(resolved_country) != normalize_text(expected_country):
|
||||
reason = f"Country mismatch ({resolved_country} != {expected_country})"
|
||||
await _record_location_workflow_run(
|
||||
db,
|
||||
question=str(query.name or ""),
|
||||
status_value="failed",
|
||||
tool_trace=tool_trace,
|
||||
steps_used=steps_taken,
|
||||
error_message=reason,
|
||||
)
|
||||
return (
|
||||
LocationLLMFallbackResult(
|
||||
candidates=[],
|
||||
attempted_queries=[*(attempted_queries or []), *agent_attempts],
|
||||
failure_reason=reason,
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
confidence = min(max(parse_float(submitted_payload.get("confidence")) or 0.78, 0.0), 1.0)
|
||||
raw_precision = coerce_str(submitted_payload.get("precision")).lower()
|
||||
precision = raw_precision if raw_precision in {"precise", "site", "city"} else "city"
|
||||
facility_label = coerce_str(submitted_payload.get("facility_name")) or coerce_str(geo_entry.get("display_name")) or coerce_str(query.name)
|
||||
candidate = LocationCandidate(
|
||||
latitude=float(geo_entry["latitude"]),
|
||||
longitude=float(geo_entry["longitude"]),
|
||||
display_name=facility_label,
|
||||
precision=precision,
|
||||
confidence=max(confidence, min_confidence),
|
||||
query=f"location_agent:{entity_type}:{query.name or extra.get('source_id') or 'unknown'}",
|
||||
source="llm_location_factcheck",
|
||||
source_note=reasoning or f"Verified via tool-calling agent ({len(verified_citations)} citations)",
|
||||
matched_fields=("name", "tool_calling_agent"),
|
||||
needs_confirmation=True,
|
||||
city=coerce_str(submitted_payload.get("city")) or geo_entry.get("city") or query.city or None,
|
||||
region=coerce_str(submitted_payload.get("region")) or geo_entry.get("region") or query.region or None,
|
||||
country=resolved_country or expected_country or query.country,
|
||||
matched_location_name=facility_label,
|
||||
raw_payload={"citations": verified_citations or citations, "geocode_candidate_id": geo_cid},
|
||||
)
|
||||
await _record_location_workflow_run(
|
||||
db,
|
||||
question=str(query.name or ""),
|
||||
status_value="completed",
|
||||
tool_trace=[*tool_trace, "l4_persist_outcome:located"],
|
||||
steps_used=steps_taken,
|
||||
)
|
||||
return (
|
||||
LocationLLMFallbackResult(
|
||||
candidates=[candidate],
|
||||
attempted_queries=[*(attempted_queries or []), *agent_attempts],
|
||||
failure_reason=None,
|
||||
),
|
||||
None,
|
||||
)
|
||||
@@ -266,7 +266,14 @@ def _detect_country_in_text(text: str) -> str:
|
||||
variants = [canonical, *aliases]
|
||||
for variant in variants:
|
||||
normalized_variant = normalize_text(variant)
|
||||
if normalized_variant and normalized_variant in normalized_text:
|
||||
if not normalized_variant:
|
||||
continue
|
||||
if normalized_variant.isascii():
|
||||
if len(normalized_variant) < 4:
|
||||
continue
|
||||
if re.search(rf"\b{re.escape(normalized_variant)}\b", normalized_text):
|
||||
return canonical
|
||||
elif normalized_variant in normalized_text:
|
||||
return canonical
|
||||
return ""
|
||||
|
||||
@@ -488,6 +495,7 @@ def _fill_city_coordinates_from_geocoder(
|
||||
|
||||
if not geocode_queries:
|
||||
return payload, None
|
||||
expected_country = normalize_text(normalize_country_text(country or query.country))
|
||||
failures: list[str] = []
|
||||
geocode_query = ""
|
||||
result: dict[str, Any] | None = None
|
||||
@@ -503,9 +511,19 @@ def _fill_city_coordinates_from_geocoder(
|
||||
continue
|
||||
latitude = parse_float(maybe_result.get("lat"))
|
||||
longitude = parse_float(maybe_result.get("lon"))
|
||||
if latitude in (None, 0.0) or longitude in (None, 0.0):
|
||||
if (
|
||||
latitude in (None, 0.0)
|
||||
or longitude in (None, 0.0)
|
||||
or not (-90.0 <= latitude <= 90.0)
|
||||
or not (-180.0 <= longitude <= 180.0)
|
||||
):
|
||||
failures.append(f"{geocode_query}: invalid coordinates")
|
||||
continue
|
||||
cand_addr = maybe_result.get("address") if isinstance(maybe_result.get("address"), dict) else {}
|
||||
cand_country = normalize_text(normalize_country_text(cand_addr.get("country")))
|
||||
if expected_country and cand_country and cand_country != expected_country:
|
||||
failures.append(f"{geocode_query}: country mismatch ({cand_country} != {expected_country})")
|
||||
continue
|
||||
result = maybe_result
|
||||
break
|
||||
if result is None:
|
||||
@@ -514,7 +532,12 @@ def _fill_city_coordinates_from_geocoder(
|
||||
|
||||
latitude = parse_float(result.get("lat"))
|
||||
longitude = parse_float(result.get("lon"))
|
||||
if latitude in (None, 0.0) or longitude in (None, 0.0):
|
||||
if (
|
||||
latitude in (None, 0.0)
|
||||
or longitude in (None, 0.0)
|
||||
or not (-90.0 <= latitude <= 90.0)
|
||||
or not (-180.0 <= longitude <= 180.0)
|
||||
):
|
||||
return payload, f"city geocode fallback returned invalid coordinates for '{geocode_query}'"
|
||||
address = result.get("address") if isinstance(result.get("address"), dict) else {}
|
||||
city = (
|
||||
@@ -527,9 +550,11 @@ def _fill_city_coordinates_from_geocoder(
|
||||
)
|
||||
country = country or address.get("country")
|
||||
try:
|
||||
precision = _normalize_llm_precision(payload.get("precision")) or "city"
|
||||
raw_precision = _normalize_llm_precision(payload.get("precision")) or "city"
|
||||
except Exception:
|
||||
precision = "city"
|
||||
raw_precision = "city"
|
||||
# City-level geocoder fallback must never keep inflated site/precise claims.
|
||||
precision = "city" if raw_precision in {"precise", "site", "city"} else raw_precision
|
||||
filled = {
|
||||
**payload,
|
||||
"latitude": latitude,
|
||||
@@ -665,7 +690,15 @@ def _ambiguity_text(payload: dict[str, Any], evidence_items: list[dict[str, Any]
|
||||
def _conflict_penalty(payload: dict[str, Any], evidence_items: list[dict[str, Any]]) -> float:
|
||||
penalty = 0.0
|
||||
ambiguity_text = _ambiguity_text(payload, evidence_items)
|
||||
if any(token in ambiguity_text for token in ("conflict", "contradict", "inconsistent")):
|
||||
cleaned_text = re.sub(
|
||||
r"\b(?:no|without|not|zero)\s+(?:conflict|contradiction|ambiguity)s?\b|无冲突|未见矛盾",
|
||||
" ",
|
||||
ambiguity_text,
|
||||
)
|
||||
if any(
|
||||
token in cleaned_text
|
||||
for token in ("conflict", "contradict", "inconsistent", "冲突", "矛盾", "不一致")
|
||||
):
|
||||
penalty += 0.35
|
||||
if any(
|
||||
_truthy_evidence_field(item, "has_conflict", "conflicting")
|
||||
@@ -685,8 +718,12 @@ def _weak_evidence_penalty(
|
||||
conflict_penalty: float,
|
||||
) -> float:
|
||||
ambiguity_text = _ambiguity_text(payload, evidence_items)
|
||||
cleaned_text = re.sub(r"\b(?:no|without|not)\s+ambiguity\b|无歧义", " ", ambiguity_text)
|
||||
penalty = 0.0
|
||||
if any(token in ambiguity_text for token in ("ambiguous", "unclear", "weak", "guess")):
|
||||
if any(
|
||||
token in cleaned_text
|
||||
for token in ("ambiguous", "unclear", "weak", "guess", "存疑", "不确定", "猜测", "无法确认")
|
||||
):
|
||||
penalty += 0.20
|
||||
if any(_truthy_evidence_field(item, "ambiguous") for item in evidence_items):
|
||||
penalty += 0.15
|
||||
@@ -762,7 +799,12 @@ def _candidate_from_payload(
|
||||
min_confidence: float,
|
||||
) -> tuple[LocationCandidate | None, str | None]:
|
||||
latitude, longitude = _extract_llm_coordinates(payload)
|
||||
if latitude in (None, 0.0) or longitude in (None, 0.0):
|
||||
if (
|
||||
latitude in (None, 0.0)
|
||||
or longitude in (None, 0.0)
|
||||
or not (-90.0 <= latitude <= 90.0)
|
||||
or not (-180.0 <= longitude <= 180.0)
|
||||
):
|
||||
return None, "missing, invalid, or zero latitude/longitude"
|
||||
|
||||
precision = _normalize_llm_precision(payload.get("precision"))
|
||||
@@ -770,11 +812,11 @@ def _candidate_from_payload(
|
||||
return None, f"precision '{payload.get('precision')}' is not precise/site/city"
|
||||
|
||||
city = coerce_str(payload.get("city")) or query.city or None
|
||||
country = (
|
||||
normalize_country_text(payload.get("country"))
|
||||
or normalize_country_text(query.country)
|
||||
or query.country
|
||||
)
|
||||
payload_country = normalize_country_text(payload.get("country"))
|
||||
expected_country = normalize_country_text(query.country)
|
||||
if payload_country and expected_country and normalize_text(payload_country) != normalize_text(expected_country):
|
||||
return None, f"country '{payload_country}' contradicts expected '{expected_country}'"
|
||||
country = payload_country or expected_country or query.country
|
||||
evidence_score = _score_llm_location_payload(payload, query=query, precision=precision)
|
||||
if evidence_score.score < min_confidence:
|
||||
return None, (
|
||||
@@ -1230,20 +1272,25 @@ async def collect_llm_location_fallback_candidate(
|
||||
if search_evidence:
|
||||
payload["search_evidence"] = search_evidence
|
||||
existing_evidence = _evidence_items(payload.get("evidence"))
|
||||
payload["evidence"] = [
|
||||
*existing_evidence,
|
||||
*[
|
||||
{
|
||||
"source": item.get("title") or item.get("url"),
|
||||
"url": item.get("url"),
|
||||
"text": item.get("snippet") or item.get("content"),
|
||||
"source_type": "web_search",
|
||||
"entity_match": _search_evidence_entity_match(item, query),
|
||||
}
|
||||
for item in search_evidence
|
||||
if isinstance(item, dict)
|
||||
],
|
||||
]
|
||||
search_by_url = {
|
||||
str(item.get("url")).strip(): item
|
||||
for item in search_evidence
|
||||
if isinstance(item, dict) and item.get("url")
|
||||
}
|
||||
enriched_evidence = []
|
||||
for item in existing_evidence:
|
||||
url = coerce_str(item.get("url"))
|
||||
matched_search = search_by_url.get(url)
|
||||
if matched_search is not None:
|
||||
enriched_evidence.append(
|
||||
{
|
||||
**item,
|
||||
"entity_match": item.get("entity_match") or _search_evidence_entity_match(matched_search, query),
|
||||
}
|
||||
)
|
||||
else:
|
||||
enriched_evidence.append(item)
|
||||
payload["evidence"] = enriched_evidence
|
||||
latitude, longitude = _extract_llm_coordinates(payload)
|
||||
city_geocode_failure = None
|
||||
if latitude in (None, 0.0) or longitude in (None, 0.0):
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
"""PeeringDB Facility (/api/fac) resolver for commercial datacenter compute sites."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from ..models import LocationCandidate, LocationQuery, ResolverOutput
|
||||
from ..text import coerce_str, normalize_country_text, normalize_text, parse_float
|
||||
|
||||
PEERINGDB_FAC_URL = "https://www.peeringdb.com/api/fac"
|
||||
PEERINGDB_USER_AGENT = "Planet-Intelligence-System/1.0"
|
||||
PEERINGDB_TIMEOUT_SECONDS = 6.0
|
||||
|
||||
|
||||
async def lookup_peeringdb_facility(
|
||||
query: LocationQuery,
|
||||
*,
|
||||
timeout_seconds: float = PEERINGDB_TIMEOUT_SECONDS,
|
||||
) -> ResolverOutput:
|
||||
"""Query PeeringDB facilities matching the target site/operator/name."""
|
||||
extra = query.extra or {}
|
||||
search_terms: list[str] = []
|
||||
for raw in [
|
||||
extra.get("site"),
|
||||
extra.get("operator"),
|
||||
*(query.aliases or ()),
|
||||
query.name,
|
||||
]:
|
||||
cleaned = coerce_str(raw)
|
||||
if cleaned and len(cleaned) >= 3 and cleaned not in search_terms:
|
||||
search_terms.append(cleaned)
|
||||
if not search_terms:
|
||||
return ResolverOutput()
|
||||
|
||||
attempted: list[str] = []
|
||||
candidates: list[LocationCandidate] = []
|
||||
expected_country = normalize_text(normalize_country_text(query.country))
|
||||
headers = {"User-Agent": PEERINGDB_USER_AGENT, "Accept": "application/json"}
|
||||
api_key = os.environ.get("PEERINGDB_API_KEY", "").strip()
|
||||
|
||||
async with httpx.AsyncClient(timeout=timeout_seconds, headers=headers) as client:
|
||||
for term in search_terms[:2]:
|
||||
attempted.append(f"peeringdb_fac:{term}")
|
||||
params: dict[str, Any] = {"name__icontains": term, "limit": 4}
|
||||
if api_key:
|
||||
params["key"] = api_key
|
||||
try:
|
||||
resp = await client.get(PEERINGDB_FAC_URL, params=params)
|
||||
resp.raise_for_status()
|
||||
rows = (resp.json() or {}).get("data") or []
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
term_norm = normalize_text(term)
|
||||
for item in rows:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
lat = parse_float(item.get("latitude"))
|
||||
lon = parse_float(item.get("longitude"))
|
||||
if (
|
||||
lat in (None, 0.0)
|
||||
or lon in (None, 0.0)
|
||||
or not (-90.0 <= lat <= 90.0)
|
||||
or not (-180.0 <= lon <= 180.0)
|
||||
):
|
||||
continue
|
||||
item_country = normalize_country_text(item.get("country"))
|
||||
if expected_country and item_country and normalize_text(item_country) != expected_country:
|
||||
continue
|
||||
fac_name = coerce_str(item.get("name")) or term
|
||||
if term_norm and term_norm not in normalize_text(fac_name):
|
||||
# Require meaningful overlap when fuzzy matched
|
||||
fac_tokens = set(normalize_text(fac_name).split())
|
||||
if not (set(term_norm.split()) & fac_tokens):
|
||||
continue
|
||||
city = coerce_str(item.get("city")) or None
|
||||
addr = coerce_str(item.get("address1"))
|
||||
candidates.append(
|
||||
LocationCandidate(
|
||||
latitude=lat,
|
||||
longitude=lon,
|
||||
display_name=fac_name,
|
||||
precision="precise" if addr else "site",
|
||||
confidence=0.80,
|
||||
query=f"peeringdb_fac:{term}",
|
||||
source="peeringdb_facility",
|
||||
source_note=f"PeeringDB facility #{item.get('id')}: {fac_name}" + (f" ({addr})" if addr else ""),
|
||||
matched_fields=("site", "peeringdb"),
|
||||
needs_confirmation=True,
|
||||
city=city,
|
||||
region=coerce_str(item.get("state")) or None,
|
||||
country=item_country or query.country,
|
||||
matched_location_name=fac_name,
|
||||
raw_payload={"peeringdb_fac_id": item.get("id"), "address": addr},
|
||||
)
|
||||
)
|
||||
|
||||
return ResolverOutput(candidates=tuple(candidates), attempted_queries=tuple(attempted))
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Wikidata structured entity lookup for compute-center / facility coordinates (P625 / P276)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from ..models import LocationCandidate, LocationQuery, ResolverOutput
|
||||
from ..text import coerce_str, normalize_country_text, normalize_text, parse_float
|
||||
|
||||
WIKIDATA_API_URL = "https://www.wikidata.org/w/api.php"
|
||||
WIKIDATA_USER_AGENT = "planet-earth-location-resolver/1.0"
|
||||
WIKIDATA_TIMEOUT_SECONDS = 6.0
|
||||
|
||||
|
||||
async def lookup_wikidata_facility(
|
||||
query: LocationQuery,
|
||||
*,
|
||||
timeout_seconds: float = WIKIDATA_TIMEOUT_SECONDS,
|
||||
) -> ResolverOutput:
|
||||
"""Query Wikidata entities for facility-level P625 coordinate claims."""
|
||||
extra = query.extra or {}
|
||||
terms: list[str] = []
|
||||
for raw in [
|
||||
*(query.aliases or ()),
|
||||
query.name,
|
||||
extra.get("site"),
|
||||
]:
|
||||
cleaned = coerce_str(raw)
|
||||
if cleaned and cleaned not in terms:
|
||||
terms.append(cleaned)
|
||||
if not terms:
|
||||
return ResolverOutput()
|
||||
|
||||
attempted: list[str] = []
|
||||
candidates: list[LocationCandidate] = []
|
||||
seen_qids: set[str] = set()
|
||||
headers = {"User-Agent": WIKIDATA_USER_AGENT, "Accept": "application/json"}
|
||||
|
||||
async with httpx.AsyncClient(timeout=timeout_seconds, headers=headers) as client:
|
||||
for term in terms[:2]:
|
||||
attempted.append(f"wikidata:{term}")
|
||||
try:
|
||||
search_resp = await client.get(
|
||||
WIKIDATA_API_URL,
|
||||
params={
|
||||
"action": "wbsearchentities",
|
||||
"search": term,
|
||||
"language": "en",
|
||||
"format": "json",
|
||||
"limit": 4,
|
||||
},
|
||||
)
|
||||
search_resp.raise_for_status()
|
||||
search_items = (search_resp.json() or {}).get("search") or []
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
qids = [
|
||||
str(item.get("id"))
|
||||
for item in search_items
|
||||
if isinstance(item, dict) and item.get("id") and item.get("id") not in seen_qids
|
||||
]
|
||||
if not qids:
|
||||
continue
|
||||
seen_qids.update(qids)
|
||||
try:
|
||||
ent_resp = await client.get(
|
||||
WIKIDATA_API_URL,
|
||||
params={
|
||||
"action": "wbgetentities",
|
||||
"ids": "|".join(qids[:4]),
|
||||
"props": "labels|descriptions|claims",
|
||||
"languages": "en|zh",
|
||||
"format": "json",
|
||||
},
|
||||
)
|
||||
ent_resp.raise_for_status()
|
||||
entities = (ent_resp.json() or {}).get("entities") or {}
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
term_tokens = set(normalize_text(term).split())
|
||||
for qid, entity in entities.items():
|
||||
if not isinstance(entity, dict):
|
||||
continue
|
||||
labels = entity.get("labels") or {}
|
||||
label = coerce_str((labels.get("en") or {}).get("value") or (labels.get("zh") or {}).get("value"))
|
||||
desc = coerce_str(((entity.get("descriptions") or {}).get("en") or {}).get("value")).lower()
|
||||
if label:
|
||||
label_tokens = set(normalize_text(label).split())
|
||||
if term_tokens and not (term_tokens & label_tokens):
|
||||
continue
|
||||
if desc and not any(
|
||||
kw in desc
|
||||
for kw in ("supercomputer", "data center", "datacenter", "computer", "cluster", "laboratory", "facility", "campus")
|
||||
):
|
||||
continue
|
||||
|
||||
claims = entity.get("claims") or {}
|
||||
coord_claims = claims.get("P625") or []
|
||||
for claim in coord_claims:
|
||||
mainsnak = claim.get("mainsnak") if isinstance(claim, dict) else None
|
||||
datavalue = (mainsnak or {}).get("datavalue") or {}
|
||||
val = datavalue.get("value") if isinstance(datavalue, dict) else None
|
||||
if not isinstance(val, dict):
|
||||
continue
|
||||
lat = parse_float(val.get("latitude"))
|
||||
lon = parse_float(val.get("longitude"))
|
||||
if (
|
||||
lat in (None, 0.0)
|
||||
or lon in (None, 0.0)
|
||||
or not (-90.0 <= lat <= 90.0)
|
||||
or not (-180.0 <= lon <= 180.0)
|
||||
):
|
||||
continue
|
||||
country = normalize_country_text(query.country)
|
||||
candidates.append(
|
||||
LocationCandidate(
|
||||
latitude=lat,
|
||||
longitude=lon,
|
||||
display_name=label or term,
|
||||
precision="site",
|
||||
confidence=0.84,
|
||||
query=f"wikidata:{term}",
|
||||
source="wikidata_facility",
|
||||
source_note=f"Wikidata entity {qid} P625 coordinates ({desc or label})",
|
||||
matched_fields=("name", "wikidata"),
|
||||
needs_confirmation=True,
|
||||
city=query.city or None,
|
||||
country=country or query.country,
|
||||
matched_location_name=label or term,
|
||||
raw_payload={"wikidata_qid": qid, "description": desc},
|
||||
)
|
||||
)
|
||||
break
|
||||
|
||||
return ResolverOutput(candidates=tuple(candidates), attempted_queries=tuple(attempted))
|
||||
@@ -0,0 +1,697 @@
|
||||
"""Tests for Admin AI Advisor workflows, versioning, fixtures, optimization diff, and Playground SSE."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.ai_tasks.prompts import get_effective_prompt
|
||||
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.situational_assessment import WorkflowRun
|
||||
from app.models.system_setting import SystemSetting
|
||||
from app.services.ai.workflow_registry import (
|
||||
BUILTIN_WORKFLOWS,
|
||||
_LEGACY_BUILTIN_POSITIONS,
|
||||
ensure_builtin_workflows,
|
||||
)
|
||||
|
||||
|
||||
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__,
|
||||
],
|
||||
)
|
||||
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_ai_workflows_seed_draft_publish_rollback_and_fixtures(monkeypatch):
|
||||
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:
|
||||
list_resp = await client.get("/api/v1/ai/workflows")
|
||||
assert list_resp.status_code == 200
|
||||
body = list_resp.json()
|
||||
assert body["total"] == len(BUILTIN_WORKFLOWS)
|
||||
ids = {item["workflow_id"] for item in body["items"]}
|
||||
assert "default.general" in ids
|
||||
assert "location.resolve_unknown" in ids
|
||||
assert "earth.news.analysis" in ids
|
||||
assert any(item["is_default"] for item in body["items"])
|
||||
|
||||
detail_resp = await client.get("/api/v1/ai/workflows/earth.news.analysis")
|
||||
assert detail_resp.status_code == 200
|
||||
detail = detail_resp.json()
|
||||
assert len(detail["tool_catalog"]) >= 10
|
||||
graph = detail["workflow"]["published_graph"]
|
||||
target_node = next(n for n in graph["nodes"] if n.get("prompt_key") == "earth.news.analysis")
|
||||
target_node["system_prompt"] = "自定义新闻参谋系统提示词"
|
||||
target_node["tools"] = ["query_recent_earth_news", "invalid_unknown_tool"]
|
||||
|
||||
draft_resp = await client.put(
|
||||
"/api/v1/ai/workflows/earth.news.analysis/draft",
|
||||
json={"graph": graph},
|
||||
)
|
||||
assert draft_resp.status_code == 200
|
||||
draft_body = draft_resp.json()
|
||||
assert draft_body["has_draft"] is True
|
||||
draft_node = next(
|
||||
n for n in draft_body["draft_graph"]["nodes"] if n["id"] == target_node["id"]
|
||||
)
|
||||
# Invalid tool id must be stripped cleanly by whitelist validation
|
||||
assert draft_node["tools"] == ["query_recent_earth_news"]
|
||||
|
||||
pub_resp = await client.post(
|
||||
"/api/v1/ai/workflows/earth.news.analysis/publish",
|
||||
json={"change_summary": "Enable custom news system prompt"},
|
||||
)
|
||||
assert pub_resp.status_code == 200
|
||||
pub_body = pub_resp.json()
|
||||
assert pub_body["active_revision"] == 2
|
||||
assert pub_body["has_draft"] is False
|
||||
|
||||
# Runtime effective prompt must pick up the published workflow node prompt
|
||||
async with factory() as session:
|
||||
eff = await get_effective_prompt(session, "earth.news.analysis")
|
||||
assert eff.system_prompt == "自定义新闻参谋系统提示词"
|
||||
|
||||
# Rollback back to v1 -> creates v3 with v1 graph
|
||||
rb_resp = await client.post(
|
||||
"/api/v1/ai/workflows/earth.news.analysis/rollback",
|
||||
json={"revision": 1},
|
||||
)
|
||||
assert rb_resp.status_code == 200
|
||||
assert rb_resp.json()["active_revision"] == 3
|
||||
|
||||
# Explicit fixture create + delete
|
||||
fix_resp = await client.post(
|
||||
"/api/v1/ai/workflows/earth.news.analysis/fixtures",
|
||||
json={
|
||||
"name": "Red Sea Cable News Sample",
|
||||
"description": "Anonymized local Earth context export",
|
||||
"earth_context": {"schema": "planet.earth_context.v1", "selected": {"id": "news-1"}},
|
||||
"sample_question": "分析影响",
|
||||
},
|
||||
)
|
||||
assert fix_resp.status_code == 200
|
||||
fixture_id = fix_resp.json()["id"]
|
||||
del_resp = await client.delete(
|
||||
f"/api/v1/ai/workflows/earth.news.analysis/fixtures/{fixture_id}"
|
||||
)
|
||||
assert del_resp.status_code == 200
|
||||
assert del_resp.json()["deleted"] is True
|
||||
finally:
|
||||
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()
|
||||
|
||||
class _FakeAIClient:
|
||||
async def is_ready(self):
|
||||
return True, "openai", "gpt-test"
|
||||
|
||||
async def analyze(self, _req):
|
||||
return SimpleNamespace(
|
||||
content=json.dumps(
|
||||
{
|
||||
"summary": "Add fetch tool & block bad tool",
|
||||
"node_patches": [
|
||||
{
|
||||
"node_id": "l2_agent_research",
|
||||
"field": "tools",
|
||||
"after": ["fetch_source_url", "evil_rm_rf_tool"],
|
||||
"reason": "Keep only whitelisted tool",
|
||||
},
|
||||
{
|
||||
"node_id": "l2_agent_research",
|
||||
"field": "max_steps",
|
||||
"after": 5,
|
||||
"reason": "Allow 5 steps",
|
||||
},
|
||||
],
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
async def stream_analyze(self, _req, request_id=None):
|
||||
yield {"event": "reasoning", "delta": "Checking local earth context..."}
|
||||
yield {"event": "text", "delta": "已结合地球本地上下文完成分析。"}
|
||||
|
||||
from app.api.v1 import ai_workflows as ai_workflows_api
|
||||
|
||||
async def _fake_get_ai_client(_db):
|
||||
return _FakeAIClient()
|
||||
|
||||
monkeypatch.setattr(ai_workflows_api, "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:
|
||||
opt_resp = await client.post(
|
||||
"/api/v1/ai/workflows/location.resolve_unknown/optimize",
|
||||
json={"instruction": "允许抓取一手页面并屏蔽非法工具"},
|
||||
)
|
||||
assert opt_resp.status_code == 200
|
||||
opt_body = opt_resp.json()
|
||||
assert opt_body["base_revision"] == 1
|
||||
tools_patch = next(c for c in opt_body["changes"] if c["field"] == "tools")
|
||||
assert tools_patch["after"] == ["fetch_source_url"]
|
||||
assert "evil_rm_rf_tool" not in tools_patch["after"]
|
||||
|
||||
# Live workflow must remain untouched (no draft, revision=1) until admin clicks Apply
|
||||
detail = (await client.get("/api/v1/ai/workflows/location.resolve_unknown")).json()
|
||||
assert detail["workflow"]["has_draft"] is False
|
||||
assert detail["workflow"]["active_revision"] == 1
|
||||
|
||||
# Stream Playground chat with portable planet.earth_context.v1
|
||||
sse_resp = await client.post(
|
||||
"/api/v1/ai/playground/chat/stream",
|
||||
json={
|
||||
"workflow_id": "default.general",
|
||||
"message": "结合我刚导出的地球上下文说明重点风险",
|
||||
"earth_context": {
|
||||
"schema": "planet.earth_context.v1",
|
||||
"selected": {"type": "compute_center", "name": "Colossus"},
|
||||
},
|
||||
},
|
||||
)
|
||||
assert sse_resp.status_code == 200
|
||||
raw_sse = sse_resp.text
|
||||
assert "event: meta" in raw_sse
|
||||
assert "event: reasoning" in raw_sse
|
||||
assert "已结合地球本地上下文完成分析。" in raw_sse
|
||||
assert "event: done" in raw_sse
|
||||
|
||||
# WorkflowRun must be persisted cleanly in /runs
|
||||
runs_resp = await client.get("/api/v1/ai/runs?workflow_id=default.general")
|
||||
assert runs_resp.status_code == 200
|
||||
runs = runs_resp.json()["items"]
|
||||
assert len(runs) == 1
|
||||
assert runs[0]["status"] == "completed"
|
||||
assert runs[0]["input_params"]["has_earth_context"] is True
|
||||
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"
|
||||
@@ -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()
|
||||
@@ -0,0 +1,618 @@
|
||||
"""Tests for zero-login Earth sessions, permanent/scoped API keys, anti-scraping gate, and controlled OpenAPI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import hashlib
|
||||
import hmac
|
||||
import importlib.util
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
import pytest
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.pool import StaticPool
|
||||
from starlette.websockets import WebSocketDisconnect
|
||||
|
||||
from app import main as main_module
|
||||
from app.core import access_gate
|
||||
from app.core.access_gate import (
|
||||
EARTH_SESSION_COOKIE,
|
||||
EARTH_TOKEN_HEADER,
|
||||
reset_access_gate_caches,
|
||||
)
|
||||
from app.core.config import settings
|
||||
from app.core.security import create_access_token, get_password_hash
|
||||
from app.db.session import Base, get_db
|
||||
from app.main import app
|
||||
from app.models.api_key import ApiKey
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.system_setting import SystemSetting
|
||||
from app.models.user import User
|
||||
from app.services.api_keys import hash_api_key, reset_api_key_runtime_caches
|
||||
|
||||
|
||||
class _AsyncSQLiteSession:
|
||||
"""Minimal async wrapper around sync SQLAlchemy Session for fast isolated tests."""
|
||||
|
||||
def __init__(self, session: Session):
|
||||
self._session = session
|
||||
|
||||
def add(self, instance: Any) -> None:
|
||||
self._session.add(instance)
|
||||
|
||||
def add_all(self, instances: list[Any]) -> None:
|
||||
self._session.add_all(instances)
|
||||
|
||||
async def delete(self, instance: Any) -> None:
|
||||
self._session.delete(instance)
|
||||
|
||||
async def get(self, entity: Any, ident: Any) -> Any:
|
||||
return self._session.get(entity, ident)
|
||||
|
||||
async def execute(self, statement: Any, params: dict[str, Any] | None = None):
|
||||
if params is not None:
|
||||
return self._session.execute(statement, params)
|
||||
return self._session.execute(statement)
|
||||
|
||||
async def scalar(self, statement: Any):
|
||||
return self._session.scalar(statement)
|
||||
|
||||
async def scalars(self, statement: Any):
|
||||
return self._session.scalars(statement)
|
||||
|
||||
async def flush(self) -> None:
|
||||
self._session.flush()
|
||||
|
||||
async def commit(self) -> None:
|
||||
self._session.commit()
|
||||
|
||||
async def rollback(self) -> None:
|
||||
self._session.rollback()
|
||||
|
||||
async def refresh(self, instance: Any) -> None:
|
||||
self._session.refresh(instance)
|
||||
|
||||
|
||||
class _NoRedisClient:
|
||||
def sismember(self, *_args, **_kwargs):
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def get_client():
|
||||
raise RuntimeError("Redis disabled in unit test")
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_gate_and_redis(monkeypatch):
|
||||
reset_access_gate_caches()
|
||||
reset_api_key_runtime_caches()
|
||||
monkeypatch.setattr("app.core.security.redis_client", _NoRedisClient())
|
||||
monkeypatch.setattr("app.core.security._AsyncRedisClient", _NoRedisClient)
|
||||
monkeypatch.setattr("app.core.access_gate._AsyncRedisClient", _NoRedisClient)
|
||||
monkeypatch.setattr("app.services.api_keys._AsyncRedisClient", _NoRedisClient)
|
||||
yield
|
||||
app.dependency_overrides.clear()
|
||||
reset_access_gate_caches()
|
||||
reset_api_key_runtime_caches()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def access_db():
|
||||
engine = create_engine(
|
||||
"sqlite://",
|
||||
connect_args={"check_same_thread": False},
|
||||
poolclass=StaticPool,
|
||||
)
|
||||
Base.metadata.create_all(
|
||||
engine,
|
||||
tables=[
|
||||
User.__table__,
|
||||
ApiKey.__table__,
|
||||
SystemSetting.__table__,
|
||||
CollectedData.__table__,
|
||||
],
|
||||
)
|
||||
with Session(engine) as session:
|
||||
admin = User(
|
||||
id=1,
|
||||
username="admin-user",
|
||||
email="admin@example.invalid",
|
||||
password_hash=get_password_hash("AdminPass!123"),
|
||||
role="admin",
|
||||
is_active=True,
|
||||
email_verified=True,
|
||||
gatekeeper_groups=[],
|
||||
)
|
||||
viewer = User(
|
||||
id=2,
|
||||
username="plain-viewer",
|
||||
email="viewer@example.invalid",
|
||||
password_hash=get_password_hash("ViewerPass!123"),
|
||||
role="viewer",
|
||||
is_active=True,
|
||||
email_verified=True,
|
||||
gatekeeper_groups=[],
|
||||
)
|
||||
partner = User(
|
||||
id=3,
|
||||
username="partner-api",
|
||||
email="partner@example.invalid",
|
||||
password_hash=get_password_hash("PartnerPass!123"),
|
||||
role="viewer",
|
||||
is_active=True,
|
||||
email_verified=True,
|
||||
gatekeeper_groups=["api_access"],
|
||||
)
|
||||
docs_dev = User(
|
||||
id=4,
|
||||
username="docs-dev",
|
||||
email="docsdev@example.invalid",
|
||||
password_hash=get_password_hash("DocsDevPass!123"),
|
||||
role="viewer",
|
||||
is_active=True,
|
||||
email_verified=True,
|
||||
gatekeeper_groups=["docs_developer"],
|
||||
)
|
||||
session.add_all([admin, viewer, partner, docs_dev])
|
||||
session.commit()
|
||||
|
||||
async_session = _AsyncSQLiteSession(session)
|
||||
|
||||
async def _override_get_db():
|
||||
yield async_session
|
||||
|
||||
app.dependency_overrides[get_db] = _override_get_db
|
||||
yield async_session
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def _bearer_headers(user_id: int, username: str) -> dict[str, str]:
|
||||
token = create_access_token({"sub": str(user_id), "username": username})
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_enforce_mode_blocks_anonymous_endpoints_and_allows_public_exemptions(
|
||||
monkeypatch, access_db
|
||||
):
|
||||
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
|
||||
|
||||
class _ReadyDbContext:
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *args):
|
||||
return False
|
||||
|
||||
async def execute(self, *_args, **_kwargs):
|
||||
return None
|
||||
|
||||
class _ReadyRedis:
|
||||
class _Client:
|
||||
async def ping(self):
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def get_client():
|
||||
return _ReadyRedis._Client()
|
||||
|
||||
monkeypatch.setattr(main_module, "async_session_factory", lambda: _ReadyDbContext())
|
||||
monkeypatch.setattr(main_module, "_AsyncRedisClient", _ReadyRedis)
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
for protected_path in [
|
||||
"/api/v1/visualization/geo/summary",
|
||||
"/api/v1/layers/cables?bbox=-10,-10,10,10&zoom=5",
|
||||
"/api/v1/vessels/snapshot?bbox=-10,-10,10,10&zoom=5",
|
||||
"/api/v1/news/earth-feed",
|
||||
"/api/v1/data-products/compute/configuration",
|
||||
"/api/v1/earth/brand",
|
||||
"/api/v1/tv/streams",
|
||||
]:
|
||||
resp = await client.get(protected_path)
|
||||
assert resp.status_code == 401, f"{protected_path} returned {resp.status_code}"
|
||||
|
||||
assert (await client.get("/health")).status_code == 200
|
||||
assert (await client.get("/health/live")).status_code == 200
|
||||
health_resp = await client.get("/health/ready")
|
||||
assert health_resp.status_code == 200
|
||||
manifest_resp = await client.get("/api/v1/client/update-manifest")
|
||||
assert manifest_resp.status_code == 200
|
||||
docs_resp = await client.get("/api/v1/docs/catalog")
|
||||
assert docs_resp.status_code == 200
|
||||
|
||||
tc = TestClient(app)
|
||||
with pytest.raises(WebSocketDisconnect) as exc_info:
|
||||
with tc.websocket_connect("/ws"):
|
||||
pass
|
||||
assert exc_info.value.code == 4001
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_web_earth_session_zero_login_origin_cookie_ws_and_turnstile(
|
||||
monkeypatch, access_db
|
||||
):
|
||||
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
|
||||
monkeypatch.setattr(settings, "TURNSTILE_SECRET_KEY", "")
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
no_origin = await client.post("/api/v1/auth/earth-session", json={"client_type": "web"})
|
||||
assert no_origin.status_code == 403
|
||||
|
||||
cross_site = await client.post(
|
||||
"/api/v1/auth/earth-session",
|
||||
json={"client_type": "web"},
|
||||
headers={"Origin": "https://evil.example", "Sec-Fetch-Site": "cross-site"},
|
||||
)
|
||||
assert cross_site.status_code == 403
|
||||
|
||||
ok = await client.post(
|
||||
"/api/v1/auth/earth-session",
|
||||
json={"client_type": "web"},
|
||||
headers={"Origin": "http://test", "Sec-Fetch-Site": "same-origin"},
|
||||
)
|
||||
assert ok.status_code == 200
|
||||
body = ok.json()
|
||||
assert body["client_type"] == "web"
|
||||
assert body["ws_token"]
|
||||
assert body["turnstile_required"] is False
|
||||
set_cookie = ok.headers.get("set-cookie", "")
|
||||
assert EARTH_SESSION_COOKIE in set_cookie
|
||||
assert "HttpOnly" in set_cookie
|
||||
assert "samesite=strict" in set_cookie.lower()
|
||||
|
||||
authed_brand = await client.get("/api/v1/earth/brand")
|
||||
assert authed_brand.status_code == 200
|
||||
|
||||
tc = TestClient(app)
|
||||
with tc.websocket_connect(f"/ws?earth_token={body['ws_token']}") as ws:
|
||||
hello = ws.receive_json()
|
||||
assert hello["type"] == "connection_established"
|
||||
|
||||
monkeypatch.setattr(settings, "TURNSTILE_SECRET_KEY", "ts-secret")
|
||||
|
||||
class _MockTurnstileClient:
|
||||
def __init__(self, success: bool):
|
||||
self._success = success
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *args):
|
||||
return False
|
||||
|
||||
async def post(self, *_args, **_kwargs):
|
||||
class _Resp:
|
||||
def __init__(self, success_flag: bool):
|
||||
self._success_flag = success_flag
|
||||
|
||||
def raise_for_status(self):
|
||||
return None
|
||||
|
||||
def json(self):
|
||||
return {"success": self._success_flag}
|
||||
|
||||
return _Resp(self._success)
|
||||
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
missing_ts = await client.post(
|
||||
"/api/v1/auth/earth-session",
|
||||
json={"client_type": "web"},
|
||||
headers={"Origin": "http://test"},
|
||||
)
|
||||
assert missing_ts.status_code == 403
|
||||
|
||||
monkeypatch.setattr(
|
||||
access_gate.httpx,
|
||||
"AsyncClient",
|
||||
lambda **_kw: _MockTurnstileClient(False),
|
||||
)
|
||||
failed_ts = await client.post(
|
||||
"/api/v1/auth/earth-session",
|
||||
json={"client_type": "web", "turnstile_token": "bad-token"},
|
||||
headers={"Origin": "http://test"},
|
||||
)
|
||||
assert failed_ts.status_code == 403
|
||||
|
||||
monkeypatch.setattr(
|
||||
access_gate.httpx,
|
||||
"AsyncClient",
|
||||
lambda **_kw: _MockTurnstileClient(True),
|
||||
)
|
||||
ok_ts = await client.post(
|
||||
"/api/v1/auth/earth-session",
|
||||
json={"client_type": "web", "turnstile_token": "good-token"},
|
||||
headers={"Origin": "http://test"},
|
||||
)
|
||||
assert ok_ts.status_code == 200
|
||||
assert ok_ts.json()["turnstile_required"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_desktop_earth_handshake_hmac_replay_and_token_access(monkeypatch, access_db):
|
||||
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
|
||||
secret = "desktop-shared-hmac-secret"
|
||||
monkeypatch.setattr(settings, "EARTH_DESKTOP_HANDSHAKE_SECRET", secret)
|
||||
|
||||
client_header = "planet-earth-desktop/0.82.0"
|
||||
ts = str(int(time.time()))
|
||||
nonce = "nonce-unique-123"
|
||||
sig = hmac.new(
|
||||
secret.encode("utf-8"),
|
||||
f"{ts}.{nonce}.{client_header}".encode("utf-8"),
|
||||
hashlib.sha256,
|
||||
).hexdigest()
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
missing_hdr = await client.post("/api/v1/auth/earth-session", json={"client_type": "desktop"})
|
||||
assert missing_hdr.status_code == 403
|
||||
|
||||
bad_sig = await client.post(
|
||||
"/api/v1/auth/earth-session",
|
||||
json={"client_type": "desktop"},
|
||||
headers={
|
||||
"X-Planet-Client": client_header,
|
||||
"X-Planet-Client-Timestamp": ts,
|
||||
"X-Planet-Client-Nonce": nonce,
|
||||
"X-Planet-Client-Signature": "0" * 64,
|
||||
},
|
||||
)
|
||||
assert bad_sig.status_code == 403
|
||||
|
||||
ok = await client.post(
|
||||
"/api/v1/auth/earth-session",
|
||||
json={"client_type": "desktop"},
|
||||
headers={
|
||||
"X-Planet-Client": client_header,
|
||||
"X-Planet-Client-Timestamp": ts,
|
||||
"X-Planet-Client-Nonce": nonce,
|
||||
"X-Planet-Client-Signature": sig,
|
||||
},
|
||||
)
|
||||
assert ok.status_code == 200
|
||||
desktop_token = ok.json()["token"]
|
||||
|
||||
replay = await client.post(
|
||||
"/api/v1/auth/earth-session",
|
||||
json={"client_type": "desktop"},
|
||||
headers={
|
||||
"X-Planet-Client": client_header,
|
||||
"X-Planet-Client-Timestamp": ts,
|
||||
"X-Planet-Client-Nonce": nonce,
|
||||
"X-Planet-Client-Signature": sig,
|
||||
},
|
||||
)
|
||||
assert replay.status_code == 403
|
||||
|
||||
brand_resp = await client.get(
|
||||
"/api/v1/earth/brand",
|
||||
headers={EARTH_TOKEN_HEADER: desktop_token},
|
||||
)
|
||||
assert brand_resp.status_code == 200
|
||||
|
||||
tc = TestClient(app)
|
||||
with tc.websocket_connect("/ws", headers={EARTH_TOKEN_HEADER: desktop_token}) as ws:
|
||||
hello = ws.receive_json()
|
||||
assert hello["type"] == "connection_established"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_api_key_lifecycle_permanent_scopes_rate_limit_revocation_and_ws(
|
||||
monkeypatch, access_db
|
||||
):
|
||||
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
|
||||
admin_hdrs = _bearer_headers(1, "admin-user")
|
||||
viewer_hdrs = _bearer_headers(2, "plain-viewer")
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
denied_create = await client.post(
|
||||
"/api/v1/system/api-keys",
|
||||
json={"name": "unauthorized"},
|
||||
headers=viewer_hdrs,
|
||||
)
|
||||
assert denied_create.status_code == 403
|
||||
|
||||
created = await client.post(
|
||||
"/api/v1/system/api-keys",
|
||||
json={
|
||||
"name": "ue5-permanent",
|
||||
"scopes": ["earth:all_read"],
|
||||
"rate_limit_per_minute": None,
|
||||
"expires_in_days": None,
|
||||
},
|
||||
headers=admin_hdrs,
|
||||
)
|
||||
assert created.status_code == 201
|
||||
created_data = created.json()
|
||||
raw_perm_key = created_data["api_key"]
|
||||
perm_item = created_data["item"]
|
||||
assert raw_perm_key.startswith("plt_live_")
|
||||
assert perm_item["expires_at"] is None
|
||||
assert perm_item["rate_limit_per_minute"] is None
|
||||
|
||||
listing = await client.get("/api/v1/system/api-keys", headers=admin_hdrs)
|
||||
assert listing.status_code == 200
|
||||
listed_item = listing.json()["items"][0]
|
||||
assert listed_item["key_prefix"] == perm_item["key_prefix"]
|
||||
assert raw_perm_key not in listing.text
|
||||
|
||||
ok_http = await client.get("/api/v1/earth/brand", headers={"X-API-Key": raw_perm_key})
|
||||
assert ok_http.status_code == 200
|
||||
|
||||
ok_tv_query = await client.get(f"/api/v1/tv/streams?api_key={raw_perm_key}")
|
||||
# /tv/streams intentionally requires header X-API-Key (not query), whereas /tv/proxy allows query
|
||||
assert ok_tv_query.status_code == 401
|
||||
ok_tv_header = await client.get("/api/v1/tv/streams", headers={"X-API-Key": raw_perm_key})
|
||||
assert ok_tv_header.status_code == 200
|
||||
|
||||
tc = TestClient(app)
|
||||
with tc.websocket_connect(f"/ws?api_key={raw_perm_key}") as ws:
|
||||
hello = ws.receive_json()
|
||||
assert hello["type"] == "connection_established"
|
||||
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
scoped_created = await client.post(
|
||||
"/api/v1/system/api-keys",
|
||||
json={
|
||||
"name": "earth-only-limited",
|
||||
"scopes": ["earth:read"],
|
||||
"rate_limit_per_minute": 2,
|
||||
"expires_in_days": 30,
|
||||
},
|
||||
headers=admin_hdrs,
|
||||
)
|
||||
assert scoped_created.status_code == 201
|
||||
scoped_key = scoped_created.json()["api_key"]
|
||||
|
||||
assert (
|
||||
await client.get("/api/v1/earth/brand", headers={"X-API-Key": scoped_key})
|
||||
).status_code == 200
|
||||
assert (
|
||||
await client.get("/api/v1/earth/brand", headers={"X-API-Key": scoped_key})
|
||||
).status_code == 200
|
||||
assert (
|
||||
await client.get("/api/v1/earth/brand", headers={"X-API-Key": scoped_key})
|
||||
).status_code == 429
|
||||
|
||||
out_of_scope = await client.get(
|
||||
"/api/v1/layers/cables?bbox=-10,-10,10,10&zoom=5",
|
||||
headers={"X-API-Key": scoped_key},
|
||||
)
|
||||
assert out_of_scope.status_code == 403
|
||||
|
||||
revoked = await client.post(
|
||||
f"/api/v1/system/api-keys/{perm_item['id']}/revoke",
|
||||
headers=admin_hdrs,
|
||||
)
|
||||
assert revoked.status_code == 200
|
||||
assert revoked.json()["item"]["status"] == "revoked"
|
||||
assert (
|
||||
await client.get("/api/v1/earth/brand", headers={"X-API-Key": raw_perm_key})
|
||||
).status_code == 401
|
||||
|
||||
deleted = await client.delete(
|
||||
f"/api/v1/system/api-keys/{scoped_created.json()['item']['id']}",
|
||||
headers=admin_hdrs,
|
||||
)
|
||||
assert deleted.status_code == 200
|
||||
|
||||
expired_raw = "plt_live_expired_unit_test_key"
|
||||
expired_row = ApiKey(
|
||||
name="expired-key",
|
||||
key_prefix="plt_live_exp...",
|
||||
key_hash=hash_api_key(expired_raw),
|
||||
scopes=["earth:all_read"],
|
||||
is_active=True,
|
||||
expires_at=datetime.now(UTC) - timedelta(days=1),
|
||||
)
|
||||
access_db.add(expired_row)
|
||||
await access_db.commit()
|
||||
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
exp_resp = await client.get("/api/v1/earth/brand", headers={"X-API-Key": expired_raw})
|
||||
assert exp_resp.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_jwt_api_access_group_enforcement(monkeypatch, access_db):
|
||||
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
assert (
|
||||
await client.get(
|
||||
"/api/v1/earth/brand",
|
||||
headers=_bearer_headers(1, "admin-user"),
|
||||
)
|
||||
).status_code == 200
|
||||
assert (
|
||||
await client.get(
|
||||
"/api/v1/earth/brand",
|
||||
headers=_bearer_headers(3, "partner-api"),
|
||||
)
|
||||
).status_code == 200
|
||||
assert (
|
||||
await client.get(
|
||||
"/api/v1/earth/brand",
|
||||
headers=_bearer_headers(2, "plain-viewer"),
|
||||
)
|
||||
).status_code == 403
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_news_refresh_requires_auth_and_enforces_cooldown(monkeypatch, access_db):
|
||||
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
|
||||
from app.services import scheduler as scheduler_service
|
||||
|
||||
monkeypatch.setattr(
|
||||
scheduler_service,
|
||||
"request_earth_news_region_refresh",
|
||||
lambda region: {"refresh_id": "11111111111111111111111111111111", "region": region, "status": "queued"},
|
||||
)
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
anon = await client.post("/api/v1/news/refresh", json={"region": "global"})
|
||||
assert anon.status_code == 401
|
||||
|
||||
hdrs = _bearer_headers(3, "partner-api")
|
||||
for _ in range(3):
|
||||
ok = await client.post("/api/v1/news/refresh", json={"region": "global"}, headers=hdrs)
|
||||
assert ok.status_code == 202
|
||||
limited = await client.post("/api/v1/news/refresh", json={"region": "global"}, headers=hdrs)
|
||||
assert limited.status_code == 429
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_controlled_openapi_and_production_mode_defaults(monkeypatch, access_db):
|
||||
monkeypatch.setattr(settings, "APP_ENV", "production")
|
||||
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "")
|
||||
assert settings.effective_earth_api_auth_mode == "enforce"
|
||||
|
||||
spec = importlib.util.spec_from_file_location("app_main_prod_probe", main_module.__file__)
|
||||
assert spec is not None and spec.loader is not None
|
||||
prod_main = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(prod_main)
|
||||
assert prod_main.app.docs_url is None
|
||||
assert prod_main.app.redoc_url is None
|
||||
assert prod_main.app.openapi_url is None
|
||||
|
||||
monkeypatch.setattr(settings, "APP_ENV", "development")
|
||||
assert settings.effective_earth_api_auth_mode == "off"
|
||||
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
|
||||
assert settings.effective_earth_api_auth_mode == "enforce"
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
assert (await client.get("/api/v1/system/openapi.json")).status_code == 401
|
||||
assert (
|
||||
await client.get(
|
||||
"/api/v1/system/openapi.json",
|
||||
headers=_bearer_headers(2, "plain-viewer"),
|
||||
)
|
||||
).status_code == 403
|
||||
|
||||
full_resp = await client.get(
|
||||
"/api/v1/system/openapi.json",
|
||||
headers=_bearer_headers(4, "docs-dev"),
|
||||
)
|
||||
assert full_resp.status_code == 200
|
||||
assert "/api/v1/users" in full_resp.json()["paths"]
|
||||
|
||||
ext_resp = await client.get(
|
||||
"/api/v1/system/openapi-external.json",
|
||||
headers=_bearer_headers(1, "admin-user"),
|
||||
)
|
||||
assert ext_resp.status_code == 200
|
||||
ext = ext_resp.json()
|
||||
assert "ApiKeyAuth" in ext["components"]["securitySchemes"]
|
||||
assert "/api/v1/visualization/geo/summary" in ext["paths"]
|
||||
assert "/api/v1/users" not in ext["paths"]
|
||||
assert "/api/v1/settings/integrations" not in ext["paths"]
|
||||
@@ -9,6 +9,13 @@ from app.services import llm_provider_catalog as catalog
|
||||
REAL_CLIENT = httpx.AsyncClient
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_aggregator_cache():
|
||||
discovery.clear_aggregator_catalog_cache()
|
||||
yield
|
||||
discovery.clear_aggregator_catalog_cache()
|
||||
|
||||
|
||||
def mock_http(monkeypatch, handler):
|
||||
transport = httpx.MockTransport(handler)
|
||||
monkeypatch.setattr(
|
||||
@@ -26,6 +33,10 @@ def mock_http(monkeypatch, handler):
|
||||
("deepseek", "/v1/models", "authorization"),
|
||||
("alibaba", "/api/v1/models", "authorization"),
|
||||
("moonshotai", "/v1/models", "authorization"),
|
||||
("glm", "/api/paas/v4/models", "authorization"),
|
||||
("meta", "/v1/models", "authorization"),
|
||||
("gemini", "/v1beta/openai/models", "authorization"),
|
||||
("grok", "/v1/models", "authorization"),
|
||||
("openrouter", "/api/v1/models", None),
|
||||
("opencode-go", "/zen/go/v1/models", None),
|
||||
("ollama", "/api/tags", "authorization"),
|
||||
@@ -51,6 +62,8 @@ async def test_official_catalog_requests(monkeypatch, provider, path, auth):
|
||||
)
|
||||
if provider == "ollama":
|
||||
return httpx.Response(200, json={"models": [{"name": "latest:7b"}]})
|
||||
if provider == "gemini":
|
||||
return httpx.Response(200, json={"data": [{"id": "models/latest"}]})
|
||||
return httpx.Response(200, json={"data": [{"id": "latest"}]})
|
||||
|
||||
mock_http(monkeypatch, handle)
|
||||
@@ -220,7 +233,12 @@ async def test_retry_transient_error_only(monkeypatch):
|
||||
|
||||
mock_http(monkeypatch, unauthorized)
|
||||
with pytest.raises(httpx.HTTPStatusError) as error:
|
||||
await catalog.refresh_llm_provider_preset("minimax", "test-key")
|
||||
await discovery.fetch_model_catalog(
|
||||
"minimax",
|
||||
"https://api.minimaxi.com/anthropic",
|
||||
"anthropic-messages",
|
||||
"test-key",
|
||||
)
|
||||
assert len(calls) == 1
|
||||
assert "secret-upstream-text" not in discovery.catalog_error_message(error.value)
|
||||
|
||||
@@ -294,3 +312,225 @@ async def test_config_error_type_and_clean_upstream_error_messages(monkeypatch):
|
||||
await catalog.refresh_llm_provider_preset("openai", "test-key")
|
||||
assert not isinstance(exc.value, discovery.LLMProviderCatalogConfigError)
|
||||
assert "已保留上次模型列表" not in str(exc.value)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_keyless_official_providers_use_models_dev_cache_and_filter_non_text(monkeypatch):
|
||||
calls = []
|
||||
models_dev_payload = {
|
||||
"minimax-cn": {"models": {"MiniMax-M3.1-Flash": {"release_date": "2026-10-19", "modalities": {"output": ["text"]}}}},
|
||||
"openai": {"models": {"gpt-6.2-astra": {"release_date": "2026-11-17", "modalities": {"output": ["text"]}}}},
|
||||
"anthropic": {"models": {"claude-fable-5-2": {"release_date": "2026-11-09", "modalities": {"output": ["text"]}}}},
|
||||
"deepseek": {"models": {"deepseek-v4-pro": {"release_date": "2026-08-13", "modalities": {"output": ["text"]}}}},
|
||||
"alibaba-cn": {"models": {"qwen4-max": {"release_date": "2026-11-16", "modalities": {"output": ["text"]}}}},
|
||||
"moonshotai": {"models": {"kimi-k3.1-pro": {"release_date": "2026-10-23", "modalities": {"output": ["text"]}}}},
|
||||
"zhipuai": {"models": {"glm-5.3": {"release_date": "2026-08-14", "modalities": {"output": ["text"]}}}},
|
||||
"meta": {"models": {"muse-ember-1.0": {"release_date": "2026-11-09", "modalities": {"output": ["text"]}}}},
|
||||
"google": {"models": {"gemini-4-neon": {"release_date": "2026-11-18", "modalities": {"output": ["text"]}}}},
|
||||
"xai": {
|
||||
"models": {
|
||||
"grok-imagine-video": {"release_date": "2026-10-01", "modalities": {"output": ["video"]}},
|
||||
"grok-4.6": {"release_date": "2026-08-12", "modalities": {"output": ["text"]}},
|
||||
"grok-4.7": {"release_date": "2026-09-21", "modalities": {"output": ["text"]}},
|
||||
"grok-legacy": {"release_date": "2026-11-01", "status": "deprecated", "modalities": {"output": ["text"]}},
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
def handle(request):
|
||||
calls.append(str(request.url))
|
||||
assert str(request.url) == discovery.MODELS_DEV_CATALOG_URL
|
||||
return httpx.Response(200, json=models_dev_payload)
|
||||
|
||||
mock_http(monkeypatch, handle)
|
||||
expected = {
|
||||
"minimax": ["MiniMax-M3.1-Flash"],
|
||||
"openai": ["gpt-6.2-astra"],
|
||||
"anthropic": ["claude-fable-5-2"],
|
||||
"deepseek": ["deepseek-v4-pro"],
|
||||
"alibaba": ["qwen4-max"],
|
||||
"moonshotai": ["kimi-k3.1-pro"],
|
||||
"glm": ["glm-5.3"],
|
||||
"meta": ["muse-ember-1.0"],
|
||||
"gemini": ["gemini-4-neon"],
|
||||
"grok": ["grok-4.7", "grok-4.6", "grok-legacy"],
|
||||
}
|
||||
for provider, models in expected.items():
|
||||
result = await catalog.refresh_llm_provider_preset(provider)
|
||||
assert result["models"] == models
|
||||
assert result["source"].startswith(discovery.MODELS_DEV_CATALOG_URL)
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_keyless_aggregator_falls_back_to_openrouter_when_models_dev_fails(monkeypatch):
|
||||
seen_urls = []
|
||||
|
||||
def handle(request):
|
||||
seen_urls.append(str(request.url))
|
||||
if str(request.url) == discovery.MODELS_DEV_CATALOG_URL:
|
||||
return httpx.Response(503, text="models.dev down")
|
||||
if str(request.url) == discovery.OPENROUTER_CATALOG_URL:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"data": [
|
||||
{"id": "moonshotai/kimi-k3:batch", "created": 300},
|
||||
{"id": "moonshotai/kimi-k3.1-pro", "created": 200},
|
||||
{"id": "moonshotai/kimi-k3", "created": 100},
|
||||
{"id": "z-ai/glm-5.3", "created": 150},
|
||||
]
|
||||
},
|
||||
)
|
||||
pytest.fail(f"unexpected URL {request.url}")
|
||||
|
||||
mock_http(monkeypatch, handle)
|
||||
result = await catalog.refresh_llm_provider_preset("moonshotai")
|
||||
assert result["models"] == ["kimi-k3.1-pro", "kimi-k3"]
|
||||
assert result["source"] == f"{discovery.OPENROUTER_CATALOG_URL}#moonshotai"
|
||||
assert discovery.MODELS_DEV_CATALOG_URL in seen_urls
|
||||
assert discovery.OPENROUTER_CATALOG_URL in seen_urls
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_keyless_aggregator_fails_cleanly_and_official_vs_gateway_keyed_fallback(monkeypatch):
|
||||
mock_http(monkeypatch, lambda request: httpx.Response(503, text="secret-upstream-error"))
|
||||
with pytest.raises(discovery.LLMProviderCatalogError) as agg_exc:
|
||||
await catalog.refresh_llm_provider_preset("glm")
|
||||
assert not isinstance(agg_exc.value, discovery.LLMProviderCatalogConfigError)
|
||||
|
||||
# Keyed official host falling back to models.dev when official /models returns 401
|
||||
seen_hosts = []
|
||||
|
||||
def deepseek_401_then_aggregator(request):
|
||||
seen_hosts.append(request.url.host)
|
||||
if request.url.host == "api.deepseek.com":
|
||||
return httpx.Response(401, text="bad-key")
|
||||
if str(request.url) == discovery.MODELS_DEV_CATALOG_URL:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"deepseek": {
|
||||
"models": {
|
||||
"deepseek-chat": {"release_date": "2026-01-01"},
|
||||
"deepseek-v4-flash": {"release_date": "2026-10-17"},
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
pytest.fail(f"unexpected URL {request.url}")
|
||||
|
||||
mock_http(monkeypatch, deepseek_401_then_aggregator)
|
||||
ds_result = await catalog.refresh_llm_provider_preset("deepseek", api_key="stale-key")
|
||||
assert seen_hosts == ["api.deepseek.com", "models.dev"]
|
||||
assert ds_result["models"] == ["deepseek-v4-flash", "deepseek-chat"]
|
||||
assert ds_result["source"] == f"{discovery.MODELS_DEV_CATALOG_URL}#deepseek"
|
||||
|
||||
# Keyed official host where both aggregators also fail preserves original 401 HTTPStatusError
|
||||
seen_hosts.clear()
|
||||
discovery.clear_aggregator_catalog_cache()
|
||||
|
||||
def official_and_aggregators_fail(request):
|
||||
seen_hosts.append(request.url.host)
|
||||
if request.url.host == "api.moonshot.ai":
|
||||
return httpx.Response(401, text="bad-key")
|
||||
return httpx.Response(503, text="aggregator-down")
|
||||
|
||||
mock_http(monkeypatch, official_and_aggregators_fail)
|
||||
with pytest.raises(httpx.HTTPStatusError) as official_err:
|
||||
await catalog.refresh_llm_provider_preset("moonshotai", api_key="invalid-key")
|
||||
assert official_err.value.response.status_code == 401
|
||||
assert seen_hosts[0] == "api.moonshot.ai"
|
||||
|
||||
# Keyed custom gateway never falls back to public aggregators
|
||||
seen_hosts.clear()
|
||||
discovery.clear_aggregator_catalog_cache()
|
||||
|
||||
def custom_gateway_bad_key(request):
|
||||
seen_hosts.append(request.url.host)
|
||||
return httpx.Response(401, text="bad-gateway-key")
|
||||
|
||||
mock_http(monkeypatch, custom_gateway_bad_key)
|
||||
with pytest.raises(httpx.HTTPStatusError):
|
||||
await catalog.refresh_llm_provider_preset(
|
||||
"moonshotai",
|
||||
api_key="invalid-key",
|
||||
base_url="https://proxy.example.test/v1",
|
||||
)
|
||||
assert seen_hosts == ["proxy.example.test"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_openai_6_2_defaults_and_aggregator_chat_filtering_demotion(monkeypatch):
|
||||
preset = catalog.get_fallback_llm_provider_preset("openai")
|
||||
assert preset["model"] == "gpt-6.2-astra"
|
||||
assert {"gpt-6.2-astra", "gpt-6.2-sol"}.issubset(set(preset["models"]))
|
||||
assert preset["model_provider_apis"]["gpt-6.2-astra"] == "openai-responses"
|
||||
assert preset["model_provider_apis"]["gpt-6.2-sol"] == "openai-responses"
|
||||
|
||||
models_dev_payload = {
|
||||
"openai": {
|
||||
"models": {
|
||||
"gpt-6.2-sol-healthcare": {"release_date": "2026-11-24", "modalities": {"output": ["text"]}},
|
||||
"gpt-daybreak-red-latest": {"release_date": "2026-11-24", "modalities": {"output": ["text"]}},
|
||||
"gpt-6.2-sol": {"release_date": "2026-11-17", "modalities": {"output": ["text"]}},
|
||||
"gpt-6.2-astra": {"release_date": "2026-11-17", "modalities": {"output": ["text"]}},
|
||||
"gpt-chat-latest": {"release_date": "2026-11-20", "modalities": {"output": ["text"]}},
|
||||
"text-embedding-3-small": {"release_date": "2026-11-20", "modalities": {"output": ["text"]}},
|
||||
"chatgpt-image-latest": {"release_date": "2026-11-20", "modalities": {"output": ["text", "image"]}},
|
||||
"gpt-image-1.5": {"release_date": "2026-11-20", "modalities": {"output": ["text", "image"]}},
|
||||
"gpt-audio": {"release_date": "2026-11-20", "modalities": {"output": ["text", "audio"]}},
|
||||
}
|
||||
},
|
||||
"zhipuai": {
|
||||
"models": {
|
||||
"glm-5.3-flashx-legal": {"release_date": "2026-11-24", "modalities": {"output": ["text"]}},
|
||||
"glm-5.3": {"release_date": "2026-08-14", "modalities": {"output": ["text"]}},
|
||||
}
|
||||
},
|
||||
"deepseek": {
|
||||
"models": {
|
||||
"deepseek-v4-flash": {"release_date": "2026-10-17", "modalities": {"output": ["text"]}},
|
||||
"deepseek-chat": {"release_date": "2026-01-01", "modalities": {"output": ["text"]}},
|
||||
}
|
||||
},
|
||||
}
|
||||
mock_http(monkeypatch, lambda request: httpx.Response(200, json=models_dev_payload))
|
||||
|
||||
oai = await catalog.refresh_llm_provider_preset("openai")
|
||||
assert oai["models"] == [
|
||||
"gpt-6.2-sol",
|
||||
"gpt-6.2-astra",
|
||||
"gpt-daybreak-red-latest",
|
||||
"gpt-6.2-sol-healthcare",
|
||||
]
|
||||
assert oai["model"] == "gpt-6.2-sol"
|
||||
assert oai["model_provider_apis"]["gpt-6.2-sol"] == "openai-responses"
|
||||
assert oai["model_provider_apis"]["gpt-6.2-astra"] == "openai-responses"
|
||||
|
||||
glm = await catalog.refresh_llm_provider_preset("glm")
|
||||
assert glm["models"] == ["glm-5.3", "glm-5.3-flashx-legal"]
|
||||
assert glm["model"] == "glm-5.3"
|
||||
|
||||
ds = await catalog.refresh_llm_provider_preset("deepseek")
|
||||
assert ds["models"] == ["deepseek-v4-flash", "deepseek-chat"]
|
||||
|
||||
mock_http(
|
||||
monkeypatch,
|
||||
lambda request: httpx.Response(200, json={"data": [{"id": "gpt-6.2-astra"}, {"id": "gpt-6.2-sol"}]}),
|
||||
)
|
||||
gw = await catalog.refresh_llm_provider_preset(
|
||||
"openai",
|
||||
api_key="gw-key",
|
||||
base_url="https://gateway.test/v1",
|
||||
)
|
||||
assert gw["model_provider_apis"] == {}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_keyless_custom_gateway_still_requires_api_key(monkeypatch):
|
||||
mock_http(monkeypatch, lambda request: pytest.fail("must not call aggregator or proxy"))
|
||||
with pytest.raises(discovery.LLMProviderCatalogConfigError):
|
||||
await catalog.refresh_llm_provider_preset(
|
||||
"moonshotai", base_url="https://proxy.example.test/v1"
|
||||
)
|
||||
@@ -17,6 +17,13 @@ ADMIN_USER = SimpleNamespace(role="admin")
|
||||
VIEWER_USER = SimpleNamespace(role="viewer")
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_aggregator_cache():
|
||||
discovery.clear_aggregator_catalog_cache()
|
||||
yield
|
||||
discovery.clear_aggregator_catalog_cache()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def settings_db(monkeypatch, tmp_path):
|
||||
# Real SQL reads, commits and reloads; do not mock the settings helpers.
|
||||
@@ -46,7 +53,9 @@ def use_upstream(monkeypatch, handler):
|
||||
@pytest.mark.asyncio
|
||||
async def test_fresh_database_lists_all_builtin_presets(settings_db):
|
||||
result = await api.get_ai_provider_presets(current_user=None, db=settings_db)
|
||||
assert len(result["data"]) == 9
|
||||
assert len(result["data"]) == 13
|
||||
providers = {row["provider"] for row in result["data"]}
|
||||
assert {"moonshotai", "glm", "meta", "gemini", "grok"}.issubset(providers)
|
||||
assert all(row["models"] for row in result["data"])
|
||||
assert "MiniMax-M3" in result["data"][0]["models"]
|
||||
|
||||
@@ -125,12 +134,49 @@ async def test_missing_key_is_actionable_and_does_not_request_upstream(settings_
|
||||
pytest.fail("must not query a private catalog without credentials")
|
||||
|
||||
use_upstream(monkeypatch, fail_request)
|
||||
draft = api.AIProviderIntegrationUpdate(
|
||||
provider="minimax",
|
||||
base_url="https://proxy.example.test/anthropic",
|
||||
model="MiniMax-M3",
|
||||
)
|
||||
with pytest.raises(api.HTTPException) as error:
|
||||
await api.refresh_ai_provider_preset("minimax", ADMIN_USER, settings_db)
|
||||
await api.refresh_ai_provider_preset("minimax", ADMIN_USER, settings_db, draft)
|
||||
assert error.value.status_code == 400
|
||||
assert "API Key" in error.value.detail
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_missing_key_on_official_host_refreshes_via_aggregator(settings_db, monkeypatch):
|
||||
seen_urls = []
|
||||
models_dev_payload = {
|
||||
"moonshotai": {"models": {"kimi-k3.1-pro": {"release_date": "2026-10-23"}}},
|
||||
"zhipuai": {"models": {"glm-5.3": {"release_date": "2026-08-14"}}},
|
||||
"meta": {"models": {"muse-ember-1.0": {"release_date": "2026-11-09"}}},
|
||||
"google": {"models": {"gemini-4-neon": {"release_date": "2026-11-18"}}},
|
||||
"xai": {"models": {"grok-4.7": {"release_date": "2026-09-21"}}},
|
||||
}
|
||||
|
||||
def handle(request):
|
||||
seen_urls.append(str(request.url))
|
||||
assert str(request.url) == discovery.MODELS_DEV_CATALOG_URL
|
||||
return httpx.Response(200, json=models_dev_payload)
|
||||
|
||||
use_upstream(monkeypatch, handle)
|
||||
for provider_id, expected_model in (
|
||||
("moonshotai", "kimi-k3.1-pro"),
|
||||
("glm", "glm-5.3"),
|
||||
("meta", "muse-ember-1.0"),
|
||||
("gemini", "gemini-4-neon"),
|
||||
("grok", "grok-4.7"),
|
||||
):
|
||||
refreshed = await api.refresh_ai_provider_preset(provider_id, ADMIN_USER, settings_db)
|
||||
assert refreshed["data"]["models"] == [expected_model]
|
||||
assert refreshed["data"]["source"].startswith(discovery.MODELS_DEV_CATALOG_URL)
|
||||
stored = await api.get_setting_payload(settings_db, f"llm_provider_preset:{provider_id}")
|
||||
assert stored["models"] == [expected_model]
|
||||
assert seen_urls == [discovery.MODELS_DEV_CATALOG_URL]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_refresh_requires_admin_role(settings_db):
|
||||
with pytest.raises(api.HTTPException) as single_err:
|
||||
@@ -269,27 +315,115 @@ async def test_refresh_public_presets_updates_credential_free_and_isolates_failu
|
||||
)
|
||||
|
||||
seen_hosts = []
|
||||
models_dev_payload = {
|
||||
"minimax-cn": {"models": {"MiniMax-M3": {"release_date": "2026-06-01"}}},
|
||||
"openai": {"models": {"gpt-6.2-astra": {"release_date": "2026-11-17"}}},
|
||||
"anthropic": {"models": {"claude-fable-5-2": {"release_date": "2026-11-09"}}},
|
||||
"deepseek": {"models": {"deepseek-v4-pro": {"release_date": "2026-08-13"}}},
|
||||
"alibaba-cn": {"models": {"qwen4-max": {"release_date": "2026-11-16"}}},
|
||||
"moonshotai": {"models": {"kimi-k3.1-pro": {"release_date": "2026-10-23"}}},
|
||||
"zhipuai": {"models": {"glm-5.3": {"release_date": "2026-08-14"}}},
|
||||
"meta": {"models": {"muse-ember-1.0": {"release_date": "2026-11-09"}}},
|
||||
"google": {"models": {"gemini-4-neon": {"release_date": "2026-11-18"}}},
|
||||
"xai": {"models": {"grok-4.7": {"release_date": "2026-09-21"}}},
|
||||
}
|
||||
|
||||
def handle(request):
|
||||
seen_hosts.append(request.url.host)
|
||||
assert "authorization" not in request.headers
|
||||
if request.url.host == "models.dev":
|
||||
return httpx.Response(200, json=models_dev_payload)
|
||||
if request.url.host == "opencode.ai":
|
||||
return httpx.Response(200, json={"data": [{"id": "glm-5.3"}, {"id": "qwen4-max"}]})
|
||||
raise httpx.ConnectError("local ollama offline", request=request)
|
||||
|
||||
use_upstream(monkeypatch, handle)
|
||||
summary = await api.refresh_public_ai_provider_presets(ADMIN_USER, settings_db)
|
||||
assert seen_hosts == ["opencode.ai", "127.0.0.1", "127.0.0.1"]
|
||||
assert summary["refreshed"] == ["opencode-go"]
|
||||
assert seen_hosts.count("models.dev") == 1
|
||||
assert "opencode.ai" in seen_hosts
|
||||
assert "127.0.0.1" in seen_hosts
|
||||
assert "proxy.test" not in seen_hosts
|
||||
assert "opencode-go" in summary["refreshed"]
|
||||
assert "glm" in summary["refreshed"]
|
||||
assert "moonshotai" in summary["refreshed"]
|
||||
assert summary["failed"] == ["ollama"]
|
||||
assert (await api.get_setting_payload(settings_db, "llm_provider_preset:opencode-go"))[
|
||||
"models"
|
||||
] == ["glm-5.3", "qwen4-max"]
|
||||
assert (await api.get_setting_payload(settings_db, "llm_provider_preset:glm"))["models"] == [
|
||||
"glm-5.3"
|
||||
]
|
||||
assert (await api.get_setting_payload(settings_db, "llm_provider_preset:ollama"))[
|
||||
"models"
|
||||
] == ["kept-local-model"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_deepseek_stale_saved_key_refreshes_via_aggregator_but_connect_fails(
|
||||
settings_db, monkeypatch
|
||||
):
|
||||
await api.save_setting_payload(
|
||||
settings_db,
|
||||
"external_integrations",
|
||||
{
|
||||
"ai_provider": {
|
||||
"default_provider": "deepseek",
|
||||
"providers": {
|
||||
"deepseek": {
|
||||
"base_url": "https://api.deepseek.com/v1",
|
||||
"provider_api": "openai-completions",
|
||||
"model": "deepseek-chat",
|
||||
"api_key": "sk-stale-deepseek-key",
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
seen_hosts = []
|
||||
models_dev_payload = {
|
||||
"deepseek": {
|
||||
"models": {
|
||||
"deepseek-v4-flash": {"release_date": "2026-10-17", "modalities": {"output": ["text"]}},
|
||||
"deepseek-v4-pro": {"release_date": "2026-08-13", "modalities": {"output": ["text"]}},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def handle(request):
|
||||
seen_hosts.append(request.url.host)
|
||||
if request.url.host == "api.deepseek.com":
|
||||
return httpx.Response(401, text="secret-upstream-auth-error")
|
||||
if str(request.url) == discovery.MODELS_DEV_CATALOG_URL:
|
||||
return httpx.Response(200, json=models_dev_payload)
|
||||
pytest.fail(f"unexpected URL {request.url}")
|
||||
|
||||
use_upstream(monkeypatch, handle)
|
||||
refreshed = await api.refresh_ai_provider_preset("deepseek", ADMIN_USER, settings_db)
|
||||
assert seen_hosts == ["api.deepseek.com", "models.dev"]
|
||||
assert refreshed["data"]["models"] == ["deepseek-v4-flash", "deepseek-v4-pro"]
|
||||
assert refreshed["data"]["source"] == f"{discovery.MODELS_DEV_CATALOG_URL}#deepseek"
|
||||
assert "sk-stale-deepseek-key" not in str(refreshed)
|
||||
stored = await api.get_setting_payload(settings_db, "llm_provider_preset:deepseek")
|
||||
assert stored["models"] == ["deepseek-v4-flash", "deepseek-v4-pro"]
|
||||
|
||||
# Connectivity test with stale key must still fail strictly without hitting aggregator
|
||||
seen_hosts.clear()
|
||||
check = await api._check_ai_provider_lightweight(
|
||||
{
|
||||
"provider": "deepseek",
|
||||
"provider_api": "openai-completions",
|
||||
"base_url": "https://api.deepseek.com/v1",
|
||||
"model": "deepseek-v4-flash",
|
||||
"api_key": "sk-stale-deepseek-key",
|
||||
},
|
||||
5,
|
||||
)
|
||||
assert check["success"] is False
|
||||
assert check["connected"] is False
|
||||
assert seen_hosts == ["api.deepseek.com"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"preset", list_fallback_llm_provider_presets(), ids=lambda p: p["provider"]
|
||||
|
||||
@@ -0,0 +1,507 @@
|
||||
"""Tests for Wikidata/PeeringDB L1 resolvers and Tool-Calling Location Agent."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import ssl
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.db.session import Base
|
||||
from app.models.compute_center_location import ComputeCenterLocationRecord
|
||||
from app.models.situational_assessment import WorkflowRun
|
||||
from app.services.location.agent_resolver import run_controlled_location_agent
|
||||
from app.services.location.models import LocationQuery
|
||||
from app.services.location.resolvers.peeringdb_facility import lookup_peeringdb_facility
|
||||
from app.services.location.resolvers.wikidata import lookup_wikidata_facility
|
||||
|
||||
|
||||
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 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_sync_db():
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
Base.metadata.create_all(
|
||||
engine,
|
||||
tables=[ComputeCenterLocationRecord.__table__, WorkflowRun.__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_wikidata_and_peeringdb_resolvers_parse_coordinates(monkeypatch):
|
||||
class _FakeResponse:
|
||||
def __init__(self, payload):
|
||||
self._payload = payload
|
||||
|
||||
def raise_for_status(self):
|
||||
return None
|
||||
|
||||
def json(self):
|
||||
return self._payload
|
||||
|
||||
class _FakeAsyncClient:
|
||||
def __init__(self, **_kwargs):
|
||||
pass
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *_args):
|
||||
return False
|
||||
|
||||
async def get(self, url, params=None):
|
||||
if "wikidata.org" in url and (params or {}).get("action") == "wbsearchentities":
|
||||
return _FakeResponse({"search": [{"id": "Q123456"}]})
|
||||
if "wikidata.org" in url and (params or {}).get("action") == "wbgetentities":
|
||||
return _FakeResponse(
|
||||
{
|
||||
"entities": {
|
||||
"Q123456": {
|
||||
"labels": {"en": {"value": "Memphis Supercluster Facility"}},
|
||||
"descriptions": {"en": {"value": "data center campus in Memphis, Tennessee"}},
|
||||
"claims": {
|
||||
"P625": [
|
||||
{
|
||||
"mainsnak": {
|
||||
"datavalue": {
|
||||
"value": {"latitude": 35.0612, "longitude": -90.1511}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
if "peeringdb.com" in url:
|
||||
return _FakeResponse(
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": 9901,
|
||||
"name": "Equinix NY5 Secaucus",
|
||||
"city": "Secaucus",
|
||||
"state": "NJ",
|
||||
"country": "US",
|
||||
"address1": "800 Secaucus Rd",
|
||||
"latitude": 40.7831,
|
||||
"longitude": -74.0725,
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
return _FakeResponse({})
|
||||
|
||||
from app.services.location.resolvers import peeringdb_facility, wikidata
|
||||
|
||||
monkeypatch.setattr(wikidata.httpx, "AsyncClient", _FakeAsyncClient)
|
||||
monkeypatch.setattr(peeringdb_facility.httpx, "AsyncClient", _FakeAsyncClient)
|
||||
|
||||
wd_out = await lookup_wikidata_facility(
|
||||
LocationQuery(name="Memphis Supercluster Facility", country="United States")
|
||||
)
|
||||
assert len(wd_out.candidates) == 1
|
||||
assert wd_out.candidates[0].source == "wikidata_facility"
|
||||
assert wd_out.candidates[0].latitude == pytest.approx(35.0612, abs=1e-4)
|
||||
|
||||
pdb_out = await lookup_peeringdb_facility(
|
||||
LocationQuery(name="Equinix NY5 Secaucus", country="United States")
|
||||
)
|
||||
assert len(pdb_out.candidates) == 1
|
||||
assert pdb_out.candidates[0].source == "peeringdb_facility"
|
||||
assert pdb_out.candidates[0].precision == "precise"
|
||||
assert pdb_out.candidates[0].city == "Secaucus"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tool_calling_location_agent_loop_and_guardrails(monkeypatch):
|
||||
from app.services.location import agent_resolver
|
||||
|
||||
async def _fake_safe_fetch(url, **_kwargs):
|
||||
return {
|
||||
"url": url,
|
||||
"status_code": 200,
|
||||
"content": "The Colossus supercomputer operates at 5420 Tulane Rd, Memphis, TN, USA.",
|
||||
}
|
||||
|
||||
def _fake_geocode(place_query, country_hint=""):
|
||||
return {
|
||||
"latitude": 35.0612,
|
||||
"longitude": -90.1511,
|
||||
"display_name": "5420 Tulane Rd, Memphis, Shelby County, Tennessee, United States",
|
||||
"city": "Memphis",
|
||||
"region": "Tennessee",
|
||||
"country": "美国",
|
||||
"precision": "precise",
|
||||
}
|
||||
|
||||
monkeypatch.setattr(agent_resolver, "safe_web_fetch", _fake_safe_fetch)
|
||||
monkeypatch.setattr(agent_resolver, "_agent_geocoder", _fake_geocode)
|
||||
|
||||
class _StepProvider:
|
||||
def __init__(self):
|
||||
self.turn = 0
|
||||
|
||||
async def analyze(self, req):
|
||||
self.turn += 1
|
||||
if self.turn == 1:
|
||||
return SimpleNamespace(
|
||||
content="",
|
||||
tool_calls=[
|
||||
SimpleNamespace(
|
||||
id="call_1",
|
||||
name="fetch_source_url",
|
||||
arguments=json.dumps({"url": "https://epoch.ai/colossus-source"}),
|
||||
)
|
||||
],
|
||||
)
|
||||
if self.turn == 2:
|
||||
return SimpleNamespace(
|
||||
content="",
|
||||
tool_calls=[
|
||||
SimpleNamespace(
|
||||
id="call_2",
|
||||
name="geocode_verify",
|
||||
arguments=json.dumps({"place_query": "5420 Tulane Rd, Memphis, USA", "country": "United States"}),
|
||||
)
|
||||
],
|
||||
)
|
||||
return SimpleNamespace(
|
||||
content="",
|
||||
tool_calls=[
|
||||
SimpleNamespace(
|
||||
id="call_3",
|
||||
name="submit_location_result",
|
||||
arguments=json.dumps(
|
||||
{
|
||||
"status": "located",
|
||||
"facility_name": "Colossus Memphis Campus",
|
||||
"city": "Memphis",
|
||||
"region": "Tennessee",
|
||||
"country": "United States",
|
||||
"precision": "precise",
|
||||
"geocode_candidate_id": "geo_1",
|
||||
"citations": ["https://epoch.ai/colossus-source"],
|
||||
"confidence": 0.91,
|
||||
"reasoning": "Epoch source confirms 5420 Tulane Rd in Memphis.",
|
||||
}
|
||||
),
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
engine, factory = _make_sync_db()
|
||||
|
||||
try:
|
||||
async with factory() as session:
|
||||
result, term = await run_controlled_location_agent(
|
||||
provider_client=_StepProvider(),
|
||||
web_search_client=None,
|
||||
query=LocationQuery(
|
||||
name="Colossus",
|
||||
country="United States",
|
||||
extra={"source": "epoch_ai_gpu", "source_id": "epoch-colossus", "source_url": "https://epoch.ai/colossus-source"},
|
||||
),
|
||||
db=session,
|
||||
)
|
||||
assert term is None
|
||||
assert len(result.candidates) == 1
|
||||
cand = result.candidates[0]
|
||||
assert cand.precision == "precise"
|
||||
assert cand.city == "Memphis"
|
||||
assert cand.raw_payload["citations"] == ["https://epoch.ai/colossus-source"]
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tool_calling_agent_rejects_unobserved_citations_and_persists_terminal(monkeypatch):
|
||||
from app.services.location import agent_resolver
|
||||
|
||||
monkeypatch.setattr(agent_resolver, "_agent_geocoder", lambda _q, _c="": {
|
||||
"latitude": 35.0612,
|
||||
"longitude": -90.1511,
|
||||
"display_name": "Memphis, TN, USA",
|
||||
"city": "Memphis",
|
||||
"country": "美国",
|
||||
"precision": "city",
|
||||
})
|
||||
|
||||
class _FabricatedCitationProvider:
|
||||
def __init__(self):
|
||||
self.turn = 0
|
||||
|
||||
async def analyze(self, _req):
|
||||
self.turn += 1
|
||||
if self.turn == 1:
|
||||
return SimpleNamespace(
|
||||
content="",
|
||||
tool_calls=[
|
||||
SimpleNamespace(
|
||||
id="g1",
|
||||
name="geocode_verify",
|
||||
arguments=json.dumps({"place_query": "Memphis, USA", "country": "United States"}),
|
||||
)
|
||||
],
|
||||
)
|
||||
return SimpleNamespace(
|
||||
content="",
|
||||
tool_calls=[
|
||||
SimpleNamespace(
|
||||
id="s1",
|
||||
name="submit_location_result",
|
||||
arguments=json.dumps(
|
||||
{
|
||||
"status": "located",
|
||||
"geocode_candidate_id": "geo_1",
|
||||
"citations": ["https://madeup.example.com/fake-url"],
|
||||
"country": "United States",
|
||||
"reasoning": "Made up citation test",
|
||||
}
|
||||
),
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
res_bad, _ = await run_controlled_location_agent(
|
||||
provider_client=_FabricatedCitationProvider(),
|
||||
web_search_client=None,
|
||||
query=LocationQuery(name="FakeCitedCluster", country="United States"),
|
||||
)
|
||||
assert res_bad.candidates == []
|
||||
assert "No verified citation URLs" in (res_bad.failure_reason or "")
|
||||
|
||||
class _TerminalProvider:
|
||||
async def analyze(self, _req):
|
||||
return SimpleNamespace(
|
||||
content="",
|
||||
tool_calls=[
|
||||
SimpleNamespace(
|
||||
id="t1",
|
||||
name="submit_location_result",
|
||||
arguments=json.dumps(
|
||||
{
|
||||
"status": "undisclosed",
|
||||
"reasoning": "Customer confidential cluster location is undisclosed.",
|
||||
}
|
||||
),
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
engine, factory = _make_sync_db()
|
||||
|
||||
from app.services import compute_center_locations
|
||||
|
||||
monkeypatch.setattr(
|
||||
compute_center_locations,
|
||||
"refresh_compute_center_location_cache",
|
||||
lambda _db: _noop(),
|
||||
)
|
||||
|
||||
async def _noop():
|
||||
return None
|
||||
|
||||
try:
|
||||
async with factory() as session:
|
||||
res_term, term = await run_controlled_location_agent(
|
||||
provider_client=_TerminalProvider(),
|
||||
web_search_client=None,
|
||||
query=LocationQuery(
|
||||
name="Undisclosed Customer",
|
||||
extra={"source": "epoch_ai_gpu", "source_id": "epoch-undisclosed"},
|
||||
),
|
||||
db=session,
|
||||
)
|
||||
assert term == "undisclosed"
|
||||
assert res_term.candidates == []
|
||||
saved = await session.get(ComputeCenterLocationRecord, 1)
|
||||
assert saved is not None
|
||||
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
|
||||
@@ -346,3 +346,99 @@ def test_anthropic_request_omits_temperature_and_bumps_max_tokens_when_thinking_
|
||||
)
|
||||
assert disabled_body["temperature"] == 0.2
|
||||
assert disabled_body["thinking"] == {"type": "disabled"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_protocol_tools_structured_output_and_json_context(monkeypatch):
|
||||
service_openai = ProviderService(
|
||||
{
|
||||
"provider": "openai",
|
||||
"provider_api": "openai-completions",
|
||||
"base_url": "https://api.openai.test/v1",
|
||||
"api_key": "test-key",
|
||||
"model": "gpt-6-astra",
|
||||
}
|
||||
)
|
||||
tools_spec = [
|
||||
{
|
||||
"name": "web_search",
|
||||
"description": "Search web",
|
||||
"parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]},
|
||||
}
|
||||
]
|
||||
req = SituationalAnalysisRequest(
|
||||
title="locate",
|
||||
objective="find location",
|
||||
context={"country": "中国", "sources": ["https://example.invalid/a"]},
|
||||
tools=tools_spec,
|
||||
tool_choice="auto",
|
||||
response_format={"type": "json_schema", "json_schema": {"name": "loc", "schema": {"type": "object"}}},
|
||||
)
|
||||
prompt = service_openai._build_prompt(req)
|
||||
assert '"country": "中国"' in prompt
|
||||
|
||||
captured_openai = []
|
||||
|
||||
async def fake_post_openai(**kwargs):
|
||||
captured_openai.append(kwargs["request_body"])
|
||||
return {
|
||||
"choices": [
|
||||
{
|
||||
"finish_reason": "tool_calls",
|
||||
"message": {
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{"id": "call_1", "type": "function", "function": {"name": "web_search", "arguments": '{"query":"Frontier ORNL"}'}}
|
||||
],
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
monkeypatch.setattr(service_openai, "_post", fake_post_openai)
|
||||
resp = await service_openai.analyze(req)
|
||||
assert captured_openai[0]["tools"][0]["function"]["name"] == "web_search"
|
||||
assert captured_openai[0]["response_format"]["type"] == "json_schema"
|
||||
assert resp.stop_reason == "tool_calls"
|
||||
assert len(resp.tool_calls) == 1
|
||||
assert resp.tool_calls[0].name == "web_search"
|
||||
assert resp.tool_calls[0].arguments == {"query": "Frontier ORNL"}
|
||||
|
||||
service_anthropic = ProviderService(
|
||||
{
|
||||
"provider": "anthropic",
|
||||
"provider_api": "anthropic-messages",
|
||||
"base_url": "https://api.anthropic.test/v1",
|
||||
"api_key": "test-key",
|
||||
"model": "claude-sonnet",
|
||||
}
|
||||
)
|
||||
captured_anth = []
|
||||
|
||||
async def fake_post_anth(**kwargs):
|
||||
captured_anth.append(kwargs["request_body"])
|
||||
return {
|
||||
"stop_reason": "tool_use",
|
||||
"content": [
|
||||
{"type": "tool_use", "id": "tu_1", "name": "web_search", "input": {"query": "Oak Ridge"}}
|
||||
],
|
||||
}
|
||||
|
||||
monkeypatch.setattr(service_anthropic, "_post", fake_post_anth)
|
||||
anth_req = SituationalAnalysisRequest(
|
||||
title="locate",
|
||||
objective="continue",
|
||||
tools=tools_spec,
|
||||
native_web_search=True,
|
||||
messages=[
|
||||
{"role": "user", "content": "find Frontier"},
|
||||
{"role": "assistant", "content": "", "tool_calls": [{"id": "tu_0", "name": "web_search", "arguments": {"query": "Frontier"}}]},
|
||||
{"role": "tool", "tool_call_id": "tu_0", "content": '{"results": []}'},
|
||||
],
|
||||
)
|
||||
anth_resp = await service_anthropic.analyze(anth_req)
|
||||
assert any(t.get("type") == "web_search_20250305" for t in captured_anth[0]["tools"])
|
||||
assert captured_anth[0]["messages"][1]["content"][0]["type"] == "tool_use"
|
||||
assert captured_anth[0]["messages"][2]["content"][0]["type"] == "tool_result"
|
||||
assert anth_resp.tool_calls[0].id == "tu_1"
|
||||
assert anth_resp.tool_calls[0].arguments == {"query": "Oak Ridge"}
|
||||
@@ -37,6 +37,10 @@ def isolated_ai_provider_env_file(monkeypatch, tmp_path):
|
||||
"DEEPSEEK_API_KEY",
|
||||
"DASHSCOPE_API_KEY",
|
||||
"MOONSHOT_API_KEY",
|
||||
"ZHIPU_API_KEY",
|
||||
"META_MODEL_API_KEY",
|
||||
"GEMINI_API_KEY",
|
||||
"XAI_API_KEY",
|
||||
"OPENROUTER_API_KEY",
|
||||
"OPENCODE_GO_API_KEY",
|
||||
):
|
||||
@@ -115,6 +119,20 @@ def test_opencode_go_provider_preset_is_openai_compatible():
|
||||
assert preset["api_key_env"] == "OPENCODE_GO_API_KEY"
|
||||
|
||||
|
||||
def test_glm_meta_gemini_and_grok_default_presets():
|
||||
assert get_fallback_llm_provider_preset("glm")["base_url"] == "https://open.bigmodel.cn/api/paas/v4"
|
||||
assert get_fallback_llm_provider_preset("glm")["api_key_env"] == "ZHIPU_API_KEY"
|
||||
assert get_fallback_llm_provider_preset("meta")["base_url"] == "https://api.meta.ai/v1"
|
||||
assert get_fallback_llm_provider_preset("meta")["api_key_env"] == "META_MODEL_API_KEY"
|
||||
assert (
|
||||
get_fallback_llm_provider_preset("gemini")["base_url"]
|
||||
== "https://generativelanguage.googleapis.com/v1beta/openai"
|
||||
)
|
||||
assert get_fallback_llm_provider_preset("gemini")["api_key_env"] == "GEMINI_API_KEY"
|
||||
assert get_fallback_llm_provider_preset("grok")["base_url"] == "https://api.x.ai/v1"
|
||||
assert get_fallback_llm_provider_preset("grok")["api_key_env"] == "XAI_API_KEY"
|
||||
|
||||
|
||||
def test_mask_secret_without_prefix_is_fully_masked():
|
||||
assert _mask_secret("plainsecret")["preview"] == "***********"
|
||||
assert _mask_secret("sk-prefixed")["preview"] == "sk-********"
|
||||
|
||||
@@ -10,9 +10,19 @@ from app.api.v1.visualization import (
|
||||
convert_compute_centers_to_geojson,
|
||||
)
|
||||
import app.services.compute_center_locations as compute_center_locations
|
||||
from app.core.security import get_current_user
|
||||
from app.db.session import get_db
|
||||
from app.main import app
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.user import User
|
||||
|
||||
|
||||
def _override_admin_user() -> User:
|
||||
return User(id=1, username="test-admin", email="admin@example.invalid", role="admin", is_active=True)
|
||||
|
||||
|
||||
def _override_viewer_user() -> User:
|
||||
return User(id=2, username="test-viewer", email="viewer@example.invalid", role="viewer", is_active=True)
|
||||
|
||||
|
||||
def _build_record(
|
||||
@@ -1158,6 +1168,7 @@ async def test_collect_location_endpoint_returns_candidates_for_known_record(mon
|
||||
yield _FakeSession()
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
app.dependency_overrides[get_current_user] = _override_admin_user
|
||||
transport = ASGITransport(app=app)
|
||||
try:
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
@@ -1213,6 +1224,7 @@ async def test_collect_location_endpoint_returns_failure_reason(monkeypatch):
|
||||
yield _FakeSession()
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
app.dependency_overrides[get_current_user] = _override_admin_user
|
||||
transport = ASGITransport(app=app)
|
||||
try:
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
@@ -1292,6 +1304,7 @@ async def test_save_location_endpoint_upserts_and_geojson_can_render():
|
||||
yield fake_session
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
app.dependency_overrides[get_current_user] = _override_admin_user
|
||||
transport = ASGITransport(app=app)
|
||||
try:
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
@@ -1411,3 +1424,51 @@ def test_infrastructure_type_is_preserved_in_geojson_and_image_classification(ki
|
||||
record.extra_data = {**record.extra_data, "site_type": kind, "location": "Tokyo, Japan"}
|
||||
assert compute_site_type(record) == kind
|
||||
assert convert_compute_centers_to_geojson([record])["features"][0]["properties"]["site_type"] == kind
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_compute_center_location_write_endpoints_require_admin():
|
||||
collect_payload = {
|
||||
"name": "Frontier",
|
||||
"operator": "Oak Ridge National Laboratory",
|
||||
"country": "United States",
|
||||
}
|
||||
save_payload = {
|
||||
"source": "epoch_ai_gpu",
|
||||
"name": "Saved Cluster",
|
||||
"latitude": 35.1495,
|
||||
"longitude": -90.049,
|
||||
"precision": "city",
|
||||
"confidence": 0.72,
|
||||
"location_source": "ror_organization_registry",
|
||||
}
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
try:
|
||||
app.dependency_overrides.clear()
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
r1 = await client.post(
|
||||
"/api/v1/visualization/compute-centers/top500-42/collect-location",
|
||||
json=collect_payload,
|
||||
)
|
||||
r2 = await client.post(
|
||||
"/api/v1/visualization/compute-centers/epoch_ai_gpu-52/location",
|
||||
json=save_payload,
|
||||
)
|
||||
assert r1.status_code == 401
|
||||
assert r2.status_code == 401
|
||||
|
||||
app.dependency_overrides[get_current_user] = _override_viewer_user
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
r3 = await client.post(
|
||||
"/api/v1/visualization/compute-centers/top500-42/collect-location",
|
||||
json=collect_payload,
|
||||
)
|
||||
r4 = await client.post(
|
||||
"/api/v1/visualization/compute-centers/epoch_ai_gpu-52/location",
|
||||
json=save_payload,
|
||||
)
|
||||
assert r3.status_code == 403
|
||||
assert r4.status_code == 403
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
@@ -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()
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "planet-client",
|
||||
"version": "0.80.3",
|
||||
"version": "0.82.0",
|
||||
"description": "Intelligent Planet Program - Native Electron Earth Viewer",
|
||||
"private": true,
|
||||
"packageManager": "bun@1",
|
||||
|
||||
@@ -16,6 +16,11 @@ const mainBuild = await Bun.build({
|
||||
external: ['electron'],
|
||||
minify: true,
|
||||
naming: 'index.cjs',
|
||||
define: {
|
||||
'process.env.PLANET_EARTH_DESKTOP_HANDSHAKE_SECRET': JSON.stringify(
|
||||
process.env.PLANET_EARTH_DESKTOP_HANDSHAKE_SECRET || '',
|
||||
),
|
||||
},
|
||||
})
|
||||
|
||||
if (!mainBuild.success) {
|
||||
@@ -36,4 +41,32 @@ if (!preloadBuild.success) {
|
||||
throw new AggregateError(preloadBuild.logs, 'Electron preload build failed')
|
||||
}
|
||||
|
||||
const indicatorPreloadBuild = await Bun.build({
|
||||
entrypoints: [join(desktopRoot, 'src/preload/recording-indicator.ts')],
|
||||
outdir: join(outDir, 'preload'),
|
||||
target: 'node',
|
||||
format: 'cjs',
|
||||
external: ['electron'],
|
||||
minify: true,
|
||||
naming: 'recording-indicator.cjs',
|
||||
})
|
||||
|
||||
if (!indicatorPreloadBuild.success) {
|
||||
throw new AggregateError(indicatorPreloadBuild.logs, 'Electron indicator preload build failed')
|
||||
}
|
||||
|
||||
const cursorPreloadBuild = await Bun.build({
|
||||
entrypoints: [join(desktopRoot, 'src/preload/recording-cursor.ts')],
|
||||
outdir: join(outDir, 'preload'),
|
||||
target: 'node',
|
||||
format: 'cjs',
|
||||
external: ['electron'],
|
||||
minify: true,
|
||||
naming: 'recording-cursor.cjs',
|
||||
})
|
||||
|
||||
if (!cursorPreloadBuild.success) {
|
||||
throw new AggregateError(cursorPreloadBuild.logs, 'Electron cursor preload build failed')
|
||||
}
|
||||
|
||||
console.log('Built Electron main and preload to dist-electron/')
|
||||
@@ -13,6 +13,8 @@ export interface ServerEndpoints {
|
||||
export interface PersistedUserConfig extends Partial<ServerEndpoints> {
|
||||
splashTheme?: SplashTheme
|
||||
gpuMode?: GpuRenderMode
|
||||
recordAudio?: boolean
|
||||
recordHideCursor?: boolean
|
||||
}
|
||||
|
||||
export type GpuHandoffTarget = 'default' | 'high-performance' | 'low-power' | 'software'
|
||||
@@ -49,6 +51,18 @@ export interface DesktopRuntimeConfig extends ServerEndpoints, DesktopLaunchFlag
|
||||
wsUrl: string
|
||||
splashTheme: SplashTheme
|
||||
gpuMode: GpuRenderMode
|
||||
recordAudio: boolean
|
||||
recordHideCursor: boolean
|
||||
}
|
||||
|
||||
export function normalizeBooleanFlag(raw: unknown, fallback = false): boolean {
|
||||
if (typeof raw === 'boolean') return raw
|
||||
if (typeof raw === 'string') {
|
||||
const normalized = raw.trim().toLowerCase()
|
||||
if (normalized === 'true' || normalized === '1' || normalized === 'yes') return true
|
||||
if (normalized === 'false' || normalized === '0' || normalized === 'no') return false
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
const LEGACY_ACTIVE_THEMES: ReadonlySet<string> = new Set([
|
||||
@@ -326,6 +340,11 @@ export class DesktopConfigStore {
|
||||
userSaved.gpuMode,
|
||||
'auto',
|
||||
)
|
||||
const recordAudio = normalizeBooleanFlag(portable.recordAudio ?? userSaved.recordAudio, false)
|
||||
const recordHideCursor = normalizeBooleanFlag(
|
||||
portable.recordHideCursor ?? userSaved.recordHideCursor,
|
||||
false,
|
||||
)
|
||||
|
||||
return {
|
||||
backendUrl,
|
||||
@@ -334,6 +353,8 @@ export class DesktopConfigStore {
|
||||
wsUrl: deriveBackendWsUrl(backendUrl),
|
||||
splashTheme,
|
||||
gpuMode,
|
||||
recordAudio,
|
||||
recordHideCursor,
|
||||
...this.launchFlags,
|
||||
}
|
||||
}
|
||||
@@ -385,4 +406,24 @@ export class DesktopConfigStore {
|
||||
}
|
||||
return this.get()
|
||||
}
|
||||
|
||||
updateRecordAudio(enabled: unknown): DesktopRuntimeConfig {
|
||||
const nextRecordAudio = normalizeBooleanFlag(enabled, this.current.recordAudio)
|
||||
this.writeUserConfig({ recordAudio: nextRecordAudio })
|
||||
this.current = {
|
||||
...this.current,
|
||||
recordAudio: nextRecordAudio,
|
||||
}
|
||||
return this.get()
|
||||
}
|
||||
|
||||
updateRecordHideCursor(enabled: unknown): DesktopRuntimeConfig {
|
||||
const nextRecordHideCursor = normalizeBooleanFlag(enabled, this.current.recordHideCursor)
|
||||
this.writeUserConfig({ recordHideCursor: nextRecordHideCursor })
|
||||
this.current = {
|
||||
...this.current,
|
||||
recordHideCursor: nextRecordHideCursor,
|
||||
}
|
||||
return this.get()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import crypto from 'node:crypto'
|
||||
|
||||
export interface EarthDesktopAuth {
|
||||
getToken(options?: { forceRefresh?: boolean }): Promise<string | null>
|
||||
clear(): void
|
||||
}
|
||||
|
||||
interface CachedEarthToken {
|
||||
backendUrl: string
|
||||
token: string
|
||||
expiresAtMs: number
|
||||
}
|
||||
|
||||
const REFRESH_MARGIN_MS = 120_000
|
||||
const DEFAULT_TTL_SECONDS = 1800
|
||||
const AUTH_TIMEOUT_MS = 8000
|
||||
|
||||
export function createEarthDesktopAuth(options: {
|
||||
getBackendUrl: () => string
|
||||
getAppVersion: () => string
|
||||
handshakeSecret?: string
|
||||
fetchImpl?: typeof fetch
|
||||
nowMs?: () => number
|
||||
}): EarthDesktopAuth {
|
||||
const fetchImpl = options.fetchImpl ?? fetch
|
||||
const nowMs = options.nowMs ?? (() => Date.now())
|
||||
let cached: CachedEarthToken | null = null
|
||||
let inFlight: Promise<string | null> | null = null
|
||||
let inFlightBackendUrl = ''
|
||||
|
||||
const fetchFreshToken = async (backendUrl: string): Promise<string | null> => {
|
||||
const version = (options.getAppVersion() || '0.0.0').trim() || '0.0.0'
|
||||
const clientHeader = `planet-earth-desktop/${version}`
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Planet-Client': clientHeader,
|
||||
}
|
||||
|
||||
const secret = String(options.handshakeSecret || '').trim()
|
||||
if (secret) {
|
||||
const timestamp = String(Math.floor(nowMs() / 1000))
|
||||
const nonce = crypto.randomBytes(16).toString('hex')
|
||||
const signature = crypto
|
||||
.createHmac('sha256', secret)
|
||||
.update(`${timestamp}.${nonce}.${clientHeader}`)
|
||||
.digest('hex')
|
||||
headers['X-Planet-Client-Timestamp'] = timestamp
|
||||
headers['X-Planet-Client-Nonce'] = nonce
|
||||
headers['X-Planet-Client-Signature'] = signature
|
||||
}
|
||||
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), AUTH_TIMEOUT_MS)
|
||||
try {
|
||||
const targetUrl = new URL('/api/v1/auth/earth-session', backendUrl).toString()
|
||||
const response = await fetchImpl(targetUrl, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({ client_type: 'desktop' }),
|
||||
signal: controller.signal,
|
||||
})
|
||||
if (!response.ok) {
|
||||
return null
|
||||
}
|
||||
const data = (await response.json()) as { token?: unknown; expires_in?: unknown }
|
||||
if (typeof data?.token !== 'string' || !data.token.trim()) {
|
||||
return null
|
||||
}
|
||||
const ttlSeconds =
|
||||
typeof data.expires_in === 'number' && Number.isFinite(data.expires_in) && data.expires_in > 0
|
||||
? data.expires_in
|
||||
: DEFAULT_TTL_SECONDS
|
||||
cached = {
|
||||
backendUrl,
|
||||
token: data.token.trim(),
|
||||
expiresAtMs: nowMs() + ttlSeconds * 1000,
|
||||
}
|
||||
return cached.token
|
||||
} catch {
|
||||
return null
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
async getToken(getOpts) {
|
||||
const backendUrl = String(options.getBackendUrl() || '').trim().replace(/\/+$/, '')
|
||||
if (!backendUrl) return null
|
||||
|
||||
if (cached && cached.backendUrl !== backendUrl) {
|
||||
cached = null
|
||||
}
|
||||
|
||||
if (
|
||||
!getOpts?.forceRefresh &&
|
||||
cached &&
|
||||
cached.expiresAtMs - nowMs() > REFRESH_MARGIN_MS
|
||||
) {
|
||||
return cached.token
|
||||
}
|
||||
|
||||
if (inFlight && inFlightBackendUrl === backendUrl && !getOpts?.forceRefresh) {
|
||||
return inFlight
|
||||
}
|
||||
|
||||
const promise = fetchFreshToken(backendUrl).finally(() => {
|
||||
if (inFlight === promise) {
|
||||
inFlight = null
|
||||
inFlightBackendUrl = ''
|
||||
}
|
||||
})
|
||||
inFlight = promise
|
||||
inFlightBackendUrl = backendUrl
|
||||
return promise
|
||||
},
|
||||
|
||||
clear() {
|
||||
cached = null
|
||||
inFlight = null
|
||||
inFlightBackendUrl = ''
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
},
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -1,16 +1,19 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
import { app, BrowserWindow, dialog, ipcMain, Menu, session, shell } from 'electron'
|
||||
import { app, BrowserWindow, dialog, ipcMain, Menu, net, session, shell } from 'electron'
|
||||
|
||||
import { DesktopConfigStore, normalizeSplashTheme, readPreReadyGpuHandoff, readPreReadyGpuMode, type GpuRenderMode, type ServerEndpoints } from './config'
|
||||
import { DESKTOP_SCHEME, registerDesktopLink } from './desktop-link'
|
||||
import { createEarthDesktopAuth } from './earth-auth'
|
||||
import { createAdaptiveGpuMonitor, probeWindowsGpuEnvironmentSync } from './gpu-monitor'
|
||||
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'
|
||||
import { createMainWindow, dismissMenuBarOnPointerDown, flushWindowState, toggleWindowOrientation } from './window'
|
||||
|
||||
registerEarthScheme()
|
||||
@@ -106,6 +109,24 @@ function resolvePreloadPath(): string {
|
||||
return candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0]
|
||||
}
|
||||
|
||||
function resolveIndicatorPreloadPath(): string {
|
||||
const candidates = [
|
||||
path.join(app.getAppPath(), 'dist-electron/preload/recording-indicator.cjs'),
|
||||
path.resolve(app.getAppPath(), '../preload/recording-indicator.cjs'),
|
||||
path.resolve(process.cwd(), 'dist-electron/preload/recording-indicator.cjs'),
|
||||
]
|
||||
return candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0]
|
||||
}
|
||||
|
||||
function resolveCursorOverlayPreloadPath(): string {
|
||||
const candidates = [
|
||||
path.join(app.getAppPath(), 'dist-electron/preload/recording-cursor.cjs'),
|
||||
path.resolve(app.getAppPath(), '../preload/recording-cursor.cjs'),
|
||||
path.resolve(process.cwd(), 'dist-electron/preload/recording-cursor.cjs'),
|
||||
]
|
||||
return candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0]
|
||||
}
|
||||
|
||||
let mainWindow: BrowserWindow | null = null
|
||||
let launchWindow: (() => void) | undefined
|
||||
|
||||
@@ -211,6 +232,8 @@ if (!singleInstanceLock) {
|
||||
}
|
||||
}
|
||||
|
||||
let screenRecorder: ReturnType<typeof createScreenRecorderController> | null = null
|
||||
|
||||
const refreshApplicationMenu = () => {
|
||||
if (!mainWindow || mainWindow.isDestroyed()) return
|
||||
Menu.setApplicationMenu(
|
||||
@@ -228,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,
|
||||
}
|
||||
@@ -242,14 +265,65 @@ if (!singleInstanceLock) {
|
||||
relaunchDesktopApp({ gpuHandoff: true })
|
||||
}
|
||||
},
|
||||
getRecordingState: () => screenRecorder?.getState() ?? {
|
||||
state: 'idle',
|
||||
elapsedMs: 0,
|
||||
includeAudio: configStore.get().recordAudio,
|
||||
hideCursor: configStore.get().recordHideCursor,
|
||||
filePath: null,
|
||||
},
|
||||
onToggleRecording: (fromMenu = false) => {
|
||||
void screenRecorder?.toggleRecording({ fromMenu })
|
||||
},
|
||||
onToggleRecordAudio: (enabled: boolean) => {
|
||||
configStore.updateRecordAudio(enabled)
|
||||
refreshApplicationMenu()
|
||||
},
|
||||
onToggleRecordHideCursor: (enabled: boolean) => {
|
||||
configStore.updateRecordHideCursor(enabled)
|
||||
refreshApplicationMenu()
|
||||
},
|
||||
onOpenRecordingsFolder: () => {
|
||||
void screenRecorder?.openRecordingsFolder()
|
||||
},
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
screenRecorder = createScreenRecorderController({
|
||||
getMainWindow: () => mainWindow,
|
||||
configStore,
|
||||
session: session.defaultSession,
|
||||
indicatorPreloadPath: resolveIndicatorPreloadPath(),
|
||||
cursorOverlayPreloadPath: resolveCursorOverlayPreloadPath(),
|
||||
dismissMenuBar: dismissMenuBarOnPointerDown,
|
||||
onStateChanged: () => {
|
||||
refreshApplicationMenu()
|
||||
},
|
||||
})
|
||||
app.on('will-quit', () => {
|
||||
screenRecorder?.destroy()
|
||||
})
|
||||
|
||||
const earthAuth = createEarthDesktopAuth({
|
||||
getBackendUrl: () => configStore.get().backendUrl,
|
||||
getAppVersion: () => app.getVersion(),
|
||||
handshakeSecret: process.env.PLANET_EARTH_DESKTOP_HANDSHAKE_SECRET || '',
|
||||
fetchImpl: (input, init) => net.fetch(input as string, init),
|
||||
})
|
||||
|
||||
installEarthSessionHandlers(session.defaultSession, {
|
||||
earthBundleRoot,
|
||||
getEarthOverlayRoot: () => hotUpdater.getOverlayRoot(),
|
||||
getBackendUrl: () => configStore.get().backendUrl,
|
||||
getEarthAuthToken: (opts) => earthAuth.getToken(opts),
|
||||
})
|
||||
|
||||
ipcMain.handle('planet:get-earth-session-token', (_event, opts: unknown) => {
|
||||
const forceRefresh = Boolean(
|
||||
opts && typeof opts === 'object' && (opts as { forceRefresh?: unknown }).forceRefresh,
|
||||
)
|
||||
return earthAuth.getToken({ forceRefresh })
|
||||
})
|
||||
|
||||
ipcMain.on('planet:earth-startup-ready', () => {
|
||||
@@ -338,6 +412,7 @@ if (!singleInstanceLock) {
|
||||
|
||||
ipcMain.handle('planet:set-server-config', (_event, partial: unknown) => {
|
||||
const next = configStore.updateEndpoints((partial || {}) as Partial<ServerEndpoints>)
|
||||
earthAuth.clear()
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
mainWindow.reload()
|
||||
}
|
||||
@@ -363,6 +438,15 @@ if (!singleInstanceLock) {
|
||||
iconPath: resolveIconPath(),
|
||||
userDataDir: app.getPath('userData'),
|
||||
configStore,
|
||||
onToggleRecording: () => {
|
||||
void screenRecorder?.toggleRecording({ fromMenu: false })
|
||||
},
|
||||
})
|
||||
|
||||
mainWindow.on('close', (event) => {
|
||||
if (mainWindow) {
|
||||
screenRecorder?.handleWindowClose(mainWindow, event)
|
||||
}
|
||||
})
|
||||
|
||||
refreshApplicationMenu()
|
||||
|
||||
+95
-33
@@ -3,22 +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: {
|
||||
@@ -28,6 +33,11 @@ export function buildApplicationMenu(options: {
|
||||
onCheckForUpdates?: () => void
|
||||
getGpuStatus?: () => GpuRuntimeSummary
|
||||
onSelectGpuMode?: (mode: GpuRenderMode) => void | Promise<void>
|
||||
getRecordingState?: () => RecordingStatusSnapshot
|
||||
onToggleRecording?: (fromMenu?: boolean) => void
|
||||
onToggleRecordAudio?: (enabled: boolean) => void
|
||||
onToggleRecordHideCursor?: (enabled: boolean) => void
|
||||
onOpenRecordingsFolder?: () => void
|
||||
}): Menu {
|
||||
const sendAction = (action: string) => {
|
||||
if (!options.mainWindow.isDestroyed()) {
|
||||
@@ -42,7 +52,12 @@ export function buildApplicationMenu(options: {
|
||||
|
||||
const currentSplashTheme = options.configStore.get().splashTheme
|
||||
const currentGpuMode = options.configStore.get().gpuMode
|
||||
const currentRecordAudio = options.configStore.get().recordAudio
|
||||
const currentRecordHideCursor = options.configStore.get().recordHideCursor
|
||||
const gpuSummary = options.getGpuStatus?.()
|
||||
const recordingSnapshot = options.getRecordingState?.()
|
||||
const recordingState = recordingSnapshot?.state ?? 'idle'
|
||||
const isRecordingOrStopping = recordingState === 'recording' || recordingState === 'stopping'
|
||||
|
||||
const selectSplashTheme = (theme: SplashTheme) => {
|
||||
options.configStore.updateSplashTheme(theme)
|
||||
@@ -78,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()) {
|
||||
@@ -96,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
|
||||
? [
|
||||
@@ -125,7 +140,7 @@ export function buildApplicationMenu(options: {
|
||||
]
|
||||
: []),
|
||||
{
|
||||
label: '自动(卡顿缺显存切核显,显存空出自动回独显) / Auto',
|
||||
label: tClient('自动切换(推荐)', 'Automatic (Recommended)'),
|
||||
type: 'radio',
|
||||
checked: currentGpuMode === 'auto',
|
||||
click: () => {
|
||||
@@ -133,7 +148,7 @@ export function buildApplicationMenu(options: {
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '独立显卡(高性能) / Discrete GPU',
|
||||
label: tClient('高性能显卡', 'High-Performance GPU'),
|
||||
type: 'radio',
|
||||
checked: currentGpuMode === 'high-performance',
|
||||
click: () => {
|
||||
@@ -141,7 +156,7 @@ export function buildApplicationMenu(options: {
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '集成核显(不占独显显存) / Integrated GPU',
|
||||
label: tClient('节能核显', 'Integrated GPU'),
|
||||
type: 'radio',
|
||||
checked: currentGpuMode === 'low-power',
|
||||
click: () => {
|
||||
@@ -149,7 +164,7 @@ export function buildApplicationMenu(options: {
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '纯 CPU 软渲染 / Software GL',
|
||||
label: tClient('软件兼容渲染', 'Software Rendering'),
|
||||
type: 'radio',
|
||||
checked: currentGpuMode === 'software',
|
||||
click: () => {
|
||||
@@ -158,61 +173,106 @@ export function buildApplicationMenu(options: {
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: tClient('录屏', 'Screen Recording'),
|
||||
submenu: [
|
||||
{
|
||||
label: isRecordingOrStopping
|
||||
? tClient('停止录屏', 'Stop Recording')
|
||||
: recordingState === 'starting'
|
||||
? tClient('正在启动录屏…', 'Starting Recording…')
|
||||
: tClient('开始录屏', 'Start Recording'),
|
||||
accelerator: 'CmdOrCtrl+Shift+F9',
|
||||
enabled: recordingState === 'idle' || recordingState === 'recording',
|
||||
click: () => {
|
||||
options.onToggleRecording?.(true)
|
||||
},
|
||||
},
|
||||
{
|
||||
label: tClient('录制音频', 'Include Audio'),
|
||||
type: 'checkbox',
|
||||
checked: currentRecordAudio,
|
||||
enabled: recordingState === 'idle',
|
||||
click: (item) => {
|
||||
options.onToggleRecordAudio?.(item.checked)
|
||||
},
|
||||
},
|
||||
{
|
||||
label: tClient('隐藏光标', 'Hide Cursor'),
|
||||
type: 'checkbox',
|
||||
checked: currentRecordHideCursor,
|
||||
enabled: recordingState === 'idle',
|
||||
click: (item) => {
|
||||
options.onToggleRecordHideCursor?.(item.checked)
|
||||
},
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: tClient('打开录屏目录', 'Open Recordings Folder'),
|
||||
click: () => {
|
||||
options.onOpenRecordingsFolder?.()
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{ 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()) {
|
||||
@@ -221,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: () => {
|
||||
@@ -231,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()) {
|
||||
|
||||
@@ -158,6 +158,7 @@ export function createEarthProtocolHandler(options: {
|
||||
earthBundleRoot: string
|
||||
getEarthOverlayRoot?: () => string | null
|
||||
getBackendUrl: () => string
|
||||
getEarthAuthToken?: (opts?: { forceRefresh?: boolean }) => Promise<string | null>
|
||||
fetchImpl?: typeof fetch
|
||||
}): (request: Request) => Promise<Response> {
|
||||
const fetchImpl = options.fetchImpl ?? fetch
|
||||
@@ -170,28 +171,58 @@ export function createEarthProtocolHandler(options: {
|
||||
|
||||
if (isProxiedBackendPath(parsedUrl.pathname)) {
|
||||
const targetUrl = new URL(`${parsedUrl.pathname}${parsedUrl.search}`, options.getBackendUrl())
|
||||
const forwardHeaders = new Headers(request.headers)
|
||||
forwardHeaders.delete('host')
|
||||
forwardHeaders.delete('content-length')
|
||||
if (!forwardHeaders.has('accept-encoding')) {
|
||||
forwardHeaders.set('accept-encoding', 'gzip, deflate, br')
|
||||
const buildForwardHeaders = async (forceRefresh = false): Promise<Headers> => {
|
||||
const headers = new Headers(request.headers)
|
||||
headers.delete('host')
|
||||
headers.delete('content-length')
|
||||
if (!headers.has('accept-encoding')) {
|
||||
headers.set('accept-encoding', 'gzip, deflate, br')
|
||||
}
|
||||
if (
|
||||
options.getEarthAuthToken &&
|
||||
parsedUrl.pathname !== '/api/v1/auth/earth-session' &&
|
||||
(forceRefresh || !headers.has('x-planet-earth-token'))
|
||||
) {
|
||||
const token = await options.getEarthAuthToken({ forceRefresh })
|
||||
if (token) {
|
||||
headers.set('x-planet-earth-token', token)
|
||||
}
|
||||
}
|
||||
return headers
|
||||
}
|
||||
|
||||
const method = request.method.toUpperCase()
|
||||
const hasBody = method !== 'GET' && method !== 'HEAD'
|
||||
try {
|
||||
const init: RequestInit & { duplex?: 'half' } = {
|
||||
method,
|
||||
headers: forwardHeaders,
|
||||
const makeInit = (headers: Headers): RequestInit & { duplex?: 'half' } => {
|
||||
const init: RequestInit & { duplex?: 'half' } = {
|
||||
method,
|
||||
headers,
|
||||
}
|
||||
if (request.signal) {
|
||||
init.signal = request.signal
|
||||
}
|
||||
if (hasBody && request.body) {
|
||||
init.body = request.body
|
||||
init.duplex = 'half'
|
||||
}
|
||||
return init
|
||||
}
|
||||
if (request.signal) {
|
||||
init.signal = request.signal
|
||||
|
||||
let upstream = await fetchImpl(targetUrl.toString(), makeInit(await buildForwardHeaders(false)))
|
||||
if (
|
||||
upstream.status === 401 &&
|
||||
!hasBody &&
|
||||
options.getEarthAuthToken &&
|
||||
parsedUrl.pathname !== '/api/v1/auth/earth-session'
|
||||
) {
|
||||
try {
|
||||
await upstream.body?.cancel()
|
||||
} catch {
|
||||
// Ignore cancel errors on drained/aborted streams.
|
||||
}
|
||||
upstream = await fetchImpl(targetUrl.toString(), makeInit(await buildForwardHeaders(true)))
|
||||
}
|
||||
if (hasBody && request.body) {
|
||||
init.body = request.body
|
||||
init.duplex = 'half'
|
||||
}
|
||||
const upstream = await fetchImpl(targetUrl.toString(), init)
|
||||
const responseHeaders = new Headers(upstream.headers)
|
||||
responseHeaders.delete('content-encoding')
|
||||
responseHeaders.delete('content-length')
|
||||
|
||||
@@ -31,12 +31,14 @@ export function installEarthSessionHandlers(
|
||||
earthBundleRoot: string
|
||||
getEarthOverlayRoot?: () => string | null
|
||||
getBackendUrl: () => string
|
||||
getEarthAuthToken?: (opts?: { forceRefresh?: boolean }) => Promise<string | null>
|
||||
},
|
||||
): void {
|
||||
const handler = createEarthProtocolHandler({
|
||||
earthBundleRoot: options.earthBundleRoot,
|
||||
getEarthOverlayRoot: options.getEarthOverlayRoot,
|
||||
getBackendUrl: options.getBackendUrl,
|
||||
getEarthAuthToken: options.getEarthAuthToken,
|
||||
fetchImpl: (input, init) => net.fetch(input as string, init),
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,333 @@
|
||||
export type RecordingState = 'idle' | 'starting' | 'recording' | 'stopping'
|
||||
|
||||
export interface RecordingStatusSnapshot {
|
||||
state: RecordingState
|
||||
elapsedMs: number
|
||||
includeAudio: boolean
|
||||
hideCursor: boolean
|
||||
filePath: string | null
|
||||
}
|
||||
|
||||
export type RecordingCursorShape = 'default' | 'pointer' | 'grab' | 'grabbing' | 'text'
|
||||
|
||||
export interface RecordingCursorPayload {
|
||||
visible: boolean
|
||||
x: number
|
||||
y: number
|
||||
shape: RecordingCursorShape
|
||||
}
|
||||
|
||||
export interface RectBounds {
|
||||
x: number
|
||||
y: number
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
const INDICATOR_BASE_WIDTH = 120
|
||||
const INDICATOR_LONG_WIDTH = 136
|
||||
const INDICATOR_HEIGHT = 36
|
||||
|
||||
/**
|
||||
* Format elapsed recording duration as MM:SS (or HH:MM:SS once >= 1 hour).
|
||||
*/
|
||||
export function formatRecordingDuration(elapsedMs: number): string {
|
||||
const safeSeconds = Number.isFinite(elapsedMs) && elapsedMs > 0 ? Math.floor(elapsedMs / 1000) : 0
|
||||
const hours = Math.floor(safeSeconds / 3600)
|
||||
const minutes = Math.floor((safeSeconds % 3600) / 60)
|
||||
const seconds = safeSeconds % 60
|
||||
const pad = (value: number) => String(value).padStart(2, '0')
|
||||
return hours > 0 ? `${pad(hours)}:${pad(minutes)}:${pad(seconds)}` : `${pad(minutes)}:${pad(seconds)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a MediaRecorder MIME type to an output video container extension.
|
||||
*/
|
||||
export function resolveRecordingExtension(mimeType?: string): 'mp4' | 'webm' {
|
||||
return typeof mimeType === 'string' && mimeType.toLowerCase().includes('mp4') ? 'mp4' : 'webm'
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a collision-safe output filename for saved screen recordings.
|
||||
*/
|
||||
export function buildRecordingFilename(now: Date, ext: 'mp4' | 'webm', suffixIndex = 0): string {
|
||||
const pad = (value: number) => String(value).padStart(2, '0')
|
||||
const stamp = [
|
||||
now.getFullYear(),
|
||||
pad(now.getMonth() + 1),
|
||||
pad(now.getDate()),
|
||||
'-',
|
||||
pad(now.getHours()),
|
||||
pad(now.getMinutes()),
|
||||
pad(now.getSeconds()),
|
||||
].join('')
|
||||
const suffix = suffixIndex > 0 ? `-${suffixIndex + 1}` : ''
|
||||
return `Planet-Earth-${stamp}${suffix}.${ext}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Return ordered MediaRecorder MIME candidates, preferring H.264 MP4 before WebM fallbacks.
|
||||
*/
|
||||
export function pickSupportedRecordingMimeTypes(includeAudio: boolean): string[] {
|
||||
if (includeAudio) {
|
||||
return [
|
||||
'video/mp4;codecs=avc1.42E01E,mp4a.40.2',
|
||||
'video/mp4;codecs=avc1.4d401f,mp4a.40.2',
|
||||
'video/mp4;codecs=avc1.42E01E',
|
||||
'video/mp4',
|
||||
'video/webm;codecs=vp9,opus',
|
||||
'video/webm;codecs=vp8,opus',
|
||||
'video/webm;codecs=vp9',
|
||||
'video/webm;codecs=vp8',
|
||||
'video/webm',
|
||||
]
|
||||
}
|
||||
return [
|
||||
'video/mp4;codecs=avc1.42E01E',
|
||||
'video/mp4;codecs=avc1.4d401f',
|
||||
'video/mp4',
|
||||
'video/webm;codecs=vp9',
|
||||
'video/webm;codecs=vp8',
|
||||
'video/webm',
|
||||
]
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute centered top-overlay indicator bounds anchored safely inside mainWindow content area.
|
||||
*/
|
||||
export function computeIndicatorBounds(options: {
|
||||
contentBounds: RectBounds
|
||||
elapsedMs: number
|
||||
}): RectBounds {
|
||||
const { contentBounds, elapsedMs } = options
|
||||
const desiredWidth = elapsedMs >= 3_600_000 ? INDICATOR_LONG_WIDTH : INDICATOR_BASE_WIDTH
|
||||
const width = Math.max(60, Math.min(desiredWidth, Math.max(60, contentBounds.width - 16)))
|
||||
const height = Math.min(INDICATOR_HEIGHT, Math.max(24, contentBounds.height - 8))
|
||||
const rawX = contentBounds.x + Math.round((contentBounds.width - width) / 2)
|
||||
const topOffset = Math.min(56, Math.max(10, Math.round(contentBounds.height * 0.08)))
|
||||
const rawY = contentBounds.y + topOffset
|
||||
const maxX = contentBounds.x + Math.max(0, contentBounds.width - width)
|
||||
const maxY = contentBounds.y + Math.max(0, contentBounds.height - height)
|
||||
return {
|
||||
x: Math.max(contentBounds.x, Math.min(rawX, maxX)),
|
||||
y: Math.max(contentBounds.y, Math.min(rawY, maxY)),
|
||||
width,
|
||||
height,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render self-contained HTML for the transparent floating recording indicator pill.
|
||||
*/
|
||||
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 `<!DOCTYPE html>
|
||||
<html lang="${locale}">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<style>
|
||||
html, body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: transparent;
|
||||
overflow: hidden;
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
}
|
||||
.rec-pill {
|
||||
appearance: none;
|
||||
height: 30px;
|
||||
padding: 0 12px 0 10px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(201, 225, 247, 0.22);
|
||||
background: rgba(8, 16, 28, 0.8);
|
||||
backdrop-filter: blur(14px) saturate(130%);
|
||||
-webkit-backdrop-filter: blur(14px) saturate(130%);
|
||||
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.42), inset 0 1px 0 rgba(255, 255, 255, 0.14);
|
||||
color: #eef5ff;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
outline: none;
|
||||
transition: border-color 0.16s ease, background 0.16s ease, box-shadow 0.16s ease, transform 0.14s ease;
|
||||
}
|
||||
.rec-pill:hover {
|
||||
border-color: rgba(248, 113, 113, 0.56);
|
||||
background: rgba(24, 18, 28, 0.88);
|
||||
box-shadow: 0 6px 20px rgba(239, 68, 68, 0.22), inset 0 1px 0 rgba(255, 255, 255, 0.18);
|
||||
}
|
||||
.rec-pill:active {
|
||||
transform: scale(0.96);
|
||||
}
|
||||
.rec-glyph-wrap {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.rec-glyph {
|
||||
width: 9px;
|
||||
height: 9px;
|
||||
border-radius: 50%;
|
||||
background: #ef4444;
|
||||
box-shadow: 0 0 8px rgba(239, 68, 68, 0.72);
|
||||
animation: recPulse 1.4s ease-in-out infinite;
|
||||
transition: width 0.15s ease, height 0.15s ease, border-radius 0.15s ease, background 0.15s ease, box-shadow 0.15s ease;
|
||||
}
|
||||
.rec-pill:hover .rec-glyph {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 2px;
|
||||
background: #f87171;
|
||||
box-shadow: 0 0 10px rgba(248, 113, 113, 0.8);
|
||||
animation: none;
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
.rec-time {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
letter-spacing: 0.03em;
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
}
|
||||
@keyframes recPulse {
|
||||
0%, 100% {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
50% {
|
||||
opacity: 0.32;
|
||||
transform: scale(0.8);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<button id="rec-stop-btn" class="rec-pill" type="button" title="${stopTitle}" aria-label="${stopAria}">
|
||||
<span class="rec-glyph-wrap" aria-hidden="true"><span class="rec-glyph"></span></span>
|
||||
<span id="rec-timer" class="rec-time">00:00</span>
|
||||
</button>
|
||||
<script>
|
||||
const btn = document.getElementById('rec-stop-btn');
|
||||
const timerEl = document.getElementById('rec-timer');
|
||||
if (window.planetRecordingIndicator?.onTick) {
|
||||
window.planetRecordingIndicator.onTick((formatted) => {
|
||||
if (typeof formatted === 'string' && timerEl) {
|
||||
timerEl.textContent = formatted;
|
||||
}
|
||||
});
|
||||
}
|
||||
btn?.addEventListener('click', () => {
|
||||
window.planetRecordingIndicator?.requestStop?.();
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>`
|
||||
}
|
||||
|
||||
/**
|
||||
* Render self-contained HTML for the transparent click-through custom cursor overlay window.
|
||||
*/
|
||||
export function buildCursorOverlayHtml(): string {
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<style>
|
||||
html, body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: transparent;
|
||||
overflow: hidden;
|
||||
pointer-events: none;
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
}
|
||||
#cursor-root {
|
||||
position: fixed;
|
||||
left: 0;
|
||||
top: 0;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
opacity: 0;
|
||||
will-change: transform;
|
||||
pointer-events: none;
|
||||
}
|
||||
.cursor-svg {
|
||||
display: none;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.55));
|
||||
}
|
||||
#cursor-root[data-shape="default"] .cursor-svg--default,
|
||||
#cursor-root[data-shape="pointer"] .cursor-svg--pointer,
|
||||
#cursor-root[data-shape="grab"] .cursor-svg--grab,
|
||||
#cursor-root[data-shape="grabbing"] .cursor-svg--grabbing,
|
||||
#cursor-root[data-shape="text"] .cursor-svg--text {
|
||||
display: block;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="cursor-root" data-shape="default" aria-hidden="true">
|
||||
<svg class="cursor-svg cursor-svg--default" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M2 1.5L2 19.5L6.8 14.9L10.3 21.8L13.1 20.4L9.7 13.6L16.3 13.6L2 1.5Z" fill="#ffffff" stroke="#0f172a" stroke-width="1.5" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
<svg class="cursor-svg cursor-svg--pointer" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M8.5 1.8C9.6 1.8 10.5 2.7 10.5 3.8V10.1C11 9.6 11.7 9.4 12.4 9.7C13.1 9.9 13.6 10.5 13.7 11.1C14.2 10.7 15 10.5 15.7 10.8C16.4 11.1 16.9 11.8 17 12.6C17.5 12.3 18.2 12.3 18.8 12.6C19.5 12.9 20 13.6 20 14.5V16.8C20 19.7 17.8 22 14.9 22H11.5C9.6 22 7.9 21 6.9 19.4L4.7 15.7C4.2 14.9 4.5 13.8 5.3 13.4C6 13 6.9 13.2 7.4 13.9L6.5 15.3V3.8C6.5 2.7 7.4 1.8 8.5 1.8Z" fill="#ffffff" stroke="#0f172a" stroke-width="1.45" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
<svg class="cursor-svg cursor-svg--grab" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M7 11V5.5C7 4.7 7.7 4 8.5 4C9.3 4 10 4.7 10 5.5V10.5M10 10V4.5C10 3.7 10.7 3 11.5 3C12.3 3 13 3.7 13 4.5V10.5M13 10.5V5.5C13 4.7 13.7 4 14.5 4C15.3 4 16 4.7 16 5.5V11.5M16 11.5V7.5C16 6.7 16.7 6 17.5 6C18.3 6 19 6.7 19 7.5V15C19 18.6 16.3 21 12.8 21H10.5C8.5 21 6.7 20 5.7 18.3L4.2 15.7C3.7 14.9 4 13.9 4.8 13.4C5.5 13 6.4 13.2 6.9 13.9L7 14V11Z" fill="#ffffff" stroke="#0f172a" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
<svg class="cursor-svg cursor-svg--grabbing" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M6.5 11.5C6.5 9.8 7.8 8.8 9.2 9.2V8.2C9.2 7 10.2 6.2 11.3 6.5C11.9 6.7 12.4 7.1 12.6 7.7C13.2 7 14.3 6.8 15.2 7.3C15.8 7.6 16.2 8.2 16.3 8.9C17.2 8.7 18.2 9.4 18.2 10.4V15C18.2 18.4 15.7 21 12.4 21H10.4C8.4 21 6.7 19.8 5.9 18L4.9 15.6C4.6 14.9 4.9 14 5.7 13.7L6.5 13.4V11.5Z" fill="#ffffff" stroke="#0f172a" stroke-width="1.45" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
<svg class="cursor-svg cursor-svg--text" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M6 4H14M6 20H14M10 4V20" stroke="#0f172a" stroke-width="3.2" stroke-linecap="round"/>
|
||||
<path d="M6 4H14M6 20H14M10 4V20" stroke="#ffffff" stroke-width="1.6" stroke-linecap="round"/>
|
||||
</svg>
|
||||
</div>
|
||||
<script>
|
||||
const root = document.getElementById('cursor-root');
|
||||
const HOTSPOTS = {
|
||||
default: [0, 0],
|
||||
pointer: [-8, -2],
|
||||
grab: [-10, -10],
|
||||
grabbing: [-10, -10],
|
||||
text: [-10, -12],
|
||||
};
|
||||
if (window.planetRecordingCursor?.onUpdate) {
|
||||
window.planetRecordingCursor.onUpdate((payload) => {
|
||||
if (!root || !payload) return;
|
||||
if (!payload.visible) {
|
||||
root.style.opacity = '0';
|
||||
return;
|
||||
}
|
||||
const shape = HOTSPOTS[payload.shape] ? payload.shape : 'default';
|
||||
const [ox, oy] = HOTSPOTS[shape];
|
||||
root.dataset.shape = shape;
|
||||
root.style.transform = 'translate3d(' + (Math.round(payload.x) + ox) + 'px, ' + (Math.round(payload.y) + oy) + 'px, 0)';
|
||||
root.style.opacity = '1';
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>`
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
import { BrowserWindow } from 'electron'
|
||||
|
||||
import { buildCursorOverlayHtml, type RecordingCursorPayload } from './recording-core'
|
||||
|
||||
export interface RecordingCursorOverlayController {
|
||||
show: () => void
|
||||
updateCursor: (payload: RecordingCursorPayload) => void
|
||||
hide: () => void
|
||||
destroy: () => void
|
||||
}
|
||||
|
||||
const HIDDEN_CURSOR_PAYLOAD: RecordingCursorPayload = {
|
||||
visible: false,
|
||||
x: 0,
|
||||
y: 0,
|
||||
shape: 'default',
|
||||
}
|
||||
|
||||
/**
|
||||
* Manage a stationary, transparent, click-through overlay window that renders a custom
|
||||
* pointer for the user while the OS cursor is hidden in mainFrame screen recordings.
|
||||
*/
|
||||
export function createRecordingCursorOverlayController(options: {
|
||||
getMainWindow: () => BrowserWindow | null
|
||||
preloadPath: string
|
||||
}): RecordingCursorOverlayController {
|
||||
let overlayWin: BrowserWindow | null = null
|
||||
let boundMainWin: BrowserWindow | null = null
|
||||
let blurHideTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let visible = false
|
||||
let destroyed = false
|
||||
let readyToShow = false
|
||||
|
||||
const clearBlurHideTimer = () => {
|
||||
if (blurHideTimer) {
|
||||
clearTimeout(blurHideTimer)
|
||||
blurHideTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
const pushCursor = (payload: RecordingCursorPayload) => {
|
||||
if (!overlayWin || overlayWin.isDestroyed() || overlayWin.webContents.isDestroyed()) return
|
||||
overlayWin.webContents.send('planet:recording-cursor-update', payload)
|
||||
}
|
||||
|
||||
const syncBoundsAndLevel = () => {
|
||||
const mainWin = options.getMainWindow()
|
||||
if (
|
||||
destroyed ||
|
||||
!visible ||
|
||||
!overlayWin ||
|
||||
overlayWin.isDestroyed() ||
|
||||
!mainWin ||
|
||||
mainWin.isDestroyed()
|
||||
) {
|
||||
return
|
||||
}
|
||||
if (mainWin.isMinimized() || !mainWin.isVisible() || !mainWin.isFocused()) {
|
||||
pushCursor(HIDDEN_CURSOR_PAYLOAD)
|
||||
if (overlayWin.isVisible()) {
|
||||
overlayWin.hide()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const contentBounds = mainWin.getContentBounds()
|
||||
if (contentBounds.width > 0 && contentBounds.height > 0) {
|
||||
overlayWin.setBounds(contentBounds)
|
||||
}
|
||||
|
||||
overlayWin.setAlwaysOnTop(true, mainWin.isFullScreen() ? 'screen-saver' : 'floating')
|
||||
if (readyToShow && !overlayWin.isVisible()) {
|
||||
overlayWin.showInactive()
|
||||
}
|
||||
}
|
||||
|
||||
const handleMainFocus = () => {
|
||||
clearBlurHideTimer()
|
||||
syncBoundsAndLevel()
|
||||
}
|
||||
|
||||
const handleMainBlur = () => {
|
||||
clearBlurHideTimer()
|
||||
blurHideTimer = setTimeout(() => {
|
||||
blurHideTimer = null
|
||||
const mainWin = options.getMainWindow()
|
||||
if (!mainWin || mainWin.isDestroyed() || !mainWin.isFocused()) {
|
||||
pushCursor(HIDDEN_CURSOR_PAYLOAD)
|
||||
if (overlayWin && !overlayWin.isDestroyed() && overlayWin.isVisible()) {
|
||||
overlayWin.hide()
|
||||
}
|
||||
}
|
||||
}, 60)
|
||||
}
|
||||
|
||||
const unbindMainWindowListeners = () => {
|
||||
clearBlurHideTimer()
|
||||
if (!boundMainWin || boundMainWin.isDestroyed()) {
|
||||
boundMainWin = null
|
||||
return
|
||||
}
|
||||
boundMainWin.removeListener('move', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('resize', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('maximize', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('unmaximize', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('minimize', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('restore', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('enter-full-screen', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('leave-full-screen', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('show', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('hide', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('focus', handleMainFocus)
|
||||
boundMainWin.removeListener('blur', handleMainBlur)
|
||||
boundMainWin.removeListener('closed', hide)
|
||||
boundMainWin = null
|
||||
}
|
||||
|
||||
const bindMainWindowListeners = (mainWin: BrowserWindow) => {
|
||||
if (boundMainWin === mainWin) return
|
||||
unbindMainWindowListeners()
|
||||
boundMainWin = mainWin
|
||||
mainWin.on('move', syncBoundsAndLevel)
|
||||
mainWin.on('resize', syncBoundsAndLevel)
|
||||
mainWin.on('maximize', syncBoundsAndLevel)
|
||||
mainWin.on('unmaximize', syncBoundsAndLevel)
|
||||
mainWin.on('minimize', syncBoundsAndLevel)
|
||||
mainWin.on('restore', syncBoundsAndLevel)
|
||||
mainWin.on('enter-full-screen', syncBoundsAndLevel)
|
||||
mainWin.on('leave-full-screen', syncBoundsAndLevel)
|
||||
mainWin.on('show', syncBoundsAndLevel)
|
||||
mainWin.on('hide', syncBoundsAndLevel)
|
||||
mainWin.on('focus', handleMainFocus)
|
||||
mainWin.on('blur', handleMainBlur)
|
||||
mainWin.on('closed', hide)
|
||||
}
|
||||
|
||||
const ensureOverlayWindow = (mainWin: BrowserWindow): BrowserWindow => {
|
||||
if (overlayWin && !overlayWin.isDestroyed()) {
|
||||
return overlayWin
|
||||
}
|
||||
readyToShow = false
|
||||
const contentBounds = mainWin.getContentBounds()
|
||||
overlayWin = new BrowserWindow({
|
||||
x: contentBounds.x,
|
||||
y: contentBounds.y,
|
||||
width: Math.max(1, contentBounds.width),
|
||||
height: Math.max(1, contentBounds.height),
|
||||
transparent: true,
|
||||
backgroundColor: '#00000000',
|
||||
frame: false,
|
||||
thickFrame: false,
|
||||
roundedCorners: false,
|
||||
resizable: false,
|
||||
movable: false,
|
||||
minimizable: false,
|
||||
maximizable: false,
|
||||
closable: false,
|
||||
focusable: false,
|
||||
skipTaskbar: true,
|
||||
hasShadow: false,
|
||||
show: false,
|
||||
webPreferences: {
|
||||
preload: options.preloadPath,
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: true,
|
||||
},
|
||||
})
|
||||
overlayWin.setMenuBarVisibility(false)
|
||||
overlayWin.setIgnoreMouseEvents(true)
|
||||
overlayWin.webContents.once('did-finish-load', () => {
|
||||
if (!overlayWin || overlayWin.isDestroyed()) return
|
||||
void overlayWin.webContents.setVisualZoomLevelLimits(1, 1)
|
||||
readyToShow = true
|
||||
pushCursor(HIDDEN_CURSOR_PAYLOAD)
|
||||
if (visible) {
|
||||
syncBoundsAndLevel()
|
||||
}
|
||||
})
|
||||
void overlayWin.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(buildCursorOverlayHtml())}`)
|
||||
return overlayWin
|
||||
}
|
||||
|
||||
const show = () => {
|
||||
if (destroyed) return
|
||||
const mainWin = options.getMainWindow()
|
||||
if (!mainWin || mainWin.isDestroyed()) return
|
||||
clearBlurHideTimer()
|
||||
visible = true
|
||||
bindMainWindowListeners(mainWin)
|
||||
ensureOverlayWindow(mainWin)
|
||||
syncBoundsAndLevel()
|
||||
}
|
||||
|
||||
const updateCursor = (payload: RecordingCursorPayload) => {
|
||||
if (destroyed || !visible || !readyToShow) return
|
||||
pushCursor(payload)
|
||||
}
|
||||
|
||||
function hide() {
|
||||
clearBlurHideTimer()
|
||||
visible = false
|
||||
pushCursor(HIDDEN_CURSOR_PAYLOAD)
|
||||
if (overlayWin && !overlayWin.isDestroyed() && overlayWin.isVisible()) {
|
||||
overlayWin.hide()
|
||||
}
|
||||
}
|
||||
|
||||
const destroy = () => {
|
||||
destroyed = true
|
||||
visible = false
|
||||
unbindMainWindowListeners()
|
||||
if (overlayWin && !overlayWin.isDestroyed()) {
|
||||
overlayWin.destroy()
|
||||
}
|
||||
overlayWin = null
|
||||
}
|
||||
|
||||
return {
|
||||
show,
|
||||
updateCursor,
|
||||
hide,
|
||||
destroy,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
import { BrowserWindow, screen, type Display } from 'electron'
|
||||
|
||||
import { getClientLocale } from './i18n'
|
||||
import { buildRecordingIndicatorHtml, computeIndicatorBounds, formatRecordingDuration } from './recording-core'
|
||||
|
||||
export interface RecordingIndicatorController {
|
||||
show: (elapsedMs?: number) => void
|
||||
updateElapsed: (elapsedMs: number) => void
|
||||
hide: () => void
|
||||
destroy: () => void
|
||||
}
|
||||
|
||||
export function createRecordingIndicatorController(options: {
|
||||
getMainWindow: () => BrowserWindow | null
|
||||
preloadPath: string
|
||||
}): RecordingIndicatorController {
|
||||
let indicatorWin: BrowserWindow | null = null
|
||||
let boundMainWin: BrowserWindow | null = null
|
||||
let blurHideTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let visible = false
|
||||
let lastElapsedMs = 0
|
||||
let destroyed = false
|
||||
let readyToShow = false
|
||||
|
||||
const clearBlurHideTimer = () => {
|
||||
if (blurHideTimer) {
|
||||
clearTimeout(blurHideTimer)
|
||||
blurHideTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
const syncBoundsAndLevel = () => {
|
||||
const mainWin = options.getMainWindow()
|
||||
if (
|
||||
destroyed ||
|
||||
!visible ||
|
||||
!indicatorWin ||
|
||||
indicatorWin.isDestroyed() ||
|
||||
!mainWin ||
|
||||
mainWin.isDestroyed()
|
||||
) {
|
||||
return
|
||||
}
|
||||
if (mainWin.isMinimized() || !mainWin.isVisible() || !mainWin.isFocused()) {
|
||||
if (indicatorWin.isVisible()) {
|
||||
indicatorWin.hide()
|
||||
}
|
||||
return
|
||||
}
|
||||
const contentBounds = mainWin.getContentBounds()
|
||||
const nextBounds = computeIndicatorBounds({ contentBounds, elapsedMs: lastElapsedMs })
|
||||
indicatorWin.setBounds(nextBounds)
|
||||
|
||||
indicatorWin.setAlwaysOnTop(true, mainWin.isFullScreen() ? 'screen-saver' : 'pop-up-menu')
|
||||
if (readyToShow && !indicatorWin.isVisible()) {
|
||||
indicatorWin.showInactive()
|
||||
}
|
||||
}
|
||||
|
||||
const handleMainFocus = () => {
|
||||
clearBlurHideTimer()
|
||||
syncBoundsAndLevel()
|
||||
}
|
||||
|
||||
const handleMainBlur = () => {
|
||||
clearBlurHideTimer()
|
||||
blurHideTimer = setTimeout(() => {
|
||||
blurHideTimer = null
|
||||
const mainWin = options.getMainWindow()
|
||||
if (!mainWin || mainWin.isDestroyed() || !mainWin.isFocused()) {
|
||||
if (indicatorWin && !indicatorWin.isDestroyed() && indicatorWin.isVisible()) {
|
||||
indicatorWin.hide()
|
||||
}
|
||||
}
|
||||
}, 60)
|
||||
}
|
||||
|
||||
const pushTick = (elapsedMs: number) => {
|
||||
if (!indicatorWin || indicatorWin.isDestroyed() || indicatorWin.webContents.isDestroyed()) return
|
||||
indicatorWin.webContents.send('planet:recording-indicator-tick', formatRecordingDuration(elapsedMs))
|
||||
}
|
||||
|
||||
const unbindMainWindowListeners = () => {
|
||||
clearBlurHideTimer()
|
||||
if (!boundMainWin || boundMainWin.isDestroyed()) {
|
||||
boundMainWin = null
|
||||
return
|
||||
}
|
||||
boundMainWin.removeListener('move', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('resize', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('maximize', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('unmaximize', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('minimize', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('restore', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('enter-full-screen', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('leave-full-screen', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('show', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('hide', syncBoundsAndLevel)
|
||||
boundMainWin.removeListener('focus', handleMainFocus)
|
||||
boundMainWin.removeListener('blur', handleMainBlur)
|
||||
boundMainWin.removeListener('closed', hide)
|
||||
boundMainWin = null
|
||||
}
|
||||
|
||||
const bindMainWindowListeners = (mainWin: BrowserWindow) => {
|
||||
if (boundMainWin === mainWin) return
|
||||
unbindMainWindowListeners()
|
||||
boundMainWin = mainWin
|
||||
mainWin.on('move', syncBoundsAndLevel)
|
||||
mainWin.on('resize', syncBoundsAndLevel)
|
||||
mainWin.on('maximize', syncBoundsAndLevel)
|
||||
mainWin.on('unmaximize', syncBoundsAndLevel)
|
||||
mainWin.on('minimize', syncBoundsAndLevel)
|
||||
mainWin.on('restore', syncBoundsAndLevel)
|
||||
mainWin.on('enter-full-screen', syncBoundsAndLevel)
|
||||
mainWin.on('leave-full-screen', syncBoundsAndLevel)
|
||||
mainWin.on('show', syncBoundsAndLevel)
|
||||
mainWin.on('hide', syncBoundsAndLevel)
|
||||
mainWin.on('focus', handleMainFocus)
|
||||
mainWin.on('blur', handleMainBlur)
|
||||
mainWin.on('closed', hide)
|
||||
}
|
||||
|
||||
const ensureIndicatorWindow = (mainWin: BrowserWindow): BrowserWindow => {
|
||||
if (indicatorWin && !indicatorWin.isDestroyed()) {
|
||||
return indicatorWin
|
||||
}
|
||||
readyToShow = false
|
||||
const initialBounds = computeIndicatorBounds({
|
||||
contentBounds: mainWin.getContentBounds(),
|
||||
elapsedMs: lastElapsedMs,
|
||||
})
|
||||
indicatorWin = new BrowserWindow({
|
||||
...initialBounds,
|
||||
transparent: true,
|
||||
backgroundColor: '#00000000',
|
||||
frame: false,
|
||||
thickFrame: false,
|
||||
roundedCorners: false,
|
||||
resizable: false,
|
||||
movable: false,
|
||||
minimizable: false,
|
||||
maximizable: false,
|
||||
closable: false,
|
||||
focusable: false,
|
||||
skipTaskbar: true,
|
||||
hasShadow: false,
|
||||
show: false,
|
||||
webPreferences: {
|
||||
preload: options.preloadPath,
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: true,
|
||||
},
|
||||
})
|
||||
indicatorWin.setMenuBarVisibility(false)
|
||||
indicatorWin.webContents.once('did-finish-load', () => {
|
||||
if (!indicatorWin || indicatorWin.isDestroyed()) return
|
||||
void indicatorWin.webContents.setVisualZoomLevelLimits(1, 1)
|
||||
readyToShow = true
|
||||
pushTick(lastElapsedMs)
|
||||
if (visible) {
|
||||
syncBoundsAndLevel()
|
||||
}
|
||||
})
|
||||
void indicatorWin.loadURL(
|
||||
`data:text/html;charset=utf-8,${encodeURIComponent(buildRecordingIndicatorHtml(getClientLocale()))}`,
|
||||
)
|
||||
return indicatorWin
|
||||
}
|
||||
|
||||
const show = (elapsedMs = 0) => {
|
||||
if (destroyed) return
|
||||
const mainWin = options.getMainWindow()
|
||||
if (!mainWin || mainWin.isDestroyed()) return
|
||||
clearBlurHideTimer()
|
||||
visible = true
|
||||
lastElapsedMs = Math.max(0, elapsedMs)
|
||||
bindMainWindowListeners(mainWin)
|
||||
ensureIndicatorWindow(mainWin)
|
||||
pushTick(lastElapsedMs)
|
||||
syncBoundsAndLevel()
|
||||
}
|
||||
|
||||
const updateElapsed = (elapsedMs: number) => {
|
||||
lastElapsedMs = Math.max(0, elapsedMs)
|
||||
if (!visible) return
|
||||
pushTick(lastElapsedMs)
|
||||
syncBoundsAndLevel()
|
||||
}
|
||||
|
||||
function hide() {
|
||||
clearBlurHideTimer()
|
||||
visible = false
|
||||
if (indicatorWin && !indicatorWin.isDestroyed() && indicatorWin.isVisible()) {
|
||||
indicatorWin.hide()
|
||||
}
|
||||
}
|
||||
|
||||
const destroy = () => {
|
||||
destroyed = true
|
||||
visible = false
|
||||
unbindMainWindowListeners()
|
||||
if (indicatorWin && !indicatorWin.isDestroyed()) {
|
||||
indicatorWin.destroy()
|
||||
}
|
||||
indicatorWin = null
|
||||
}
|
||||
|
||||
return {
|
||||
show,
|
||||
updateElapsed,
|
||||
hide,
|
||||
destroy,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,466 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
import {
|
||||
app,
|
||||
ipcMain,
|
||||
shell,
|
||||
type BrowserWindow,
|
||||
type Event as ElectronEvent,
|
||||
type Session,
|
||||
} from 'electron'
|
||||
|
||||
import type { DesktopConfigStore } from './config'
|
||||
import { tClient } from './i18n'
|
||||
import {
|
||||
buildRecordingFilename,
|
||||
resolveRecordingExtension,
|
||||
type RecordingCursorShape,
|
||||
type RecordingState,
|
||||
type RecordingStatusSnapshot,
|
||||
} from './recording-core'
|
||||
import { createRecordingCursorOverlayController } from './recording-cursor-overlay'
|
||||
import { createRecordingIndicatorController } from './recording-indicator'
|
||||
|
||||
export interface RecordingStatusToastOptions {
|
||||
message: string
|
||||
type?: 'info' | 'success' | 'error'
|
||||
fullText?: boolean
|
||||
durationMs?: number
|
||||
actionLabel?: string
|
||||
action?: 'open-recordings-folder'
|
||||
}
|
||||
|
||||
const VALID_CURSOR_SHAPES = new Set<RecordingCursorShape>(['default', 'pointer', 'grab', 'grabbing', 'text'])
|
||||
|
||||
export interface ScreenRecorderController {
|
||||
getState: () => RecordingStatusSnapshot
|
||||
isActive: () => boolean
|
||||
startRecording: (options?: { fromMenu?: boolean }) => Promise<void>
|
||||
stopRecording: (options?: { timeoutMs?: number }) => Promise<void>
|
||||
toggleRecording: (options?: { fromMenu?: boolean }) => Promise<RecordingStatusSnapshot>
|
||||
openRecordingsFolder: () => Promise<void>
|
||||
handleWindowClose: (win: BrowserWindow, event: ElectronEvent) => void
|
||||
destroy: () => void
|
||||
}
|
||||
|
||||
export function createScreenRecorderController(options: {
|
||||
getMainWindow: () => BrowserWindow | null
|
||||
configStore: DesktopConfigStore
|
||||
session: Session
|
||||
indicatorPreloadPath: string
|
||||
cursorOverlayPreloadPath: string
|
||||
dismissMenuBar: (win: BrowserWindow | null) => void
|
||||
onStateChanged: () => void
|
||||
}): ScreenRecorderController {
|
||||
let state: RecordingState = 'idle'
|
||||
let includeAudio = options.configStore.get().recordAudio
|
||||
let hideCursor = options.configStore.get().recordHideCursor
|
||||
let activeFilePath: string | null = null
|
||||
let activeFileName: string | null = null
|
||||
let lastSavedFilePath: string | null = null
|
||||
let writeStream: fs.WriteStream | null = null
|
||||
let writeChain: Promise<void> = Promise.resolve()
|
||||
let bytesWritten = 0
|
||||
let startedAtMs = 0
|
||||
let elapsedTimer: ReturnType<typeof setInterval> | null = null
|
||||
let pendingCaptureExpiresAt = 0
|
||||
let pendingCaptureIncludeAudio = false
|
||||
let finishPromise: Promise<void> | null = null
|
||||
let resolveFinish: (() => void) | null = null
|
||||
let lastToggleAt = 0
|
||||
let forceAllowWindowClose = false
|
||||
let destroyed = false
|
||||
|
||||
const cursorOverlay = createRecordingCursorOverlayController({
|
||||
getMainWindow: options.getMainWindow,
|
||||
preloadPath: options.cursorOverlayPreloadPath,
|
||||
})
|
||||
|
||||
const indicator = createRecordingIndicatorController({
|
||||
getMainWindow: options.getMainWindow,
|
||||
preloadPath: options.indicatorPreloadPath,
|
||||
})
|
||||
|
||||
const notifyStatus = (
|
||||
messageOrOptions: string | RecordingStatusToastOptions,
|
||||
type: 'info' | 'success' | 'error' = 'info',
|
||||
) => {
|
||||
const win = options.getMainWindow()
|
||||
if (!win || win.isDestroyed() || win.webContents.isDestroyed()) return
|
||||
const payload: RecordingStatusToastOptions =
|
||||
typeof messageOrOptions === 'string'
|
||||
? { message: messageOrOptions, type }
|
||||
: { type: 'info', ...messageOrOptions }
|
||||
win.webContents.send('planet:update-status', payload)
|
||||
}
|
||||
|
||||
const resolveRecordingsDir = (): string => {
|
||||
try {
|
||||
return path.join(app.getPath('videos'), 'Planet Earth')
|
||||
} catch {
|
||||
return path.join(app.getPath('userData'), 'recordings')
|
||||
}
|
||||
}
|
||||
|
||||
const allocateOutputFile = (mimeType?: string): { filePath: string; fileName: string } => {
|
||||
const dir = resolveRecordingsDir()
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
const ext = resolveRecordingExtension(mimeType)
|
||||
const now = new Date()
|
||||
for (let suffix = 0; suffix < 100; suffix += 1) {
|
||||
const fileName = buildRecordingFilename(now, ext, suffix)
|
||||
const filePath = path.join(dir, fileName)
|
||||
if (!fs.existsSync(filePath)) {
|
||||
return { filePath, fileName }
|
||||
}
|
||||
}
|
||||
const fallbackName = buildRecordingFilename(now, ext, Math.floor(Math.random() * 10000))
|
||||
return { filePath: path.join(dir, fallbackName), fileName: fallbackName }
|
||||
}
|
||||
|
||||
const clearElapsedTimer = () => {
|
||||
if (elapsedTimer) {
|
||||
clearInterval(elapsedTimer)
|
||||
elapsedTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
const resolvePendingFinish = () => {
|
||||
const resolver = resolveFinish
|
||||
resolveFinish = null
|
||||
finishPromise = null
|
||||
resolver?.()
|
||||
}
|
||||
|
||||
const closeWriteStream = async (): Promise<{ savedPath: string | null; savedName: string | null; hadData: boolean }> => {
|
||||
const targetStream = writeStream
|
||||
const targetPath = activeFilePath
|
||||
const targetName = activeFileName
|
||||
const wroteBytes = bytesWritten
|
||||
writeStream = null
|
||||
activeFilePath = null
|
||||
activeFileName = null
|
||||
bytesWritten = 0
|
||||
|
||||
await writeChain.catch(() => {})
|
||||
if (targetStream) {
|
||||
await new Promise<void>((resolve) => {
|
||||
if (targetStream.closed || targetStream.writableEnded) {
|
||||
resolve()
|
||||
return
|
||||
}
|
||||
targetStream.once('finish', resolve)
|
||||
targetStream.once('error', () => resolve())
|
||||
targetStream.end()
|
||||
})
|
||||
}
|
||||
|
||||
if (targetPath && wroteBytes === 0) {
|
||||
try {
|
||||
if (fs.existsSync(targetPath)) {
|
||||
fs.unlinkSync(targetPath)
|
||||
}
|
||||
} catch {
|
||||
// Ignore empty file cleanup error.
|
||||
}
|
||||
return { savedPath: null, savedName: null, hadData: false }
|
||||
}
|
||||
|
||||
return { savedPath: targetPath, savedName: targetName, hadData: wroteBytes > 0 }
|
||||
}
|
||||
|
||||
const resetToIdle = () => {
|
||||
clearElapsedTimer()
|
||||
pendingCaptureExpiresAt = 0
|
||||
startedAtMs = 0
|
||||
cursorOverlay.hide()
|
||||
indicator.hide()
|
||||
state = 'idle'
|
||||
options.onStateChanged()
|
||||
resolvePendingFinish()
|
||||
}
|
||||
|
||||
const getState = (): RecordingStatusSnapshot => ({
|
||||
state,
|
||||
elapsedMs: startedAtMs > 0 && (state === 'recording' || state === 'stopping') ? Date.now() - startedAtMs : 0,
|
||||
includeAudio,
|
||||
hideCursor,
|
||||
filePath: activeFilePath ?? lastSavedFilePath,
|
||||
})
|
||||
|
||||
const isActive = () => state !== 'idle'
|
||||
|
||||
// Capture Planet Earth's mainFrame directly so external floating overlays never appear in recordings.
|
||||
options.session.setDisplayMediaRequestHandler((_request, callback) => {
|
||||
if (destroyed || Date.now() > pendingCaptureExpiresAt) {
|
||||
callback({})
|
||||
return
|
||||
}
|
||||
const win = options.getMainWindow()
|
||||
if (!win || win.isDestroyed() || win.webContents.isDestroyed()) {
|
||||
callback({})
|
||||
return
|
||||
}
|
||||
const mainFrame = win.webContents.mainFrame
|
||||
if (!mainFrame) {
|
||||
callback({})
|
||||
return
|
||||
}
|
||||
callback(
|
||||
pendingCaptureIncludeAudio
|
||||
? { video: mainFrame, audio: mainFrame, enableLocalEcho: true }
|
||||
: { video: mainFrame },
|
||||
)
|
||||
})
|
||||
|
||||
const onOpenFile = (
|
||||
_event: Electron.IpcMainInvokeEvent,
|
||||
payload: { mimeType?: string; includeAudio?: boolean; hideCursor?: boolean } = {},
|
||||
) => {
|
||||
if (destroyed || state === 'idle' || state === 'stopping') {
|
||||
throw new Error('Recording is not active')
|
||||
}
|
||||
pendingCaptureExpiresAt = 0
|
||||
includeAudio = Boolean(payload?.includeAudio)
|
||||
hideCursor = Boolean(payload?.hideCursor)
|
||||
const { filePath, fileName } = allocateOutputFile(payload?.mimeType)
|
||||
activeFilePath = filePath
|
||||
activeFileName = fileName
|
||||
bytesWritten = 0
|
||||
writeChain = Promise.resolve()
|
||||
writeStream = fs.createWriteStream(filePath)
|
||||
writeStream.on('error', (err) => {
|
||||
notifyStatus(tClient(`录屏写入失败:${err.message}`, `Recording write failed: ${err.message}`), 'error')
|
||||
})
|
||||
|
||||
startedAtMs = Date.now()
|
||||
state = 'recording'
|
||||
if (hideCursor) {
|
||||
cursorOverlay.show()
|
||||
} else {
|
||||
cursorOverlay.hide()
|
||||
}
|
||||
// Show stop indicator after cursor overlay so the clickable pill stays above the cursor layer.
|
||||
indicator.show(0)
|
||||
clearElapsedTimer()
|
||||
elapsedTimer = setInterval(() => {
|
||||
if (state === 'recording' || state === 'stopping') {
|
||||
indicator.updateElapsed(Date.now() - startedAtMs)
|
||||
}
|
||||
}, 250)
|
||||
options.onStateChanged()
|
||||
return { filePath, fileName }
|
||||
}
|
||||
|
||||
const onChunk = (_event: Electron.IpcMainEvent, rawChunk: unknown) => {
|
||||
if (!writeStream || !(rawChunk instanceof Uint8Array || Buffer.isBuffer(rawChunk))) return
|
||||
const buffer = Buffer.from(rawChunk)
|
||||
if (buffer.byteLength === 0) return
|
||||
bytesWritten += buffer.byteLength
|
||||
const targetStream = writeStream
|
||||
writeChain = writeChain.then(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
if (!targetStream || targetStream.destroyed) {
|
||||
resolve()
|
||||
return
|
||||
}
|
||||
const ok = targetStream.write(buffer, () => resolve())
|
||||
if (!ok) {
|
||||
targetStream.once('drain', resolve)
|
||||
}
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
const onCursorMove = (_event: Electron.IpcMainEvent, rawPayload: unknown) => {
|
||||
if (destroyed || !hideCursor || (state !== 'recording' && state !== 'stopping')) return
|
||||
if (!rawPayload || typeof rawPayload !== 'object') return
|
||||
const candidate = rawPayload as { visible?: unknown; x?: unknown; y?: unknown; shape?: unknown }
|
||||
const x = Number(candidate.x)
|
||||
const y = Number(candidate.y)
|
||||
if (!Number.isFinite(x) || !Number.isFinite(y)) return
|
||||
const shape: RecordingCursorShape =
|
||||
typeof candidate.shape === 'string' && VALID_CURSOR_SHAPES.has(candidate.shape as RecordingCursorShape)
|
||||
? (candidate.shape as RecordingCursorShape)
|
||||
: 'default'
|
||||
cursorOverlay.updateCursor({
|
||||
visible: Boolean(candidate.visible),
|
||||
x,
|
||||
y,
|
||||
shape,
|
||||
})
|
||||
}
|
||||
|
||||
const onFinish = async () => {
|
||||
clearElapsedTimer()
|
||||
const result = await closeWriteStream()
|
||||
if (result.savedPath && result.savedName && result.hadData) {
|
||||
lastSavedFilePath = result.savedPath
|
||||
notifyStatus({
|
||||
message: tClient(`已保存录屏:${result.savedPath}`, `Recording saved: ${result.savedPath}`),
|
||||
type: 'success',
|
||||
fullText: true,
|
||||
durationMs: 6000,
|
||||
actionLabel: tClient('打开目录', 'Open Folder'),
|
||||
action: 'open-recordings-folder',
|
||||
})
|
||||
} else if (state !== 'idle') {
|
||||
notifyStatus(tClient('录屏已停止(未采集到有效画面帧)', 'Recording stopped (no valid frames captured)'), 'info')
|
||||
}
|
||||
resetToIdle()
|
||||
return result
|
||||
}
|
||||
|
||||
const onAbort = async (_event: Electron.IpcMainInvokeEvent, payload?: { error?: string }) => {
|
||||
await closeWriteStream()
|
||||
if (payload?.error) {
|
||||
notifyStatus(tClient(`启动录屏失败:${payload.error}`, `Failed to start recording: ${payload.error}`), 'error')
|
||||
}
|
||||
resetToIdle()
|
||||
}
|
||||
|
||||
const onAudioFallback = () => {
|
||||
includeAudio = false
|
||||
notifyStatus(tClient('当前设备不支持音频录制,已切换为静音录屏', 'System audio capture unavailable; recording muted'), 'info')
|
||||
}
|
||||
|
||||
const onIndicatorStop = () => {
|
||||
void stopRecording()
|
||||
}
|
||||
|
||||
const onIpcToggle = async () => {
|
||||
return toggleRecording({ fromMenu: false })
|
||||
}
|
||||
|
||||
const onIpcOpenFolder = async () => {
|
||||
await openRecordingsFolder()
|
||||
}
|
||||
|
||||
ipcMain.handle('planet:recording-open-file', onOpenFile)
|
||||
ipcMain.on('planet:recording-chunk', onChunk)
|
||||
ipcMain.on('planet:recording-cursor-move', onCursorMove)
|
||||
ipcMain.handle('planet:recording-finish', onFinish)
|
||||
ipcMain.handle('planet:recording-abort', onAbort)
|
||||
ipcMain.on('planet:recording-audio-fallback', onAudioFallback)
|
||||
ipcMain.on('planet:recording-indicator-stop', onIndicatorStop)
|
||||
ipcMain.handle('planet:recording-toggle', onIpcToggle)
|
||||
ipcMain.handle('planet:recording-open-folder', onIpcOpenFolder)
|
||||
|
||||
const startRecording = async (startOpts?: { fromMenu?: boolean }): Promise<void> => {
|
||||
if (destroyed || state !== 'idle') return
|
||||
const win = options.getMainWindow()
|
||||
if (!win || win.isDestroyed() || win.webContents.isDestroyed()) return
|
||||
|
||||
state = 'starting'
|
||||
includeAudio = options.configStore.get().recordAudio
|
||||
hideCursor = options.configStore.get().recordHideCursor
|
||||
options.onStateChanged()
|
||||
|
||||
if (startOpts?.fromMenu) {
|
||||
options.dismissMenuBar(win)
|
||||
await new Promise((resolve) => setTimeout(resolve, 140))
|
||||
}
|
||||
if (destroyed || win.isDestroyed() || win.webContents.isDestroyed() || state !== 'starting') {
|
||||
resetToIdle()
|
||||
return
|
||||
}
|
||||
|
||||
pendingCaptureIncludeAudio = includeAudio
|
||||
pendingCaptureExpiresAt = Date.now() + 8000
|
||||
win.webContents.send('planet:recording-start', { includeAudio, hideCursor })
|
||||
}
|
||||
|
||||
const stopRecording = async (stopOpts?: { timeoutMs?: number }): Promise<void> => {
|
||||
if (destroyed || state === 'idle') return
|
||||
if (finishPromise) return finishPromise
|
||||
|
||||
const win = options.getMainWindow()
|
||||
state = 'stopping'
|
||||
options.onStateChanged()
|
||||
|
||||
if (!win || win.isDestroyed() || win.webContents.isDestroyed()) {
|
||||
await onFinish()
|
||||
return
|
||||
}
|
||||
|
||||
finishPromise = new Promise<void>((resolve) => {
|
||||
resolveFinish = resolve
|
||||
})
|
||||
const timeoutMs = stopOpts?.timeoutMs ?? 4000
|
||||
const timeoutHandle = setTimeout(() => {
|
||||
void onFinish()
|
||||
}, timeoutMs)
|
||||
|
||||
win.webContents.send('planet:recording-stop')
|
||||
await finishPromise
|
||||
clearTimeout(timeoutHandle)
|
||||
}
|
||||
|
||||
const toggleRecording = async (toggleOpts?: { fromMenu?: boolean }): Promise<RecordingStatusSnapshot> => {
|
||||
const now = Date.now()
|
||||
if (now - lastToggleAt < 250) {
|
||||
return getState()
|
||||
}
|
||||
lastToggleAt = now
|
||||
if (state === 'idle') {
|
||||
await startRecording(toggleOpts)
|
||||
} else if (state === 'recording') {
|
||||
await stopRecording()
|
||||
}
|
||||
return getState()
|
||||
}
|
||||
|
||||
const openRecordingsFolder = async (): Promise<void> => {
|
||||
const dir = resolveRecordingsDir()
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
if (lastSavedFilePath && fs.existsSync(lastSavedFilePath)) {
|
||||
shell.showItemInFolder(lastSavedFilePath)
|
||||
return
|
||||
}
|
||||
await shell.openPath(dir)
|
||||
}
|
||||
|
||||
const handleWindowClose = (win: BrowserWindow, event: ElectronEvent): void => {
|
||||
if (forceAllowWindowClose || state === 'idle') return
|
||||
event.preventDefault()
|
||||
void stopRecording({ timeoutMs: 3000 }).finally(() => {
|
||||
forceAllowWindowClose = true
|
||||
if (!win.isDestroyed()) {
|
||||
win.close()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const destroy = () => {
|
||||
if (destroyed) return
|
||||
destroyed = true
|
||||
clearElapsedTimer()
|
||||
pendingCaptureExpiresAt = 0
|
||||
void closeWriteStream()
|
||||
cursorOverlay.destroy()
|
||||
indicator.destroy()
|
||||
ipcMain.removeHandler('planet:recording-open-file')
|
||||
ipcMain.removeListener('planet:recording-chunk', onChunk)
|
||||
ipcMain.removeListener('planet:recording-cursor-move', onCursorMove)
|
||||
ipcMain.removeHandler('planet:recording-finish')
|
||||
ipcMain.removeHandler('planet:recording-abort')
|
||||
ipcMain.removeListener('planet:recording-audio-fallback', onAudioFallback)
|
||||
ipcMain.removeListener('planet:recording-indicator-stop', onIndicatorStop)
|
||||
ipcMain.removeHandler('planet:recording-toggle')
|
||||
ipcMain.removeHandler('planet:recording-open-folder')
|
||||
resolvePendingFinish()
|
||||
}
|
||||
|
||||
return {
|
||||
getState,
|
||||
isActive,
|
||||
startRecording,
|
||||
stopRecording,
|
||||
toggleRecording,
|
||||
openRecordingsFolder,
|
||||
handleWindowClose,
|
||||
destroy,
|
||||
}
|
||||
}
|
||||
+27
-10
@@ -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,
|
||||
@@ -180,6 +181,7 @@ export function createMainWindow(options: {
|
||||
iconPath: string
|
||||
userDataDir: string
|
||||
configStore: DesktopConfigStore
|
||||
onToggleRecording?: () => void
|
||||
}): BrowserWindow {
|
||||
nativeTheme.themeSource = 'dark'
|
||||
|
||||
@@ -266,6 +268,21 @@ export function createMainWindow(options: {
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
input.type === 'keyDown' &&
|
||||
!input.isAutoRepeat &&
|
||||
input.control &&
|
||||
input.shift &&
|
||||
!input.alt &&
|
||||
!input.meta &&
|
||||
input.key.toLowerCase() === 'f9'
|
||||
) {
|
||||
altTracker.reset()
|
||||
event.preventDefault()
|
||||
options.onToggleRecording?.()
|
||||
return
|
||||
}
|
||||
|
||||
const action = altTracker.handleInput(input)
|
||||
if (action === 'toggle') {
|
||||
event.preventDefault()
|
||||
@@ -480,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,
|
||||
@@ -493,7 +510,7 @@ export function openServerSettingsDialog(
|
||||
value.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>')
|
||||
|
||||
const html = `<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<html lang="${getClientLocale()}">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<style>
|
||||
@@ -512,23 +529,23 @@ export function openServerSettingsDialog(
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h2>服务端连接配置 / Server Connection</h2>
|
||||
<h2>${tClient('服务器连接设置', 'Server Connection Settings')}</h2>
|
||||
<form id="cfg">
|
||||
<label>后端服务地址 (Backend API URL)
|
||||
<label>${tClient('服务器地址', 'Backend API URL')}
|
||||
<input name="backendUrl" type="url" required value="${escapeAttr(current.backendUrl)}">
|
||||
</label>
|
||||
<label>运维控制台地址 (Admin Console URL)
|
||||
<label>${tClient('管理控制台地址', 'Admin Console URL')}
|
||||
<input name="adminUrl" type="url" required value="${escapeAttr(current.adminUrl)}">
|
||||
</label>
|
||||
<label>本地动捕 WebSocket (Motion Agent WS URL)
|
||||
<label>${tClient('动捕服务地址', 'Motion Service WS URL')}
|
||||
<input name="motionWsUrl" type="text" required value="${escapeAttr(current.motionWsUrl)}">
|
||||
</label>
|
||||
<div id="err" class="error" aria-live="polite"></div>
|
||||
<div class="actions">
|
||||
<button type="button" id="defaults">恢复默认 / Defaults</button>
|
||||
<button type="button" id="defaults">${tClient('恢复默认', 'Reset Defaults')}</button>
|
||||
<div class="actions-right">
|
||||
<button type="button" id="cancel">取消 / Cancel</button>
|
||||
<button type="submit" class="primary">保存并重连 / Save</button>
|
||||
<button type="button" id="cancel">${tClient('取消', 'Cancel')}</button>
|
||||
<button type="submit" class="primary">${tClient('保存并重连', 'Save & Reconnect')}</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -562,7 +579,7 @@ export function openServerSettingsDialog(
|
||||
!isValidUrl(adminUrl, ['http:', 'https:']) ||
|
||||
!isValidUrl(motionWsUrl, ['ws:', 'wss:'])
|
||||
) {
|
||||
errEl.textContent = '请输入有效地址 (http/https 与 ws/wss) / Enter valid URLs.';
|
||||
errEl.textContent = ${JSON.stringify(tClient('请输入有效的服务器地址(支持 http/https 与 ws/wss)。', 'Enter valid URLs (http/https and ws/wss).'))};
|
||||
return;
|
||||
}
|
||||
const q = new URLSearchParams({ backendUrl, adminUrl, motionWsUrl });
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { contextBridge, ipcRenderer } from 'electron'
|
||||
|
||||
import { startDesktopLowFpsWatcher } from './fps-watcher'
|
||||
import { initDesktopScreenRecorder, openDesktopRecordingsFolder, toggleDesktopRecording } from './screen-recorder'
|
||||
import { createDesktopSplashController, type SplashTheme } from './splash'
|
||||
|
||||
interface PreloadRuntimeConfig {
|
||||
@@ -72,6 +73,10 @@ if (
|
||||
})
|
||||
}
|
||||
|
||||
if (!runtimeConfig.headlessSmoke) {
|
||||
initDesktopScreenRecorder()
|
||||
}
|
||||
|
||||
contextBridge.exposeInMainWorld('__PLANET_RUNTIME_CONFIG__', runtimeConfig)
|
||||
|
||||
contextBridge.exposeInMainWorld('planetDesktop', {
|
||||
@@ -93,8 +98,12 @@ contextBridge.exposeInMainWorld('planetDesktop', {
|
||||
replaySplash: (theme?: SplashTheme) => {
|
||||
splashController.replay(theme)
|
||||
},
|
||||
toggleRecording: () => toggleDesktopRecording(),
|
||||
openRecordingsFolder: () => openDesktopRecordingsFolder(),
|
||||
checkForUpdates: () => ipcRenderer.invoke('planet:check-for-updates') as Promise<void>,
|
||||
getVersionInfo: () => ipcRenderer.invoke('planet:get-version-info'),
|
||||
getEarthSessionToken: (opts?: { forceRefresh?: boolean }) =>
|
||||
ipcRenderer.invoke('planet:get-earth-session-token', opts) as Promise<string | null>,
|
||||
})
|
||||
|
||||
ipcRenderer.on('planet:visibility', (_event, detail) => {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { contextBridge, ipcRenderer } from 'electron'
|
||||
|
||||
import type { RecordingCursorPayload } from '../main/recording-core'
|
||||
|
||||
contextBridge.exposeInMainWorld('planetRecordingCursor', {
|
||||
onUpdate: (callback: (payload: RecordingCursorPayload) => void) => {
|
||||
const listener = (_event: Electron.IpcRendererEvent, payload: unknown) => {
|
||||
if (payload && typeof payload === 'object') {
|
||||
callback(payload as RecordingCursorPayload)
|
||||
}
|
||||
}
|
||||
ipcRenderer.on('planet:recording-cursor-update', listener)
|
||||
return () => {
|
||||
ipcRenderer.removeListener('planet:recording-cursor-update', listener)
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,18 @@
|
||||
import { contextBridge, ipcRenderer } from 'electron'
|
||||
|
||||
contextBridge.exposeInMainWorld('planetRecordingIndicator', {
|
||||
onTick: (callback: (formattedElapsed: string) => void) => {
|
||||
const listener = (_event: Electron.IpcRendererEvent, formatted: unknown) => {
|
||||
if (typeof formatted === 'string') {
|
||||
callback(formatted)
|
||||
}
|
||||
}
|
||||
ipcRenderer.on('planet:recording-indicator-tick', listener)
|
||||
return () => {
|
||||
ipcRenderer.removeListener('planet:recording-indicator-tick', listener)
|
||||
}
|
||||
},
|
||||
requestStop: () => {
|
||||
ipcRenderer.send('planet:recording-indicator-stop')
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,324 @@
|
||||
import { ipcRenderer } from 'electron'
|
||||
|
||||
import {
|
||||
pickSupportedRecordingMimeTypes,
|
||||
type RecordingCursorPayload,
|
||||
type RecordingCursorShape,
|
||||
type RecordingStatusSnapshot,
|
||||
} from '../main/recording-core'
|
||||
|
||||
interface ActiveCaptureSession {
|
||||
stream: MediaStream
|
||||
recorder: MediaRecorder
|
||||
mimeType: string
|
||||
includeAudio: boolean
|
||||
hideCursor: boolean
|
||||
pendingChunkWrites: Set<Promise<void>>
|
||||
stoppedByRenderer: boolean
|
||||
}
|
||||
|
||||
const HIDE_CURSOR_STYLE_ID = 'planet-recording-hide-cursor-style'
|
||||
const HIDE_CURSOR_CLASS = 'planet-recording-hide-cursor'
|
||||
|
||||
function chooseSupportedMimeType(includeAudio: boolean): string {
|
||||
if (typeof MediaRecorder === 'undefined' || typeof MediaRecorder.isTypeSupported !== 'function') {
|
||||
return ''
|
||||
}
|
||||
for (const candidate of pickSupportedRecordingMimeTypes(includeAudio)) {
|
||||
if (MediaRecorder.isTypeSupported(candidate)) {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
function resolveCursorShape(target: EventTarget | null, buttons: number): RecordingCursorShape {
|
||||
if (!(target instanceof Element)) return 'default'
|
||||
if ((buttons & 1) !== 0 && target.tagName === 'CANVAS') {
|
||||
return 'grabbing'
|
||||
}
|
||||
if (
|
||||
target.closest(
|
||||
'input:not([type="checkbox"]):not([type="radio"]):not([type="range"]), textarea, [contenteditable="true"]',
|
||||
)
|
||||
) {
|
||||
return 'text'
|
||||
}
|
||||
if (
|
||||
target.closest(
|
||||
'a, button, summary, select, label, [role="button"], [tabindex], .hud-panel__action, .news-region-card__header',
|
||||
)
|
||||
) {
|
||||
return 'pointer'
|
||||
}
|
||||
return 'default'
|
||||
}
|
||||
|
||||
export function initDesktopScreenRecorder(): void {
|
||||
let activeSession: ActiveCaptureSession | null = null
|
||||
let stoppingPromise: Promise<void> | null = null
|
||||
let cursorMaskActive = false
|
||||
let pendingCursorPayload: RecordingCursorPayload | null = null
|
||||
let cursorRafId: number | null = null
|
||||
|
||||
const sendCursorPayload = (payload: RecordingCursorPayload) => {
|
||||
ipcRenderer.send('planet:recording-cursor-move', payload)
|
||||
}
|
||||
|
||||
const flushCursorPayload = () => {
|
||||
cursorRafId = null
|
||||
if (!cursorMaskActive || !pendingCursorPayload) return
|
||||
const next = pendingCursorPayload
|
||||
pendingCursorPayload = null
|
||||
sendCursorPayload(next)
|
||||
}
|
||||
|
||||
const scheduleCursorPayload = (payload: RecordingCursorPayload) => {
|
||||
if (!cursorMaskActive) return
|
||||
pendingCursorPayload = payload
|
||||
if (cursorRafId === null) {
|
||||
cursorRafId = window.requestAnimationFrame(flushCursorPayload)
|
||||
}
|
||||
}
|
||||
|
||||
const onPointerMove = (event: PointerEvent) => {
|
||||
scheduleCursorPayload({
|
||||
visible: true,
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
shape: resolveCursorShape(event.target, event.buttons),
|
||||
})
|
||||
}
|
||||
|
||||
const onPointerButton = (event: PointerEvent) => {
|
||||
if (!cursorMaskActive) return
|
||||
sendCursorPayload({
|
||||
visible: true,
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
shape: resolveCursorShape(event.target, event.buttons),
|
||||
})
|
||||
}
|
||||
|
||||
const onPointerHide = () => {
|
||||
if (cursorRafId !== null) {
|
||||
window.cancelAnimationFrame(cursorRafId)
|
||||
cursorRafId = null
|
||||
}
|
||||
pendingCursorPayload = null
|
||||
sendCursorPayload({ visible: false, x: 0, y: 0, shape: 'default' })
|
||||
}
|
||||
|
||||
const setCursorMaskEnabled = (enabled: boolean) => {
|
||||
const root = document.documentElement
|
||||
if (!root) return
|
||||
if (enabled === cursorMaskActive) return
|
||||
cursorMaskActive = enabled
|
||||
if (enabled) {
|
||||
if (!document.getElementById(HIDE_CURSOR_STYLE_ID)) {
|
||||
const styleEl = document.createElement('style')
|
||||
styleEl.id = HIDE_CURSOR_STYLE_ID
|
||||
styleEl.textContent = `html.${HIDE_CURSOR_CLASS}, html.${HIDE_CURSOR_CLASS} * { cursor: none !important; }`
|
||||
;(document.head || root).appendChild(styleEl)
|
||||
}
|
||||
root.classList.add(HIDE_CURSOR_CLASS)
|
||||
root.addEventListener('pointermove', onPointerMove, { capture: true, passive: true })
|
||||
root.addEventListener('pointerdown', onPointerButton, { capture: true, passive: true })
|
||||
root.addEventListener('pointerup', onPointerButton, { capture: true, passive: true })
|
||||
root.addEventListener('pointerleave', onPointerHide, { capture: true, passive: true })
|
||||
window.addEventListener('blur', onPointerHide)
|
||||
} else {
|
||||
root.classList.remove(HIDE_CURSOR_CLASS)
|
||||
root.removeEventListener('pointermove', onPointerMove, { capture: true })
|
||||
root.removeEventListener('pointerdown', onPointerButton, { capture: true })
|
||||
root.removeEventListener('pointerup', onPointerButton, { capture: true })
|
||||
root.removeEventListener('pointerleave', onPointerHide, { capture: true })
|
||||
window.removeEventListener('blur', onPointerHide)
|
||||
onPointerHide()
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('beforeunload', () => {
|
||||
setCursorMaskEnabled(false)
|
||||
})
|
||||
|
||||
const cleanupStreamTracks = (stream: MediaStream | null) => {
|
||||
if (!stream) return
|
||||
for (const track of stream.getTracks()) {
|
||||
try {
|
||||
track.stop()
|
||||
} catch {
|
||||
// Ignore already-ended track stop errors.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const finalizeActiveSession = async (reason: string): Promise<void> => {
|
||||
if (stoppingPromise) return stoppingPromise
|
||||
const session = activeSession
|
||||
if (!session) return
|
||||
|
||||
stoppingPromise = (async () => {
|
||||
try {
|
||||
if (session.recorder.state !== 'inactive') {
|
||||
await new Promise<void>((resolve) => {
|
||||
const timeout = setTimeout(resolve, 2500)
|
||||
session.recorder.addEventListener(
|
||||
'stop',
|
||||
() => {
|
||||
clearTimeout(timeout)
|
||||
resolve()
|
||||
},
|
||||
{ once: true },
|
||||
)
|
||||
try {
|
||||
session.recorder.stop()
|
||||
} catch {
|
||||
clearTimeout(timeout)
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
}
|
||||
if (session.pendingChunkWrites.size > 0) {
|
||||
await Promise.allSettled([...session.pendingChunkWrites])
|
||||
}
|
||||
await ipcRenderer.invoke('planet:recording-finish', { reason })
|
||||
} finally {
|
||||
setCursorMaskEnabled(false)
|
||||
cleanupStreamTracks(session.stream)
|
||||
if (activeSession === session) {
|
||||
activeSession = null
|
||||
}
|
||||
stoppingPromise = null
|
||||
}
|
||||
})()
|
||||
|
||||
return stoppingPromise
|
||||
}
|
||||
|
||||
ipcRenderer.on(
|
||||
'planet:recording-start',
|
||||
(_event, payload?: { includeAudio?: boolean; hideCursor?: boolean }) => {
|
||||
void (async () => {
|
||||
if (activeSession || stoppingPromise) return
|
||||
const wantAudio = Boolean(payload?.includeAudio)
|
||||
const hideCursor = Boolean(payload?.hideCursor)
|
||||
|
||||
let stream: MediaStream | null = null
|
||||
let includeAudio = wantAudio
|
||||
|
||||
try {
|
||||
const videoConstraints = { frameRate: { ideal: 60, max: 60 } } as unknown as MediaTrackConstraints
|
||||
if (wantAudio) {
|
||||
try {
|
||||
stream = await navigator.mediaDevices.getDisplayMedia({
|
||||
video: videoConstraints,
|
||||
audio: true,
|
||||
})
|
||||
if (stream.getAudioTracks().length === 0) {
|
||||
includeAudio = false
|
||||
ipcRenderer.send('planet:recording-audio-fallback')
|
||||
}
|
||||
} catch {
|
||||
includeAudio = false
|
||||
ipcRenderer.send('planet:recording-audio-fallback')
|
||||
stream = await navigator.mediaDevices.getDisplayMedia({
|
||||
video: videoConstraints,
|
||||
audio: false,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
stream = await navigator.mediaDevices.getDisplayMedia({
|
||||
video: videoConstraints,
|
||||
audio: false,
|
||||
})
|
||||
}
|
||||
|
||||
if (!stream) {
|
||||
throw new Error('Display capture returned no stream')
|
||||
}
|
||||
|
||||
const mimeType = chooseSupportedMimeType(includeAudio && stream.getAudioTracks().length > 0)
|
||||
const recorderOptions: MediaRecorderOptions = {
|
||||
videoBitsPerSecond: 8_000_000,
|
||||
...(includeAudio ? { audioBitsPerSecond: 128_000 } : {}),
|
||||
...(mimeType ? { mimeType } : {}),
|
||||
}
|
||||
|
||||
await ipcRenderer.invoke('planet:recording-open-file', {
|
||||
mimeType,
|
||||
includeAudio,
|
||||
hideCursor,
|
||||
})
|
||||
|
||||
setCursorMaskEnabled(hideCursor)
|
||||
|
||||
const recorder = new MediaRecorder(stream, recorderOptions)
|
||||
const pendingChunkWrites = new Set<Promise<void>>()
|
||||
const session: ActiveCaptureSession = {
|
||||
stream,
|
||||
recorder,
|
||||
mimeType: recorder.mimeType || mimeType,
|
||||
includeAudio,
|
||||
hideCursor,
|
||||
pendingChunkWrites,
|
||||
stoppedByRenderer: false,
|
||||
}
|
||||
activeSession = session
|
||||
|
||||
recorder.addEventListener('dataavailable', (event: BlobEvent) => {
|
||||
if (!event.data || event.data.size === 0) return
|
||||
const task = event.data
|
||||
.arrayBuffer()
|
||||
.then((buffer) => {
|
||||
ipcRenderer.send('planet:recording-chunk', new Uint8Array(buffer))
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
pendingChunkWrites.delete(task)
|
||||
})
|
||||
pendingChunkWrites.add(task)
|
||||
})
|
||||
|
||||
const [videoTrack] = stream.getVideoTracks()
|
||||
if (videoTrack) {
|
||||
videoTrack.addEventListener(
|
||||
'ended',
|
||||
() => {
|
||||
if (activeSession === session && !session.stoppedByRenderer) {
|
||||
session.stoppedByRenderer = true
|
||||
void finalizeActiveSession('track-ended')
|
||||
}
|
||||
},
|
||||
{ once: true },
|
||||
)
|
||||
}
|
||||
|
||||
recorder.start(1000)
|
||||
} catch (error) {
|
||||
setCursorMaskEnabled(false)
|
||||
cleanupStreamTracks(stream)
|
||||
activeSession = null
|
||||
await ipcRenderer.invoke('planet:recording-abort', {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
}
|
||||
})()
|
||||
},
|
||||
)
|
||||
|
||||
ipcRenderer.on('planet:recording-stop', () => {
|
||||
if (activeSession) {
|
||||
activeSession.stoppedByRenderer = true
|
||||
}
|
||||
void finalizeActiveSession('requested-stop')
|
||||
})
|
||||
}
|
||||
|
||||
export async function toggleDesktopRecording(): Promise<RecordingStatusSnapshot> {
|
||||
return (await ipcRenderer.invoke('planet:recording-toggle')) as RecordingStatusSnapshot
|
||||
}
|
||||
|
||||
export async function openDesktopRecordingsFolder(): Promise<void> {
|
||||
await ipcRenderer.invoke('planet:recording-open-folder')
|
||||
}
|
||||
@@ -752,6 +752,7 @@ export function createDesktopSplashController(options: {
|
||||
const styleEl = document.createElement('style')
|
||||
styleEl.textContent = SPLASH_CSS
|
||||
|
||||
const isEn = getLocaleIsEn()
|
||||
const root = document.createElement('div')
|
||||
root.className = 'splash-root'
|
||||
root.dataset.theme = activeTheme
|
||||
@@ -760,16 +761,16 @@ export function createDesktopSplashController(options: {
|
||||
<header class="splash-topbar">
|
||||
<div class="splash-telemetry-tag">
|
||||
<span class="splash-telemetry-dot"></span>
|
||||
<span>PLANET EARTH // HOLOGRAPHIC PERCEPTION KERNEL</span>
|
||||
<span>${isEn ? 'INTELLIGENT PLANET // 3D EARTH KERNEL' : '智能星球 // 三维地球核心'}</span>
|
||||
</div>
|
||||
<div class="splash-controls">
|
||||
<button type="button" class="splash-skip" data-splash-skip title="跳过启动动画 (Esc)">ESC 跳过</button>
|
||||
<button type="button" class="splash-skip" data-splash-skip title="${isEn ? 'Skip splash screen (Esc)' : '跳过启动动画 (Esc)'}">${isEn ? 'ESC SKIP' : 'ESC 跳过'}</button>
|
||||
</div>
|
||||
</header>
|
||||
<footer class="splash-footer">
|
||||
<div class="splash-brand-head">
|
||||
<h1 class="splash-title">智能星球计划</h1>
|
||||
<div class="splash-subtitle">INTELLIGENT PLANET PROGRAM</div>
|
||||
<h1 class="splash-title">${isEn ? 'INTELLIGENT PLANET' : '智能星球计划'}</h1>
|
||||
${isEn ? '' : '<div class="splash-subtitle">全球基础设施与空间态势引擎</div>'}
|
||||
</div>
|
||||
<div class="splash-progress-box">
|
||||
<div class="splash-progress-meta">
|
||||
@@ -781,12 +782,11 @@ export function createDesktopSplashController(options: {
|
||||
</div>
|
||||
</div>
|
||||
<div class="splash-presenter">
|
||||
<img class="splash-zju-emblem" src="planet://earth/earth/assets/brand/zju-emblem.png" alt="浙江大学">
|
||||
<img class="splash-zju-emblem" src="planet://earth/earth/assets/brand/zju-emblem.png" alt="${isEn ? 'Zhejiang University' : '浙江大学'}">
|
||||
<div class="splash-presenter-divider" aria-hidden="true"></div>
|
||||
<div class="splash-presenter-copy">
|
||||
<span class="splash-presenter-kicker">PRESENTED BY</span>
|
||||
<span class="splash-presenter-zh">临空智能媒体研究院</span>
|
||||
<span class="splash-presenter-en">Intelligent Media Institute</span>
|
||||
<span class="splash-presenter-kicker">${isEn ? 'PRESENTED BY' : '联合研制'}</span>
|
||||
<span class="${isEn ? 'splash-presenter-en' : 'splash-presenter-zh'}">${isEn ? 'Linkong Intelligent Media Institute' : '临空智能媒体研究院'}</span>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import crypto from 'node:crypto'
|
||||
import fs from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
|
||||
import { afterEach, describe, expect, test } from 'bun:test'
|
||||
|
||||
import { createEarthDesktopAuth } from '../src/main/earth-auth'
|
||||
import { createEarthProtocolHandler } from '../src/main/protocol-core'
|
||||
|
||||
const tempDirs: string[] = []
|
||||
|
||||
function makeBundleDir(): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'planet-earth-auth-test-'))
|
||||
tempDirs.push(dir)
|
||||
fs.writeFileSync(path.join(dir, 'index.html'), '<html></html>')
|
||||
return dir
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
while (tempDirs.length > 0) {
|
||||
const dir = tempDirs.pop()!
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
describe('createEarthDesktopAuth', () => {
|
||||
test('mints, caches, signs HMAC handshake, and clears on backend change', async () => {
|
||||
let backendUrl = 'https://rclaw.top'
|
||||
let now = 1_700_000_000_000
|
||||
const calls: Array<{ url: string; headers: Headers; body: string }> = []
|
||||
let counter = 0
|
||||
|
||||
const auth = createEarthDesktopAuth({
|
||||
getBackendUrl: () => backendUrl,
|
||||
getAppVersion: () => '0.80.3',
|
||||
handshakeSecret: 'super-secret-handshake',
|
||||
nowMs: () => now,
|
||||
fetchImpl: async (input, init) => {
|
||||
counter += 1
|
||||
calls.push({
|
||||
url: String(input),
|
||||
headers: new Headers(init?.headers),
|
||||
body: String(init?.body || ''),
|
||||
})
|
||||
return new Response(
|
||||
JSON.stringify({ token: `desktop-tok-${counter}`, expires_in: 1800 }),
|
||||
{ status: 200, headers: { 'Content-Type': 'application/json' } },
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
const tok1 = await auth.getToken()
|
||||
const tok2 = await auth.getToken()
|
||||
expect(tok1).toBe('desktop-tok-1')
|
||||
expect(tok2).toBe('desktop-tok-1')
|
||||
expect(calls).toHaveLength(1)
|
||||
|
||||
const first = calls[0]!
|
||||
expect(first.url).toBe('https://rclaw.top/api/v1/auth/earth-session')
|
||||
expect(JSON.parse(first.body)).toEqual({ client_type: 'desktop' })
|
||||
expect(first.headers.get('x-planet-client')).toBe('planet-earth-desktop/0.80.3')
|
||||
const ts = first.headers.get('x-planet-client-timestamp')!
|
||||
const nonce = first.headers.get('x-planet-client-nonce')!
|
||||
const sig = first.headers.get('x-planet-client-signature')!
|
||||
const expectedSig = crypto
|
||||
.createHmac('sha256', 'super-secret-handshake')
|
||||
.update(`${ts}.${nonce}.planet-earth-desktop/0.80.3`)
|
||||
.digest('hex')
|
||||
expect(sig).toBe(expectedSig)
|
||||
|
||||
// Near expiration triggers refresh
|
||||
now += 1700 * 1000
|
||||
const tok3 = await auth.getToken()
|
||||
expect(tok3).toBe('desktop-tok-2')
|
||||
expect(calls).toHaveLength(2)
|
||||
|
||||
// Backend URL switch clears cache
|
||||
backendUrl = 'https://other.rclaw.top'
|
||||
const tok4 = await auth.getToken()
|
||||
expect(tok4).toBe('desktop-tok-3')
|
||||
expect(calls[2]!.url).toBe('https://other.rclaw.top/api/v1/auth/earth-session')
|
||||
})
|
||||
|
||||
test('protocol handler injects X-Planet-Earth-Token and refreshes once on 401', async () => {
|
||||
const bundleRoot = makeBundleDir()
|
||||
let currentToken = 'tok-stale'
|
||||
let refreshCalls = 0
|
||||
const upstreamTokens: Array<string | null> = []
|
||||
|
||||
const handler = createEarthProtocolHandler({
|
||||
earthBundleRoot: bundleRoot,
|
||||
getBackendUrl: () => 'https://rclaw.top',
|
||||
getEarthAuthToken: async (opts) => {
|
||||
if (opts?.forceRefresh) {
|
||||
refreshCalls += 1
|
||||
currentToken = 'tok-fresh'
|
||||
}
|
||||
return currentToken
|
||||
},
|
||||
fetchImpl: async (_input, init) => {
|
||||
const headers = new Headers(init?.headers)
|
||||
const tok = headers.get('x-planet-earth-token')
|
||||
upstreamTokens.push(tok)
|
||||
if (tok === 'tok-stale') {
|
||||
return new Response(JSON.stringify({ detail: 'expired' }), { status: 401 })
|
||||
}
|
||||
return new Response(JSON.stringify({ ok: true }), { status: 200 })
|
||||
},
|
||||
})
|
||||
|
||||
const res = await handler(new Request('planet://earth/api/v1/visualization/geo/summary'))
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ ok: true })
|
||||
expect(refreshCalls).toBe(1)
|
||||
expect(upstreamTokens).toEqual(['tok-stale', 'tok-fresh'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,134 @@
|
||||
import fs from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
|
||||
import { afterEach, describe, expect, it } from 'bun:test'
|
||||
|
||||
import { DesktopConfigStore } from '../src/main/config'
|
||||
import {
|
||||
buildCursorOverlayHtml,
|
||||
buildRecordingFilename,
|
||||
buildRecordingIndicatorHtml,
|
||||
computeIndicatorBounds,
|
||||
formatRecordingDuration,
|
||||
pickSupportedRecordingMimeTypes,
|
||||
resolveRecordingExtension,
|
||||
} from '../src/main/recording-core'
|
||||
|
||||
const tempDirs: string[] = []
|
||||
|
||||
afterEach(() => {
|
||||
while (tempDirs.length > 0) {
|
||||
const dir = tempDirs.pop()!
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
describe('recording-core helpers & preference persistence', () => {
|
||||
it('formats durations across zero, sub-minute, multi-minute, and multi-hour boundaries', () => {
|
||||
expect(formatRecordingDuration(-500)).toBe('00:00')
|
||||
expect(formatRecordingDuration(Number.NaN)).toBe('00:00')
|
||||
expect(formatRecordingDuration(0)).toBe('00:00')
|
||||
expect(formatRecordingDuration(59_900)).toBe('00:59')
|
||||
expect(formatRecordingDuration(60_000)).toBe('01:00')
|
||||
expect(formatRecordingDuration(3_661_000)).toBe('01:01:01')
|
||||
})
|
||||
|
||||
it('builds collision-safe filenames and resolves mp4/webm extensions', () => {
|
||||
const stamp = new Date(2026, 10, 30, 14, 35, 9)
|
||||
expect(resolveRecordingExtension('video/mp4;codecs=avc1.42E01E')).toBe('mp4')
|
||||
expect(resolveRecordingExtension('video/webm;codecs=vp9')).toBe('webm')
|
||||
expect(resolveRecordingExtension(undefined)).toBe('webm')
|
||||
|
||||
expect(buildRecordingFilename(stamp, 'mp4')).toBe('Planet-Earth-20261130-143509.mp4')
|
||||
expect(buildRecordingFilename(stamp, 'mp4', 1)).toBe('Planet-Earth-20261130-143509-2.mp4')
|
||||
expect(buildRecordingFilename(stamp, 'webm', 0)).toBe('Planet-Earth-20261130-143509.webm')
|
||||
})
|
||||
|
||||
it('prioritizes MP4 H.264 MIME candidates before WebM fallbacks', () => {
|
||||
const silent = pickSupportedRecordingMimeTypes(false)
|
||||
expect(silent[0]).toContain('video/mp4')
|
||||
expect(silent.some((item) => item.includes('opus') || item.includes('mp4a'))).toBe(false)
|
||||
|
||||
const withAudio = pickSupportedRecordingMimeTypes(true)
|
||||
expect(withAudio[0]).toContain('video/mp4')
|
||||
expect(withAudio[0]).toContain('mp4a')
|
||||
expect(withAudio.some((item) => item.includes('opus'))).toBe(true)
|
||||
})
|
||||
|
||||
it('computes centered top indicator bounds inside contentBounds for landscape, portrait, and >1h timer', () => {
|
||||
const landscape = computeIndicatorBounds({
|
||||
contentBounds: { x: 100, y: 80, width: 1280, height: 800 },
|
||||
elapsedMs: 12_000,
|
||||
})
|
||||
expect(landscape.width).toBe(120)
|
||||
expect(landscape.height).toBe(36)
|
||||
expect(landscape.x).toBe(680)
|
||||
expect(landscape.y).toBe(136)
|
||||
|
||||
const longTimer = computeIndicatorBounds({
|
||||
contentBounds: { x: 0, y: 0, width: 1000, height: 700 },
|
||||
elapsedMs: 3_600_000,
|
||||
})
|
||||
expect(longTimer.width).toBe(136)
|
||||
|
||||
const tinyWindow = computeIndicatorBounds({
|
||||
contentBounds: { x: 20, y: 30, width: 110, height: 80 },
|
||||
elapsedMs: 5000,
|
||||
})
|
||||
expect(tinyWindow.x).toBeGreaterThanOrEqual(20)
|
||||
expect(tinyWindow.x + tinyWindow.width).toBeLessThanOrEqual(130)
|
||||
expect(tinyWindow.y).toBeGreaterThanOrEqual(30)
|
||||
expect(tinyWindow.y + tinyWindow.height).toBeLessThanOrEqual(110)
|
||||
})
|
||||
|
||||
it('renders transparent HUD pill HTML with blinking red dot, hover square stop morph, and click action', () => {
|
||||
const html = buildRecordingIndicatorHtml()
|
||||
expect(html).toContain('background: transparent')
|
||||
expect(html).toContain('@keyframes recPulse')
|
||||
expect(html).toContain('.rec-pill:hover .rec-glyph')
|
||||
expect(html).toContain('border-radius: 2px')
|
||||
expect(html).toContain('window.planetRecordingIndicator?.requestStop')
|
||||
expect(html).toContain('Ctrl+Shift+F9')
|
||||
expect(html).toContain('00:00')
|
||||
})
|
||||
|
||||
it('renders click-through custom cursor overlay HTML supporting all cursor shapes', () => {
|
||||
const html = buildCursorOverlayHtml()
|
||||
expect(html).toContain('background: transparent')
|
||||
expect(html).toContain('pointer-events: none')
|
||||
expect(html).toContain('cursor-svg--default')
|
||||
expect(html).toContain('cursor-svg--pointer')
|
||||
expect(html).toContain('cursor-svg--grabbing')
|
||||
expect(html).toContain('cursor-svg--text')
|
||||
expect(html).toContain('window.planetRecordingCursor?.onUpdate')
|
||||
})
|
||||
|
||||
it('persists recordAudio and recordHideCursor preferences defaulting to false', () => {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'planet-rec-cfg-'))
|
||||
tempDirs.push(tempDir)
|
||||
|
||||
const store1 = new DesktopConfigStore({
|
||||
userDataDir: tempDir,
|
||||
exeDir: tempDir,
|
||||
argv: [],
|
||||
env: {},
|
||||
})
|
||||
expect(store1.get().recordAudio).toBe(false)
|
||||
expect(store1.get().recordHideCursor).toBe(false)
|
||||
|
||||
store1.updateRecordAudio(true)
|
||||
store1.updateRecordHideCursor(true)
|
||||
expect(store1.get().recordAudio).toBe(true)
|
||||
expect(store1.get().recordHideCursor).toBe(true)
|
||||
|
||||
const store2 = new DesktopConfigStore({
|
||||
userDataDir: tempDir,
|
||||
exeDir: tempDir,
|
||||
argv: [],
|
||||
env: {},
|
||||
})
|
||||
expect(store2.get().recordAudio).toBe(true)
|
||||
expect(store2.get().recordHideCursor).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,74 @@
|
||||
# Shared backend API proxy locations included by rclaw.top and api.rclaw.top.
|
||||
# Note: FastAPI /docs, /redoc, and /openapi.json are intentionally NOT exposed publicly here.
|
||||
|
||||
location = /health {
|
||||
proxy_pass http://127.0.0.1:8000/health;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location = /health/live {
|
||||
proxy_pass http://127.0.0.1:8000/health/live;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location = /health/ready {
|
||||
proxy_pass http://127.0.0.1:8000/health/ready;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location = /api/health {
|
||||
proxy_pass http://127.0.0.1:8000/health;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location = /api {
|
||||
return 301 https://$host/api/;
|
||||
}
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://127.0.0.1:8000/api/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_connect_timeout 10s;
|
||||
proxy_send_timeout 180s;
|
||||
proxy_read_timeout 180s;
|
||||
proxy_buffering off;
|
||||
proxy_request_buffering off;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /ws {
|
||||
proxy_pass http://127.0.0.1:8000/ws;
|
||||
proxy_http_version 1.1;
|
||||
proxy_connect_timeout 10s;
|
||||
proxy_send_timeout 3600s;
|
||||
proxy_read_timeout 3600s;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /earth-brand-assets/ {
|
||||
proxy_pass http://127.0.0.1:8000/earth-brand-assets/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
# Reference host Nginx virtual hosts for Planet production (3-domain split).
|
||||
# Copy/adapt TLS certificate paths for your host before reloading Nginx.
|
||||
|
||||
# 1) Primary domain: Planet Earth desktop backend + download/doc redirects
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name rclaw.top;
|
||||
|
||||
# ssl_certificate /etc/letsencrypt/live/rclaw.top/fullchain.pem;
|
||||
# ssl_certificate_key /etc/letsencrypt/live/rclaw.top/privkey.pem;
|
||||
|
||||
location = / {
|
||||
return 302 https://gitea.rclaw.top/linkong/planet/releases/latest;
|
||||
}
|
||||
|
||||
# Human-facing documentation & Earth handoff redirect cleanly to admin.rclaw.top
|
||||
location = /docs {
|
||||
return 302 https://admin.rclaw.top/docs;
|
||||
}
|
||||
location ^~ /docs/ {
|
||||
return 302 https://admin.rclaw.top$request_uri;
|
||||
}
|
||||
location = /earth {
|
||||
return 302 https://admin.rclaw.top/earth;
|
||||
}
|
||||
|
||||
# Keep admin login, OpenAPI, and redoc off the primary public domain
|
||||
location = /admin { return 404; }
|
||||
location ^~ /admin/ { return 404; }
|
||||
location = /openapi.json { return 404; }
|
||||
location = /redoc { return 404; }
|
||||
|
||||
include /opt/planet/current/planet-api-locations.conf;
|
||||
|
||||
location / {
|
||||
return 404;
|
||||
}
|
||||
}
|
||||
|
||||
# 2) Dedicated external / UE5 API domain: pure API + WebSocket only
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name api.rclaw.top;
|
||||
|
||||
# ssl_certificate /etc/letsencrypt/live/rclaw.top/fullchain.pem;
|
||||
# ssl_certificate_key /etc/letsencrypt/live/rclaw.top/privkey.pem;
|
||||
|
||||
location = / {
|
||||
return 302 https://api.rclaw.top/health/ready;
|
||||
}
|
||||
|
||||
include /opt/planet/current/planet-api-locations.conf;
|
||||
|
||||
location / {
|
||||
return 404;
|
||||
}
|
||||
}
|
||||
|
||||
# 3) Admin Console & Gatekeeper Docs SPA (backed by frontend Nginx on 127.0.0.1:3000)
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name admin.rclaw.top;
|
||||
|
||||
# ssl_certificate /etc/letsencrypt/live/rclaw.top/fullchain.pem;
|
||||
# ssl_certificate_key /etc/letsencrypt/live/rclaw.top/privkey.pem;
|
||||
|
||||
location = / {
|
||||
return 302 https://admin.rclaw.top/admin;
|
||||
}
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:3000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,11 @@ x-backend-env: &backend-env
|
||||
HTTP_PROXY: ${HTTP_PROXY:-}
|
||||
HTTPS_PROXY: ${HTTPS_PROXY:-}
|
||||
NO_PROXY: ${NO_PROXY:-localhost,127.0.0.1,postgres,redis,backend,aiprovider,admin}
|
||||
EARTH_API_AUTH_MODE: ${EARTH_API_AUTH_MODE:-enforce}
|
||||
EARTH_SESSION_TTL_MINUTES: ${EARTH_SESSION_TTL_MINUTES:-30}
|
||||
EARTH_WEB_ALLOWED_ORIGINS: ${EARTH_WEB_ALLOWED_ORIGINS:-[]}
|
||||
EARTH_DESKTOP_HANDSHAKE_SECRET: ${EARTH_DESKTOP_HANDSHAKE_SECRET:-}
|
||||
TURNSTILE_SECRET_KEY: ${TURNSTILE_SECRET_KEY:-}
|
||||
|
||||
services:
|
||||
postgres:
|
||||
|
||||
@@ -8,6 +8,38 @@ This project follows the repository versioning rule:
|
||||
- `improvement` -> `+0.0.1`(bugfix + 小功能混合)
|
||||
- `bugfix` -> `+0.0.1`
|
||||
|
||||
## [0.82.0] — 2026-12-01
|
||||
|
||||
Released: 2026-12-01
|
||||
|
||||
### Highlights
|
||||
|
||||
- **AI 参谋 3 层工作流自进化与元进化系统**: 引入 Tier-0 不可变宪法安全内核(`validate_evolution_patch`)、可自举元工作流 `meta.workflow_evolver`(单层递归锁防止无限自改)、Playground 👍/👎 用户反馈与模型/耗时遥测采集、5 次运行金丝雀自动回滚、Fixture A/B 离线评测与运行反刍孵化;支持在工作流画布通过 `自进化策略` 与 `调优` 面板管理自动/半自动优化。
|
||||
- **多模态 Playground 与工作流绑定**: 新增 Playground 附件上传与运行时上下文注入、DAG 执行器与 `ai_workflows.bindings` 地球交互绑定。
|
||||
- **Electron 客户端增强与国际化**: 升级桌面端无边框 `mainFrame` 录屏与指示浮窗、GPU 监控、热更新检查及主进程中英文国际化(`client/src/main/i18n.ts`)。
|
||||
- **AI Provider 模型目录与全量 UI / 文档升级**: AI Provider 支持模型聚合目录排序/折叠/刷新,升级地球界面与管理台中英文 UI,归档近期计划至 `docs/plans/` 并为 `README.md` 增加可渲染 Mermaid 架构图与自进化架构说明。
|
||||
|
||||
### Added / Changed
|
||||
|
||||
- Backend: `workflow_registry.py`、`workflow_evolver.py`、`dag_executor.py`、`stream_turn.py`、`ai_workflows.py`、`0006_add_ai_workflow_bindings.py`
|
||||
- Admin & Earth: `AdvisorPlayground.tsx`、`AdvisorRuns.tsx`、`AdvisorWorkflows.tsx`、`workflow-bindings.js`、地球面板与全量 i18n 审计修复
|
||||
- Desktop Client: `recording-core.ts`、`screen-recorder.ts`、`gpu-monitor.ts`、`hot-updater.ts`、`window.ts`、`i18n.ts`
|
||||
- Docs: 更新 `README.md` Mermaid 架构图、`docs/plans/` 与中英文技术文档
|
||||
|
||||
---
|
||||
|
||||
## [0.81.0] — 2026-11-30
|
||||
|
||||
Released: 2026-11-30
|
||||
|
||||
### Highlights
|
||||
|
||||
- Admin restructures AI modules into **AI 参谋** (`/advisor/playground` pure-chat workbench + client-owned `planet.earth_context.v1` local context drawer, `/advisor/workflows` `@xyflow/react` 9-workflow visual studio + AI Diff auto-tuning + rollback, `/advisor/runs` trace audit) while consolidating alerts & BGP telemetry into **运维与配置 → 告警与观测** (`/ops/monitoring`) and scoping `/ai` to model/tool infrastructure.
|
||||
- Backend & `aiprovider` introduce protocol-level Tool-Calling (`tools`, `tool_choice`, `response_format`, `native_web_search`, structured `context` JSON serialization) backing an L0–L4 controlled Location Agent (BuildsUpon inheritance, ROR hyperscaler filter, async Wikidata P625 & PeeringDB `/api/fac` lookups, 4-step URL/search/geocode verification, and terminal `undisclosed`/`multi_site`/`anonymous` persistence).
|
||||
- Enforced anti-scraping session protection with zero-login Web/Electron Earth access, scoped permanent `X-API-Key` issuance for UE5/partners, curated `/api/v1/openapi-external.json`, Electron screen recording (`CmdOrCtrl+Shift+F9`, audio & hide-cursor/custom cursor overlay), keyless aggregator model catalog MRU sorting, compute `site_type` colors, and satellite compression/comet-trail/twinkle controls.
|
||||
|
||||
---
|
||||
|
||||
## [0.80.3] — 2026-11-30
|
||||
|
||||
Released: 2026-11-30
|
||||
|
||||
+3
-2
@@ -65,10 +65,10 @@ git diff --unified=0 HEAD -- <path>
|
||||
| Purpose | Command |
|
||||
| --- | --- |
|
||||
| First setup | `./planet.sh init` |
|
||||
| Start local stack | `./planet.sh start` |
|
||||
| Start local stack | `./planet.sh start` (Vite HMR frontend on `:3000`) |
|
||||
| Start with LAN access | `./planet.sh start --allow-lan` |
|
||||
| Restart all services | `./planet.sh restart` |
|
||||
| Restart one area | `./planet.sh restart -b`, `-f`, `-a`, or `-d` |
|
||||
| Restart one area | `./planet.sh restart -b`, `-f` (Vite HMR), `-a`, or `-d` |
|
||||
| Health check | `./planet.sh health` |
|
||||
| Logs | `./planet.sh log`, `./planet.sh log -b`, `-f`, `-a`, or `-m` |
|
||||
| Create local user | `./planet.sh createuser` |
|
||||
@@ -272,6 +272,7 @@ modify the host Docker environment.
|
||||
- Do not replace Bun with npm, pnpm, or yarn.
|
||||
- Do not migrate CI from `.gitea/workflows/` to `.github/workflows/`.
|
||||
- Do not rewrite `planet.sh` lifecycle behavior as a parallel script.
|
||||
- Do not start or rebuild the static Nginx `planet_admin` container (`./planet.sh admin ...`) for routine local development; use the Vite HMR dev server (`./planet.sh start` / `./planet.sh restart -f`) unless the user explicitly asks to simulate production locally.
|
||||
- Do not run `./planet.sh destroy` unless explicitly requested.
|
||||
- Do not commit `.env`, secrets, private keys, logs, or generated build output.
|
||||
- Do not add external integrations, hooks, or new dependency managers just to
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
# Lightweight Agent Orchestrator and WebSearch Evidence Plan
|
||||
|
||||
> [!NOTE]
|
||||
> 本计划的编排与工具调用演进部分已随 [ai-advisor-workflow-and-location-agent-plan.md](/home/ray/dev/linkong/planet/docs/plans/ai-advisor-workflow-and-location-agent-plan.md) 落地实现(随 `v0.81.0` 发布):`aiprovider` 保留纯协议适配并新增原生 `tools` / `response_format` 透传,未知设施位置解析由后端 4 步受控 Tool-Calling Agent 与工作流注册表执行,全量运行记录持久化在 `workflow_runs`。
|
||||
|
||||
## Overview
|
||||
|
||||
Planet should not turn `aiprovider` into a general-purpose agent runtime.
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
# AI 参谋工作流可视化编排、客户端上下文与受控位置 Agent 方案
|
||||
|
||||
> 状态:已落地实现并随 `v0.81.0` 发布。本文档统一并取代早期 [frontend-ai-playground-development-plan.md](/home/ray/dev/linkong/planet/docs/plans/frontend-ai-playground-development-plan.md)、[ai-prompt-settings-task-registry-plan.md](/home/ray/dev/linkong/planet/docs/plans/ai-prompt-settings-task-registry-plan.md) 与 [agents-light-orchestrator-websearch-plan.md](/home/ray/dev/linkong/planet/docs/plans/agents-light-orchestrator-websearch-plan.md)。
|
||||
|
||||
## 1. 目标与边界
|
||||
|
||||
1. **Admin 菜单收口(去测试化、工作流与运维分离)**:
|
||||
- 合并原 `专题观测`(`/bgp`)与 `告警与研判`(`/alerts/*`)为统一 `运维与配置 → 告警与观测`(`/ops/monitoring`),专注原始告警、BGP 事故/异常/事件与采集器健康度。
|
||||
- 新增独立顶级分组 `AI 参谋`(`advisor`),包含:
|
||||
- `/advisor/playground`:纯净对话调试台(支持通用默认工作流、斜杠简报/定位指令、本地地球上下文抽屉)。
|
||||
- `/advisor/workflows`:基于 `@xyflow/react` 的可视化工作流与节点管理画布。
|
||||
- `/advisor/runs`:工作流运行记录与轨迹审计。
|
||||
- `/ai` 收缩为纯粹的 `AI 基础设施`(`模型供应商` 与 `工具调用`),旧路由 `/bgp`、`/alerts/*`、`/ai/prompts`、`/ai/playground` 以及旧 `prompts` / `playground` 参数自动重定向。
|
||||
2. **客户端自持地球上下文(Local-First)**:
|
||||
- Earth 网页端(IndexedDB `planet-earth-copilot-store`)与桌面客户端各自保管对话、摘要与本地状态,**不强制同步入库**,避免匿名访问或客户端本地文件引发账号混淆与脏数据。
|
||||
- 地球 Copilot 面板新增「导出本地上下文 JSON」(`planet.earth_context.v1`)剪贴板复制 / `.json` 下载;Admin `Playground` 右侧提供本地上下文抽屉,可直读同源 IndexedDB / `localStorage` 或粘贴桌面客户端导出的 JSON,并允许按需显式「保存为工作流样本(Fixture)」。
|
||||
3. **统一 9 条内建工作流与 AI Patch Diff 自动调优**:
|
||||
- 数据模型:`ai_workflows`、`ai_workflow_revisions`、`ai_workflow_fixtures` 与既有的 `workflow_runs`。
|
||||
- 收纳全站 9 条核心 AI 工作流:
|
||||
1. `default.general`(默认通用参谋)
|
||||
2. `earth.copilot.chat`(地球态势工作台多轮参谋)
|
||||
3. `earth.news.enrich`(Earth 新闻汉化与地理标注)
|
||||
4. `earth.news.analysis`(Earth 新闻深层地缘/基础设施研判)
|
||||
5. `location.resolve_unknown`(未知算力/设施位置 L0–L4 事实核查 Agent)
|
||||
6. `ops.bgp_brief`(BGP 态势简报)
|
||||
7. `ops.alerts_brief`(系统告警研判)
|
||||
8. `ops.situational_alerts_brief`(跨模块态势告警研判)
|
||||
9. `collection.mapping_and_guide`(数据源映射与凭据教程生成)
|
||||
- AI 调优接口 `POST /api/v1/ai/workflows/{workflow_id}/optimize` 输出受 `ALLOWED_NODE_PATCH_FIELDS` 与 `TOOL_CATALOG` 白名单约束的 Diff 提案,严禁未确认直接改写已发布版本;管理员审核后点击「应用为草稿」或「直接发布」。
|
||||
4. **L0–L4 未知设施位置解析管线与 `aiprovider` 纯协议扩展**:
|
||||
- `aiprovider` 保持纯协议适配器,新增 `tools`、`tool_choice`、`response_format`、`native_web_search` 与多轮 `tool`/`tool_calls` 透传以及结构化 `context` JSON 序列化。
|
||||
- 后端位置管线:`BuildsUponComputeCenterResolver` + ROR 商业云超大规模数据中心过滤 → L1 异步 `wikidata_lookup`(P625/P276)与 `peeringdb_fac_lookup`(`/api/fac`) → L2 最多 4 步受控 Tool-Calling Agent(`fetch_source_url`、`web_search`、`geocode_verify`、`submit_location_result`) → L3 硬护栏(强校验观测 URL 引用、Nominatim 国家/范围校核与市级降级) → L4 终态(`undisclosed` / `multi_site` / `anonymous`)持久化与短路。
|
||||
|
||||
---
|
||||
|
||||
## 2. Phase 2 & Phase 3 演进落地摘要(随 `v0.82.0` 发布)
|
||||
|
||||
1. **多节点 DAG 运行时与地球交互动态绑定**:
|
||||
- 新增 `backend/app/services/ai/dag_executor.py` 支持任意 `trigger -> deterministic -> llm_agent -> guardrail -> output` 有向无环图流式执行与条件路由。
|
||||
- 通过 `0006_add_ai_workflow_bindings.py` 在 `ai_workflows` 表增加 `bindings` JSON 声明,`GET /api/v1/earth/workflow-bindings` 与前端 `workflow-bindings.js` 驱动信息卡、专题卡、Copilot 快捷动作及多目标对比触发。
|
||||
- `/advisor/playground` 升级为统一多模态对话输入台(图片/视频关键帧/网页链接 SSRF 隔离解析/JSON 及地球上下文自动识别挂载),支持 Markdown 渲染与 `/locate` / Nominatim SSL 重试保护。
|
||||
2. **三层轻量可扩展自进化与元进化(零改表 / 零迁移脚本)**:
|
||||
- 新增内建 `meta.workflow_evolver` 三节点元工作流(`diag_node -> patch_node -> verify_output`),并由 `backend/app/services/ai/workflow_evolver.py` 实现三层有界自举架构。
|
||||
- **Tier 0 不可变宪法内核(Python 硬约束)**:单层元递归锁(禁止自定义 `meta.*`)、`verify_output` 只读冻结、自动变更半径上限(单次最多 2 个且 `<= 40%` 节点)、`24h / 7d` 冷却与每日自动预算锁、以及 **5 次运行灰度观察自动回滚**(元引擎自身为 3 次下游结果窗口自动回滚)。
|
||||
- **Tier 1 业务自优化与模型漂移适配**:复用 `WorkflowRun.budget_used` 记录模型/耗时/版本号与 👍/👎 反馈,支持 0-Token 健康诊断、活跃模型切换检测、DGM 历史最佳父版本选择、Fixture A/B 对照、高频问题孵化自定义工作流及后台非阻塞自动进化(`off | draft | auto`)。
|
||||
- **Tier 2 元进化与可扩展注册表**:台账与策略存储于 `system_settings`(`ai_evolution_policy`、`ai_evolution_ledger` 上限 50 条),通过 `EvolutionSignalDetector` 与 `EvolutionEvaluator` 协议支持后续无侵入接入新探针与离线评测器。
|
||||
@@ -1,5 +1,8 @@
|
||||
# AI Prompt Settings and Task Registry Plan
|
||||
|
||||
> [!NOTE]
|
||||
> 本计划已由 [ai-advisor-workflow-and-location-agent-plan.md](/home/ray/dev/linkong/planet/docs/plans/ai-advisor-workflow-and-location-agent-plan.md) 接管并升级(随 `v0.81.0` 发布):静态 `Prompts` 分区已升级为 `@xyflow/react` 可视化工作流与节点编排画布(`/advisor/workflows`),支持草稿/发布/回滚与 AI Diff 自动调优;运行时仍兼容 `get_effective_prompt(db, task_key)` 与 `ai_tasks/default_prompts.json`。
|
||||
|
||||
## Summary
|
||||
|
||||
Add an AI prompt settings tab under the operations AI settings page. Operators can select a business AI task from a dropdown, edit its prompt, save the override, and reset it back to the shipped default. Runtime LLM calls must resolve prompts through a task registry instead of embedding large prompt blocks at each call site.
|
||||
|
||||
@@ -36,8 +36,8 @@
|
||||
7. **配置 AI 凭证** — `/ai?section=integrations`:默认 provider、模型、Base URL、API Key、本地代理;工具 section(WebSearch、OCR)位于 `/ai?section=tools`
|
||||
8. **系统设置** — `/settings` 其他子 tab(系统设置、电视直播源、SMTP 邮件)
|
||||
9. **用户管理(管理员)** — `/users`:创建、删除、改角色、Gatekeeper 权限组
|
||||
10. **数据探索** — `/datasources`、`/data`、`/bgp`、`/alerts/*`
|
||||
11. **AI 测试台** — `/ai?section=playground`
|
||||
10. **数据探索** — `/datasources`、`/data`、`/ops/monitoring`(兼容重定向原 `/bgp`、`/alerts/*`)
|
||||
11. **AI 测试台** — `/advisor/playground`(兼容重定向原 Playground 分区)
|
||||
12. **Earth 公开页面** — 现 manual.md 的 Earth 章节原样保留(图层、图例、搜索、位置候选、设置、视角、动捕、巡航、移动端)
|
||||
13. **Docs 文档站** — 当前 Docs 章节保留(权限组说明)
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
# Earth 贴地影响范围与电影级三维视觉升级方案
|
||||
|
||||
> 状态:**规划待排期**(全量 Three.js / 着色器 / Agent 场景协议只读评估已完成,当前无需升级 `three@0.128.0` 亦不引入全屏后处理 `UnrealBloomPass`,全部效果可在核显与 Electron 60fps 录屏约束下通过轻量化自定义 Shader 实现)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 背景与现状诊断
|
||||
|
||||
核查 `frontend/public/earth/js/` 与 Agent `SceneSpec` 链路后,发现当前 3D 场景存在 6 项主要提升空间:
|
||||
|
||||
1. **贴地影响范围能力空白**:尚无面向新闻事件、多边会晤(如 APEC 中美俄及亚太梯度覆盖)或交互物件辐射半径的贴地矢量/球面范围层,无法支持自定义颜色、透明度、硬边界/渐变边缘切换及锋面扫光动画。
|
||||
2. **地球本体光影与晨昏散射**:[earth-surface-material.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/earth-surface-material.js) 晨昏线为简单线性冷暖过渡,海面缺少太阳镜面高光(Sunglint),夜半球缺少城市灯火,云层使用 `DoubleSide` 易从边缘透出背面。
|
||||
3. **Windows WebGL2 下多处 `1px` 细线退化**:`LineBasicMaterial({ linewidth: 3 })` 在 Windows ANGLE 上锁定为 `1px`(国界悬停高亮、高空 BGP/算力逻辑弧线、选中海缆轮廓、船只航迹、卫星选中轨道均受此限制);而 [satellites.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/satellites.js) 已验证“屏幕空间自适应宽度 + 柔化边缘 Shader Ribbon”方案可行。
|
||||
4. **BGP 采集器雷达扇区**:[bgp.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/bgp.js) 通过高频销毁/重建几何体实现旋转,产生 GC 抖动且视觉偏硬。
|
||||
5. **Iridium 卫星覆盖足迹**:[iridium-footprint-adapter.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/iridium-footprint-adapter.js) 仍在每帧 CPU 循环重算 649 个顶点,未迁入 [satellite-footprint-geometry.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/satellite-footprint-geometry.js) 的 GPU 顶点投影管线。
|
||||
|
||||
---
|
||||
|
||||
## 2. 分期升级路线(Phase 1 → Phase 4)
|
||||
|
||||
### Phase 1(核心旗舰):贴地影响范围(Surface Influence Zones)Shader 引擎 + Agent/事件联动
|
||||
|
||||
- **目标文件**:
|
||||
- 新建 `frontend/public/earth/js/influence-zones.js`
|
||||
- 修改 [country-boundaries.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/country-boundaries.js)、[main.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/main.js)、[situational-copilot.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/situational-copilot.js)、[stage-narrative-player.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/stage-narrative-player.js)
|
||||
- 扩展后端 `SceneSpec.influence_zones`([workflow_runtime.py](/home/ray/dev/linkong/planet/backend/app/services/ai/workflow_runtime.py)、[stream_turn.py](/home/ray/dev/linkong/planet/backend/app/services/ai/stream_turn.py)、[earth_interactables.py](/home/ray/dev/linkong/planet/backend/app/services/earth_interactables.py))
|
||||
- **核心架构**:
|
||||
1. **零冲突渲染插槽**:复用同半径 `r = 100.48` 的 `128×128` 球壳(`createEarthSurfaceGeometry`),置于 `renderOrder = 0.965`(紧贴高清纹理 `0.96` 之上,严守在国界线 `0.97` 与全部交互图标之下),不破坏 `earth-surface.test.js` 断言。
|
||||
2. **双通道混合渲染**:
|
||||
- 国家/区域预设(如 `APEC` / `EU` / `ASEAN` / `G7` / `BRICS`)及任意多边形通过离屏高清 `CanvasTexture`(`2048×1024` / `4096×2048`)按层级 `tier` 从低到高叠画;修复 `-99` `ISO_A2/A3` 匹配并优先索引 `ADM0_A3`。
|
||||
- 圆形辐射区在片元 Shader 内按球面大圆角距离实时求解,保证极区与高纬无变形。
|
||||
3. **可调视觉参数与三种电影级入场动效**:支持任意色值、独立透明度、`edge_mode: "sharp" | "soft"` 边缘模式与羽化宽度,以及 `sweep`(方向性高亮能量锋面扫光铺开)、`radial`(中心大圆波纹扩散)、`fade`(柔缓浮现)三种入场模式。
|
||||
|
||||
### Phase 2:地球本体大气散射、海洋高光与立体云影升级
|
||||
|
||||
- **目标文件**:[earth-surface-material.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/earth-surface-material.js)、[earth.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/earth.js)。
|
||||
- **核心内容**:
|
||||
1. 晨昏线升级为三阶物理瑞利散射(白昼 → 琥珀金暮光带 → 深蓝暗夜);
|
||||
2. 结合海陆掩码增加向阳海面柔和太阳镜面高光(Sunglint);
|
||||
3. 增加轻量本地夜半球城市灯火贴图(按 `1 - daylight` 混合,完全离线可用);
|
||||
4. 大气层补充太阳侧 Mie 前向散射光弧;
|
||||
5. 云层由 `DoubleSide` 改为 `FrontSide` Shader 并叠加微位移地表云影。
|
||||
|
||||
### Phase 3:通用发光丝带系统与雷达/弧线/海缆/航迹升级
|
||||
|
||||
- **目标文件**:新建 `frontend/public/earth/js/surface-ribbon.js`;升级 [bgp.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/bgp.js)、[compute-centers.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/compute-centers.js)、[cable-batches.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/cable-batches.js)、[vessels.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/vessels.js)、[country-boundaries.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/country-boundaries.js)。
|
||||
- **核心内容**:
|
||||
1. 抽出共享屏幕空间抗锯齿发光丝带底层(亮核 + 高斯羽化外晕),替代 Windows 下退化为 1px 的 `THREE.Line`;
|
||||
2. BGP 采集器雷达改为静态球面圆盘 + 60fps 片元扫描余辉与同心刻度(0 GC);
|
||||
3. 高空逻辑弧线支持生长动画与高速光弹脉冲;选中海缆叠层发光流光;船只航迹支持尾迹渐隐;国界悬停换用柔光轮廓。
|
||||
|
||||
### Phase 4:卫星覆盖 GPU 提纯与轨道丝带
|
||||
|
||||
- **目标文件**:[iridium-footprint-adapter.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/iridium-footprint-adapter.js)、[satellite-orbit-visual.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/satellite-orbit-visual.js)、[satellites.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/satellites.js)。
|
||||
- **核心内容**:将 Iridium 足迹迁入 GPU 顶点投影消除每帧 649 顶点 CPU 循环,并将选中卫星轨道升级为发光丝带脉冲。
|
||||
|
||||
---
|
||||
|
||||
## 3. 性能与质量约束
|
||||
|
||||
- 不增加全屏 RenderTarget 后处理管线,单层均匀控制在 `1~2 Draw Calls`,保障核显性能与桌面端录屏流畅度。
|
||||
- 所有球壳必须通过 [earth-surface.test.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/earth-surface.test.js) 深度与渲染顺序回归测试。
|
||||
@@ -1,5 +1,8 @@
|
||||
# AI Playground Development Plan
|
||||
|
||||
> [!NOTE]
|
||||
> 本计划已由 [ai-advisor-workflow-and-location-agent-plan.md](/home/ray/dev/linkong/planet/docs/plans/ai-advisor-workflow-and-location-agent-plan.md) 接管并实现(随 `v0.81.0` 发布):旧 Playground 表单已迁移至 `/advisor/playground` 纯聊天工作台与客户端本地上下文抽屉,`/ai` 收口为模型供应商与工具基础设施配置。
|
||||
|
||||
## 目标
|
||||
|
||||
这份计划用于统一 `aiprovider`、`backend AI facade`、`Playground` 页面,以及后续 `BGP / 告警 / 数据源健康` 等 AI 入口的演进方向。
|
||||
|
||||
@@ -104,22 +104,26 @@ The AI settings page uses:
|
||||
|
||||
These endpoints require an authenticated user, and preset catalog refresh endpoints require administrator privileges. The `secrets` endpoint is only used when the settings page reveals a key or token; hiding the field restores the masked preview.
|
||||
|
||||
Model refresh and lightweight checks share `backend/app/services/llm_model_catalog.py` and query provider endpoints directly, without models.dev. Refresh uses the draft base URL, protocol and credentials, or saved configuration when no draft is supplied. Regional hosts and custom gateway paths are preserved. For official public catalogs (`openrouter.ai`, `opencode.ai`) and local Ollama, catalog refresh does not require or send an API key so stale or invalid credentials do not block public discovery; pointing those providers at a custom private gateway still requires and sends credentials. Lightweight connectivity checks continue sending configured credentials (Ollama remains key-free under both `ollama-generate` and `openai-completions`). Missing required credentials, invalid base URLs, or unsupported protocols return 400; upstream failures return 502 with safe errors and retain the previous catalog. `POST /api/v1/settings/integrations/ai-provider/presets/refresh-public` refreshes and persists all currently credential-free presets in one pass, isolating per-provider failures while preserving prior catalogs.
|
||||
Model refresh and lightweight checks share `backend/app/services/llm_model_catalog.py`. When an API key is configured (draft, saved, or env), refresh queries the provider endpoint directly while preserving regional hosts and custom gateway paths. For official public catalogs (`openrouter.ai`, `opencode.ai`) and local Ollama, catalog refresh does not require or send an API key so stale or invalid credentials do not block public discovery. For keyed built-in providers on their official hosts (`minimax`, `openai`, `anthropic`, `deepseek`, `alibaba`, `moonshotai`, `glm`, `meta`, `gemini`, `grok`), **keyless refresh automatically falls back to public aggregators** (`models.dev/api.json` primary -> `openrouter.ai/api/v1/models` backup, cached in-process for 5 minutes); pointing those providers at a custom private gateway still requires and sends credentials. Lightweight connectivity checks continue querying the configured endpoint directly with credentials (Ollama remains key-free under both `ollama-generate` and `openai-completions`) and never fall back to aggregators. Missing required credentials, invalid base URLs, or unsupported protocols return 400; upstream/aggregator failures return 502 with safe errors and retain the previous catalog. `POST /api/v1/settings/integrations/ai-provider/presets/refresh-public` refreshes and persists all currently credential-free and aggregator-backed presets in one pass, isolating per-provider failures while preserving prior catalogs.
|
||||
|
||||
Successful catalogs and `refreshed_at` are stored under `llm_provider_preset:<provider>` in `system_settings`. Dynamic categories use the provider preset as their defaults and are validated before committing. Listing prefers saved catalogs and otherwise shows bundled suggestions. Refresh never modifies the active model, protocol, URL or credentials in `external_integrations`. The frontend retains the draft and previously loaded models when listing fails, with an explicit error message.
|
||||
|
||||
### Model Catalog Endpoints
|
||||
|
||||
These endpoints were checked against official documentation on 2026-09-13. The table lists discovery URLs; the form still takes the generation base URL. Credentials must belong to the configured service region.
|
||||
These endpoints align with official and public aggregator catalogs. The table lists discovery URLs; the form still takes the generation base URL. Direct keyed queries must use credentials for the configured service region; keyless official hosts query mapped public aggregator catalogs.
|
||||
|
||||
| Provider | Model list GET endpoint | Authentication and parsing |
|
||||
| --- | --- | --- |
|
||||
| [MiniMax](https://platform.minimax.io/docs/api-reference/models/anthropic/list-models) | `https://api.minimaxi.com/anthropic/v1/models`; international: `api.minimax.io` | `x-api-key`; `data[].id`; `has_more/last_id` pagination |
|
||||
| [OpenAI](https://developers.openai.com/api/reference/resources/models/methods/list) | `https://api.openai.com/v1/models` | Bearer; `data[].id` |
|
||||
| [Anthropic](https://platform.claude.com/docs/en/api/models/list) | `https://api.anthropic.com/v1/models` | `x-api-key`, `anthropic-version`; paginate with `after_id` |
|
||||
| [DeepSeek](https://api-docs.deepseek.com/api/list-models) | `https://api.deepseek.com/v1/models` | Bearer; `data[].id` |
|
||||
| [Alibaba Model Studio](https://help.aliyun.com/zh/model-studio/list-models) | `/api/v1/models` on the configured regional host | Bearer; `output.models[].model`; `page_no/page_size/output.total`; filter `capabilities=TG` |
|
||||
| [Moonshot / Kimi](https://platform.kimi.ai/docs/api/list-models) | `https://api.moonshot.ai/v1/models`; China: `api.moonshot.cn` | Bearer; `data[].id` |
|
||||
| [MiniMax](https://platform.minimax.io/docs/api-reference/models/anthropic/list-models) | `https://api.minimaxi.com/anthropic/v1/models`; international: `api.minimax.io` | Keyed: `x-api-key` + `has_more/last_id`; keyless: aggregator `minimax-cn`/`minimax` |
|
||||
| [OpenAI](https://developers.openai.com/api/reference/resources/models/methods/list) | `https://api.openai.com/v1/models` | Keyed: Bearer; keyless: aggregator `openai` |
|
||||
| [Anthropic](https://platform.claude.com/docs/en/api/models/list) | `https://api.anthropic.com/v1/models` | Keyed: `x-api-key`, `anthropic-version`; keyless: aggregator `anthropic` |
|
||||
| [DeepSeek](https://api-docs.deepseek.com/api/list-models) | `https://api.deepseek.com/v1/models` | Keyed: Bearer; keyless: aggregator `deepseek` |
|
||||
| [Alibaba Model Studio](https://help.aliyun.com/zh/model-studio/list-models) | `/api/v1/models` on the configured regional host | Keyed: Bearer + `page_no` + `capabilities=TG`; keyless: aggregator `alibaba-cn`/`alibaba` |
|
||||
| [Moonshot / Kimi](https://platform.kimi.ai/docs/api/list-models) | `https://api.moonshot.ai/v1/models`; China: `api.moonshot.cn` | Keyed: Bearer; keyless: aggregator `moonshotai`/`moonshotai-cn` |
|
||||
| [Zhipu GLM (CN)](https://docs.bigmodel.cn/api-reference/%E6%A8%A1%E5%9E%8B-api/%E6%9F%A5%E8%AF%A2%E6%A8%A1%E5%9E%8B%E5%88%97%E8%A1%A8) | `https://open.bigmodel.cn/api/paas/v4/models` | Keyed: Bearer; keyless: aggregator `zhipuai` |
|
||||
| [Meta AI](https://llama.developer.meta.com/docs/models) | `https://api.meta.ai/v1/models` | Keyed: Bearer; keyless: aggregator `meta` (backup `meta-llama`) |
|
||||
| [Google Gemini](https://ai.google.dev/gemini-api/docs/openai) | `https://generativelanguage.googleapis.com/v1beta/openai/models` | Keyed: Bearer (`models/` prefix stripped); keyless: aggregator `google` |
|
||||
| [xAI Grok](https://docs.x.ai/docs/api-reference#list-models) | `https://api.x.ai/v1/models` | Keyed: Bearer; keyless: aggregator `xai` |
|
||||
| [OpenRouter](https://openrouter.ai/docs/api/api-reference/models/list-all-models-and-their-properties) | `https://openrouter.ai/api/v1/models` | Official public catalog refreshes without sending a key; custom gateways and connectivity checks send Bearer; `data[].id` |
|
||||
| [OpenCode Go](https://opencode.ai/docs/go/#models) | `https://opencode.ai/zen/go/v1/models` | Official public catalog refreshes without sending a key; custom gateways and connectivity checks send Bearer; `data[].id` |
|
||||
| [Ollama](https://docs.ollama.com/api/tags) | `/api/tags` on the configured server (or `/v1/models` under `openai-completions`) | Local servers need no key; `models[].model/name` or `data[].id`; empty means no installed models |
|
||||
@@ -128,30 +132,34 @@ New Model Studio endpoints for Beijing, Tokyo, Frankfurt and Virginia require th
|
||||
|
||||
Pagination and retries have a 30-second overall deadline. Network failures and 502/503/504 allow up to two attempts; authentication failures are not retried. Models are sorted by supplied creation/release dates, preserving upstream order on ties, without arbitrary list truncation. Public catalog membership does not establish account-specific generation permission.
|
||||
|
||||
Admin keeps the AI page aligned with the legacy information architecture:
|
||||
Admin separates AI configuration from workflow orchestration across two areas:
|
||||
|
||||
- `Model Providers`
|
||||
- Manages provider, wire adapter, default model, LLM API key, proxy URL, proxy token, model refresh, set-as-default, and lightweight connectivity testing.
|
||||
- `Tool Calling`
|
||||
- Manages tools such as WebSearch and OCR. Each tool first selects a provider, then edits that provider's API, key, and advanced parameters.
|
||||
- `Prompts`
|
||||
- Edits system/user prompts by prompt group and task key. Save and reset only affect the current task.
|
||||
- `Playground`
|
||||
- Runs real conversations with the active provider and prompt configuration. AI responses are rendered as Markdown.
|
||||
- **Operations and Settings → AI (`/ai`)**:
|
||||
- `Model Providers`: manages provider, wire adapter, default model, LLM API key, proxy URL/token, catalog refresh (keyless official providers fall back to public aggregator catalogs sorted selected-first + MRU + release date with a 6-item collapsible list), set-as-default, and connectivity testing.
|
||||
- `Tool Calling`: manages WebSearch (including keyless SearXNG) and OCR tool credentials.
|
||||
- **AI Advisor (`/advisor/*`)**:
|
||||
- `Playground` (`/advisor/playground`): unified multimodal debugging workbench (text, images, sampled video keyframes, SSRF-isolated web links, JSON, and automatic Earth context mounting) with slash commands, Markdown rendering, and inline 👍/👎 assistant feedback persisted in `WorkflowRun.budget_used`.
|
||||
- `Workflows & Nodes` (`/advisor/workflows`): `@xyflow/react` visual graph studio over all 10 built-in workflows (including `meta.workflow_evolver`) and custom DAGs executed via `dag_executor.py`, supporting Earth interactive `bindings`, immutable revisions/rollback, Fixture A/B evaluation, and 3-tier bounded self-evolution controls.
|
||||
- `Run History` (`/advisor/runs`): execution trace audit surfacing model, latency, revision, and feedback filters with one-click canvas replay and trace-guided tuning.
|
||||
|
||||
Save, set-as-default, and connectivity testing are separate responsibilities: save only persists the form, set-as-default only changes the active provider/tool, and connectivity testing only validates the current draft. It must not implicitly save or switch defaults.
|
||||
### Three-Tier Workflow Self-Evolution and Meta-Evolution
|
||||
|
||||
The `ai-prompts` endpoints back the Prompts tab in AI settings. Shipped defaults come from versioned backend resources, while business code references stable task keys. The API stores only operator overrides. Resetting a prompt removes the override and falls back to the current shipped default.
|
||||
Implemented in [workflow_evolver.py](/home/ray/dev/linkong/planet/backend/app/services/ai/workflow_evolver.py) with **zero database schema changes or migrations** by reusing `ai_workflows`, `ai_workflow_revisions`, `ai_workflow_fixtures`, `workflow_runs.budget_used`, and `system_settings` (`ai_evolution_policy` and `ai_evolution_ledger`):
|
||||
|
||||
- **Tier 0 (Immutable Python Constitution Kernel)**: enforces acyclic DAG structure and trigger/output preservation, blocks emptying `system_prompt`, restricts tools to allowlisted IDs, caps auto-mode blast radius (`<= 2` nodes and `<= 40%` of nodes), freezes the `verify_output` node on `meta.workflow_evolver`, blocks custom `meta.*` creation (single-level recursion lock), enforces `24h / 7d` cooldowns and daily auto-evolution quotas, and runs a **5-run canary window** with automatic rollback on consecutive failures or elevated bad-rating rates (with a 3-outcome meta-canary rollback guard on `meta.workflow_evolver`).
|
||||
- **Tier 1 (Business Optimization & Model Drift Adaptation)**: `GET /api/v1/ai/evolution/health/{workflow_id}` computes 0-token health metrics, active model capability drift, unused tools, and DGM best-parent revision recommendations; `POST /api/v1/ai/evolution/propose/{workflow_id}` reads live `diag_node` / `patch_node` prompts from `meta.workflow_evolver` alongside historical ledger lessons; `POST /api/v1/ai/evolution/eval/{workflow_id}` runs Fixture A/B checks and `POST /api/v1/ai/evolution/incubate` proposes new workflows from frequent `default.general` queries. Non-blocking post-run hooks run via `schedule_post_run_evolution`.
|
||||
- **Tier 2 (Meta-Evolution & Extensibility Hooks)**: `POST /api/v1/ai/evolution/meta-evolve` evolves `meta.workflow_evolver` prompts under an independent `meta_mode` (`off | draft | auto`) using objective ledger outcomes; `EvolutionSignalDetector` (`SIGNAL_DETECTORS`) and `EvolutionEvaluator` (`EVALUATORS`) provide clean `Protocol` extension points.
|
||||
- **Feedback & Policy APIs**: `POST /api/v1/ai/runs/{run_id}/feedback`, `GET /api/v1/ai/runs?feedback=negative|positive`, `GET/PUT /api/v1/ai/evolution/policy`, `GET /api/v1/ai/evolution/ledger`, and `POST /api/v1/ai/evolution/ledger/{entry_id}/dismiss`.
|
||||
|
||||
Save, set-as-default, and connectivity testing remain three separate responsibilities. Runtime prompts resolve from published `AIWorkflow` nodes and versioned `default_prompts.json` resources while preserving `task_key` compatibility.
|
||||
|
||||
### Prompt Boundary
|
||||
|
||||
`aiprovider` is a pure model adapter and does not inject a global business system prompt. News localization, alert briefing, BGP briefing, location factcheck, datasource mapping, and credential guide generation each resolve their own effective prompt by task key. Alert-analysis system prompts are only sent by alert-related tasks and do not leak into other LLM calls.
|
||||
`aiprovider` is a pure model adapter and injects no business system prompts. Each workflow node and task key resolves its own effective prompt and serializes structured `context` as compact JSON.
|
||||
|
||||
### Agent And Tool Boundary
|
||||
|
||||
Agent workflows belong in the `backend`, not in `aiprovider`. Future Earth LLM commands, situational awareness, multi-role simulation, WebSearch, database queries, evidence storage, and configuration proposal application should be orchestrated by the backend Agent Runtime. `aiprovider` should receive model-ready requests from the backend and return normalized model responses.
|
||||
|
||||
If a provider supports native tool calling, `aiprovider` may pass through protocol fields and normalize response blocks, but tool whitelists, argument validation, permission policy, run records, and write approvals must stay in the backend. When a provider does not support native tools, the backend uses JSON tool-call fallback; business tools should not move into `aiprovider` for a provider-specific shortcut.
|
||||
Agent workflows belong in `backend`, not `aiprovider`. `aiprovider` transparently passes normalized `tools`, `tool_choice`, `response_format`, `native_web_search`, and multi-turn `tool` / `tool_calls` messages across adapters and normalizes returned `tool_calls` + `stop_reason`, while tool whitelists, validation, permission checks, `WorkflowRun` audit logs, and Diff approval remain strictly in the backend.
|
||||
|
||||
### AI provider internal API
|
||||
|
||||
|
||||
Loaded 100 of 224 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user