feat(sdk): add runAgent() to run app agents from logic functions (#21157)
<img width="948" height="593" alt="image" src="https://github.com/user-attachments/assets/d990fa98-3cfd-469d-ab7f-0b2d4ccf3afc" /> <img width="1361" height="802" alt="image" src="https://github.com/user-attachments/assets/1091f598-49f3-4c16-92ea-1e1c200181e2" /> ## Add `runAgent()` to the Logic Function SDK Lets an app's logic function run one of its own AI agents server-side and get the result back synchronously — reusing the existing agent executor instead of a new bespoke transport. ### Backend - New **`runAgent` GraphQL mutation** (metadata schema) in `ai-agent-execution`, wrapping the existing `AgentAsyncExecutorService.executeAgent`. Scopes the agent lookup to the calling application and runs it under an application auth context. - New `@AuthApplication()` param decorator (mirrors `@AuthWorkspace()`) — first GraphQL resolver authenticated by an **application access token**. - Guarded by `WorkspaceAuthGuard` + `SettingsPermissionGuard(PermissionFlagType.AI)`: the app's role must grant the `AI` permission flag. ### SDK - `runAgent({ agentUniversalIdentifier, prompt })` posts the mutation to `/metadata` with the app token via a new runtime GraphQL transport. Returns `{ result, hasNoMoreAvailableCredits }`. - Refactored the connections helpers onto a shared `postAppEndpoint` util (removes duplicated transport logic). ### Frontend - App install permission modal now shows an explicit consent line — _"Run AI agents and bill AI credits to your workspace"_ — when the app's role requests the `AI` flag. ### Docs - Documented `runAgent` and its `AI` permission-flag requirement in _Skills & Agents_. - Fixed outdated role-permission examples in _Roles & Permissions_ (`permissionFlags` → `permissionFlagUniversalIdentifiers`, `PermissionFlag` → `SystemPermissionFlag`). ### Test plan - [x] SDK unit tests (`run-agent.spec.ts`) — request shape, GraphQL/HTTP error handling, missing env vars - [x] `twenty-server`, `twenty-front`, `twenty-shared` typecheck + lint - [ ] Manual: install an app granting the `AI` flag, call `runAgent()` from a logic function, confirm the agent runs and credits are billed --------- Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
This commit is contained in:
+4
-3
@@ -22,9 +22,10 @@ import { JwtAuthGuard } from 'src/engine/guards/jwt-auth.guard';
|
||||
import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
|
||||
import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
|
||||
|
||||
// On-demand connection lookup for app logic functions. Authenticated via the
|
||||
// application access token (already injected into the function runtime as
|
||||
// TWENTY_APP_ACCESS_TOKEN). Apps can only list their own connections.
|
||||
/** @deprecated Superseded by the `appConnections` / `appConnection` GraphQL
|
||||
* queries on the metadata schema (ApplicationConnectionsResolver). The SDK
|
||||
* helpers (`listConnections`, `getConnection`) now call GraphQL. Kept for
|
||||
* backward compatibility with already-deployed app runtimes. */
|
||||
@Controller('apps/connections')
|
||||
@UseGuards(JwtAuthGuard, WorkspaceAuthGuard, NoPermissionGuard)
|
||||
@UsePipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true }))
|
||||
|
||||
+5
-1
@@ -3,6 +3,7 @@ import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
|
||||
import { ConnectionProviderEntity } from 'src/engine/core-modules/application/connection-provider/connection-provider.entity';
|
||||
import { ApplicationConnectionsController } from 'src/engine/core-modules/application/connection-provider/connections/application-connections.controller';
|
||||
import { ApplicationConnectionsResolver } from 'src/engine/core-modules/application/connection-provider/connections/application-connections.resolver';
|
||||
import { ApplicationConnectionsListService } from 'src/engine/core-modules/application/connection-provider/connections/services/application-connections-list.service';
|
||||
import { TokenModule } from 'src/engine/core-modules/auth/token/token.module';
|
||||
import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
|
||||
@@ -25,7 +26,10 @@ import { RefreshTokensManagerModule } from 'src/modules/connected-account/refres
|
||||
RefreshTokensManagerModule,
|
||||
ConnectedAccountTokenEncryptionModule,
|
||||
],
|
||||
providers: [ApplicationConnectionsListService],
|
||||
providers: [
|
||||
ApplicationConnectionsListService,
|
||||
ApplicationConnectionsResolver,
|
||||
],
|
||||
controllers: [ApplicationConnectionsController],
|
||||
exports: [ApplicationConnectionsListService],
|
||||
})
|
||||
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
import { UseGuards } from '@nestjs/common';
|
||||
import { Args, ID, Query } from '@nestjs/graphql';
|
||||
|
||||
import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';
|
||||
import { AppConnectionObjectDto } from 'src/engine/core-modules/application/connection-provider/connections/dtos/app-connection.object';
|
||||
import { ListAppConnectionsInput } from 'src/engine/core-modules/application/connection-provider/connections/dtos/list-app-connections.input';
|
||||
import { ApplicationConnectionsListService } from 'src/engine/core-modules/application/connection-provider/connections/services/application-connections-list.service';
|
||||
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
|
||||
import { type FlatWorkspace } from 'src/engine/core-modules/workspace/types/flat-workspace.type';
|
||||
import { AuthApplication } from 'src/engine/decorators/auth/auth-application.decorator';
|
||||
import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';
|
||||
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
|
||||
import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
|
||||
import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
|
||||
|
||||
@UseGuards(WorkspaceAuthGuard, NoPermissionGuard)
|
||||
@MetadataResolver()
|
||||
export class ApplicationConnectionsResolver {
|
||||
constructor(
|
||||
private readonly listService: ApplicationConnectionsListService,
|
||||
) {}
|
||||
|
||||
@Query(() => [AppConnectionObjectDto])
|
||||
async appConnections(
|
||||
@AuthApplication() application: FlatApplication,
|
||||
@AuthWorkspace() workspace: FlatWorkspace,
|
||||
@AuthUserWorkspaceId({ allowUndefined: true })
|
||||
userWorkspaceId: string | undefined,
|
||||
@Args('filter', { nullable: true }) filter?: ListAppConnectionsInput,
|
||||
): Promise<AppConnectionObjectDto[]> {
|
||||
return this.listService.list({
|
||||
applicationId: application.id,
|
||||
workspaceId: workspace.id,
|
||||
requestUserWorkspaceId: userWorkspaceId ?? null,
|
||||
filter: filter ?? {},
|
||||
});
|
||||
}
|
||||
|
||||
@Query(() => AppConnectionObjectDto)
|
||||
async appConnection(
|
||||
@AuthApplication() application: FlatApplication,
|
||||
@AuthWorkspace() workspace: FlatWorkspace,
|
||||
@AuthUserWorkspaceId({ allowUndefined: true })
|
||||
userWorkspaceId: string | undefined,
|
||||
@Args('id', { type: () => ID }) id: string,
|
||||
): Promise<AppConnectionObjectDto> {
|
||||
return this.listService.getOne({
|
||||
applicationId: application.id,
|
||||
workspaceId: workspace.id,
|
||||
requestUserWorkspaceId: userWorkspaceId ?? null,
|
||||
id,
|
||||
});
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
import { Field, ID, ObjectType } from '@nestjs/graphql';
|
||||
|
||||
import { type AppConnection } from 'twenty-shared/application';
|
||||
|
||||
@ObjectType('AppConnection')
|
||||
export class AppConnectionObjectDto implements AppConnection {
|
||||
@Field(() => ID)
|
||||
id: string;
|
||||
|
||||
@Field()
|
||||
providerName: string;
|
||||
|
||||
@Field()
|
||||
name: string;
|
||||
|
||||
@Field()
|
||||
handle: string;
|
||||
|
||||
@Field(() => String)
|
||||
visibility: 'user' | 'workspace';
|
||||
|
||||
@Field()
|
||||
userWorkspaceId: string;
|
||||
|
||||
@Field()
|
||||
accessToken: string;
|
||||
|
||||
@Field(() => [String])
|
||||
scopes: string[];
|
||||
|
||||
@Field(() => String, { nullable: true })
|
||||
authFailedAt: string | null;
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
import { Field, InputType } from '@nestjs/graphql';
|
||||
|
||||
import { IsIn, IsOptional, IsString, IsUUID } from 'class-validator';
|
||||
|
||||
@InputType('ListAppConnectionsInput')
|
||||
export class ListAppConnectionsInput {
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@Field({ nullable: true })
|
||||
providerName?: string;
|
||||
|
||||
@IsUUID()
|
||||
@IsOptional()
|
||||
@Field({ nullable: true })
|
||||
userWorkspaceId?: string;
|
||||
|
||||
@IsIn(['user', 'workspace'])
|
||||
@IsOptional()
|
||||
@Field(() => String, { nullable: true })
|
||||
visibility?: 'user' | 'workspace';
|
||||
}
|
||||
+1
-1
@@ -22,7 +22,7 @@ export const fromAgentManifestToUniversalFlatAgent = ({
|
||||
description: agentManifest.description ?? null,
|
||||
prompt: agentManifest.prompt,
|
||||
modelId: (agentManifest.modelId as ModelId) ?? AUTO_SELECT_SMART_MODEL_ID,
|
||||
responseFormat: { type: 'text' },
|
||||
responseFormat: agentManifest.responseFormat ?? { type: 'text' },
|
||||
modelConfiguration: null,
|
||||
evaluationInputs: [],
|
||||
isCustom: false,
|
||||
|
||||
Reference in New Issue
Block a user