From 41059ca42a85caa32e5d54f8d6c70a7ac1b653c6 Mon Sep 17 00:00:00 2001 From: linkong Date: Thu, 26 Nov 2026 10:50:38 +0800 Subject: [PATCH] release: bump version to 0.80.0 --- VERSION | 2 +- aiprovider/main.py | 34 + aiprovider/provider_service.py | 513 ++++++- aiprovider/schemas.py | 8 +- backend/app/api/v1/settings.py | 92 +- backend/app/api/v1/situational_awareness.py | 78 +- backend/app/main.py | 20 +- backend/app/schemas/ai.py | 9 +- .../app/services/ai/conversation_memory.py | 209 +++ backend/app/services/ai/domain_catalog.py | 7 +- .../app/services/ai/spatial_domain_agent.py | 2 +- backend/app/services/ai/stream_turn.py | 613 ++++++++ backend/app/services/ai/tool_registry.py | 98 +- backend/app/services/ai_client.py | 77 + backend/app/services/llm_model_catalog.py | 59 +- backend/app/services/llm_provider_catalog.py | 53 +- backend/tests/test_ai_stream_turn.py | 279 ++++ backend/tests/test_llm_provider_catalog.py | 83 +- backend/tests/test_llm_provider_settings.py | 167 ++- backend/tests/test_provider_protocols.py | 171 +++ backend/tests/test_settings_ai_provider.py | 6 +- client/electron-builder.yml | 2 + client/package.json | 2 +- client/scripts/build-earth-bundle.mjs | 13 +- client/src/main/index.ts | 1 + client/src/main/protocol.ts | 36 +- client/src/preload/index.ts | 1 + docs/CHANGELOG.md | 12 + docs/plans/README.md | 1 + ...th-local-motion-single-and-dual-3d-plan.md | 95 ++ docs/technical/en/agents-aiprovider.md | 11 +- docs/technical/zh/agents-aiprovider.md | 11 +- docs/version-history.md | 3 +- frontend/bun.lock | 3 + frontend/nginx.conf.template | 12 +- frontend/package.json | 3 +- frontend/public/earth/css/card-images.css | 4 +- frontend/public/earth/css/compute-topic.css | 666 ++++++++- frontend/public/earth/css/hud.css | 17 +- frontend/public/earth/css/info-panel.css | 25 +- frontend/public/earth/css/news-panel.css | 37 + .../public/earth/css/news-region-cards.css | 25 +- frontend/public/earth/css/tv-panel.css | 9 +- frontend/public/earth/index.html | 60 +- frontend/public/earth/js/card-images.js | 6 +- .../earth/js/card-workbench-actions.test.js | 166 +++ frontend/public/earth/js/compute-topic.js | 5 + frontend/public/earth/js/controls.js | 226 ++- frontend/public/earth/js/copilot-store.js | 326 +++++ .../public/earth/js/copilot-store.test.js | 69 + frontend/public/earth/js/copilot-stream.js | 177 +++ .../public/earth/js/copilot-stream.test.js | 70 + frontend/public/earth/js/i18n.js | 43 +- frontend/public/earth/js/info-card.js | 240 ++-- frontend/public/earth/js/main.js | 25 + .../earth/js/motion-browser-provider.js | 218 ++- .../public/earth/js/motion-camera-topology.js | 149 ++ frontend/public/earth/js/motion-control.js | 11 +- .../public/earth/js/motion-control.test.js | 204 +++ .../public/earth/js/motion-debug-panel.js | 2 +- frontend/public/earth/js/news-region-cards.js | 38 +- frontend/public/earth/js/news.js | 54 +- .../public/earth/js/situational-copilot.js | 1244 +++++++++++++++-- .../earth/js/situational-copilot.test.js | 627 ++++++++- .../mediapipe/pose_landmarker_lite.task | Bin 0 -> 5777746 bytes frontend/scripts/earth-runtime-plugin.mjs | 46 +- frontend/src/pages/Earth/Earth.tsx | 1 + pyproject.toml | 2 +- uv.lock | 2 +- 69 files changed, 7099 insertions(+), 481 deletions(-) create mode 100644 backend/app/services/ai/conversation_memory.py create mode 100644 backend/app/services/ai/stream_turn.py create mode 100644 backend/tests/test_ai_stream_turn.py create mode 100644 docs/plans/earth-local-motion-single-and-dual-3d-plan.md create mode 100644 frontend/public/earth/js/card-workbench-actions.test.js create mode 100644 frontend/public/earth/js/copilot-store.js create mode 100644 frontend/public/earth/js/copilot-store.test.js create mode 100644 frontend/public/earth/js/copilot-stream.js create mode 100644 frontend/public/earth/js/copilot-stream.test.js create mode 100644 frontend/public/earth/js/motion-camera-topology.js create mode 100644 frontend/public/earth/vendor/mediapipe/pose_landmarker_lite.task diff --git a/VERSION b/VERSION index de4de097..b53d377d 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.79.2 +0.80.0 diff --git a/aiprovider/main.py b/aiprovider/main.py index 00e56618..a8522c5d 100644 --- a/aiprovider/main.py +++ b/aiprovider/main.py @@ -1,8 +1,10 @@ from contextlib import asynccontextmanager import hmac +import json from uuid import uuid4 from fastapi import Depends, FastAPI, Header, HTTPException, Request, Response, status +from fastapi.responses import StreamingResponse from aiprovider.config import settings from aiprovider.provider_service import ProviderService @@ -124,3 +126,35 @@ async def analyze( ): response.headers["X-Request-ID"] = request.state.request_id return await provider_service.analyze(payload) + + +@app.post( + "/v1/analyze/stream", + dependencies=[Depends(verify_service_token)], +) +async def analyze_stream( + payload: SituationalAnalysisRequest, + request: Request, + provider_service: ProviderService = Depends(get_provider_service), +): + request_id = request.state.request_id + + async def event_generator(): + try: + async for item in provider_service.stream_analyze(payload): + event_name = str(item.get("event") or "message") + yield f"event: {event_name}\ndata: {json.dumps(item, ensure_ascii=False)}\n\n" + except Exception as exc: + detail = exc.detail if isinstance(exc, HTTPException) else exc + err_payload = {"event": "error", "detail": str(detail)} + yield f"event: error\ndata: {json.dumps(err_payload, ensure_ascii=False)}\n\n" + + return StreamingResponse( + event_generator(), + media_type="text/event-stream", + headers={ + "Cache-Control": "no-cache", + "X-Accel-Buffering": "no", + "X-Request-ID": request_id, + }, + ) diff --git a/aiprovider/provider_service.py b/aiprovider/provider_service.py index 28f16052..57d20f26 100644 --- a/aiprovider/provider_service.py +++ b/aiprovider/provider_service.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +from collections.abc import AsyncIterator import json from typing import Any from uuid import NAMESPACE_URL, uuid4, uuid5 @@ -97,17 +98,22 @@ class ProviderService: ) prompt = self._build_prompt(payload) + conversation_messages = self._build_conversation_messages(payload, prompt) if payload.context.get("session_id") is not None: self.session_id = str(uuid5(NAMESPACE_URL, f"planet:{payload.context['session_id']}")) provider_api = self._resolve_model_provider_api(model) if provider_api == "openai-completions": - data = await self._request_openai_compatible(model, prompt, payload.system_prompt) + data = await self._request_openai_compatible( + model, prompt, payload.system_prompt, conversation_messages=conversation_messages + ) content = self._extract_openai_content(data) content_blocks = self._extract_openai_blocks(data) elif provider_api == "openai-responses": - data = await self._request_openai_responses(model, prompt, payload.system_prompt) + data = await self._request_openai_responses( + model, prompt, payload.system_prompt, conversation_messages=conversation_messages + ) content_blocks = self._extract_responses_blocks(data) content = "".join(block.text for block in content_blocks if block.text) elif provider_api == "anthropic-messages": @@ -116,11 +122,14 @@ class ProviderService: prompt, payload.thinking, payload.system_prompt, + conversation_messages=conversation_messages, ) content = self._extract_anthropic_content(data) content_blocks = self._extract_anthropic_blocks(data) elif provider_api == "ollama-generate": - data = await self._request_ollama(model, prompt, payload.system_prompt) + data = await self._request_ollama( + model, prompt, payload.system_prompt, conversation_messages=conversation_messages + ) content = self._extract_ollama_content(data) content_blocks = self._extract_ollama_blocks(data) else: @@ -142,6 +151,394 @@ class ProviderService: raw_response=data, ) + async def stream_analyze( + self, + payload: SituationalAnalysisRequest, + ) -> AsyncIterator[dict[str, Any]]: + if self.provider == "disabled": + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="AI provider is disabled. Configure AI_PROVIDER in .env to enable analysis.", + ) + + model = payload.preferred_model or self.default_model + has_credentials = bool(self.api_key) if self._requires_api_key() else True + if not self.base_url or not has_credentials or not model: + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="AI provider is not fully configured. Check AI_BASE_URL, AI_API_KEY, and AI_MODEL.", + ) + + prompt = self._build_prompt(payload) + conversation_messages = self._build_conversation_messages(payload, prompt) + if payload.context.get("session_id") is not None: + self.session_id = str(uuid5(NAMESPACE_URL, f"planet:{payload.context['session_id']}")) + + provider_api = self._resolve_model_provider_api(model) + yield {"event": "start", "provider": self.provider, "model": model} + + if provider_api == "anthropic-messages": + async for item in self._stream_anthropic_messages( + model, + prompt, + payload.thinking, + payload.system_prompt, + conversation_messages=conversation_messages, + ): + 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 + ): + 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 + ): + yield item + return + if provider_api == "ollama-generate": + async for item in self._stream_ollama( + model, prompt, payload.system_prompt, conversation_messages=conversation_messages + ): + yield item + return + + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"Unsupported AI provider API: {self.provider_api}", + ) + + def _outbound_headers(self, headers: dict[str, str]) -> dict[str, str]: + merged = {"User-Agent": "Planet/1.0", **headers} + if self.provider == "opencode-go": + merged["x-opencode-session"] = self.session_id + return merged + + async def _iter_sse_events( + self, + response: httpx.Response, + ) -> AsyncIterator[tuple[str, str]]: + event_name = "" + data_lines: list[str] = [] + async for raw_line in response.aiter_lines(): + line = raw_line.rstrip("\r") + if line == "": + if data_lines: + yield event_name, "\n".join(data_lines) + event_name = "" + data_lines = [] + continue + if line.startswith(":"): + continue + if line.startswith("event:"): + event_name = line[6:].strip() + elif line.startswith("data:"): + data_lines.append(line[5:].lstrip()) + if data_lines: + yield event_name, "\n".join(data_lines) + + def _build_anthropic_request( + self, + model: str, + prompt: str, + thinking: dict[str, Any] | None = None, + system_prompt: str | None = None, + *, + stream: bool = False, + conversation_messages: 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}]}] + resolved_thinking, resolved_output_config = self._resolve_anthropic_thinking(thinking, model) + thinking_active = bool( + resolved_thinking + and str(resolved_thinking.get("type") or "").lower() in {"enabled", "adaptive"} + ) + max_tokens = self.max_tokens + if resolved_thinking and isinstance(resolved_thinking.get("budget_tokens"), (int, float)): + budget_tokens = int(resolved_thinking["budget_tokens"]) + if budget_tokens >= max_tokens: + max_tokens = budget_tokens + 1024 + + request_body: dict[str, Any] = { + "model": model, + "messages": anthropic_messages, + "max_tokens": max_tokens, + } + if not thinking_active: + request_body["temperature"] = 0.2 + if stream: + request_body["stream"] = True + resolved_system_prompt = self._resolve_system_prompt(system_prompt) + if resolved_system_prompt: + request_body["system"] = resolved_system_prompt + if resolved_thinking: + request_body["thinking"] = resolved_thinking + if resolved_output_config: + request_body["output_config"] = resolved_output_config + path = "/v1/messages" if self.provider == "minimax" and self.base_url.endswith("/anthropic") else "/messages" + headers = { + "x-api-key": self.api_key, + "anthropic-version": self.anthropic_version, + "Content-Type": "application/json", + } + return path, headers, request_body + + async def _stream_anthropic_messages( + self, + model: str, + prompt: str, + thinking: dict[str, Any] | None = None, + system_prompt: str | None = None, + *, + conversation_messages: list[dict[str, str]] | None = None, + ) -> AsyncIterator[dict[str, Any]]: + path, headers, request_body = self._build_anthropic_request( + model, + prompt, + thinking, + system_prompt, + stream=True, + conversation_messages=conversation_messages, + ) + resolved_model = model + usage: dict[str, Any] = {} + async with httpx.AsyncClient(timeout=self.timeout) as client: + async with client.stream( + "POST", + f"{self.base_url}{path}", + headers=self._outbound_headers(headers), + json=request_body, + ) as response: + if response.status_code >= 400: + detail = (await response.aread()).decode("utf-8", errors="replace") + raise HTTPException( + status_code=status.HTTP_502_BAD_GATEWAY, + detail=f"AI provider request failed: {detail or response.status_code}", + ) + async for event_name, data_str in self._iter_sse_events(response): + if data_str == "[DONE]": + continue + try: + chunk = json.loads(data_str) + except json.JSONDecodeError: + continue + if not isinstance(chunk, dict): + continue + msg_type = str(chunk.get("type") or event_name or "") + if msg_type == "error": + err = chunk.get("error") if isinstance(chunk.get("error"), dict) else {} + raise HTTPException( + status_code=status.HTTP_502_BAD_GATEWAY, + detail=str(err.get("message") or chunk.get("message") or "Upstream stream error"), + ) + if msg_type == "message_start": + message = chunk.get("message") if isinstance(chunk.get("message"), dict) else {} + if isinstance(message.get("model"), str) and message["model"]: + resolved_model = message["model"] + if isinstance(message.get("usage"), dict): + usage.update(message["usage"]) + elif msg_type == "message_delta": + if isinstance(chunk.get("usage"), dict): + usage.update(chunk["usage"]) + elif msg_type == "content_block_start": + block = chunk.get("content_block") if isinstance(chunk.get("content_block"), dict) else {} + if block.get("type") == "thinking" and isinstance(block.get("thinking"), str) and block["thinking"]: + yield {"event": "reasoning", "delta": block["thinking"]} + elif block.get("type") == "text" and isinstance(block.get("text"), str) and block["text"]: + yield {"event": "text", "delta": block["text"]} + elif msg_type == "content_block_delta": + delta = chunk.get("delta") if isinstance(chunk.get("delta"), dict) else {} + delta_type = str(delta.get("type") or "") + if delta_type == "thinking_delta" and isinstance(delta.get("thinking"), str) and delta["thinking"]: + yield {"event": "reasoning", "delta": delta["thinking"]} + elif delta_type == "text_delta" and isinstance(delta.get("text"), str) and delta["text"]: + yield {"event": "text", "delta": delta["text"]} + yield {"event": "done", "provider": self.provider, "model": resolved_model, "usage": usage} + + async def _stream_openai_compatible( + self, + model: str, + prompt: str, + system_prompt: str | None = None, + *, + conversation_messages: list[dict[str, str]] | None = None, + ) -> AsyncIterator[dict[str, Any]]: + messages = [] + 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 = { + "model": model, + "messages": messages, + "temperature": 0.2, + "max_tokens": self.max_tokens, + "stream": True, + "stream_options": {"include_usage": True}, + } + resolved_model = model + usage: dict[str, Any] = {} + async with httpx.AsyncClient(timeout=self.timeout) as client: + async with client.stream( + "POST", + f"{self.base_url}/chat/completions", + headers=self._outbound_headers( + {"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"} + ), + json=request_body, + ) as response: + if response.status_code >= 400: + detail = (await response.aread()).decode("utf-8", errors="replace") + raise HTTPException( + status_code=status.HTTP_502_BAD_GATEWAY, + detail=f"AI provider request failed: {detail or response.status_code}", + ) + async for _, data_str in self._iter_sse_events(response): + if data_str == "[DONE]": + break + try: + chunk = json.loads(data_str) + except json.JSONDecodeError: + continue + if not isinstance(chunk, dict): + continue + if isinstance(chunk.get("model"), str) and chunk["model"]: + resolved_model = chunk["model"] + if isinstance(chunk.get("usage"), dict): + usage.update(chunk["usage"]) + choices = chunk.get("choices") or [] + if not choices or not isinstance(choices[0], dict): + continue + delta = choices[0].get("delta") if isinstance(choices[0].get("delta"), dict) else {} + for r_key in ("reasoning_content", "reasoning", "thinking"): + r_val = delta.get(r_key) + if isinstance(r_val, str) and r_val: + yield {"event": "reasoning", "delta": r_val} + break + text_val = delta.get("content") + if isinstance(text_val, str) and text_val: + yield {"event": "text", "delta": text_val} + yield {"event": "done", "provider": self.provider, "model": resolved_model, "usage": usage} + + async def _stream_openai_responses( + self, + model: str, + prompt: str, + system_prompt: str | None = None, + *, + conversation_messages: 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 + ) + request_body: dict[str, Any] = { + "model": model, + "input": responses_input, + "max_output_tokens": self.max_tokens, + "store": False, + "stream": True, + } + resolved_system_prompt = self._resolve_system_prompt(system_prompt) + if resolved_system_prompt: + request_body["instructions"] = resolved_system_prompt + resolved_model = model + usage: dict[str, Any] = {} + async with httpx.AsyncClient(timeout=self.timeout) as client: + async with client.stream( + "POST", + f"{self.base_url}/responses", + headers=self._outbound_headers( + {"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"} + ), + json=request_body, + ) as response: + if response.status_code >= 400: + detail = (await response.aread()).decode("utf-8", errors="replace") + raise HTTPException( + status_code=status.HTTP_502_BAD_GATEWAY, + detail=f"AI provider request failed: {detail or response.status_code}", + ) + async for event_name, data_str in self._iter_sse_events(response): + if data_str == "[DONE]": + break + try: + chunk = json.loads(data_str) + except json.JSONDecodeError: + continue + if not isinstance(chunk, dict): + continue + ev_type = str(chunk.get("type") or event_name or "") + if ev_type == "response.output_text.delta" and isinstance(chunk.get("delta"), str) and chunk["delta"]: + yield {"event": "text", "delta": chunk["delta"]} + elif ("reasoning" in ev_type or "thinking" in ev_type) and isinstance(chunk.get("delta"), str) and chunk["delta"]: + yield {"event": "reasoning", "delta": chunk["delta"]} + elif ev_type == "response.completed": + resp_obj = chunk.get("response") if isinstance(chunk.get("response"), dict) else {} + if isinstance(resp_obj.get("model"), str) and resp_obj["model"]: + resolved_model = resp_obj["model"] + if isinstance(resp_obj.get("usage"), dict): + usage.update(resp_obj["usage"]) + yield {"event": "done", "provider": self.provider, "model": resolved_model, "usage": usage} + + async def _stream_ollama( + self, + model: str, + prompt: str, + system_prompt: str | None = None, + *, + conversation_messages: list[dict[str, str]] | None = None, + ) -> AsyncIterator[dict[str, Any]]: + ollama_prompt = self._format_ollama_prompt(prompt, conversation_messages) + request_body: dict[str, Any] = { + "model": model, + "stream": True, + "prompt": ollama_prompt, + "options": {"temperature": 0.2, "num_predict": self.max_tokens}, + } + resolved_system_prompt = self._resolve_system_prompt(system_prompt) + if resolved_system_prompt: + request_body["system"] = resolved_system_prompt + usage: dict[str, Any] = {} + async with httpx.AsyncClient(timeout=self.timeout) as client: + async with client.stream( + "POST", + f"{self.base_url}/api/generate", + headers=self._outbound_headers({"Content-Type": "application/json"}), + json=request_body, + ) as response: + if response.status_code >= 400: + detail = (await response.aread()).decode("utf-8", errors="replace") + raise HTTPException( + status_code=status.HTTP_502_BAD_GATEWAY, + detail=f"AI provider request failed: {detail or response.status_code}", + ) + async for line in response.aiter_lines(): + if not line.strip(): + continue + try: + chunk = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(chunk.get("thinking"), str) and chunk["thinking"]: + yield {"event": "reasoning", "delta": chunk["thinking"]} + if isinstance(chunk.get("response"), str) and chunk["response"]: + yield {"event": "text", "delta": chunk["response"]} + yield {"event": "done", "provider": self.provider, "model": model, "usage": usage} + def _requires_api_key(self) -> bool: return self.provider_api != "ollama-generate" @@ -165,6 +562,44 @@ class ProviderService: if model and provider_api } + def _build_conversation_messages( + 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 []: + 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: + continue + if not normalized and role == "assistant": + continue + if normalized and normalized[-1]["role"] == role: + normalized[-1]["content"] = f"{normalized[-1]['content']}\n\n{content}" + else: + normalized.append({"role": role, "content": content}) + + if normalized and normalized[-1]["role"] == "user": + normalized[-1]["content"] = f"{normalized[-1]['content']}\n\n{final_prompt}" + else: + normalized.append({"role": "user", "content": final_prompt}) + return normalized + + @staticmethod + def _format_ollama_prompt( + prompt: str, + conversation_messages: list[dict[str, str]] | 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']}" + def _build_prompt(self, payload: SituationalAnalysisRequest) -> str: sections = [ f"任务标题:\n{payload.title}", @@ -187,12 +622,17 @@ class ProviderService: model: str, prompt: str, system_prompt: str | None = None, + *, + conversation_messages: list[dict[str, str]] | None = None, ) -> dict[str, Any]: messages = [] resolved_system_prompt = self._resolve_system_prompt(system_prompt) if resolved_system_prompt: messages.append({"role": "system", "content": resolved_system_prompt}) - messages.append({"role": "user", "content": prompt}) + if conversation_messages and len(conversation_messages) > 1: + messages.extend(conversation_messages) + else: + messages.append({"role": "user", "content": prompt}) request_body = { "model": model, "messages": messages, @@ -209,10 +649,23 @@ class ProviderService: ) async def _request_openai_responses( - self, model: str, prompt: str, system_prompt: str | None = None, + self, + model: str, + prompt: str, + system_prompt: str | None = None, + *, + conversation_messages: 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 + ) request_body: dict[str, Any] = { - "model": model, "input": prompt, "max_output_tokens": self.max_tokens, "store": False, + "model": model, + "input": responses_input, + "max_output_tokens": self.max_tokens, + "store": False, } resolved_system_prompt = self._resolve_system_prompt(system_prompt) if resolved_system_prompt: @@ -247,44 +700,20 @@ class ProviderService: prompt: str, thinking: dict[str, Any] | None = None, system_prompt: str | None = None, + *, + conversation_messages: list[dict[str, str]] | None = None, ) -> dict[str, Any]: - request_body = { - "model": model, - "messages": [ - { - "role": "user", - "content": [ - { - "type": "text", - "text": prompt, - } - ], - } - ], - "max_tokens": self.max_tokens, - "temperature": 0.2, - } - resolved_system_prompt = self._resolve_system_prompt(system_prompt) - if resolved_system_prompt: - request_body["system"] = resolved_system_prompt - resolved_thinking, resolved_output_config = self._resolve_anthropic_thinking( - thinking, model + path, headers, request_body = self._build_anthropic_request( + model, + prompt, + thinking, + system_prompt, + stream=False, + conversation_messages=conversation_messages, ) - if resolved_thinking: - request_body["thinking"] = resolved_thinking - if resolved_output_config: - request_body["output_config"] = resolved_output_config - if self.provider == "minimax" and self.base_url.endswith("/anthropic"): - path = "/v1/messages" - else: - path = "/messages" return await self._post( path=path, - headers={ - "x-api-key": self.api_key, - "anthropic-version": self.anthropic_version, - "Content-Type": "application/json", - }, + headers=headers, request_body=request_body, ) @@ -332,11 +761,13 @@ class ProviderService: model: str, prompt: str, system_prompt: str | None = None, + *, + conversation_messages: list[dict[str, str]] | None = None, ) -> dict[str, Any]: request_body = { "model": model, "stream": False, - "prompt": prompt, + "prompt": self._format_ollama_prompt(prompt, conversation_messages), "options": { "temperature": 0.2, "num_predict": self.max_tokens, diff --git a/aiprovider/schemas.py b/aiprovider/schemas.py index 3cc61395..2d232a06 100644 --- a/aiprovider/schemas.py +++ b/aiprovider/schemas.py @@ -1,8 +1,13 @@ -from typing import Any +from typing import Any, Literal from pydantic import BaseModel, Field +class ChatMessage(BaseModel): + role: Literal["user", "assistant"] + content: str = Field(..., min_length=1, max_length=12000) + + class AIContentBlock(BaseModel): type: str text: str | None = None @@ -20,6 +25,7 @@ class SituationalAnalysisRequest(BaseModel): 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) class SituationalAnalysisResponse(BaseModel): diff --git a/backend/app/api/v1/settings.py b/backend/app/api/v1/settings.py index bdce446a..9ee87fa6 100644 --- a/backend/app/api/v1/settings.py +++ b/backend/app/api/v1/settings.py @@ -66,7 +66,12 @@ from app.services.llm_provider_catalog import ( list_fallback_llm_provider_presets, refresh_llm_provider_preset, ) -from app.services.llm_model_catalog import catalog_error_message, fetch_model_catalog +from app.services.llm_model_catalog import ( + LLMProviderCatalogConfigError, + catalog_error_message, + catalog_requires_api_key, + fetch_model_catalog, +) from app.services.scheduler import sync_datasource_job from app.services.tv_streams import DEFAULT_TV_SETTINGS, get_tv_settings_payload, normalize_tv_settings from app.services.persistent_logs import record_audit_log @@ -840,7 +845,7 @@ async def _check_ai_provider_lightweight(llm_config: dict, timeout_seconds: int) } if not base_url or not model: return {**result, "message": "当前 provider/base_url/model 未完整配置。"} - if provider_api != ProviderApi.OLLAMA_GENERATE.value and not api_key: + if provider != "ollama" and provider_api != ProviderApi.OLLAMA_GENERATE.value and not api_key: return {**result, "message": "当前 provider 未配置 API Key。"} try: catalog = await fetch_model_catalog( @@ -2145,6 +2150,74 @@ async def get_ai_provider_presets( } +async def refresh_public_llm_provider_presets(db: AsyncSession) -> dict: + current_payload = await get_setting_payload(db, "external_integrations") + ai_payload = _normalize_ai_provider_payload(current_payload.get("ai_provider") or {}) + results: list[dict] = [] + for preset in list_fallback_llm_provider_presets(): + provider_id = preset["provider"] + 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): + continue + try: + refreshed = await refresh_llm_provider_preset( + provider_id, + api_key="", + base_url=base_url, + provider_api=provider_api, + anthropic_version=provider_config.get("anthropic_version") or "2023-06-01", + ) + except Exception as exc: + logger.warning( + "LLM provider catalog refresh failed", + extra={ + "event": "settings.ai_provider.catalog.failed", + "context": { + "provider": provider_id, + "error_type": type(exc).__name__, + }, + }, + ) + results.append( + { + "provider": provider_id, + "status": "failed", + "error": f"{catalog_error_message(exc)} 已保留上次模型列表。", + } + ) + continue + + refreshed["refreshed_at"] = to_iso8601_utc(datetime.now(UTC)) + await save_setting_payload( + db, f"{LLM_PROVIDER_PRESET_CATEGORY_PREFIX}{provider_id}", refreshed + ) + results.append( + { + "provider": provider_id, + "status": "refreshed", + "models_count": len(refreshed["models"]), + "refreshed_at": refreshed["refreshed_at"], + "source": refreshed["source"], + } + ) + return { + "data": results, + "refreshed": [item["provider"] for item in results if item["status"] == "refreshed"], + "failed": [item["provider"] for item in results if item["status"] == "failed"], + } + + +@router.post("/integrations/ai-provider/presets/refresh-public") +async def refresh_public_ai_provider_presets( + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db), +): + _require_admin(current_user, "Only administrators can refresh AI provider presets") + return await refresh_public_llm_provider_presets(db) + + @router.post("/integrations/ai-provider/presets/{provider}/refresh") async def refresh_ai_provider_preset( provider: str, @@ -2152,9 +2225,10 @@ async def refresh_ai_provider_preset( db: AsyncSession = Depends(get_db), payload: AIProviderIntegrationUpdate | None = None, ): + _require_admin(current_user, "Only administrators can refresh AI provider presets") try: provider_id = _normalize_provider_id(provider) - get_fallback_llm_provider_preset(provider_id) + fallback = get_fallback_llm_provider_preset(provider_id) except ValueError as exc: raise HTTPException(status_code=404, detail=str(exc)) from exc @@ -2166,17 +2240,23 @@ async def refresh_ai_provider_preset( else: ai_payload = _normalize_ai_provider_payload(current_payload.get("ai_provider") or {}) provider_config = ai_payload["providers"].get(provider_id) or _provider_defaults(provider_id) + 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 provider_id not in {"ollama", "opencode-go", "openrouter"}: + if not api_key and catalog_requires_api_key(provider_id, resolved_base_url, resolved_api): raise HTTPException( status_code=400, detail="请先配置当前供应商的 API Key,再刷新模型列表。", ) try: refreshed = await refresh_llm_provider_preset( - provider_id, api_key=api_key, base_url=provider_config.get("base_url"), - provider_api=provider_config.get("provider_api"), + provider_id, + api_key=api_key, + base_url=resolved_base_url, + provider_api=resolved_api, anthropic_version=provider_config.get("anthropic_version") or "2023-06-01", ) + except LLMProviderCatalogConfigError as exc: + raise HTTPException(status_code=400, detail=catalog_error_message(exc)) from exc except Exception as exc: logger.warning( "LLM provider catalog refresh failed", diff --git a/backend/app/api/v1/situational_awareness.py b/backend/app/api/v1/situational_awareness.py index b6ed186f..488be42d 100644 --- a/backend/app/api/v1/situational_awareness.py +++ b/backend/app/api/v1/situational_awareness.py @@ -7,7 +7,8 @@ from datetime import UTC, datetime import uuid from typing import Any, Literal -from fastapi import APIRouter, Depends, HTTPException, Query, Response +from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response +from fastapi.responses import StreamingResponse from pydantic import BaseModel, ConfigDict, Field from sqlalchemy import desc, select from sqlalchemy.ext.asyncio import AsyncSession @@ -53,6 +54,7 @@ from app.services.ai.workflow_runtime import ( get_active_run_handle, read_frozen_result_revision, ) +from app.services.ai.stream_turn import stream_session_turn from app.services.ai_client import AIProviderClient, get_ai_provider_client from app.services.compute_history import ComputeSeriesMode @@ -79,6 +81,13 @@ class SessionPinUpdateRequest(BaseModel): pinned_items: list[dict[str, Any]] = Field(default_factory=list, max_length=12) +class HistoryMessageItem(BaseModel): + model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) + + role: Literal["user", "assistant"] + content: str = Field(min_length=1, max_length=6000) + + class SessionTurnRequest(BaseModel): model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) @@ -95,6 +104,11 @@ class SessionTurnRequest(BaseModel): preset: ViewPreset | None = None prefer_llm: bool | Literal["auto"] = False external_urls: list[str] = Field(default_factory=list, max_length=3) + news_context: dict[str, Any] | None = None + history: list[HistoryMessageItem] = Field(default_factory=list, max_length=40) + conversation_summary: str | None = Field(default=None, max_length=2400) + memory_notes: list[str] = Field(default_factory=list, max_length=12) + pinned_summaries: list[str] = Field(default_factory=list, max_length=8) run_id: str | None = Field(default=None, min_length=4, max_length=64, pattern=r"^[A-Za-z0-9_-]+$") @@ -340,6 +354,68 @@ async def create_session_turn( return turn_result +@router.post("/sessions/{session_id}/turns/stream") +async def stream_investigation_session_turn( + session_id: str, + payload: SessionTurnRequest, + request: Request, + response: Response, + access: AccessContext = Depends(resolve_access_context), + db: AsyncSession = Depends(get_db), + ai_client: AIProviderClient = Depends(get_ai_provider_client), +) -> StreamingResponse: + """Adaptive SSE endpoint streaming LLM reasoning & answer when configured, else grounded baseline.""" + session_row: InvestigationSession | None = None + effective_access = access + issued_token: str | None = None + if session_id == "stateless": + owner_key, issued_token = ensure_session_owner_identity(access, response) + effective_access = replace(access, actor_key=owner_key, has_session_credential=True) + else: + session_row = await _load_owned_session_or_fail(session_id, access, db) + + codes = ( + selected_countries(",".join(payload.selected_codes)) + if payload.selected_codes + else None + ) + overrides = { + "domain": payload.domain, + "selected_codes": codes, + "mode": payload.mode, + "focus_year": payload.focus_year, + "entity_id": payload.entity_id, + "visible_layers": payload.visible_layers, + "time_basis": payload.time_basis, + "cutoff_at": payload.cutoff_at, + "include_drill": payload.include_drill, + } + headers = { + "Cache-Control": "no-cache", + "X-Accel-Buffering": "no", + } + return StreamingResponse( + stream_session_turn( + db, + request=request, + session=session_row, + question=payload.question, + context_override=overrides, + news_context=payload.news_context, + history=[item.model_dump() for item in payload.history], + conversation_summary=payload.conversation_summary, + memory_notes=payload.memory_notes, + pinned_summaries=payload.pinned_summaries, + access=effective_access, + ai_client=ai_client, + client_run_id=payload.run_id, + issued_session_token=issued_token, + ), + media_type="text/event-stream", + headers=headers, + ) + + # ============================================================================ # Group 3: WorkflowRun Inspection & Explicit Cancellation # ============================================================================ diff --git a/backend/app/main.py b/backend/app/main.py index c8434b12..a36b5fe0 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -186,7 +186,25 @@ app = FastAPI( openapi_url="/openapi.json", ) -app.add_middleware(GZipMiddleware, minimum_size=1024) +class NonStreamingGZipMiddleware: + """Apply GZip compression while skipping SSE streaming responses so events flush immediately.""" + + def __init__(self, app, minimum_size: int = 1024) -> None: + self.app = app + self.gzip_app = GZipMiddleware(app, minimum_size=minimum_size) + + async def __call__(self, scope, receive, send) -> None: + if scope.get("type") == "http": + path = str(scope.get("path") or "") + headers = dict(scope.get("headers") or []) + accept = headers.get(b"accept", b"").lower() + if path.endswith("/stream") or b"text/event-stream" in accept: + await self.app(scope, receive, send) + return + await self.gzip_app(scope, receive, send) + + +app.add_middleware(NonStreamingGZipMiddleware, minimum_size=1024) configured_origins = list(settings.CORS_ORIGINS or []) app.add_middleware( diff --git a/backend/app/schemas/ai.py b/backend/app/schemas/ai.py index 938a6820..1eacf6a6 100644 --- a/backend/app/schemas/ai.py +++ b/backend/app/schemas/ai.py @@ -1,9 +1,15 @@ -from typing import Any +from typing import Any, Literal from pydantic import BaseModel, Field from app.core.enums import PlaygroundMessageKind, PlaygroundMessageRole, PlaygroundMessageStatus + +class ChatMessage(BaseModel): + role: Literal["user", "assistant"] + content: str = Field(..., min_length=1, max_length=12000) + + class AIContentBlock(BaseModel): type: str text: str | None = None @@ -21,6 +27,7 @@ class SituationalAnalysisRequest(BaseModel): 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) class BGPBriefRequest(BaseModel): diff --git a/backend/app/services/ai/conversation_memory.py b/backend/app/services/ai/conversation_memory.py new file mode 100644 index 00000000..75478ebe --- /dev/null +++ b/backend/app/services/ai/conversation_memory.py @@ -0,0 +1,209 @@ +"""Multi-turn conversation sanitization, rolling compaction, and lightweight memory formatting.""" + +from __future__ import annotations + +import asyncio +from typing import Any + +from app.core.logging import get_logger +from app.schemas.ai import SituationalAnalysisRequest +from app.services.ai.thinking_sanitizer import prepare_situational_ai_call, strip_thinking_text +from app.services.ai_client import AIProviderClient + +logger = get_logger(__name__, service="ai_memory") + +RECENT_WINDOW_TURNS = 4 +COMPACT_TRIGGER_CHARS = 7500 +MAX_MESSAGE_CHARS = 1800 +MAX_SUMMARY_CHARS = 1600 +MAX_MEMORY_NOTES = 12 +MAX_PINNED_SUMMARIES = 8 + + +def _truncate_text(text: str, limit: int) -> str: + cleaned = str(text or "").strip() + if len(cleaned) <= limit: + return cleaned + return f"{cleaned[: max(0, limit - 1)].rstrip()}…" + + +def sanitize_history_messages(raw_messages: list[Any] | None) -> list[dict[str, str]]: + """Strip inline thinking blocks, truncate extremes, and normalize alternating user/assistant turns.""" + normalized: list[dict[str, str]] = [] + for item in raw_messages or []: + if isinstance(item, dict): + role = str(item.get("role") or "").strip().lower() + raw_content = item.get("content") + else: + role = str(getattr(item, "role", "") or "").strip().lower() + raw_content = getattr(item, "content", "") + if role not in {"user", "assistant"}: + continue + content = str(raw_content or "").strip() + if not content: + continue + if role == "assistant": + clean_content, _ = strip_thinking_text(content) + content = clean_content or content + content = _truncate_text(content, MAX_MESSAGE_CHARS) + if not content: + continue + if not normalized and role == "assistant": + continue + if normalized and normalized[-1]["role"] == role: + merged = f"{normalized[-1]['content']}\n\n{content}" + normalized[-1]["content"] = _truncate_text(merged, MAX_MESSAGE_CHARS) + else: + normalized.append({"role": role, "content": content}) + return normalized + + +def _sanitize_short_list(items: list[Any] | None, *, max_items: int, max_chars: int = 200) -> list[str]: + result: list[str] = [] + seen: set[str] = set() + for raw in items or []: + text = _truncate_text(str(raw or "").replace("\r", " ").replace("\n", " "), max_chars) + if not text or text in seen: + continue + seen.add(text) + result.append(text) + if len(result) >= max_items: + break + return result + + +def sanitize_memory_notes(notes: list[Any] | None) -> list[str]: + """Return deduplicated short user memory notes within configured cap.""" + return _sanitize_short_list(notes, max_items=MAX_MEMORY_NOTES) + + +def sanitize_pinned_summaries(items: list[Any] | None) -> list[str]: + """Return deduplicated short pinned comparison summaries within configured cap.""" + return _sanitize_short_list(items, max_items=MAX_PINNED_SUMMARIES) + + +def build_deterministic_compaction_summary( + existing_summary: str, + dropped_messages: list[dict[str, str]], +) -> str: + """Build a bounded structured summary when older turns overflow the active window.""" + lines: list[str] = [] + prior = str(existing_summary or "").strip() + if prior: + lines.append(prior) + + pair_lines: list[str] = [] + idx = 0 + while idx < len(dropped_messages): + msg = dropped_messages[idx] + if msg["role"] == "user": + q = _truncate_text(msg["content"].replace("\n", " "), 120) + a = "" + if idx + 1 < len(dropped_messages) and dropped_messages[idx + 1]["role"] == "assistant": + a = _truncate_text(dropped_messages[idx + 1]["content"].replace("\n", " "), 180) + idx += 2 + else: + idx += 1 + pair_lines.append(f"- 问:{q}" + (f" → 结:{a}" if a else "")) + else: + a = _truncate_text(msg["content"].replace("\n", " "), 160) + pair_lines.append(f"- 历史结论:{a}") + idx += 1 + + if pair_lines: + block = "\n".join(pair_lines) + if prior and not prior.startswith("### 前序对话摘要"): + lines = [f"### 前序对话摘要\n{prior}", block] + elif prior: + lines = [prior, block] + else: + lines = [f"### 前序对话摘要\n{block}"] + + combined = "\n".join(lines).strip() + if len(combined) > MAX_SUMMARY_CHARS: + head = "### 前序对话摘要\n" + tail_budget = MAX_SUMMARY_CHARS - len(head) - 2 + combined = f"{head}…{combined[-tail_budget:].lstrip()}" + return combined + + +async def compact_conversation_history( + raw_messages: list[Any] | None, + existing_summary: str = "", + *, + ai_client: AIProviderClient | None = None, + ai_ready: bool = False, + recent_window_turns: int = RECENT_WINDOW_TURNS, + char_budget: int = COMPACT_TRIGGER_CHARS, +) -> dict[str, Any]: + """Keep recent window verbatim and compact overflow turns into a rolling summary.""" + sanitized = sanitize_history_messages(raw_messages) + summary = _truncate_text(existing_summary or "", MAX_SUMMARY_CHARS) + + keep_limit = max(2, recent_window_turns * 2) + split_idx = max(0, len(sanitized) - keep_limit) + if split_idx < len(sanitized) and sanitized[split_idx]["role"] == "assistant": + split_idx += 1 + + older = sanitized[:split_idx] + recent = sanitized[split_idx:] + + total_chars = len(summary) + sum(len(m["content"]) for m in recent) + while not older and total_chars > char_budget and len(recent) > 2: + move_count = 2 if (len(recent) >= 4 and recent[0]["role"] == "user" and recent[1]["role"] == "assistant") else 1 + older.extend(recent[:move_count]) + recent = recent[move_count:] + total_chars = len(summary) + sum(len(m["content"]) for m in recent) + + if not older: + return { + "summary": summary, + "recent_messages": recent, + "compacted": False, + "compacted_count": 0, + } + + next_summary = "" + if ai_ready and ai_client is not None: + try: + effective_client = ai_client + if type(ai_client) is AIProviderClient and ai_client.llm_config: + effective_client, _ = prepare_situational_ai_call(ai_client, min_max_tokens=900) + transcript = "\n".join( + f"{'用户' if m['role'] == 'user' else 'AI 参谋'}: {m['content']}" for m in older + ) + compact_req = SituationalAnalysisRequest( + title="Planet 多轮对话上下文压缩摘要", + objective=( + "请将以下较早的多轮对话与既有摘要压缩为简明中文备忘(不超过 280 字)," + "保留:1) 用户聚焦的图层/国家/新闻实体与口径边界;2) 已核验关键数据结论;" + "3) 尚未完结的追问线索。严禁保留客套或编造数值。" + ), + system_prompt="你是精准的对话上下文压缩器,只输出精炼中文要点摘要。", + context={ + "existing_summary": summary or None, + "archived_dialogue": transcript, + }, + thinking=None, + ) + resp = await asyncio.wait_for(effective_client.analyze(compact_req), timeout=12.0) + clean_resp, _ = strip_thinking_text(str(getattr(resp, "content", "") or "")) + next_summary = _truncate_text(clean_resp, MAX_SUMMARY_CHARS) + except asyncio.CancelledError: + raise + except Exception as exc: + logger.warning_event( + "LLM conversation compaction fell back to deterministic summary", + event="ai_memory.compaction.fallback", + context={"error": str(exc), "older_count": len(older)}, + ) + + if not next_summary: + next_summary = build_deterministic_compaction_summary(summary, older) + + return { + "summary": next_summary, + "recent_messages": recent, + "compacted": True, + "compacted_count": len(older), + } diff --git a/backend/app/services/ai/domain_catalog.py b/backend/app/services/ai/domain_catalog.py index 4bee6e25..30908869 100644 --- a/backend/app/services/ai/domain_catalog.py +++ b/backend/app/services/ai/domain_catalog.py @@ -4,7 +4,7 @@ from __future__ import annotations from typing import Literal -WorkbenchDomain = Literal["global", "compute", "bgp", "cable", "satellite", "vessel"] +WorkbenchDomain = Literal["global", "compute", "bgp", "cable", "satellite", "vessel", "news"] SpatialDomain = Literal["global", "cable", "satellite", "vessel"] ReportSubjectType = Literal[ "global_posture", @@ -13,11 +13,12 @@ ReportSubjectType = Literal[ "cable_posture", "satellite_posture", "vessel_posture", + "news_brief", ] SPATIAL_POSTURE_DOMAINS: frozenset[str] = frozenset({"global", "cable", "satellite", "vessel"}) SUPPORTED_WORKBENCH_DOMAINS: frozenset[str] = frozenset( - {"global", "compute", "bgp", "cable", "satellite", "vessel"} + {"global", "compute", "bgp", "cable", "satellite", "vessel", "news"} ) DOMAIN_TO_SUBJECT_TYPE: dict[str, ReportSubjectType] = { @@ -27,6 +28,7 @@ DOMAIN_TO_SUBJECT_TYPE: dict[str, ReportSubjectType] = { "cable": "cable_posture", "satellite": "satellite_posture", "vessel": "vessel_posture", + "news": "news_brief", } SUBJECT_TYPE_TO_DOMAIN: dict[str, WorkbenchDomain] = { @@ -36,6 +38,7 @@ SUBJECT_TYPE_TO_DOMAIN: dict[str, WorkbenchDomain] = { "cable_posture": "cable", "satellite_posture": "satellite", "vessel_posture": "vessel", + "news_brief": "news", } diff --git a/backend/app/services/ai/spatial_domain_agent.py b/backend/app/services/ai/spatial_domain_agent.py index 0d5cc9c8..c95f2dd2 100644 --- a/backend/app/services/ai/spatial_domain_agent.py +++ b/backend/app/services/ai/spatial_domain_agent.py @@ -520,7 +520,7 @@ async def investigate_spatial_domain( timeout=35.0, ) _raise_if_cancelled(cancel_event) - raw_text = (llm_resp.answer or "").strip() + raw_text = (llm_resp.content or "").strip() assert_no_thinking_leak(raw_text) parsed = extract_json_object(raw_text) if not isinstance(parsed, dict): diff --git a/backend/app/services/ai/stream_turn.py b/backend/app/services/ai/stream_turn.py new file mode 100644 index 00000000..2df4a572 --- /dev/null +++ b/backend/app/services/ai/stream_turn.py @@ -0,0 +1,613 @@ +"""Adaptive SSE streaming turn orchestrator with thinking process, model attribution, and news context.""" + +from __future__ import annotations + +import asyncio +from collections import defaultdict, deque +from collections.abc import AsyncIterator +from datetime import UTC, datetime, timedelta +import json +import os +from typing import Any +import uuid + +from fastapi import HTTPException, Request, status +from sqlalchemy.ext.asyncio import AsyncSession + +from app.core.logging import get_logger +from app.models.situational_assessment import InvestigationSession +from app.schemas.ai import ChatMessage, SituationalAnalysisRequest +from app.services.ai.access_policy import AccessContext +from app.services.ai.conversation_memory import ( + compact_conversation_history, + sanitize_memory_notes, + sanitize_pinned_summaries, +) +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_runtime import classify_turn_intent, execute_session_turn +from app.services.ai_client import AIProviderClient + +logger = get_logger(__name__, service="ai_stream") + +_STREAM_QUOTA_WINDOW: dict[str, deque[datetime]] = defaultdict(deque) +_GEOPOLITICAL_OR_NEWS_KEYWORDS = ( + "国际局势", + "全球局势", + "地缘", + "新闻", + "报道", + "外交", + "冲突", + "制裁", + "关税", + "战争", + "和平", + "热点", + "geopolit", + "headline", + "news", + "international situation", + "world situation", +) + + +def reset_stream_quota_ledger() -> None: + """Reset in-memory public stream rate limiter state (for deterministic tests).""" + _STREAM_QUOTA_WINDOW.clear() + + +def check_stream_quota(access: AccessContext) -> None: + """Enforce bounded hourly quota on adaptive streaming AI turns across all access tiers.""" + default_public_cap = int(os.getenv("PLANET_PUBLIC_AI_STREAM_HOURLY_QUOTA", "60")) + limit = access.hourly_paid_quota if access.hourly_paid_quota > 0 else default_public_cap + if limit <= 0: + return + + now = datetime.now(UTC) + window_start = now - timedelta(hours=1) + dq = _STREAM_QUOTA_WINDOW[access.actor_key] + while dq and dq[0] < window_start: + dq.popleft() + if len(dq) >= limit: + raise HTTPException( + status_code=status.HTTP_429_TOO_MANY_REQUESTS, + detail=f"Hourly AI stream quota ({limit}) exceeded.", + ) + dq.append(now) + + +def build_streaming_thinking_config(ai_client: AIProviderClient) -> dict[str, Any] | None: + """Enable streamed reasoning tokens for MiniMax/Anthropic providers when streaming turns.""" + llm_cfg = getattr(ai_client, "llm_config", None) or {} + provider = str(llm_cfg.get("provider") or "").strip().lower() + provider_api = str(llm_cfg.get("provider_api") or "").strip().lower() + model = str(llm_cfg.get("model") or "").strip().lower() + + if "minimax-m3" in model: + return {"type": "adaptive", "effort": "medium"} + if provider == "minimax" or provider_api == "anthropic-messages" or "anthropic" in provider or "claude" in model: + return {"type": "enabled", "budget_tokens": 2048} + return None + + +def _is_geopolitical_or_news_question( + question: str, + *, + domain: str, + news_context: dict[str, Any] | None, +) -> bool: + if domain == "news" or news_context: + return True + q = (question or "").strip().lower() + return any(kw in q for kw in _GEOPOLITICAL_OR_NEWS_KEYWORDS) + + +def _format_sse(event: str, payload: dict[str, Any]) -> str: + return f"event: {event}\ndata: {json.dumps(payload, ensure_ascii=False, default=str)}\n\n" + + +def _build_news_fallback_markdown( + *, + question: str, + news_context: dict[str, Any] | None, + recent_news: dict[str, Any], + ai_configured: bool, + fallback_reason: str | None = None, +) -> str: + lines: list[str] = [] + if news_context: + title = str(news_context.get("title") or "新闻速递").strip() + source = str(news_context.get("source") or "").strip() + region = str(news_context.get("region") or news_context.get("region_key") or "").strip() + published_at = str(news_context.get("published_at") or "").strip() + summary = str(news_context.get("summary") or "").strip() + lines.append(f"### 新闻焦点:{title}") + meta_parts = [p for p in (source, region, published_at) if p] + if meta_parts: + lines.append(f"- **来源与时间**:{' · '.join(meta_parts)}") + if summary: + lines.append(f"- **报道摘要**:{summary}") + else: + lines.append("### 全球局势与新闻态势速览") + if question: + lines.append(f"- **当前问题**:{question}") + + items = list(recent_news.get("items") or []) + if items: + lines.append("") + lines.append("#### 近期关联动态") + for item in items[:5]: + item_title = str(item.get("title") or "").strip() + item_src = str(item.get("source") or "").strip() + item_reg = str(item.get("region") or "").strip() + if item_title: + meta = f"({item_src}{' · ' + item_reg if item_reg else ''})" if item_src else "" + lines.append(f"- {item_title}{meta}") + + if not ai_configured: + lines.append("") + lines.append("> 当前后台尚未接入可用 AI 大模型,以上为内置新闻与遥测结构化汇总。") + elif fallback_reason: + lines.append("") + lines.append(f"> AI 流式生成暂时不可用({fallback_reason}),已自动回退为内置结构化汇总。") + return "\n".join(lines).strip() + + +def _build_news_analysis_request( + *, + question: str, + news_context: dict[str, Any] | None, + recent_news: dict[str, Any], + global_snapshot: dict[str, Any], + thinking_cfg: dict[str, Any] | None, + conversation_messages: list[ChatMessage] | None = None, + conversation_summary: str = "", + memory_notes: list[str] | None = None, + pinned_summaries: list[str] | None = None, +) -> SituationalAnalysisRequest: + context: dict[str, Any] = { + "focused_news": news_context or None, + "recent_news_headlines": (recent_news.get("items") or [])[:10], + "global_infrastructure_summary": global_snapshot.get("domain_summaries") or [], + } + if conversation_summary: + context["conversation_summary"] = conversation_summary + if memory_notes: + context["user_memory_notes"] = memory_notes + if pinned_summaries: + context["pinned_comparisons"] = pinned_summaries + return SituationalAnalysisRequest( + title="Planet 全球新闻与国际局势研判", + objective=( + f"用户提问:{question}\n\n" + "请结合多轮对话延续性与记忆备忘,直接使用中文(若用户用英文提问则用英文)输出结构清晰的 Markdown 深度分析,包括:\n" + "1. **核心事实与背景脉络**(紧扣聚焦新闻或近期头条);\n" + "2. **地缘、产业与基础设施影响**(可结合海缆/算力/航运/卫星/BGP 背景若相关,无直接关联则勿强行牵连);\n" + "3. **后续重点观察信号与不确定边界**。\n" + "请直接输出面向用户的 Markdown 正文,不要包在 JSON 里。" + ), + system_prompt=( + "你是 Planet(智能星球计划)的全球新闻与国际局势分析参谋。" + "如有前序对话与用户备忘录,请保持指代与口径延续。" + "请严谨区分已报道事实与推演研判,禁止虚构具体伤亡、断缆或未经报道的内部消息。" + ), + context=context, + constraints=[ + "Output clean user-facing Markdown directly (not JSON).", + "Distinguish reported facts from analytical outlook.", + ], + thinking=thinking_cfg, + messages=conversation_messages or [], + ) + + +def _build_telemetry_stream_request( + *, + domain: str, + question: str, + base_answer_md: str, + evidence: dict[str, Any], + view_spec: dict[str, Any] | None, + recent_news: dict[str, Any] | None, + thinking_cfg: dict[str, Any] | None, + conversation_messages: list[ChatMessage] | None = None, + conversation_summary: str = "", + memory_notes: list[str] | None = None, + pinned_summaries: list[str] | None = None, +) -> SituationalAnalysisRequest: + context: dict[str, Any] = { + "domain": domain, + "verified_baseline_summary": base_answer_md, + "evidence": evidence, + "view_headline": (view_spec or {}).get("headline"), + } + if recent_news and recent_news.get("items"): + context["recent_news_headlines"] = (recent_news.get("items") or [])[:10] + if conversation_summary: + context["conversation_summary"] = conversation_summary + if memory_notes: + context["user_memory_notes"] = memory_notes + if pinned_summaries: + context["pinned_comparisons"] = pinned_summaries + return SituationalAnalysisRequest( + title=f"Planet 态势参谋分析({domain})", + objective=( + f"用户问题:{question}\n\n" + "请严格基于 context 中的已核验内置遥测结论、证据源、前序对话摘要/记忆备忘与关联新闻头条," + "使用清晰自然的 Markdown 直接回答用户问题,给出结构化洞察与口径边界,不要输出 JSON 对象。" + ), + system_prompt=( + "你是 Planet 空间与网络基础设施态势参谋。如有前序对话与用户记忆备忘,请延续语境与偏好;" + "所有具体数值必须与 context 一致,不得编造未给出的实时数值或故障原因;直接输出高质量 Markdown 分析正文。" + ), + context=context, + constraints=[ + "Output clean Markdown directly (not JSON).", + "Do not invent telemetry counts or unverified outages outside context.", + ], + thinking=thinking_cfg, + messages=conversation_messages or [], + ) + + +async def stream_session_turn( + db: AsyncSession, + *, + request: Request | None, + session: InvestigationSession | None, + question: str, + context_override: dict[str, Any] | None, + news_context: dict[str, Any] | None, + access: AccessContext, + ai_client: AIProviderClient | None, + client_run_id: str | None = None, + issued_session_token: str | None = None, + history: list[dict[str, Any]] | None = None, + conversation_summary: str | None = None, + memory_notes: list[str] | None = None, + pinned_summaries: list[str] | None = None, +) -> AsyncIterator[str]: + """Adaptive SSE generator: streams real LLM + thinking when AI is configured, else grounded baseline.""" + check_stream_quota(access) + + session_id_val = str(session.id) if session is not None else "stateless" + run_id = client_run_id or f"run-{uuid.uuid4().hex[:12]}" + + merged_ctx: dict[str, Any] = {} + if session is not None and isinstance(session.context_state, dict): + merged_ctx.update(session.context_state) + if context_override: + for k, v in context_override.items(): + if v is not None: + merged_ctx[k] = v + + raw_history = history if history else merged_ctx.get("recent_messages") + existing_summary = str( + conversation_summary + if conversation_summary is not None + else merged_ctx.get("conversation_summary") or "" + ) + clean_memory_notes = sanitize_memory_notes(memory_notes) + clean_pinned_summaries = sanitize_pinned_summaries( + pinned_summaries + if pinned_summaries is not None + else [ + f"{p.get('pin_id', 'PIN')}: {p.get('title', '')}" + for p in ((getattr(session, "pinned_items", None) or []) if session is not None else []) + if isinstance(p, dict) and p.get("title") + ] + ) + + routed = classify_turn_intent(question, merged_ctx) + explicit_domain = str((context_override or {}).get("domain") or "").strip().lower() + domain = "news" if news_context or explicit_domain == "news" else str(routed.get("domain") or "global") + is_pure_view = bool(routed.get("is_pure_projection") or routed.get("auto_play_presentation")) + geo_or_news_query = _is_geopolitical_or_news_question( + question, + domain=domain, + news_context=news_context, + ) + + time_basis: TimeBasis = (context_override or {}).get("time_basis") or merged_ctx.get("time_basis") or "retrospective" + cutoff_at: str | None = (context_override or {}).get("cutoff_at") or merged_ctx.get("cutoff_at") + codes = list((context_override or {}).get("selected_codes") or merged_ctx.get("selected_codes") or ["CN", "US"]) + visible_layers = dict((context_override or {}).get("visible_layers") or merged_ctx.get("visible_layers") or {}) + + ai_ready = False + provider_name = "" + model_name = "" + if ai_client is not None: + ai_ready, provider_name, model_name = await ai_client.is_ready() + + compaction = await compact_conversation_history( + raw_history, + existing_summary, + ai_client=ai_client, + ai_ready=ai_ready, + ) + compacted_summary = str(compaction.get("summary") or "") + recent_history = list(compaction.get("recent_messages") or []) + compacted_flag = bool(compaction.get("compacted")) + memory_used_flag = bool(compacted_summary or recent_history or clean_memory_notes or clean_pinned_summaries) + + view_spec: dict[str, Any] | None = None + scene_spec: dict[str, Any] | None = None + evidence: dict[str, Any] = {} + subject_key = "global" + revision = 1 + base_answer_md = "" + context_state: dict[str, Any] = {**merged_ctx, "domain": domain} + recent_news: dict[str, Any] = {"items": [], "evidence": {}} + + if news_context or domain == "news": + news_region = str((news_context or {}).get("region_key") or "").strip() or None + recent_news = await query_recent_earth_news_tool(db, region=news_region, limit=10) + global_snap = await query_global_situational_tool( + db, + selected_codes=codes, + visible_layers=visible_layers, + time_basis=time_basis, + cutoff_at=cutoff_at, + ) + evidence = {**(recent_news.get("evidence") or {}), **(global_snap.get("evidence") or {})} + if news_context and news_context.get("url"): + evidence["ev-news-focus"] = { + "id": "ev-news-focus", + "title": str(news_context.get("title") or "聚焦新闻"), + "publisher": str(news_context.get("source") or "Planet News"), + "url": str(news_context.get("url") or ""), + "published_at": str(news_context.get("published_at") or ""), + "locator": str(news_context.get("region") or news_context.get("region_key") or "news"), + } + subject_key = f"news:{(news_context or {}).get('id') or news_region or 'global'}" + base_answer_md = _build_news_fallback_markdown( + question=question, + news_context=news_context, + recent_news=recent_news, + ai_configured=ai_ready, + ) + else: + base_turn = await execute_session_turn( + db, + session=session, + question=question, + context_override=context_override, + prefer_llm=False, + access=access, + ai_client=None, + client_run_id=None, + ) + view_spec = base_turn.get("view_spec") + scene_spec = base_turn.get("scene_spec") + evidence = base_turn.get("evidence") or {} + subject_key = str(base_turn.get("subject_key") or domain) + revision = int(base_turn.get("revision") or 1) + base_answer_md = str((base_turn.get("reply") or {}).get("answer_markdown") or "") + if isinstance(base_turn.get("context_state"), dict): + context_state = base_turn["context_state"] + if domain == "global" and (geo_or_news_query or ai_ready): + recent_news = await query_recent_earth_news_tool(db, limit=10) + evidence = {**evidence, **(recent_news.get("evidence") or {})} + if geo_or_news_query and not is_pure_view: + # Conversational international/news questions should focus on the narrative, not a static bar chart. + view_spec = None + scene_spec = None + if not ai_ready: + base_answer_md = _build_news_fallback_markdown( + question=question, + news_context=None, + recent_news=recent_news, + ai_configured=False, + ) + + meta_payload: dict[str, Any] = { + "session_id": session_id_val, + "run_id": run_id, + "domain": domain, + "subject_key": subject_key, + "revision": revision, + "ai_enabled": ai_ready and not is_pure_view, + "provider": provider_name if (ai_ready and not is_pure_view) else None, + "model": model_name if (ai_ready and not is_pure_view) else None, + "compacted": compacted_flag, + "conversation_summary": compacted_summary, + "memory_used": memory_used_flag, + "view_spec": view_spec, + "scene_spec": scene_spec, + "evidence": evidence, + "context_state": context_state, + } + if issued_session_token: + meta_payload["session_token"] = issued_session_token + yield _format_sse("meta", meta_payload) + + def _persist_session_memory(answer_text: str) -> None: + if session is None or not isinstance(session.context_state, dict): + return + updated_recent = [*recent_history, {"role": "user", "content": question}] + if answer_text: + updated_recent.append({"role": "assistant", "content": answer_text[:1800]}) + session.context_state = { + **session.context_state, + "conversation_summary": compacted_summary, + "recent_messages": updated_recent[-8:], + } + + if not ai_ready or is_pure_view or ai_client is None: + _persist_session_memory(base_answer_md) + if base_answer_md: + yield _format_sse("text", {"delta": base_answer_md}) + yield _format_sse( + "done", + { + "status": "completed", + "generation_mode": "deterministic_baseline", + "zero_token": True, + "provider": None, + "model": None, + "usage": {}, + "compacted": compacted_flag, + "conversation_summary": compacted_summary, + "memory_used": memory_used_flag, + "answer_markdown": base_answer_md, + "reasoning_markdown": "", + }, + ) + return + + conversation_messages = [ + ChatMessage(role=m["role"], content=m["content"]) for m in recent_history + ] + thinking_cfg = build_streaming_thinking_config(ai_client) + effective_client = ai_client + current_max = int((getattr(ai_client, "llm_config", None) or {}).get("max_tokens") or 0) + if type(ai_client) is AIProviderClient and ai_client.llm_config and current_max < 3200: + effective_client, _ = prepare_situational_ai_call(ai_client, min_max_tokens=3200) + analysis_req = ( + _build_news_analysis_request( + question=question, + news_context=news_context, + recent_news=recent_news, + global_snapshot=await query_global_situational_tool( + db, + selected_codes=codes, + visible_layers=visible_layers, + time_basis=time_basis, + cutoff_at=cutoff_at, + ), + thinking_cfg=thinking_cfg, + conversation_messages=conversation_messages, + conversation_summary=compacted_summary, + memory_notes=clean_memory_notes, + pinned_summaries=clean_pinned_summaries, + ) + if (news_context or domain == "news") + else _build_telemetry_stream_request( + domain=domain, + question=question, + base_answer_md=base_answer_md, + evidence=evidence, + view_spec=view_spec, + recent_news=recent_news if domain == "global" else None, + thinking_cfg=thinking_cfg, + conversation_messages=conversation_messages, + conversation_summary=compacted_summary, + memory_notes=clean_memory_notes, + pinned_summaries=clean_pinned_summaries, + ) + ) + + text_chunks: list[str] = [] + reasoning_chunks: list[str] = [] + resolved_provider = provider_name + resolved_model = model_name + final_usage: dict[str, Any] = {} + + try: + async for ev in effective_client.stream_analyze(analysis_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": + delta = ev.get("delta") + if isinstance(delta, str) and delta: + reasoning_chunks.append(delta) + yield _format_sse("reasoning", {"delta": delta}) + elif ev_type == "text": + delta = ev.get("delta") + if isinstance(delta, str) and delta: + text_chunks.append(delta) + yield _format_sse("text", {"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"] + if isinstance(ev.get("usage"), dict): + final_usage = ev["usage"] + elif ev_type == "error": + raise RuntimeError(str(ev.get("detail") or "AI stream error")) + + combined_text = "".join(text_chunks).strip() + if not combined_text: + raise RuntimeError("AI provider stream returned empty response") + + clean_text, inline_thoughts = strip_thinking_text(combined_text) + combined_reasoning = "".join(reasoning_chunks).strip() + if inline_thoughts: + extra_thought = "\n\n".join(inline_thoughts) + combined_reasoning = f"{combined_reasoning}\n\n{extra_thought}".strip() if combined_reasoning else extra_thought + + final_answer_md = clean_text or combined_text + _persist_session_memory(final_answer_md) + if hasattr(db, "commit"): + try: + await db.commit() + except Exception: + pass + + yield _format_sse( + "done", + { + "status": "completed", + "generation_mode": "llm_verified", + "zero_token": False, + "provider": resolved_provider, + "model": resolved_model, + "usage": final_usage, + "compacted": compacted_flag, + "conversation_summary": compacted_summary, + "memory_used": memory_used_flag, + "answer_markdown": final_answer_md, + "reasoning_markdown": combined_reasoning, + }, + ) + except asyncio.CancelledError: + raise + except Exception as exc: + logger.warning_event( + "AI stream turn failed", + event="ai_stream.llm.fallback", + context={"domain": domain, "emitted_text": bool(text_chunks), "error": str(exc)}, + ) + if text_chunks: + yield _format_sse("error", {"detail": str(exc), "partial": True}) + return + + fallback_md = ( + _build_news_fallback_markdown( + question=question, + news_context=news_context, + recent_news=recent_news, + ai_configured=True, + fallback_reason=str(exc), + ) + if (news_context or domain == "news" or geo_or_news_query) + else f"{base_answer_md}\n\n> AI 流式研判暂时回退:{exc}".strip() + ) + if fallback_md: + yield _format_sse("text", {"delta": fallback_md}) + yield _format_sse( + "done", + { + "status": "completed", + "generation_mode": "deterministic_fallback", + "zero_token": True, + "provider": None, + "model": None, + "usage": {}, + "answer_markdown": fallback_md, + "reasoning_markdown": "".join(reasoning_chunks).strip(), + "fallback_reason": str(exc), + }, + ) diff --git a/backend/app/services/ai/tool_registry.py b/backend/app/services/ai/tool_registry.py index c2add212..c3b42945 100644 --- a/backend/app/services/ai/tool_registry.py +++ b/backend/app/services/ai/tool_registry.py @@ -11,11 +11,13 @@ from urllib.parse import urljoin, urlparse import httpx from bs4 import BeautifulSoup -from sqlalchemy import select +from sqlalchemy import desc, func, select from sqlalchemy.ext.asyncio import AsyncSession from app.core.logging import get_logger from app.models.bgp_incident import BGPIncident +from app.models.collected_data import CollectedData +from app.models.earth_news import EarthNewsItem from app.schemas.compute_configuration import ComputeConfiguration from app.services.ai_tools.schemas import FetchedEvidence from app.services.compute_configuration import read_configuration @@ -610,7 +612,20 @@ async def query_satellite_posture_tool( safe_limit = max(50, min(int(limit or 1200), 3000)) features: list[dict[str, Any]] = [] + catalog_total: int | None = None limitations: list[str] = [] + try: + count_stmt = select(func.count(CollectedData.id)).where( + CollectedData.source == "celestrak_tle", + CollectedData.is_current.is_(True), + CollectedData.name != "Unknown", + ) + counted = (await db.execute(count_stmt)).scalar_one_or_none() + if isinstance(counted, int) and counted > 0: + catalog_total = counted + except Exception: + catalog_total = None + try: sat_fc = await _build_satellites_geojson(limit=safe_limit, db=db) features = list(sat_fc.get("features") or []) @@ -622,6 +637,8 @@ async def query_satellite_posture_tool( ) limitations.append("内置卫星 TLE 查询受限") + effective_total = catalog_total if catalog_total is not None and catalog_total >= len(features) else len(features) + by_constellation: dict[str, int] = {} by_orbit_regime: dict[str, int] = {} sample_satellites: list[dict[str, Any]] = [] @@ -657,15 +674,18 @@ async def query_satellite_posture_tool( sorted_constellations = dict( sorted(by_constellation.items(), key=lambda kv: kv[1], reverse=True)[:10] ) - if len(features) >= safe_limit: - limitations.append(f"本次卫星样本按性能上限截取前 {safe_limit} 颗轨道目标,不代表全库总编目。") + if effective_total > len(features): + limitations.append( + f"在轨卫星全库共 {effective_total} 颗;星座/轨道分布基于最新 {len(features)} 颗样本统计。" + ) if time_basis == "as_known_then": limitations.append("在轨星历基于最新同步批次(celestrak_tle),未按历史截点回卷旧 TLE。") return { "domain": "satellite", - "available": len(features) > 0, - "satellites_total": len(features), + "available": effective_total > 0, + "satellites_total": effective_total, + "sampled_count": len(features), "sample_limit": safe_limit, "by_constellation": sorted_constellations, "by_orbit_regime": by_orbit_regime, @@ -678,6 +698,74 @@ async def query_satellite_posture_tool( } +async def query_recent_earth_news_tool( + db: AsyncSession, + *, + region: str | None = None, + limit: int = 12, +) -> dict[str, Any]: + """Read-only built-in snapshot of recent global/regional Earth news items for geopolitical & news copilot turns.""" + base_ev_id = "ev-news-1" + evidence = { + base_ev_id: { + "id": base_ev_id, + "title": "Planet 全球态势新闻聚合快照(earth_news_items)", + "publisher": "Planet Global News Monitor", + "url": "/api/v1/earth/news", + "published_at": datetime.now(UTC).date().isoformat(), + "locator": f"builtin:earth_news:{region or 'global'}:limit={limit}", + } + } + if not hasattr(db, "execute"): + return {"domain": "news", "available": False, "items": [], "evidence": evidence} + + safe_limit = max(1, min(int(limit or 12), 25)) + items: list[dict[str, Any]] = [] + try: + stmt = ( + select(EarthNewsItem) + .where(EarthNewsItem.resolved_at.is_(None)) + .order_by(desc(EarthNewsItem.published_at), desc(EarthNewsItem.last_seen_at)) + .limit(safe_limit) + ) + if region: + stmt = stmt.where(EarthNewsItem.region == region) + rows = (await db.execute(stmt)).scalars().all() + for row in rows: + loc_meta = dict(row.location_meta or {}) + news_meta = loc_meta.get("news_meta") if isinstance(loc_meta.get("news_meta"), dict) else {} + localizations = row.localizations if isinstance(row.localizations, dict) else {} + zh_loc = localizations.get("zh-CN") if isinstance(localizations.get("zh-CN"), dict) else {} + items.append( + { + "id": row.id, + "title": zh_loc.get("title") or row.title, + "summary": (zh_loc.get("summary") or row.summary or "")[:400], + "source": row.source or row.feed_name, + "region": row.region, + "location_label": row.location_label, + "category": news_meta.get("category") or "other", + "breaking_level": news_meta.get("breaking_level") or "none", + "published_at": row.published_at.isoformat() if row.published_at else None, + "url": row.url, + } + ) + except Exception as exc: + logger.warning_event( + "Recent earth news query degraded", + event="ai_tool.earth_news.degraded", + context={"error": str(exc)}, + ) + + return { + "domain": "news", + "available": len(items) > 0, + "count": len(items), + "items": items, + "evidence": evidence, + } + + async def query_vessel_posture_tool( db: AsyncSession, *, diff --git a/backend/app/services/ai_client.py b/backend/app/services/ai_client.py index 783b72ba..11795448 100644 --- a/backend/app/services/ai_client.py +++ b/backend/app/services/ai_client.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +from collections.abc import AsyncIterator import json from time import perf_counter @@ -45,6 +46,82 @@ class AIProviderClient: ) self.llm_config = llm_config or {} + async def is_ready(self) -> tuple[bool, str, str]: + """Return `(configured_and_enabled, provider, model)` without calling LLM inference.""" + if not self.service_url: + return False, "unconfigured", "" + if isinstance(self.llm_config, dict) and self.llm_config: + provider = str(self.llm_config.get("provider") or "").strip().lower() + provider_api = str(self.llm_config.get("provider_api") or "").strip().lower() + base_url = str(self.llm_config.get("base_url") or "").strip() + model = str(self.llm_config.get("model") or "").strip() + api_key = str(self.llm_config.get("api_key") or "").strip() + if not provider or provider == "disabled": + return False, provider or "disabled", model + needs_key = provider != "ollama" and provider_api != "ollama-generate" + configured = bool(base_url and model and (api_key or not needs_key)) + return configured, provider, model + try: + status_resp = await self.get_status() + return ( + bool(status_resp.enabled and status_resp.configured), + str(status_resp.provider or ""), + str(status_resp.model or ""), + ) + except Exception: + return False, "unavailable", "" + + async def stream_analyze( + self, + payload: SituationalAnalysisRequest, + request_id: str | None = None, + ) -> AsyncIterator[dict]: + """Stream structured SSE events (`start`, `reasoning`, `text`, `done`, `error`) from aiprovider.""" + if not self.service_url: + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="AI provider service URL is not configured.", + ) + async with httpx.AsyncClient(timeout=self.timeout) as client: + async with client.stream( + "POST", + f"{self.service_url}/v1/analyze/stream", + headers=self._headers(request_id), + json=payload.model_dump(), + ) as response: + if response.status_code >= 400: + detail = (await response.aread()).decode("utf-8", errors="replace") + raise HTTPException( + status_code=status.HTTP_502_BAD_GATEWAY, + detail=f"AI provider service request failed: {detail or response.status_code}", + ) + event_name = "" + data_lines: list[str] = [] + async for raw_line in response.aiter_lines(): + line = raw_line.rstrip("\r") + if line == "": + if data_lines: + raw_json = "\n".join(data_lines) + event_name_cur = event_name + event_name = "" + data_lines = [] + parsed = json.loads(raw_json) + if isinstance(parsed, dict): + parsed.setdefault("event", event_name_cur or "message") + yield parsed + continue + if line.startswith(":"): + continue + if line.startswith("event:"): + event_name = line[6:].strip() + elif line.startswith("data:"): + data_lines.append(line[5:].lstrip()) + if data_lines: + parsed = json.loads("\n".join(data_lines)) + if isinstance(parsed, dict): + parsed.setdefault("event", event_name or "message") + yield parsed + def _headers(self, request_id: str | None = None) -> dict[str, str]: headers = {"Content-Type": "application/json"} if self.service_token: diff --git a/backend/app/services/llm_model_catalog.py b/backend/app/services/llm_model_catalog.py index 233afaff..1681c6a0 100644 --- a/backend/app/services/llm_model_catalog.py +++ b/backend/app/services/llm_model_catalog.py @@ -20,26 +20,47 @@ SUPPORTED_PROVIDER_APIS = { "anthropic-messages", "ollama-generate", } +OFFICIAL_PUBLIC_CATALOG_HOSTS: dict[str, frozenset[str]] = { + "openrouter": frozenset({"openrouter.ai"}), + "opencode-go": frozenset({"opencode.ai"}), +} class LLMProviderCatalogError(RuntimeError): """A safe, user-facing catalog failure with no upstream response or credentials.""" +class LLMProviderCatalogConfigError(LLMProviderCatalogError): + """Invalid local catalog configuration or missing required credentials.""" + + @dataclass(frozen=True) class ModelCatalog: url: str models: list[str] +def is_official_public_catalog(provider: str, base_url: str) -> bool: + provider_key = provider.strip().lower() + host = (urlsplit(base_url.strip()).hostname or "").lower() + return host in OFFICIAL_PUBLIC_CATALOG_HOSTS.get(provider_key, frozenset()) + + +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": + return False + return not is_official_public_catalog(provider_key, base_url) + + 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: - raise LLMProviderCatalogError("请填写有效的 HTTP(S) 模型基础地址。") + raise LLMProviderCatalogConfigError("请填写有效的 HTTP(S) 模型基础地址。") if parts.username or parts.password or parts.query or parts.fragment: - raise LLMProviderCatalogError("模型基础地址不能包含账号、密码、查询参数或片段。") + raise LLMProviderCatalogConfigError("模型基础地址不能包含账号、密码、查询参数或片段。") if provider_api not in SUPPORTED_PROVIDER_APIS: - raise LLMProviderCatalogError("当前接口协议不支持模型目录查询。") + raise LLMProviderCatalogConfigError("当前接口协议不支持模型目录查询。") path = parts.path.rstrip("/") if provider_api == "ollama-generate": path = path.removesuffix("/api").removesuffix("/v1") + "/api/tags" @@ -132,21 +153,23 @@ async def fetch_model_catalog( api_key: str = "", anthropic_version: str = "2023-06-01", timeout_seconds: int = CATALOG_TIMEOUT_SECONDS, + *, + include_auth: bool = True, ) -> ModelCatalog: url = model_catalog_url(provider, base_url, provider_api) - public_catalog = provider in {"opencode-go", "openrouter"} - if not api_key and provider_api != "ollama-generate" and not public_catalog: - raise LLMProviderCatalogError("请先配置当前供应商的 API Key,再刷新模型列表。") + if not api_key and catalog_requires_api_key(provider, base_url, provider_api): + raise LLMProviderCatalogConfigError("请先配置当前供应商的 API Key,再刷新模型列表。") headers = {"User-Agent": "Planet/1.0", "Accept": "application/json"} - if provider_api == "anthropic-messages" and provider not in { - "opencode-go", - "openrouter", - "alibaba", - "moonshotai", - }: - headers.update({"x-api-key": api_key, "anthropic-version": anthropic_version}) - elif api_key: - headers["Authorization"] = f"Bearer {api_key}" + if include_auth and api_key: + if provider_api == "anthropic-messages" and provider not in { + "opencode-go", + "openrouter", + "alibaba", + "moonshotai", + }: + headers.update({"x-api-key": api_key, "anthropic-version": anthropic_version}) + else: + headers["Authorization"] = f"Bearer {api_key}" native_dashscope = provider == "alibaba" and urlsplit(url).hostname.endswith(".aliyuncs.com") params: dict[str, str | int] = {} if native_dashscope: @@ -179,8 +202,8 @@ async def fetch_model_catalog( ) # An empty Ollama catalog is valid: no models have been installed yet. if not models and provider_api != "ollama-generate": - raise LLMProviderCatalogError("供应商返回了空模型目录,已保留上次模型列表。") + raise LLMProviderCatalogError("供应商返回了空模型目录。") return ModelCatalog(url=url, models=models) if len(rows_by_id) == previous_count: - raise LLMProviderCatalogError("供应商模型目录分页没有进展,已保留上次模型列表。") - raise LLMProviderCatalogError("供应商模型目录分页超过限制,已保留上次模型列表。") + raise LLMProviderCatalogError("供应商模型目录分页没有进展。") + raise LLMProviderCatalogError("供应商模型目录分页超过限制。") diff --git a/backend/app/services/llm_provider_catalog.py b/backend/app/services/llm_provider_catalog.py index 48e21888..ea4e5728 100644 --- a/backend/app/services/llm_provider_catalog.py +++ b/backend/app/services/llm_provider_catalog.py @@ -5,7 +5,7 @@ from __future__ import annotations from typing import Any from urllib.parse import urlsplit -from app.services.llm_model_catalog import fetch_model_catalog +from app.services.llm_model_catalog import fetch_model_catalog, is_official_public_catalog OPENCODE_GO_MODEL_PROVIDER_APIS = { "minimax-m3": "anthropic-messages", @@ -22,23 +22,31 @@ OPENCODE_GO_MODEL_PROVIDER_APIS = { "minimax-m2.5": "anthropic-messages", } OPENCODE_GO_FALLBACK_MODELS = [ - "minimax-m3", - "kimi-k3", "glm-5.3", - "qwen3.8-max", - "gpt-5.6-luna", - "minimax-m2.7", - "minimax-m2.5", - "kimi-k2.6", - "kimi-k2.5", - "glm-5.1", - "glm-5", + "glm-5.3-flash", + "deepseek-v4.1-flash", "deepseek-v4-pro", - "deepseek-v4-flash", - "qwen3.6-plus", - "qwen3.5-plus", - "mimo-v2.5-pro", - "mimo-v2.5", + "kimi-k3.1-pro", + "kimi-k3", + "kimi-k2.7-code", + "minimax-m3", + "minimax-m3.1-flash", + "qwen4-max", + "qwen3.8-max", + "qwen3.8-flash", + "qwen3.7-plus", + "gpt-6-luna", + "gpt-5.6-luna", + "grok-4.7", + "claude-haiku-5-5", + "gemini-4-argon", + "mimo-v2.6-pro", + "mimo-v2.6-flash", + "hy4", + "hy4-flash-free", + "step-5-preview", + "muse-spark-1.3-contributor", + "muse-spark-1.2-contributor", ] @@ -131,8 +139,14 @@ FALLBACK_LLM_PROVIDER_PRESETS: dict[str, dict[str, Any]] = { "label": "OpenRouter", "provider_api": "openai-completions", "base_url": "https://openrouter.ai/api/v1", - "model": "openai/gpt-5.1", - "models": ["openai/gpt-5.1", "anthropic/claude-sonnet-4.5", "qwen/qwen3-max"], + "model": "openai/gpt-6.2-astra", + "models": [ + "openai/gpt-6.2-astra", + "openai/gpt-6.2-sol", + "google/gemini-4-neon", + "qwen/qwen4-max", + "anthropic/claude-sonnet-4.5", + ], "api_key_env": "OPENROUTER_API_KEY", "source": "fallback", }, @@ -141,7 +155,7 @@ FALLBACK_LLM_PROVIDER_PRESETS: dict[str, dict[str, Any]] = { "label": "OpenCode Go", "provider_api": "openai-completions", "base_url": "https://opencode.ai/zen/go/v1", - "model": "glm-5.1", + "model": "glm-5.3", "models": OPENCODE_GO_FALLBACK_MODELS, "model_provider_apis": OPENCODE_GO_MODEL_PROVIDER_APIS, "api_key_env": "OPENCODE_GO_API_KEY", @@ -195,6 +209,7 @@ async def refresh_llm_provider_preset( 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) diff --git a/backend/tests/test_ai_stream_turn.py b/backend/tests/test_ai_stream_turn.py new file mode 100644 index 00000000..4b69bab6 --- /dev/null +++ b/backend/tests/test_ai_stream_turn.py @@ -0,0 +1,279 @@ +from __future__ import annotations + +import json + +import httpx +import pytest +from fastapi import FastAPI + +from app.api.v1 import situational_awareness +from app.schemas.ai import SituationalAnalysisResponse +from app.services.ai import spatial_domain_agent +from app.services.ai.stream_turn import reset_stream_quota_ledger +from app.services.ai_client import AIProviderClient, get_ai_provider_client + + +def _parse_sse_text(raw: str) -> list[tuple[str, dict]]: + events: list[tuple[str, dict]] = [] + for block in raw.replace("\r\n", "\n").split("\n\n"): + if not block.strip(): + continue + ev_name = "message" + data_lines: list[str] = [] + for line in block.split("\n"): + if line.startswith("event:"): + ev_name = line[6:].strip() + elif line.startswith("data:"): + data_lines.append(line[5:].lstrip()) + if data_lines: + events.append((ev_name, json.loads("\n".join(data_lines)))) + return events + + +class _StubDb: + pass + + +@pytest.mark.asyncio +async def test_spatial_domain_agent_reads_content_attribute(monkeypatch): + class _FakeClient: + service_url = "http://aiprovider.test" + llm_config = {"provider": "minimax", "model": "MiniMax-M2.7"} + + async def analyze(self, _req): + return SituationalAnalysisResponse( + provider="minimax", + model="MiniMax-M2.7", + content=json.dumps( + { + "domain": "global", + "subject_key": "global:test", + "title": "全球多图层态势", + "executive_assertion": "已成功读取大模型合成内容。", + "confirmed_facts": [{"statement": "全网多图层数据在线。", "evidence_ids": ["ev-global-1"]}], + "analytical_notes": [{"statement": "LLM 输出字段匹配成功。", "evidence_ids": ["ev-global-1"]}], + "open_gaps": ["示例口径边界。"], + "evidence_ids": ["ev-global-1"], + }, + ensure_ascii=False, + ), + ) + + async def fake_global_tool(*_args, **_kwargs): + return { + "domain": "global", + "available": True, + "domain_summaries": [], + "bgp_summary": {"active_count": 0}, + "evidence": {"ev-global-1": {"id": "ev-global-1", "title": "Global Snapshot"}}, + "limitations": [], + } + + monkeypatch.setattr(spatial_domain_agent, "query_global_situational_tool", fake_global_tool) + + result = await spatial_domain_agent.investigate_spatial_domain( + _StubDb(), + domain="global", + question="分析全球态势", + persist=False, + ai_client=_FakeClient(), + ) + + assert result["generation_mode"] == "llm_verified" + assert result["payload"]["executive_assertion"] == "已成功读取大模型合成内容。" + + +@pytest.mark.asyncio +async def test_stream_turn_adapts_between_configured_minimax_and_disabled_ai(monkeypatch): + reset_stream_quota_ledger() + + async def fake_recent_news(*_args, **_kwargs): + return { + "domain": "news", + "available": True, + "count": 1, + "items": [{"id": "n1", "title": "全球海缆路由测试头条", "source": "Reuters", "region": "global"}], + "evidence": {"ev-news-1": {"id": "ev-news-1", "title": "Planet News"}}, + } + + async def fake_global_tool(*_args, **_kwargs): + return { + "domain": "global", + "domain_summaries": [{"domain": "cable", "label": "海底光缆", "metric_text": "343 条"}], + "evidence": {"ev-global-1": {"id": "ev-global-1", "title": "Global Telemetry"}}, + } + + monkeypatch.setattr("app.services.ai.stream_turn.query_recent_earth_news_tool", fake_recent_news) + monkeypatch.setattr("app.services.ai.stream_turn.query_global_situational_tool", fake_global_tool) + + class _ConfiguredClient(AIProviderClient): + def __init__(self): + super().__init__( + service_url="http://aiprovider.test", + llm_config={ + "provider": "minimax", + "provider_api": "anthropic-messages", + "base_url": "https://api.minimaxi.com/anthropic", + "api_key": "secret-key", + "model": "MiniMax-M2.7", + }, + ) + + async def stream_analyze(self, payload, request_id=None): + assert payload.thinking == {"type": "enabled", "budget_tokens": 2048} + yield {"event": "start", "provider": "minimax", "model": "MiniMax-M2.7"} + yield {"event": "reasoning", "delta": "先梳理新闻核心矛盾。"} + yield {"event": "text", "delta": "### 新闻深度分析\n\n- **要点**:供应链与光缆关注升温。"} + yield {"event": "done", "provider": "minimax", "model": "MiniMax-M2.7", "usage": {"total_tokens": 42}} + + class _DisabledClient(AIProviderClient): + def __init__(self): + super().__init__( + service_url="http://aiprovider.test", + llm_config={"provider": "disabled"}, + ) + + app = FastAPI() + app.include_router(situational_awareness.router, prefix="/api/v1/situational-awareness") + app.dependency_overrides[situational_awareness.get_db] = lambda: _StubDb() + app.dependency_overrides[get_ai_provider_client] = lambda: _ConfiguredClient() + + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client: + # 1. Anonymous Earth/desktop caller uses MiniMax automatically when configured + res_ai = await client.post( + "/api/v1/situational-awareness/sessions/stateless/turns/stream", + json={ + "question": "请深度分析这条新闻:「全球海缆路由测试头条」", + "domain": "news", + "news_context": { + "id": "n1", + "title": "全球海缆路由测试头条", + "summary": "测试新闻摘要", + "source": "Reuters", + "region": "全球", + }, + }, + ) + assert res_ai.status_code == 200 + assert "text/event-stream" in res_ai.headers["content-type"] + ai_events = _parse_sse_text(res_ai.text) + ai_names = [name for name, _ in ai_events] + assert ai_names == ["meta", "reasoning", "text", "done"] + assert ai_events[0][1]["ai_enabled"] is True + assert ai_events[0][1]["model"] == "MiniMax-M2.7" + assert ai_events[1][1]["delta"] == "先梳理新闻核心矛盾。" + assert "新闻深度分析" in ai_events[2][1]["delta"] + assert ai_events[3][1]["zero_token"] is False + assert ai_events[3][1]["generation_mode"] == "llm_verified" + assert ai_events[3][1]["model"] == "MiniMax-M2.7" + + # 2. Switching provider to disabled adapts seamlessly back to deterministic baseline + app.dependency_overrides[get_ai_provider_client] = lambda: _DisabledClient() + res_no_ai = await client.post( + "/api/v1/situational-awareness/sessions/stateless/turns/stream", + json={ + "question": "请深度分析这条新闻:「全球海缆路由测试头条」", + "domain": "news", + "news_context": {"id": "n1", "title": "全球海缆路由测试头条", "summary": "测试新闻摘要"}, + }, + ) + assert res_no_ai.status_code == 200 + no_ai_events = _parse_sse_text(res_no_ai.text) + assert no_ai_events[0][1]["ai_enabled"] is False + assert no_ai_events[0][1]["model"] is None + assert no_ai_events[-1][0] == "done" + assert no_ai_events[-1][1]["zero_token"] is True + assert no_ai_events[-1][1]["model"] is None + assert no_ai_events[-1][1]["generation_mode"] == "deterministic_baseline" + + +@pytest.mark.asyncio +async def test_stream_turn_forwards_history_compaction_and_memory(monkeypatch): + reset_stream_quota_ledger() + + async def fake_global_tool(*_args, **_kwargs): + return { + "domain": "global", + "domain_summaries": [{"domain": "cable", "label": "海底光缆", "metric_text": "343 条"}], + "evidence": {"ev-global-1": {"id": "ev-global-1", "title": "Global Telemetry"}}, + } + + async def fake_recent_news(*_args, **_kwargs): + return {"domain": "news", "available": True, "count": 0, "items": [], "evidence": {}} + + monkeypatch.setattr("app.services.ai.stream_turn.query_global_situational_tool", fake_global_tool) + monkeypatch.setattr("app.services.ai.stream_turn.query_recent_earth_news_tool", fake_recent_news) + + captured_analyze_reqs = [] + captured_stream_reqs = [] + + class _CompactingClient(AIProviderClient): + def __init__(self): + super().__init__( + service_url="http://aiprovider.test", + llm_config={ + "provider": "minimax", + "provider_api": "anthropic-messages", + "base_url": "https://api.minimaxi.com/anthropic", + "api_key": "secret-key", + "model": "MiniMax-M2.7", + }, + ) + + async def analyze(self, payload, request_id=None): + captured_analyze_reqs.append(payload) + return SituationalAnalysisResponse( + provider="minimax", + model="MiniMax-M2.7", + content="internal前序关注中美算力与亚太海缆冗余,已核验 343 条骨干海缆。", + ) + + async def stream_analyze(self, payload, request_id=None): + captured_stream_reqs.append(payload) + yield {"event": "start", "provider": "minimax", "model": "MiniMax-M2.7"} + yield {"event": "text", "delta": "结合前文 343 条海缆与您的亚太聚焦偏好,补充说明如下。"} + yield {"event": "done", "provider": "minimax", "model": "MiniMax-M2.7", "usage": {"total_tokens": 55}} + + app = FastAPI() + app.include_router(situational_awareness.router, prefix="/api/v1/situational-awareness") + app.dependency_overrides[situational_awareness.get_db] = lambda: _StubDb() + app.dependency_overrides[get_ai_provider_client] = lambda: _CompactingClient() + + long_history = [] + for idx in range(1, 7): + long_history.append({"role": "user", "content": f"第 {idx} 轮提问"}) + long_history.append({"role": "assistant", "content": f"thought-{idx}第 {idx} 轮结论"}) + + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client: + res = await client.post( + "/api/v1/situational-awareness/sessions/stateless/turns/stream", + json={ + "question": "基于前面总结继续追问亚太海缆脆弱点", + "domain": "global", + "history": long_history, + "memory_notes": ["优先给出亚太海缆冗余与算力口径边界"], + "pinned_summaries": ["GLOBAL · Rev.1: 全球综合态势"], + }, + ) + assert res.status_code == 200 + events = _parse_sse_text(res.text) + meta_ev = events[0][1] + done_ev = events[-1][1] + + assert meta_ev["compacted"] is True + assert "343 条骨干海缆" in meta_ev["conversation_summary"] + assert "" not in meta_ev["conversation_summary"] + assert meta_ev["memory_used"] is True + assert done_ev["compacted"] is True + assert done_ev["conversation_summary"] == meta_ev["conversation_summary"] + + assert len(captured_analyze_reqs) == 1 + assert len(captured_stream_reqs) == 1 + sent_payload = captured_stream_reqs[0] + # Recent window preserves latest 4 turns (8 messages), with stripped + assert len(sent_payload.messages) == 8 + assert sent_payload.messages[0].content == "第 3 轮提问" + assert sent_payload.messages[1].content == "第 3 轮结论" + assert sent_payload.context["conversation_summary"] == meta_ev["conversation_summary"] + assert sent_payload.context["user_memory_notes"] == ["优先给出亚太海缆冗余与算力口径边界"] + assert sent_payload.context["pinned_comparisons"] == ["GLOBAL · Rev.1: 全球综合态势"] diff --git a/backend/tests/test_llm_provider_catalog.py b/backend/tests/test_llm_provider_catalog.py index 7a2ce9ca..4379cc7f 100644 --- a/backend/tests/test_llm_provider_catalog.py +++ b/backend/tests/test_llm_provider_catalog.py @@ -26,8 +26,8 @@ def mock_http(monkeypatch, handler): ("deepseek", "/v1/models", "authorization"), ("alibaba", "/api/v1/models", "authorization"), ("moonshotai", "/v1/models", "authorization"), - ("openrouter", "/api/v1/models", "authorization"), - ("opencode-go", "/zen/go/v1/models", "authorization"), + ("openrouter", "/api/v1/models", None), + ("opencode-go", "/zen/go/v1/models", None), ("ollama", "/api/tags", "authorization"), ], ) @@ -37,7 +37,13 @@ async def test_official_catalog_requests(monkeypatch, provider, path, auth): def handle(request): assert request.url.path == path assert request.url.host == httpx.URL(preset["base_url"]).host - assert request.headers[auth] == ("test-key" if auth == "x-api-key" else "Bearer test-key") + if auth is None: + assert "authorization" not in request.headers + assert "x-api-key" not in request.headers + else: + assert request.headers[auth] == ( + "test-key" if auth == "x-api-key" else "Bearer test-key" + ) if provider == "alibaba": assert request.url.params["capabilities"] == "TG" return httpx.Response( @@ -217,3 +223,74 @@ async def test_retry_transient_error_only(monkeypatch): await catalog.refresh_llm_provider_preset("minimax", "test-key") assert len(calls) == 1 assert "secret-upstream-text" not in discovery.catalog_error_message(error.value) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "provider,custom_base", + [ + ("openrouter", "https://proxy.test/api/v1"), + ("opencode-go", "https://proxy.test/zen/go/v1"), + ], +) +async def test_custom_gateway_for_public_provider_requires_and_sends_key( + monkeypatch, provider, custom_base +): + with pytest.raises(discovery.LLMProviderCatalogConfigError): + await catalog.refresh_llm_provider_preset(provider, base_url=custom_base) + + def handle(request): + assert request.url.host == "proxy.test" + assert request.headers["authorization"] == "Bearer custom-key" + return httpx.Response(200, json={"data": [{"id": "proxy-model"}]}) + + mock_http(monkeypatch, handle) + result = await catalog.refresh_llm_provider_preset( + provider, api_key="custom-key", base_url=custom_base + ) + assert result["models"] == ["proxy-model"] + + +@pytest.mark.asyncio +async def test_fetch_model_catalog_include_auth_for_connectivity_check(monkeypatch): + def handle(request): + assert request.headers["authorization"] == "Bearer check-key" + return httpx.Response(200, json={"data": [{"id": "glm-5.3"}]}) + + mock_http(monkeypatch, handle) + result = await discovery.fetch_model_catalog( + "opencode-go", + "https://opencode.ai/zen/go/v1", + "openai-completions", + api_key="check-key", + include_auth=True, + ) + assert result.models == ["glm-5.3"] + + +@pytest.mark.asyncio +async def test_ollama_openai_completions_refreshes_without_key(monkeypatch): + def handle(request): + assert request.url.path == "/v1/models" + assert "authorization" not in request.headers + return httpx.Response(200, json={"data": [{"id": "qwen2.5:7b"}]}) + + mock_http(monkeypatch, handle) + result = await catalog.refresh_llm_provider_preset( + "ollama", provider_api="openai-completions" + ) + assert result["models"] == ["qwen2.5:7b"] + + +@pytest.mark.asyncio +async def test_config_error_type_and_clean_upstream_error_messages(monkeypatch): + with pytest.raises(discovery.LLMProviderCatalogConfigError): + discovery.model_catalog_url("openai", "not-a-url", "openai-responses") + with pytest.raises(discovery.LLMProviderCatalogConfigError): + discovery.model_catalog_url("openai", "https://api.openai.com/v1", "unsupported-api") + + mock_http(monkeypatch, lambda request: httpx.Response(200, json={"data": []})) + with pytest.raises(discovery.LLMProviderCatalogError) as exc: + await catalog.refresh_llm_provider_preset("openai", "test-key") + assert not isinstance(exc.value, discovery.LLMProviderCatalogConfigError) + assert "已保留上次模型列表" not in str(exc.value) diff --git a/backend/tests/test_llm_provider_settings.py b/backend/tests/test_llm_provider_settings.py index 46c4d34e..77f47c25 100644 --- a/backend/tests/test_llm_provider_settings.py +++ b/backend/tests/test_llm_provider_settings.py @@ -13,6 +13,8 @@ from app.services import llm_model_catalog as discovery from app.services.llm_provider_catalog import list_fallback_llm_provider_presets REAL_CLIENT = httpx.AsyncClient +ADMIN_USER = SimpleNamespace(role="admin") +VIEWER_USER = SimpleNamespace(role="viewer") @pytest.fixture @@ -82,7 +84,7 @@ async def test_refresh_commits_reloads_and_preserves_runtime_and_draft(settings_ api_key="draft-secret", service_token="unsaved-service-token", ) - refreshed = await api.refresh_ai_provider_preset("minimax", None, settings_db, draft) + refreshed = await api.refresh_ai_provider_preset("minimax", ADMIN_USER, settings_db, draft) result = await api.get_ai_provider_presets(None, settings_db) preset = next(row for row in result["data"] if row["provider"] == "minimax") assert len(seen) == 1 @@ -108,7 +110,7 @@ async def test_failed_refresh_preserves_stored_catalog_and_sanitizes_errors( use_upstream(monkeypatch, lambda request: httpx.Response(401, text="private-upstream-secret")) commits = settings_db.commit.await_count with pytest.raises(api.HTTPException) as error: - await api.refresh_ai_provider_preset("openrouter", None, settings_db) + await api.refresh_ai_provider_preset("openrouter", ADMIN_USER, settings_db) assert error.value.status_code == 502 assert "private-upstream-secret" not in error.value.detail assert settings_db.commit.await_count == commits @@ -124,11 +126,170 @@ async def test_missing_key_is_actionable_and_does_not_request_upstream(settings_ use_upstream(monkeypatch, fail_request) with pytest.raises(api.HTTPException) as error: - await api.refresh_ai_provider_preset("minimax", None, settings_db) + await api.refresh_ai_provider_preset("minimax", ADMIN_USER, settings_db) assert error.value.status_code == 400 assert "API Key" in error.value.detail +@pytest.mark.asyncio +async def test_refresh_requires_admin_role(settings_db): + with pytest.raises(api.HTTPException) as single_err: + await api.refresh_ai_provider_preset("openrouter", VIEWER_USER, settings_db) + assert single_err.value.status_code == 403 + + with pytest.raises(api.HTTPException) as bulk_err: + await api.refresh_public_ai_provider_presets(VIEWER_USER, settings_db) + assert bulk_err.value.status_code == 403 + + +@pytest.mark.asyncio +async def test_opencode_go_refreshes_ignoring_invalid_saved_and_draft_keys( + settings_db, monkeypatch +): + await api.save_setting_payload( + settings_db, + "external_integrations", + { + "ai_provider": { + "default_provider": "opencode-go", + "providers": { + "opencode-go": { + "base_url": "https://opencode.ai/zen/go/v1", + "model": "glm-5.3", + "api_key": "stale-invalid-key", + } + }, + } + }, + ) + + def handle(request): + assert "authorization" not in request.headers + assert "x-api-key" not in request.headers + return httpx.Response(200, json={"data": [{"id": "glm-5.3"}, {"id": "deepseek-v4.1-flash"}]}) + + use_upstream(monkeypatch, handle) + draft = api.AIProviderIntegrationUpdate( + provider="opencode-go", + base_url="https://opencode.ai/zen/go/v1", + model="glm-5.3", + api_key="bad-draft-key", + ) + refreshed = await api.refresh_ai_provider_preset("opencode-go", ADMIN_USER, settings_db, draft) + assert refreshed["data"]["models"] == ["glm-5.3", "deepseek-v4.1-flash"] + stored = await api.get_setting_payload(settings_db, "llm_provider_preset:opencode-go") + assert stored["models"] == ["glm-5.3", "deepseek-v4.1-flash"] + + +@pytest.mark.asyncio +async def test_ollama_openai_completions_works_without_key(settings_db, monkeypatch): + def handle(request): + assert request.url.path == "/v1/models" + assert "authorization" not in request.headers + return httpx.Response(200, json={"data": [{"id": "qwen2.5:7b"}]}) + + use_upstream(monkeypatch, handle) + draft = api.AIProviderIntegrationUpdate( + provider="ollama", + provider_api="openai-completions", + base_url="http://127.0.0.1:11434/v1", + model="qwen2.5:7b", + ) + refreshed = await api.refresh_ai_provider_preset("ollama", ADMIN_USER, settings_db, draft) + assert refreshed["data"]["models"] == ["qwen2.5:7b"] + + check = await api._check_ai_provider_lightweight( + { + "provider": "ollama", + "provider_api": "openai-completions", + "base_url": "http://127.0.0.1:11434/v1", + "model": "qwen2.5:7b", + "api_key": "", + }, + 5, + ) + assert check["success"] is True + assert check["connected"] is True + + +@pytest.mark.asyncio +async def test_invalid_draft_base_url_returns_400_without_calling_upstream( + settings_db, monkeypatch +): + use_upstream( + monkeypatch, + lambda request: pytest.fail("must not query upstream when draft base_url is invalid"), + ) + draft = api.AIProviderIntegrationUpdate( + provider="openrouter", + base_url="not-a-valid-url", + model="openai/gpt-6.2-astra", + ) + with pytest.raises(api.HTTPException) as error: + await api.refresh_ai_provider_preset("openrouter", ADMIN_USER, settings_db, draft) + assert error.value.status_code == 400 + + +@pytest.mark.asyncio +async def test_empty_catalog_error_does_not_duplicate_retention_suffix(settings_db, monkeypatch): + use_upstream(monkeypatch, lambda request: httpx.Response(200, json={"data": []})) + with pytest.raises(api.HTTPException) as error: + await api.refresh_ai_provider_preset("openrouter", ADMIN_USER, settings_db) + assert error.value.status_code == 502 + assert error.value.detail.count("已保留上次模型列表") == 1 + + +@pytest.mark.asyncio +async def test_refresh_public_presets_updates_credential_free_and_isolates_failures( + settings_db, monkeypatch +): + await api.save_setting_payload( + settings_db, + "external_integrations", + { + "ai_provider": { + "default_provider": "openrouter", + "providers": { + "openrouter": { + "base_url": "https://proxy.test/api/v1", + "model": "custom-model", + "api_key": "", + }, + "opencode-go": { + "base_url": "https://opencode.ai/zen/go/v1", + "model": "glm-5.3", + "api_key": "stale-key", + }, + }, + } + }, + ) + await api.save_setting_payload( + settings_db, "llm_provider_preset:ollama", {"models": ["kept-local-model"]} + ) + + seen_hosts = [] + + def handle(request): + seen_hosts.append(request.url.host) + assert "authorization" not in request.headers + 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 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:ollama"))[ + "models" + ] == ["kept-local-model"] + + @pytest.mark.asyncio @pytest.mark.parametrize( "preset", list_fallback_llm_provider_presets(), ids=lambda p: p["provider"] diff --git a/backend/tests/test_provider_protocols.py b/backend/tests/test_provider_protocols.py index 9d8384fc..4ae3cd14 100644 --- a/backend/tests/test_provider_protocols.py +++ b/backend/tests/test_provider_protocols.py @@ -1,3 +1,4 @@ +import json from pathlib import Path import sys from unittest.mock import patch @@ -175,3 +176,173 @@ async def test_minimax_m31_flash_forces_adaptive_thinking_and_effort(monkeypatch assert payloads[0]["output_config"] == {"effort": "low"} assert payloads[1]["thinking"] == {"type": "adaptive"} assert payloads[1]["output_config"] == {"effort": "medium"} + + +@pytest.mark.asyncio +async def test_stream_analyze_anthropic_emits_thinking_text_and_done(monkeypatch): + client_type = httpx.AsyncClient + sse_bytes = ( + b'event: message_start\n' + b'data: {"type":"message_start","message":{"model":"MiniMax-M2.7","usage":{"input_tokens":12}}}\n\n' + b'event: content_block_delta\n' + b'data: {"type":"content_block_delta","delta":{"type":"thinking_delta","thinking":"step-1 "}}\n\n' + b'event: content_block_delta\n' + b'data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"hello "}}\n\n' + b'event: message_delta\n' + b'data: {"type":"message_delta","usage":{"output_tokens":7}}\n\n' + b'event: message_stop\n' + b'data: {"type":"message_stop"}\n\n' + ) + + def handle(_request): + return httpx.Response(200, content=sse_bytes, headers={"content-type": "text/event-stream"}) + + transport = httpx.MockTransport(handle) + monkeypatch.setattr(httpx, "AsyncClient", lambda **kw: client_type(transport=transport, **kw)) + service = ProviderService( + { + "provider": "minimax", + "provider_api": "anthropic-messages", + "base_url": "https://api.minimaxi.com/anthropic", + "api_key": "test-key", + "model": "MiniMax-M2.7", + } + ) + + events = [] + async for ev in service.stream_analyze( + SituationalAnalysisRequest(title="news", objective="analyze", thinking={"type": "enabled", "budget_tokens": 1024}) + ): + events.append(ev) + + assert events[0] == {"event": "start", "provider": "minimax", "model": "MiniMax-M2.7"} + assert {"event": "reasoning", "delta": "step-1 "} in events + assert {"event": "text", "delta": "hello "} in events + assert events[-1]["event"] == "done" + assert events[-1]["model"] == "MiniMax-M2.7" + assert events[-1]["usage"]["output_tokens"] == 7 + + +@pytest.mark.asyncio +async def test_stream_analyze_openai_emits_reasoning_and_text(monkeypatch): + client_type = httpx.AsyncClient + sse_bytes = ( + b'data: {"model":"gpt-5.6","choices":[{"delta":{"reasoning_content":"check cables"}}]}\n\n' + b'data: {"model":"gpt-5.6","choices":[{"delta":{"content":"summary ok"}}],"usage":{"total_tokens":20}}\n\n' + b'data: [DONE]\n\n' + ) + + def handle(_request): + return httpx.Response(200, content=sse_bytes, headers={"content-type": "text/event-stream"}) + + transport = httpx.MockTransport(handle) + monkeypatch.setattr(httpx, "AsyncClient", lambda **kw: client_type(transport=transport, **kw)) + service = ProviderService( + { + "provider": "openai", + "provider_api": "openai-completions", + "base_url": "https://api.openai.test/v1", + "api_key": "test-key", + "model": "gpt-5.6", + } + ) + + events = [] + async for ev in service.stream_analyze(SituationalAnalysisRequest(title="global", objective="analyze")): + events.append(ev) + + assert {"event": "reasoning", "delta": "check cables"} in events + assert {"event": "text", "delta": "summary ok"} in events + assert events[-1]["event"] == "done" + assert events[-1]["usage"]["total_tokens"] == 20 + + +@pytest.mark.asyncio +async def test_stream_analyze_forwards_normalized_multi_turn_messages(monkeypatch): + client_type = httpx.AsyncClient + captured_bodies = [] + + def handle(request): + captured_bodies.append(json.loads(request.content.decode("utf-8"))) + sse = ( + b'event: content_block_delta\n' + b'data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"multi-turn ok"}}\n\n' + b'event: message_stop\n' + b'data: {"type":"message_stop"}\n\n' + ) + return httpx.Response(200, content=sse, headers={"content-type": "text/event-stream"}) + + transport = httpx.MockTransport(handle) + monkeypatch.setattr(httpx, "AsyncClient", lambda **kw: client_type(transport=transport, **kw)) + service = ProviderService( + { + "provider": "minimax", + "provider_api": "anthropic-messages", + "base_url": "https://api.minimaxi.com/anthropic", + "api_key": "test-key", + "model": "MiniMax-M2.7", + } + ) + + events = [] + async for ev in service.stream_analyze( + SituationalAnalysisRequest( + title="follow-up", + objective="继续追问第二点", + messages=[ + {"role": "assistant", "content": "leading assistant ignored"}, + {"role": "user", "content": "第一轮问题"}, + {"role": "assistant", "content": "第一轮回答"}, + ], + ) + ): + events.append(ev) + + assert len(captured_bodies) == 1 + sent_msgs = captured_bodies[0]["messages"] + assert [m["role"] for m in sent_msgs] == ["user", "assistant", "user"] + assert sent_msgs[0]["content"][0]["text"] == "第一轮问题" + assert sent_msgs[1]["content"][0]["text"] == "第一轮回答" + assert "继续追问第二点" in sent_msgs[2]["content"][0]["text"] + assert {"event": "text", "delta": "multi-turn ok"} in events + + +def test_anthropic_request_omits_temperature_and_bumps_max_tokens_when_thinking_enabled(): + service = ProviderService( + { + "provider": "minimax", + "provider_api": "anthropic-messages", + "base_url": "https://api.minimaxi.com/anthropic", + "api_key": "test-key", + "model": "MiniMax-M2.7", + "max_tokens": 1200, + } + ) + + _, _, enabled_body = service._build_anthropic_request( + "MiniMax-M2.7", + "analyze", + thinking={"type": "enabled", "budget_tokens": 2048}, + stream=True, + ) + assert "temperature" not in enabled_body + assert enabled_body["max_tokens"] == 3072 + assert enabled_body["thinking"] == {"type": "enabled", "budget_tokens": 2048} + + _, _, adaptive_body = service._build_anthropic_request( + "MiniMax-M3.1", + "analyze", + thinking=None, + stream=True, + ) + assert "temperature" not in adaptive_body + assert adaptive_body["thinking"] == {"type": "adaptive"} + + _, _, disabled_body = service._build_anthropic_request( + "MiniMax-M2.7", + "analyze", + thinking=None, + stream=False, + ) + assert disabled_body["temperature"] == 0.2 + assert disabled_body["thinking"] == {"type": "disabled"} diff --git a/backend/tests/test_settings_ai_provider.py b/backend/tests/test_settings_ai_provider.py index 4d5612c4..5f019764 100644 --- a/backend/tests/test_settings_ai_provider.py +++ b/backend/tests/test_settings_ai_provider.py @@ -108,9 +108,9 @@ def test_opencode_go_provider_preset_is_openai_compatible(): assert preset["label"] == "OpenCode Go" assert preset["provider_api"] == "openai-completions" assert preset["base_url"] == "https://opencode.ai/zen/go/v1" - assert preset["model"] == "glm-5.1" - assert "glm-5.1" in preset["models"] - assert "deepseek-v4-flash" in preset["models"] + assert preset["model"] == "glm-5.3" + assert "glm-5.3" in preset["models"] + assert "deepseek-v4.1-flash" in preset["models"] assert preset["model_provider_apis"]["minimax-m2.7"] == "anthropic-messages" assert preset["api_key_env"] == "OPENCODE_GO_API_KEY" diff --git a/client/electron-builder.yml b/client/electron-builder.yml index 6f410483..b77adeb1 100644 --- a/client/electron-builder.yml +++ b/client/electron-builder.yml @@ -56,6 +56,8 @@ linux: mac: icon: resources/icon.png category: public.app-category.utilities + extendInfo: + NSCameraUsageDescription: Planet Earth uses your camera locally for motion gesture control. target: - target: dmg arch: diff --git a/client/package.json b/client/package.json index 5fdeec9e..5f48bef9 100644 --- a/client/package.json +++ b/client/package.json @@ -1,6 +1,6 @@ { "name": "planet-client", - "version": "0.79.2", + "version": "0.80.0", "description": "Intelligent Planet Program - Native Electron Earth Viewer", "private": true, "packageManager": "bun@1", diff --git a/client/scripts/build-earth-bundle.mjs b/client/scripts/build-earth-bundle.mjs index 21073d57..ceb0b27b 100644 --- a/client/scripts/build-earth-bundle.mjs +++ b/client/scripts/build-earth-bundle.mjs @@ -90,16 +90,19 @@ if (existsSync(zjuEmblemSrc)) { const mediaPipePkgDir = dirname(require.resolve('@mediapipe/tasks-vision/package.json')) const mediaPipeOutDir = join(bundleEarthDir, 'vendor/mediapipe') mkdirSync(mediaPipeOutDir, { recursive: true }) -for (const candidate of ['vision_bundle.mjs', 'vision_bundle.cjs']) { - const srcFile = join(mediaPipePkgDir, candidate) - if (existsSync(srcFile)) { - cpSync(srcFile, join(mediaPipeOutDir, candidate)) - } +const mediaPipeBundleSrc = join(mediaPipePkgDir, 'vision_bundle.mjs') +if (existsSync(mediaPipeBundleSrc)) { + cpSync(mediaPipeBundleSrc, join(mediaPipeOutDir, 'vision_bundle.mjs')) } const mediaPipeWasmDir = join(mediaPipePkgDir, 'wasm') if (existsSync(mediaPipeWasmDir)) { cpSync(mediaPipeWasmDir, join(mediaPipeOutDir, 'wasm'), { recursive: true }) } +const poseModelSrc = join(earthSourceDir, 'vendor/mediapipe/pose_landmarker_lite.task') +if (!existsSync(poseModelSrc)) { + throw new Error(`Missing bundled MediaPipe pose model: ${poseModelSrc}`) +} +cpSync(poseModelSrc, join(mediaPipeOutDir, 'pose_landmarker_lite.task')) console.log(`Built offline Earth bundle at ${bundleEarthDir}`) diff --git a/client/src/main/index.ts b/client/src/main/index.ts index 8a5d688e..9a13f52e 100644 --- a/client/src/main/index.ts +++ b/client/src/main/index.ts @@ -292,6 +292,7 @@ if (!singleInstanceLock) { isElectron: true, platform: process.platform, localMediaPipeBaseUrl: `${EARTH_ORIGIN}/earth/vendor/mediapipe`, + localPoseModelUrl: `${EARTH_ORIGIN}/earth/vendor/mediapipe/pose_landmarker_lite.task`, } }) diff --git a/client/src/main/protocol.ts b/client/src/main/protocol.ts index 141a77e0..5447edc3 100644 --- a/client/src/main/protocol.ts +++ b/client/src/main/protocol.ts @@ -1,10 +1,14 @@ -import { net, protocol, type Session } from 'electron' +import { net, protocol, systemPreferences, type Session } from 'electron' import { createEarthProtocolHandler } from './protocol-core' export const EARTH_ORIGIN = 'planet://earth' export const EARTH_ENTRY_URL = `${EARTH_ORIGIN}/earth/index.html` +function isEarthUrl(url: string): boolean { + return url === EARTH_ORIGIN || url.startsWith(`${EARTH_ORIGIN}/`) +} + export function registerEarthScheme(): void { protocol.registerSchemesAsPrivileged([ { @@ -51,13 +55,35 @@ export function installEarthSessionHandlers( }, ) - targetSession.setPermissionRequestHandler((webContents, permission, callback) => { - const pageUrl = webContents.getURL() - const isEarthOrigin = pageUrl.startsWith(EARTH_ORIGIN) - if (isEarthOrigin && (permission === 'media' || permission === 'fullscreen')) { + targetSession.setPermissionRequestHandler((webContents, permission, callback, details) => { + if (permission === 'fullscreen') { + callback(isEarthUrl(webContents.getURL())) + return + } + if (permission === 'media' && details.isMainFrame && isEarthUrl(details.requestingUrl)) { + if ('mediaTypes' in details && details.mediaTypes?.includes('audio')) { + callback(false) + return + } + if (process.platform === 'darwin') { + void systemPreferences.askForMediaAccess('camera').then( + (granted) => callback(granted), + () => callback(false), + ) + return + } callback(true) return } callback(false) }) + + targetSession.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { + if (permission === 'fullscreen') return isEarthUrl(webContents?.getURL() || '') + if (permission !== 'media' || details.mediaType === 'audio' || !details.isMainFrame) return false + return ( + isEarthUrl(details.requestingUrl || requestingOrigin) && + (process.platform !== 'darwin' || systemPreferences.getMediaAccessStatus('camera') === 'granted') + ) + }) } diff --git a/client/src/preload/index.ts b/client/src/preload/index.ts index 15042a7f..f78e467d 100644 --- a/client/src/preload/index.ts +++ b/client/src/preload/index.ts @@ -17,6 +17,7 @@ interface PreloadRuntimeConfig { isElectron: true platform: string localMediaPipeBaseUrl: string + localPoseModelUrl: string } const runtimeConfig = ipcRenderer.sendSync('planet:get-runtime-config') as PreloadRuntimeConfig diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 3867a0b3..775b2d39 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,6 +8,18 @@ This project follows the repository versioning rule: - `improvement` -> `+0.0.1`(bugfix + 小功能混合) - `bugfix` -> `+0.0.1` +## [0.80.0] — 2026-11-26 + +Released: 2026-11-26 + +### Highlights + +- Earth streams AI workbench responses as they arrive and saves conversations and memory notes on the device. Asset and news cards can open a conversation with the selected item as context. +- AI Provider supports streaming across Anthropic Messages, OpenAI-compatible Chat Completions, OpenAI Responses, and Ollama. The Admin console can refresh public model catalogs in one operation. +- Earth bundles the MediaPipe runtime and pose model for local single-camera gesture control. Camera selection supports automatic detection and a manual choice. Dual-camera 3D is planned. + +--- + ## [0.79.2] — 2026-11-25 Released: 2026-11-25 diff --git a/docs/plans/README.md b/docs/plans/README.md index b6b74a32..d06bd96c 100644 --- a/docs/plans/README.md +++ b/docs/plans/README.md @@ -36,6 +36,7 @@ - [Earth News Cruise Summary Plan](/home/ray/dev/linkong/planet/docs/plans/earth-news-cruise-summary-plan.md) - [Earth 动作捕捉手势控制计划](/home/ray/dev/linkong/planet/docs/plans/earth-motion-capture-gesture-control-plan.md) - [Earth 动捕交互语义 V2 计划](/home/ray/dev/linkong/planet/docs/plans/earth-motion-gesture-interaction-v2-plan.md) +- [Earth 本地动捕单摄闭环与双摄真 3D 深度规划](/home/ray/dev/linkong/planet/docs/plans/earth-local-motion-single-and-dual-3d-plan.md) - [Motion Agent v2 控制协议与 3D 标定路线](/home/ray/dev/linkong/planet/docs/plans/motion-agent-v2-control-protocol-plan.md) - [Earth Presentation 解耦架构计划](/home/ray/dev/linkong/planet/docs/plans/earth-presentation-decoupled-architecture-plan.md) - [Earth Vessel Rendering Performance Plan](/home/ray/dev/linkong/planet/docs/plans/earth-vessel-rendering-performance-plan.md) diff --git a/docs/plans/earth-local-motion-single-and-dual-3d-plan.md b/docs/plans/earth-local-motion-single-and-dual-3d-plan.md new file mode 100644 index 00000000..029d39d4 --- /dev/null +++ b/docs/plans/earth-local-motion-single-and-dual-3d-plan.md @@ -0,0 +1,95 @@ +# Earth 本地动捕单摄闭环与双摄真 3D 深度规划 + +## 背景与目标 + +早期动捕 Demo 依赖本机单独启动 `motion_agent`(Python + OpenCV + MediaPipe)并通过 WebSocket 转发骨骼与手势事件。该方式在普通桌面客户端与网页端部署成本高、存在额外跨进程配置负担。 + +本方案确立统一方向:**默认由 Earth 渲染端(Electron 桌面客户端与 Web 网页版共用同一套运行时)在进程内直接完成本地摄像头采集与 MediaPipe WASM/WebGL 骨骼识别,零外部服务即可工作**;同时根据本机物理摄像头拓扑自动判定运行模式: + +- **单摄(Phase 1,已完成)**:自动启用单摄 2D 本地骨骼识别,完成 Web 与 Electron 全链路离线/自托管闭环。 +- **双摄(Phase 2,规划占位,目标硬件:罗技 C1000e × 2)**:检测到两台物理摄像头且完成双目标定后,自动进入双摄三角测量真 3D 深度模式,用于展厅近距离交互锁定与过滤背景路人。 + +--- + +## Phase 1:单摄本地动捕闭环(已完成) + +### 核心落地内容 + +1. **全离线 / 同源自托管 MediaPipe 资源** + - 将 `pose_landmarker_lite.task`(约 5.5 MiB)置于 `frontend/public/earth/vendor/mediapipe/pose_landmarker_lite.task`,并使 `frontend` 与 `client` 均锁定 `@mediapipe/tasks-vision@0.10.35`。 + - Web 构建与开发服务器(`frontend/scripts/earth-runtime-plugin.mjs`)以及 Nginx(`frontend/nginx.conf.template`)同源托管 `vision_bundle.mjs`、`wasm/` 与 `.task` 模型,并启用 WASM gzip 与长缓存,无需访问国外 CDN。 + - Electron 构建(`client/scripts/build-earth-bundle.mjs`)将 `vision_bundle.mjs`、`wasm/` 与 `.task` 打入离线 `earth` 资源包,由主进程向渲染层注入 `localMediaPipeBaseUrl` 与 `localPoseModelUrl`(移除未使用的 `vision_bundle.cjs`)。 +2. **GPU → CPU 自动降级与低分辨率采集** + - `frontend/public/earth/js/motion-browser-provider.js` 默认采集分辨率收敛为 `640×360`,降低 USB 带宽与纹理上传开销。 + - 当客户端处于 `software` 渲染模式或 WebGL/GPU delegate 初始化失败时,自动降级为 `CPU` delegate,并按「Electron 本地注入 → 同源 `./vendor/mediapipe/` → CDN 兜底」顺序加载模型与 WASM。 +3. **跨平台权限打通** + - Electron `client/electron-builder.yml` 增加 macOS `NSCameraUsageDescription` 权限声明;`client/src/main/protocol.ts` 在 macOS 下调用 `systemPreferences.askForMediaAccess('camera')` 并配置 `setPermissionCheckHandler`。 + - Web 端 `frontend/src/pages/Earth/Earth.tsx` 为 Earth `