Skip to content

Build and run agents you can see, understand and trust.

feat(service): support to share resource (credential, agent, knowledge bases) across different users as a group or org (#1998)

DavdGao1aeb03d00429
diff --git a/examples/web_ui/frontend/src/api/agent.ts b/examples/web_ui/frontend/src/api/agent.ts
index 264793e4d..557aa390d 100644
--- a/examples/web_ui/frontend/src/api/agent.ts
+++ b/examples/web_ui/frontend/src/api/agent.ts
@@ -1,7 +1,7 @@
import { client } from './client';
import type {
AgentListResponse,
- AgentRecord,
+ AgentView,
AgentSchemaV2Response,
CreateAgentRequest,
CreateAgentResponse,
@@ -17,7 +17,7 @@ export const agentApi = {
client.post<CreateAgentResponse>('/agent/', body, undefined, options),
update: (agentId: string, body: UpdateAgentRequest, options?: { silent?: boolean }) =>
- client.patch<AgentRecord>(`/agent/${agentId}`, body, undefined, options),
+ client.patch<AgentView>(`/agent/${agentId}`, body, undefined, options),
delete: (agentId: string) => client.delete(`/agent/${agentId}`),
};
diff --git a/examples/web_ui/frontend/src/api/credential.ts b/examples/web_ui/frontend/src/api/credential.ts
index 49e486d5b..28f03f527 100644
--- a/examples/web_ui/frontend/src/api/credential.ts
+++ b/examples/web_ui/frontend/src/api/credential.ts
@@ -3,7 +3,7 @@ import type {
CreateCredentialRequest,
CreateCredentialResponse,
CredentialListResponse,
- CredentialRecord,
+ CredentialView,
CredentialSchemasResponse,
UpdateCredentialRequest,
} from './types';
@@ -17,7 +17,7 @@ export const credentialApi = {
client.post<CreateCredentialResponse>('/credential/', body),
update: (credentialId: string, body: UpdateCredentialRequest) =>
- client.patch<CredentialRecord>(`/credential/${credentialId}`, body),
+ client.patch<CredentialView>(`/credential/${credentialId}`, body),
delete: (credentialId: string) => client.delete(`/credential/${credentialId}`),
};
diff --git a/examples/web_ui/frontend/src/api/types.ts b/examples/web_ui/frontend/src/api/types.ts
index 6c539df5e..344691043 100644
--- a/examples/web_ui/frontend/src/api/types.ts
+++ b/examples/web_ui/frontend/src/api/types.ts
@@ -49,9 +49,14 @@ export interface AgentData {
invite_config: InviteConfig;
}
-export interface AgentRecord extends RecordBase {
+export interface AgentView extends RecordBase {
user_id: string;
data: AgentData;
+ /**
+ * Whether the current viewer may PATCH/DELETE this agent. `false`
+ * for agents shared to the viewer with read-only permission.
+ */
+ editable: boolean;
}
export interface CreateAgentRequest {
@@ -75,7 +80,7 @@ export interface UpdateAgentRequest {
}
export interface AgentListResponse {
- agents: AgentRecord[];
+ agents: AgentView[];
total: number;
}
@@ -220,11 +225,11 @@ export interface TeamRecord extends RecordBase {
/**
* One member entry inside `TeamDetailResponse.members`. Pairs the
- * worker's `AgentRecord` with its single `session_id` so the UI can
+ * worker's `AgentView` with its single `session_id` so the UI can
* navigate straight to the worker's chat.
*/
export interface TeamMemberInfo {
- agent: AgentRecord;
+ agent: AgentView;
/** `null` if the agent is in an inconsistent state (no session). */
session_id: string | null;
}
@@ -232,12 +237,12 @@ export interface TeamMemberInfo {
/**
* Resolved team detail returned inline inside `SessionView.team`.
*
- * The leader's `AgentRecord` is looked up from the team's
+ * The leader's `AgentView` is looked up from the team's
* `session_id` → `session.agent_id` chain on the server side.
*/
export interface TeamDetailResponse {
team: TeamRecord;
- leader_agent: AgentRecord | null;
+ leader_agent: AgentView | null;
members: TeamMemberInfo[];
}
@@ -304,9 +309,19 @@ export interface CredentialSchemasResponse {
schemas: CredentialSchema[];
}
-export interface CredentialRecord extends RecordBase {
+export interface CredentialView extends RecordBase {
user_id: string;
+ /**
+ * Credential payload. When the current viewer is not the owner
+ * (shared credential), only `type` and `name` are populated —
+ * secret fields are stripped server-side.
+ */
data: Record<string, unknown>;
+ /**
+ * Whether the current viewer may PATCH/DELETE this credential.
+ * `false` for credentials shared with read-only permission.
+ */
+ editable: boolean;
}
export interface CreateCredentialRequest {
@@ -322,7 +337,7 @@ export interface UpdateCredentialRequest {
}
export interface CredentialListResponse {
- credentials: CredentialRecord[];
+ credentials: CredentialView[];
total: number;
}
@@ -517,10 +532,7 @@ export interface EmbeddingModelCard {
/**
* Knowledge base view as exposed by the API. Mirrors
- * :class:`agentscope.app._router._schema.KnowledgeBaseView`.
- *
- * Internal `user_id` / `collection_name` are stripped — the front-end
- * has no business introspecting either.
+ * :class:`agentscope.app._service.KnowledgeBaseView`.
*/
export interface KnowledgeBaseView {
id: string;
@@ -529,6 +541,12 @@ export interface KnowledgeBaseView {
embedding_model_config: EmbeddingModelConfig;
created_at: string;
updated_at: string;
+ /**
+ * Whether the current viewer may modify this knowledge base (edit
+ * metadata, add/delete documents). `false` for knowledge bases
+ * shared with read-only permission.
+ */
+ editable: boolean;
}
export interface ListKnowledgeBasesResponse {
@@ -653,7 +671,7 @@ export interface DimensionPolicy {
/** One credential and the embedding models it can serve, post-policy. */
export interface KbEmbeddingProvider {
- credential: CredentialRecord;
+ credential: CredentialView;
models: EmbeddingModelCard[];
}
diff --git a/examples/web_ui/frontend/src/components/dialog/EditAgentDialog.tsx b/examples/web_ui/frontend/src/components/dialog/EditAgentDialog.tsx
index 4400936b3..859e9c126 100644
--- a/examples/web_ui/frontend/src/components/dialog/EditAgentDialog.tsx
+++ b/examples/web_ui/frontend/src/components/dialog/EditAgentDialog.tsx
@@ -2,7 +2,7 @@ import { CircleAlert, Loader2, Save } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import type { AgentRecord, ContextConfig, InviteConfig, ReActConfig } from '@/api';
+import type { AgentView, ContextConfig, InviteConfig, ReActConfig } from '@/api';
import {
AgentFormFields,
defaultAgentFormValues,
@@ -27,7 +27,7 @@ import { formatApiErrorForAlert } from '@/lib/api-error';
interface Props {
open: boolean;
onOpenChange: (open: boolean) => void;
- agent: AgentRecord;
+ agent: AgentView;
onUpdated?: () => void;
}
diff --git a/examples/web_ui/frontend/src/components/dialog/EditCredentialDialog.tsx b/examples/web_ui/frontend/src/components/dialog/EditCredentialDialog.tsx
index 36f3e2702..ba0e47d11 100644
--- a/examples/web_ui/frontend/src/components/dialog/EditCredentialDialog.tsx
+++ b/examples/web_ui/frontend/src/components/dialog/EditCredentialDialog.tsx
@@ -2,7 +2,7 @@ import { CircleAlert, Loader2, Save } from 'lucide-react';
import { useState, useEffect } from 'react';
import { credentialApi } from '@/api';
-import type { CredentialRecord, CredentialSchema } from '@/api';
+import type { CredentialView, CredentialSchema } from '@/api';
import { SchemaForm, type SchemaFormValue } from '@/components/form/SchemaForm';
import { Button } from '@/components/ui/button';
import {
@@ -19,7 +19,7 @@ import { useTranslation } from '@/i18n/useI18n';
interface Props {
open: boolean;
onOpenChange: (open: boolean) => void;
- credential: CredentialRecord;
+ credential: CredentialView;
onUpdated?: () => void;
}
diff --git a/examples/web_ui/frontend/src/components/select/AgentSelect.tsx b/examples/web_ui/frontend/src/components/select/AgentSelect.tsx
new file mode 100644
index 000000000..2b7321f0a
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/select/AgentSelect.tsx
@@ -0,0 +1,109 @@
+import { Check, ChevronDown } from 'lucide-react';
+
+import type { AgentView } from '@/api';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { useTranslation } from '@/i18n/useI18n.ts';
+
+interface Props {
+ agents: AgentView[];
+ /** Currently selected agent id, or `null` when none is selected. */
+ value?: string | null;
+ onChange?: (agentId: string) => void;
+ /** Override the trigger label shown when no agent is selected. */
+ placeholder?: string;
+}
+
+/**
+ * Agent picker used in the chat sidebar. Rendered on top of the
+ * shadcn dropdown-menu primitives (same base as `LlmSelect`) so
+ * grouping and per-row content (icons, badges) is fully composable.
+ *
+ * Grouping rule: when every visible agent is editable (i.e. no
+ * cross-owner shares in play), the list is rendered flat. As soon
+ * as at least one entry is `editable === false`, the list splits
+ * into "Yours" and "Shared with you" groups so the read-only
+ * origin of the shared entries is unambiguous at a glance.
+ */
+export function AgentSelect({ agents, value, onChange, placeholder }: Props) {
+ const { t } = useTranslation();
+ const selected = agents.find((a) => a.id === value) ?? null;
+ const displayLabel = selected
+ ? selected.data.name
+ : (placeholder ?? t('chat.agent.selectPlaceholder'));
+
+ const hasShared = agents.some((a) => !a.editable);
+ const yours = agents.filter((a) => a.editable);
+ const shared = agents.filter((a) => !a.editable);
+
+ const renderItem = (agent: AgentView) => {
+ const isSelected = agent.id === value;
+ return (
+ <DropdownMenuItem key={agent.id} onSelect={() => onChange?.(agent.id)}>
+ <Check
+ className={`size-3.5 shrink-0 ${isSelected ? 'opacity-100' : 'opacity-0'}`}
+ />
+ <span className="min-w-0 flex-1 truncate">{agent.data.name}</span>
+ {!agent.editable && (
+ <Badge
+ variant="secondary"
+ className="text-[10px] px-1 py-0"
+ title={t('common.readOnlyTooltip')}
+ >
+ {t('common.readOnly')}
+ </Badge>
+ )}
+ </DropdownMenuItem>
+ );
+ };
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="outline"
+ size="sm"
+ className="flex-1 min-w-0 justify-between gap-1"
+ >
+ <span className="truncate">{displayLabel}</span>
+ <ChevronDown className="size-3.5 opacity-50" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="min-w-56 max-h-72 overflow-y-auto">
+ {agents.length === 0 ? (
+ <div className="px-2 py-3 text-center text-sm text-muted-foreground">
+ <p className="font-medium">{t('chat.agent.emptyTitle')}</p>
+ <p className="text-xs mt-1">{t('chat.agent.emptyDescription')}</p>
+ </div>
+ ) : hasShared ? (
+ <>
+ {yours.length > 0 && (
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{t('chat.agent.groupYours')}</DropdownMenuLabel>
+ {yours.map(renderItem)}
+ </DropdownMenuGroup>
+ )}
+ {yours.length > 0 && shared.length > 0 && <DropdownMenuSeparator />}
+ {shared.length > 0 && (
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{t('chat.agent.groupShared')}</DropdownMenuLabel>
+ {shared.map(renderItem)}
+ </DropdownMenuGroup>
+ )}
+ </>
+ ) : (
+ agents.map(renderItem)
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/examples/web_ui/frontend/src/components/team/TeamSidebar.tsx b/examples/web_ui/frontend/src/components/team/TeamSidebar.tsx
index bbbfdb8f5..eb6ee488e 100644
--- a/examples/web_ui/frontend/src/components/team/TeamSidebar.tsx
+++ b/examples/web_ui/frontend/src/components/team/TeamSidebar.tsx
@@ -1,7 +1,7 @@
import { Bot, Crown } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
-import type { TeamDetailResponse, TeamMemberInfo, AgentRecord } from '@/api';
+import type { TeamDetailResponse, TeamMemberInfo, AgentView } from '@/api';
import {
Sidebar,
SidebarContent,
@@ -70,7 +70,7 @@ export function TeamSidebar({ team, currentSessionId }: TeamSidebarProps) {
navigate(`/chat/${leaderAgentId}/${leaderSessionId}/${memberAgentId}`);
};
- const renderLeader = (leader: AgentRecord) => (
+ const renderLeader = (leader: AgentView) => (
<SidebarMenuItem>
<SidebarMenuButton isActive={currentSessionId === leaderSessionId} onClick={goToLeader}>
<Crown />
diff --git a/examples/web_ui/frontend/src/hooks/useAgents.ts b/examples/web_ui/frontend/src/hooks/useAgents.ts
index b690cf971..1c69340fb 100644
--- a/examples/web_ui/frontend/src/hooks/useAgents.ts
+++ b/examples/web_ui/frontend/src/hooks/useAgents.ts
@@ -1,14 +1,14 @@
import { useState, useEffect, useCallback } from 'react';
import { agentApi } from '../api';
-import type { AgentRecord, CreateAgentRequest, UpdateAgentRequest } from '../api';
+import type { AgentView, CreateAgentRequest, UpdateAgentRequest } from '../api';
/**
* Manages the full agent list with CRUD operations.
* Fetches on mount and automatically re-fetches after each mutation.
*/
export function useAgents() {
- const [agents, setAgents] = useState<AgentRecord[]>([]);
+ const [agents, setAgents] = useState<AgentView[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
diff --git a/examples/web_ui/frontend/src/hooks/useAvailableModels.ts b/examples/web_ui/frontend/src/hooks/useAvailableModels.ts
index f5cd535c2..cae10a095 100644
--- a/examples/web_ui/frontend/src/hooks/useAvailableModels.ts
+++ b/examples/web_ui/frontend/src/hooks/useAvailableModels.ts
@@ -1,10 +1,10 @@
import { useState, useEffect, useCallback } from 'react';
import { credentialApi, modelApi } from '@/api';
-import type { CredentialRecord, ModelCard } from '@/api';
+import type { CredentialView, ModelCard } from '@/api';
export interface CredentialWithModels {
- credential: CredentialRecord;
+ credential: CredentialView;
models: ModelCard[];
}
diff --git a/examples/web_ui/frontend/src/hooks/useAvailableTTSModels.ts b/examples/web_ui/frontend/src/hooks/useAvailableTTSModels.ts
index 2c5147ab1..9f1dca6ab 100644
--- a/examples/web_ui/frontend/src/hooks/useAvailableTTSModels.ts
+++ b/examples/web_ui/frontend/src/hooks/useAvailableTTSModels.ts
@@ -1,10 +1,10 @@
import { useState, useEffect, useCallback } from 'react';
import { credentialApi, ttsModelApi } from '@/api';
-import type { CredentialRecord, TTSModelCard } from '@/api';
+import type { CredentialView, TTSModelCard } from '@/api';
export interface CredentialWithTTSModels {
- credential: CredentialRecord;
+ credential: CredentialView;
models: TTSModelCard[];
}
diff --git a/examples/web_ui/frontend/src/hooks/useCredentials.ts b/examples/web_ui/frontend/src/hooks/useCredentials.ts
index 64609610a..29d1511a9 100644
--- a/examples/web_ui/frontend/src/hooks/useCredentials.ts
+++ b/examples/web_ui/frontend/src/hooks/useCredentials.ts
@@ -1,14 +1,14 @@
import { useState, useEffect, useCallback } from 'react';
import { credentialApi } from '../api';
-import type { CredentialRecord, CreateCredentialRequest, UpdateCredentialRequest } from '../api';
+import type { CredentialView, CreateCredentialRequest, UpdateCredentialRequest } from '../api';
/**
* Manages API key credentials with CRUD operations.
* Fetches on mount and automatically re-fetches after each mutation.
*/
export function useCredentials() {
- const [credentials, setCredentials] = useState<CredentialRecord[]>([]);
+ const [credentials, setCredentials] = useState<CredentialView[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
diff --git a/examples/web_ui/frontend/src/i18n/locales/en.json b/examples/web_ui/frontend/src/i18n/locales/en.json
index 547fd7304..0578bd164 100644
--- a/examples/web_ui/frontend/src/i18n/locales/en.json
+++ b/examples/web_ui/frontend/src/i18n/locales/en.json
@@ -23,6 +23,8 @@
"name": "Name",
"no": "No",
"noData": "No data",
+ "readOnly": "Read-only",
+ "readOnlyTooltip": "Shared with you as read-only; editing and deletion are disabled.",
"completed": "Completed",
"failed": "Failed",
"running": "Running",
@@ -107,7 +109,9 @@
"agent": {
"selectPlaceholder": "Select an agent",
"emptyTitle": "No agents",
- "emptyDescription": "Create an agent to get started."
+ "emptyDescription": "Create an agent to get started.",
+ "groupYours": "Yours",
+ "groupShared": "Shared with you"
},
"session": {
"label": "Session",
diff --git a/examples/web_ui/frontend/src/i18n/locales/zh.json b/examples/web_ui/frontend/src/i18n/locales/zh.json
index 3b24d1518..27e8c3922 100644
--- a/examples/web_ui/frontend/src/i18n/locales/zh.json
+++ b/examples/web_ui/frontend/src/i18n/locales/zh.json
@@ -23,6 +23,8 @@
"name": "名称",
"no": "否",
"noData": "暂无数据",
+ "readOnly": "只读",
+ "readOnlyTooltip": "该资源以只读方式共享给你,编辑和删除均被禁用。",
"completed": "已完成",
"failed": "已失败",
"running": "运行中",
@@ -107,7 +109,9 @@
"agent": {
"selectPlaceholder": "选择 Agent",
"emptyTitle": "暂无 Agent",
- "emptyDescription": "创建一个 Agent 开始使用。"
+ "emptyDescription": "创建一个 Agent 开始使用。",
+ "groupYours": "我的",
+ "groupShared": "共享给我"
},
"session": {
"label": "会话",
diff --git a/examples/web_ui/frontend/src/pages/chat/index.tsx b/examples/web_ui/frontend/src/pages/chat/index.tsx
index 4805c1bec..c1c856635 100644
--- a/examples/web_ui/frontend/src/pages/chat/index.tsx
+++ b/examples/web_ui/frontend/src/pages/chat/index.tsx
@@ -17,6 +17,7 @@ import { AgentDialog } from '@/components/dialog/AgentDialog';
import { DeleteDialog } from '@/components/dialog/DeleteDialog';
import { EditAgentDialog } from '@/components/dialog/EditAgentDialog';
import { RenameSessionDialog } from '@/components/dialog/RenameSessionDialog';
+import { AgentSelect } from '@/components/select/AgentSelect';
import { TeamSidebar } from '@/components/team/TeamSidebar';
import { ChatTourController } from '@/components/tour/ChatTourController';
import { Button } from '@/components/ui/button';
@@ -34,13 +35,6 @@ import {
EmptyContent,
EmptyMedia,
} from '@/components/ui/empty';
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from '@/components/ui/select';
import {
Sidebar,
SidebarContent,
@@ -215,38 +209,20 @@ const ChatPageInner = () => {
{localStorage.getItem('server_url')}
</span>
<div className="flex flex-row gap-x-2 items-center">
- <Select
- value={urlAgentId ?? ''}
- onValueChange={(id) => navigate(`/chat/${id}`)}
- >
- <SelectTrigger className="w-full" size="sm">
- <SelectValue placeholder={t('chat.agent.selectPlaceholder')} />
- </SelectTrigger>
- <SelectContent position="popper">
- {agents.length === 0 ? (
- <Empty className="border-none py-4">
- <EmptyHeader>
- <EmptyTitle>
- {t('chat.agent.emptyTitle')}
- </EmptyTitle>
- <EmptyDescription>
- {t('chat.agent.emptyDescription')}
- </EmptyDescription>
- </EmptyHeader>
- </Empty>
- ) : (
- agents.map((agent) => (
- <SelectItem key={agent.id} value={agent.id}>
- {agent.data.name}
- </SelectItem>
- ))
- )}
- </SelectContent>
- </Select>
+ <AgentSelect
+ agents={agents}
+ value={urlAgentId ?? null}
+ onChange={(id) => navigate(`/chat/${id}`)}
+ />
<Button
size="icon"
variant="ghost"
- disabled={!urlAgentId}
+ disabled={!urlAgentId || !selectedAgent?.editable}
+ tooltip={
+ selectedAgent && !selectedAgent.editable
+ ? t('common.readOnlyTooltip')
+ : undefined
+ }
onClick={() => setEditOpen(true)}
>
<Settings2 />
@@ -254,7 +230,12 @@ const ChatPageInner = () => {
<Button
size="icon"
variant="ghost"
- disabled={!urlAgentId}
+ disabled={!urlAgentId || !selectedAgent?.editable}
+ tooltip={
+ selectedAgent && !selectedAgent.editable
+ ? t('common.readOnlyTooltip')
+ : undefined
+ }
onClick={() => setDeleteOpen(true)}
>
<Trash2 className="text-destructive" />
diff --git a/examples/web_ui/frontend/src/pages/credential/index.tsx b/examples/web_ui/frontend/src/pages/credential/index.tsx
index 0301ccb25..96c66e77c 100644
--- a/examples/web_ui/frontend/src/pages/credential/index.tsx
+++ b/examples/web_ui/frontend/src/pages/credential/index.tsx
@@ -2,7 +2,7 @@ import { Eye, EyeOff, Plus, Pencil, Trash2 } from 'lucide-react';
import { useState, useEffect, useCallback } from 'react';
import { credentialApi, modelApi, ttsModelApi } from '@/api';
-import type { CredentialRecord, CredentialSchema, ModelCard, TTSModelCard } from '@/api';
+import type { CredentialView, CredentialSchema, ModelCard, TTSModelCard } from '@/api';
import { InputTypeBadges } from '@/components/badge/InputTypeBadges';
import { CreateCredentialDialog } from '@/components/dialog/CreateCredentialDialog';
import { DeleteDialog } from '@/components/dialog/DeleteDialog';
@@ -152,7 +152,7 @@ function TTSModelCardItem({ model }: { model: TTSModelCard }) {
// ─── Detail panel ─────────────────────────────────────────────────────────────
interface DetailPanelProps {
- credential: CredentialRecord;
+ credential: CredentialView;
schema: CredentialSchema | null;
onEdit: () => void;
onDelete: () => void;
@@ -207,15 +207,32 @@ function DetailPanel({ credential, schema, onEdit, onDelete }: DetailPanelProps)
<div className="flex flex-col gap-y-6 p-6 overflow-y-auto h-full">
{/* Header */}
<div className="flex items-start justify-between gap-x-4">
- <div>
+ <div className="flex flex-col gap-y-1">
<h2 className="text-lg font-semibold">{name}</h2>
<p className="text-muted-foreground text-sm">{type}</p>
+ {!credential.editable && (
+ <Badge variant="secondary" title={t('common.readOnlyTooltip')}>
+ {t('common.readOnly')}
+ </Badge>
+ )}
</div>
<div className="flex items-center gap-x-2 shrink-0">
- <Button size="icon-sm" variant="outline" onClick={onEdit}>
+ <Button
+ size="icon-sm"
+ variant="outline"
+ onClick={onEdit}
+ disabled={!credential.editable}
+ tooltip={credential.editable ? undefined : t('common.readOnlyTooltip')}
+ >
<Pencil />
</Button>
- <Button size="icon-sm" variant="destructive" onClick={onDelete}>
+ <Button
+ size="icon-sm"
+ variant="destructive"
+ onClick={onDelete}
+ disabled={!credential.editable}
+ tooltip={credential.editable ? undefined : t('common.readOnlyTooltip')}
+ >
<Trash2 />
</Button>
</div>
@@ -333,7 +350,7 @@ export const CredentialPage = () => {
: null;
// Group credentials by type, then list all schema types (even empty ones)
- const groupedByType: Array<{ type: string; title: string; records: CredentialRecord[] }> =
+ const groupedByType: Array<{ type: string; title: string; records: CredentialView[] }> =
schemas.map((s) => {
const type = s.properties.type?.const as string;
return {
@@ -411,6 +428,17 @@ export const CredentialPage = () => {
<span className="min-w-0 flex-1 truncate">
{name}
</span>
+ {!rec.editable && (
+ <Badge
+ variant="secondary"
+ className="text-[10px] px-1 py-0"
+ title={t(
+ 'common.readOnlyTooltip',
+ )}
+ >
+ {t('common.readOnly')}
+ </Badge>
+ )}
</SidebarMenuButton>
</SidebarMenuItem>
);
diff --git a/examples/web_ui/frontend/src/pages/knowledge/index.tsx b/examples/web_ui/frontend/src/pages/knowledge/index.tsx
index f1485c44c..4e6734fa1 100644
--- a/examples/web_ui/frontend/src/pages/knowledge/index.tsx
+++ b/examples/web_ui/frontend/src/pages/knowledge/index.tsx
@@ -10,6 +10,7 @@ import { DeleteDialog } from '@/components/dialog/DeleteDialog.tsx';
import { EditKnowledgeBaseDialog } from '@/components/dialog/EditKnowledgeBaseDialog.tsx';
import { KnowledgeSearchDrawer } from '@/components/drawer/KnowledgeSearchDrawer.tsx';
import { KnowledgeDocumentsPanel } from '@/components/knowledge/KnowledgeDocumentsPanel.tsx';
+import { Badge } from '@/components/ui/badge.tsx';
import { Button } from '@/components/ui/button.tsx';
import {
DropdownMenu,
@@ -68,7 +69,14 @@ function DetailPanel({ knowledgeBase, onTest }: DetailPanelProps) {
{/* Header */}
<div className="flex items-start justify-between gap-x-4">
<div className="flex flex-col gap-y-1 min-w-0">
- <h2 className="text-lg font-semibold truncate">{knowledgeBase.name}</h2>
+ <div className="flex items-center gap-x-2">
+ <h2 className="text-lg font-semibold truncate">{knowledgeBase.name}</h2>
+ {!knowledgeBase.editable && (
+ <Badge variant="secondary" title={t('common.readOnlyTooltip')}>
+ {t('common.readOnly')}
+ </Badge>
+ )}
+ </div>
{knowledgeBase.description ? (
<p className="text-sm text-muted-foreground">{knowledgeBase.description}</p>
) : null}
@@ -178,32 +186,47 @@ export const KnowledgePage = () => {
}}
>
<span className="truncate">{kb.name}</span>
- </SidebarMenuButton>
- <SidebarMenuAction showOnHover>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Ellipsis />
- </DropdownMenuTrigger>
- <DropdownMenuContent
- side="right"
- align="start"
+ {!kb.editable && (
+ <Badge
+ variant="secondary"
+ className="text-[10px] px-1 py-0"
+ title={t('common.readOnlyTooltip')}
>
- <DropdownMenuItem
- onClick={() => setEditTarget(kb)}
- >
- <Pencil />
- {t('common.edit')}
- </DropdownMenuItem>
- <DropdownMenuItem
- variant="destructive"
- onClick={() => setDeleteTarget(kb)}
+ {t('common.readOnly')}
+ </Badge>
+ )}
+ </SidebarMenuButton>
+ {kb.editable && (
+ <SidebarMenuAction showOnHover>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Ellipsis />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ side="right"
+ align="start"
>
- <Trash2 />
- {t('common.delete')}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </SidebarMenuAction>
+ <DropdownMenuItem
+ onClick={() =>
+ setEditTarget(kb)
+ }
+ >
+ <Pencil />
+ {t('common.edit')}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() =>
+ setDeleteTarget(kb)
+ }
+ >
+ <Trash2 />
+ {t('common.delete')}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </SidebarMenuAction>
+ )}
</SidebarMenuItem>
);
})}
diff --git a/src/agentscope/app/_app.py b/src/agentscope/app/_app.py
index ad2dfc8d0..255b2c984 100644
--- a/src/agentscope/app/_app.py
+++ b/src/agentscope/app/_app.py
@@ -3,6 +3,7 @@
from typing import Type, TYPE_CHECKING, Any
from ._lifespan import lifespan
+from .access import DenyAllResourceAccessPolicy, ResourceAccessPolicyBase
from .rag.blob_store import BlobStoreBase, LocalBlobStore
from .rag.knowledge_base_manager import KnowledgeBaseManagerBase
from .workspace_manager import WorkspaceManagerBase
@@ -55,6 +56,7 @@ def create_app(
extra_agent_tools: AgentToolFactory | None = None,
custom_subagent_templates: list[SubAgentTemplate] | None = None,
custom_agent_cls: Type[Agent] | None = None,
+ resource_access_policy: ResourceAccessPolicyBase | None = None,
title: str = "AgentScope",
version: str = __version__,
) -> FastAPI:
@@ -178,6 +180,12 @@ def create_app(
A custom :class:`~agentscope.agent.Agent` subclass to use
when assembling agents. When ``None`` (default), the
built-in :class:`~agentscope.agent.Agent` is used.
+ resource_access_policy (`ResourceAccessPolicyBase | None`, optional):
+ Policy deciding whether a viewer may access
+ credentials / agents / knowledge bases owned by another
+ user. When ``None`` (default), a
+ :class:`DenyAllResourceAccessPolicy` is installed which
+ preserves the historical owner-isolated behavior.
title (`str`, defaults to ``"AgentScope"``):
OpenAPI title shown in the docs UI.
version (`str`, defaults to the package version):
@@ -202,6 +210,9 @@ def create_app(
app.state.extra_agent_middlewares = extra_agent_middlewares
app.state.extra_agent_tools = extra_agent_tools
app.state.custom_agent_cls = custom_agent_cls
+ app.state.resource_access_policy = (
+ resource_access_policy or DenyAllResourceAccessPolicy()
+ )
# Parser / chunker / blob-store defaults only make sense when the
# KB feature is actually enabled. When ``knowledge_base_manager`` is
diff --git a/src/agentscope/app/_lifespan.py b/src/agentscope/app/_lifespan.py
index 293871b24..5e4c14819 100644
--- a/src/agentscope/app/_lifespan.py
+++ b/src/agentscope/app/_lifespan.py
@@ -18,6 +18,7 @@ from ._service import (
IndexTaskConsumer,
IndexWorker,
KnowledgeBaseService,
+ ResourceAccessService,
SessionService,
)
@@ -46,6 +47,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
knowledge_base_manager = app.state.knowledge_base_manager
blob_store = app.state.blob_store
enable_index_worker = app.state.enable_index_worker
+ resource_access_policy = app.state.resource_access_policy
async with AsyncExitStack() as stack:
await stack.enter_async_context(storage)
@@ -81,12 +83,23 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
)
app.state.scheduler_manager = scheduler
+ # Resource access service — combines owner-scoped storage reads
+ # with the injected policy so both routers and runtime services
+ # go through a single choke point when resolving credentials /
+ # agents / knowledge bases.
+ resource_access_service = ResourceAccessService(
+ storage=storage,
+ policy=resource_access_policy,
+ )
+ app.state.resource_access_service = resource_access_service
+
chat_service = ChatService(
storage=storage,
workspace_manager=workspace_manager,
scheduler_manager=scheduler,
background_task_manager=bg_manager,
message_bus=message_bus,
+ resource_access_service=resource_access_service,
knowledge_base_manager=knowledge_base_manager,
extra_agent_middlewares=app.state.extra_agent_middlewares,
extra_agent_tools=app.state.extra_agent_tools,
@@ -154,6 +167,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
knowledge_base_manager=knowledge_base_manager,
blob_store=blob_store,
message_bus=message_bus,
+ resource_access_service=resource_access_service,
)
app.state.knowledge_base_service = knowledge_base_service
diff --git a/src/agentscope/app/_router/_agent.py b/src/agentscope/app/_router/_agent.py
index a3574199f..e7b622abc 100644
--- a/src/agentscope/app/_router/_agent.py
+++ b/src/agentscope/app/_router/_agent.py
@@ -7,7 +7,13 @@ from pydantic import ValidationError
from ...agent import ContextConfig, ReActConfig
from ..._utils._common import _flatten_json_schema
-from ..deps import get_current_user_id, get_session_service, get_storage
+from ..access import ResourceKind
+from ..deps import (
+ get_current_user_id,
+ get_resource_access_service,
+ get_session_service,
+ get_storage,
+)
from ._schema import (
AgentSchemaResponse,
AgentSchemaV2Response,
@@ -16,7 +22,7 @@ from ._schema import (
CreateAgentResponse,
UpdateAgentRequest,
)
-from .._service import SessionService
+from .._service import AgentView, ResourceAccessService, SessionService
from ..storage import StorageBase, AgentData, AgentRecord
agent_router = APIRouter(
@@ -133,22 +139,27 @@ async def get_agent_schema_v2() -> AgentSchemaV2Response:
)
async def list_agents(
user_id: str = Depends(get_current_user_id),
- storage: StorageBase = Depends(get_storage),
+ access: ResourceAccessService = Depends(get_resource_access_service),
) -> ListAgentsResponse:
- """Return all agent records belonging to the authenticated user.
+ """Return all agent records visible to the authenticated user.
+
+ Includes the caller's own ``source == "user"`` agents plus any agents
+ shared to them through :class:`ResourceAccessPolicyBase`. Each entry
+ carries an ``editable`` flag indicating whether the caller may
+ PATCH/DELETE it.
Args:
user_id (`str`):
Injected authenticated user ID.
- storage (`StorageBase`):
- Injected storage backend.
+ access (`ResourceAccessService`):
+ Injected resource access service.
Returns:
`ListAgentsResponse`:
- All agent records and their total count.
+ All visible agent records paired with per-viewer editability.
"""
- agents = await storage.list_agents(user_id)
- return ListAgentsResponse(agents=agents, total=len(agents))
+ entries = await access.list_resource(user_id, ResourceKind.AGENT)
+ return ListAgentsResponse(agents=entries, total=len(entries))
@agent_router.post(
@@ -204,7 +215,7 @@ async def create_agent(
@agent_router.patch(
"/{agent_id}",
- response_model=AgentRecord,
+ response_model=AgentView,
summary="Update an agent",
)
async def update_agent(
@@ -212,7 +223,8 @@ async def update_agent(
body: UpdateAgentRequest,
user_id: str = Depends(get_current_user_id),
storage: StorageBase = Depends(get_storage),
-) -> AgentRecord:
+ access: ResourceAccessService = Depends(get_resource_access_service),
+) -> AgentView:
"""Partially update an existing agent configuration.
Only the fields present in the request body are updated; all other fields
@@ -223,21 +235,20 @@ async def update_agent(
body (`UpdateAgentRequest`): Fields to update.
user_id (`str`): Injected authenticated user ID.
storage (`StorageBase`): Injected storage backend.
+ access (`ResourceAccessService`): Injected access service.
Returns:
- `AgentRecord`: The full agent record after the update.
+ `AgentView`: The full agent record after the update.
Raises:
- `HTTPException`: 404 if the agent does not exist or does not belong
- to the authenticated user.
+ `HTTPException`: 404 if the agent is not visible to the caller;
+ 403 if visible but only readable.
"""
- agents = await storage.list_agents(user_id)
- existing = next((a for a in agents if a.id == agent_id), None)
- if existing is None:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Agent '{agent_id}' not found.",
- )
+ owner_id, existing = await access.resolve_for_edit(
+ user_id,
+ ResourceKind.AGENT,
+ agent_id,
+ )
updates = body.model_dump(exclude_none=True)
# ``model_copy(update=...)`` skips validators; re-run
@@ -257,8 +268,12 @@ async def update_agent(
updated_agent = existing.model_copy(
update={"data": updated_data, "updated_at": datetime.now()},
)
- await storage.upsert_agent(user_id, updated_agent)
- return updated_agent
+ await storage.upsert_agent(owner_id, updated_agent)
+ # Only reachable via ``resolve_for_edit``, so the caller has edit
+ # permission by construction.
+ return AgentView.model_validate(
+ {**updated_agent.model_dump(), "editable": True},
+ )
@agent_router.delete(
@@ -270,6 +285,7 @@ async def delete_agent(
agent_id: str,
user_id: str = Depends(get_current_user_id),
session_service: SessionService = Depends(get_session_service),
+ access: ResourceAccessService = Depends(get_resource_access_service),
) -> None:
"""Permanently delete an agent configuration.
@@ -281,12 +297,20 @@ async def delete_agent(
agent_id (`str`): The agent to delete.
user_id (`str`): Injected authenticated user ID.
session_service (`SessionService`): Injected session service.
+ access (`ResourceAccessService`): Injected access service — used
+ to resolve the owning user and enforce the edit permission
+ when a shared editor deletes the agent.
Raises:
- `HTTPException`: 404 if the agent does not exist or does not belong
- to the authenticated user.
+ `HTTPException`: 404 if the agent is not visible to the caller;
+ 403 if visible but only readable.
"""
- deleted = await session_service.delete_agent(user_id, agent_id)
+ owner_id, _ = await access.resolve_for_edit(
+ user_id,
+ ResourceKind.AGENT,
+ agent_id,
+ )
+ deleted = await session_service.delete_agent(owner_id, agent_id)
if not deleted:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
diff --git a/src/agentscope/app/_router/_credential.py b/src/agentscope/app/_router/_credential.py
index 395af678c..598d735f9 100644
--- a/src/agentscope/app/_router/_credential.py
+++ b/src/agentscope/app/_router/_credential.py
@@ -1,8 +1,13 @@
# -*- coding: utf-8 -*-
"""Credential router — CRUD endpoints for API key credentials."""
-from fastapi import APIRouter, Depends, HTTPException, status
+from fastapi import APIRouter, Depends, status
-from ..deps import get_current_user_id, get_storage
+from ..access import ResourceKind
+from ..deps import (
+ get_current_user_id,
+ get_resource_access_service,
+ get_storage,
+)
from ._schema import (
CreateCredentialRequest,
CreateCredentialResponse,
@@ -10,7 +15,8 @@ from ._schema import (
ListCredentialSchemasResponse,
UpdateCredentialRequest,
)
-from ..storage import StorageBase, CredentialRecord
+from .._service import CredentialView, ResourceAccessService
+from ..storage import StorageBase
from ...credential import CredentialFactory
credential_router = APIRouter(
@@ -43,24 +49,31 @@ async def list_credential_schemas() -> ListCredentialSchemasResponse:
)
async def list_credentials(
user_id: str = Depends(get_current_user_id),
- storage: StorageBase = Depends(get_storage),
+ access: ResourceAccessService = Depends(get_resource_access_service),
) -> ListCredentialsResponse:
- """Return all credential records belonging to the authenticated user.
+ """Return all credential records visible to the authenticated user.
+
+ Includes the caller's own credentials plus any credentials shared to
+ them through :class:`ResourceAccessPolicyBase`. Shared entries have
+ their secret ``data`` payload masked — only the discriminator and
+ display name survive in the response — while runtime resolution
+ (e.g. the chat model service) still sees the full payload.
Args:
user_id (`str`):
Injected authenticated user ID.
- storage (`StorageBase`):
- Injected storage backend.
+ access (`ResourceAccessService`):
+ Injected resource access service.
Returns:
`ListCredentialsResponse`:
- All credential records and their total count.
+ All visible credentials paired with editability and
+ (for shared entries) redacted data.
"""
- credentials = await storage.list_credentials(user_id)
+ entries = await access.list_resource(user_id, ResourceKind.CREDENTIAL)
return ListCredentialsResponse(
- credentials=credentials,
- total=len(credentials),
+ credentials=entries,
+ total=len(entries),
)
@@ -94,7 +107,7 @@ async def create_credential(
@credential_router.patch(
"/{credential_id}",
- response_model=CredentialRecord,
+ response_model=CredentialView,
summary="Update a credential",
)
async def update_credential(
@@ -102,7 +115,8 @@ async def update_credential(
body: UpdateCredentialRequest,
user_id: str = Depends(get_current_user_id),
storage: StorageBase = Depends(get_storage),
-) -> CredentialRecord:
+ access: ResourceAccessService = Depends(get_resource_access_service),
+) -> CredentialView:
"""Replace the payload of an existing credential.
Args:
@@ -110,29 +124,42 @@ async def update_credential(
body (`UpdateCredentialRequest`): New credential payload.
user_id (`str`): Injected authenticated user ID.
storage (`StorageBase`): Injected storage backend.
+ access (`ResourceAccessService`): Injected access service — used
+ to resolve the owning user and enforce the edit permission
+ when a shared editor updates the credential.
Returns:
- `CredentialRecord`: The updated credential record.
+ `CredentialView`: The updated credential record.
Raises:
- `HTTPException`: 404 if the credential does not exist or does not
- belong to the authenticated user.
+ `HTTPException`: 404 if the credential is not visible to the
+ caller; 403 if visible but only readable.
"""
- credentials = await storage.list_credentials(user_id)
- existing = next((c for c in credentials if c.id == credential_id), None)
- if existing is None:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Credential '{credential_id}' not found.",
- )
+ owner_id, _ = await access.resolve_for_edit(
+ user_id,
+ ResourceKind.CREDENTIAL,
+ credential_id,
+ )
credential = CredentialFactory.from_dict(body.data)
credential.id = credential_id
- await storage.upsert_credential(user_id, credential)
- # Re-fetch to return the persisted record with updated timestamps.
- credentials = await storage.list_credentials(user_id)
- updated = next(c for c in credentials if c.id == credential_id)
- return updated
+ await storage.upsert_credential(owner_id, credential)
+ # ``resolve_for_edit`` proved the record existed under ``owner_id``
+ # and the upsert above just wrote back to the same key, so the read
+ # is a value refresh, not an existence check. If it still comes back
+ # empty (e.g. a concurrent delete), surface an explicit server error
+ # rather than relying on ``assert`` (which ``-O`` strips).
+ updated = await storage.get_credential(owner_id, credential_id)
+ if updated is None:
+ raise RuntimeError(
+ f"Credential {credential_id!r} for owner {owner_id!r} "
+ "disappeared immediately after a successful upsert.",
+ )
+ # Only reachable via ``resolve_for_edit``, so the caller has edit
+ # permission by construction.
+ return CredentialView.model_validate(
+ {**updated.model_dump(), "editable": True},
+ )
@credential_router.delete(
@@ -144,6 +171,7 @@ async def delete_credential(
credential_id: str,
user_id: str = Depends(get_current_user_id),
storage: StorageBase = Depends(get_storage),
+ access: ResourceAccessService = Depends(get_resource_access_service),
) -> None:
"""Permanently delete a credential.
@@ -151,14 +179,17 @@ async def delete_credential(
credential_id (`str`): The credential to delete.
user_id (`str`): Injected authenticated user ID.
storage (`StorageBase`): Injected storage backend.
+ access (`ResourceAccessService`): Injected access service — used
+ to resolve the owning user and enforce the edit permission
+ when a shared editor deletes the credential.
Raises:
- `HTTPException`: 404 if the credential does not exist or does not
- belong to the authenticated user.
+ `HTTPException`: 404 if the credential is not visible to the
+ caller; 403 if visible but only readable.
"""
- deleted = await storage.delete_credential(user_id, credential_id)
- if not deleted:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Credential '{credential_id}' not found.",
- )
+ owner_id, _ = await access.resolve_for_edit(
+ user_id,
+ ResourceKind.CREDENTIAL,
+ credential_id,
+ )
+ await storage.delete_credential(owner_id, credential_id)
diff --git a/src/agentscope/app/_router/_knowledge_base.py b/src/agentscope/app/_router/_knowledge_base.py
index 68b6dc8a3..901acc4eb 100644
--- a/src/agentscope/app/_router/_knowledge_base.py
+++ b/src/agentscope/app/_router/_knowledge_base.py
@@ -18,19 +18,19 @@ from fastapi import (
status,
)
+from ..access import ResourceKind
from ..deps import (
get_current_user_id,
get_knowledge_base_manager,
get_knowledge_base_service,
get_knowledge_parsers,
- get_storage,
+ get_resource_access_service,
)
from ._schema import (
CreateKnowledgeBaseRequest,
CreateKnowledgeBaseResponse,
KbEmbeddingProvider,
KbMiddlewareParametersSchemaResponse,
- KnowledgeBaseView,
KnowledgeDocumentView,
ListKbEmbeddingModelsResponse,
ListKnowledgeBasesResponse,
@@ -44,8 +44,11 @@ from ._schema import (
)
from ...credential import CredentialFactory
from ..rag.knowledge_base_manager import KnowledgeBaseManagerBase
-from ..storage import StorageBase
-from .._service import KnowledgeBaseService
+from .._service import (
+ KnowledgeBaseService,
+ KnowledgeBaseView,
+ ResourceAccessService,
+)
from ...middleware import RAGMiddleware
from ...rag import ParserBase
@@ -64,26 +67,29 @@ knowledge_base_router = APIRouter(
)
async def list_kb_embedding_models(
user_id: str = Depends(get_current_user_id),
- storage: "StorageBase" = Depends(get_storage),
+ access: "ResourceAccessService" = Depends(get_resource_access_service),
manager: "KnowledgeBaseManagerBase" = Depends(
get_knowledge_base_manager,
),
) -> ListKbEmbeddingModelsResponse:
"""List embedding models the user can pick at KB-creation time.
- Walks the caller's credentials, looks up each provider's
- embedding model class, gathers its model cards, and projects
- each card through the manager's :class:`DimensionPolicy`.
- Incompatible cards are dropped; matryoshka cards under a
- ``FIXED`` / ``LOCKED_BY_EXISTING`` policy are narrowed to the
- locked dimension. Providers that end up with zero compatible
- models are omitted from the response entirely.
+ Walks every credential visible to the caller (own + shared via the
+ resource access policy), looks up each provider's embedding model
+ class, gathers its model cards, and projects each card through the
+ manager's :class:`DimensionPolicy`. Incompatible cards are
+ dropped; matryoshka cards under a ``FIXED`` /
+ ``LOCKED_BY_EXISTING`` policy are narrowed to the locked
+ dimension. Providers that end up with zero compatible models are
+ omitted from the response entirely.
Args:
user_id (`str`):
Injected authenticated user ID.
- storage (`StorageBase`):
- Injected storage backend used to enumerate credentials.
+ access (`ResourceAccessService`):
+ Injected resource access service; enumerates visible
+ credentials (own + shared) so KB creation works against
+ shared credentials too.
manager (`KnowledgeBaseManagerBase`):
Injected knowledge base manager.
@@ -93,7 +99,7 @@ async def list_kb_embedding_models(
embedding model, plus the policy used for filtering.
"""
policy = await manager.get_dimension_policy()
- credentials = await storage.list_credentials(user_id)
+ credentials = await access.list_resource(user_id, ResourceKind.CREDENTIAL)
providers: list[KbEmbeddingProvider] = []
for credential in credentials:
@@ -251,33 +257,31 @@ async def create_knowledge_base(
)
async def list_knowledge_bases(
user_id: str = Depends(get_current_user_id),
- service: "KnowledgeBaseService" = Depends(get_knowledge_base_service),
+ access: "ResourceAccessService" = Depends(get_resource_access_service),
) -> ListKnowledgeBasesResponse:
- """Return all knowledge bases owned by the authenticated user.
+ """Return all knowledge bases visible to the authenticated user.
+
+ Includes the caller's own knowledge bases plus any shared to them
+ through :class:`ResourceAccessPolicyBase`. Each entry carries an
+ ``editable`` flag: ``read`` grants search + attach; ``edit`` also
+ grants document add/delete and metadata update.
Args:
user_id (`str`):
Injected authenticated user ID.
- service (`KnowledgeBaseService`):
- Injected knowledge base service.
+ access (`ResourceAccessService`):
+ Injected resource access service.
Returns:
`ListKnowledgeBasesResponse`:
- The user's knowledge bases.
+ All visible knowledge bases paired with per-viewer
+ editability.
"""
- records = await service.list_knowledge_bases(user_id)
- views = [
- KnowledgeBaseView(
- id=record.id,
- name=record.name,
- description=record.description,
- embedding_model_config=record.embedding_model_config,
- created_at=record.created_at,
- updated_at=record.updated_at,
- )
- for record in records
- ]
- return ListKnowledgeBasesResponse(knowledge_bases=views, total=len(views))
+ entries = await access.list_resource(user_id, ResourceKind.KNOWLEDGE_BASE)
+ return ListKnowledgeBasesResponse(
+ knowledge_bases=entries,
+ total=len(entries),
+ )
@knowledge_base_router.patch(
@@ -317,13 +321,10 @@ async def update_knowledge_base(
name=body.name,
description=body.description,
)
- return KnowledgeBaseView(
- id=record.id,
- name=record.name,
- description=record.description,
- embedding_model_config=record.embedding_model_config,
- created_at=record.created_at,
- updated_at=record.updated_at,
+ # Only reachable via ``_require_edit`` inside the service, so the
+ # caller definitionally has edit permission.
+ return KnowledgeBaseView.model_validate(
+ {**record.model_dump(), "editable": True},
)
diff --git a/src/agentscope/app/_router/_schedule.py b/src/agentscope/app/_router/_schedule.py
index dac15247c..aab4a8123 100644
--- a/src/agentscope/app/_router/_schedule.py
+++ b/src/agentscope/app/_router/_schedule.py
@@ -4,9 +4,11 @@ from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException, status
+from ..access import ResourceKind
from .._manager import SchedulerManager
from ..deps import (
get_current_user_id,
+ get_resource_access_service,
get_scheduler_manager,
get_session_service,
get_storage,
@@ -18,7 +20,7 @@ from ._schema import (
ScheduleSessionsResponse,
UpdateScheduleRequest,
)
-from .._service import SessionService
+from .._service import ResourceAccessService, SessionService
from ..storage import (
StorageBase,
ScheduleData,
@@ -66,14 +68,20 @@ async def create_schedule(
body: CreateScheduleRequest,
user_id: str = Depends(get_current_user_id),
storage: StorageBase = Depends(get_storage),
+ access: ResourceAccessService = Depends(get_resource_access_service),
scheduler: SchedulerManager = Depends(get_scheduler_manager),
) -> CreateScheduleResponse:
"""Create a new schedule and register it with the scheduler.
+ The referenced agent may be either the viewer's own or one shared
+ to them through :class:`ResourceAccessPolicyBase`; the schedule
+ record itself is always owned by the caller.
+
Args:
body (`CreateScheduleRequest`): Schedule configuration.
user_id (`str`): Authenticated user ID.
storage (`StorageBase`): Storage instance.
+ access (`ResourceAccessService`): Access service.
scheduler (`SchedulerManager`): Scheduler manager.
Returns:
@@ -81,14 +89,20 @@ async def create_schedule(
The ID of the newly created schedule.
Raises:
- `HTTPException`: 404 if the specified agent does not exist.
+ `HTTPException`: 404 if the specified agent or the credential
+ referenced by ``chat_model_config`` is not visible to the
+ caller.
"""
- agent = await storage.get_agent(user_id, body.agent_id)
- if agent is None or agent.user_id != user_id:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Agent '{body.agent_id}' not found.",
- )
+ # Visibility checks — raise 404 when neither owned nor shared. The
+ # schedule fires under the owner's user_id, so re-validating the
+ # credential here surfaces the error at creation time rather than
+ # silently at the first (possibly much later) scheduled run.
+ await access.resolve_agent(user_id, body.agent_id)
+ await access.get_resource(
+ user_id,
+ ResourceKind.CREDENTIAL,
+ body.chat_model_config.credential_id,
+ )
record = ScheduleRecord(
user_id=user_id,
diff --git a/src/agentscope/app/_router/_schema/__init__.py b/src/agentscope/app/_router/_schema/__init__.py
index 340e57ab8..8b08faa13 100644
--- a/src/agentscope/app/_router/_schema/__init__.py
+++ b/src/agentscope/app/_router/_schema/__init__.py
@@ -31,7 +31,6 @@ from ._knowledge_base import (
CreateKnowledgeBaseResponse,
KbEmbeddingProvider,
KbMiddlewareParametersSchemaResponse,
- KnowledgeBaseView,
KnowledgeDocumentView,
ListKbEmbeddingModelsResponse,
ListKnowledgeBasesResponse,
@@ -80,7 +79,6 @@ __all__ = [
"CreateKnowledgeBaseResponse",
"KbEmbeddingProvider",
"KbMiddlewareParametersSchemaResponse",
- "KnowledgeBaseView",
"KnowledgeDocumentView",
"ListKbEmbeddingModelsResponse",
"ListKnowledgeBasesResponse",
diff --git a/src/agentscope/app/_router/_schema/_agent.py b/src/agentscope/app/_router/_schema/_agent.py
index 1949d6364..750db6938 100644
--- a/src/agentscope/app/_router/_schema/_agent.py
+++ b/src/agentscope/app/_router/_schema/_agent.py
@@ -5,7 +5,8 @@ import warnings
from pydantic import BaseModel, Field
from ....agent import ContextConfig, ReActConfig
-from ...storage import AgentRecord, InviteConfig
+from ...storage import InviteConfig
+from ..._service import AgentView
class CreateAgentRequest(BaseModel):
@@ -72,7 +73,7 @@ class UpdateAgentRequest(BaseModel):
class ListAgentsResponse(BaseModel):
"""Response body for listing agents."""
- agents: list[AgentRecord] = Field(description="Agent records.")
+ agents: list[AgentView] = Field(description="Agent records.")
total: int = Field(description="Total number of agents.")
diff --git a/src/agentscope/app/_router/_schema/_credential.py b/src/agentscope/app/_router/_schema/_credential.py
index 249bbd3b3..445260a27 100644
--- a/src/agentscope/app/_router/_schema/_credential.py
+++ b/src/agentscope/app/_router/_schema/_credential.py
@@ -2,7 +2,7 @@
"""Request / response schemas for the credential router."""
from pydantic import BaseModel, Field
-from ...storage import CredentialRecord
+from ..._service import CredentialView
class CreateCredentialRequest(BaseModel):
@@ -28,7 +28,7 @@ class UpdateCredentialRequest(BaseModel):
class ListCredentialsResponse(BaseModel):
"""Response body for listing credentials."""
- credentials: list[CredentialRecord] = Field(
+ credentials: list[CredentialView] = Field(
description="Credential records.",
)
total: int = Field(description="Total number of credentials.")
diff --git a/src/agentscope/app/_router/_schema/_knowledge_base.py b/src/agentscope/app/_router/_schema/_knowledge_base.py
index afd9dd786..5484b74e0 100644
--- a/src/agentscope/app/_router/_schema/_knowledge_base.py
+++ b/src/agentscope/app/_router/_schema/_knowledge_base.py
@@ -5,11 +5,11 @@ from datetime import datetime
from pydantic import BaseModel, Field
from ...storage import (
- CredentialRecord,
EmbeddingModelConfig,
KnowledgeDocumentRecord,
KnowledgeDocumentStatus,
)
+from ..._service import CredentialView, KnowledgeBaseView
from ....embedding import EmbeddingModelCard
from ....rag import VectorSearchResult
from ...rag.knowledge_base_manager._dimension_policy import DimensionPolicy
@@ -58,24 +58,6 @@ class UpdateKnowledgeBaseRequest(BaseModel):
)
-class KnowledgeBaseView(BaseModel):
- """A knowledge base record as exposed to API clients.
-
- Mirrors :class:`KnowledgeBaseRecord` with the internal
- ``user_id`` / ``collection_name`` fields stripped — clients have
- no business introspecting either.
- """
-
- id: str = Field(description="The knowledge base identifier.")
- name: str = Field(description="Display name of the knowledge base.")
- description: str = Field(description="Free-form description.")
- embedding_model_config: EmbeddingModelConfig = Field(
- description="Embedding model configuration pinned at creation.",
- )
- created_at: datetime = Field(description="Creation timestamp.")
- updated_at: datetime = Field(description="Last-update timestamp.")
-
-
class ListKnowledgeBasesResponse(BaseModel):
"""Response body for listing the caller's knowledge bases."""
@@ -212,7 +194,7 @@ class KbEmbeddingProvider(BaseModel):
cards are narrowed to the locked dimension when applicable.
"""
- credential: CredentialRecord = Field(
+ credential: CredentialView = Field(
description="The credential record exposing these models.",
)
models: list[EmbeddingModelCard] = Field(
diff --git a/src/agentscope/app/_router/_schema/_session.py b/src/agentscope/app/_router/_schema/_session.py
index 5a84f72e5..52a407856 100644
--- a/src/agentscope/app/_router/_schema/_session.py
+++ b/src/agentscope/app/_router/_schema/_session.py
@@ -4,25 +4,24 @@ from pydantic import BaseModel, Field
from ....permission import PermissionMode
from ...storage import (
- AgentRecord,
ChatModelConfig,
SessionKnowledgeConfig,
TTSModelConfig,
SessionRecord,
TeamRecord,
)
-from ..._service import SessionStatus
+from ..._service import AgentView, SessionStatus
class TeamMemberView(BaseModel):
"""One row in :attr:`TeamDetailResponse.members`.
- Pairs each member's :class:`AgentRecord` with its single
+ Pairs each member's :class:`AgentView` with its single
``session_id`` so the UI can subscribe to the worker's chat
stream without a separate lookup.
"""
- agent: AgentRecord = Field(
+ agent: AgentView = Field(
description="The worker agent record.",
)
session_id: str | None = Field(
@@ -38,7 +37,7 @@ class TeamDetailResponse(BaseModel):
"""Resolved team detail embedded inside :class:`SessionView.team`."""
team: TeamRecord = Field(description="The team record.")
- leader_agent: AgentRecord | None = Field(
+ leader_agent: AgentView | None = Field(
default=None,
description=(
"Leader's agent record (resolved from the team's "
diff --git a/src/agentscope/app/_router/_session.py b/src/agentscope/app/_router/_session.py
index 54c678950..35a29e50c 100644
--- a/src/agentscope/app/_router/_session.py
+++ b/src/agentscope/app/_router/_session.py
@@ -8,10 +8,12 @@ from fastapi import APIRouter, Depends, HTTPException, Query, status
from fastapi.responses import StreamingResponse
from ..._utils._common import _generate_id
+from ..access import ResourceKind
from ..deps import (
get_chat_service,
get_current_user_id,
get_message_bus,
+ get_resource_access_service,
get_session_service,
get_storage,
get_workspace_manager,
@@ -30,13 +32,14 @@ from ._schema import (
)
from ..message_bus import MessageBus, MessageBusKeys
from .._service import (
+ AgentView,
+ ResourceAccessService,
ChatService,
SessionService,
SessionProjection,
SubagentHitlProjector,
)
from ..storage import (
- AgentRecord,
ChatModelConfig,
SessionKnowledgeConfig,
TTSModelConfig,
@@ -73,13 +76,20 @@ async def _build_team_detail(
The team plus its resolved leader and member agents (each
member paired with its session id when available).
"""
- leader_agent: AgentRecord | None = None
+ leader_agent: AgentView | None = None
leader_session = await storage.get_session(user_id, "", team.session_id)
if leader_session is not None:
- leader_agent = await storage.get_agent(
+ leader_record = await storage.get_agent(
user_id,
leader_session.agent_id,
)
+ if leader_record is not None:
+ leader_agent = AgentView.model_validate(
+ {
+ **leader_record.model_dump(),
+ "editable": leader_record.user_id == user_id,
+ },
+ )
members: list[TeamMemberView] = []
for member in await _ensure_team_members(storage, user_id, team):
@@ -88,9 +98,18 @@ async def _build_team_detail(
continue
# Use the member's team-scoped session id directly; an invited
# agent has multiple sessions and only ``member.session_id``
- # belongs to this team.
+ # belongs to this team. A member whose owner is not the current
+ # user was invited from another user's pool — read-only here.
members.append(
- TeamMemberView(agent=agent, session_id=member.session_id),
+ TeamMemberView(
+ agent=AgentView.model_validate(
+ {
+ **agent.model_dump(),
+ "editable": member.owner_id == user_id,
+ },
+ ),
+ session_id=member.session_id,
+ ),
)
return TeamDetailResponse(
@@ -108,62 +127,61 @@ session_router = APIRouter(
async def _ensure_credential_exists(
- storage: StorageBase,
+ access: ResourceAccessService,
user_id: str,
config: ChatModelConfig | TTSModelConfig | None,
) -> None:
- """Validate that the credential referenced by ``config`` belongs to the
- given user. No-op when ``config`` is ``None``.
+ """Validate that the credential referenced by ``config`` is visible to
+ the given user (own or shared). No-op when ``config`` is ``None``.
Args:
- storage (`StorageBase`): Injected storage backend.
+ access (`ResourceAccessService`): Injected access service.
user_id (`str`): The authenticated user ID.
config (`ChatModelConfig | TTSModelConfig | None`): Model config to
validate. Pass ``None`` to skip the check.
Raises:
- `HTTPException`: 404 if the credential does not exist or does not
- belong to the user.
+ `HTTPException`: 404 if the credential does not exist or is not
+ visible to the user.
"""
if config is None:
return
- credentials = await storage.list_credentials(user_id)
- if not any(c.id == config.credential_id for c in credentials):
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Credential '{config.credential_id}' not found.",
- )
+ # ``get_resource`` raises 404 when the credential is neither owned
+ # nor shared to the viewer — exactly the semantics we want.
+ await access.get_resource(
+ user_id,
+ ResourceKind.CREDENTIAL,
+ config.credential_id,
+ )
async def _ensure_knowledge_bases_exist(
- storage: StorageBase,
+ access: ResourceAccessService,
user_id: str,
config: SessionKnowledgeConfig | None,
) -> None:
- """Validate every KB id in ``config`` belongs to the given user.
+ """Validate every KB id in ``config`` is visible to the given user.
No-op when ``config`` is ``None`` or its ``knowledge_base_ids``
list is empty.
Args:
- storage (`StorageBase`): Injected storage backend.
+ access (`ResourceAccessService`): Injected access service.
user_id (`str`): The authenticated user ID.
config (`SessionKnowledgeConfig | None`):
Knowledge config to validate. Pass ``None`` to skip.
Raises:
- `HTTPException`: 404 if any KB id does not exist or is not
- owned by the user.
+ `HTTPException`: 404 if any KB id is not visible to the user.
"""
if config is None or not config.knowledge_base_ids:
return
for kb_id in config.knowledge_base_ids:
- kb = await storage.get_knowledge_base(user_id, kb_id)
- if kb is None:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Knowledge base '{kb_id}' not found.",
- )
+ await access.get_resource(
+ user_id,
+ ResourceKind.KNOWLEDGE_BASE,
+ kb_id,
+ )
@session_router.get(
@@ -175,6 +193,7 @@ async def list_sessions(
agent_id: str = Query(description="Filter sessions by agent ID."),
user_id: str = Depends(get_current_user_id),
storage: StorageBase = Depends(get_storage),
+ access: ResourceAccessService = Depends(get_resource_access_service),
message_bus: MessageBus = Depends(get_message_bus),
) -> ListSessionsResponse:
"""Return all sessions for an agent as enriched
@@ -188,11 +207,16 @@ async def list_sessions(
Args:
agent_id (`str`):
- Agent whose sessions to list.
+ Agent whose sessions to list. May be an agent shared to
+ the viewer through :class:`ResourceAccessPolicyBase`;
+ the returned sessions are still the viewer's own.
user_id (`str`):
Injected authenticated user ID.
storage (`StorageBase`):
Injected storage backend.
+ access (`ResourceAccessService`):
+ Injected resource access service; used to validate that
+ the target agent is visible to the viewer.
message_bus (`MessageBus`):
Injected message bus (used for ``session_is_running``).
@@ -201,19 +225,12 @@ async def list_sessions(
Enriched session views and their count.
Raises:
- `HTTPException`: 404 if the agent does not exist or does not
- belong to the authenticated user.
+ `HTTPException`: 404 if the agent is not visible to the caller.
"""
- # Direct ownership check via get_agent — handles both source=user
- # and source=team agents (the latter aren't returned by
- # storage.list_agents but are still owned by the user; reachable
- # via team navigation).
- agent = await storage.get_agent(user_id, agent_id)
- if agent is None or agent.user_id != user_id:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Agent '{agent_id}' not found.",
- )
+ # Verify visibility (own or shared) — raises 404 otherwise. Sessions
+ # themselves are always looked up under ``user_id``, so a viewer
+ # only ever sees their own runs of a shared agent.
+ await access.resolve_agent(user_id, agent_id)
sessions = await storage.list_sessions(user_id, agent_id)
views: list[SessionView] = []
@@ -250,6 +267,7 @@ async def create_session(
user_id: str = Depends(get_current_user_id),
storage: StorageBase = Depends(get_storage),
workspace_manager: WorkspaceManagerBase = Depends(get_workspace_manager),
+ access: ResourceAccessService = Depends(get_resource_access_service),
) -> CreateSessionResponse:
"""Create (or resume) a session for a given agent and workspace.
@@ -265,30 +283,27 @@ async def create_session(
manager; consulted via
:meth:`WorkspaceManagerBase.assign_workspace_id` to fill in
``workspace_id`` when the request body omits it.
+ access (`ResourceAccessService`): Injected access service.
Returns:
`CreateSessionResponse`: The session identifier.
Raises:
- `HTTPException`: 404 if the agent or credential does not exist or
- does not belong to the authenticated user.
+ `HTTPException`: 404 if the agent / credential / knowledge base
+ is not visible to the caller.
"""
- agent = await storage.get_agent(user_id, body.agent_id)
- if agent is None or agent.user_id != user_id:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Agent '{body.agent_id}' not found.",
- )
+ # Agent must be visible to the caller (own or shared).
+ await access.resolve_agent(user_id, body.agent_id)
- await _ensure_credential_exists(storage, user_id, body.chat_model_config)
+ await _ensure_credential_exists(access, user_id, body.chat_model_config)
await _ensure_credential_exists(
- storage,
+ access,
user_id,
body.fallback_chat_model_config,
)
- await _ensure_credential_exists(storage, user_id, body.tts_model_config)
+ await _ensure_credential_exists(access, user_id, body.tts_model_config)
await _ensure_knowledge_bases_exist(
- storage,
+ access,
user_id,
body.knowledge_config,
)
@@ -415,6 +430,7 @@ async def update_session(
agent_id: str = Query(description="Agent the session belongs to."),
user_id: str = Depends(get_current_user_id),
storage: StorageBase = Depends(get_storage),
+ access: ResourceAccessService = Depends(get_resource_access_service),
) -> SessionRecord:
"""Update the model configuration of an existing session.
@@ -423,13 +439,14 @@ async def update_session(
body (`UpdateSessionRequest`): Fields to update.
user_id (`str`): Injected authenticated user ID.
storage (`StorageBase`): Injected storage backend.
+ access (`ResourceAccessService`): Injected access service.
Returns:
`SessionRecord`: The full session record after the update.
Raises:
- `HTTPException`: 404 if the session, agent, or credential does not
- exist or does not belong to the authenticated user.
+ `HTTPException`: 404 if the session does not exist, or if the
+ referenced credential / KB is not visible to the caller.
"""
existing = await storage.get_session(user_id, agent_id, session_id)
if existing is None:
@@ -438,15 +455,15 @@ async def update_session(
detail=f"Session '{session_id}' not found.",
)
- await _ensure_credential_exists(storage, user_id, body.chat_model_config)
+ await _ensure_credential_exists(access, user_id, body.chat_model_config)
await _ensure_credential_exists(
- storage,
+ access,
user_id,
body.fallback_chat_model_config,
)
- await _ensure_credential_exists(storage, user_id, body.tts_model_config)
+ await _ensure_credential_exists(access, user_id, body.tts_model_config)
await _ensure_knowledge_bases_exist(
- storage,
+ access,
user_id,
body.knowledge_config,
)
diff --git a/src/agentscope/app/_service/__init__.py b/src/agentscope/app/_service/__init__.py
index 03db5ec1d..2d6648368 100644
--- a/src/agentscope/app/_service/__init__.py
+++ b/src/agentscope/app/_service/__init__.py
@@ -1,5 +1,11 @@
# -*- coding: utf-8 -*-
"""Service layer for the AgentScope app."""
+from ._access import (
+ AgentView,
+ CredentialView,
+ KnowledgeBaseView,
+ ResourceAccessService,
+)
from ._chat import ChatService
from ._embedding import get_embedding_model
from ._index_sweeper import IndexSweeper
@@ -14,11 +20,15 @@ from ._projectors import SubagentHitlProjector
from ._toolkit import get_toolkit
__all__ = [
+ "AgentView",
"ChatService",
+ "CredentialView",
"IndexSweeper",
"IndexTaskConsumer",
"IndexWorker",
"KnowledgeBaseService",
+ "KnowledgeBaseView",
+ "ResourceAccessService",
"SessionService",
"SessionStatus",
"SessionProjection",
diff --git a/src/agentscope/app/_service/_access.py b/src/agentscope/app/_service/_access.py
new file mode 100644
index 000000000..8026ba464
--- /dev/null
+++ b/src/agentscope/app/_service/_access.py
@@ -0,0 +1,473 @@
+# -*- coding: utf-8 -*-
+"""Resource access service — cross-owner reads with viewer-relative views."""
+from __future__ import annotations
+
+from typing import Any, Literal, TypeVar, overload
+
+from fastapi import HTTPException, status
+from pydantic import BaseModel, Field
+
+from ..access import (
+ ResourceAccessPolicyBase,
+ ResourceKind,
+ ResourcePermission,
+ ResourceRef,
+)
+from ..storage import (
+ AgentRecord,
+ CredentialRecord,
+ KnowledgeBaseRecord,
+ StorageBase,
+)
+
+
+# ---------------------------------------------------------------------
+# Views — viewer-relative projections of storage records.
+# ---------------------------------------------------------------------
+
+
+class AgentView(AgentRecord):
+ """Agent record + viewer-relative ``editable``.
+
+ Subclasses :class:`AgentRecord` so the wire format is a strict
+ superset of the historical response (one extra top-level field);
+ old clients ignore ``editable`` transparently.
+ """
+
+ editable: bool = Field(
+ description=(
+ "Whether the current viewer may PATCH/DELETE this agent."
+ ),
+ )
+
+
+class CredentialView(CredentialRecord):
+ """Credential record + viewer-relative ``editable``.
+
+ ``data`` inherits :class:`CredentialRecord.data` in shape, but the
+ service masks it for shared credentials before constructing the
+ view: only ``type`` and ``name`` survive. Runtime paths that need
+ the raw payload call :meth:`ResourceAccessService.resolve_credential`
+ instead, which returns the underlying record.
+ """
+
+ editable: bool = Field(
+ description=(
+ "Whether the current viewer may PATCH/DELETE this credential."
+ ),
+ )
+
+
+class KnowledgeBaseView(KnowledgeBaseRecord):
+ """Knowledge base record + viewer-relative ``editable``.
+
+ Subclasses :class:`KnowledgeBaseRecord` so the wire format is a
+ strict superset of the record (one extra top-level field), matching
+ :class:`AgentView` and :class:`CredentialView`.
+ """
+
+ editable: bool = Field(
+ description=(
+ "Whether the current viewer may modify this knowledge base."
+ ),
+ )
+
+
+# ---------------------------------------------------------------------
+# Service
+# ---------------------------------------------------------------------
+
+
+_T = TypeVar("_T", bound=BaseModel)
+
+
+class ResourceAccessService:
+ """Resolve resources visible to a viewer.
+
+ Combines owner-scoped storage reads with cross-owner refs from
+ :class:`ResourceAccessPolicyBase`. Routers use it for list/get and
+ edit checks; runtime services use it to resolve shared credentials,
+ agents, and knowledge bases without depending on FastAPI dependencies.
+ """
+
+ def __init__(
+ self,
+ storage: StorageBase,
+ policy: ResourceAccessPolicyBase,
+ ) -> None:
+ """Initialize the service.
+
+ Args:
+ storage: Owner-scoped storage backend.
+ policy: Cross-owner access policy.
+ """
+ self._storage = storage
+ self._policy = policy
+
+ # ------------------------------------------------------------------
+ # list_resource
+ # ------------------------------------------------------------------
+
+ @overload
+ async def list_resource(
+ self,
+ viewer_id: str,
+ kind: Literal[ResourceKind.CREDENTIAL],
+ ) -> list[CredentialView]:
+ ...
+
+ @overload
+ async def list_resource(
+ self,
+ viewer_id: str,
+ kind: Literal[ResourceKind.AGENT],
+ ) -> list[AgentView]:
+ ...
+
+ @overload
+ async def list_resource(
+ self,
+ viewer_id: str,
+ kind: Literal[ResourceKind.KNOWLEDGE_BASE],
+ ) -> list[KnowledgeBaseView]:
+ ...
+
+ async def list_resource(
+ self,
+ viewer_id: str,
+ kind: ResourceKind,
+ ) -> list[BaseModel]:
+ """List resources of ``kind`` visible to ``viewer_id``.
+
+ The result merges the viewer's own records (always ``editable``)
+ with any cross-owner records granted by
+ :class:`ResourceAccessPolicyBase`. Credentials shared to the
+ viewer have their ``data`` payload masked in the view;
+ :meth:`resolve_credential` should be used when the raw payload
+ is required for runtime provider calls.
+ """
+ if kind is ResourceKind.CREDENTIAL:
+ own = await self._storage.list_credentials(viewer_id)
+ elif kind is ResourceKind.AGENT:
+ own = [
+ record
+ for record in await self._storage.list_agents(viewer_id)
+ if record.source != "team"
+ ]
+ else:
+ own = await self._storage.list_knowledge_bases(viewer_id)
+
+ views: list[BaseModel] = [
+ self._build_view(record, viewer_id, True) for record in own
+ ]
+ seen = {(record.user_id, record.id) for record in own}
+
+ for ref in await self._list_refs(viewer_id, kind):
+ key = (ref.owner_id, ref.resource_id)
+ if key in seen:
+ continue
+ record = await self._get_owned(
+ kind,
+ ref.owner_id,
+ ref.resource_id,
+ )
+ if record is None:
+ continue
+ # Team workers are not shareable; owner reads still see them
+ # via ``resolve_agent`` (used by ChatService).
+ if isinstance(record, AgentRecord) and record.source == "team":
+ continue
+ views.append(
+ self._build_view(
+ record,
+ viewer_id,
+ ref.permission == ResourcePermission.EDIT,
+ ),
+ )
+ seen.add(key)
+ return views
+
+ # ------------------------------------------------------------------
+ # get_resource
+ # ------------------------------------------------------------------
+
+ @overload
+ async def get_resource(
+ self,
+ viewer_id: str,
+ kind: Literal[ResourceKind.CREDENTIAL],
+ resource_id: str,
+ ) -> CredentialView:
+ ...
+
+ @overload
+ async def get_resource(
+ self,
+ viewer_id: str,
+ kind: Literal[ResourceKind.AGENT],
+ resource_id: str,
+ ) -> AgentView:
+ ...
+
+ @overload
+ async def get_resource(
+ self,
+ viewer_id: str,
+ kind: Literal[ResourceKind.KNOWLEDGE_BASE],
+ resource_id: str,
+ ) -> KnowledgeBaseView:
+ ...
+
+ async def get_resource(
+ self,
+ viewer_id: str,
+ kind: ResourceKind,
+ resource_id: str,
+ ) -> BaseModel:
+ """Get a visible resource by id or raise ``404``.
+
+ Returns the viewer-relative view so the caller does not have to
+ query editability separately (see the KB detail-page case). For
+ the viewer's own resource the view is derived directly from
+ storage; for a shared resource the policy ref supplies the
+ ``permission`` used to compute ``editable``. Credential ``data``
+ is masked for shared entries — use :meth:`resolve_credential`
+ for runtime provider calls.
+ """
+ own = await self._get_owned(kind, viewer_id, resource_id)
+ if own is not None:
+ # Owner-side reads bypass the ``team`` filter on purpose:
+ # runtime paths legitimately load the owner's ``source ==
+ # "team"`` agents, and we want a single call site.
+ return self._build_view(own, viewer_id, True)
+
+ for ref in await self._list_refs(viewer_id, kind):
+ if ref.resource_id != resource_id:
+ continue
+ record = await self._get_owned(
+ kind,
+ ref.owner_id,
+ ref.resource_id,
+ )
+ if record is None:
+ continue
+ if isinstance(record, AgentRecord) and record.source == "team":
+ continue
+ return self._build_view(
+ record,
+ viewer_id,
+ ref.permission == ResourcePermission.EDIT,
+ )
+ raise self._not_found(kind, resource_id)
+
+ # ------------------------------------------------------------------
+ # Runtime-only helpers
+ # ------------------------------------------------------------------
+
+ async def resolve_credential(
+ self,
+ viewer_id: str,
+ credential_id: str,
+ ) -> CredentialRecord:
+ """Resolve a credential for runtime use — returns the raw record.
+
+ Unlike :meth:`get_resource`, the returned record is NOT masked:
+ the caller is expected to feed the ``data`` payload into a
+ provider client. Restrict use to trusted runtime paths
+ (chat / embedding / TTS model construction).
+ """
+ record = await self._storage.get_credential(viewer_id, credential_id)
+ if record is not None:
+ return record
+
+ for ref in await self._list_refs(viewer_id, ResourceKind.CREDENTIAL):
+ if ref.resource_id != credential_id:
+ continue
+ record = await self._storage.get_credential(
+ ref.owner_id,
+ ref.resource_id,
+ )
+ if record is not None:
+ return record
+ raise self._not_found(ResourceKind.CREDENTIAL, credential_id)
+
+ async def resolve_agent(
+ self,
+ viewer_id: str,
+ agent_id: str,
+ ) -> AgentRecord:
+ """Resolve an agent for runtime use — returns the raw record.
+
+ Owner reads include team workers (needed by ChatService when
+ running a worker session); cross-owner refs only resolve
+ ``source == "user"`` agents since team workers are not
+ shareable.
+ """
+ record = await self._storage.get_agent(viewer_id, agent_id)
+ if record is not None:
+ return record
+
+ for ref in await self._list_refs(viewer_id, ResourceKind.AGENT):
+ if ref.resource_id != agent_id:
+ continue
+ record = await self._storage.get_agent(
+ ref.owner_id,
+ ref.resource_id,
+ )
+ if record is not None and record.source != "team":
+ return record
+ raise self._not_found(ResourceKind.AGENT, agent_id)
+
+ async def resolve_knowledge_base(
+ self,
+ viewer_id: str,
+ knowledge_base_id: str,
+ ) -> KnowledgeBaseRecord:
+ """Resolve a knowledge base for runtime use — returns the raw
+ record. Used by the RAG middleware and the KB service to look
+ up the vector-store collection tied to a shared KB."""
+ record = await self._storage.get_knowledge_base(
+ viewer_id,
+ knowledge_base_id,
+ )
+ if record is not None:
+ return record
+
+ for ref in await self._list_refs(
+ viewer_id,
+ ResourceKind.KNOWLEDGE_BASE,
+ ):
+ if ref.resource_id != knowledge_base_id:
+ continue
+ record = await self._storage.get_knowledge_base(
+ ref.owner_id,
+ ref.resource_id,
+ )
+ if record is not None:
+ return record
+ raise self._not_found(
+ ResourceKind.KNOWLEDGE_BASE,
+ knowledge_base_id,
+ )
+
+ # ------------------------------------------------------------------
+ # Edit resolution
+ # ------------------------------------------------------------------
+
+ async def resolve_for_edit(
+ self,
+ viewer_id: str,
+ kind: ResourceKind,
+ resource_id: str,
+ ) -> tuple[str, Any]:
+ """Resolve ``(owner_id, record)`` for a mutation.
+
+ Routers use this before PATCH/DELETE to keep the resource_id
+ aware of shared editors: an owner writes under their own
+ user_id, but a shared editor writes back through the owning
+ user's storage key. The returned ``record`` is the raw storage
+ record (not a masked view) so callers can inspect and modify
+ it before persisting.
+
+ Raises:
+ HTTPException:
+ * 404 if the resource is not visible to ``viewer_id``
+ (matches the historical owner-only 404).
+ * 403 if the resource is visible but ``viewer_id`` only
+ has ``READ`` permission on it.
+ """
+ own = await self._get_owned(kind, viewer_id, resource_id)
+ if own is not None:
+ return viewer_id, own
+
+ for ref in await self._list_refs(viewer_id, kind):
+ if ref.resource_id != resource_id:
+ continue
+ record = await self._get_owned(
+ kind,
+ ref.owner_id,
+ ref.resource_id,
+ )
+ if record is None:
+ continue
+ if isinstance(record, AgentRecord) and record.source == "team":
+ continue
+ if ref.permission != ResourcePermission.EDIT:
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail=(
+ f"{kind.value.replace('_', ' ').title()} "
+ f"'{resource_id}' is read-only for this viewer."
+ ),
+ )
+ return ref.owner_id, record
+ raise self._not_found(kind, resource_id)
+
+ # ------------------------------------------------------------------
+ # Internals
+ # ------------------------------------------------------------------
+
+ async def _get_owned(
+ self,
+ kind: ResourceKind,
+ owner_id: str,
+ resource_id: str,
+ ) -> Any:
+ """Owner-scoped read on the storage backend, dispatched by kind."""
+ if kind is ResourceKind.CREDENTIAL:
+ return await self._storage.get_credential(owner_id, resource_id)
+ if kind is ResourceKind.AGENT:
+ return await self._storage.get_agent(owner_id, resource_id)
+ return await self._storage.get_knowledge_base(owner_id, resource_id)
+
+ def _build_view(
+ self,
+ record: Any,
+ viewer_id: str,
+ editable: bool,
+ ) -> BaseModel:
+ """Project a raw storage record onto a viewer-relative view.
+
+ Credential ``data`` is masked when the viewer is not the owner
+ so the wire format never leaks the shared secret; other kinds
+ pass through unchanged apart from the added ``editable`` flag.
+ """
+ if isinstance(record, CredentialRecord):
+ payload = record.model_dump()
+ if record.user_id != viewer_id:
+ payload["data"] = {
+ k: payload["data"][k]
+ for k in ("type", "name")
+ if k in payload["data"]
+ }
+ payload["editable"] = editable
+ return CredentialView.model_validate(payload)
+ if isinstance(record, AgentRecord):
+ return AgentView.model_validate(
+ {**record.model_dump(), "editable": editable},
+ )
+ return KnowledgeBaseView.model_validate(
+ {**record.model_dump(), "editable": editable},
+ )
+
+ async def _list_refs(
+ self,
+ viewer_id: str,
+ kind: ResourceKind,
+ ) -> list[ResourceRef]:
+ """Return policy refs for ``kind`` and drop mismatched refs."""
+ refs = await self._policy.list_accessible(
+ viewer_id,
+ kind,
+ self._storage,
+ )
+ return [ref for ref in refs if ref.kind == kind]
+
+ @staticmethod
+ def _not_found(kind: ResourceKind, resource_id: str) -> HTTPException:
+ """Build a consistent not-found exception for visible resources."""
+ label = kind.value.replace("_", " ")
+ return HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"{label.title()} '{resource_id}' not found.",
+ )
diff --git a/src/agentscope/app/_service/_chat.py b/src/agentscope/app/_service/_chat.py
index da5e97587..8d93cff31 100644
--- a/src/agentscope/app/_service/_chat.py
+++ b/src/agentscope/app/_service/_chat.py
@@ -34,6 +34,7 @@ from .._types import (
EventProjector,
SubAgentTemplate,
)
+from ._access import ResourceAccessService
from ._model import get_model
from ._tts_model import get_tts_model
from ._toolkit import get_toolkit
@@ -75,6 +76,7 @@ class ChatService:
scheduler_manager: SchedulerManager,
background_task_manager: BackgroundTaskManager,
message_bus: MessageBus,
+ resource_access_service: ResourceAccessService,
knowledge_base_manager: KnowledgeBaseManagerBase | None = None,
extra_agent_middlewares: AgentMiddlewareFactory | None = None,
extra_agent_tools: AgentToolFactory | None = None,
@@ -103,6 +105,11 @@ class ChatService:
distributed locking (via :meth:`session_run`), event
replay + live fan-out (via :meth:`session_publish_event`),
and inbox delivery (via :class:`InboxMiddleware`).
+ resource_access_service (`ResourceAccessService`):
+ Resolves cross-owner resources at runtime. Agent
+ assembly and model / TTS construction all route
+ through this service so shared credentials, agents,
+ and knowledge bases work uniformly.
knowledge_base_manager (`KnowledgeBaseManagerBase | None`, \
optional):
The application's knowledge base manager. When
@@ -140,6 +147,7 @@ class ChatService:
self._scheduler_manager = scheduler_manager
self._background_task_manager = background_task_manager
self._message_bus = message_bus
+ self._access = resource_access_service
self._knowledge_base_manager = knowledge_base_manager
self._extra_agent_middlewares = extra_agent_middlewares
self._extra_agent_tools = extra_agent_tools
@@ -291,13 +299,19 @@ class ChatService:
# 1. Load records + resolve workspace ONCE here, reused below.
# Reject missing records up front with a clear error so the
# downstream assembly code can rely on non-None values.
+ #
+ # ``resolve_agent`` covers own agents (including team workers,
+ # which the owner runs directly) and cross-owner shared agents
+ # (viewer runs a shared user-source agent). It raises 404 when
+ # the agent is not visible to the caller.
# ----------------------------------------------------------------
- agent_record = await self._storage.get_agent(user_id, agent_id)
- if agent_record is None:
+ try:
+ agent_record = await self._access.resolve_agent(user_id, agent_id)
+ except HTTPException as exc:
raise HTTPException(
status_code=404,
detail=f"Agent {agent_id!r} not found.",
- )
+ ) from exc
session_record = await self._storage.get_session(
user_id,
agent_id,
@@ -367,7 +381,7 @@ class ChatService:
tts_model = await get_tts_model(
user_id,
tts_cfg,
- self._storage,
+ self._access,
)
middlewares.append(TTSMiddleware(tts_model))
@@ -376,6 +390,12 @@ class ChatService:
# attached. Each KB resolves to its own :class:`KnowledgeBase` handle
# (own embedding model + vector store), so the middleware can
# retrieve across heterogeneous KBs in one fan-out.
+ #
+ # Each KB may be either owned by the caller or shared to them
+ # via the resource access policy. We resolve the owner through
+ # ``resolve_knowledge_base`` first and hand the KB manager the
+ # true owner id — its own storage lookups stay owner-scoped
+ # and unaware of sharing.
# ----------------------------------------------------------------
kb_cfg = session_record.config.knowledge_config
if (
@@ -386,16 +406,21 @@ class ChatService:
knowledges: list[KnowledgeBase] = []
for kb_id in kb_cfg.knowledge_base_ids:
try:
+ kb_record = await self._access.resolve_knowledge_base(
+ user_id,
+ kb_id,
+ )
knowledge = (
await self._knowledge_base_manager.get_knowledge(
- user_id,
+ kb_record.user_id,
kb_id,
)
)
except Exception: # pylint: disable=broad-except
- # A KB the session referenced was deleted (or its
- # credential revoked) — log and skip so the chat
- # turn can still run with the remaining KBs.
+ # A KB the session referenced was deleted, its
+ # sharing revoked, or its credential is gone —
+ # log and skip so the chat turn can still run
+ # with the remaining KBs.
logger.exception(
"Skipping knowledge base %r for session %r: "
"failed to resolve runtime handle.",
@@ -429,6 +454,7 @@ class ChatService:
user_id=user_id,
agent_record=agent_record,
session_record=session_record,
+ resource_access_service=self._access,
extra_factory=self._extra_agent_tools,
sub_agent_templates=self._sub_agent_templates,
)
@@ -442,11 +468,11 @@ class ChatService:
status_code=404,
detail=f"No model configuration found for agent {agent_id}",
)
- model = await get_model(user_id, model_cfg, self._storage)
+ model = await get_model(user_id, model_cfg, self._access)
fallback_cfg = session_record.config.fallback_chat_model_config
fallback_model = (
- await get_model(user_id, fallback_cfg, self._storage)
+ await get_model(user_id, fallback_cfg, self._access)
if fallback_cfg is not None
else None
)
diff --git a/src/agentscope/app/_service/_embedding.py b/src/agentscope/app/_service/_embedding.py
index 9554c2085..d3e6bd795 100644
--- a/src/agentscope/app/_service/_embedding.py
+++ b/src/agentscope/app/_service/_embedding.py
@@ -3,36 +3,43 @@
credential + config.
Mirrors :mod:`._model` (which does the same for chat models).
+
+Two entry points are provided:
+
+- :func:`get_embedding_model` — HTTP / ChatService path. Resolves the
+ credential through :class:`ResourceAccessService`, so shared
+ credentials work.
+- :func:`build_embedding_model` — pure record-in, model-out helper.
+ Used by owner-internal paths (e.g. the knowledge-base manager, which
+ already holds the KB owner's :class:`CredentialRecord`) and by
+ :func:`get_embedding_model` under the hood.
"""
from fastapi import HTTPException, status
-from ..storage import StorageBase, EmbeddingModelConfig
+from ._access import ResourceAccessService
+from ..storage import CredentialRecord, EmbeddingModelConfig
from ...credential import CredentialFactory
from ...embedding import EmbeddingModelBase
-async def get_embedding_model(
- user_id: str,
+def build_embedding_model(
+ credential_record: CredentialRecord,
config: EmbeddingModelConfig,
- storage: StorageBase,
) -> EmbeddingModelBase:
- """Construct an embedding model from a stored credential and config.
+ """Construct an embedding model from an already-resolved credential.
- This is the embedding counterpart of
- :func:`~agentscope.app._service._model.get_model`. It loads the
- user's credential from storage, resolves the matching embedding
- model class, looks up the model card for ``context_size``, and
- constructs a ready-to-use instance.
+ This is the record-in variant used by owner-internal paths (e.g.
+ the KB manager, which reads the credential directly from storage
+ since KB owner == credential owner). HTTP / cross-owner paths
+ should call :func:`get_embedding_model` instead.
Args:
- user_id (`str`):
- The authenticated user id (credential owner).
+ credential_record (`CredentialRecord`):
+ The credential record whose ``data`` will be handed to the
+ provider client.
config (`EmbeddingModelConfig`):
- The embedding model configuration containing
- ``type``, ``credential_id``, ``model``, and
- ``parameters``.
- storage (`StorageBase`):
- The storage backend for loading credentials.
+ The embedding model configuration (``type``, ``model``,
+ ``parameters``, ``dimensions``).
Returns:
`EmbeddingModelBase`:
@@ -40,23 +47,10 @@ async def get_embedding_model(
Raises:
`HTTPException`:
- 404 if the credential is not found.
400 if the provider does not support embedding.
"""
- # 1. Load credential from storage.
- credential_record = await storage.get_credential(
- user_id,
- config.credential_id,
- )
- if credential_record is None:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Credential {config.credential_id!r} not found.",
- )
-
credential = CredentialFactory.from_dict(credential_record.data)
- # 2. Resolve the embedding model class from the credential type.
credential_cls = CredentialFactory.get_credential_class(config.type)
if credential_cls is None:
raise HTTPException(
@@ -74,21 +68,18 @@ async def get_embedding_model(
),
)
- # 3. Look up the model card for context_size.
context_size: int | None = None
for card in embedding_cls.list_models():
if card.name == config.model:
context_size = card.context_size
break
- # 4. Build parameters (provider-specific, no dimensions).
parameters = (
embedding_cls.Parameters(**config.parameters)
if config.parameters
else None
)
- # 5. Construct the model — dimensions is first-class, not in parameters.
kwargs: dict = {
"credential": credential,
"model": config.model,
@@ -99,3 +90,37 @@ async def get_embedding_model(
kwargs["context_size"] = context_size
return embedding_cls(**kwargs)
+
+
+async def get_embedding_model(
+ user_id: str,
+ config: EmbeddingModelConfig,
+ access: ResourceAccessService,
+) -> EmbeddingModelBase:
+ """Resolve a credential through :class:`ResourceAccessService` and
+ build the corresponding embedding model.
+
+ Args:
+ user_id (`str`):
+ The viewer's user id (may differ from the credential owner
+ for shared credentials).
+ config (`EmbeddingModelConfig`):
+ The embedding model configuration.
+ access (`ResourceAccessService`):
+ Injected resource access service.
+
+ Returns:
+ `EmbeddingModelBase`:
+ A configured embedding model instance.
+
+ Raises:
+ `HTTPException`:
+ 404 if the credential is neither owned by ``user_id`` nor
+ shared to them.
+ 400 if the provider does not support embedding.
+ """
+ credential_record = await access.resolve_credential(
+ user_id,
+ config.credential_id,
+ )
+ return build_embedding_model(credential_record, config)
diff --git a/src/agentscope/app/_service/_knowledge_base.py b/src/agentscope/app/_service/_knowledge_base.py
index 7fb514e0c..180e0bcda 100644
--- a/src/agentscope/app/_service/_knowledge_base.py
+++ b/src/agentscope/app/_service/_knowledge_base.py
@@ -22,6 +22,7 @@ from typing import IO, TYPE_CHECKING
from fastapi import HTTPException, status
+from ..access import ResourceKind
from ..rag.knowledge_base_manager import (
DimensionPolicyError,
KnowledgeBaseNotFoundError,
@@ -32,6 +33,7 @@ from ..storage import (
)
from ..._logging import logger
from .._bus_ops import enqueue_index_task
+from ._access import ResourceAccessService
if TYPE_CHECKING:
from ..rag.blob_store import BlobStoreBase
@@ -62,6 +64,7 @@ class KnowledgeBaseService:
knowledge_base_manager: "KnowledgeBaseManagerBase",
blob_store: "BlobStoreBase",
message_bus: "MessageBus",
+ resource_access_service: "ResourceAccessService",
) -> None:
"""Initialize the service.
@@ -82,11 +85,17 @@ class KnowledgeBaseService:
:func:`~agentscope.app._bus_ops.enqueue_index_task`;
a co-located or out-of-process
:class:`IndexTaskConsumer` drains and processes them.
+ resource_access_service (`ResourceAccessService`):
+ Cross-owner access resolver. Every KB lookup (read
+ *and* mutation) goes through it so shared knowledge
+ bases work end-to-end: readers see documents +
+ search hits, editors can also upload / delete.
"""
self._storage = storage
self._manager = knowledge_base_manager
self._blob_store = blob_store
self._bus = message_bus
+ self._access = resource_access_service
# ------------------------------------------------------------------
# Knowledge base CRUD
@@ -161,8 +170,9 @@ class KnowledgeBaseService:
Only ``name`` and ``description`` are mutable. The embedding
model configuration is pinned at creation time.
"""
+ owner_id = await self._require_edit(user_id, knowledge_base_id)
record = await self._manager.update_knowledge_base(
- user_id=user_id,
+ user_id=owner_id,
knowledge_base_id=knowledge_base_id,
name=name,
description=description,
@@ -186,15 +196,16 @@ class KnowledgeBaseService:
best-effort here so disk space is reclaimed even though the
manager + storage cascade would otherwise orphan them.
"""
+ owner_id = await self._require_edit(user_id, knowledge_base_id)
documents = await self._storage.list_knowledge_documents(
- user_id,
+ owner_id,
knowledge_base_id,
)
for document in documents:
await self._delete_blob_quietly(document.data.blob_uri)
deleted = await self._manager.delete_knowledge_base(
- user_id,
+ owner_id,
knowledge_base_id,
)
if not deleted:
@@ -252,8 +263,9 @@ class KnowledgeBaseService:
``404`` if the knowledge base does not exist.
"""
# Authorise before touching the blob store: raising after a
- # write would leave the blob orphaned.
- await self._authorise_kb(user_id, knowledge_base_id)
+ # write would leave the blob orphaned. Uploading a document is
+ # a mutation, so require edit permission.
+ owner_id = await self._require_edit(user_id, knowledge_base_id)
document_id = uuid.uuid4().hex
blob_uri = await self._blob_store.write_stream(
@@ -263,7 +275,7 @@ class KnowledgeBaseService:
record = KnowledgeDocumentRecord(
id=document_id,
- user_id=user_id,
+ user_id=owner_id,
knowledge_base_id=knowledge_base_id,
data=KnowledgeDocumentData(
filename=filename,
@@ -274,7 +286,7 @@ class KnowledgeBaseService:
)
try:
stored = await self._storage.upsert_knowledge_document(
- user_id,
+ owner_id,
record,
)
except Exception:
@@ -285,7 +297,7 @@ class KnowledgeBaseService:
await enqueue_index_task(
self._bus,
- user_id=user_id,
+ user_id=owner_id,
knowledge_base_id=knowledge_base_id,
document_id=document_id,
)
@@ -305,7 +317,8 @@ class KnowledgeBaseService:
Args:
user_id (`str`):
- The owner user id.
+ The viewer user id — can be the owner or a viewer
+ granted access through the resource access policy.
knowledge_base_id (`str`):
The target knowledge base id.
@@ -316,13 +329,17 @@ class KnowledgeBaseService:
Raises:
`HTTPException`:
- ``404`` if the knowledge base does not exist.
+ ``404`` if the knowledge base is not visible to the
+ caller.
"""
- await self._authorise_kb(user_id, knowledge_base_id)
- return await self._storage.list_knowledge_documents(
+ record = await self._access.resolve_knowledge_base(
user_id,
knowledge_base_id,
)
+ return await self._storage.list_knowledge_documents(
+ record.user_id,
+ knowledge_base_id,
+ )
async def get_document_status(
self,
@@ -341,7 +358,7 @@ class KnowledgeBaseService:
Args:
user_id (`str`):
- The owner user id.
+ The viewer user id.
knowledge_base_id (`str`):
The target knowledge base id.
document_ids (`list[str]`):
@@ -353,18 +370,22 @@ class KnowledgeBaseService:
Raises:
`HTTPException`:
- ``404`` if the knowledge base does not exist.
+ ``404`` if the knowledge base is not visible to the
+ caller.
"""
- await self._authorise_kb(user_id, knowledge_base_id)
+ record = await self._access.resolve_knowledge_base(
+ user_id,
+ knowledge_base_id,
+ )
records: list[KnowledgeDocumentRecord] = []
for document_id in document_ids:
- record = await self._storage.get_knowledge_document(
- user_id,
+ record_doc = await self._storage.get_knowledge_document(
+ record.user_id,
knowledge_base_id,
document_id,
)
- if record is not None:
- records.append(record)
+ if record_doc is not None:
+ records.append(record_doc)
return records
async def delete_document(
@@ -391,7 +412,7 @@ class KnowledgeBaseService:
Args:
user_id (`str`):
- The owner user id.
+ The viewer user id — owner or shared editor.
knowledge_base_id (`str`):
The target knowledge base id.
document_id (`str`):
@@ -399,23 +420,24 @@ class KnowledgeBaseService:
Raises:
`HTTPException`:
- ``404`` if the knowledge base does not exist.
+ ``404`` if the knowledge base is not visible to the
+ caller; ``403`` if visible but not editable.
"""
+ owner_id = await self._require_edit(user_id, knowledge_base_id)
record = await self._storage.get_knowledge_document(
- user_id,
+ owner_id,
knowledge_base_id,
document_id,
)
if record is None:
- # 404 if the KB does not exist, otherwise treat the
- # missing document as already-deleted (idempotent).
- await self._authorise_kb(user_id, knowledge_base_id)
+ # Idempotent: KB exists (edit check succeeded) but the
+ # document is already gone.
return
knowledge = await self._resolve_knowledge(user_id, knowledge_base_id)
await knowledge.delete_document(document_id)
await self._storage.delete_knowledge_document(
- user_id,
+ owner_id,
knowledge_base_id,
document_id,
)
@@ -436,7 +458,7 @@ class KnowledgeBaseService:
Args:
user_id (`str`):
- The owner user id.
+ The viewer user id — owner or shared reader.
knowledge_base_id (`str`):
The knowledge base to search.
query (`str`):
@@ -450,7 +472,8 @@ class KnowledgeBaseService:
Raises:
`HTTPException`:
- ``404`` if the knowledge base does not exist.
+ ``404`` if the knowledge base is not visible to the
+ caller.
"""
knowledge = await self._resolve_knowledge(user_id, knowledge_base_id)
return await knowledge.search(queries=[query], top_k=top_k)
@@ -459,38 +482,45 @@ class KnowledgeBaseService:
# Internal helpers
# ------------------------------------------------------------------
- async def _authorise_kb(
+ async def _require_edit(
self,
user_id: str,
knowledge_base_id: str,
- ) -> "KnowledgeBaseRecord":
- """Look the KB record up so we can 404 cleanly.
-
- The check is intentionally separate from :meth:`_resolve_knowledge`
- because document-level endpoints (list / delete) need to refuse
- unknown KBs without paying the embedding-model construction cost
- that :meth:`_resolve_knowledge` triggers.
+ ) -> str:
+ """Ensure the caller can mutate this KB; return the *owner* id.
+
+ Every KB mutation writes back through the owner's storage key,
+ so a shared editor's request must be resolved to the owner id
+ before touching storage. Raises ``404`` when the KB is not
+ visible to ``user_id`` and ``403`` when it is visible but only
+ readable.
"""
- record = await self._storage.get_knowledge_base(
+ owner_id, _ = await self._access.resolve_for_edit(
user_id,
+ ResourceKind.KNOWLEDGE_BASE,
knowledge_base_id,
)
- if record is None:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Knowledge base {knowledge_base_id!r} not found.",
- )
- return record
+ return owner_id
async def _resolve_knowledge(
self,
user_id: str,
knowledge_base_id: str,
) -> "object":
- """Resolve a :class:`KnowledgeBase` and translate not-found to 404."""
+ """Resolve a :class:`KnowledgeBase` for a viewer.
+
+ Rewrites ``user_id`` to the owning user id when the caller is a
+ shared reader/editor, so the manager reads the correct
+ collection metadata from storage. ``KnowledgeBaseNotFoundError``
+ is translated to ``404``.
+ """
+ record = await self._access.resolve_knowledge_base(
+ user_id,
+ knowledge_base_id,
+ )
try:
return await self._manager.get_knowledge(
- user_id,
+ record.user_id,
knowledge_base_id,
)
except KnowledgeBaseNotFoundError as exc:
diff --git a/src/agentscope/app/_service/_model.py b/src/agentscope/app/_service/_model.py
index d80f4c87a..6d1134490 100644
--- a/src/agentscope/app/_service/_model.py
+++ b/src/agentscope/app/_service/_model.py
@@ -1,8 +1,7 @@
# -*- coding: utf-8 -*-
"""Model service: builds a ChatModelBase from stored credential + config."""
-from fastapi import HTTPException, status
-
-from ..storage import StorageBase, ChatModelConfig
+from ._access import ResourceAccessService
+from ..storage import ChatModelConfig
from ...credential import CredentialFactory
from ...model import ChatModelBase
@@ -10,31 +9,39 @@ from ...model import ChatModelBase
async def get_model(
user_id: str,
config: ChatModelConfig,
- storage: StorageBase,
+ access: ResourceAccessService,
) -> ChatModelBase:
- """Get the model instance from the configuration and storage.
+ """Build a chat model instance from a stored credential and config.
+
+ Credentials are resolved through :class:`ResourceAccessService` so
+ both the viewer's own credentials and any shared to them via the
+ resource access policy work. Runtime paths use
+ :meth:`ResourceAccessService.resolve_credential` which returns the
+ raw record (not the masked view) — required for making real
+ provider calls.
Args:
user_id (`str`):
- The user id.
+ The viewer's user id. May differ from the credential owner
+ when the credential is shared.
config (`ChatModelConfig`):
The chat model configuration.
- storage (`StorageBase`):
- The storage instance.
+ access (`ResourceAccessService`):
+ Injected resource access service.
Returns:
`ChatModelBase`:
The model instance.
+
+ Raises:
+ `HTTPException`:
+ 404 when the credential is neither owned by ``user_id`` nor
+ shared to them.
"""
- credential_record = await storage.get_credential(
+ credential_record = await access.resolve_credential(
user_id,
config.credential_id,
)
- if credential_record is None:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Credential {config.credential_id!r} not found.",
- )
credential = CredentialFactory.from_dict(credential_record.data)
model_cls = credential.get_chat_model_class()
diff --git a/src/agentscope/app/_service/_toolkit.py b/src/agentscope/app/_service/_toolkit.py
index a614dc1be..d0c6ef93d 100644
--- a/src/agentscope/app/_service/_toolkit.py
+++ b/src/agentscope/app/_service/_toolkit.py
@@ -30,6 +30,8 @@ from ...tool import (
ToolGroup,
)
from ...workspace import WorkspaceBase
+from ..access import ResourceKind
+from ._access import ResourceAccessService
async def get_toolkit(
@@ -44,6 +46,7 @@ async def get_toolkit(
user_id: str,
agent_record: AgentRecord,
session_record: SessionRecord,
+ resource_access_service: ResourceAccessService,
extra_factory: AgentToolFactory | None = None,
sub_agent_templates: dict[str, SubAgentTemplate] | None = None,
) -> Toolkit:
@@ -206,11 +209,19 @@ time or interval"
# targets). Team-tool base is safe to call for either team or
# non-team sessions — AgentInvite rechecks the leader
# precondition at call time.
+ #
+ # Walk agents *visible* to the caller (own + shared through the
+ # resource access policy) so a leader can invite a partner's
+ # agent when the policy grants access.
+ visible_agents = await resource_access_service.list_resource(
+ user_id,
+ ResourceKind.AGENT,
+ )
invitable_pool = [
- a
- for a in await storage.list_agents(user_id)
- if a.data.invite_config.invitable
- and (a.data.invite_config.invite_description or "").strip()
+ view
+ for view in visible_agents
+ if view.data.invite_config.invitable
+ and (view.data.invite_config.invite_description or "").strip()
]
if invitable_pool:
tools.append(
diff --git a/src/agentscope/app/_service/_tts_model.py b/src/agentscope/app/_service/_tts_model.py
index 6f2a3dbe5..88c7a5a67 100644
--- a/src/agentscope/app/_service/_tts_model.py
+++ b/src/agentscope/app/_service/_tts_model.py
@@ -4,7 +4,8 @@ from typing import Type
from fastapi import HTTPException, status
-from ..storage import StorageBase, TTSModelConfig
+from ._access import ResourceAccessService
+from ..storage import TTSModelConfig
from ...credential import CredentialFactory
from ...tts import TTSModelBase
@@ -12,31 +13,27 @@ from ...tts import TTSModelBase
async def get_tts_model(
user_id: str,
config: TTSModelConfig,
- storage: StorageBase,
+ access: ResourceAccessService,
) -> TTSModelBase:
- """Get the TTS model instance from the configuration and storage.
+ """Build a TTS model instance from a stored credential and config.
Args:
user_id (`str`):
- The user id.
+ The viewer's user id (may differ from the credential owner
+ for shared credentials).
config (`TTSModelConfig`):
The TTS model configuration.
- storage (`StorageBase`):
- The storage instance.
+ access (`ResourceAccessService`):
+ Injected resource access service.
Returns:
`TTSModelBase`:
The TTS model instance.
"""
- credential_record = await storage.get_credential(
+ credential_record = await access.resolve_credential(
user_id,
config.credential_id,
)
- if credential_record is None:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Credential {config.credential_id!r} not found.",
- )
credential = CredentialFactory.from_dict(credential_record.data)
tts_classes = credential.get_tts_model_classes()
diff --git a/src/agentscope/app/access/__init__.py b/src/agentscope/app/access/__init__.py
new file mode 100644
index 000000000..7d62dbafe
--- /dev/null
+++ b/src/agentscope/app/access/__init__.py
@@ -0,0 +1,30 @@
+# -*- coding: utf-8 -*-
+"""Public resource access policy extension points.
+
+Import from this package when customizing cross-owner resource access:
+
+.. code-block:: python
+
+ from agentscope.app.access import (
+ ResourceAccessPolicyBase,
+ ResourceKind,
+ ResourcePermission,
+ ResourceRef,
+ )
+"""
+
+from ._policy import (
+ DenyAllResourceAccessPolicy,
+ ResourceAccessPolicyBase,
+ ResourceKind,
+ ResourcePermission,
+ ResourceRef,
+)
+
+__all__ = [
+ "DenyAllResourceAccessPolicy",
+ "ResourceAccessPolicyBase",
+ "ResourceKind",
+ "ResourcePermission",
+ "ResourceRef",
+]
diff --git a/src/agentscope/app/access/_policy.py b/src/agentscope/app/access/_policy.py
new file mode 100644
index 000000000..5a934aead
--- /dev/null
+++ b/src/agentscope/app/access/_policy.py
@@ -0,0 +1,163 @@
+# -*- coding: utf-8 -*-
+"""Resource access policy primitives for cross-owner resource reads.
+
+This module defines the extension point used by the app service layer to
+decide whether a viewer can access resources owned by another user. The
+default policy denies all cross-owner access, preserving the historical
+owner-isolated behavior.
+"""
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from enum import StrEnum
+
+from pydantic import BaseModel, Field
+
+from ..storage import StorageBase
+
+
+class ResourceKind(StrEnum):
+ """Resource kinds that can be resolved through the access policy."""
+
+ CREDENTIAL = "credential"
+ """A stored credential record."""
+
+ AGENT = "agent"
+ """A stored agent configuration."""
+
+ KNOWLEDGE_BASE = "knowledge_base"
+ """A stored knowledge base."""
+
+
+class ResourcePermission(StrEnum):
+ """Permission level granted for a referenced resource.
+
+ Values:
+ READ: The viewer can see and use the resource. Credentials remain
+ masked in API responses and can only be used by runtime code.
+ EDIT: The viewer can read/use the resource and also mutate it. This
+ is equivalent to co-owner access for the specific resource.
+
+ ``EDIT`` implies ``READ``.
+ """
+
+ READ = "read"
+ """Read/use access."""
+
+ EDIT = "edit"
+ """Read/use access plus mutation rights."""
+
+
+class ResourceRef(BaseModel):
+ """Reference to a resource owned by a specific user.
+
+ Policies return ``ResourceRef`` objects to describe cross-owner resources
+ that a viewer may access. Routers and runtime services then load the
+ concrete record through the existing owner-scoped storage APIs using
+ ``(owner_id, resource_id)``.
+ """
+
+ kind: ResourceKind = Field(
+ description="Resource kind: credential, agent, or knowledge_base.",
+ )
+ owner_id: str = Field(
+ description=(
+ "Resource owner user id, matching the storage record's user_id."
+ ),
+ )
+ resource_id: str = Field(
+ description=(
+ "Resource id under the owner, such as credential_id or agent_id."
+ ),
+ )
+ permission: ResourcePermission = Field(
+ default=ResourcePermission.READ,
+ description="Granted permission level. Defaults to read.",
+ )
+
+
+class ResourceAccessPolicyBase(ABC):
+ """Base class for cross-owner resource access policies.
+
+ Applications subclass this policy to read access rules from configuration,
+ external IAM systems, LDAP, request-scoped context, or any other source.
+
+ The policy intentionally does not manage users, groups, memberships, or
+ resource-share records in AgentScope storage. It only maps a ``viewer_id``
+ to resource references.
+ """
+
+ @abstractmethod
+ async def list_accessible(
+ self,
+ viewer_id: str,
+ kind: ResourceKind,
+ storage: StorageBase,
+ ) -> list[ResourceRef]:
+ """List cross-owner resources of ``kind`` accessible by ``viewer_id``.
+
+ The returned refs should not include resources owned by ``viewer_id``.
+ Callers merge the viewer's own resources from storage with these
+ cross-owner refs.
+
+ Args:
+ viewer_id (`str`): The current viewer's user id.
+ kind (`ResourceKind`): The resource kind to list.
+ storage (`StorageBase`): The owner-scoped storage backend. Policy
+ subclasses may use it for read-only lookups.
+
+ Returns:
+ `list[ResourceRef]`: The accessible cross-owner resource
+ references.
+ """
+
+ async def can_edit(
+ self,
+ viewer_id: str,
+ kind: ResourceKind,
+ owner_id: str,
+ resource_id: str,
+ storage: StorageBase,
+ ) -> bool:
+ """Return whether ``viewer_id`` may mutate the given resource.
+
+ Owners can always edit their own resources. For cross-owner access,
+ the default implementation falls back to :meth:`list_accessible` and
+ grants mutation only when a matching ref has
+ ``ResourcePermission.EDIT``. Subclasses may override this method to
+ perform a more efficient direct authorization check.
+
+ Args:
+ viewer_id (`str`): The current viewer's user id.
+ kind (`ResourceKind`): The resource kind.
+ owner_id (`str`): The resource owner's user id.
+ resource_id (`str`): The resource id under ``owner_id``.
+ storage (`StorageBase`): The owner-scoped storage backend.
+
+ Returns:
+ `bool`: ``True`` when mutation is allowed, otherwise ``False``.
+ """
+ if viewer_id == owner_id:
+ return True
+
+ refs = await self.list_accessible(viewer_id, kind, storage)
+ return any(
+ ref.kind == kind
+ and ref.owner_id == owner_id
+ and ref.resource_id == resource_id
+ and ref.permission == ResourcePermission.EDIT
+ for ref in refs
+ )
+
+
+class DenyAllResourceAccessPolicy(ResourceAccessPolicyBase):
+ """Default policy that denies all cross-owner resource access."""
+
+ async def list_accessible(
+ self,
+ viewer_id: str,
+ kind: ResourceKind,
+ storage: StorageBase,
+ ) -> list[ResourceRef]:
+ """Return no cross-owner resources."""
+ return []
diff --git a/src/agentscope/app/deps.py b/src/agentscope/app/deps.py
index 80b27279f..b26dcfe49 100644
--- a/src/agentscope/app/deps.py
+++ b/src/agentscope/app/deps.py
@@ -8,7 +8,12 @@ from ._manager import (
ChatRunRegistry,
SchedulerManager,
)
-from ._service import ChatService, KnowledgeBaseService, SessionService
+from ._service import (
+ ChatService,
+ KnowledgeBaseService,
+ ResourceAccessService,
+ SessionService,
+)
from ._types import AgentMiddlewareFactory, AgentToolFactory
from .message_bus import MessageBus
from .rag.blob_store import BlobStoreBase
@@ -78,6 +83,23 @@ async def get_chat_service(request: Request) -> ChatService:
return request.app.state.chat_service
+async def get_resource_access_service(
+ request: Request,
+) -> ResourceAccessService:
+ """Return the application-wide resource access service.
+
+ Args:
+ request (`Request`): The incoming FastAPI request.
+
+ Returns:
+ `ResourceAccessService`:
+ The access service stored in ``app.state`` — the single
+ entry point routers should use to resolve
+ credential / agent / knowledge base records.
+ """
+ return request.app.state.resource_access_service
+
+
async def get_session_service(request: Request) -> SessionService:
"""Return the application-wide session service.
diff --git a/src/agentscope/app/rag/knowledge_base_manager/_collection_per_kb.py b/src/agentscope/app/rag/knowledge_base_manager/_collection_per_kb.py
index 042d8077e..34f033b3b 100644
--- a/src/agentscope/app/rag/knowledge_base_manager/_collection_per_kb.py
+++ b/src/agentscope/app/rag/knowledge_base_manager/_collection_per_kb.py
@@ -21,7 +21,7 @@ from ._dimension_policy import DimensionPolicy, DimensionPolicyKind
from ._errors import KnowledgeBaseNotFoundError
from ...._logging import logger
from ....rag import KnowledgeBase
-from ..._service._embedding import get_embedding_model
+from ..._service._embedding import build_embedding_model
from ...storage import KnowledgeBaseRecord
if TYPE_CHECKING:
@@ -173,10 +173,24 @@ class CollectionPerKbManager(KnowledgeBaseManagerBase):
f"Knowledge base {knowledge_base_id!r} not found.",
)
- embedding_model = await get_embedding_model(
- user_id=user_id,
+ # KB manager is an owner-internal path: the credential lives
+ # under the same owner as the knowledge base, so we read it
+ # directly from storage rather than routing through the access
+ # service (which is only relevant when the viewer differs from
+ # the owner).
+ credential_record = await self._storage.get_credential(
+ record.user_id,
+ record.embedding_model_config.credential_id,
+ )
+ if credential_record is None:
+ raise KnowledgeBaseNotFoundError(
+ f"Credential "
+ f"{record.embedding_model_config.credential_id!r} for "
+ f"knowledge base {knowledge_base_id!r} not found.",
+ )
+ embedding_model = build_embedding_model(
+ credential_record=credential_record,
config=record.embedding_model_config,
- storage=self._storage,
)
return KnowledgeBase(
name=record.name,
diff --git a/tests/resource_access_policy_test.py b/tests/resource_access_policy_test.py
new file mode 100644
index 000000000..cc95783ec
--- /dev/null
+++ b/tests/resource_access_policy_test.py
@@ -0,0 +1,358 @@
+# -*- coding: utf-8 -*-
+"""Tests for resource access policy primitives."""
+
+from typing import cast
+from unittest.async_case import IsolatedAsyncioTestCase
+
+from fastapi import HTTPException
+from utils import AnyValue
+
+from agentscope.app.access import (
+ DenyAllResourceAccessPolicy,
+ ResourceAccessPolicyBase,
+ ResourceKind,
+ ResourcePermission,
+ ResourceRef,
+)
+from agentscope.app._service import ResourceAccessService
+from agentscope.app.storage import AgentData, AgentRecord, CredentialRecord
+from agentscope.app.storage import StorageBase
+from agentscope.agent import ContextConfig, ReActConfig
+
+
+class _EditPolicy(ResourceAccessPolicyBase):
+ """Test policy that grants edit access to one cross-owner agent."""
+
+ async def list_accessible(
+ self,
+ viewer_id: str,
+ kind: ResourceKind,
+ storage: StorageBase,
+ ) -> list[ResourceRef]:
+ if viewer_id == "viewer" and kind == ResourceKind.AGENT:
+ return [
+ ResourceRef(
+ kind=ResourceKind.AGENT,
+ owner_id="owner",
+ resource_id="agent-1",
+ permission=ResourcePermission.EDIT,
+ ),
+ ]
+ return []
+
+
+class _SharingPolicy(ResourceAccessPolicyBase):
+ """Test policy that grants read access to shared resources."""
+
+ async def list_accessible(
+ self,
+ viewer_id: str,
+ kind: ResourceKind,
+ storage: StorageBase,
+ ) -> list[ResourceRef]:
+ if viewer_id != "viewer":
+ return []
+ if kind == ResourceKind.AGENT:
+ return [
+ ResourceRef(
+ kind=ResourceKind.AGENT,
+ owner_id="owner",
+ resource_id="agent-1",
+ ),
+ ResourceRef(
+ kind=ResourceKind.AGENT,
+ owner_id="owner",
+ resource_id="team-agent",
+ ),
+ ]
+ if kind == ResourceKind.CREDENTIAL:
+ return [
+ ResourceRef(
+ kind=ResourceKind.CREDENTIAL,
+ owner_id="owner",
+ resource_id="credential-1",
+ ),
+ ]
+ return []
+
+
+class _FakeStorage:
+ """Tiny storage double for resource access tests."""
+
+ def __init__(self) -> None:
+ """Initialize in-memory records."""
+ self.credentials: dict[tuple[str, str], CredentialRecord] = {
+ ("owner", "credential-1"): CredentialRecord(
+ id="credential-1",
+ user_id="owner",
+ data={"type": "test"},
+ ),
+ ("viewer", "credential-own"): CredentialRecord(
+ id="credential-own",
+ user_id="viewer",
+ data={"type": "own"},
+ ),
+ }
+ self.agents: dict[tuple[str, str], AgentRecord] = {
+ ("owner", "agent-1"): AgentRecord(
+ id="agent-1",
+ user_id="owner",
+ data=_make_agent_data("Shared"),
+ ),
+ ("owner", "team-agent"): AgentRecord(
+ id="team-agent",
+ user_id="owner",
+ source="team",
+ data=_make_agent_data("Shared team"),
+ ),
+ ("viewer", "team-agent"): AgentRecord(
+ id="team-agent",
+ user_id="viewer",
+ source="team",
+ data=_make_agent_data("Own team"),
+ ),
+ }
+
+ async def list_credentials(
+ self,
+ user_id: str,
+ ) -> list[CredentialRecord]:
+ """List credentials owned by ``user_id``."""
+ return [
+ record
+ for (owner_id, _), record in self.credentials.items()
+ if owner_id == user_id
+ ]
+
+ async def get_credential(
+ self,
+ user_id: str,
+ credential_id: str,
+ ) -> CredentialRecord | None:
+ """Get a credential."""
+ return self.credentials.get((user_id, credential_id))
+
+ async def list_agents(self, user_id: str) -> list[AgentRecord]:
+ """List agents owned by ``user_id``."""
+ return [
+ record
+ for (owner_id, _), record in self.agents.items()
+ if owner_id == user_id
+ ]
+
+ async def get_agent(
+ self,
+ user_id: str,
+ agent_id: str,
+ ) -> AgentRecord | None:
+ """Get an agent."""
+ return self.agents.get((user_id, agent_id))
+
+
+def _make_agent_data(name: str) -> AgentData:
+ """Create valid agent data for tests."""
+ return AgentData(
+ name=name,
+ system_prompt="You are a helpful assistant.",
+ context_config=ContextConfig(),
+ react_config=ReActConfig(),
+ )
+
+
+class ResourceAccessPolicyTest(IsolatedAsyncioTestCase):
+ """Test resource access policy defaults and edit fallback."""
+
+ async def test_default_policy_denies_cross_owner_access(self) -> None:
+ """The base policy should preserve owner-isolated behavior."""
+ policy = DenyAllResourceAccessPolicy()
+ storage = cast(StorageBase, object())
+
+ result = (
+ await policy.list_accessible(
+ "viewer",
+ ResourceKind.CREDENTIAL,
+ storage,
+ ),
+ await policy.can_edit(
+ "viewer",
+ ResourceKind.CREDENTIAL,
+ "owner",
+ "credential-1",
+ storage,
+ ),
+ )
+
+ self.assertEqual(result, ([], False))
+
+ async def test_owner_can_edit_own_resource(self) -> None:
+ """Owners should not need an explicit policy ref to edit resources."""
+ policy = DenyAllResourceAccessPolicy()
+ storage = cast(StorageBase, object())
+
+ self.assertEqual(
+ await policy.can_edit(
+ "owner",
+ ResourceKind.AGENT,
+ "owner",
+ "agent-1",
+ storage,
+ ),
+ True,
+ )
+
+ async def test_edit_ref_allows_cross_owner_edit(self) -> None:
+ """A matching edit ref should grant cross-owner mutation rights."""
+ policy = _EditPolicy()
+ storage = cast(StorageBase, object())
+
+ result = (
+ await policy.can_edit(
+ "viewer",
+ ResourceKind.AGENT,
+ "owner",
+ "agent-1",
+ storage,
+ ),
+ await policy.can_edit(
+ "viewer",
+ ResourceKind.AGENT,
+ "owner",
+ "agent-2",
+ storage,
+ ),
+ )
+
+ self.assertEqual(result, (True, False))
+
+
+class ResourceAccessServiceTest(IsolatedAsyncioTestCase):
+ """Test resource access service resolution behavior."""
+
+ async def asyncSetUp(self) -> None:
+ """Create the service under test."""
+ self.storage = cast(StorageBase, _FakeStorage())
+ self.service = ResourceAccessService(
+ storage=self.storage,
+ policy=_SharingPolicy(),
+ )
+
+ async def test_get_shared_credential(self) -> None:
+ """Shared credentials should resolve through owner storage."""
+ view = await self.service.get_resource(
+ "viewer",
+ ResourceKind.CREDENTIAL,
+ "credential-1",
+ )
+
+ self.assertEqual(
+ view.model_dump(),
+ {
+ "id": "credential-1",
+ "user_id": "owner",
+ "created_at": AnyValue(),
+ "updated_at": AnyValue(),
+ # Shared credentials must be masked in the view.
+ "data": {"type": "test"},
+ "editable": False,
+ },
+ )
+
+ async def test_resolve_shared_credential_returns_raw(self) -> None:
+ """Runtime resolution should return the unmasked record."""
+ record = await self.service.resolve_credential(
+ "viewer",
+ "credential-1",
+ )
+
+ self.assertEqual(
+ record.model_dump(),
+ {
+ "id": "credential-1",
+ "user_id": "owner",
+ "created_at": AnyValue(),
+ "updated_at": AnyValue(),
+ "data": {"type": "test"},
+ },
+ )
+
+ async def test_list_credentials_includes_own_and_shared(self) -> None:
+ """Credential lists should merge own records and policy refs."""
+ views = await self.service.list_resource(
+ "viewer",
+ ResourceKind.CREDENTIAL,
+ )
+
+ self.assertEqual(
+ [v.model_dump() for v in views],
+ [
+ {
+ "id": "credential-own",
+ "user_id": "viewer",
+ "created_at": AnyValue(),
+ "updated_at": AnyValue(),
+ "data": {"type": "own"},
+ "editable": True,
+ },
+ {
+ "id": "credential-1",
+ "user_id": "owner",
+ "created_at": AnyValue(),
+ "updated_at": AnyValue(),
+ # Shared entry has masked data.
+ "data": {"type": "test"},
+ "editable": False,
+ },
+ ],
+ )
+
+ async def test_get_own_team_agent_is_allowed(self) -> None:
+ """Runtime owner reads should still resolve team agents."""
+ agent = await self.service.resolve_agent("viewer", "team-agent")
+
+ self.assertEqual(
+ agent.model_dump(),
+ {
+ "id": "team-agent",
+ "user_id": "viewer",
+ "source": "team",
+ "created_at": AnyValue(),
+ "updated_at": AnyValue(),
+ "data": AnyValue(),
+ },
+ )
+
+ async def test_list_agents_skips_shared_team_agents(self) -> None:
+ """Cross-owner team agents should not appear in shared lists."""
+ views = await self.service.list_resource(
+ "viewer",
+ ResourceKind.AGENT,
+ )
+
+ self.assertEqual(
+ [v.model_dump() for v in views],
+ [
+ {
+ "id": "agent-1",
+ "user_id": "owner",
+ "source": "user",
+ "created_at": AnyValue(),
+ "updated_at": AnyValue(),
+ "data": AnyValue(),
+ "editable": False,
+ },
+ ],
+ )
+
+ async def test_missing_resource_raises_404(self) -> None:
+ """Missing visible resources should raise a 404 HTTPException."""
+ with self.assertRaises(HTTPException) as ctx:
+ await self.service.get_resource(
+ "viewer",
+ ResourceKind.CREDENTIAL,
+ "missing",
+ )
+
+ self.assertEqual(
+ (ctx.exception.status_code, ctx.exception.detail),
+ (404, "Credential 'missing' not found."),
+ )
diff --git a/tests/service_toolkit_test.py b/tests/service_toolkit_test.py
index 553af19f9..87e07c5fb 100644
--- a/tests/service_toolkit_test.py
+++ b/tests/service_toolkit_test.py
@@ -25,7 +25,8 @@ from agentscope.app._manager import (
BackgroundTaskManager,
SchedulerManager,
)
-from agentscope.app._service import get_toolkit
+from agentscope.app._service import ResourceAccessService, get_toolkit
+from agentscope.app.access import DenyAllResourceAccessPolicy
from agentscope.app.storage import (
AgentData,
AgentRecord,
@@ -119,14 +120,16 @@ class _NoOpStorage:
storage method — the team tools bind a reference for later use.
Exceptions: since :class:`AgentInvite` landed, ``get_toolkit`` calls
- ``list_agents(user_id)`` at assembly time to build the invitable
- pool. Return an empty list — the toolkit tests care about which
- team tools are attached, not about the pool contents; the non-empty
- case is covered by the ``AgentInvite`` tests in
- ``service_team_tools_test.py``. Additionally, when the session has
- a ``team_id`` set, ``get_toolkit`` calls ``get_team`` to decide
- leader-vs-worker; the ``team_id_map`` constructor arg lets a test
- inject a lookup so the worker branch can be exercised.
+ ``ResourceAccessService.list_resource`` at assembly time to build
+ the invitable pool, which fans out to
+ :meth:`StorageBase.list_agents` under the hood. Return an empty
+ list — the toolkit tests care about which team tools are attached,
+ not about the pool contents; the non-empty case is covered by the
+ ``AgentInvite`` tests in ``service_team_tools_test.py``.
+ Additionally, when the session has a ``team_id`` set, ``get_toolkit``
+ calls ``get_team`` to decide leader-vs-worker; the ``team_id_map``
+ constructor arg lets a test inject a lookup so the worker branch
+ can be exercised.
"""
def __init__(
@@ -149,6 +152,20 @@ class _NoOpStorage:
return self._teams.get(team_id)
+def _make_access(storage: Any) -> ResourceAccessService:
+ """Build a :class:`ResourceAccessService` bound to ``storage`` with a
+ deny-all policy for ``get_toolkit`` tests.
+
+ ``list_resource(AGENT)`` therefore fans out to
+ ``storage.list_agents(user_id)`` alone — matching the pre-share
+ behaviour the toolkit tests were written against.
+ """
+ return ResourceAccessService(
+ storage=storage,
+ policy=DenyAllResourceAccessPolicy(),
+ )
+
+
def _tool_names(toolkit: Any) -> list[str]:
"""Extract every registered tool name from a :class:`Toolkit`,
walking its tool groups."""
@@ -219,6 +236,7 @@ class TestGetToolkitBaseAssembly(IsolatedAsyncioTestCase):
session_record=session,
extra_factory=None,
middlewares=[],
+ resource_access_service=_make_access(_NoOpStorage()),
)
names = set(_tool_names(toolkit))
@@ -289,6 +307,7 @@ class TestGetToolkitWorkerVariant(IsolatedAsyncioTestCase):
session_record=session,
extra_factory=None,
middlewares=[],
+ resource_access_service=_make_access(_NoOpStorage()),
)
names = set(_tool_names(toolkit))
# Only TeamSay from the team toolset.
@@ -332,6 +351,7 @@ class TestGetToolkitSchedulingGuard(IsolatedAsyncioTestCase):
session_record=session,
extra_factory=None,
middlewares=[],
+ resource_access_service=_make_access(_NoOpStorage()),
)
names = set(_tool_names(toolkit))
for missing in (
@@ -389,5 +409,6 @@ class TestGetToolkitExtraFactory(IsolatedAsyncioTestCase):
session_record=session,
extra_factory=factory,
middlewares=[],
+ resource_access_service=_make_access(_NoOpStorage()),
)
self.assertIn("my-extra", _tool_names(toolkit))