Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(admin): support wildcard matching in list-accounts and list-users (#4409)

dingben953d0bb9f104
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index 16d38b037..81204ccac 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -1420,8 +1420,21 @@ impl HttpClient {
.await
}
- pub async fn admin_list_accounts(&self) -> Result<Value> {
- self.get("/api/v1/admin/accounts", &[]).await
+ pub async fn admin_list_accounts(
+ &self,
+ name: Option<String>,
+ limit: Option<u32>,
+ page: u32,
+ ) -> Result<Value> {
+ let mut params = vec![];
+ if let Some(n) = name {
+ params.push(("name".to_string(), n));
+ }
+ if let Some(l) = limit {
+ params.push(("limit".to_string(), l.to_string()));
+ params.push(("page".to_string(), page.to_string()));
+ }
+ self.get("/api/v1/admin/accounts", &params).await
}
pub async fn admin_delete_account(&self, account_id: &str) -> Result<Value> {
@@ -1453,12 +1466,17 @@ impl HttpClient {
pub async fn admin_list_users(
&self,
account_id: &str,
- limit: u32,
+ limit: Option<u32>,
name: Option<String>,
role: Option<String>,
+ page: u32,
) -> Result<Value> {
let path = format!("/api/v1/admin/accounts/{}/users", account_id);
- let mut params = vec![("limit".to_string(), limit.to_string())];
+ let mut params = vec![];
+ if let Some(l) = limit {
+ params.push(("limit".to_string(), l.to_string()));
+ params.push(("page".to_string(), page.to_string()));
+ }
if let Some(n) = name {
params.push(("name".to_string(), n));
}
diff --git a/crates/ov_cli/src/commands/admin.rs b/crates/ov_cli/src/commands/admin.rs
index bb8cf4de2..3c80c8f39 100644
--- a/crates/ov_cli/src/commands/admin.rs
+++ b/crates/ov_cli/src/commands/admin.rs
@@ -27,10 +27,13 @@ pub async fn create_account(
pub async fn list_accounts(
client: &HttpClient,
+ name: Option<String>,
+ limit: Option<u32>,
+ page: u32,
output_format: OutputFormat,
compact: bool,
) -> Result<()> {
- let response = client.admin_list_accounts().await?;
+ let response = client.admin_list_accounts(name, limit, page).await?;
output_success(&response, output_format, compact);
Ok(())
}
@@ -97,14 +100,15 @@ fn parse_user_config_json(value: Option<&str>, flag: &str) -> Result<Option<Valu
pub async fn list_users(
client: &HttpClient,
account_id: &str,
- limit: u32,
+ limit: Option<u32>,
name: Option<String>,
role: Option<String>,
+ page: u32,
output_format: OutputFormat,
compact: bool,
) -> Result<()> {
let response = client
- .admin_list_users(account_id, limit, name, role)
+ .admin_list_users(account_id, limit, name, role, page)
.await?;
let response = list_users_response_for_output(response, output_format);
output_success(&response, output_format, compact);
diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rs
index d5ac097f3..04a1aeae8 100644
--- a/crates/ov_cli/src/handlers.rs
+++ b/crates/ov_cli/src/handlers.rs
@@ -623,8 +623,9 @@ pub async fn handle_admin(cmd: AdminCommands, ctx: CliContext) -> Result<()> {
)
.await
}
- AdminCommands::ListAccounts => {
- commands::admin::list_accounts(&client, ctx.output_format, ctx.compact).await
+ AdminCommands::ListAccounts { name, limit, page } => {
+ commands::admin::list_accounts(&client, name, limit, page, ctx.output_format, ctx.compact)
+ .await
}
AdminCommands::DeleteAccount { account_id } => {
commands::admin::delete_account(&client, &account_id, ctx.output_format, ctx.compact)
@@ -657,6 +658,7 @@ pub async fn handle_admin(cmd: AdminCommands, ctx: CliContext) -> Result<()> {
limit,
name,
role,
+ page,
} => {
commands::admin::list_users(
&client,
@@ -664,6 +666,7 @@ pub async fn handle_admin(cmd: AdminCommands, ctx: CliContext) -> Result<()> {
limit,
name,
role,
+ page,
ctx.output_format,
ctx.compact,
)
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index 7aa6ff826..76330307d 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -1832,7 +1832,17 @@ enum AdminCommands {
user_config_json: Option<String>,
},
/// List all accounts (ROOT only)
- ListAccounts,
+ ListAccounts {
+ /// Filter accounts by ID (supports wildcard * and ?)
+ #[arg(long, value_name = "pattern")]
+ name: Option<String>,
+ /// Page size; omit to list all accounts
+ #[arg(long, value_name = "n")]
+ limit: Option<u32>,
+ /// 1-based page number (requires --limit)
+ #[arg(long, default_value = "1", value_name = "n")]
+ page: u32,
+ },
/// Delete an account and all associated users (ROOT only)
DeleteAccount {
/// Account ID to delete
@@ -1868,15 +1878,18 @@ enum AdminCommands {
/// Account ID
#[arg(value_name = "account-id")]
account_id: String,
- /// Maximum number of users to list (default: 100)
- #[arg(long, default_value = "100", value_name = "n")]
- limit: u32,
+ /// Page size; omit to list all users
+ #[arg(long, value_name = "n")]
+ limit: Option<u32>,
/// Filter users by name (supports wildcard * and ?)
#[arg(long, value_name = "pattern")]
name: Option<String>,
/// Filter users by role
#[arg(long, value_name = "role")]
role: Option<String>,
+ /// 1-based page number (requires --limit)
+ #[arg(long, default_value = "1", value_name = "n")]
+ page: u32,
},
/// Remove a user from an account
RemoveUser {
diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.md
index befb18054..2e9fb7284 100644
--- a/docs/en/api/08-admin.md
+++ b/docs/en/api/08-admin.md
@@ -337,8 +337,10 @@ List all workspaces (ROOT only).
**Processing Flow:**
1. Verify requester has ROOT privileges
-2. Call API Key Manager to get all accounts
-3. Return list with account ID, creation time, and user count
+2. Call API Key Manager to get all accounts (ordered lexicographically by account ID)
+3. Apply optional `name` filter
+4. Apply optional `limit`/`page` pagination
+5. Return list with account ID, creation time, and user count
**Code Entry Points:**
- `openviking/server/routers/admin.py:list_accounts` - HTTP route
@@ -347,7 +349,13 @@ List all workspaces (ROOT only).
#### 2. Interface and Parameters
-No parameters.
+| Parameter | Type | Required | Default | Description |
+|-----------|------|----------|---------|-------------|
+| name | str | No | null | Filter by account ID (wildcard `*` and `?` matching) |
+| limit | int | No | null | Page size (≥1). Omit to return all matches |
+| page | int | No | 1 | 1-based page number; only applies when `limit` is set |
+
+Results are always returned in lexicographic order of account ID.
#### 3. Usage Examples
@@ -358,8 +366,17 @@ GET /api/v1/admin/accounts
```
```bash
+# List all accounts
curl -X GET http://localhost:1933/api/v1/admin/accounts \
-H "X-API-Key: <root-key>"
+
+# With filter (wildcard name matching)
+curl -X GET "http://localhost:1933/api/v1/admin/accounts?name=*acme*" \
+ -H "X-API-Key: <root-key>"
+
+# Paginated (second page of 50)
+curl -X GET "http://localhost:1933/api/v1/admin/accounts?limit=50&page=2" \
+ -H "X-API-Key: <root-key>"
```
**Python SDK**
@@ -370,7 +387,7 @@ import openviking as ov
client = ov.SyncHTTPClient(api_key="<root-key>")
client.initialize()
-accounts = client.admin_list_accounts()
+accounts = client.admin_list_accounts(name="*acme*", limit=50, page=1)
for account in accounts:
print(f"Account: {account['account_id']}, created: {account['created_at']}, users: {account['user_count']}")
```
@@ -378,7 +395,7 @@ for account in accounts:
**TypeScript SDK**
```typescript
-console.log(await client.adminListAccounts());
+console.log(await client.adminListAccounts({ name: "*acme*", limit: 50, page: 1 }));
```
**Go SDK**
@@ -396,6 +413,12 @@ fmt.Println(accounts)
```bash
# Requires ROOT privileges, use --sudo
ov --sudo admin list-accounts
+
+# Filter by wildcard name
+ov --sudo admin list-accounts --name '*acme*'
+
+# Paginated
+ov --sudo admin list-accounts --limit 50 --page 2
```
**Response Example**
@@ -649,9 +672,10 @@ List active users in a workspace. Users with deletion in progress are omitted.
**Processing Flow:**
1. Verify requester has ROOT privileges or is an ADMIN of the account
-2. Call API Key Manager to get active users list
-3. Apply optional filters (name, role) and pagination limit
-4. Return users list (trusted mode omits user_key)
+2. Call API Key Manager to get active users list (ordered lexicographically by user ID)
+3. Apply optional filters (name, role)
+4. Apply optional `limit`/`page` pagination
+5. Return users list (trusted mode omits user_key)
**Code Entry Points:**
- `openviking/server/routers/admin.py:list_users` - HTTP route
@@ -665,11 +689,13 @@ List active users in a workspace. Users with deletion in progress are omitted.
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| account_id | str | Yes | - | Workspace ID |
-| limit | int | No | 100 | Maximum number of users to return |
-| name | str | No | null | Filter by user ID (prefix match) |
+| name | str | No | null | Filter by user ID (wildcard `*` and `?` matching) |
| role | str | No | null | Filter by role |
+| limit | int | No | null | Page size (≥1). Omit to return all matches |
+| page | int | No | 1 | 1-based page number; only applies when `limit` is set |
**Notes:**
+- Results are always returned in lexicographic order of user ID
- ADMIN can only list users in their own account
- In `trusted` mode, `user_key` is omitted from the response
- Users whose deletion has started are no longer returned
@@ -687,8 +713,12 @@ GET /api/v1/admin/accounts/{account_id}/users
curl -X GET http://localhost:1933/api/v1/admin/accounts/acme/users \
-H "X-API-Key: <root-or-admin-key>"
-# With filters
-curl -X GET "http://localhost:1933/api/v1/admin/accounts/acme/users?role=admin&limit=50" \
+# With filters (wildcard name matching)
+curl -X GET "http://localhost:1933/api/v1/admin/accounts/acme/users?name=*ali*&role=admin" \
+ -H "X-API-Key: <root-or-admin-key>"
+
+# Paginated (second page of 50)
+curl -X GET "http://localhost:1933/api/v1/admin/accounts/acme/users?limit=50&page=2" \
-H "X-API-Key: <root-or-admin-key>"
```
@@ -700,7 +730,7 @@ import openviking as ov
client = ov.SyncHTTPClient(api_key="<root-or-admin-key>")
client.initialize()
-users = client.admin_list_users(account_id="acme")
+users = client.admin_list_users(account_id="acme", name="*ali*", limit=50, page=1)
for user in users:
print(f"User: {user['user_id']}, role: {user['role']}")
```
@@ -708,7 +738,7 @@ for user in users:
**TypeScript SDK**
```typescript
-console.log(await client.adminListUsers("account-id"));
+console.log(await client.adminListUsers("account-id", { name: "*ali*", limit: 50, page: 1 }));
```
**Go SDK**
@@ -729,6 +759,10 @@ fmt.Println(users)
ov admin list-users acme
# If using root_api_key (--sudo):
ov --sudo admin list-users acme
+# Filter by wildcard name
+ov admin list-users acme --name '*ali*'
+# Paginated
+ov admin list-users acme --limit 50 --page 2
```
**Response Example**
diff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.md
index a33d7c5c3..cd3e95f65 100644
--- a/docs/zh/api/08-admin.md
+++ b/docs/zh/api/08-admin.md
@@ -329,8 +329,10 @@ ov --sudo admin create-account acme-private --admin alice \
**处理流程:**
1. 验证请求者具有 ROOT 权限
-2. 调用 API Key Manager 获取所有账户列表
-3. 返回包含账户 ID、创建时间和用户数量的列表
+2. 调用 API Key Manager 获取所有账户列表(按账户 ID 字典序排列)
+3. 应用可选的 `name` 过滤
+4. 应用可选的 `limit`/`page` 分页
+5. 返回包含账户 ID、创建时间和用户数量的列表
**代码入口:**
- `openviking/server/routers/admin.py:list_accounts` - HTTP 路由
@@ -339,7 +341,13 @@ ov --sudo admin create-account acme-private --admin alice \
#### 2. 接口和参数说明
-无参数。
+| 参数 | 类型 | 必填 | 默认值 | 说明 |
+|------|------|------|--------|------|
+| name | str | 否 | null | 按账户 ID 过滤(通配符 `*` 和 `?` 匹配) |
+| limit | int | 否 | null | 每页数量(≥1)。省略则返回所有匹配项 |
+| page | int | 否 | 1 | 从 1 开始的页码;仅在设置了 `limit` 时生效 |
+
+结果始终按账户 ID 字典序返回。
#### 3. 使用示例
@@ -350,8 +358,17 @@ GET /api/v1/admin/accounts
```
```bash
+# 列出所有账户
curl -X GET http://localhost:1933/api/v1/admin/accounts \
-H "X-API-Key: <root-key>"
+
+# 带过滤条件(通配符 name 匹配)
+curl -X GET "http://localhost:1933/api/v1/admin/accounts?name=*acme*" \
+ -H "X-API-Key: <root-key>"
+
+# 分页(每页 50,取第 2 页)
+curl -X GET "http://localhost:1933/api/v1/admin/accounts?limit=50&page=2" \
+ -H "X-API-Key: <root-key>"
```
**Python SDK**
@@ -362,7 +379,7 @@ import openviking as ov
client = ov.SyncHTTPClient(api_key="<root-key>")
client.initialize()
-accounts = client.admin_list_accounts()
+accounts = client.admin_list_accounts(name="*acme*", limit=50, page=1)
for account in accounts:
print(f"Account: {account['account_id']}, created: {account['created_at']}, users: {account['user_count']}")
```
@@ -370,7 +387,7 @@ for account in accounts:
**TypeScript SDK**
```typescript
-console.log(await client.adminListAccounts());
+console.log(await client.adminListAccounts({ name: "*acme*", limit: 50, page: 1 }));
```
**Go SDK**
@@ -388,6 +405,12 @@ fmt.Println(accounts)
```bash
# 需要 ROOT 权限,使用 --sudo
ov --sudo admin list-accounts
+
+# 按通配符 name 过滤
+ov --sudo admin list-accounts --name '*acme*'
+
+# 分页
+ov --sudo admin list-accounts --limit 50 --page 2
```
**响应示例**
@@ -641,9 +664,10 @@ ov admin register-user acme bob-private --role user \
**处理流程:**
1. 验证请求者具有 ROOT 权限,或为本账户的 ADMIN
-2. 调用 API Key Manager 获取活跃用户列表
-3. 应用可选的过滤条件(name、role)和分页限制
-4. 返回用户列表(trusted 模式下不包含 user_key)
+2. 调用 API Key Manager 获取活跃用户列表(按用户 ID 字典序排列)
+3. 应用可选的过滤条件(name、role)
+4. 应用可选的 `limit`/`page` 分页
+5. 返回用户列表(trusted 模式下不包含 user_key)
**代码入口:**
- `openviking/server/routers/admin.py:list_users` - HTTP 路由
@@ -657,11 +681,13 @@ ov admin register-user acme bob-private --role user \
| 参数 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
| account_id | str | 是 | - | 工作区 ID |
-| limit | int | 否 | 100 | 返回用户数量上限 |
-| name | str | 否 | null | 按用户 ID 过滤(前缀匹配) |
+| name | str | 否 | null | 按用户 ID 过滤(通配符 `*` 和 `?` 匹配) |
| role | str | 否 | null | 按角色过滤 |
+| limit | int | 否 | null | 每页数量(≥1)。省略则返回所有匹配项 |
+| page | int | 否 | 1 | 从 1 开始的页码;仅在设置了 `limit` 时生效 |
**说明:**
+- 结果始终按用户 ID 字典序返回
- ADMIN 只能列出自己所属的 account 中的用户
- 在 `trusted` 模式下,响应中不会包含 `user_key` 字段
- 用户删除开始后,不再出现在该列表中
@@ -679,8 +705,12 @@ GET /api/v1/admin/accounts/{account_id}/users
curl -X GET http://localhost:1933/api/v1/admin/accounts/acme/users \
-H "X-API-Key: <root-or-admin-key>"
-# 带过滤条件
-curl -X GET "http://localhost:1933/api/v1/admin/accounts/acme/users?role=admin&limit=50" \
+# 带过滤条件(通配符 name 匹配)
+curl -X GET "http://localhost:1933/api/v1/admin/accounts/acme/users?name=*ali*&role=admin" \
+ -H "X-API-Key: <root-or-admin-key>"
+
+# 分页(每页 50,取第 2 页)
+curl -X GET "http://localhost:1933/api/v1/admin/accounts/acme/users?limit=50&page=2" \
-H "X-API-Key: <root-or-admin-key>"
```
@@ -692,7 +722,7 @@ import openviking as ov
client = ov.SyncHTTPClient(api_key="<root-or-admin-key>")
client.initialize()
-users = client.admin_list_users(account_id="acme")
+users = client.admin_list_users(account_id="acme", name="*ali*", limit=50, page=1)
for user in users:
print(f"User: {user['user_id']}, role: {user['role']}")
```
@@ -700,7 +730,7 @@ for user in users:
**TypeScript SDK**
```typescript
-console.log(await client.adminListUsers("account-id"));
+console.log(await client.adminListUsers("account-id", { name: "*ali*", limit: 50, page: 1 }));
```
**Go SDK**
@@ -721,6 +751,10 @@ fmt.Println(users)
ov admin list-users acme
# 如果使用 root_api_key(--sudo):
ov --sudo admin list-users acme
+# 按通配符 name 过滤
+ov admin list-users acme --name '*ali*'
+# 分页
+ov admin list-users acme --limit 50 --page 2
```
**响应示例**
diff --git a/openviking/server/api_keys/legacy.py b/openviking/server/api_keys/legacy.py
index 53a8da278..0879ba8f2 100644
--- a/openviking/server/api_keys/legacy.py
+++ b/openviking/server/api_keys/legacy.py
@@ -59,6 +59,20 @@ def derive_seeded_api_key_secret(user_id: str, seed: str) -> str:
return hashlib.sha256(f"{user_id}\0{seed}".encode("utf-8")).hexdigest()
+def _paginate(items: list, limit: int | None, page: int) -> list:
+ """Slice a list by 1-based ``page`` of ``limit`` items.
+
+ ``limit=None`` returns everything (pagination is opt-in), so callers that
+ rely on the full set are unaffected. ``page`` is clamped to a minimum of 1.
+ """
+ if limit is None:
+ return items
+ if page < 1:
+ page = 1
+ start = (page - 1) * limit
+ return items[start : start + limit]
+
+
class LegacyAPIKeyManager:
"""Manages API keys for multi-tenant authentication (legacy implementation)."""
@@ -648,10 +662,27 @@ class LegacyAPIKeyManager:
await self._save_users_json(account_id)
- def get_accounts(self) -> list:
- """List all accounts."""
+ def get_accounts(
+ self,
+ name_filter: str | None = None,
+ limit: int | None = None,
+ page: int = 1,
+ ) -> list:
+ """List accounts in lexicographic order of account ID.
+
+ ``name_filter`` uses the same wildcard (``*`` and ``?``) matching as
+ ``get_users``. Pagination is opt-in: ``limit=None`` returns every
+ matching account so internal callers that rely on the full account set
+ are unaffected; when ``limit`` is set, ``page`` (1-based) selects the
+ slice.
+ """
result = []
- for account_id, info in self._accounts.items():
+ for account_id in sorted(self._accounts):
+ # Apply name filter if provided (fnmatch wildcard matching)
+ if name_filter and not fnmatch.fnmatch(account_id, name_filter):
+ continue
+
+ info = self._accounts[account_id]
result.append(
{
"account_id": account_id,
@@ -659,24 +690,29 @@ class LegacyAPIKeyManager:
"user_count": len(info.users),
}
)
- return result
+ return _paginate(result, limit, page)
def get_users(
self,
account_id: str,
- limit: int = 100,
+ limit: int | None = 100,
name_filter: str | None = None,
role_filter: str | None = None,
expose_key: bool = True,
+ page: int = 1,
) -> list:
- """List all users in an account."""
+ """List users in an account, ordered lexicographically by user ID.
+
+ Pagination is opt-in via ``limit``/``page`` (1-based); ``limit=None``
+ returns every matching user.
+ """
account = self._accounts.get(account_id)
if account is None:
raise NotFoundError(account_id, "account")
result = []
- count = 0
- for user_id, user_info in account.users.items():
+ for user_id in sorted(account.users):
+ user_info = account.users[user_id]
if user_info.get("deletion"):
continue
@@ -690,9 +726,6 @@ class LegacyAPIKeyManager:
if role_filter and user_role != role_filter:
continue
- if count >= limit:
- break
-
user_data = {
"user_id": user_id,
"role": user_role,
@@ -710,8 +743,7 @@ class LegacyAPIKeyManager:
# Plaintext key - show full api_key
user_data["api_key"] = key
result.append(user_data)
- count += 1
- return result
+ return _paginate(result, limit, page)
def has_user(self, account_id: str, user_id: str) -> bool:
"""Return True when the account registry contains the given user."""
diff --git a/openviking/server/api_keys/new.py b/openviking/server/api_keys/new.py
index 99ab5ada2..1f628b081 100644
--- a/openviking/server/api_keys/new.py
+++ b/openviking/server/api_keys/new.py
@@ -451,17 +451,23 @@ class NewAPIKeyManager:
"""Update a user's role."""
await self._legacy.set_role(account_id, user_id, role)
- def get_accounts(self) -> list:
+ def get_accounts(
+ self,
+ name_filter: str | None = None,
+ limit: int | None = None,
+ page: int = 1,
+ ) -> list:
"""List all accounts."""
- return self._legacy.get_accounts()
+ return self._legacy.get_accounts(name_filter=name_filter, limit=limit, page=page)
def get_users(
self,
account_id: str,
- limit: int = 100,
+ limit: int | None = 100,
name_filter: str | None = None,
role_filter: str | None = None,
expose_key: bool = True,
+ page: int = 1,
) -> list:
"""List all users in an account."""
return self._legacy.get_users(
@@ -470,6 +476,7 @@ class NewAPIKeyManager:
name_filter=name_filter,
role_filter=role_filter,
expose_key=expose_key,
+ page=page,
)
def has_user(self, account_id: str, user_id: str) -> bool:
diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.py
index e01096f3b..ae50b852a 100644
--- a/openviking/server/routers/admin.py
+++ b/openviking/server/routers/admin.py
@@ -5,7 +5,7 @@
import asyncio
from typing import Optional
-from fastapi import APIRouter, Body, Depends, Path, Request
+from fastapi import APIRouter, Body, Depends, Path, Query, Request
from pydantic import BaseModel
from openviking.server.account_settings import (
@@ -315,11 +315,14 @@ async def create_account(
@require_auth_root
async def list_accounts(
request: Request,
+ name: str | None = None,
+ limit: int | None = Query(None, ge=1, description="Page size; omit to return all"),
+ page: int = Query(1, ge=1, description="1-based page number (requires limit)"),
ctx: RequestContext = Depends(get_request_context),
):
- """List all accounts."""
+ """List accounts in lexicographic order. `name` supports wildcard (* and ?) matching."""
manager = _get_api_key_manager(request)
- accounts = manager.get_accounts()
+ accounts = manager.get_accounts(name_filter=name, limit=limit, page=page)
return Response(status="ok", result=accounts)
@@ -490,17 +493,23 @@ async def register_user(
async def list_users(
request: Request,
account_id: str = Path(..., description="Account ID"),
- limit: int = 100,
+ limit: int | None = Query(None, ge=1, description="Page size; omit to return all"),
name: str | None = None,
role: str | None = None,
+ page: int = Query(1, ge=1, description="1-based page number (requires limit)"),
ctx: RequestContext = Depends(get_request_context),
):
- """List all users in an account."""
+ """List users in an account, ordered lexicographically by user ID."""
_check_account_access(ctx, account_id)
manager = _get_api_key_manager(request)
expose_key = _should_expose_user_key(request)
users = manager.get_users(
- account_id, limit=limit, name_filter=name, role_filter=role, expose_key=expose_key
+ account_id,
+ limit=limit,
+ name_filter=name,
+ role_filter=role,
+ expose_key=expose_key,
+ page=page,
)
return Response(status="ok", result=users)
diff --git a/sdk/go/admin.go b/sdk/go/admin.go
index cf66be805..656af5bff 100644
--- a/sdk/go/admin.go
+++ b/sdk/go/admin.go
@@ -30,8 +30,26 @@ func (c *Client) AdminCreateAccountWithOptions(ctx context.Context, accountID, a
// AdminListAccounts lists accounts.
func (c *Client) AdminListAccounts(ctx context.Context) ([]any, error) {
+ return c.AdminListAccountsWithOptions(ctx, nil)
+}
+
+// AdminListAccountsWithOptions lists accounts (ordered by account ID), optionally
+// filtering by a wildcard name pattern and paging via Limit/Page.
+func (c *Client) AdminListAccountsWithOptions(ctx context.Context, opts *AdminListAccountsOptions) ([]any, error) {
+ query := url.Values{}
+ if opts != nil {
+ setQueryString(query, "name", opts.Name)
+ if opts.Limit != nil {
+ queryInt(query, "limit", *opts.Limit)
+ page := 1
+ if opts.Page != nil {
+ page = *opts.Page
+ }
+ queryInt(query, "page", page)
+ }
+ }
var result []any
- err := c.doJSON(ctx, http.MethodGet, "/api/v1/admin/accounts", nil, nil, &result)
+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/admin/accounts", query, nil, &result)
return result, err
}
@@ -69,8 +87,27 @@ func (c *Client) AdminRegisterUserWithOptions(ctx context.Context, accountID, us
// AdminListUsers lists users in an account.
func (c *Client) AdminListUsers(ctx context.Context, accountID string) ([]any, error) {
+ return c.AdminListUsersWithOptions(ctx, accountID, nil)
+}
+
+// AdminListUsersWithOptions lists users in an account (ordered by user ID),
+// optionally filtering by a wildcard name pattern, role, and paging via Limit/Page.
+func (c *Client) AdminListUsersWithOptions(ctx context.Context, accountID string, opts *AdminListUsersOptions) ([]any, error) {
+ query := url.Values{}
+ if opts != nil {
+ if opts.Limit != nil {
+ queryInt(query, "limit", *opts.Limit)
+ page := 1
+ if opts.Page != nil {
+ page = *opts.Page
+ }
+ queryInt(query, "page", page)
+ }
+ setQueryString(query, "name", opts.Name)
+ setQueryString(query, "role", opts.Role)
+ }
var result []any
- err := c.doJSON(ctx, http.MethodGet, "/api/v1/admin/accounts/"+url.PathEscape(accountID)+"/users", nil, nil, &result)
+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/admin/accounts/"+url.PathEscape(accountID)+"/users", query, nil, &result)
return result, err
}
diff --git a/sdk/go/types.go b/sdk/go/types.go
index d641d1239..cda267c5b 100644
--- a/sdk/go/types.go
+++ b/sdk/go/types.go
@@ -69,6 +69,27 @@ type AdminRegisterUserOptions struct {
Seed *string
}
+// AdminListAccountsOptions controls AdminListAccountsWithOptions.
+// Name uses wildcard (* and ?) matching against account IDs. Pagination is
+// opt-in: set Limit to page the (lexicographically ordered) result; Page is
+// 1-based and only applies when Limit is set.
+type AdminListAccountsOptions struct {
+ Name string
+ Limit *int
+ Page *int
+}
+
+// AdminListUsersOptions controls AdminListUsersWithOptions.
+// Name uses wildcard (* and ?) matching against user IDs. Pagination is
+// opt-in: set Limit to page the (lexicographically ordered) result; Page is
+// 1-based and only applies when Limit is set.
+type AdminListUsersOptions struct {
+ Limit *int
+ Name string
+ Role string
+ Page *int
+}
+
// AdminRegenerateKeyOptions controls AdminRegenerateKeyWithOptions.
type AdminRegenerateKeyOptions struct {
Seed *string
diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.py
index 497c02055..c0267e9d5 100644
--- a/sdk/python/openviking_sdk/client.py
+++ b/sdk/python/openviking_sdk/client.py
@@ -1692,8 +1692,19 @@ class AsyncHTTPClient:
)
return self._handle_response(response)
- async def admin_list_accounts(self) -> List[Any]:
- response = await self._request("GET", "/api/v1/admin/accounts")
+ async def admin_list_accounts(
+ self,
+ name: Optional[str] = None,
+ limit: Optional[int] = None,
+ page: int = 1,
+ ) -> List[Any]:
+ params: Dict[str, Any] = {}
+ if name is not None:
+ params["name"] = name
+ if limit is not None:
+ params["limit"] = limit
+ params["page"] = page
+ response = await self._request("GET", "/api/v1/admin/accounts", params=params)
return self._handle_response(response)
async def admin_delete_account(self, account_id: str) -> Dict[str, Any]:
@@ -1720,8 +1731,25 @@ class AsyncHTTPClient:
)
return self._handle_response(response)
- async def admin_list_users(self, account_id: str) -> List[Any]:
- response = await self._request("GET", f"/api/v1/admin/accounts/{account_id}/users")
+ async def admin_list_users(
+ self,
+ account_id: str,
+ limit: Optional[int] = None,
+ name: Optional[str] = None,
+ role: Optional[str] = None,
+ page: int = 1,
+ ) -> List[Any]:
+ params: Dict[str, Any] = {}
+ if limit is not None:
+ params["limit"] = limit
+ params["page"] = page
+ if name is not None:
+ params["name"] = name
+ if role is not None:
+ params["role"] = role
+ response = await self._request(
+ "GET", f"/api/v1/admin/accounts/{account_id}/users", params=params
+ )
return self._handle_response(response)
async def admin_remove_user(self, account_id: str, user_id: str) -> Dict[str, Any]:
@@ -2584,8 +2612,15 @@ class SyncHTTPClient:
)
)
- def admin_list_accounts(self) -> List[Any]:
- return run_async(self._async_client.admin_list_accounts())
+ def admin_list_accounts(
+ self,
+ name: Optional[str] = None,
+ limit: Optional[int] = None,
+ page: int = 1,
+ ) -> List[Any]:
+ return run_async(
+ self._async_client.admin_list_accounts(name=name, limit=limit, page=page)
+ )
def admin_delete_account(self, account_id: str) -> Dict[str, Any]:
return run_async(self._async_client.admin_delete_account(account_id))
@@ -2608,8 +2643,19 @@ class SyncHTTPClient:
)
)
- def admin_list_users(self, account_id: str) -> List[Any]:
- return run_async(self._async_client.admin_list_users(account_id))
+ def admin_list_users(
+ self,
+ account_id: str,
+ limit: Optional[int] = None,
+ name: Optional[str] = None,
+ role: Optional[str] = None,
+ page: int = 1,
+ ) -> List[Any]:
+ return run_async(
+ self._async_client.admin_list_users(
+ account_id, limit=limit, name=name, role=role, page=page
+ )
+ )
def admin_remove_user(self, account_id: str, user_id: str) -> Dict[str, Any]:
return run_async(self._async_client.admin_remove_user(account_id, user_id))
diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.ts
index 51d4be95c..da4ff0dad 100644
--- a/sdk/typescript/src/client.ts
+++ b/sdk/typescript/src/client.ts
@@ -1091,9 +1091,17 @@ export class OpenVikingClient {
}),
});
}
- /** List tenant accounts. */
- adminListAccounts(): Promise<unknown[]> {
- return this.request("GET", "/api/v1/admin/accounts");
+ /** List tenant accounts, ordered by account ID. `name` supports wildcard (* and ?) matching. */
+ adminListAccounts(
+ options: { name?: string; limit?: number; page?: number } = {},
+ ): Promise<unknown[]> {
+ return this.request("GET", "/api/v1/admin/accounts", {
+ query: {
+ name: options.name,
+ limit: options.limit,
+ page: options.limit !== undefined ? (options.page ?? 1) : undefined,
+ },
+ });
}
/** Delete a tenant account. */
adminDeleteAccount(accountId: string): Promise<JsonObject> {
@@ -1122,11 +1130,22 @@ export class OpenVikingClient {
},
);
}
- /** List users in an account. */
- adminListUsers(accountId: string): Promise<unknown[]> {
+ /** List users in an account, ordered by user ID. `name` supports wildcard (* and ?) matching. */
+ adminListUsers(
+ accountId: string,
+ options: { limit?: number; name?: string; role?: string; page?: number } = {},
+ ): Promise<unknown[]> {
return this.request(
"GET",
`/api/v1/admin/accounts/${pathPart(accountId)}/users`,
+ {
+ query: {
+ limit: options.limit,
+ name: options.name,
+ role: options.role,
+ page: options.limit !== undefined ? (options.page ?? 1) : undefined,
+ },
+ },
);
}
/** Remove a user from an account. */
diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.py
index cd8f9b064..324b93f28 100644
--- a/tests/server/test_admin_api.py
+++ b/tests/server/test_admin_api.py
@@ -261,13 +261,15 @@ async def _agfs_read_text(service: OpenVikingService, path: str) -> str:
async def _wait_for_task(client: httpx.AsyncClient, task_id: str) -> dict:
- for _ in range(100):
+ # Budget ~30s: recursive AGFS cleanup can take a couple of seconds, and the
+ # original 1s budget was too tight on slower backends/interpreters.
+ for _ in range(600):
resp = await client.get(f"/api/v1/tasks/{task_id}", headers=root_headers())
assert resp.status_code == 200
task = resp.json()["result"]
if task["status"] in {"completed", "failed"}:
return task
- await asyncio.sleep(0.01)
+ await asyncio.sleep(0.05)
raise AssertionError(f"Task {task_id} did not finish")
@@ -1350,15 +1352,17 @@ async def test_legacy_cleanup_removes_only_legacy_namespaces(
removed = {
(item["account_id"], item["source"]) for item in task["result"]["cleanup"]["targets"]
}
- assert (acct, "viking://agent") in removed
+ # Cleanup targets each legacy agent_id individually (reserved subdirs such as
+ # viking://agent/skills are preserved), so the agent roots appear per agent.
+ assert (acct, "viking://agent/code-agent") in removed
assert (acct, "viking://session") in removed
assert (acct, "viking://user/alice/agent") in removed
- assert (other_acct, "viking://agent") in removed
+ assert (other_acct, "viking://agent/code-agent") in removed
- assert not await _agfs_exists(admin_service, f"/local/{acct}/agent")
+ assert not await _agfs_exists(admin_service, f"/local/{acct}/agent/code-agent")
assert not await _agfs_exists(admin_service, f"/local/{acct}/session")
assert not await _agfs_exists(admin_service, f"/local/{acct}/user/alice/agent")
- assert not await _agfs_exists(admin_service, f"/local/{other_acct}/agent")
+ assert not await _agfs_exists(admin_service, f"/local/{other_acct}/agent/code-agent")
assert (
await _agfs_read_text(
admin_service,
diff --git a/tests/server/test_api_key_manager.py b/tests/server/test_api_key_manager.py
index edc9df2ff..9a3994718 100644
--- a/tests/server/test_api_key_manager.py
+++ b/tests/server/test_api_key_manager.py
@@ -358,7 +358,101 @@ async def test_get_users(manager: APIKeyManager):
assert {u["user_id"] for u in users} == {"alice"}
-# ---- Persistence tests ----
+async def test_get_users_name_filter(manager: APIKeyManager):
+ """get_users name_filter uses fnmatch wildcard matching against user IDs."""
+ acct = _uid()
+ await manager.create_account(acct, "alice")
+ await manager.register_user(acct, "alan", "user")
+ await manager.register_user(acct, "bob", "user")
+
+ # Wildcard substring match
+ matched = {u["user_id"] for u in manager.get_users(acct, name_filter="al*")}
+ assert matched == {"alice", "alan"}
+
+ # Exact match (no wildcard) only hits the literal ID
+ assert {u["user_id"] for u in manager.get_users(acct, name_filter="alice")} == {"alice"}
+
+ # No match
+ assert manager.get_users(acct, name_filter="zzz*") == []
+
+ # No filter returns all
+ assert {u["user_id"] for u in manager.get_users(acct)} == {"alice", "alan", "bob"}
+
+
+async def test_get_accounts_filter(manager: APIKeyManager):
+ """get_accounts supports fnmatch name_filter, mirroring get_users."""
+ prefix = f"acme_{uuid.uuid4().hex[:8]}"
+ first = f"{prefix}_alpha"
+ second = f"{prefix}_beta"
+ other = f"other_{uuid.uuid4().hex[:8]}"
+ await manager.create_account(first, "u1")
+ await manager.create_account(second, "u2")
+ await manager.create_account(other, "u3")
+
+ # Wildcard match returns only the two prefixed accounts
+ matched = {a["account_id"] for a in manager.get_accounts(name_filter=f"{prefix}*")}
+ assert matched == {first, second}
+
+ # Exact match (no wildcard) hits a single account
+ assert {a["account_id"] for a in manager.get_accounts(name_filter=first)} == {first}
+
+ # No filter returns all accounts (including the default one)
+ all_ids = {a["account_id"] for a in manager.get_accounts()}
+ assert {first, second, other} <= all_ids
+
+
+async def test_get_users_pagination_and_ordering(manager: APIKeyManager):
+ """get_users returns users in lexicographic order and honors limit/page."""
+ acct = _uid()
+ await manager.create_account(acct, "alice")
+ # Register out of order; expected sorted order is alice, bob, carol, dave.
+ await manager.register_user(acct, "dave", "user")
+ await manager.register_user(acct, "bob", "user")
+ await manager.register_user(acct, "carol", "user")
+
+ # No limit -> all users, lexicographically ordered.
+ ids = [u["user_id"] for u in manager.get_users(acct)]
+ assert ids == ["alice", "bob", "carol", "dave"]
+
+ # First page of 2.
+ page1 = [u["user_id"] for u in manager.get_users(acct, limit=2, page=1)]
+ assert page1 == ["alice", "bob"]
+
+ # Second page of 2.
+ page2 = [u["user_id"] for u in manager.get_users(acct, limit=2, page=2)]
+ assert page2 == ["carol", "dave"]
+
+ # Page past the end is empty.
+ assert manager.get_users(acct, limit=2, page=3) == []
+
+ # Pagination applies after the name filter.
+ filtered = [u["user_id"] for u in manager.get_users(acct, name_filter="*a*", limit=1, page=2)]
+ assert filtered == ["carol"]
+
+
+async def test_get_accounts_pagination_and_ordering(manager: APIKeyManager):
+ """get_accounts returns accounts in lexicographic order and honors limit/page."""
+ prefix = f"page_{uuid.uuid4().hex[:8]}"
+ ids = [f"{prefix}_{suffix}" for suffix in ("delta", "alpha", "charlie", "bravo")]
+ for account_id in ids:
+ await manager.create_account(account_id, "u")
+
+ expected = sorted(ids)
+
+ # No limit -> all matches, lexicographically ordered.
+ got = [a["account_id"] for a in manager.get_accounts(name_filter=f"{prefix}*")]
+ assert got == expected
+
+ # First page of 2.
+ page1 = [a["account_id"] for a in manager.get_accounts(name_filter=f"{prefix}*", limit=2, page=1)]
+ assert page1 == expected[:2]
+
+ # Second page of 2.
+ page2 = [a["account_id"] for a in manager.get_accounts(name_filter=f"{prefix}*", limit=2, page=2)]
+ assert page2 == expected[2:]
+
+ # Page past the end is empty.
+ assert manager.get_accounts(name_filter=f"{prefix}*", limit=2, page=3) == []
async def test_persistence_across_reload(manager_service):