AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(twenty): add AI actions and output schemas (#16807)
Kishan Parmar8f38b8e66911
diff --git a/packages/pieces/community/twenty/package.json b/packages/pieces/community/twenty/package.jsonindex 92628e9e42b..38242a34406 100644--- a/packages/pieces/community/twenty/package.json+++ b/packages/pieces/community/twenty/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-twenty",- "version": "0.1.1",+ "version": "0.2.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {diff --git a/packages/pieces/community/twenty/src/index.ts b/packages/pieces/community/twenty/src/index.tsindex 37eef517069..72e03077f22 100644--- a/packages/pieces/community/twenty/src/index.ts+++ b/packages/pieces/community/twenty/src/index.ts@@ -1,16 +1,17 @@-import { createPiece } from '@activepieces/pieces-framework';+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';import { createCustomApiCallAction } from '@activepieces/pieces-common';-import { PieceCategory } from '@activepieces/pieces-framework';import { twentyAuth } from './lib/auth';-import { createContact } from './lib/actions/create-contact';-import { createCompany } from './lib/actions/create-company';-import { createOpportunity } from './lib/actions/create-opportunity';-import { findPerson } from './lib/actions/find-person';-import { findCompany } from './lib/actions/find-company';-import { updatePerson } from './lib/actions/update-person';-import { updateCompany } from './lib/actions/update-company';-import { newPerson } from './lib/triggers/new-person';-import { newCompany } from './lib/triggers/new-company';+import { twentyClient } from './lib/common/client';+import { createContactAction } from './lib/actions/create-contact';+import { createCompanyAction } from './lib/actions/create-company';+import { createOpportunityAction } from './lib/actions/create-opportunity';+import { findPersonAction } from './lib/actions/find-person';+import { findCompanyAction } from './lib/actions/find-company';+import { updatePersonAction } from './lib/actions/update-person';+import { updateCompanyAction } from './lib/actions/update-company';+import { twentyAiActions } from './lib/actions/ai';+import { newPersonTrigger } from './lib/triggers/new-person';+import { newCompanyTrigger } from './lib/triggers/new-company';export { twentyAuth };@@ -18,26 +19,26 @@ export const twenty = createPiece({displayName: 'Twenty',description: 'Open-source CRM platform.',auth: twentyAuth,- minimumSupportedRelease: '0.36.1',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/twenty.png',categories: [PieceCategory.SALES_AND_CRM],authors: ['Akash5908'],actions: [- createContact,- createCompany,- createOpportunity,- findPerson,- findCompany,- updatePerson,- updateCompany,+ createContactAction,+ createCompanyAction,+ createOpportunityAction,+ findPersonAction,+ findCompanyAction,+ updatePersonAction,+ updateCompanyAction,+ ...twentyAiActions,createCustomApiCallAction({- baseUrl: (auth) =>- (auth as unknown as { props: { base_url: string } }).props.base_url.replace(/\/$/, ''),+ baseUrl: (auth) => (auth ? twentyClient.baseUrl({ auth }) : ''),auth: twentyAuth,authMapping: async (auth) => ({- Authorization: `Bearer ${(auth as unknown as { props: { api_key: string } }).props.api_key}`,+ Authorization: `Bearer ${auth.props.api_key}`,}),}),],- triggers: [newPerson, newCompany],+ triggers: [newPersonTrigger, newCompanyTrigger],});diff --git a/packages/pieces/community/twenty/src/lib/actions/ai/create-record.ts b/packages/pieces/community/twenty/src/lib/actions/ai/create-record.tsnew file mode 100644index 00000000000..6946aa32018--- /dev/null+++ b/packages/pieces/community/twenty/src/lib/actions/ai/create-record.ts@@ -0,0 +1,35 @@+import { createAction, Property } from '@activepieces/pieces-framework';++import { twentyAuth } from '../../auth';+import { twentyAiProps } from '../../common/ai-props';+import { twentyApi } from '../../common/api';+import { twentyCreateRecordOutputSchema } from '../../output-schemas';++export const createRecordAction = createAction({+ auth: twentyAuth,+ name: 'twenty_create_record',+ outputSchema: twentyCreateRecordOutputSchema,+ displayName: 'Create Record',+ description: 'Creates one record of any object.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description:+ "Creates one record (a person, company, opportunity, task, note or custom object record) from a JSON object of field values. Use Get Object first to learn the field names. Not idempotent: each call inserts a new record unless Upsert is on, in which case a record matching a unique field (such as a person's email or a company's domain) is updated instead.",+ idempotent: false,+ },+ props: {+ objectNamePlural: twentyAiProps.objectNamePlural({ required: true }),+ record: twentyAiProps.record({ required: true }),+ upsert: Property.Checkbox({+ displayName: 'Upsert',+ description:+ 'Update the existing record instead of creating a duplicate when a unique field (e.g. email, domain) already matches. Defaults to false.',+ required: false,+ }),+ },+ async run(context) {+ const { objectNamePlural, record, upsert } = context.propsValue;+ return await twentyApi.createRecord({ auth: context.auth, objectNamePlural, record, upsert });+ },+});diff --git a/packages/pieces/community/twenty/src/lib/actions/ai/create-records.ts b/packages/pieces/community/twenty/src/lib/actions/ai/create-records.tsnew file mode 100644index 00000000000..5c1ea578e9c--- /dev/null+++ b/packages/pieces/community/twenty/src/lib/actions/ai/create-records.ts@@ -0,0 +1,53 @@+import { createAction, Property } from '@activepieces/pieces-framework';++import { twentyAuth } from '../../auth';+import { twentyAiProps } from '../../common/ai-props';+import { twentyApi } from '../../common/api';+import { twentyCreateRecordsOutputSchema } from '../../output-schemas';++export const createRecordsAction = createAction({+ auth: twentyAuth,+ name: 'twenty_create_records',+ outputSchema: twentyCreateRecordsOutputSchema,+ displayName: 'Create Records',+ description: 'Creates up to 60 records of one object in a single call.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Creates 1 to 60 records of the same object in one call, each a JSON object of field values (same format as Create Record). Prefer it over repeated Create Record calls for imports. The batch succeeds or fails as a whole. Not idempotent unless Upsert is on.',+ idempotent: false,+ },+ props: {+ objectNamePlural: twentyAiProps.objectNamePlural({ required: true }),+ records: Property.Array({+ displayName: 'Records',+ description:+ 'Array of 1-60 JSON objects of field values, e.g. [{"name": "Acme"}, {"name": "Globex"}].',+ required: true,+ }),+ upsert: Property.Checkbox({+ displayName: 'Upsert',+ description:+ 'Update existing records instead of creating duplicates when a unique field already matches. Defaults to false.',+ required: false,+ }),+ },+ async run(context) {+ const { objectNamePlural, records, upsert } = context.propsValue;+ if (records.length === 0 || records.length > MAX_RECORDS) {+ throw new Error(`Records must contain between 1 and ${MAX_RECORDS} items.`);+ }+ if (+ !records.every(+ (item): item is Record<string, unknown> =>+ typeof item === 'object' && item !== null && !Array.isArray(item),+ )+ ) {+ throw new Error('Every item in Records must be a JSON object of field values.');+ }+ return await twentyApi.createRecords({ auth: context.auth, objectNamePlural, records, upsert });+ },+});++const MAX_RECORDS = 60;diff --git a/packages/pieces/community/twenty/src/lib/actions/ai/delete-record.ts b/packages/pieces/community/twenty/src/lib/actions/ai/delete-record.tsnew file mode 100644index 00000000000..aa364bceced--- /dev/null+++ b/packages/pieces/community/twenty/src/lib/actions/ai/delete-record.ts@@ -0,0 +1,40 @@+import { createAction, Property } from '@activepieces/pieces-framework';++import { twentyAuth } from '../../auth';+import { twentyAiProps } from '../../common/ai-props';+import { twentyApi } from '../../common/api';+import { twentyDeleteRecordOutputSchema } from '../../output-schemas';++export const deleteRecordAction = createAction({+ auth: twentyAuth,+ name: 'twenty_delete_record',+ outputSchema: twentyDeleteRecordOutputSchema,+ displayName: 'Delete Record',+ description: 'Deletes one record of any object, softly by default.',+ audience: 'ai',+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description:+ 'Deletes one record by its UUID. By default it is a soft delete: the record moves to the trash and Restore Record brings it back. Turn on Permanent only when the user explicitly wants it gone for good; that cannot be undone and needs the destroy permission.',+ idempotent: false,+ },+ props: {+ objectNamePlural: twentyAiProps.objectNamePlural({ required: true }),+ recordId: twentyAiProps.recordId({ required: true }),+ permanent: Property.Checkbox({+ displayName: 'Permanent',+ description:+ 'Permanently destroy the record instead of moving it to the trash. Cannot be undone. Defaults to false.',+ required: false,+ }),+ },+ async run(context) {+ const { objectNamePlural, recordId, permanent } = context.propsValue;+ return await twentyApi.deleteRecord({+ auth: context.auth,+ objectNamePlural,+ recordId,+ permanent,+ });+ },+});diff --git a/packages/pieces/community/twenty/src/lib/actions/ai/find-duplicate-records.ts b/packages/pieces/community/twenty/src/lib/actions/ai/find-duplicate-records.tsnew file mode 100644index 00000000000..8320b93510d--- /dev/null+++ b/packages/pieces/community/twenty/src/lib/actions/ai/find-duplicate-records.ts@@ -0,0 +1,60 @@+import { createAction, Property } from '@activepieces/pieces-framework';++import { twentyAuth } from '../../auth';+import { twentyAiProps } from '../../common/ai-props';+import { twentyApi } from '../../common/api';+import { twentyFindDuplicateRecordsOutputSchema } from '../../output-schemas';++export const findDuplicateRecordsAction = createAction({+ auth: twentyAuth,+ name: 'twenty_find_duplicate_records',+ outputSchema: twentyFindDuplicateRecordsOutputSchema,+ displayName: 'Find Duplicate Records',+ description: 'Finds likely duplicates of existing records or of candidate record data.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ "Finds records that Twenty's duplicate rules (e.g. same email, domain or name) consider duplicates, either of existing records (Record IDs) or of candidate data before creating it (Records). Pass exactly one of the two. Returns one result per input, in order. Use before Create Record to avoid duplicates, or before Merge Records.",+ idempotent: true,+ },+ props: {+ objectNamePlural: twentyAiProps.objectNamePlural({ required: true }),+ recordIds: twentyAiProps.recordIds({+ required: false,+ description:+ 'UUIDs of existing records to check for duplicates, from List Records. Leave empty when passing Records.',+ }),+ records: Property.Array({+ displayName: 'Records',+ description:+ 'Candidate records to check before creating them, as JSON objects of field values, e.g. [{"emails": {"primaryEmail": "[email protected]"}}]. Leave empty when passing Record IDs.',+ required: false,+ }),+ },+ async run(context) {+ const { objectNamePlural, recordIds, records } = context.propsValue;+ const ids = recordIds ?? [];+ const candidates = records ?? [];+ if (ids.length > 0 === candidates.length > 0) {+ throw new Error('Pass exactly one of Record IDs or Records.');+ }+ if (!ids.every((id): id is string => typeof id === 'string' && id !== '')) {+ throw new Error('Every item in Record IDs must be a non-empty string.');+ }+ if (+ !candidates.every(+ (item): item is Record<string, unknown> =>+ typeof item === 'object' && item !== null && !Array.isArray(item),+ )+ ) {+ throw new Error('Every item in Records must be a JSON object of field values.');+ }+ return await twentyApi.findDuplicateRecords({+ auth: context.auth,+ objectNamePlural,+ recordIds: ids.length > 0 ? ids : undefined,+ records: candidates.length > 0 ? candidates : undefined,+ });+ },+});diff --git a/packages/pieces/community/twenty/src/lib/actions/ai/get-object.ts b/packages/pieces/community/twenty/src/lib/actions/ai/get-object.tsnew file mode 100644index 00000000000..6899071735f--- /dev/null+++ b/packages/pieces/community/twenty/src/lib/actions/ai/get-object.ts@@ -0,0 +1,30 @@+import { createAction, Property } from '@activepieces/pieces-framework';++import { twentyAuth } from '../../auth';+import { twentyApi } from '../../common/api';+import { twentyGetObjectOutputSchema } from '../../output-schemas';++export const getObjectAction = createAction({+ auth: twentyAuth,+ name: 'twenty_get_object',+ outputSchema: twentyGetObjectOutputSchema,+ displayName: 'Get Object',+ description: 'Gets one object definition with its fields.',+ audience: 'ai',+ classification: 'READ',+ aiMetadata: {+ description:+ "Gets one object's definition, including every field's name, type, options and relation target. Use it before Create Record, Update Record or a filter to learn exact field names and select values. Needs the API key's role to have the Data Model settings permission.",+ idempotent: true,+ },+ props: {+ objectId: Property.ShortText({+ displayName: 'Object ID',+ description: 'UUID of the object (the `id` field), from List Objects. Not the object name.',+ required: true,+ }),+ },+ async run(context) {+ return await twentyApi.getObject({ auth: context.auth, objectId: context.propsValue.objectId });+ },+});diff --git a/packages/pieces/community/twenty/src/lib/actions/ai/get-record.ts b/packages/pieces/community/twenty/src/lib/actions/ai/get-record.tsnew file mode 100644index 00000000000..d07219f26f5--- /dev/null+++ b/packages/pieces/community/twenty/src/lib/actions/ai/get-record.ts@@ -0,0 +1,37 @@+import { createAction } from '@activepieces/pieces-framework';++import { twentyAuth } from '../../auth';+import { twentyAiProps } from '../../common/ai-props';+import { twentyApi } from '../../common/api';+import { twentyGetRecordOutputSchema } from '../../output-schemas';++export const getRecordAction = createAction({+ auth: twentyAuth,+ name: 'twenty_get_record',+ outputSchema: twentyGetRecordOutputSchema,+ displayName: 'Get Record',+ description: 'Gets one record of any object by its id.',+ audience: 'ai',+ classification: 'READ',+ aiMetadata: {+ description:+ "Gets one record of an object by its UUID. Use when the id is already known (from List Records or a create); set Depth to 1 to also embed directly related records such as a person's company.",+ idempotent: true,+ },+ props: {+ objectNamePlural: twentyAiProps.objectNamePlural({ required: true }),+ recordId: twentyAiProps.recordId({ required: true }),+ depth: twentyAiProps.depth({ required: false }),+ fields: twentyAiProps.fields({ required: false }),+ },+ async run(context) {+ const { objectNamePlural, recordId, depth, fields } = context.propsValue;+ return await twentyApi.getRecord({+ auth: context.auth,+ objectNamePlural,+ recordId,+ depth,+ fields,+ });+ },+});diff --git a/packages/pieces/community/twenty/src/lib/actions/ai/group-records.ts b/packages/pieces/community/twenty/src/lib/actions/ai/group-records.tsnew file mode 100644index 00000000000..436528c741d--- /dev/null+++ b/packages/pieces/community/twenty/src/lib/actions/ai/group-records.ts@@ -0,0 +1,77 @@+import { createAction, Property } from '@activepieces/pieces-framework';++import { twentyAuth } from '../../auth';+import { twentyAiProps } from '../../common/ai-props';+import { twentyApi } from '../../common/api';+import { twentyGroupRecordsOutputSchema } from '../../output-schemas';++export const groupRecordsAction = createAction({+ auth: twentyAuth,+ name: 'twenty_group_records',+ outputSchema: twentyGroupRecordsOutputSchema,+ displayName: 'Group Records',+ description: 'Groups records by fields and computes aggregates per group.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Groups the records of one object by one or more fields and returns aggregate values per group, e.g. the number of opportunities and total amount per stage, or people created per month. Use it for counts and totals instead of paging through List Records. Returns up to 50 groups by default; each group lists its group-by values in groupByDimensionValues and each aggregate under its name, as a string (e.g. "countNotEmptyId": "3").',+ idempotent: true,+ },+ props: {+ objectNamePlural: twentyAiProps.objectNamePlural({ required: true }),+ groupBy: Property.Array({+ displayName: 'Group By',+ description:+ 'Fields to group by, as an array of JSON objects, e.g. [{"stage": true}], [{"address": {"addressCity": true}}] for a composite sub-field, or [{"createdAt": {"granularity": "MONTH"}}] for dates (DAY, WEEK, MONTH, QUARTER, YEAR).',+ required: true,+ }),+ aggregate: Property.Array({+ displayName: 'Aggregates',+ description:+ 'Aggregate names to compute per group, e.g. ["countNotEmptyId"] for a count, ["sumAmountAmountMicros"] or ["maxCreatedAt"]. Pattern: count/countEmpty/countNotEmpty/countUniqueValues/percentageEmpty/min/max/avg/sum + capitalised field name. Omit to get only the group values, without counts.',+ required: false,+ }),+ filter: twentyAiProps.filter({ required: false }),+ orderBy: twentyAiProps.orderBy({+ required: false,+ description:+ 'Order of the groups, as a JSON array, e.g. [{"stage": "AscNullsLast"}] or [{"aggregate": {"countNotEmptyId": "DescNullsLast"}}].',+ }),+ limit: twentyAiProps.limit({+ required: false,+ description: 'Maximum number of groups to return. Defaults to 50.',+ }),+ },+ async run(context) {+ const { objectNamePlural, groupBy, aggregate, filter, orderBy, limit } = context.propsValue;+ if (+ groupBy.length === 0 ||+ !groupBy.every(+ (item): item is Record<string, unknown> =>+ typeof item === 'object' && item !== null && !Array.isArray(item),+ )+ ) {+ throw new Error(+ 'Group By must be a non-empty array of JSON objects, e.g. [{"stage": true}].',+ );+ }+ if (+ aggregate !== undefined &&+ !aggregate.every((name): name is string => typeof name === 'string' && name !== '')+ ) {+ throw new Error(+ 'Every item in Aggregates must be a non-empty string, e.g. "countNotEmptyId".',+ );+ }+ return await twentyApi.groupRecords({+ auth: context.auth,+ objectNamePlural,+ groupBy,+ aggregate: aggregate !== undefined && aggregate.length > 0 ? aggregate : undefined,+ filter,+ orderBy,+ limit,+ });+ },+});diff --git a/packages/pieces/community/twenty/src/lib/actions/ai/index.ts b/packages/pieces/community/twenty/src/lib/actions/ai/index.tsnew file mode 100644index 00000000000..8c1bb3a6df8--- /dev/null+++ b/packages/pieces/community/twenty/src/lib/actions/ai/index.ts@@ -0,0 +1,29 @@+import { createRecordAction } from './create-record';+import { createRecordsAction } from './create-records';+import { deleteRecordAction } from './delete-record';+import { findDuplicateRecordsAction } from './find-duplicate-records';+import { getObjectAction } from './get-object';+import { getRecordAction } from './get-record';+import { groupRecordsAction } from './group-records';+import { listFieldsAction } from './list-fields';+import { listObjectsAction } from './list-objects';+import { listRecordsAction } from './list-records';+import { mergeRecordsAction } from './merge-records';+import { restoreRecordAction } from './restore-record';+import { updateRecordAction } from './update-record';++export const twentyAiActions = [+ listObjectsAction,+ getObjectAction,+ listFieldsAction,+ listRecordsAction,+ getRecordAction,+ createRecordAction,+ createRecordsAction,+ updateRecordAction,+ deleteRecordAction,+ restoreRecordAction,+ findDuplicateRecordsAction,+ mergeRecordsAction,+ groupRecordsAction,+];diff --git a/packages/pieces/community/twenty/src/lib/actions/ai/list-fields.ts b/packages/pieces/community/twenty/src/lib/actions/ai/list-fields.tsnew file mode 100644index 00000000000..ca00e23a836--- /dev/null+++ b/packages/pieces/community/twenty/src/lib/actions/ai/list-fields.ts@@ -0,0 +1,32 @@+import { createAction } from '@activepieces/pieces-framework';++import { twentyAuth } from '../../auth';+import { twentyAiProps } from '../../common/ai-props';+import { twentyApi } from '../../common/api';+import { twentyListFieldsOutputSchema } from '../../output-schemas';++export const listFieldsAction = createAction({+ auth: twentyAuth,+ name: 'twenty_list_fields',+ outputSchema: twentyListFieldsOutputSchema,+ displayName: 'List Fields',+ description: 'Lists field definitions across all objects in the workspace.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ "Lists field definitions across every object in the workspace, one page at a time. It cannot filter by object, so prefer Get Object to see one object's fields. Needs the API key's role to have the Data Model settings permission.",+ idempotent: true,+ },+ props: {+ limit: twentyAiProps.limit({+ required: false,+ description: 'Maximum number of fields to return.',+ }),+ startingAfter: twentyAiProps.startingAfter({ required: false }),+ },+ async run(context) {+ const { limit, startingAfter } = context.propsValue;+ return await twentyApi.listFields({ auth: context.auth, limit, startingAfter });+ },+});diff --git a/packages/pieces/community/twenty/src/lib/actions/ai/list-objects.ts b/packages/pieces/community/twenty/src/lib/actions/ai/list-objects.tsnew file mode 100644index 00000000000..d6d1008823c--- /dev/null+++ b/packages/pieces/community/twenty/src/lib/actions/ai/list-objects.ts@@ -0,0 +1,32 @@+import { createAction } from '@activepieces/pieces-framework';++import { twentyAuth } from '../../auth';+import { twentyAiProps } from '../../common/ai-props';+import { twentyApi } from '../../common/api';+import { twentyListObjectsOutputSchema } from '../../output-schemas';++export const listObjectsAction = createAction({+ auth: twentyAuth,+ name: 'twenty_list_objects',+ outputSchema: twentyListObjectsOutputSchema,+ displayName: 'List Objects',+ description: 'Lists the standard and custom objects in the workspace.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ "Lists the workspace's objects (standard ones like people and companies, and custom ones) with their names and ids. Call it first to get the `namePlural` that every record action takes as Object, and the id Get Object needs. Needs the API key's role to have the Data Model settings permission.",+ idempotent: true,+ },+ props: {+ limit: twentyAiProps.limit({+ required: false,+ description: 'Maximum number of objects to return.',+ }),+ startingAfter: twentyAiProps.startingAfter({ required: false }),+ },+ async run(context) {+ const { limit, startingAfter } = context.propsValue;+ return await twentyApi.listObjects({ auth: context.auth, limit, startingAfter });+ },+});diff --git a/packages/pieces/community/twenty/src/lib/actions/ai/list-records.ts b/packages/pieces/community/twenty/src/lib/actions/ai/list-records.tsnew file mode 100644index 00000000000..fd9be3e988a--- /dev/null+++ b/packages/pieces/community/twenty/src/lib/actions/ai/list-records.ts@@ -0,0 +1,44 @@+import { createAction } from '@activepieces/pieces-framework';++import { twentyAuth } from '../../auth';+import { twentyAiProps } from '../../common/ai-props';+import { twentyApi } from '../../common/api';+import { twentyListRecordsOutputSchema } from '../../output-schemas';++export const listRecordsAction = createAction({+ auth: twentyAuth,+ name: 'twenty_list_records',+ outputSchema: twentyListRecordsOutputSchema,+ displayName: 'List Records',+ description: 'Lists or searches records of any object, with filter, sort and cursor paging.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Lists records of one object (people, companies, opportunities, tasks, notes or a custom object), optionally narrowed by a Twenty filter expression and sorted. Use it to find a record by email, name or domain and get its id, or to page through records. Returns one page; pass `pageInfo.endCursor` back as Starting After with the same filter for the next page.',+ idempotent: true,+ },+ props: {+ objectNamePlural: twentyAiProps.objectNamePlural({ required: true }),+ filter: twentyAiProps.filter({ required: false }),+ orderBy: twentyAiProps.orderBy({ required: false }),+ limit: twentyAiProps.limit({ required: false }),+ startingAfter: twentyAiProps.startingAfter({ required: false }),+ depth: twentyAiProps.depth({ required: false }),+ fields: twentyAiProps.fields({ required: false }),+ },+ async run(context) {+ const { objectNamePlural, filter, orderBy, limit, startingAfter, depth, fields } =+ context.propsValue;+ return await twentyApi.listRecords({+ auth: context.auth,+ objectNamePlural,+ filter,+ orderBy,+ limit,+ startingAfter,+ depth,+ fields,+ });+ },+});diff --git a/packages/pieces/community/twenty/src/lib/actions/ai/merge-records.ts b/packages/pieces/community/twenty/src/lib/actions/ai/merge-records.tsnew file mode 100644index 00000000000..3f1021a50af--- /dev/null+++ b/packages/pieces/community/twenty/src/lib/actions/ai/merge-records.ts@@ -0,0 +1,53 @@+import { createAction, Property } from '@activepieces/pieces-framework';++import { twentyAuth } from '../../auth';+import { twentyAiProps } from '../../common/ai-props';+import { twentyApi } from '../../common/api';+import { twentyMergeRecordsOutputSchema } from '../../output-schemas';++export const mergeRecordsAction = createAction({+ auth: twentyAuth,+ name: 'twenty_merge_records',+ outputSchema: twentyMergeRecordsOutputSchema,+ displayName: 'Merge Records',+ description: 'Merges 2 to 9 duplicate records of one object into one.',+ audience: 'ai',+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description:+ 'Merges 2 to 9 records of the same object into one: where fields conflict, the record at Conflict Priority Index wins, and the other records are permanently deleted (Restore Record cannot bring them back). Run it with Dry Run on first to preview the merged record, then again with Dry Run off. Find candidates with Find Duplicate Records. Needs update and delete permission.',+ idempotent: false,+ },+ props: {+ objectNamePlural: twentyAiProps.objectNamePlural({ required: true }),+ recordIds: twentyAiProps.recordIds({+ required: true,+ description:+ 'UUIDs of the 2-9 records to merge, from List Records or Find Duplicate Records.',+ }),+ conflictPriorityIndex: Property.Number({+ displayName: 'Conflict Priority Index',+ description:+ 'Zero-based position in Record IDs of the record whose values win when fields conflict, e.g. 0 for the first id.',+ required: true,+ }),+ dryRun: Property.Checkbox({+ displayName: 'Dry Run',+ description: 'Preview the merged record without changing anything. Defaults to false.',+ required: false,+ }),+ },+ async run(context) {+ const { objectNamePlural, recordIds, conflictPriorityIndex, dryRun } = context.propsValue;+ if (!recordIds.every((id): id is string => typeof id === 'string' && id !== '')) {+ throw new Error('Every item in Record IDs must be a non-empty string.');+ }+ return await twentyApi.mergeRecords({+ auth: context.auth,+ objectNamePlural,+ recordIds,+ conflictPriorityIndex,+ dryRun,+ });+ },+});diff --git a/packages/pieces/community/twenty/src/lib/actions/ai/restore-record.ts b/packages/pieces/community/twenty/src/lib/actions/ai/restore-record.tsnew file mode 100644index 00000000000..94dbadbb6f6--- /dev/null+++ b/packages/pieces/community/twenty/src/lib/actions/ai/restore-record.ts@@ -0,0 +1,33 @@+import { createAction } from '@activepieces/pieces-framework';++import { twentyAuth } from '../../auth';+import { twentyAiProps } from '../../common/ai-props';+import { twentyApi } from '../../common/api';+import { twentyRestoreRecordOutputSchema } from '../../output-schemas';++export const restoreRecordAction = createAction({+ auth: twentyAuth,+ name: 'twenty_restore_record',+ outputSchema: twentyRestoreRecordOutputSchema,+ displayName: 'Restore Record',+ description: 'Restores a soft-deleted record.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Restores one soft-deleted record (deleted by Delete Record without Permanent) by its UUID. Find soft-deleted ids with List Records and the filter deletedAt[is]:NOT_NULL. Permanently deleted records cannot be restored.',+ idempotent: true,+ },+ props: {+ objectNamePlural: twentyAiProps.objectNamePlural({ required: true }),+ recordId: twentyAiProps.recordId({+ required: true,+ description:+ 'UUID of the soft-deleted record, from List Records with the filter deletedAt[is]:NOT_NULL.',+ }),+ },+ async run(context) {+ const { objectNamePlural, recordId } = context.propsValue;+ return await twentyApi.restoreRecord({ auth: context.auth, objectNamePlural, recordId });+ },+});diff --git a/packages/pieces/community/twenty/src/lib/actions/ai/update-record.ts b/packages/pieces/community/twenty/src/lib/actions/ai/update-record.tsnew file mode 100644index 00000000000..930bca6d72c--- /dev/null+++ b/packages/pieces/community/twenty/src/lib/actions/ai/update-record.ts@@ -0,0 +1,35 @@+import { createAction } from '@activepieces/pieces-framework';++import { twentyAuth } from '../../auth';+import { twentyAiProps } from '../../common/ai-props';+import { twentyApi } from '../../common/api';+import { twentyUpdateRecordOutputSchema } from '../../output-schemas';++export const updateRecordAction = createAction({+ auth: twentyAuth,+ name: 'twenty_update_record',+ outputSchema: twentyUpdateRecordOutputSchema,+ displayName: 'Update Record',+ description: 'Updates fields on one record of any object.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Updates one record by its UUID (from List Records), changing only the fields present in the JSON; other fields stay as they are. A composite field (name, emails, address, amount) is replaced as a whole, so send all of its sub-fields. Set a field to null to clear it.',+ idempotent: true,+ },+ props: {+ objectNamePlural: twentyAiProps.objectNamePlural({ required: true }),+ recordId: twentyAiProps.recordId({ required: true }),+ record: twentyAiProps.record({+ required: true,+ displayName: 'Changes',+ description:+ 'Fields to change, as a JSON object keyed by field name (same format as Create Record), e.g. {"stage": "PROPOSAL"} or {"jobTitle": null} to clear a field.',+ }),+ },+ async run(context) {+ const { objectNamePlural, recordId, record } = context.propsValue;+ return await twentyApi.updateRecord({ auth: context.auth, objectNamePlural, recordId, record });+ },+});diff --git a/packages/pieces/community/twenty/src/lib/actions/create-company.ts b/packages/pieces/community/twenty/src/lib/actions/create-company.tsindex 0723f19e94d..58c76535498 100644--- a/packages/pieces/community/twenty/src/lib/actions/create-company.ts+++ b/packages/pieces/community/twenty/src/lib/actions/create-company.ts@@ -1,15 +1,16 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';import { twentyAuth } from '../auth';-import { twentyRequest } from '../common';+import { twentyApi } from '../common/api';+import { createCompanyOutputSchema } from '../output-schemas';-export const createCompany = createAction({+export const createCompanyAction = createAction({auth: twentyAuth,name: 'create_company',+ outputSchema: createCompanyOutputSchema,classification: 'WRITE',displayName: 'Create Company',description: 'Creates a new company record in Twenty CRM.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Creates a new company in Twenty CRM. Use when adding an organization to the CRM; company name is required, with optional domain, address, and employee count. Not idempotent: each call inserts a new record with no de-duplication, so repeated calls create duplicate companies.', idempotent: false },props: {name: Property.ShortText({@@ -33,16 +34,12 @@ export const createCompany = createAction({async run(context) {const { name, domainName, address, employees } = context.propsValue;- return await twentyRequest(- context.auth,- HttpMethod.POST,- '/rest/companies',- {- name,- domainName: domainName ? { primaryLinkUrl: domainName, primaryLinkLabel: '' } : undefined,- address: address ? { addressStreet1: address } : undefined,- employees: employees ?? undefined,- },- );+ return await twentyApi.createCompany({+ auth: context.auth,+ name,+ domainName,+ address,+ employees,+ });},});diff --git a/packages/pieces/community/twenty/src/lib/actions/create-contact.ts b/packages/pieces/community/twenty/src/lib/actions/create-contact.tsindex d943868eea5..e148c97c965 100644--- a/packages/pieces/community/twenty/src/lib/actions/create-contact.ts+++ b/packages/pieces/community/twenty/src/lib/actions/create-contact.ts@@ -1,15 +1,16 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';import { twentyAuth } from '../auth';-import { twentyRequest } from '../common';+import { twentyApi } from '../common/api';+import { createContactOutputSchema } from '../output-schemas';-export const createContact = createAction({+export const createContactAction = createAction({auth: twentyAuth,name: 'create_contact',+ outputSchema: createContactOutputSchema,classification: 'WRITE',displayName: 'Create Contact',description: 'Creates a new person record in your Twenty CRM workspace.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Creates a new person (contact) in Twenty CRM. Use when adding a known individual to the CRM; first name is required, last name and primary email are optional. Not idempotent: each call inserts a new record with no de-duplication, so repeated calls create duplicate people.', idempotent: false },props: {firstName: Property.ShortText({@@ -28,17 +29,11 @@ export const createContact = createAction({async run(context) {const { firstName, lastName, email } = context.propsValue;- return await twentyRequest(- context.auth,- HttpMethod.POST,- '/rest/people',- {- name: {- firstName,- lastName,- },- emails: email ? { primaryEmail: email } : undefined,- },- );+ return await twentyApi.createPerson({+ auth: context.auth,+ firstName,+ lastName,+ email,+ });},});diff --git a/packages/pieces/community/twenty/src/lib/actions/create-opportunity.ts b/packages/pieces/community/twenty/src/lib/actions/create-opportunity.tsindex ad9f2dd15c4..dd2dcbca020 100644--- a/packages/pieces/community/twenty/src/lib/actions/create-opportunity.ts+++ b/packages/pieces/community/twenty/src/lib/actions/create-opportunity.ts@@ -1,15 +1,16 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';import { twentyAuth } from '../auth';-import { twentyRequest } from '../common';+import { twentyApi } from '../common/api';+import { createOpportunityOutputSchema } from '../output-schemas';-export const createOpportunity = createAction({+export const createOpportunityAction = createAction({auth: twentyAuth,name: 'create_opportunity',+ outputSchema: createOpportunityOutputSchema,classification: 'WRITE',displayName: 'Create Opportunity',description: 'Creates a new opportunity (deal) in Twenty CRM.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Creates a new opportunity (sales deal) in Twenty CRM. Use when registering a deal to track; only the opportunity name is required, with optional stage, amount, currency, close date, and a company ID to link it to an existing company. Not idempotent: each call inserts a new deal, so repeated calls create duplicates.', idempotent: false },props: {name: Property.ShortText({@@ -56,17 +57,14 @@ export const createOpportunity = createAction({async run(context) {const { name, stage, amount, currency, closeDate, companyId } = context.propsValue;- return await twentyRequest(- context.auth,- HttpMethod.POST,- '/rest/opportunities',- {- name,- stage: stage ?? undefined,- amount: amount != null ? { amountMicros: Math.round(amount * 1_000_000), currencyCode: currency ?? 'USD' } : undefined,- closeDate: closeDate ?? undefined,- companyId: companyId ?? undefined,- },- );+ return await twentyApi.createOpportunity({+ auth: context.auth,+ name,+ stage,+ amount,+ currency,+ closeDate,+ companyId,+ });},});diff --git a/packages/pieces/community/twenty/src/lib/actions/find-company.ts b/packages/pieces/community/twenty/src/lib/actions/find-company.tsindex 100bc0a23f9..10c41bd2d23 100644--- a/packages/pieces/community/twenty/src/lib/actions/find-company.ts+++ b/packages/pieces/community/twenty/src/lib/actions/find-company.ts@@ -1,15 +1,16 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';import { twentyAuth } from '../auth';-import { twentyRequest, parseRecords } from '../common';+import { twentyApi } from '../common/api';+import { findCompanyOutputSchema } from '../output-schemas';-export const findCompany = createAction({+export const findCompanyAction = createAction({auth: twentyAuth,name: 'find_company',+ outputSchema: findCompanyOutputSchema,classification: 'SEARCH',displayName: 'Find Company',description: 'Searches for company records in Twenty CRM.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Looks up company records in Twenty CRM, optionally filtering by an exact-match company name and/or domain. Use to resolve a company to its record ID before updating or linking, or to check existence; leaving both filters empty returns all companies. Idempotent: a read-only query with no side effects.', idempotent: true },props: {name: Property.ShortText({@@ -25,23 +26,11 @@ export const findCompany = createAction({},async run(context) {const { name, domainName } = context.propsValue;- const queryParams: Record<string, string> = {};- if (name) {- queryParams['filter[name][eq]'] = name;- }- if (domainName) {- queryParams['filter[domainName][primaryLinkUrl][eq]'] = domainName;- }-- const body = await twentyRequest(- context.auth,- HttpMethod.GET,- '/rest/companies',- undefined,- queryParams,- );-- return parseRecords(body);+ return await twentyApi.findCompanies({+ auth: context.auth,+ name,+ domainName,+ });},});diff --git a/packages/pieces/community/twenty/src/lib/actions/find-person.ts b/packages/pieces/community/twenty/src/lib/actions/find-person.tsindex 487bc36a8d9..fc1b0055aab 100644--- a/packages/pieces/community/twenty/src/lib/actions/find-person.ts+++ b/packages/pieces/community/twenty/src/lib/actions/find-person.ts@@ -1,15 +1,16 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';import { twentyAuth } from '../auth';-import { twentyRequest, parseRecords } from '../common';+import { twentyApi } from '../common/api';+import { findPersonOutputSchema } from '../output-schemas';-export const findPerson = createAction({+export const findPersonAction = createAction({auth: twentyAuth,name: 'find_person',+ outputSchema: findPersonOutputSchema,classification: 'SEARCH',displayName: 'Find Person',description: 'Searches for person records in Twenty CRM.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Looks up person records in Twenty CRM, optionally filtering by an exact-match email, first name, and/or last name. Use to resolve a person to their record ID before updating, or to check existence; leaving all filters empty returns all people. Idempotent: a read-only query with no side effects.', idempotent: true },props: {email: Property.ShortText({@@ -30,26 +31,12 @@ export const findPerson = createAction({},async run(context) {const { email, firstName, lastName } = context.propsValue;- const queryParams: Record<string, string> = {};- if (email) {- queryParams['filter[emails][primaryEmail][eq]'] = email;- }- if (firstName) {- queryParams['filter[name][firstName][eq]'] = firstName;- }- if (lastName) {- queryParams['filter[name][lastName][eq]'] = lastName;- }-- const body = await twentyRequest(- context.auth,- HttpMethod.GET,- '/rest/people',- undefined,- queryParams,- );-- return parseRecords(body);+ return await twentyApi.findPeople({+ auth: context.auth,+ email,+ firstName,+ lastName,+ });},});diff --git a/packages/pieces/community/twenty/src/lib/actions/update-company.ts b/packages/pieces/community/twenty/src/lib/actions/update-company.tsindex 0505610ee3c..573ff2dd08e 100644--- a/packages/pieces/community/twenty/src/lib/actions/update-company.ts+++ b/packages/pieces/community/twenty/src/lib/actions/update-company.ts@@ -1,15 +1,16 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';import { twentyAuth } from '../auth';-import { twentyRequest } from '../common';+import { twentyApi } from '../common/api';+import { updateCompanyOutputSchema } from '../output-schemas';-export const updateCompany = createAction({+export const updateCompanyAction = createAction({auth: twentyAuth,name: 'update_company',+ outputSchema: updateCompanyOutputSchema,classification: 'WRITE',displayName: 'Update Company',description: 'Updates an existing company record in Twenty CRM.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Updates an existing company in Twenty CRM, identified by the required company ID (resolve it first with Find Company). Patches only the supplied name, domain, address, and/or employee count; if no fields are given it simply returns the current record. Idempotent: targets a fixed ID and re-applying the same field values leaves the record unchanged.', idempotent: true },props: {companyId: Property.ShortText({@@ -39,25 +40,13 @@ export const updateCompany = createAction({const { companyId, name, domainName, address, employees } =context.propsValue;- const body: Record<string, unknown> = {};- if (name) body['name'] = name;- if (domainName) body['domainName'] = { primaryLinkUrl: domainName, primaryLinkLabel: '' };- if (address) body['address'] = { addressStreet1: address };- if (employees != null) body['employees'] = employees;-- if (Object.keys(body).length === 0) {- return await twentyRequest(- context.auth,- HttpMethod.GET,- `/rest/companies/${companyId}`,- );- }-- return await twentyRequest(- context.auth,- HttpMethod.PATCH,- `/rest/companies/${companyId}`,- body,- );+ return await twentyApi.updateCompany({+ auth: context.auth,+ companyId,+ name,+ domainName,+ address,+ employees,+ });},});diff --git a/packages/pieces/community/twenty/src/lib/actions/update-person.ts b/packages/pieces/community/twenty/src/lib/actions/update-person.tsindex aa024edcfc7..15662ed2523 100644--- a/packages/pieces/community/twenty/src/lib/actions/update-person.ts+++ b/packages/pieces/community/twenty/src/lib/actions/update-person.ts@@ -1,15 +1,16 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';import { twentyAuth } from '../auth';-import { twentyRequest, parseSingleRecord } from '../common';+import { twentyApi } from '../common/api';+import { updatePersonOutputSchema } from '../output-schemas';-export const updatePerson = createAction({+export const updatePersonAction = createAction({auth: twentyAuth,name: 'update_person',+ outputSchema: updatePersonOutputSchema,classification: 'WRITE',displayName: 'Update Person',description: 'Updates an existing person record in Twenty CRM.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Updates an existing person in Twenty CRM, identified by the required person ID (resolve it first with Find Person). Patches only the supplied first name, last name, and/or email, merging name changes with the current record; if no fields are given it simply returns the current record. Idempotent: targets a fixed ID and re-applying the same field values leaves the record unchanged.', idempotent: true },props: {personId: Property.ShortText({@@ -33,37 +34,12 @@ export const updatePerson = createAction({async run(context) {const { personId, firstName, lastName, email } = context.propsValue;- const body: Record<string, unknown> = {};- if (firstName || lastName) {- const existing = await twentyRequest<Record<string, unknown>>(- context.auth,- HttpMethod.GET,- `/rest/people/${personId}`,- );- const personData = parseSingleRecord(existing);- const existingName = (personData['name'] as Record<string, string>) ?? {};- body['name'] = {- firstName: firstName ?? existingName['firstName'],- lastName: lastName ?? existingName['lastName'],- };- }- if (email) {- body['emails'] = { primaryEmail: email };- }-- if (Object.keys(body).length === 0) {- return await twentyRequest(- context.auth,- HttpMethod.GET,- `/rest/people/${personId}`,- );- }-- return await twentyRequest(- context.auth,- HttpMethod.PATCH,- `/rest/people/${personId}`,- body,- );+ return await twentyApi.updatePerson({+ auth: context.auth,+ personId,+ firstName,+ lastName,+ email,+ });},});diff --git a/packages/pieces/community/twenty/src/lib/auth.ts b/packages/pieces/community/twenty/src/lib/auth.tsindex cb20adf1929..ef195c90df2 100644--- a/packages/pieces/community/twenty/src/lib/auth.ts+++ b/packages/pieces/community/twenty/src/lib/auth.ts@@ -1,5 +1,5 @@-import { PieceAuth, Property } from '@activepieces/pieces-framework';-import { httpClient, HttpMethod } from '@activepieces/pieces-common';+import { AppConnectionType, PieceAuth, Property, tryCatch } from '@activepieces/pieces-framework';+import { twentyApi } from './common/api';export const twentyAuth = PieceAuth.CustomAuth({description:@@ -21,25 +21,16 @@ export const twentyAuth = PieceAuth.CustomAuth({}),},validate: async ({ auth }) => {- try {- const sanitizedUrl = auth.base_url.replace(/\/$/, '');- await httpClient.sendRequest({- method: HttpMethod.GET,- url: `${sanitizedUrl}/rest/people`,- headers: {- Authorization: `Bearer ${auth.api_key}`,- },- queryParams: {- 'page[size]': '1',- },- });- return { valid: true };- } catch (e) {+ const { error } = await tryCatch(() =>+ twentyApi.checkConnection({ auth: { type: AppConnectionType.CUSTOM_AUTH, props: auth } }),+ );+ if (error) {return {valid: false,error:'Could not connect to Twenty. Please verify your Instance URL and API Key.',};}+ return { valid: true };},});diff --git a/packages/pieces/community/twenty/src/lib/common/ai-props.ts b/packages/pieces/community/twenty/src/lib/common/ai-props.tsnew file mode 100644index 00000000000..74d223499a0--- /dev/null+++ b/packages/pieces/community/twenty/src/lib/common/ai-props.ts@@ -0,0 +1,111 @@+import { Property } from '@activepieces/pieces-framework';++function objectNamePlural<R extends boolean>({+ required,+ displayName = 'Object',+ description = 'Plural API name of the object, e.g. "companies", "people", "opportunities", "tasks", "notes", or a custom object\'s plural name. Use List Objects (the `namePlural` field) to find it.',+}: PropParams<R>) {+ return Property.ShortText({ displayName, description, required });+}++function recordId<R extends boolean>({+ required,+ displayName = 'Record ID',+ description = 'UUID of the record, from List Records, Create Record or Get Record (the `id` field).',+}: PropParams<R>) {+ return Property.ShortText({ displayName, description, required });+}++function recordIds<R extends boolean>({+ required,+ displayName = 'Record IDs',+ description = 'Record UUIDs of the same object, from List Records (the `id` field).',+}: PropParams<R>) {+ return Property.Array({ displayName, description, required });+}++function record<R extends boolean>({+ required,+ displayName = 'Record',+ description = 'Field values as a JSON object keyed by field name. Composite fields are objects, e.g. {"name": {"firstName": "Ada", "lastName": "Lovelace"}, "emails": {"primaryEmail": "[email protected]"}, "domainName": {"primaryLinkUrl": "https://acme.com"}, "amount": {"amountMicros": 5000000000, "currencyCode": "USD"}}. Relations take the related record\'s id, e.g. {"companyId": "<uuid>"}. Use Get Object to see field names and types.',+}: PropParams<R>) {+ return Property.Json({ displayName, description, required });+}++function filter<R extends boolean>({+ required,+ displayName = 'Filter',+ description = 'Twenty filter expression: field[comparator]:value, comma-separated for AND, or and(...), or(...), not(...). Comparators: eq, neq, in, containsAny, is (NULL / NOT_NULL), gt, gte, lt, lte, startsWith, endsWith, like, ilike (% wildcard). Composite fields use dot paths. Examples: emails.primaryEmail[eq]:"[email protected]", name.firstName[eq]:"Ada", domainName.primaryLinkUrl[ilike]:"%acme%", stage[in]:["MEETING","PROPOSAL"], createdAt[gte]:"2026-01-01". Use deletedAt[is]:NOT_NULL to find soft-deleted records.',+}: PropParams<R>) {+ return Property.LongText({ displayName, description, required });+}++function orderBy<R extends boolean>({+ required,+ displayName = 'Order By',+ description = 'Sort expression: field[direction], comma-separated. Directions: AscNullsFirst, AscNullsLast, DescNullsFirst, DescNullsLast. Example: createdAt[DescNullsLast].',+}: PropParams<R>) {+ return Property.ShortText({ displayName, description, required });+}++function limit<R extends boolean>({+ required,+ displayName = 'Limit',+ description = 'Maximum number of items to return (1-200). Defaults to 60.',+}: PropParams<R>) {+ return Property.Number({ displayName, description, required });+}++function startingAfter<R extends boolean>({+ required,+ displayName = 'Starting After',+ description = 'Cursor for the next page: pass `pageInfo.endCursor` from the previous call, with the same filters. Omit for the first page.',+}: PropParams<R>) {+ return Property.ShortText({ displayName, description, required });+}++function depth<R extends boolean>({+ required,+ displayName = 'Depth',+ description = "Relation depth: 0 returns only the record's own fields (relations as ids), 1 also embeds directly related records. Defaults to 0.",+}: PropParams<R>) {+ return Property.StaticDropdown({+ displayName,+ description,+ required,+ options: {+ disabled: false,+ options: [+ { label: '0', value: 0 },+ { label: '1', value: 1 },+ ],+ },+ });+}++function fields<R extends boolean>({+ required,+ displayName = 'Fields',+ description = 'Comma-separated field names to return, e.g. "id,name,emails,companyId". `id` is always returned. Omit to return every field.',+}: PropParams<R>) {+ return Property.ShortText({ displayName, description, required });+}++export const twentyAiProps = {+ objectNamePlural,+ recordId,+ recordIds,+ record,+ filter,+ orderBy,+ limit,+ startingAfter,+ depth,+ fields,+};++export type PropParams<R extends boolean> = {+ required: R;+ displayName?: string;+ description?: string;+};diff --git a/packages/pieces/community/twenty/src/lib/common/api.ts b/packages/pieces/community/twenty/src/lib/common/api.tsnew file mode 100644index 00000000000..08d2d56f261--- /dev/null+++ b/packages/pieces/community/twenty/src/lib/common/api.ts@@ -0,0 +1,630 @@+import { HttpMethod, QueryParams } from '@activepieces/pieces-common';++import { twentyClient } from './client';++import type {+ TwentyAuthValue,+ TwentyDuplicateConnection,+ TwentyEnvelope,+ TwentyListResponse,+ TwentyMetadataItem,+ TwentyMetadataPage,+ TwentyMetadataSingle,+ TwentyPageInfo,+ TwentyPersonResponse,+ TwentyRecord,+ TwentyRecordList,+ TwentyRecordPage,+ TwentyResponse,+} from './types';++async function checkConnection({ auth }: { auth: TwentyAuthValue }): Promise<void> {+ await twentyClient.request<unknown>({+ auth,+ method: HttpMethod.GET,+ path: '/rest/people',+ query: { 'page[size]': '1' },+ });+}++async function createPerson({+ auth,+ firstName,+ lastName,+ email,+}: CreatePersonParams & { auth: TwentyAuthValue }): Promise<TwentyResponse> {+ return await twentyClient.request<TwentyResponse>({+ auth,+ method: HttpMethod.POST,+ path: '/rest/people',+ body: {+ name: {+ firstName,+ lastName,+ },+ emails: email ? { primaryEmail: email } : undefined,+ },+ });+}++async function createCompany({+ auth,+ name,+ domainName,+ address,+ employees,+}: CompanyFields & { auth: TwentyAuthValue; name: string }): Promise<TwentyResponse> {+ return await twentyClient.request<TwentyResponse>({+ auth,+ method: HttpMethod.POST,+ path: '/rest/companies',+ body: {+ name,+ domainName: domainName ? { primaryLinkUrl: domainName, primaryLinkLabel: '' } : undefined,+ address: address ? { addressStreet1: address } : undefined,+ employees: employees ?? undefined,+ },+ });+}++async function createOpportunity({+ auth,+ name,+ stage,+ amount,+ currency,+ closeDate,+ companyId,+}: CreateOpportunityParams & { auth: TwentyAuthValue }): Promise<TwentyResponse> {+ return await twentyClient.request<TwentyResponse>({+ auth,+ method: HttpMethod.POST,+ path: '/rest/opportunities',+ body: {+ name,+ stage: stage ?? undefined,+ amount:+ amount != null+ ? { amountMicros: Math.round(amount * 1_000_000), currencyCode: currency ?? 'USD' }+ : undefined,+ closeDate: closeDate ?? undefined,+ companyId: companyId ?? undefined,+ },+ });+}++async function findCompanies({+ auth,+ name,+ domainName,+}: {+ auth: TwentyAuthValue;+ name?: string;+ domainName?: string;+}): Promise<TwentyRecord[]> {+ return await listRecordItems({+ auth,+ path: '/rest/companies',+ query: filterQuery({+ conditions: {+ name,+ 'domainName.primaryLinkUrl': domainName+ ? [...new Set([domainName, domainName.replace(/^https?:\/\//i, '')])]+ : undefined,+ },+ }),+ });+}++async function findPeople({+ auth,+ email,+ firstName,+ lastName,+}: {+ auth: TwentyAuthValue;+ email?: string;+ firstName?: string;+ lastName?: string;+}): Promise<TwentyRecord[]> {+ return await listRecordItems({+ auth,+ path: '/rest/people',+ query: filterQuery({+ conditions: {+ 'emails.primaryEmail': email,+ 'name.firstName': firstName,+ 'name.lastName': lastName,+ },+ }),+ });+}++async function listRecentCompanies({ auth }: { auth: TwentyAuthValue }): Promise<TwentyRecord[]> {+ return await listRecordItems({ auth, path: '/rest/companies', query: RECENT_QUERY });+}++async function listRecentPeople({ auth }: { auth: TwentyAuthValue }): Promise<TwentyRecord[]> {+ return await listRecordItems({ auth, path: '/rest/people', query: RECENT_QUERY });+}++async function updateCompany({+ auth,+ companyId,+ name,+ domainName,+ address,+ employees,+}: CompanyFields & {+ auth: TwentyAuthValue;+ companyId: string;+ name?: string;+}): Promise<TwentyResponse> {+ const body: Record<string, unknown> = {};+ if (name) body['name'] = name;+ if (domainName) body['domainName'] = { primaryLinkUrl: domainName, primaryLinkLabel: '' };+ if (address) body['address'] = { addressStreet1: address };+ if (employees != null) body['employees'] = employees;++ if (Object.keys(body).length === 0) {+ return await twentyClient.request<TwentyResponse>({+ auth,+ method: HttpMethod.GET,+ path: `/rest/companies/${companyId}`,+ });+ }++ return await twentyClient.request<TwentyResponse>({+ auth,+ method: HttpMethod.PATCH,+ path: `/rest/companies/${companyId}`,+ body,+ });+}++async function updatePerson({+ auth,+ personId,+ firstName,+ lastName,+ email,+}: Partial<CreatePersonParams> & {+ auth: TwentyAuthValue;+ personId: string;+}): Promise<TwentyPersonResponse> {+ const body: Record<string, unknown> = {};+ if (firstName || lastName) {+ const existing = await getPerson({ auth, personId });+ const existingName = existing.data?.person?.name ?? {};+ body['name'] = {+ firstName: firstName ?? existingName.firstName,+ lastName: lastName ?? existingName.lastName,+ };+ }+ if (email) {+ body['emails'] = { primaryEmail: email };+ }++ if (Object.keys(body).length === 0) {+ return await getPerson({ auth, personId });+ }++ return await twentyClient.request<TwentyPersonResponse>({+ auth,+ method: HttpMethod.PATCH,+ path: `/rest/people/${personId}`,+ body,+ });+}++async function listRecords({+ auth,+ objectNamePlural,+ filter,+ orderBy,+ limit,+ depth,+ fields,+ startingAfter,+}: ListRecordsParams & { auth: TwentyAuthValue }): Promise<TwentyRecordList> {+ const response = await twentyClient.request<TwentyRecordPage>({+ auth,+ method: HttpMethod.GET,+ path: recordsPath({ objectNamePlural }),+ query: compactQuery({+ values: { filter, order_by: orderBy, limit, depth, fields, starting_after: startingAfter },+ }),+ });+ return {+ records: firstValue({ envelope: response }) ?? [],+ pageInfo: response.pageInfo,+ totalCount: response.totalCount,+ };+}++async function getRecord({+ auth,+ objectNamePlural,+ recordId,+ depth,+ fields,+}: RecordParams & { auth: TwentyAuthValue; depth?: number; fields?: string }): Promise<+ TwentyRecord | undefined+> {+ const response = await twentyClient.request<TwentyEnvelope<TwentyRecord>>({+ auth,+ method: HttpMethod.GET,+ path: recordsPath({ objectNamePlural, recordId }),+ query: compactQuery({ values: { depth, fields } }),+ });+ return firstValue({ envelope: response });+}++async function createRecord({+ auth,+ objectNamePlural,+ record,+ upsert,+}: {+ auth: TwentyAuthValue;+ objectNamePlural: string;+ record: Record<string, unknown>;+ upsert?: boolean;+}): Promise<TwentyRecord | undefined> {+ const response = await twentyClient.request<TwentyEnvelope<TwentyRecord>>({+ auth,+ method: HttpMethod.POST,+ path: recordsPath({ objectNamePlural }),+ query: compactQuery({ values: { upsert: upsert ? true : undefined } }),+ body: record,+ });+ return firstValue({ envelope: response });+}++async function createRecords({+ auth,+ objectNamePlural,+ records,+ upsert,+}: {+ auth: TwentyAuthValue;+ objectNamePlural: string;+ records: Record<string, unknown>[];+ upsert?: boolean;+}): Promise<{ records: TwentyRecord[]; count: number }> {+ const response = await twentyClient.request<TwentyEnvelope<TwentyRecord[]>>({+ auth,+ method: HttpMethod.POST,+ path: `/rest/batch/${encodeURIComponent(objectNamePlural)}`,+ query: compactQuery({ values: { upsert: upsert ? true : undefined } }),+ body: records,+ });+ const created = firstValue({ envelope: response }) ?? [];+ return { records: created, count: created.length };+}++async function updateRecord({+ auth,+ objectNamePlural,+ recordId,+ record,+}: RecordParams & { auth: TwentyAuthValue; record: Record<string, unknown> }): Promise<+ TwentyRecord | undefined+> {+ const response = await twentyClient.request<TwentyEnvelope<TwentyRecord>>({+ auth,+ method: HttpMethod.PATCH,+ path: recordsPath({ objectNamePlural, recordId }),+ body: record,+ });+ return firstValue({ envelope: response });+}++async function deleteRecord({+ auth,+ objectNamePlural,+ recordId,+ permanent,+}: RecordParams & { auth: TwentyAuthValue; permanent?: boolean }): Promise<+ TwentyRecord | undefined+> {+ const response = await twentyClient.request<TwentyEnvelope<TwentyRecord>>({+ auth,+ method: HttpMethod.DELETE,+ path: recordsPath({ objectNamePlural, recordId }),+ query: compactQuery({ values: { soft_delete: permanent ? undefined : true } }),+ });+ return firstValue({ envelope: response });+}++async function restoreRecord({+ auth,+ objectNamePlural,+ recordId,+}: RecordParams & { auth: TwentyAuthValue }): Promise<TwentyRecord | undefined> {+ const response = await twentyClient.request<TwentyEnvelope<TwentyRecord>>({+ auth,+ method: HttpMethod.PATCH,+ path: `${recordsPath({ objectNamePlural, recordId })}/restore`,+ });+ return firstValue({ envelope: response });+}++async function findDuplicateRecords({+ auth,+ objectNamePlural,+ recordIds,+ records,+}: {+ auth: TwentyAuthValue;+ objectNamePlural: string;+ recordIds?: string[];+ records?: Record<string, unknown>[];+}): Promise<{+ results: { duplicates: TwentyRecord[]; totalCount?: number; pageInfo?: TwentyPageInfo }[];+}> {+ const response = await twentyClient.request<{ data: TwentyDuplicateConnection[] }>({+ auth,+ method: HttpMethod.POST,+ path: `${recordsPath({ objectNamePlural })}/duplicates`,+ body: { ids: recordIds, data: records },+ });+ return {+ results: response.data.map((connection) => {+ const duplicates = Object.entries(connection).find(([key]) =>+ key.endsWith('Duplicates'),+ )?.[1];+ return {+ duplicates: Array.isArray(duplicates) ? duplicates : [],+ totalCount: connection.totalCount,+ pageInfo: connection.pageInfo,+ };+ }),+ };+}++async function mergeRecords({+ auth,+ objectNamePlural,+ recordIds,+ conflictPriorityIndex,+ dryRun,+}: {+ auth: TwentyAuthValue;+ objectNamePlural: string;+ recordIds: string[];+ conflictPriorityIndex: number;+ dryRun?: boolean;+}): Promise<TwentyRecord | undefined> {+ const response = await twentyClient.request<TwentyEnvelope<TwentyRecord>>({+ auth,+ method: HttpMethod.PATCH,+ path: `${recordsPath({ objectNamePlural })}/merge`,+ body: { ids: recordIds, conflictPriorityIndex, dryRun: dryRun ?? false },+ });+ return firstValue({ envelope: response });+}++async function groupRecords({+ auth,+ objectNamePlural,+ groupBy,+ aggregate,+ filter,+ orderBy,+ limit,+}: {+ auth: TwentyAuthValue;+ objectNamePlural: string;+ groupBy: Record<string, unknown>[];+ aggregate?: string[];+ filter?: string;+ orderBy?: string;+ limit?: number;+}): Promise<{ groups: Record<string, unknown>[]; count: number }> {+ const groups = await twentyClient.request<Record<string, unknown>[]>({+ auth,+ method: HttpMethod.GET,+ path: `${recordsPath({ objectNamePlural })}/groupBy`,+ query: compactQuery({+ values: {+ group_by: JSON.stringify(groupBy),+ aggregate: aggregate ? JSON.stringify(aggregate) : undefined,+ filter,+ order_by: orderBy,+ limit,+ },+ }),+ });+ return { groups, count: groups.length };+}++async function listObjects({+ auth,+ limit,+ startingAfter,+}: MetadataListParams & { auth: TwentyAuthValue }): Promise<+ MetadataList & { objects: TwentyMetadataItem[] }+> {+ const page = await listMetadata({ auth, resource: 'objects', limit, startingAfter });+ return { objects: page.items, pageInfo: page.pageInfo, totalCount: page.totalCount };+}++async function getObject({+ auth,+ objectId,+}: {+ auth: TwentyAuthValue;+ objectId: string;+}): Promise<TwentyMetadataItem> {+ const response = await twentyClient.request<TwentyMetadataSingle>({+ auth,+ method: HttpMethod.GET,+ path: `/rest/metadata/objects/${encodeURIComponent(objectId)}`,+ });+ return response.data?.object ?? response;+}++async function listFields({+ auth,+ limit,+ startingAfter,+}: MetadataListParams & { auth: TwentyAuthValue }): Promise<+ MetadataList & { fields: TwentyMetadataItem[] }+> {+ const page = await listMetadata({ auth, resource: 'fields', limit, startingAfter });+ return { fields: page.items, pageInfo: page.pageInfo, totalCount: page.totalCount };+}++async function getPerson({+ auth,+ personId,+}: {+ auth: TwentyAuthValue;+ personId: string;+}): Promise<TwentyPersonResponse> {+ return await twentyClient.request<TwentyPersonResponse>({+ auth,+ method: HttpMethod.GET,+ path: `/rest/people/${personId}`,+ });+}++async function listRecordItems({+ auth,+ path,+ query,+}: {+ auth: TwentyAuthValue;+ path: string;+ query: QueryParams;+}): Promise<TwentyRecord[]> {+ const response = await twentyClient.request<TwentyListResponse>({+ auth,+ method: HttpMethod.GET,+ path,+ query,+ });+ const items = response.data ?? response;+ if (Array.isArray(items)) return items;+ return Object.values(items).find(Array.isArray) ?? [];+}++async function listMetadata({+ auth,+ resource,+ limit,+ startingAfter,+}: MetadataListParams & { auth: TwentyAuthValue; resource: string }): Promise<+ MetadataList & { items: TwentyMetadataItem[] }+> {+ const response = await twentyClient.request<TwentyMetadataPage>({+ auth,+ method: HttpMethod.GET,+ path: `/rest/metadata/${resource}`,+ query: compactQuery({ values: { limit, starting_after: startingAfter } }),+ });+ const items = Array.isArray(response.data)+ ? response.data+ : firstValue({ envelope: { data: response.data } }) ?? [];+ return { items, pageInfo: response.pageInfo, totalCount: response.totalCount };+}++function recordsPath({+ objectNamePlural,+ recordId,+}: {+ objectNamePlural: string;+ recordId?: string;+}): string {+ const base = `/rest/${encodeURIComponent(objectNamePlural)}`;+ return recordId ? `${base}/${encodeURIComponent(recordId)}` : base;+}++function filterQuery({+ conditions,+}: {+ conditions: Record<string, string | string[] | undefined>;+}): QueryParams {+ const filter = Object.entries(conditions)+ .filter(([, value]) => value)+ .map(+ ([field, value]) =>+ `${field}[${Array.isArray(value) ? 'in' : 'eq'}]:${JSON.stringify(value)}`,+ )+ .join(',');+ return filter ? { filter } : {};+}++function firstValue<T>({ envelope }: { envelope: TwentyEnvelope<T> }): T | undefined {+ return Object.values(envelope.data)[0];+}++function compactQuery({+ values,+}: {+ values: Record<string, string | number | boolean | null | undefined>;+}): QueryParams {+ return Object.fromEntries(+ Object.entries(values)+ .filter(([, value]) => value !== undefined && value !== null && value !== '')+ .map(([key, value]) => [key, String(value)]),+ );+}++export const twentyApi = {+ checkConnection,+ createPerson,+ createCompany,+ createOpportunity,+ findCompanies,+ findPeople,+ listRecentCompanies,+ listRecentPeople,+ updateCompany,+ updatePerson,+ listRecords,+ getRecord,+ createRecord,+ createRecords,+ updateRecord,+ deleteRecord,+ restoreRecord,+ findDuplicateRecords,+ mergeRecords,+ groupRecords,+ listObjects,+ getObject,+ listFields,+};++const RECENT_QUERY: QueryParams = { order_by: 'createdAt[DescNullsLast]', limit: '100' };++type CreatePersonParams = { firstName: string; lastName?: string; email?: string };++type CompanyFields = { domainName?: string; address?: string; employees?: number };++type CreateOpportunityParams = {+ name: string;+ stage?: string;+ amount?: number;+ currency?: string;+ closeDate?: string;+ companyId?: string;+};++type RecordParams = { objectNamePlural: string; recordId: string };++type ListRecordsParams = {+ objectNamePlural: string;+ filter?: string;+ orderBy?: string;+ limit?: number;+ depth?: number;+ fields?: string;+ startingAfter?: string;+};++type MetadataListParams = { limit?: number; startingAfter?: string };++type MetadataList = { pageInfo?: TwentyPageInfo; totalCount?: number };diff --git a/packages/pieces/community/twenty/src/lib/common/client.ts b/packages/pieces/community/twenty/src/lib/common/client.tsnew file mode 100644index 00000000000..fd390203652--- /dev/null+++ b/packages/pieces/community/twenty/src/lib/common/client.ts@@ -0,0 +1,36 @@+import { httpClient, HttpMethod, QueryParams } from '@activepieces/pieces-common';++import type { TwentyAuthValue } from './types';++function baseUrl({ auth }: { auth: TwentyAuthValue }): string {+ return auth.props.base_url.replace(/\/$/, '');+}++async function request<T>({+ auth,+ method,+ path,+ query,+ body,+}: RequestParams & { auth: TwentyAuthValue }): Promise<T> {+ const response = await httpClient.sendRequest<T>({+ method,+ url: `${baseUrl({ auth })}${path}`,+ headers: {+ Authorization: `Bearer ${auth.props.api_key}`,+ 'Content-Type': 'application/json',+ },+ body,+ queryParams: query,+ });+ return response.body;+}++export const twentyClient = { baseUrl, request };++type RequestParams = {+ method: HttpMethod;+ path: string;+ query?: QueryParams;+ body?: unknown;+};diff --git a/packages/pieces/community/twenty/src/lib/common/index.ts b/packages/pieces/community/twenty/src/lib/common/index.tsdeleted file mode 100644index 25b816721ca..00000000000--- a/packages/pieces/community/twenty/src/lib/common/index.ts+++ /dev/null@@ -1,53 +0,0 @@-import { httpClient, HttpMethod } from '@activepieces/pieces-common';--type TwentyAuth = {- props: {- base_url: string;- api_key: string;- };-};--function getBaseUrl(auth: TwentyAuth): string {- return auth.props.base_url.replace(/\/$/, '');-}--function getHeaders(auth: TwentyAuth): Record<string, string> {- return {- Authorization: `Bearer ${auth.props.api_key}`,- 'Content-Type': 'application/json',- };-}--export async function twentyRequest<T = unknown>(- auth: TwentyAuth,- method: HttpMethod,- path: string,- body?: unknown,- queryParams?: Record<string, string>,-): Promise<T> {- const response = await httpClient.sendRequest({- method,- url: `${getBaseUrl(auth)}${path}`,- headers: getHeaders(auth),- body,- queryParams,- });- return response.body as T;-}--export function parseSingleRecord(body: unknown): Record<string, unknown> {- const data = body as Record<string, unknown>;- if (data?.['data'] != null && typeof data['data'] === 'object' && !Array.isArray(data['data'])) {- return data['data'] as Record<string, unknown>;- }- return data;-}--export function parseRecords(body: unknown): Record<string, unknown>[] {- const data = body as Record<string, unknown>;- const items = data?.['data'] ?? body;- if (Array.isArray(items)) return items;- const nested = items as Record<string, unknown>;- const firstArrayValue = Object.values(nested).find((v) => Array.isArray(v));- return (firstArrayValue as Record<string, unknown>[]) ?? [];-}diff --git a/packages/pieces/community/twenty/src/lib/common/types.ts b/packages/pieces/community/twenty/src/lib/common/types.tsnew file mode 100644index 00000000000..150a248e46f--- /dev/null+++ b/packages/pieces/community/twenty/src/lib/common/types.ts@@ -0,0 +1,63 @@+import type { AppConnectionType } from '@activepieces/pieces-framework';++export type TwentyAuthValue = {+ type: AppConnectionType.CUSTOM_AUTH;+ props: { base_url: string; api_key: string };+};++export type TwentyRecord = {+ id?: string;+ createdAt?: string;+ [key: string]: unknown;+};++export type TwentyPersonName = { firstName?: string; lastName?: string };++export type TwentyPerson = TwentyRecord & { name?: TwentyPersonName };++export type TwentyResponse = { data?: Record<string, unknown> };++export type TwentyPersonResponse = { data?: { person?: TwentyPerson } };++export type TwentyListResponse = { data?: Record<string, unknown> };++export type TwentyPageInfo = {+ hasNextPage?: boolean;+ hasPreviousPage?: boolean;+ startCursor?: string | null;+ endCursor?: string | null;+};++export type TwentyEnvelope<T> = { data: Record<string, T> };++export type TwentyRecordPage = TwentyEnvelope<TwentyRecord[]> & {+ pageInfo?: TwentyPageInfo;+ totalCount?: number;+};++export type TwentyRecordList = {+ records: TwentyRecord[];+ pageInfo?: TwentyPageInfo;+ totalCount?: number;+};++export type TwentyDuplicateConnection = {+ totalCount?: number;+ pageInfo?: TwentyPageInfo;+ [key: string]: TwentyRecord[] | TwentyPageInfo | number | undefined;+};++export type TwentyMetadataItem = {+ id: string;+ [key: string]: unknown;+};++export type TwentyMetadataPage = {+ data: TwentyMetadataItem[] | Record<string, TwentyMetadataItem[]>;+ pageInfo?: TwentyPageInfo;+ totalCount?: number;+};++export type TwentyMetadataSingle = TwentyMetadataItem & {+ data?: { object?: TwentyMetadataItem };+};diff --git a/packages/pieces/community/twenty/src/lib/output-schemas.ts b/packages/pieces/community/twenty/src/lib/output-schemas.tsnew file mode 100644index 00000000000..c97012a6faa--- /dev/null+++ b/packages/pieces/community/twenty/src/lib/output-schemas.ts@@ -0,0 +1,294 @@+import { OutputSchema } from '@activepieces/pieces-framework';++const actorFields: OutputSchema['fields'] = [+ { key: 'source', label: 'Source' },+ { key: 'name', label: 'Name' },+ { key: 'workspaceMemberId', label: 'Workspace Member ID' },+];++const linkFields: OutputSchema['fields'] = [+ { key: 'primaryLinkUrl', label: 'URL', format: 'url' },+ { key: 'primaryLinkLabel', label: 'Label' },+];++const amountFields: OutputSchema['fields'] = [+ { key: 'amountMicros', label: 'Amount (Micros)', format: 'number' },+ { key: 'currencyCode', label: 'Currency Code' },+];++const recordSystemFields: OutputSchema['fields'] = [+ { key: 'position', label: 'Position', format: 'number' },+ { key: 'createdBy', label: 'Created By', children: actorFields },+ { key: 'updatedBy', label: 'Updated By', children: actorFields },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },+ { key: 'deletedAt', label: 'Deleted At', format: 'datetime' },+];++const recordFields: OutputSchema['fields'] = [+ {+ key: 'id',+ label: 'Record ID',+ description: "The record's own fields follow, named as in Get Object.",+ },+ ...recordSystemFields,+];++const companyFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Company ID' },+ { key: 'name', label: 'Name' },+ { key: 'domainName', label: 'Domain', children: linkFields },+ {+ key: 'address',+ label: 'Address',+ children: [+ { key: 'addressStreet1', label: 'Street 1' },+ { key: 'addressStreet2', label: 'Street 2' },+ { key: 'addressCity', label: 'City' },+ { key: 'addressState', label: 'State' },+ { key: 'addressPostcode', label: 'Postcode' },+ { key: 'addressCountry', label: 'Country' },+ { key: 'addressLat', label: 'Latitude', format: 'number' },+ { key: 'addressLng', label: 'Longitude', format: 'number' },+ ],+ },+ { key: 'linkedinLink', label: 'LinkedIn', children: linkFields },+ { key: 'annualRevenue', label: 'Annual Revenue', children: amountFields },+ { key: 'accountOwnerId', label: 'Account Owner ID' },+ ...recordSystemFields,+];++const personFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Person ID' },+ {+ key: 'name',+ label: 'Name',+ children: [+ { key: 'firstName', label: 'First Name' },+ { key: 'lastName', label: 'Last Name' },+ ],+ },+ {+ key: 'emails',+ label: 'Emails',+ children: [+ { key: 'primaryEmail', label: 'Primary Email', format: 'email' },+ { key: 'additionalEmails', label: 'Additional Emails' },+ ],+ },+ {+ key: 'phones',+ label: 'Phones',+ children: [+ { key: 'primaryPhoneNumber', label: 'Primary Phone Number' },+ { key: 'primaryPhoneCountryCode', label: 'Country Code' },+ { key: 'primaryPhoneCallingCode', label: 'Calling Code' },+ ],+ },+ { key: 'jobTitle', label: 'Job Title' },+ { key: 'companyId', label: 'Company ID' },+ { key: 'linkedinLink', label: 'LinkedIn', children: linkFields },+ { key: 'avatarUrl', label: 'Avatar URL', format: 'image' },+ ...recordSystemFields,+];++const opportunityFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Opportunity ID' },+ { key: 'name', label: 'Name' },+ { key: 'stage', label: 'Stage' },+ { key: 'amount', label: 'Amount', children: amountFields },+ { key: 'closeDate', label: 'Close Date', format: 'datetime' },+ { key: 'companyId', label: 'Company ID' },+ { key: 'pointOfContactId', label: 'Point of Contact ID' },+ { key: 'ownerId', label: 'Owner ID' },+ ...recordSystemFields,+];++const pageInfoField: OutputSchema['fields'][number] = {+ key: 'pageInfo',+ label: 'Page Info',+ children: [+ { key: 'hasNextPage', label: 'Has Next Page', format: 'boolean' },+ { key: 'hasPreviousPage', label: 'Has Previous Page', format: 'boolean' },+ { key: 'startCursor', label: 'Start Cursor' },+ { key: 'endCursor', label: 'End Cursor' },+ ],+};++const totalCountField: OutputSchema['fields'][number] = {+ key: 'totalCount',+ label: 'Total Count',+ format: 'number',+};++const metadataFieldFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Field ID' },+ { key: 'name', label: 'Name' },+ { key: 'label', label: 'Label' },+ { key: 'type', label: 'Type' },+ { key: 'description', label: 'Description' },+ { key: 'objectMetadataId', label: 'Object ID' },+ { key: 'isActive', label: 'Is Active', format: 'boolean' },+ { key: 'isSystem', label: 'Is System', format: 'boolean' },+ { key: 'isNullable', label: 'Is Nullable', format: 'boolean' },+ { key: 'isUnique', label: 'Is Unique', format: 'boolean' },+ { key: 'isUIReadOnly', label: 'Is Read Only', format: 'boolean' },+ { key: 'defaultValue', label: 'Default Value' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },+];++const metadataObjectFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Object ID' },+ { key: 'nameSingular', label: 'Name (Singular)' },+ { key: 'namePlural', label: 'Name (Plural)' },+ { key: 'labelSingular', label: 'Label (Singular)' },+ { key: 'labelPlural', label: 'Label (Plural)' },+ { key: 'description', label: 'Description' },+ { key: 'isActive', label: 'Is Active', format: 'boolean' },+ { key: 'isSystem', label: 'Is System', format: 'boolean' },+ { key: 'isRemote', label: 'Is Remote', format: 'boolean' },+ { key: 'labelIdentifierFieldMetadataId', label: 'Label Field ID' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },+ { key: 'fields', label: 'Fields', labelKey: 'name', listItems: metadataFieldFields },+];++export const createCompanyOutputSchema: OutputSchema = {+ fields: [+ { key: 'company', label: 'Company', value: 'data.createCompany', children: companyFields },+ ],+};++export const updateCompanyOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'company',+ label: 'Updated Company',+ value: 'data.updateCompany',+ children: companyFields,+ },+ {+ key: 'unchangedCompany',+ label: 'Company (No Fields Given)',+ value: 'data.company',+ children: companyFields,+ },+ ],+};++export const findCompanyOutputSchema: OutputSchema = {+ itemLabel: '{name}',+ fields: [{ key: 'companies', label: 'Companies', value: '', listItems: companyFields }],+};++export const newCompanyOutputSchema: OutputSchema = { fields: companyFields };++export const createContactOutputSchema: OutputSchema = {+ fields: [{ key: 'person', label: 'Person', value: 'data.createPerson', children: personFields }],+};++export const updatePersonOutputSchema: OutputSchema = {+ fields: [+ { key: 'person', label: 'Updated Person', value: 'data.updatePerson', children: personFields },+ {+ key: 'unchangedPerson',+ label: 'Person (No Fields Given)',+ value: 'data.person',+ children: personFields,+ },+ ],+};++export const findPersonOutputSchema: OutputSchema = {+ itemLabel: '{name.firstName} {name.lastName}',+ fields: [{ key: 'people', label: 'People', value: '', listItems: personFields }],+};++export const newPersonOutputSchema: OutputSchema = { fields: personFields };++export const createOpportunityOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'opportunity',+ label: 'Opportunity',+ value: 'data.createOpportunity',+ children: opportunityFields,+ },+ ],+};++export const twentyGetRecordOutputSchema: OutputSchema = { fields: recordFields };++export const twentyCreateRecordOutputSchema: OutputSchema = { fields: recordFields };++export const twentyUpdateRecordOutputSchema: OutputSchema = { fields: recordFields };++export const twentyRestoreRecordOutputSchema: OutputSchema = { fields: recordFields };++export const twentyMergeRecordsOutputSchema: OutputSchema = { fields: recordFields };++export const twentyDeleteRecordOutputSchema: OutputSchema = {+ fields: [{ key: 'id', label: 'Deleted Record ID' }],+};++export const twentyListRecordsOutputSchema: OutputSchema = {+ fields: [+ { key: 'records', label: 'Records', labelKey: 'id', listItems: recordFields },+ pageInfoField,+ totalCountField,+ ],+};++export const twentyCreateRecordsOutputSchema: OutputSchema = {+ fields: [+ { key: 'records', label: 'Created Records', labelKey: 'id', listItems: recordFields },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const twentyFindDuplicateRecordsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'results',+ label: 'Results',+ description: 'One result per input record, in input order.',+ listItems: [+ { key: 'duplicates', label: 'Duplicates', labelKey: 'id', listItems: recordFields },+ totalCountField,+ pageInfoField,+ ],+ },+ ],+};++export const twentyGroupRecordsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'groups',+ label: 'Groups',+ description:+ 'Each group also holds one key per requested aggregate, e.g. countNotEmptyId, with the value as a string.',+ listItems: [{ key: 'groupByDimensionValues', label: 'Group Values' }],+ },+ { key: 'count', label: 'Group Count', format: 'number' },+ ],+};++export const twentyListObjectsOutputSchema: OutputSchema = {+ fields: [+ { key: 'objects', label: 'Objects', labelKey: 'namePlural', listItems: metadataObjectFields },+ pageInfoField,+ totalCountField,+ ],+};++export const twentyGetObjectOutputSchema: OutputSchema = { fields: metadataObjectFields };++export const twentyListFieldsOutputSchema: OutputSchema = {+ fields: [+ { key: 'fields', label: 'Fields', labelKey: 'name', listItems: metadataFieldFields },+ pageInfoField,+ totalCountField,+ ],+};diff --git a/packages/pieces/community/twenty/src/lib/triggers/new-company.ts b/packages/pieces/community/twenty/src/lib/triggers/new-company.tsindex 856dbbe9060..03944d1653d 100644--- a/packages/pieces/community/twenty/src/lib/triggers/new-company.ts+++ b/packages/pieces/community/twenty/src/lib/triggers/new-company.ts@@ -5,13 +5,13 @@ import {} from '@activepieces/pieces-framework';import {DedupeStrategy,- HttpMethod,Polling,pollingHelper,} from '@activepieces/pieces-common';import dayjs from 'dayjs';import { twentyAuth } from '../auth';-import { twentyRequest, parseRecords } from '../common';+import { twentyApi } from '../common/api';+import { newCompanyOutputSchema } from '../output-schemas';const polling: Polling<AppConnectionValueForAuthProperty<typeof twentyAuth>,@@ -19,26 +19,19 @@ const polling: Polling<> = {strategy: DedupeStrategy.TIMEBASED,items: async ({ auth }) => {- const body = await twentyRequest(- auth,- HttpMethod.GET,- '/rest/companies',- undefined,- { 'sort[createdAt]': 'desc', 'limit': '100' },- );-- const records = parseRecords(body);+ const records = await twentyApi.listRecentCompanies({ auth });return records.map((item) => ({- epochMilliSeconds: dayjs(item['createdAt'] as string).valueOf(),+ epochMilliSeconds: dayjs(item.createdAt).valueOf(),data: item,}));},};-export const newCompany = createTrigger({+export const newCompanyTrigger = createTrigger({auth: twentyAuth,name: 'new_company',+ outputSchema: newCompanyOutputSchema,classification: 'READ',displayName: 'New Company',description: 'Triggers when a new company is created in Twenty CRM.',diff --git a/packages/pieces/community/twenty/src/lib/triggers/new-person.ts b/packages/pieces/community/twenty/src/lib/triggers/new-person.tsindex 5d3705f7e42..bc07ad8efae 100644--- a/packages/pieces/community/twenty/src/lib/triggers/new-person.ts+++ b/packages/pieces/community/twenty/src/lib/triggers/new-person.ts@@ -5,13 +5,13 @@ import {} from '@activepieces/pieces-framework';import {DedupeStrategy,- HttpMethod,Polling,pollingHelper,} from '@activepieces/pieces-common';import dayjs from 'dayjs';import { twentyAuth } from '../auth';-import { twentyRequest, parseRecords } from '../common';+import { twentyApi } from '../common/api';+import { newPersonOutputSchema } from '../output-schemas';const polling: Polling<AppConnectionValueForAuthProperty<typeof twentyAuth>,@@ -19,26 +19,19 @@ const polling: Polling<> = {strategy: DedupeStrategy.TIMEBASED,items: async ({ auth }) => {- const body = await twentyRequest(- auth,- HttpMethod.GET,- '/rest/people',- undefined,- { 'sort[createdAt]': 'desc', 'limit': '100' },- );-- const records = parseRecords(body);+ const records = await twentyApi.listRecentPeople({ auth });return records.map((item) => ({- epochMilliSeconds: dayjs(item['createdAt'] as string).valueOf(),+ epochMilliSeconds: dayjs(item.createdAt).valueOf(),data: item,}));},};-export const newPerson = createTrigger({+export const newPersonTrigger = createTrigger({auth: twentyAuth,name: 'new_person',+ outputSchema: newPersonOutputSchema,classification: 'READ',displayName: 'New Person',description: 'Triggers when a new person is created in Twenty CRM.',