feat(agent): add permission controls for chat agents (#313)

* feat(agent): add permission controls for chat agents

* refactor(agent): extract shared agent permission helpers

Consolidate the duplicated role-hierarchy logic into
packages/core/src/agent/permissions.ts:

- getRoleLevel(): numeric level for a team role (fail closed at 0)
- getAgentRequiredLevel(): required level for an agent permission
  (defaults to reviewer/1)
- getAllowedAgentRoles(): inclusive role set for filtering

The typed Record over TeamMemberRole makes the mapping exhaustive,
so adding a new role fails compilation until all sites are updated.
Used by ChatService.startOrContinueChat, AssetService comment
mentions, getAgentChatContextActivity, AgentService.listAgents, and
TeamService.getTeamMembers, replacing four inline copies of the
hierarchy and the allowed-roles conditionals.

Also fix the API permission-denial test to mock HTTPException(403)
and assert a 403 response instead of a generic Error/500, matching
real authzService behavior.

* test(agent): fix flaky comment DAG tests by spacing ULID id generation

ULID ids have 1ms timestamp granularity; back-to-back comment creates
frequently land in the same millisecond, in which case Prisma ULIDs sort
by their random suffix instead of creation order. The DAG spine in
initializeAgentSessionActivity chains top-level comments by id, so a
shuffled order produces paths that omit preceding comments, making the
path-to-root assertions flaky (~80% of full-file runs locally).

Add a 2ms sleep between consecutive comment creates in the affected
tests, guaranteeing strictly increasing ULID timestamps. A 2ms delay is
sufficient because the next create always fires at least 2ms after the
previous ULID was generated. Production is unaffected: real comments
arrive seconds apart via separate requests.
This commit is contained in:
Yiling-J
2026-08-16 11:16:14 +08:00
committed by GitHub
parent 6d4f62d6f6
commit cb1c1c502b
26 changed files with 1066 additions and 122 deletions
+54 -1
View File
@@ -6,6 +6,7 @@ import { getAvatarUrl } from '@shumai/core/src/user/avatar'
import {
createAgentRequestSchema,
updateAgentRequestSchema,
updateAgentPermissionRequestSchema,
paginationParamsSchema,
AgentInfo,
AgentType,
@@ -29,7 +30,7 @@ const route = new Hono<{ Variables: { user: User } }>()
id: teamId,
})
const agents = await agentService.listAgents({ teamId })
const agents = await agentService.listAgents({ teamId, userId: userReq?.id })
const res: AgentInfo[] = await Promise.all(
agents.map(async (agent) => {
@@ -39,6 +40,7 @@ const route = new Hono<{ Variables: { user: User } }>()
name: agent.user.name,
type: agent.type as AgentType,
enabled: agent.enabled,
permission: agent.permission,
avatar: (await getAvatarUrl(agent.user.image)) || undefined,
providerId: agent.providerId || undefined,
modelId: agent.modelId || undefined,
@@ -83,6 +85,7 @@ const route = new Hono<{ Variables: { user: User } }>()
name: agent.user.name,
type: agent.type as AgentType,
enabled: agent.enabled,
permission: agent.permission,
avatar: (await getAvatarUrl(agent.user.image)) || undefined,
providerId: agent.providerId || undefined,
modelId: agent.modelId || undefined,
@@ -137,6 +140,7 @@ const route = new Hono<{ Variables: { user: User } }>()
name: agent.user.name,
type: agent.type as AgentType,
enabled: agent.enabled,
permission: agent.permission,
avatar: (await getAvatarUrl(agent.user.image)) || undefined,
providerId: agent.providerId || undefined,
modelId: agent.modelId || undefined,
@@ -154,6 +158,55 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json(info, 200)
})
.patch(
'/agents/:agentId/permission',
zValidator('json', updateAgentPermissionRequestSchema),
async (c) => {
const agentId = c.req.param('agentId')
const userReq = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
user: userReq,
permission: Permission.Admin,
type: ResourceType.Agent,
id: agentId,
})
const agent = await agentService.updateAgentPermission(agentId, req.permission)
await auditLogService.logAction({
action: AuditAction.agent_update,
teamId: agent.teamId,
userId: userReq?.id,
itemId: agent.id,
})
const config = agent.config as unknown as PrismaJson.AgentConfig
const info: AgentInfo = {
id: agent.id,
name: agent.user.name,
type: agent.type as AgentType,
enabled: agent.enabled,
permission: agent.permission,
avatar: (await getAvatarUrl(agent.user.image)) || undefined,
providerId: agent.providerId || undefined,
modelId: agent.modelId || undefined,
thinkingLevel: config.thinkingLevel || 'off',
systemPrompt: config.systemPrompt,
soul: agent.soul || undefined,
skills: agent.skills.map((s) => ({
id: s.id,
skillId: s.skillId,
skill: s.skill,
})),
mcpServerIds: (agent.mcpServers || []).map((m) => m.mcpServerId),
deniedTools: config.deniedTools || [],
}
return c.json(info, 200)
},
)
.delete('/agents/:agentId', async (c) => {
const agentId = c.req.param('agentId')
const userReq = c.get('user')