Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(admin): list agent namespaces (#1821)
Qin Haojiee887744540b6
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rsindex 00f556584..8412804c6 100644--- a/crates/ov_cli/src/client.rs+++ b/crates/ov_cli/src/client.rs@@ -980,6 +980,11 @@ impl HttpClient {self.get(&path, ¶ms).await}+ pub async fn admin_list_agents(&self, account_id: &str) -> Result<Value> {+ let path = format!("/api/v1/admin/accounts/{}/agents", account_id);+ self.get(&path, &[]).await+ }+pub async fn admin_remove_user(&self, account_id: &str, user_id: &str) -> Result<Value> {let path = format!("/api/v1/admin/accounts/{}/users/{}", account_id, user_id);self.delete(&path, &[]).awaitdiff --git a/crates/ov_cli/src/commands/admin.rs b/crates/ov_cli/src/commands/admin.rsindex 6ed25b6c6..8c4d58ee1 100644--- a/crates/ov_cli/src/commands/admin.rs+++ b/crates/ov_cli/src/commands/admin.rs@@ -73,6 +73,17 @@ pub async fn list_users(Ok(())}+pub async fn list_agents(+ client: &HttpClient,+ account_id: &str,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {+ let response = client.admin_list_agents(account_id).await?;+ output_success(&response, output_format, compact);+ Ok(())+}+pub async fn remove_user(client: &HttpClient,account_id: &str,diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rsindex 252c9389e..a4f247c86 100644--- a/crates/ov_cli/src/handlers.rs+++ b/crates/ov_cli/src/handlers.rs@@ -331,6 +331,9 @@ pub async fn handle_admin(cmd: AdminCommands, ctx: CliContext) -> Result<()> {AdminCommands::ListUsers { account_id, limit, name, role } => {commands::admin::list_users(&client, &account_id, limit, name, role, ctx.output_format, ctx.compact).await}+ AdminCommands::ListAgents { account_id } => {+ commands::admin::list_agents(&client, &account_id, ctx.output_format, ctx.compact).await+ }AdminCommands::RemoveUser {account_id,user_id,diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex 1f9373310..9e411c86d 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -748,6 +748,11 @@ enum AdminCommands {#[arg(long)]role: Option<String>,},+ /// List all agent namespaces in an account+ ListAgents {+ /// Account ID+ account_id: String,+ },/// Remove a user from an accountRemoveUser {/// Account IDdiff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.mdindex ba08c8eb4..66c1aebbf 100644--- a/docs/en/api/08-admin.md+++ b/docs/en/api/08-admin.md@@ -22,6 +22,7 @@ For `/api/v1/admin/*`, trusted mode also permits requests with no explicit ident| Create/delete workspace | Y | N | N || List workspaces | Y | N | N || Register/remove users | Y | Y (own account) | N |+| List agent namespaces | Y | Y (own account) | N || Regenerate user key | Y | Y (own account) | N || Change user role | Y | N | N |@@ -513,6 +514,75 @@ ov --sudo admin list-users acme---+### list_agents++#### 1. API Implementation Overview++List agent namespaces that exist under a workspace. This is an admin discovery API; it does not change normal `viking://agent/...` filesystem semantics.++**Processing Flow:**+1. Verify requester has ROOT privileges or is an ADMIN of the account+2. Verify the account exists+3. Scan the account's `viking://agent` namespace root+4. Return sorted agent namespace entries++**Code Entry Points:**+- `openviking/server/routers/admin.py:list_agents` - HTTP route+- `crates/ov_cli/src/client.rs:HttpClient.admin_list_agents` - CLI HTTP client+- `crates/ov_cli/src/commands/admin.rs:list_agents` - CLI command++#### 2. Interface and Parameters++**Parameters**++| Parameter | Type | Required | Default | Description |+|-----------|------|----------|---------|-------------|+| account_id | str | Yes | - | Workspace ID |++**Notes:**+- ROOT can list agents in any account+- ADMIN can only list agents in their own account+- USER cannot call this API+- The result lists agent namespaces that exist in storage. A new account includes the initialized `default` agent namespace.++#### 3. Usage Examples++**HTTP API**++```+GET /api/v1/admin/accounts/{account_id}/agents+```++```bash+curl -X GET http://localhost:1933/api/v1/admin/accounts/acme/agents \+ -H "X-API-Key: <root-or-admin-key>"+```++**CLI**++```bash+# Either ROOT or account ADMIN can execute+# If using regular user's api_key who is an ADMIN of acme:+ov admin list-agents acme+# If using root_api_key (--sudo):+ov --sudo admin list-agents acme+```++**Response Example**++```json+{+ "status": "ok",+ "result": [+ {"agent_id": "default", "uri": "viking://agent/default"},+ {"agent_id": "openclaw", "uri": "viking://agent/openclaw"}+ ],+ "time": 0.1+}+```++---+### remove_user#### 1. API Implementation Overviewdiff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.mdindex 72769cfd9..4dc6c3b05 100644--- a/docs/zh/api/08-admin.md+++ b/docs/zh/api/08-admin.md@@ -22,6 +22,7 @@ Admin API 用于多租户环境下的账户和用户管理。包括工作区(a| 创建/删除工作区 | Y | N | N || 列出工作区 | Y | N | N || 注册/移除用户 | Y | Y(本 account) | N |+| 列出 agent namespace | Y | Y(本 account) | N || 重新生成 User Key | Y | Y(本 account) | N || 修改用户角色 | Y | N | N |@@ -511,6 +512,75 @@ ov --sudo admin list-users acme---+### list_agents++#### 1. API 实现介绍++列出工作区中已经存在的 agent namespace。这是管理侧发现接口,不改变普通 `viking://agent/...` 文件系统语义。++**处理流程:**+1. 验证请求者具有 ROOT 权限,或为本账户的 ADMIN+2. 验证 account 存在+3. 扫描该 account 的 `viking://agent` namespace 根目录+4. 返回按 agent_id 排序的 agent namespace 列表++**代码入口:**+- `openviking/server/routers/admin.py:list_agents` - HTTP 路由+- `crates/ov_cli/src/client.rs:HttpClient.admin_list_agents` - CLI HTTP 客户端+- `crates/ov_cli/src/commands/admin.rs:list_agents` - CLI 命令++#### 2. 接口和参数说明++**参数**++| 参数 | 类型 | 必填 | 默认值 | 说明 |+|------|------|------|--------|------|+| account_id | str | 是 | - | 工作区 ID |++**说明:**+- ROOT 可以列出任意 account 的 agents+- ADMIN 只能列出自己所属 account 的 agents+- USER 不能调用该接口+- 返回的是存储中已经存在的 agent namespace;新建 account 会包含初始化出的 `default` agent namespace++#### 3. 使用示例++**HTTP API**++```+GET /api/v1/admin/accounts/{account_id}/agents+```++```bash+curl -X GET http://localhost:1933/api/v1/admin/accounts/acme/agents \+ -H "X-API-Key: <root-or-admin-key>"+```++**CLI**++```bash+# ROOT 或本账户的 ADMIN 都可以执行+# 如果使用普通用户的 api_key 但该用户是 acme 的 ADMIN:+ov admin list-agents acme+# 如果使用 root_api_key(--sudo):+ov --sudo admin list-agents acme+```++**响应示例**++```json+{+ "status": "ok",+ "result": [+ {"agent_id": "default", "uri": "viking://agent/default"},+ {"agent_id": "openclaw", "uri": "viking://agent/openclaw"}+ ],+ "time": 0.1+}+```++---+### remove_user#### 1. API 实现介绍diff --git a/openviking/console/app.py b/openviking/console/app.pyindex 3f8190fa7..145c78c45 100644--- a/openviking/console/app.py+++ b/openviking/console/app.py@@ -242,6 +242,13 @@ def _create_proxy_router() -> APIRouter:return invalidreturn await _forward_request(request, f"/api/v1/admin/accounts/{account_id}/users")+ @router.get("/ov/admin/accounts/{account_id}/agents")+ async def admin_agents(request: Request, account_id: str):+ invalid = _validate_path_param(account_id, "account_id")+ if invalid:+ return invalid+ return await _forward_request(request, f"/api/v1/admin/accounts/{account_id}/agents")+@router.get("/ov/system/status")async def system_status(request: Request):return await _forward_request(request, "/api/v1/system/status")diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.pyindex c32222e77..eda91bdbf 100644--- a/openviking/server/routers/admin.py+++ b/openviking/server/routers/admin.py@@ -16,7 +16,7 @@ from openviking.server.dependencies import get_servicefrom openviking.server.identity import AccountNamespacePolicy, RequestContext, Rolefrom openviking.server.models import Responsefrom openviking.storage.viking_fs import get_viking_fs-from openviking_cli.exceptions import PermissionDeniedError+from openviking_cli.exceptions import NotFoundError, PermissionDeniedErrorfrom openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils.logger import get_logger@@ -205,6 +205,48 @@ async def list_users(return Response(status="ok", result=users)[email protected]("/accounts/{account_id}/agents")+@require_auth_root_or_admin+async def list_agents(+ request: Request,+ account_id: str = Path(..., description="Account ID"),+ ctx: RequestContext = Depends(get_request_context),+):+ """List agent namespaces that have data under an account."""+ _check_account_access(ctx, account_id)+ manager = _get_api_key_manager(request)+ manager.get_users(account_id, limit=1, expose_key=False)+ policy = manager.get_account_policy(account_id)+ viking_fs = get_viking_fs()+ list_ctx = RequestContext(+ user=UserIdentifier(account_id, "system", "system"),+ role=Role.ROOT,+ namespace_policy=policy,+ )++ try:+ entries = await viking_fs.ls("viking://agent", ctx=list_ctx, output="original")+ except NotFoundError:+ entries = []++ agents = []+ for entry in entries:+ if not entry.get("isDir", False):+ continue+ agent_id = str(entry.get("name", "")).strip()+ if not agent_id:+ continue+ agents.append(+ {+ "agent_id": agent_id,+ "uri": f"viking://agent/{agent_id}",+ }+ )++ agents.sort(key=lambda item: item["agent_id"])+ return Response(status="ok", result=agents)++@router.delete("/accounts/{account_id}/users/{user_id}")@require_auth_root_or_adminasync def remove_user(diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.pyindex 9cf17724b..bc652fe18 100644--- a/tests/server/test_admin_api.py+++ b/tests/server/test_admin_api.py@@ -12,6 +12,7 @@ from openviking.server.api_keys import APIKeyManagerfrom openviking.server.app import create_appfrom openviking.server.config import ServerConfigfrom openviking.server.dependencies import set_service+from openviking.server.identity import RequestContext, Rolefrom openviking.service.core import OpenVikingServicefrom openviking_cli.session.user_id import UserIdentifier@@ -72,6 +73,14 @@ def trusted_headers(return headers+async def create_agent_namespace(service: OpenVikingService, account_id: str, agent_id: str):+ ctx = RequestContext(+ user=UserIdentifier(account_id, "system", agent_id),+ role=Role.ROOT,+ )+ await service.viking_fs.mkdir(f"viking://agent/{agent_id}", ctx=ctx, exist_ok=True)++# ---- Account CRUD ----@@ -237,6 +246,110 @@ async def test_list_users(admin_client: httpx.AsyncClient):assert user_ids == {"alice", "bob"}+async def test_list_agents(admin_client: httpx.AsyncClient, admin_service: OpenVikingService):+ """ROOT can list agent namespaces in an account."""+ acct = _uid()+ await admin_client.post(+ "/api/v1/admin/accounts",+ json={"account_id": acct, "admin_user_id": "alice"},+ headers=root_headers(),+ )+ await create_agent_namespace(admin_service, acct, "research")+ await create_agent_namespace(admin_service, acct, "writer")++ resp = await admin_client.get(f"/api/v1/admin/accounts/{acct}/agents", headers=root_headers())++ assert resp.status_code == 200+ assert resp.json()["result"] == [+ {"agent_id": "default", "uri": "viking://agent/default"},+ {"agent_id": "research", "uri": "viking://agent/research"},+ {"agent_id": "writer", "uri": "viking://agent/writer"},+ ]+++async def test_list_agents_returns_default_for_new_account(+ admin_client: httpx.AsyncClient,+):+ """New accounts should expose the initialized default agent namespace."""+ acct = _uid()+ await admin_client.post(+ "/api/v1/admin/accounts",+ json={"account_id": acct, "admin_user_id": "alice"},+ headers=root_headers(),+ )++ resp = await admin_client.get(f"/api/v1/admin/accounts/{acct}/agents", headers=root_headers())++ assert resp.status_code == 200+ assert resp.json()["result"] == [+ {"agent_id": "default", "uri": "viking://agent/default"},+ ]+++async def test_admin_can_list_agents_in_own_account(+ admin_client: httpx.AsyncClient,+ admin_service: OpenVikingService,+):+ """ADMIN can list agent namespaces in their own account."""+ acct = _uid()+ resp = await admin_client.post(+ "/api/v1/admin/accounts",+ json={"account_id": acct, "admin_user_id": "alice"},+ headers=root_headers(),+ )+ alice_key = resp.json()["result"]["user_key"]+ await create_agent_namespace(admin_service, acct, "assistant")++ resp = await admin_client.get(+ f"/api/v1/admin/accounts/{acct}/agents",+ headers={"X-API-Key": alice_key},+ )++ assert resp.status_code == 200+ assert resp.json()["result"] == [+ {"agent_id": "assistant", "uri": "viking://agent/assistant"},+ {"agent_id": "default", "uri": "viking://agent/default"},+ ]+++async def test_admin_cannot_list_agents_in_other_account(+ admin_client: httpx.AsyncClient,+ admin_service: OpenVikingService,+):+ """ADMIN cannot list agent namespaces in another account."""+ acct = _uid()+ other = _uid()+ resp = await admin_client.post(+ "/api/v1/admin/accounts",+ json={"account_id": acct, "admin_user_id": "alice"},+ headers=root_headers(),+ )+ alice_key = resp.json()["result"]["user_key"]+ await admin_client.post(+ "/api/v1/admin/accounts",+ json={"account_id": other, "admin_user_id": "eve"},+ headers=root_headers(),+ )+ await create_agent_namespace(admin_service, other, "foreign")++ resp = await admin_client.get(+ f"/api/v1/admin/accounts/{other}/agents",+ headers={"X-API-Key": alice_key},+ )++ assert resp.status_code == 403+++async def test_list_agents_unknown_account_returns_404(admin_client: httpx.AsyncClient):+ """Unknown accounts should use the same 404 behavior as other admin account APIs."""+ resp = await admin_client.get(+ f"/api/v1/admin/accounts/{_uid()}/agents",+ headers=root_headers(),+ )++ assert resp.status_code == 404++async def test_remove_user(admin_client: httpx.AsyncClient):"""ROOT can remove a user."""acct = _uid()