common-agent 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. common_agent/__init__.py +1 -0
  2. common_agent/app.py +464 -0
  3. common_agent/baseline/__init__.py +1 -0
  4. common_agent/baseline/auth.py +90 -0
  5. common_agent/baseline/checks.py +33 -0
  6. common_agent/baseline/policy.py +36 -0
  7. common_agent/cli.py +110 -0
  8. common_agent/config/__init__.py +1 -0
  9. common_agent/config/loader.py +76 -0
  10. common_agent/config/schema.py +129 -0
  11. common_agent/credential_boot.py +23 -0
  12. common_agent/doctor.py +167 -0
  13. common_agent/log_config.py +40 -0
  14. common_agent/model_catalog/__init__.py +1 -0
  15. common_agent/model_catalog/adapter.py +52 -0
  16. common_agent/model_catalog/router.py +222 -0
  17. common_agent/model_catalog/storage.py +197 -0
  18. common_agent/project_render.py +41 -0
  19. common_agent/py.typed +0 -0
  20. common_agent/rag/__init__.py +1 -0
  21. common_agent/rag/rerank.py +350 -0
  22. common_agent/request_log.py +91 -0
  23. common_agent/templates/starter/.env.example +5 -0
  24. common_agent/templates/starter/.gitignore +9 -0
  25. common_agent/templates/starter/README.md +69 -0
  26. common_agent/templates/starter/app/__init__.py +1 -0
  27. common_agent/templates/starter/app/agent/__init__.py +1 -0
  28. common_agent/templates/starter/app/agent/runtime.py +51 -0
  29. common_agent/templates/starter/app/api/__init__.py +1 -0
  30. common_agent/templates/starter/app/api/orders.py +27 -0
  31. common_agent/templates/starter/app/core/__init__.py +1 -0
  32. common_agent/templates/starter/app/core/seed_data.py +25 -0
  33. common_agent/templates/starter/app/log_config.py +40 -0
  34. common_agent/templates/starter/app/main.py +56 -0
  35. common_agent/templates/starter/app/request_log.py +91 -0
  36. common_agent/templates/starter/app/service/__init__.py +1 -0
  37. common_agent/templates/starter/app/service/order_service.py +23 -0
  38. common_agent/templates/starter/app/tools/crm.py +38 -0
  39. common_agent/templates/starter/application.yml +41 -0
  40. common_agent/templates/starter/frontend/README.md +34 -0
  41. common_agent/templates/starter/frontend/dist/assets/index-B74dwWzh.css +1 -0
  42. common_agent/templates/starter/frontend/dist/assets/index-DFfMKx-L.js +83 -0
  43. common_agent/templates/starter/frontend/dist/index.html +13 -0
  44. common_agent/templates/starter/frontend/index.html +12 -0
  45. common_agent/templates/starter/frontend/package-lock.json +1416 -0
  46. common_agent/templates/starter/frontend/package.json +22 -0
  47. common_agent/templates/starter/frontend/playwright.config.js +10 -0
  48. common_agent/templates/starter/frontend/src/App.vue +23 -0
  49. common_agent/templates/starter/frontend/src/api.js +82 -0
  50. common_agent/templates/starter/frontend/src/components/chat/ChatInput.vue +31 -0
  51. common_agent/templates/starter/frontend/src/components/chat/ConfirmCard.vue +33 -0
  52. common_agent/templates/starter/frontend/src/components/chat/MessageList.vue +56 -0
  53. common_agent/templates/starter/frontend/src/components/chat/SessionSidebar.vue +115 -0
  54. common_agent/templates/starter/frontend/src/components/chat/SettingsDialog.vue +69 -0
  55. common_agent/templates/starter/frontend/src/components/chat/TeamPanel.vue +35 -0
  56. common_agent/templates/starter/frontend/src/components/chat/ToolCallCard.vue +17 -0
  57. common_agent/templates/starter/frontend/src/icons.js +18 -0
  58. common_agent/templates/starter/frontend/src/main.js +12 -0
  59. common_agent/templates/starter/frontend/src/pages/ChatPage.vue +488 -0
  60. common_agent/templates/starter/frontend/src/pages/CredentialsPage.vue +126 -0
  61. common_agent/templates/starter/frontend/src/pages/ModelsPage.vue +296 -0
  62. common_agent/templates/starter/frontend/src/replay.js +45 -0
  63. common_agent/templates/starter/frontend/src/router.js +18 -0
  64. common_agent/templates/starter/frontend/src/sprite.js +27 -0
  65. common_agent/templates/starter/frontend/src/sse.js +99 -0
  66. common_agent/templates/starter/frontend/src/styles/app.css +217 -0
  67. common_agent/templates/starter/frontend/src/styles/tokens.css +61 -0
  68. common_agent/templates/starter/frontend/src/theme.js +37 -0
  69. common_agent/templates/starter/frontend/src/ui/ConfirmDialog.vue +20 -0
  70. common_agent/templates/starter/frontend/src/ui/Dialog.vue +29 -0
  71. common_agent/templates/starter/frontend/src/ui/EmptyState.vue +14 -0
  72. common_agent/templates/starter/frontend/src/ui/ThemeSeg.vue +18 -0
  73. common_agent/templates/starter/frontend/tests/e2e.spec.js +22 -0
  74. common_agent/templates/starter/frontend/tests/hitl-sse.spec.js +54 -0
  75. common_agent/templates/starter/frontend/vite.config.js +17 -0
  76. common_agent/templates/starter/pyproject.toml +30 -0
  77. common_agent/templates/starter/run.py +25 -0
  78. common_agent/templates/starter/tests/__init__.py +1 -0
  79. common_agent/templates/starter/tests/test_smoke.py +32 -0
  80. common_agent/tools/__init__.py +20 -0
  81. common_agent/tools/builtin/__init__.py +1 -0
  82. common_agent/tools/builtin/sop.py +348 -0
  83. common_agent/tools/discovery.py +70 -0
  84. common_agent/tools/toolkit.py +107 -0
  85. common_agent-0.1.0.dist-info/METADATA +19 -0
  86. common_agent-0.1.0.dist-info/RECORD +88 -0
  87. common_agent-0.1.0.dist-info/WHEEL +4 -0
  88. common_agent-0.1.0.dist-info/entry_points.txt +2 -0
