9e3c3131f7
## Why `runAgent()` always runs with the agent's own role, so an app has no way to scope a run to the person who triggered it. Chat-style apps (Slack, Discord, Teams) need the opposite: the agent should never be able to do more than the member who asked. This is the server/SDK prerequisite for per-user permissions in the Slack app (#22984). It is self-contained and reviewable without any Slack context. > **Scope note.** Review surfaced two authorization problems adjacent to this code that are not part of the original feature — a cross-app agent hole (#21157) and two fail-open branches in application-token auth. Both are fixed here rather than deferred, since they sit directly on the path this PR changes. They are called out separately below so they can be reviewed on their own terms. ## The feature - **`runAsWorkspaceMemberId` (optional) on `RunAgentInput`** — shared type, DTO, and the generated GraphQL artifacts. - **`AgentActorContextService.buildRunAsWorkspaceMemberContext`** resolves member → userWorkspace → role and returns an actor context, a *user* auth context, and the role id. Mirrors what `WorkflowExecutionContextService` already does for acting on behalf of a user. - **`AgentRunService`** swaps the application auth context for the member's, passes their actor context, and attributes AI credit usage to them. - **`buildAgentRolePermissionConfig`** (new util) returns `intersectionOf: [agentRoleId, runAsRoleId]`, agent role first — explicit object grants in `database-tool.provider` resolve against the first role, so it defines which objects are in scope at all and later roles only narrow permissions on them. Collapses to a single entry when the member already holds the agent role, because the permission-flag checks reject an intersection listing the same role twice. - **`ToolContext`** gains an optional `rolePermissionConfig`. The lazy tool path resolved permissions from a single `roleId`, so without this the narrowing would not reach the tool catalog or call-time `execute_tool` — and lazy is the strategy `runAgent` uses. Falls back to the previous `unionOf: [roleId]` default when absent. - Docs: a "Running on behalf of a workspace member" section in `skills-and-agents.mdx`. Omitting the field preserves today's behavior exactly, which is what autonomous runs (scheduled jobs, database-event triggers) need. **Fails closed:** an unresolvable member errors rather than falling back to the agent role, which would grant more than the caller asked for. ## Who may name a member `runAsWorkspaceMemberId` names another person, so it needs an authorization rule of its own. An application token is not sufficient on its own: `frontComponent(id)` is guarded by `UserAuthGuard, NoPermissionGuard` and mints an `APPLICATION_ACCESS` token pair for the requesting user, so any authenticated user can obtain one for an installed app. Those tokens record who they were minted for, and the caller cannot strip that. The rule keys on that binding: | Token | May name | | --- | --- | | No application token | nothing — rejected | | Application token **with** a user binding | only that user's own member | | Application token with **no** user binding | any member | The third row is unattended app code — a database-event-triggered logic function is the Slack worker's path, and `client_credentials` or API-key-minted tokens land here too. ## Adjacent fixes **Cross-app agents** (pre-existing, #21157). The agent lookup was not scoped to the caller, so any app token could run any agent in the workspace, including one belonging to an app with wider permissions — while `skills-and-agents.mdx` promised an app can only run its own. Now rejected with `RUN_AGENT_NOT_ALLOWED`. Guarded on `isDefined(callerApplication)`, so callers without an app token are unaffected; `twenty-front` never calls `runAgent`. **Two fail-open branches in `validateApplicationToken`.** Both populated the auth context conditionally instead of failing closed, and both are now asserted, making the application path structurally identical to `validateAccessToken`: 1. An unresolvable user left the token presenting as *unbound*, so removing someone from a workspace widened their live token instead of revoking it, until it expired. 2. A missing workspace member let the token carry on with the application's own permissions after that member was removed or deactivated. Both mirror `validateAccessToken`, down to its `PENDING_CREATION` / `ONGOING_CREATION` escape hatch. **Behaviour change beyond this PR:** an application token whose user has been removed now 401s where it previously degraded to app-only. That is the point, and it matches access-token semantics, but it is shared auth and worth a careful look. ## Known limitation If the app's own agent role declares row-level predicates, those are not applied in run-as mode, because the query builders resolve row-level rules from a single role via the auth context. The member's own row-level rules do apply, which is the direction that matters here. Multi-role row-level support does not exist anywhere in the codebase today. ## Tests | Check | Result | | --- | --- | | ai-agent-execution, tool-provider, record-crud, user-workspace, full auth tree | 79 suites, 666 passed | | `nx typecheck twenty-server` | clean | | oxlint + oxfmt on the changed server files | clean | Both auth regression tests were verified against the pre-fix code — each fails when the fix is reverted, so they guard the behaviour rather than passing incidentally. ## Note for reviewers Rebased onto `main`, then merged `main` in once more after #23395 landed. The `getObjectsPermissionsFromRolePermissionConfig` intersection fix this PR originally carried has since landed on main independently, and main's version is stricter — it denies when an intersected role is missing from the cache rather than treating it as empty — so this PR takes main's and no longer touches that file. `RunAgentInput` now composes with the `prompt` | `messages` XOR from #23395: `runAsWorkspaceMemberId` sits on the base object, so it is available to both variants.
208 lines
8.4 KiB
Plaintext
208 lines
8.4 KiB
Plaintext
---
|
|
title: Skills & Agents
|
|
description: Define AI skills and agents for your app.
|
|
icon: "robot"
|
|
---
|
|
|
|
<Warning>
|
|
Skills and agents are currently in alpha. The feature works but is still evolving.
|
|
</Warning>
|
|
|
|
Apps can define AI capabilities that live inside the workspace — reusable skill instructions and agents with custom system prompts.
|
|
|
|
<AccordionGroup>
|
|
<Accordion title="defineSkill" description="Define AI agent skills">
|
|
|
|
Skills define reusable instructions and capabilities that AI agents can use within your workspace. Use `defineSkill()` to define skills with built-in validation:
|
|
|
|
```ts src/skills/example-skill.ts
|
|
import { defineSkill } from 'twenty-sdk/define';
|
|
|
|
export default defineSkill({
|
|
universalIdentifier: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
|
|
name: 'sales-outreach',
|
|
label: 'Sales Outreach',
|
|
description: 'Guides the AI agent through a structured sales outreach process',
|
|
icon: 'IconBrain',
|
|
content: `You are a sales outreach assistant. When reaching out to a prospect:
|
|
1. Research the company and recent news
|
|
2. Identify the prospect's role and likely pain points
|
|
3. Draft a personalized message referencing specific details
|
|
4. Keep the tone professional but conversational`,
|
|
});
|
|
```
|
|
|
|
Key points:
|
|
- `name` is a unique identifier string for the skill (kebab-case recommended).
|
|
- `label` is the human-readable display name shown in the UI.
|
|
- `content` contains the skill instructions — this is the text the AI agent uses.
|
|
- `icon` (optional) sets the icon displayed in the UI.
|
|
- `description` (optional) provides additional context about the skill's purpose.
|
|
|
|
</Accordion>
|
|
<Accordion title="defineAgent" description="Define AI agents with custom prompts">
|
|
|
|
Agents are AI assistants that live inside your workspace. Use `defineAgent()` to create agents with a custom system prompt:
|
|
|
|
```ts src/agents/example-agent.ts
|
|
import { defineAgent } from 'twenty-sdk/define';
|
|
|
|
export default defineAgent({
|
|
universalIdentifier: 'b3c4d5e6-f7a8-9012-bcde-f34567890123',
|
|
name: 'sales-assistant',
|
|
label: 'Sales Assistant',
|
|
description: 'Helps the sales team draft outreach emails and research prospects',
|
|
icon: 'IconRobot',
|
|
prompt: 'You are a helpful sales assistant. Help users with their questions and tasks.',
|
|
});
|
|
```
|
|
|
|
Key points:
|
|
- `name` is the unique identifier string for the agent (kebab-case recommended).
|
|
- `label` is the display name shown in the UI.
|
|
- `prompt` is the system prompt that defines the agent's behavior.
|
|
- `description` (optional) provides context about what the agent does.
|
|
- `icon` (optional) sets the icon displayed in the UI.
|
|
- `modelId` (optional) overrides the default AI model used by the agent.
|
|
- `responseFormat` (optional) controls the shape of the agent's output. Defaults to `{ type: 'text' }` for free-form text. Use `{ type: 'json', schema }` to force structured JSON output.
|
|
|
|
By default an agent returns free-form text. To get structured output, set `responseFormat` to `{ type: 'json' }` and provide a `schema`:
|
|
|
|
```ts src/agents/structured-agent.ts
|
|
import { defineAgent } from 'twenty-sdk/define';
|
|
|
|
export default defineAgent({
|
|
universalIdentifier: 'c4d5e6f7-a8b9-0123-cdef-456789012345',
|
|
name: 'lead-scorer',
|
|
label: 'Lead Scorer',
|
|
prompt: 'Score the lead and explain your reasoning.',
|
|
responseFormat: {
|
|
type: 'json',
|
|
schema: {
|
|
type: 'object',
|
|
properties: {
|
|
score: { type: 'number', description: 'Lead score from 0 to 100' },
|
|
summary: { type: 'string', description: 'Short reasoning for the score' },
|
|
},
|
|
required: ['score', 'summary'],
|
|
additionalProperties: false,
|
|
},
|
|
},
|
|
});
|
|
```
|
|
|
|
Schema notes:
|
|
- The schema is a flat object: each property's `type` must be a primitive (`string`, `number`, or `boolean`). Nested objects and arrays are not supported.
|
|
- `description` (optional) on each property guides the model on what to put there.
|
|
- `required` (optional) lists the properties the model must always return.
|
|
- `additionalProperties: false` (optional) forbids any property not declared in `properties`.
|
|
|
|
</Accordion>
|
|
<Accordion title="runAgent" description="Run an agent from a logic function">
|
|
|
|
`runAgent()` lets a logic function run one of your app's agents (with its
|
|
skills and tools). Identify the agent by the `universalIdentifier` you passed
|
|
to `defineAgent()`. Pass either a `prompt` string or a `messages` conversation
|
|
history — not both:
|
|
|
|
```ts src/logic-functions/run-enricher.ts
|
|
import { runAgent } from 'twenty-sdk/logic-function';
|
|
|
|
const { result, error, success } = await runAgent({
|
|
agentUniversalIdentifier: 'b3c4d5e6-f7a8-9012-bcde-f34567890123',
|
|
prompt: 'Enrich House Ad <recordId>: fill empty fields from its listing URL.',
|
|
});
|
|
```
|
|
|
|
For multi-turn bots (Slack, Discord, Teams, …), pass thread history as
|
|
`messages` instead of a single `prompt`:
|
|
|
|
```ts src/logic-functions/reply-in-thread.ts
|
|
import { runAgent } from 'twenty-sdk/logic-function';
|
|
|
|
const { result, error, success } = await runAgent({
|
|
agentUniversalIdentifier: 'b3c4d5e6-f7a8-9012-bcde-f34567890123',
|
|
messages: [
|
|
{ role: 'user', content: 'Who owns Acme?' },
|
|
{ role: 'assistant', content: 'Sarah owns the Acme account.' },
|
|
{ role: 'user', content: 'What was the last touchpoint?' },
|
|
],
|
|
});
|
|
```
|
|
|
|
Key points:
|
|
- Provide **exactly one** of `prompt` (string) or `messages` (1 to 100 entries
|
|
of `{ role: 'user' | 'assistant', content: string }`).
|
|
- The agent runs **synchronously** and can read/update records itself via its
|
|
own tools — `runAgent()` resolves once the run completes.
|
|
- An app can only run its own agents.
|
|
- The app's [default role](/developers/extend/apps/config/roles) must grant the
|
|
`AI` permission flag — add `SystemPermissionFlag.AI` to its
|
|
`permissionFlagUniversalIdentifiers` (or set `canAccessAllTools: true`).
|
|
Without it, `runAgent()` fails with a permission error.
|
|
- Set a generous `timeoutSeconds` on the logic function — agent runs can take
|
|
several seconds.
|
|
- `success` is `true` and `result` is non-null when the run completes; on
|
|
failure `success` is `false`, `result` is `null`, and `error` holds the
|
|
reason (for example, when the workspace ran out of AI credits mid-run).
|
|
|
|
```ts src/roles/default-role.ts
|
|
import { defineApplicationRole, SystemPermissionFlag } from 'twenty-sdk/define';
|
|
|
|
export default defineApplicationRole({
|
|
universalIdentifier: 'b648f87b-1d26-4961-b974-0908fd991061',
|
|
label: 'Default function role',
|
|
// runAgent() requires the AI permission flag on the app's default role.
|
|
permissionFlagUniversalIdentifiers: [SystemPermissionFlag.AI],
|
|
});
|
|
```
|
|
|
|
<Warning>
|
|
**Avoid loops:** if you call `runAgent()` from a `*.updated` database-event
|
|
trigger and the agent updates the same record, scope the trigger with
|
|
`updatedFields` to a field the agent never writes (e.g. the source URL), or
|
|
guard on whether any target field is still empty before calling `runAgent()`.
|
|
</Warning>
|
|
|
|
### Running on behalf of a workspace member
|
|
|
|
Pass `runAsWorkspaceMemberId` when the run is triggered by a person — a chat
|
|
bot answering a message, for instance — so the agent acts as that member
|
|
instead of as the app:
|
|
|
|
```ts src/logic-functions/answer-question.ts
|
|
const { result } = await runAgent({
|
|
agentUniversalIdentifier: 'b3c4d5e6-f7a8-9012-bcde-f34567890123',
|
|
prompt: 'How many open opportunities do we have?',
|
|
runAsWorkspaceMemberId: '20202020-0687-4c41-b707-ed1bfca972a7',
|
|
});
|
|
```
|
|
|
|
The run is then restricted to what **both** the agent's role and the member's
|
|
role allow, records it creates are attributed to that member, and the member's
|
|
row-level permissions apply. Omit the field for autonomous runs (scheduled
|
|
jobs, database-event triggers): those keep the agent's own role.
|
|
|
|
Your app is responsible for mapping the person who triggered the run to a
|
|
workspace member. Naming one requires an app access token, and what a token may
|
|
name depends on whether it carries a user:
|
|
|
|
- A token with **no user attached** may name any member. A logic function runs
|
|
with one, and so do tokens minted through `client_credentials` or from an API
|
|
key.
|
|
- A token issued **on behalf of a user**, as a front component receives, may
|
|
only name that user's own member.
|
|
|
|
Anything else — a plain user session, an API key without an app token — may not
|
|
name a member at all.
|
|
|
|
<Warning>
|
|
`runAgent()` throws when the workspace member cannot be resolved — an
|
|
unknown or removed member, or one with no role. It never falls back to the
|
|
agent's own role, since that would grant more access than the caller asked
|
|
for.
|
|
</Warning>
|
|
|
|
</Accordion>
|
|
</AccordionGroup>
|