@@ -0,0 +1 @@
1
+ """common-agent:AgentScope 官方平台之上的配置化交付层,包含配置装配、工具发现、部门安全基线与 CLI。"""
common_agent/app.py ADDED
@@ -0,0 +1,464 @@
1
+ """装配编排:application.yml → 官方组件、storage 种子记录与独立 FastAPI 应用的唯一翻译入口。"""
2
+ import json
3
+ import os
4
+ import uuid
5
+ from contextlib import asynccontextmanager
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+ from typing import Any, Self
9
+
10
+ from agentscope.agent import ContextConfig, ReActConfig
11
+ from agentscope.app import create_app
12
+ from agentscope.app.channel import DingTalkChannel, DiscordChannel, FeishuChannel
13
+ from agentscope.app.message_bus import InMemoryMessageBus, MessageBus, RedisMessageBus
14
+ from agentscope.app.storage import (
15
+ AgentChatConfig,
16
+ AgentData,
17
+ AgentRecord,
18
+ AsyncSQLAlchemyStorage,
19
+ RedisStorage,
20
+ StorageBase,
21
+ )
22
+ from agentscope.app.workspace_manager import LocalWorkspaceManager, WorkspaceManagerBase
23
+ from agentscope.credential import (
24
+ AnthropicCredential,
25
+ CredentialBase,
26
+ DashScopeCredential,
27
+ DeepSeekCredential,
28
+ OpenAICredential,
29
+ )
30
+ from agentscope.middleware import MiddlewareBase
31
+ from agentscope.permission import PermissionMode, PermissionRule
32
+ from agentscope.rag import ApproxTokenChunker, TextParser
33
+ from fastapi import HTTPException
34
+ from fastapi.middleware import Middleware
35
+ from pydantic import SecretStr
36
+
37
+ from .baseline.auth import _AuthMiddleware
38
+ from .baseline.checks import run_baseline_checks
39
+ from .baseline.policy import SystemSharedAccessPolicy
40
+ from .config.loader import ConfigLoadError, load_config
41
+ from .config.schema import AgentSpec, AppConfig
42
+ from .request_log import RequestLogMiddleware
43
+ from .tools.builtin.sop import register_sop_tool_group
44
+ from .tools.discovery import discover_tools
45
+ from .tools.toolkit import install_toolkit_extensions
46
+
47
+ CHANNEL_TYPES = {
48
+ "feishu": FeishuChannel,
49
+ "dingtalk": DingTalkChannel,
50
+ "discord": DiscordChannel,
51
+ }
52
+
53
+ _CREDENTIAL_TYPES = {
54
+ "dashscope": DashScopeCredential,
55
+ "openai": OpenAICredential,
56
+ "anthropic": AnthropicCredential,
57
+ "deepseek": DeepSeekCredential,
58
+ }
59
+
60
+
61
+ @dataclass
62
+ class Components:
63
+ """经 lifespan 管理的官方组件集合。"""
64
+
65
+ storage: StorageBase
66
+ message_bus: MessageBus
67
+ workspace_manager: WorkspaceManagerBase
68
+ knowledge_base_manager: Any | None = None
69
+ # 知识库上传文件的 blob 存储后端(kb.enabled 时为 LocalBlobStore)
70
+ blob_store: Any | None = None
71
+ # rerank 后端注册表:下游可在 build_agent_app 前注册私有协议实现。
72
+ rerank_backends: Any | None = field(default_factory=lambda: None)
73
+ # 绑定该组件集合的 FastAPI 应用:嵌入模式下由 AgentRuntime 亲自驱动其官方 lifespan。
74
+ app: Any | None = None
75
+
76
+
77
+ class _OwnerFallbackStorage:
78
+ """agent 只读回退包装:会话身份查不到 agent 记录时,回退属主范围直读。
79
+
80
+ 团队工具(TeamSay/TeamCreate 等)以会话 user 直读 storage;业务前端
81
+ 身份(如 web-user)与种子 agent 属主(owner_user_id)不一致时,leader
82
+ 回读拿不到记录,TeamSay 报 leader records missing。凭据侧已有等价的
83
+ resolve_credential 属主回退语义,agent 侧在此对齐。其余属性与写路径
84
+ 全部原样转发,行为不变。
85
+ """
86
+
87
+ def __init__(self, inner: Any, owner_user_id: str) -> None:
88
+ self._inner = inner
89
+ self._owner_user_id = owner_user_id
90
+
91
+ async def get_agent(self, user_id: str, agent_id: str):
92
+ record = await self._inner.get_agent(user_id, agent_id)
93
+ if record is None and user_id != self._owner_user_id:
94
+ record = await self._inner.get_agent(self._owner_user_id, agent_id)
95
+ return record
96
+
97
+ # 官方 lifespan 直接 enter storage:协议方法不走 __getattr__,必须显式转发
98
+ def __aenter__(self):
99
+ return self._inner.__aenter__()
100
+
101
+ def __aexit__(self, *exc_info):
102
+ return self._inner.__aexit__(*exc_info)
103
+
104
+ def __getattr__(self, name: str):
105
+ return getattr(self._inner, name)
106
+
107
+
108
+ def build_components(config: AppConfig) -> Components:
109
+ """按 app 节构造存储、总线与工作区组件(未 enter,生命周期由应用 lifespan 管理)。"""
110
+ if config.storage.type == "redis":
111
+ storage: StorageBase = _redis_storage_from_url(config.storage.url)
112
+ else:
113
+ _ensure_sqlite_parent_dir(config.storage.url)
114
+ # json 列默认 json.dumps(ensure_ascii=True),汉字落库成 \uXXXX 转义;
115
+ # 显式关掉让 payload 直接存中文字符(读取 json.loads 不受影响)
116
+ storage = AsyncSQLAlchemyStorage(
117
+ config.storage.url,
118
+ engine_kwargs={"json_serializer": lambda obj: json.dumps(obj, ensure_ascii=False)},
119
+ )
120
+ if config.message_bus.type == "redis":
121
+ bus: MessageBus = RedisMessageBus(
122
+ host=config.message_bus.host,
123
+ port=config.message_bus.port,
124
+ db=config.message_bus.db,
125
+ password=config.message_bus.password,
126
+ )
127
+ else:
128
+ bus = InMemoryMessageBus()
129
+ workspace = LocalWorkspaceManager(basedir=config.workspace.basedir, ttl=config.workspace.ttl)
130
+
131
+ # 知识库(RAG):enabled 时装配官方 CollectionPerKbManager(MilvusLite 本地向量库)
132
+ # 与 LocalBlobStore;milvus-lite 未安装时 fail-fast 给出安装指引。
133
+ kb_manager = None
134
+ blob_store = None
135
+ if config.knowledge_base.enabled:
136
+ try:
137
+ from agentscope.rag import MilvusLiteStore
138
+ except ImportError as exc:
139
+ raise ConfigLoadError(
140
+ "knowledge_base.enabled=true 需要向量库依赖(未安装 milvus-lite)。\n"
141
+ " 安装:uv pip install milvus-lite"
142
+ ) from exc
143
+ from agentscope.app.rag.blob_store import LocalBlobStore
144
+ from agentscope.app.rag.knowledge_base_manager import CollectionPerKbManager
145
+
146
+ blob_store = LocalBlobStore(config.knowledge_base.blob_dir)
147
+ kb_manager = CollectionPerKbManager(
148
+ storage,
149
+ MilvusLiteStore(config.knowledge_base.vector_path),
150
+ )
151
+
152
+ from .rag.rerank import RerankBackendRegistry
153
+
154
+ return Components(storage=_OwnerFallbackStorage(storage, config.owner_user_id),
155
+ message_bus=bus, workspace_manager=workspace,
156
+ knowledge_base_manager=kb_manager, blob_store=blob_store,
157
+ rerank_backends=RerankBackendRegistry())
158
+
159
+
160
+ def _redis_storage_from_url(url: str) -> RedisStorage:
161
+ """把 redis://[user]:password@host:port/db 形式的 url 解析为官方 RedisStorage 构造参数。"""
162
+ from urllib.parse import unquote, urlparse
163
+
164
+ parsed = urlparse(url)
165
+ if parsed.scheme not in {"redis", "rediss"}:
166
+ raise ConfigLoadError("storage.type=redis 时 storage.url 必须使用 redis:// 或 rediss://")
167
+ return RedisStorage(
168
+ host=parsed.hostname or "localhost",
169
+ port=parsed.port or 6379,
170
+ db=int(parsed.path.lstrip("/") or "0"),
171
+ password=unquote(parsed.password) if parsed.password else None,
172
+ )
173
+
174
+
175
+ def _ensure_sqlite_parent_dir(url: str) -> None:
176
+ """sqlite 文件路径的父目录缺失时创建,避免首启 unable to open database file。"""
177
+ tail = url.removeprefix(url.split("://", 1)[0] + "://") if "://" in url else url
178
+ tail = tail.removeprefix("/")
179
+ if not tail or tail.startswith(":memory:"):
180
+ return
181
+ path = Path(tail)
182
+ path.expanduser().parent.mkdir(parents=True, exist_ok=True)
183
+
184
+
185
+ def _deterministic_id(*parts: str) -> str:
186
+ """配置键到稳定 id 的映射,保证重复启动 upsert 为更新而非新增。"""
187
+ return str(uuid.uuid5(uuid.NAMESPACE_URL, ":".join(parts)))
188
+
189
+
190
+ class AgentRuntime:
191
+ """接入方主 app lifespan 中使用的组件生命周期包装:enter 后种子写入。"""
192
+
193
+ def __init__(self, config: AppConfig) -> None:
194
+ self.config = config
195
+ # 组件在构造期装配(未 enter),供接入方在进入 lifespan 前即可 mount 路由 app。
196
+ self.components: Components | None = build_components(config)
197
+ self._app_lifespan: Any | None = None
198
+
199
+ async def __aenter__(self) -> Self:
200
+ assert self.components is not None
201
+ if self.components.app is not None:
202
+ # mount 的子应用 lifespan 不会被主应用触发,这里代为驱动官方 lifespan
203
+ # (它负责组件 enter 与全部服务装配),种子写入由 lifespan 收尾执行。
204
+ self._app_lifespan = self.components.app.router.lifespan_context(self.components.app)
205
+ await self._app_lifespan.__aenter__()
206
+ else:
207
+ await self.components.storage.__aenter__()
208
+ await self.components.message_bus.__aenter__()
209
+ await self.components.workspace_manager.__aenter__()
210
+ await seed_agents(self.config, self.components)
211
+ return self
212
+
213
+ async def __aexit__(self, *exc_info) -> None:
214
+ assert self.components is not None
215
+ if self._app_lifespan is not None:
216
+ await self._app_lifespan.__aexit__(*exc_info)
217
+ self._app_lifespan = None
218
+ return
219
+ await self.components.workspace_manager.__aexit__(*exc_info)
220
+ await self.components.message_bus.__aexit__(*exc_info)
221
+ await self.components.storage.__aexit__(*exc_info)
222
+
223
+
224
+ class _PermissionMiddleware(MiddlewareBase):
225
+ """按配置设置每轮 agent 的权限档位与免确认工具白名单。
226
+
227
+ 继承官方 MiddlewareBase 以满足中间件协议(is_implemented 反射、
228
+ list_tools 等钩子默认实现)——纯 duck-typing 自建类会在官方
229
+ Agent 装配与 get_toolkit 阶段直接 AttributeError。
230
+ """
231
+
232
+ def __init__(self, mode: str | None, tool_permissions: dict[str, str]) -> None:
233
+ self._mode = mode
234
+ self._tool_permissions = tool_permissions
235
+
236
+ async def on_reply(self, agent, input_kwargs, next_handler):
237
+ """实测校准:on_reply 为 async generator,next_handler() 无参调用并逐事件透传。"""
238
+ context = agent.state.permission_context
239
+ if self._mode is not None:
240
+ context.mode = PermissionMode[self._mode]
241
+ rule_buckets = {
242
+ "allow": context.allow_rules,
243
+ "deny": context.deny_rules,
244
+ "ask": context.ask_rules,
245
+ }
246
+ for tool_name, behavior in self._tool_permissions.items():
247
+ # rule_content=None 是工具名级规则,匹配该工具全部调用
248
+ bucket = rule_buckets[behavior]
249
+ if tool_name not in bucket:
250
+ bucket[tool_name] = [PermissionRule(
251
+ tool_name=tool_name,
252
+ rule_content=None,
253
+ behavior=behavior,
254
+ source="common-agent",
255
+ )]
256
+ async for event in next_handler():
257
+ yield event
258
+
259
+
260
+ def _permission_middleware_factory(config: AppConfig):
261
+ """extra_agent_middlewares 异步工厂:按 agent_id(确定性 id)反查配置档位与白名单。"""
262
+ profile_by_id = {
263
+ _deterministic_id(config.owner_user_id, key): (spec.permission_mode, spec.tool_permissions)
264
+ for key, spec in config.agents.items()
265
+ }
266
+ spec_by_id = {
267
+ key: _deterministic_id(config.owner_user_id, key)
268
+ for key in config.agents
269
+ }
270
+
271
+ async def factory(user_id, agent_id, session_id):
272
+ mode, tool_permissions = profile_by_id.get(agent_id, (None, {}))
273
+ agent_key = next((key for key, mapped_id in spec_by_id.items() if mapped_id == agent_id), None)
274
+ from .rag.rerank import set_rerank_agent_key
275
+
276
+ set_rerank_agent_key(agent_key)
277
+ return [_PermissionMiddleware(mode, tool_permissions)]
278
+
279
+ return factory
280
+
281
+
282
+ def _build_chat_config(spec: AgentSpec) -> AgentChatConfig:
283
+ """把声明面(context/react)翻译为官方 AgentChatConfig;缺省节用官方默认值。"""
284
+ context = ContextConfig(**spec.context.model_dump()) if spec.context else ContextConfig()
285
+ react = ReActConfig(max_iters=spec.react.max_iters) if spec.react else ReActConfig()
286
+ return AgentChatConfig(context_config=context, react_config=react)
287
+
288
+
289
+ async def seed_agents(config: AppConfig, components: Components) -> None:
290
+ """把 agents 节幂等写入 storage:先凭据后智能体,必须在应用 lifespan 异步上下文中 await。"""
291
+ for key, spec in config.agents.items():
292
+ raw_key = os.environ.get(spec.model.api_key_ref)
293
+ if not raw_key:
294
+ raise ConfigLoadError(f"智能体 {key} 的密钥环境变量缺失: {spec.model.api_key_ref}")
295
+ credential_type = _CREDENTIAL_TYPES.get(spec.model.provider)
296
+ if credential_type is None:
297
+ raise ConfigLoadError(f"厂商 {spec.model.provider} 的凭据构造未实现")
298
+ # 凭据与智能体的存储主键显式取确定性 id:重启 upsert 覆盖同一行,避免重复记录。
299
+ agent_id = _deterministic_id(config.owner_user_id, key)
300
+ credential_kwargs: dict[str, Any] = {"api_key": SecretStr(raw_key)}
301
+ if spec.model.base_url_ref:
302
+ # 环境变量缺失或空值均走官方默认端点(.env 里 API_BASE= 即留空语义)
303
+ base_url = os.environ.get(spec.model.base_url_ref, "").strip()
304
+ if base_url:
305
+ credential_kwargs["base_url"] = base_url
306
+ credential: CredentialBase = credential_type(
307
+ id=_deterministic_id(config.owner_user_id, key, "credential"),
308
+ **credential_kwargs,
309
+ )
310
+ await components.storage.upsert_credential(config.owner_user_id, credential)
311
+ data = AgentData(
312
+ id=agent_id,
313
+ name=key,
314
+ system_prompt=spec.system_prompt,
315
+ chat_config=_build_chat_config(spec),
316
+ )
317
+ await components.storage.upsert_agent(
318
+ config.owner_user_id,
319
+ AgentRecord(id=agent_id, user_id=config.owner_user_id, data=data),
320
+ )
321
+
322
+
323
+ def build_agent_app(
324
+ config: AppConfig,
325
+ components: Components,
326
+ tools_base_dir: Path | None = None,
327
+ rerank_resolver: Any | None = None,
328
+ ):
329
+ """用官方 create_app 组装 FastAPI:策略、鉴权、工具工厂与渠道白名单一次装配。"""
330
+ unknown = [name for name in config.channels if name not in CHANNEL_TYPES]
331
+ if unknown:
332
+ raise ConfigLoadError(f"未知渠道类型: {', '.join(unknown)},支持: {', '.join(CHANNEL_TYPES)}")
333
+ install_toolkit_extensions()
334
+ tools_base = (tools_base_dir or Path.cwd()).resolve()
335
+ spec_by_id = {key: _deterministic_id(config.owner_user_id, key) for key in config.agents}
336
+
337
+ async def tool_factory(user_id: str, agent_id: str, session_id: str) -> list:
338
+ for key, mapped_id in spec_by_id.items():
339
+ if mapped_id == agent_id:
340
+ report = discover_tools(config.agents[key].tools, base_dir=tools_base)
341
+ if report.errors:
342
+ raise ConfigLoadError("工具发现失败:\n" + "\n".join(report.errors))
343
+ return report.tools
344
+ return []
345
+
346
+ app = create_app(
347
+ storage=components.storage,
348
+ message_bus=components.message_bus,
349
+ workspace_manager=components.workspace_manager,
350
+ knowledge_base_manager=components.knowledge_base_manager,
351
+ knowledge_parsers=[TextParser()] if components.knowledge_base_manager else None,
352
+ knowledge_chunkers=[ApproxTokenChunker] if components.knowledge_base_manager else None,
353
+ blob_store=components.blob_store,
354
+ resource_access_policy=SystemSharedAccessPolicy(config.owner_user_id),
355
+ extra_middlewares=[Middleware(_AuthMiddleware, security=config.security)],
356
+ extra_agent_tools=tool_factory,
357
+ extra_agent_middlewares=_permission_middleware_factory(config),
358
+ channels=[CHANNEL_TYPES[name] for name in config.channels],
359
+ download_secret=config.security.download_secret,
360
+ title=config.name,
361
+ )
362
+ _include_model_catalog(app, config, components, rerank_resolver)
363
+ components.app = app
364
+ register_sop_tool_group(components)
365
+ _append_seed_to_lifespan(app, config, components)
366
+ return app
367
+
368
+
369
+ def _include_model_catalog(
370
+ app: Any,
371
+ config: AppConfig,
372
+ components: Components,
373
+ rerank_resolver: Any | None = None,
374
+ ) -> None:
375
+ """挂载模型目录组件:建表随 lifespan、凭据解析复用官方 storage 与共享策略。"""
376
+ from .model_catalog.router import build_model_catalog_router
377
+ from .model_catalog.storage import ModelCatalogStorage
378
+
379
+ url = config.storage.url
380
+ if not url:
381
+ return
382
+ catalog_storage = ModelCatalogStorage(url)
383
+
384
+ async def resolve_credential(credential_id: str, viewer_id: str) -> dict:
385
+ """官方凭据解析:属主直读;非属主经部门共享策略只读可见。"""
386
+ record = await components.storage.get_credential(viewer_id, credential_id)
387
+ if record is None and viewer_id != config.owner_user_id:
388
+ record = await components.storage.get_credential(config.owner_user_id, credential_id)
389
+ if record is None:
390
+ raise HTTPException(status_code=404, detail=f"凭据 {credential_id} 不可见")
391
+ data = record.data.get("data", record.data)
392
+ return {
393
+ "type": record.data.get("type", ""),
394
+ "base_url": data.get("base_url") or "",
395
+ "api_key": data.get("api_key", ""),
396
+ }
397
+
398
+ if rerank_resolver is None:
399
+ from .rag.rerank import DefaultRerankResolver
400
+
401
+ rerank_resolver = DefaultRerankResolver(
402
+ catalog_storage=catalog_storage,
403
+ credential_resolver=resolve_credential,
404
+ backends=components.rerank_backends,
405
+ )
406
+ app.include_router(build_model_catalog_router(catalog_storage, config.owner_user_id, resolve_credential))
407
+ _install_rerank_rag_middleware(config, rerank_resolver)
408
+
409
+ original = app.router.lifespan_context
410
+
411
+ @asynccontextmanager
412
+ async def lifespan_with_catalog(inner_app):
413
+ await catalog_storage.create_all()
414
+ async with original(inner_app):
415
+ yield
416
+
417
+ app.router.lifespan_context = lifespan_with_catalog
418
+
419
+
420
+ def _install_rerank_rag_middleware(config: AppConfig, rerank_resolver: Any) -> None:
421
+ """任一 agent 启用 rerank 时,让托管 ChatService 使用 rerank-aware RAGMiddleware。"""
422
+ enabled_agent_keys = {key for key, spec in config.agents.items() if spec.rerank.enabled}
423
+ if not enabled_agent_keys:
424
+ return
425
+ from agentscope.app import _service as agentscope_service
426
+
427
+ from .rag.rerank import build_rerank_rag_middleware
428
+
429
+ # AgentScope 2.0.12 的 ChatService 在模块导入期绑定 RAGMiddleware;
430
+ # 固定版本下用子类替换是当前最小侵入点。升级 AgentScope 必须回归本测试。
431
+ agentscope_service._chat.RAGMiddleware = build_rerank_rag_middleware(
432
+ owner_user_id=config.owner_user_id,
433
+ enabled_agent_keys=enabled_agent_keys,
434
+ resolver=rerank_resolver,
435
+ )
436
+
437
+
438
+ def _append_seed_to_lifespan(app, config: AppConfig, components: Components) -> None:
439
+ """在官方 lifespan 组件 enter 之后、yield 之前执行种子写入,保证种子使用已就绪的 storage。"""
440
+ original = app.router.lifespan_context
441
+
442
+ @asynccontextmanager
443
+ async def lifespan(inner_app):
444
+ async with original(inner_app):
445
+ await seed_agents(config, components)
446
+ yield
447
+
448
+ app.router.lifespan_context = lifespan
449
+
450
+
451
+ def build_app(path: str | Path):
452
+ """独立模式入口:yml 路径 → 基线检查 → 组件装配 → 可直接 uvicorn 运行的 FastAPI。"""
453
+ config = load_config(path)
454
+ report = run_baseline_checks(config)
455
+ if report.errors:
456
+ raise ConfigLoadError("安全基线检查未通过:\n" + "\n".join(f"- {e}" for e in report.errors))
457
+ components = build_components(config)
458
+ app = build_agent_app(config, components, tools_base_dir=Path(path).resolve().parent)
459
+ # 独立模式同样落全量请求日志(与嵌入模式 main.py 的挂载行为一致)
460
+ app.add_middleware(
461
+ RequestLogMiddleware,
462
+ log_dir=Path(path).resolve().parent / "data" / "logs",
463
+ )
464
+ return app
@@ -0,0 +1 @@
1
+ """安全基线域:启动检查、鉴权中间件与部门共享访问策略。"""
@@ -0,0 +1,90 @@
1
+ """鉴权中间件:鉴别身份并注入官方端点依赖的 X-User-ID。"""
2
+ import base64
3
+ import os
4
+
5
+ from starlette.types import ASGIApp, Receive, Scope, Send
6
+
7
+ from ..config.schema import SecurityConfig
8
+
9
+
10
+ def _parse_users(raw: str) -> dict[str, str]:
11
+ users: dict[str, str] = {}
12
+ for item in raw.split(","):
13
+ name, _, password = item.strip().partition(":")
14
+ if name and password:
15
+ users[name] = password
16
+ return users
17
+
18
+
19
+ async def _send_401(send: Send) -> None:
20
+ body = '{"detail":"无效凭证"}'.encode()
21
+ await send({
22
+ "type": "http.response.start",
23
+ "status": 401,
24
+ "headers": [
25
+ (b"content-type", b"application/json"),
26
+ (b"content-length", str(len(body)).encode()),
27
+ (b"www-authenticate", b"Basic"),
28
+ ],
29
+ })
30
+ await send({"type": "http.response.body", "body": body})
31
+
32
+
33
+ class _AuthMiddlewareFactory:
34
+ """FastAPI add_middleware 协议要求的中间件类:以 app 实例化后返回 ASGI 实现。"""
35
+
36
+ def __init__(self, security: SecurityConfig) -> None:
37
+ self.security = security
38
+
39
+ def __call__(self, app: ASGIApp) -> "_AuthMiddleware":
40
+ return _AuthMiddleware(app, self.security)
41
+
42
+
43
+ class _AuthMiddleware:
44
+ def __init__(self, app: ASGIApp, security: SecurityConfig) -> None:
45
+ self.app = app
46
+ self.security = security
47
+
48
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
49
+ if scope["type"] != "http":
50
+ await self.app(scope, receive, send)
51
+ return
52
+ user_id: str | None = None
53
+ if self.security.auth == "basic":
54
+ user_id = self._authenticate_basic(scope)
55
+ if user_id is None:
56
+ await _send_401(send)
57
+ return
58
+ else:
59
+ existing = self._header(scope, "x-user-id")
60
+ user_id = existing.decode("latin-1") if existing is not None else "local-dev"
61
+ scope["headers"] = [
62
+ (key, value) for key, value in scope["headers"] if key != b"x-user-id"
63
+ ]
64
+ scope["headers"].append((b"x-user-id", user_id.encode("latin-1")))
65
+ await self.app(scope, receive, send)
66
+
67
+ def _authenticate_basic(self, scope: Scope) -> str | None:
68
+ users = _parse_users(os.environ.get(self.security.users_env, ""))
69
+ raw_authorization = self._header(scope, "authorization")
70
+ if raw_authorization is None:
71
+ return None
72
+ authorization = raw_authorization.decode("latin-1")
73
+ if not authorization.startswith("Basic "):
74
+ return None
75
+ try:
76
+ name, _, password = base64.b64decode(authorization[6:]).decode("utf-8").partition(":")
77
+ except ValueError:
78
+ return None
79
+ if name and users.get(name) == password:
80
+ return name
81
+ return None
82
+
83
+ @staticmethod
84
+ def _header(scope: Scope, name: str) -> bytes | None:
85
+ return next((value for key, value in scope["headers"] if key == name.encode()), None)
86
+
87
+
88
+ def build_auth_middleware(security: SecurityConfig) -> _AuthMiddlewareFactory:
89
+ """按 security 声明构造 ASGI 中间件。"""
90
+ return _AuthMiddlewareFactory(security)
@@ -0,0 +1,33 @@
1
+ """部门安全基线启动检查:BYPASS 门控、鉴权与生产项告警。"""
2
+ from dataclasses import dataclass, field
3
+
4
+ from ..config.schema import AppConfig
5
+
6
+
7
+ @dataclass
8
+ class BaselineReport:
9
+ """检查结果:errors 阻止启动,warnings 写启动日志。"""
10
+
11
+ errors: list[str] = field(default_factory=list)
12
+ warnings: list[str] = field(default_factory=list)
13
+
14
+
15
+ def run_baseline_checks(config: AppConfig) -> BaselineReport:
16
+ """执行全部基线检查并返回报告。"""
17
+ report = BaselineReport()
18
+ if not config.security.allow_bypass_mode:
19
+ for key, spec in config.agents.items():
20
+ if spec.permission_mode == "BYPASS":
21
+ report.errors.append(
22
+ f"智能体 {key} 配置了 BYPASS 权限档位,但 security.allow_bypass_mode=false;"
23
+ "沙箱场景需显式打开该开关",
24
+ )
25
+ if config.security.auth == "none":
26
+ report.warnings.append(
27
+ "security.auth=none 仅限本地开发:请求身份直接信任 X-User-ID,禁止暴露到网络",
28
+ )
29
+ if not config.security.download_secret:
30
+ report.warnings.append(
31
+ "未设置 security.download_secret;多副本/负载均衡部署必须显式设置,否则工作区文件下载随机失败",
32
+ )
33
+ return report
@@ -0,0 +1,36 @@
1
+ """部门共享访问策略:共享 owner 的资源对所有已认证用户只读可用。"""
2
+ from agentscope.app.access import (
3
+ ResourceAccessPolicyBase,
4
+ ResourceKind,
5
+ ResourcePermission,
6
+ ResourceRef,
7
+ )
8
+
9
+
10
+ class SystemSharedAccessPolicy(ResourceAccessPolicyBase):
11
+ """允许所有用户访问 shared_owner(默认 system)名下的 agent 与 credential。"""
12
+
13
+ def __init__(self, shared_owner: str = "system") -> None:
14
+ self._shared_owner = shared_owner
15
+
16
+ async def list_accessible(self, viewer_id: str, kind: ResourceKind, storage) -> list[ResourceRef]:
17
+ if viewer_id == self._shared_owner:
18
+ return []
19
+ refs: list[ResourceRef] = []
20
+ if kind == ResourceKind.AGENT:
21
+ for record in await storage.list_agents(self._shared_owner):
22
+ refs.append(ResourceRef(
23
+ kind=kind,
24
+ owner_id=self._shared_owner,
25
+ resource_id=record.data.id,
26
+ permission=ResourcePermission.READ,
27
+ ))
28
+ elif kind == ResourceKind.CREDENTIAL:
29
+ for record in await storage.list_credentials(self._shared_owner):
30
+ refs.append(ResourceRef(
31
+ kind=kind,
32
+ owner_id=self._shared_owner,
33
+ resource_id=record.id,
34
+ permission=ResourcePermission.READ,
35
+ ))
36
+ return refs