Skip to content

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

feat(google-contacts): let agents manage contacts, groups and photos (#15695)

Odai Ahmad66b00d8d26ce
diff --git a/packages/pieces/community/google-contacts/package.json b/packages/pieces/community/google-contacts/package.json
index 2f44aee7207..e5276ee66fb 100644
--- a/packages/pieces/community/google-contacts/package.json
+++ b/packages/pieces/community/google-contacts/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-google-contacts",
- "version": "0.5.0",
+ "version": "0.5.1",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"dependencies": {
diff --git a/packages/pieces/community/google-contacts/src/i18n/translation.json b/packages/pieces/community/google-contacts/src/i18n/translation.json
index 43bc7d89914..bb6f78ba098 100644
--- a/packages/pieces/community/google-contacts/src/i18n/translation.json
+++ b/packages/pieces/community/google-contacts/src/i18n/translation.json
@@ -3,10 +3,47 @@
"Add Contact": "Add Contact",
"Update Contact": "Update Contact",
"Search Contacts": "Search Contacts",
+ "Create Contact": "Create Contact",
+ "Update Contact Fields": "Update Contact Fields",
+ "Get Contact": "Get Contact",
+ "List Contacts": "List Contacts",
+ "Delete Contact": "Delete Contact",
+ "Batch Get Contacts": "Batch Get Contacts",
+ "Batch Create Contacts": "Batch Create Contacts",
+ "Batch Update Contacts": "Batch Update Contacts",
+ "Batch Delete Contacts": "Batch Delete Contacts",
+ "Update Contact Photo": "Update Contact Photo",
+ "Delete Contact Photo": "Delete Contact Photo",
+ "List Contact Groups": "List Contact Groups",
+ "Get Contact Group": "Get Contact Group",
+ "Batch Get Contact Groups": "Batch Get Contact Groups",
+ "Create Contact Group": "Create Contact Group",
+ "Update Contact Group": "Update Contact Group",
+ "Delete Contact Group": "Delete Contact Group",
+ "Add Or Remove Contact Group Members": "Add Or Remove Contact Group Members",
"Custom API Call": "Custom API Call",
"Add a contact to a Google Contacts account": "Add a contact to a Google Contacts account",
"Update a contact in Google Contacts account.": "Update a contact in Google Contacts account.",
"Search contacts in Google Contacts account.": "Search contacts in Google Contacts account.",
+ "Create a new contact in the connected Google account.": "Create a new contact in the connected Google account.",
+ "Update only the supplied fields on an existing contact.": "Update only the supplied fields on an existing contact.",
+ "Search the connected account contacts by a plain-text query.": "Search the connected account contacts by a plain-text query.",
+ "Read a single contact by its resource name.": "Read a single contact by its resource name.",
+ "List the contacts of the connected Google account.": "List the contacts of the connected Google account.",
+ "Permanently delete a contact by its resource name.": "Permanently delete a contact by its resource name.",
+ "Read up to 200 contacts in one call by their resource names.": "Read up to 200 contacts in one call by their resource names.",
+ "Create up to 200 contacts in a single call.": "Create up to 200 contacts in a single call.",
+ "Update up to 200 contacts in a single call from full Person objects.": "Update up to 200 contacts in a single call from full Person objects.",
+ "Permanently delete up to 500 contacts in a single call.": "Permanently delete up to 500 contacts in a single call.",
+ "Set the photo of an existing contact from base64 image bytes.": "Set the photo of an existing contact from base64 image bytes.",
+ "Remove the photo of an existing contact.": "Remove the photo of an existing contact.",
+ "List every contact group of the connected Google account.": "List every contact group of the connected Google account.",
+ "Read one contact group, optionally with its member resource names.": "Read one contact group, optionally with its member resource names.",
+ "Read up to 200 contact groups in one call by their resource names.": "Read up to 200 contact groups in one call by their resource names.",
+ "Create a contact group, or return the existing one with that name.": "Create a contact group, or return the existing one with that name.",
+ "Rename an existing user-created contact group.": "Rename an existing user-created contact group.",
+ "Delete a user-created contact group.": "Delete a user-created contact group.",
+ "Add contacts to a contact group or remove them from it.": "Add contacts to a contact group or remove them from it.",
"Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
"First Name": "First Name",
"Middle Name": "Middle Name",
@@ -21,14 +58,29 @@
"Query": "Query",
"Read Mask": "Read Mask",
"Page Size": "Page Size",
+ "Nickname": "Nickname",
+ "Email Addresses": "Email Addresses",
+ "Phone Numbers": "Phone Numbers",
+ "Notes": "Notes",
+ "Max Results": "Max Results",
+ "Resource Names": "Resource Names",
+ "Contacts": "Contacts",
+ "Photo Bytes": "Photo Bytes",
+ "Max Members": "Max Members",
+ "Group Name": "Group Name",
+ "New Group Name": "New Group Name",
+ "Also Delete Contacts": "Also Delete Contacts",
+ "Contact Group Resource Name": "Contact Group Resource Name",
+ "Contacts To Add": "Contacts To Add",
+ "Contacts To Remove": "Contacts To Remove",
"Method": "Method",
"Headers": "Headers",
"Query Parameters": "Query Parameters",
"Body Type": "Body Type",
"Body": "Body",
- "Response is Binary ?": "Response is Binary ?",
- "No Error on Failure": "No Error on Failure",
- "Timeout (in seconds)": "Timeout (in seconds)",
+ "Response is Binary": "Response is Binary",
+ "Return Error as Output": "Return Error as Output",
+ "Timeout": "Timeout",
"Follow redirects": "Follow redirects",
"The first name of the contact": "The first name of the contact",
"The middle name of the contact": "The middle name of the contact",
@@ -43,8 +95,37 @@
"The plain-text query for the request.The query is used to match prefix phrases of the fields on a person. For example, a person with name \"foo name\" matches queries such as \"f\", \"fo\", \"foo\", \"foo n\", \"nam\", etc., but not \"oo n\".": "The plain-text query for the request.The query is used to match prefix phrases of the fields on a person. For example, a person with name \"foo name\" matches queries such as \"f\", \"fo\", \"foo\", \"foo n\", \"nam\", etc., but not \"oo n\".",
"A field mask to restrict which fields on each person are returned.": "A field mask to restrict which fields on each person are returned.",
"The number of results to return. Maximum 30.": "The number of results to return. Maximum 30.",
+ "Array of email address strings, for example [\"[email protected]\"]. A single address still has to be wrapped in an array.": "Array of email address strings, for example [\"[email protected]\"]. A single address still has to be wrapped in an array.",
+ "Array of phone number strings, for example [\"+1 555 0100\"]. A single number still has to be wrapped in an array.": "Array of phone number strings, for example [\"+1 555 0100\"]. A single number still has to be wrapped in an array.",
+ "Free-text notes stored on the contact biography.": "Free-text notes stored on the contact biography.",
+ "Opaque contact resource name such as people/c12345. Resolve it with List Contacts or Search Contacts.": "Opaque contact resource name such as people/c12345. Resolve it with List Contacts or Search Contacts.",
+ "Array of email address strings, for example [\"[email protected]\"]. Replaces every email address stored on the contact. Leave empty to keep the stored addresses.": "Array of email address strings, for example [\"[email protected]\"]. Replaces every email address stored on the contact. Leave empty to keep the stored addresses.",
+ "Array of phone number strings, for example [\"+1 555 0100\"]. Replaces every phone number stored on the contact. Leave empty to keep the stored numbers.": "Array of phone number strings, for example [\"+1 555 0100\"]. Replaces every phone number stored on the contact. Leave empty to keep the stored numbers.",
+ "Plain-text query prefix-matched against contact fields such as name, email and phone number.": "Plain-text query prefix-matched against contact fields such as name, email and phone number.",
+ "Number of results to return, maximum 30. Defaults to 30.": "Number of results to return, maximum 30. Defaults to 30.",
+ "Maximum number of contacts to return. Defaults to 200.": "Maximum number of contacts to return. Defaults to 200.",
+ "Opaque contact resource name such as people/c12345. Resolve it with List Contacts or Search Contacts. Deletion cannot be undone.": "Opaque contact resource name such as people/c12345. Resolve it with List Contacts or Search Contacts. Deletion cannot be undone.",
+ "Up to 200 opaque contact resource names such as people/c12345, resolved with List Contacts or Search Contacts.": "Up to 200 opaque contact resource names such as people/c12345, resolved with List Contacts or Search Contacts.",
+ "Up to 200 contacts to create. Each needs at least a name, an email or a phone number.": "Up to 200 contacts to create. Each needs at least a name, an email or a phone number.",
+ "JSON array of up to 200 full Person objects taken from Batch Get Contacts, each keeping its resourceName and etag, with the fields to change edited in place.": "JSON array of up to 200 full Person objects taken from Batch Get Contacts, each keeping its resourceName and etag, with the fields to change edited in place.",
+ "Up to 500 opaque contact resource names such as people/c12345. Every listed contact is deleted permanently and cannot be restored.": "Up to 500 opaque contact resource names such as people/c12345. Every listed contact is deleted permanently and cannot be restored.",
+ "Base64-encoded JPEG, PNG or WebP image. A data URL prefix is accepted and stripped.": "Base64-encoded JPEG, PNG or WebP image. A data URL prefix is accepted and stripped.",
+ "Opaque contact group resource name such as contactGroups/abc123, or a system group like contactGroups/myContacts. Resolve it with List Contact Groups.": "Opaque contact group resource name such as contactGroups/abc123, or a system group like contactGroups/myContacts. Resolve it with List Contact Groups.",
+ "How many member resource names to return. Defaults to 0, which returns none.": "How many member resource names to return. Defaults to 0, which returns none.",
+ "Up to 200 opaque contact group resource names such as contactGroups/abc123, resolved with List Contact Groups.": "Up to 200 opaque contact group resource names such as contactGroups/abc123, resolved with List Contact Groups.",
+ "How many member resource names to return per group. Defaults to 0, which returns none.": "How many member resource names to return per group. Defaults to 0, which returns none.",
+ "Name of the contact group to find or create.": "Name of the contact group to find or create.",
+ "Opaque contact group resource name such as contactGroups/abc123. Resolve it with List Contact Groups.": "Opaque contact group resource name such as contactGroups/abc123. Resolve it with List Contact Groups.",
+ "When enabled, every contact in the group is permanently deleted as well. Leave off to remove only the group.": "When enabled, every contact in the group is permanently deleted as well. Leave off to remove only the group.",
+ "Opaque contact group resource name such as contactGroups/abc123, contactGroups/myContacts or contactGroups/starred. Resolve it with List Contact Groups.": "Opaque contact group resource name such as contactGroups/abc123, contactGroups/myContacts or contactGroups/starred. Resolve it with List Contact Groups.",
+ "Opaque contact resource names such as people/c12345 to add to the group.": "Opaque contact resource names such as people/c12345 to add to the group.",
+ "Opaque contact resource names such as people/c12345 to remove from the group.": "Opaque contact resource names such as people/c12345 to remove from the group.",
"Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.",
+ "Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.",
"Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",
+ "On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.",
+ "Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).",
+ "Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",
"Names": "Names",
"Job Title / Company": "Job Title / Company",
"addresses": "addresses",
@@ -82,10 +163,6 @@
"PUT": "PUT",
"DELETE": "DELETE",
"HEAD": "HEAD",
- "None": "None",
- "JSON": "JSON",
- "Form Data": "Form Data",
- "Raw": "Raw",
"New Or Updated Contact": "New Or Updated Contact",
"Triggers when there is a new or updated contact": "Triggers when there is a new or updated contact"
}
\ No newline at end of file
diff --git a/packages/pieces/community/google-contacts/src/index.ts b/packages/pieces/community/google-contacts/src/index.ts
index b09affdb2cb..67456a968b1 100644
--- a/packages/pieces/community/google-contacts/src/index.ts
+++ b/packages/pieces/community/google-contacts/src/index.ts
@@ -1,25 +1,59 @@
import { createCustomApiCallAction } from '@activepieces/pieces-common';
-import {
- OAuth2PropertyValue,
- PieceAuth,
- createPiece,
-} from '@activepieces/pieces-framework';
+import { createPiece } from '@activepieces/pieces-framework';
import { PieceCategory } from '@activepieces/pieces-framework';
import { googleContactsAddContactAction } from './lib/action/create-contact';
import { googleContactsUpdateContactAction } from './lib/action/update-contact';
import { googleContactsSearchContactsAction } from './lib/action/search-contact';
+import { googleContactsCreateContactAction } from './lib/action/create-contact-agent';
+import { googleContactsUpdateContactFieldsAction } from './lib/action/update-contact-fields';
+import { googleContactsSearchContactsAtomicAction } from './lib/action/search-contacts';
+import { googleContactsGetContactAction } from './lib/action/get-contact';
+import { googleContactsListContactsAction } from './lib/action/list-contacts';
+import { googleContactsDeleteContactAction } from './lib/action/delete-contact';
+import { googleContactsBatchGetContactsAction } from './lib/action/batch-get-contacts';
+import { googleContactsBatchCreateContactsAction } from './lib/action/batch-create-contacts';
+import { googleContactsBatchUpdateContactsAction } from './lib/action/batch-update-contacts';
+import { googleContactsBatchDeleteContactsAction } from './lib/action/batch-delete-contacts';
+import { googleContactsUpdateContactPhotoAction } from './lib/action/update-contact-photo';
+import { googleContactsDeleteContactPhotoAction } from './lib/action/delete-contact-photo';
+import { googleContactsListContactGroupsAction } from './lib/action/list-contact-groups';
+import { googleContactsGetContactGroupAction } from './lib/action/get-contact-group';
+import { googleContactsBatchGetContactGroupsAction } from './lib/action/batch-get-contact-groups';
+import { googleContactsCreateContactGroupAction } from './lib/action/create-contact-group';
+import { googleContactsUpdateContactGroupAction } from './lib/action/update-contact-group';
+import { googleContactsDeleteContactGroupAction } from './lib/action/delete-contact-group';
+import { googleContactsModifyContactGroupMembersAction } from './lib/action/modify-contact-group-members';
import { googleContactsCommon } from './lib/common';
import { googleContactNewOrUpdatedContact } from './lib/trigger/new-contact';
import { googleContactsAuth } from './lib/auth';
export const googleContacts = createPiece({
- minimumSupportedRelease: '0.30.0',
+ minimumSupportedRelease: '0.87.0',
logoUrl: 'https://cdn.activepieces.com/pieces/google-contacts.png',
categories: [PieceCategory.SALES_AND_CRM],
actions: [
googleContactsAddContactAction,
googleContactsUpdateContactAction,
googleContactsSearchContactsAction,
+ googleContactsCreateContactAction,
+ googleContactsUpdateContactFieldsAction,
+ googleContactsSearchContactsAtomicAction,
+ googleContactsGetContactAction,
+ googleContactsListContactsAction,
+ googleContactsDeleteContactAction,
+ googleContactsBatchGetContactsAction,
+ googleContactsBatchCreateContactsAction,
+ googleContactsBatchUpdateContactsAction,
+ googleContactsBatchDeleteContactsAction,
+ googleContactsUpdateContactPhotoAction,
+ googleContactsDeleteContactPhotoAction,
+ googleContactsListContactGroupsAction,
+ googleContactsGetContactGroupAction,
+ googleContactsBatchGetContactGroupsAction,
+ googleContactsCreateContactGroupAction,
+ googleContactsUpdateContactGroupAction,
+ googleContactsDeleteContactGroupAction,
+ googleContactsModifyContactGroupMembersAction,
createCustomApiCallAction({
baseUrl: () => googleContactsCommon.baseUrl,
auth: googleContactsAuth,
diff --git a/packages/pieces/community/google-contacts/src/lib/action/batch-create-contacts.ts b/packages/pieces/community/google-contacts/src/lib/action/batch-create-contacts.ts
new file mode 100644
index 00000000000..e65065ad4e5
--- /dev/null
+++ b/packages/pieces/community/google-contacts/src/lib/action/batch-create-contacts.ts
@@ -0,0 +1,134 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { googleContactsAuth } from '../auth';
+import { googleContactsApi } from '../common';
+import { googleContactsPerson } from '../common/person';
+import { batchCreateContactsOutputSchema } from '../output-schemas';
+
+function optionalString({ source, key }: { source: unknown; key: string }): string | undefined {
+ const value = googleContactsApi.readString({ source, path: [key] });
+ if (value === undefined || value.trim().length === 0) {
+ return undefined;
+ }
+ return value.trim();
+}
+
+export const googleContactsBatchCreateContactsAction = createAction({
+ auth: googleContactsAuth,
+ name: 'batch_create_contacts',
+ classification: 'WRITE',
+ displayName: 'Batch Create Contacts',
+ description: 'Create up to 200 contacts in a single call.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates up to 200 new Google Contacts people in one call and returns the created contacts split into succeeded and failed collections. Use it instead of repeated Create Contact calls when importing a list; a whole-call success can still contain per-contact failures, so always read the failed collection. Not idempotent — every call creates new people, so a retry after a partial failure duplicates the ones that already succeeded.',
+ idempotent: false,
+ },
+ outputSchema: batchCreateContactsOutputSchema,
+ props: {
+ contacts: Property.Array({
+ displayName: 'Contacts',
+ description: 'Up to 200 contacts to create. Each needs at least a name, an email or a phone number.',
+ required: true,
+ properties: {
+ firstName: Property.ShortText({ displayName: 'First Name', required: false }),
+ middleName: Property.ShortText({ displayName: 'Middle Name', required: false }),
+ lastName: Property.ShortText({ displayName: 'Last Name', required: false }),
+ email: Property.ShortText({ displayName: 'Email Address', required: false }),
+ phoneNumber: Property.ShortText({ displayName: 'Phone Number', required: false }),
+ company: Property.ShortText({ displayName: 'Company', required: false }),
+ jobTitle: Property.ShortText({ displayName: 'Job Title', required: false }),
+ },
+ }),
+ },
+ async run(context) {
+ const entries = context.propsValue.contacts;
+ if (!Array.isArray(entries) || entries.length === 0) {
+ throw new Error('Contacts must contain at least one entry.');
+ }
+ if (entries.length > 200) {
+ throw new Error(
+ `Contacts accepts at most 200 entries, received ${entries.length}.`
+ );
+ }
+ const people = entries.map((entry, index) => {
+ const email = optionalString({ source: entry, key: 'email' });
+ const phoneNumber = optionalString({ source: entry, key: 'phoneNumber' });
+ const { person, fields } = googleContactsPerson.buildPerson({
+ input: {
+ firstName: optionalString({ source: entry, key: 'firstName' }),
+ middleName: optionalString({ source: entry, key: 'middleName' }),
+ lastName: optionalString({ source: entry, key: 'lastName' }),
+ emails: email === undefined ? [] : [email],
+ phoneNumbers: phoneNumber === undefined ? [] : [phoneNumber],
+ company: optionalString({ source: entry, key: 'company' }),
+ jobTitle: optionalString({ source: entry, key: 'jobTitle' }),
+ },
+ });
+ if (fields.length === 0) {
+ throw new Error(
+ `Contact ${index + 1} needs at least one of first name, last name, email address or phone number.`
+ );
+ }
+ return { contactPerson: person };
+ });
+ let response: Record<string, unknown>;
+ try {
+ response = await googleContactsApi.sendRequest({
+ accessToken: context.auth.access_token,
+ method: HttpMethod.POST,
+ path: '/people:batchCreateContacts',
+ body: {
+ contacts: people,
+ readMask: googleContactsApi.contactReadMask.join(','),
+ },
+ });
+ } catch (error) {
+ throw googleContactsApi.toApiError({
+ error,
+ operation: 'Batch Create Contacts',
+ });
+ }
+ const created = googleContactsApi.readArray({
+ source: response,
+ path: ['createdPeople'],
+ });
+ const succeeded = created
+ .map((item, index) => ({ item, index }))
+ .filter((entry) => !googleContactsApi.isFailedItem({ response: entry.item }))
+ .map((entry) => {
+ const payload = googleContactsApi.readValue({
+ source: entry.item,
+ path: ['person'],
+ });
+ return {
+ requestIndex: entry.index + 1,
+ resourceName: googleContactsApi.readString({
+ source: payload,
+ path: ['resourceName'],
+ }),
+ contact: googleContactsPerson.summarizePerson({ person: payload }),
+ };
+ });
+ const failed = created
+ .map((item, index) => ({ item, index }))
+ .filter((entry) => googleContactsApi.isFailedItem({ response: entry.item }))
+ .map((entry) => ({
+ requestIndex: entry.index + 1,
+ status: googleContactsApi.describeStatus({
+ status: googleContactsApi.readValue({
+ source: entry.item,
+ path: ['status'],
+ }),
+ }),
+ }));
+ return {
+ succeeded,
+ failed,
+ succeededCount: succeeded.length,
+ failedCount: failed.length,
+ requestedCount: people.length,
+ };
+ },
+});
diff --git a/packages/pieces/community/google-contacts/src/lib/action/batch-delete-contacts.ts b/packages/pieces/community/google-contacts/src/lib/action/batch-delete-contacts.ts
new file mode 100644
index 00000000000..28d9d7cbf72
--- /dev/null
+++ b/packages/pieces/community/google-contacts/src/lib/action/batch-delete-contacts.ts
@@ -0,0 +1,53 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { googleContactsAuth } from '../auth';
+import { googleContactsApi } from '../common';
+import { batchDeleteContactsOutputSchema } from '../output-schemas';
+
+export const googleContactsBatchDeleteContactsAction = createAction({
+ auth: googleContactsAuth,
+ name: 'batch_delete_contacts',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Batch Delete Contacts',
+ description: 'Permanently delete up to 500 contacts in a single call.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Permanently deletes up to 500 Google Contacts people in one call from a list of opaque resourceNames. Irreversible and unrecoverable — the People API has no trash and there is no per-contact confirmation in the response, so verify every resourceName with Batch Get Contacts or List Contacts before calling and prefer Delete Contact when removing a single person. Not idempotent: a repeat call fails on contacts that are already gone.',
+ idempotent: false,
+ },
+ outputSchema: batchDeleteContactsOutputSchema,
+ props: {
+ resourceNames: Property.Array({
+ displayName: 'Resource Names',
+ description:
+ 'Up to 500 opaque contact resource names such as people/c12345. Every listed contact is deleted permanently and cannot be restored.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const resourceNames = googleContactsApi.toStringList({
+ value: context.propsValue.resourceNames,
+ label: 'Resource Names',
+ });
+ googleContactsApi.assertBatchSize({
+ values: resourceNames,
+ max: 500,
+ label: 'Resource Names',
+ });
+ try {
+ await googleContactsApi.sendRequest({
+ accessToken: context.auth.access_token,
+ method: HttpMethod.POST,
+ path: '/people:batchDeleteContacts',
+ body: { resourceNames },
+ });
+ } catch (error) {
+ throw googleContactsApi.toApiError({
+ error,
+ operation: 'Batch Delete Contacts',
+ });
+ }
+ return { deleted: true, resourceNames, count: resourceNames.length };
+ },
+});
diff --git a/packages/pieces/community/google-contacts/src/lib/action/batch-get-contact-groups.ts b/packages/pieces/community/google-contacts/src/lib/action/batch-get-contact-groups.ts
new file mode 100644
index 00000000000..1cc3880c57d
--- /dev/null
+++ b/packages/pieces/community/google-contacts/src/lib/action/batch-get-contact-groups.ts
@@ -0,0 +1,89 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { googleContactsAuth } from '../auth';
+import { googleContactsApi } from '../common';
+import { googleContactsGroup } from '../common/contact-group';
+import { batchGetContactGroupsOutputSchema } from '../output-schemas';
+
+export const googleContactsBatchGetContactGroupsAction = createAction({
+ auth: googleContactsAuth,
+ name: 'batch_get_contact_groups',
+ classification: 'READ',
+ displayName: 'Batch Get Contact Groups',
+ description: 'Read up to 200 contact groups in one call by their resource names.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Reads up to 200 Google Contacts groups in one call from a list of opaque resourceNames, returning succeeded and failed collections. Use it instead of repeated Get Contact Group calls; a whole-call success can still contain per-group failures, so always read the failed collection. Resolve the resource names with List Contact Groups. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: batchGetContactGroupsOutputSchema,
+ props: {
+ resourceNames: Property.Array({
+ displayName: 'Resource Names',
+ description:
+ 'Up to 200 opaque contact group resource names such as contactGroups/abc123, resolved with List Contact Groups.',
+ required: true,
+ }),
+ maxMembers: Property.Number({
+ displayName: 'Max Members',
+ description:
+ 'How many member resource names to return per group. Defaults to 0, which returns none.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const resourceNames = googleContactsApi.toStringList({
+ value: context.propsValue.resourceNames,
+ label: 'Resource Names',
+ });
+ googleContactsApi.assertBatchSize({
+ values: resourceNames,
+ max: 200,
+ label: 'Resource Names',
+ });
+ const maxMembers = Math.max(0, context.propsValue.maxMembers ?? 0);
+ let response: Record<string, unknown>;
+ try {
+ response = await googleContactsApi.sendRequest({
+ accessToken: context.auth.access_token,
+ method: HttpMethod.GET,
+ path: '/contactGroups:batchGet',
+ queryParams: {
+ groupFields: googleContactsApi.contactGroupFields.join(','),
+ maxMembers: String(maxMembers),
+ },
+ repeatedQueryParams: { resourceNames },
+ });
+ } catch (error) {
+ throw googleContactsApi.toApiError({
+ error,
+ operation: 'Batch Get Contact Groups',
+ });
+ }
+ const items = googleContactsApi
+ .readArray({ source: response, path: ['responses'] })
+ .map((item, index) => ({
+ resourceName:
+ googleContactsApi.readString({
+ source: item,
+ path: ['requestedResourceName'],
+ }) ??
+ resourceNames[index] ??
+ '',
+ response: item,
+ }));
+ const { succeeded, failed } = googleContactsApi.splitItemResponses({
+ items,
+ payloadKey: 'contactGroup',
+ });
+ return {
+ succeeded: succeeded.map((item) =>
+ googleContactsGroup.summarizeGroup({ group: item.payload })
+ ),
+ failed,
+ succeededCount: succeeded.length,
+ failedCount: failed.length,
+ };
+ },
+});
diff --git a/packages/pieces/community/google-contacts/src/lib/action/batch-get-contacts.ts b/packages/pieces/community/google-contacts/src/lib/action/batch-get-contacts.ts
new file mode 100644
index 00000000000..4d22c62e2a9
--- /dev/null
+++ b/packages/pieces/community/google-contacts/src/lib/action/batch-get-contacts.ts
@@ -0,0 +1,83 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { googleContactsAuth } from '../auth';
+import { googleContactsApi } from '../common';
+import { googleContactsPerson } from '../common/person';
+import { batchGetContactsOutputSchema } from '../output-schemas';
+
+export const googleContactsBatchGetContactsAction = createAction({
+ auth: googleContactsAuth,
+ name: 'batch_get_contacts',
+ classification: 'READ',
+ displayName: 'Batch Get Contacts',
+ description: 'Read up to 200 contacts in one call by their resource names.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Reads up to 200 Google Contacts people in one call from a list of opaque resourceNames and returns each full contact with its current etag, split into succeeded and failed collections. Use it instead of repeated Get Contact calls, and as the input source for Batch Update Contacts. A whole-call success can still contain per-contact failures, so always read the failed collection. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: batchGetContactsOutputSchema,
+ props: {
+ resourceNames: Property.Array({
+ displayName: 'Resource Names',
+ description:
+ 'Up to 200 opaque contact resource names such as people/c12345, resolved with List Contacts or Search Contacts.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const resourceNames = googleContactsApi.toStringList({
+ value: context.propsValue.resourceNames,
+ label: 'Resource Names',
+ });
+ googleContactsApi.assertBatchSize({
+ values: resourceNames,
+ max: 200,
+ label: 'Resource Names',
+ });
+ let response: Record<string, unknown>;
+ try {
+ response = await googleContactsApi.sendRequest({
+ accessToken: context.auth.access_token,
+ method: HttpMethod.GET,
+ path: '/people:batchGet',
+ queryParams: {
+ personFields: googleContactsApi.contactReadMask.join(','),
+ },
+ repeatedQueryParams: { resourceNames },
+ });
+ } catch (error) {
+ throw googleContactsApi.toApiError({
+ error,
+ operation: 'Batch Get Contacts',
+ });
+ }
+ const items = googleContactsApi
+ .readArray({ source: response, path: ['responses'] })
+ .map((item, index) => ({
+ resourceName:
+ googleContactsApi.readString({
+ source: item,
+ path: ['requestedResourceName'],
+ }) ??
+ resourceNames[index] ??
+ '',
+ response: item,
+ }));
+ const { succeeded, failed } = googleContactsApi.splitItemResponses({
+ items,
+ payloadKey: 'person',
+ });
+ return {
+ succeeded: succeeded.map((item) => ({
+ resourceName: item.resourceName,
+ contact: googleContactsPerson.summarizePerson({ person: item.payload }),
+ person: item.payload,
+ })),
+ failed,
+ succeededCount: succeeded.length,
+ failedCount: failed.length,
+ };
+ },
+});
diff --git a/packages/pieces/community/google-contacts/src/lib/action/batch-update-contacts.ts b/packages/pieces/community/google-contacts/src/lib/action/batch-update-contacts.ts
new file mode 100644
index 00000000000..77f6f88b634
--- /dev/null
+++ b/packages/pieces/community/google-contacts/src/lib/action/batch-update-contacts.ts
@@ -0,0 +1,167 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { googleContactsAuth } from '../auth';
+import { googleContactsApi } from '../common';
+import { googleContactsPerson } from '../common/person';
+import { batchUpdateContactsOutputSchema } from '../output-schemas';
+
+function toPerson({ entry, index }: { entry: unknown; index: number }): {
+ resourceName: string;
+ person: Record<string, unknown>;
+ fields: string[];
+} {
+ const record = googleContactsApi.readRecord({ source: entry, path: [] });
+ if (record === undefined) {
+ throw new Error(`Contact ${index + 1} must be a Person object.`);
+ }
+ const resourceName = googleContactsApi.readString({
+ source: record,
+ path: ['resourceName'],
+ });
+ const etag = googleContactsApi.readString({ source: record, path: ['etag'] });
+ if (resourceName === undefined || etag === undefined) {
+ throw new Error(
+ `Contact ${index + 1} must carry both resourceName and etag exactly as returned by Batch Get Contacts.`
+ );
+ }
+ const fields = Object.keys(record).filter((key) =>
+ googleContactsApi.updatablePersonFields.includes(key)
+ );
+ const person = Object.fromEntries(
+ Object.entries(record).filter(
+ ([key]) =>
+ key === 'etag' ||
+ key === 'resourceName' ||
+ googleContactsApi.updatablePersonFields.includes(key)
+ )
+ );
+ return { resourceName, person, fields };
+}
+
+function groupBySignature({
+ parsed,
+}: {
+ parsed: { resourceName: string; person: Record<string, unknown>; fields: string[] }[];
+}): { updateMask: string; contacts: Record<string, Record<string, unknown>> }[] {
+ const groups = new Map<string, Record<string, Record<string, unknown>>>();
+ for (const item of parsed) {
+ const signature = [...item.fields].sort().join(',');
+ const existing = groups.get(signature);
+ if (existing === undefined) {
+ groups.set(signature, { [item.resourceName]: item.person });
+ } else {
+ existing[item.resourceName] = item.person;
+ }
+ }
+ return [...groups.entries()].map(([updateMask, contacts]) => ({
+ updateMask,
+ contacts,
+ }));
+}
+
+export const googleContactsBatchUpdateContactsAction = createAction({
+ auth: googleContactsAuth,
+ name: 'batch_update_contacts',
+ classification: 'WRITE',
+ displayName: 'Batch Update Contacts',
+ description: 'Update up to 200 contacts in a single call from full Person objects.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Updates up to 200 Google Contacts people in one call. Feed it the full Person objects returned by Batch Get Contacts, each still carrying its own resourceName and etag, with the values you want changed edited in place. The people are grouped by which field groups they carry and one request is issued per group, so a person carrying only a phone number and a person carrying only an email can be updated together; each request uses the field mask of its own group. Within a group the mask is applied to every person in it, so never hand-build partial Person objects here — a group a person no longer carries is erased on that person. Prefer Update Contact Fields for a single contact. Because the work is split across requests, this action can partially apply: one group can be written while another is rejected outright. It therefore does not throw when a request fails — it records every contact in that request under failed and carries on. Never treat a returned result as wholesale success and never assume an absent error means everything applied; always read failed and failedCount, which also cover per-contact rejections such as stale etags. Every submitted person must carry at least one updatable field group. Before retrying, re-read the people so the already-updated ones carry fresh etags.',
+ idempotent: true,
+ },
+ outputSchema: batchUpdateContactsOutputSchema,
+ props: {
+ contacts: Property.Json({
+ displayName: 'Contacts',
+ description:
+ 'JSON array of up to 200 full Person objects taken from Batch Get Contacts, each keeping its resourceName and etag, with the fields to change edited in place.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const entries = context.propsValue.contacts;
+ if (!Array.isArray(entries) || entries.length === 0) {
+ throw new Error(
+ 'Contacts must be a JSON array holding at least one Person object.'
+ );
+ }
+ if (entries.length > 200) {
+ throw new Error(
+ `Contacts accepts at most 200 entries, received ${entries.length}.`
+ );
+ }
+ const parsed = entries.map((entry, index) => toPerson({ entry, index }));
+ const withoutGroups = parsed
+ .filter((item) => item.fields.length === 0)
+ .map((item) => item.resourceName);
+ if (withoutGroups.length > 0) {
+ throw new Error(
+ `Every submitted person must carry at least one updatable field group, because a person with no group has nothing to update. These people carry none: ${withoutGroups.join(
+ ', '
+ )}.`
+ );
+ }
+ const groups = groupBySignature({ parsed });
+ const succeeded: { resourceName: string; contact: Record<string, unknown>; person: unknown }[] =
+ [];
+ const failed: { resourceName: string; status: string; updateMask: string }[] = [];
+ for (const group of groups) {
+ let response: Record<string, unknown>;
+ try {
+ response = await googleContactsApi.sendRequest({
+ accessToken: context.auth.access_token,
+ method: HttpMethod.POST,
+ path: '/people:batchUpdateContacts',
+ body: {
+ contacts: group.contacts,
+ updateMask: group.updateMask,
+ readMask: googleContactsApi.contactReadMask.join(','),
+ },
+ });
+ } catch (error) {
+ const status = googleContactsApi.toApiError({
+ error,
+ operation: `Batch Update Contacts (field mask ${group.updateMask})`,
+ }).message;
+ for (const resourceName of Object.keys(group.contacts)) {
+ failed.push({ resourceName, status, updateMask: group.updateMask });
+ }
+ continue;
+ }
+ const updateResult = googleContactsApi.readRecord({
+ source: response,
+ path: ['updateResult'],
+ });
+ const items = Object.entries(updateResult ?? {}).map(
+ ([resourceName, value]) => ({ resourceName, response: value })
+ );
+ const split = googleContactsApi.splitItemResponses({
+ items,
+ payloadKey: 'person',
+ });
+ for (const item of split.succeeded) {
+ succeeded.push({
+ resourceName: item.resourceName,
+ contact: googleContactsPerson.summarizePerson({ person: item.payload }),
+ person: item.payload,
+ });
+ }
+ for (const item of split.failed) {
+ failed.push({
+ resourceName: item.resourceName,
+ status: item.status,
+ updateMask: group.updateMask,
+ });
+ }
+ }
+ return {
+ succeeded,
+ failed,
+ succeededCount: succeeded.length,
+ failedCount: failed.length,
+ updateMasks: groups.map((group) => group.updateMask),
+ };
+ },
+});
diff --git a/packages/pieces/community/google-contacts/src/lib/action/create-contact-agent.ts b/packages/pieces/community/google-contacts/src/lib/action/create-contact-agent.ts
new file mode 100644
index 00000000000..6feaa42c31f
--- /dev/null
+++ b/packages/pieces/community/google-contacts/src/lib/action/create-contact-agent.ts
@@ -0,0 +1,105 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { googleContactsAuth } from '../auth';
+import { googleContactsApi } from '../common';
+import { googleContactsPerson } from '../common/person';
+import { createContactOutputSchema } from '../output-schemas';
+
+export const googleContactsCreateContactAction = createAction({
+ auth: googleContactsAuth,
+ name: 'create_contact',
+ classification: 'WRITE',
+ displayName: 'Create Contact',
+ description: 'Create a new contact in the connected Google account.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates one new person in the connected Google Contacts account from name, nickname, email, phone, organization and notes fields. Supply at least one of name, email or phone; email addresses and phone numbers are arrays of strings, so pass ["[email protected]"] rather than a bare string. Use Batch Create Contacts for many at once, and Update Contact Fields to change someone who already exists. Not idempotent — every call creates a separate person, so check with Search Contacts first if duplicates matter.',
+ idempotent: false,
+ },
+ outputSchema: createContactOutputSchema,
+ props: {
+ firstName: Property.ShortText({
+ displayName: 'First Name',
+ required: false,
+ }),
+ middleName: Property.ShortText({
+ displayName: 'Middle Name',
+ required: false,
+ }),
+ lastName: Property.ShortText({
+ displayName: 'Last Name',
+ required: false,
+ }),
+ nickname: Property.ShortText({
+ displayName: 'Nickname',
+ required: false,
+ }),
+ emails: Property.Array({
+ displayName: 'Email Addresses',
+ description:
+ 'Array of email address strings, for example ["[email protected]"]. A single address still has to be wrapped in an array.',
+ required: false,
+ }),
+ phoneNumbers: Property.Array({
+ displayName: 'Phone Numbers',
+ description:
+ 'Array of phone number strings, for example ["+1 555 0100"]. A single number still has to be wrapped in an array.',
+ required: false,
+ }),
+ company: Property.ShortText({
+ displayName: 'Company',
+ required: false,
+ }),
+ jobTitle: Property.ShortText({
+ displayName: 'Job Title',
+ required: false,
+ }),
+ biography: Property.LongText({
+ displayName: 'Notes',
+ description: 'Free-text notes stored on the contact biography.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const emails = googleContactsApi.toStringList({
+ value: context.propsValue.emails,
+ label: 'Email Addresses',
+ });
+ const phoneNumbers = googleContactsApi.toStringList({
+ value: context.propsValue.phoneNumbers,
+ label: 'Phone Numbers',
+ });
+ const { person, fields } = googleContactsPerson.buildPerson({
+ input: {
+ firstName: context.propsValue.firstName,
+ middleName: context.propsValue.middleName,
+ lastName: context.propsValue.lastName,
+ nickname: context.propsValue.nickname,
+ emails,
+ phoneNumbers,
+ company: context.propsValue.company,
+ jobTitle: context.propsValue.jobTitle,
+ biography: context.propsValue.biography,
+ },
+ });
+ if (fields.length === 0) {
+ throw new Error(
+ 'Create Contact needs at least one of first name, last name, email address or phone number.'
+ );
+ }
+ try {
+ return await googleContactsApi.sendRequest({
+ accessToken: context.auth.access_token,
+ method: HttpMethod.POST,
+ path: '/people:createContact',
+ queryParams: {
+ personFields: googleContactsApi.contactReadMask.join(','),
+ },
+ body: person,
+ });
+ } catch (error) {
+ throw googleContactsApi.toApiError({ error, operation: 'Create Contact' });
+ }
+ },
+});
diff --git a/packages/pieces/community/google-contacts/src/lib/action/create-contact-group.ts b/packages/pieces/community/google-contacts/src/lib/action/create-contact-group.ts
new file mode 100644
index 00000000000..3b10fa42f0c
--- /dev/null
+++ b/packages/pieces/community/google-contacts/src/lib/action/create-contact-group.ts
@@ -0,0 +1,120 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { googleContactsAuth } from '../auth';
+import { googleContactsApi } from '../common';
+import { googleContactsGroup } from '../common/contact-group';
+import { createContactGroupOutputSchema } from '../output-schemas';
+
+const maxPages = 10;
+
+async function findGroupByName({
+ accessToken,
+ name,
+}: {
+ accessToken: string;
+ name: string;
+}): Promise<unknown | undefined> {
+ let pageToken: string | undefined = undefined;
+ for (let page = 0; page < maxPages; page++) {
+ const response: Record<string, unknown> = await googleContactsApi.sendRequest({
+ accessToken,
+ method: HttpMethod.GET,
+ path: '/contactGroups',
+ queryParams: {
+ groupFields: googleContactsApi.contactGroupFields.join(','),
+ pageSize: '1000',
+ pageToken,
+ },
+ });
+ const match = googleContactsApi
+ .readArray({ source: response, path: ['contactGroups'] })
+ .find((group) => googleContactsGroup.matchesName({ group, name }));
+ if (match !== undefined) {
+ return match;
+ }
+ pageToken = googleContactsApi.readString({
+ source: response,
+ path: ['nextPageToken'],
+ });
+ if (pageToken === undefined) {
+ return undefined;
+ }
+ }
+ return undefined;
+}
+
+export const googleContactsCreateContactGroupAction = createAction({
+ auth: googleContactsAuth,
+ name: 'create_contact_group',
+ classification: 'WRITE',
+ displayName: 'Create Contact Group',
+ description: 'Create a contact group, or return the existing one with that name.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a contact group (label) with the given name in the connected Google account, or returns the existing group when one already carries that name, reporting which happened through the created flag. Use it before Add Or Remove Contact Group Members when the target group may not exist yet. Safe to retry: the lookup runs first and a duplicate-name rejection is resolved by returning the existing group.',
+ idempotent: true,
+ },
+ outputSchema: createContactGroupOutputSchema,
+ props: {
+ name: Property.ShortText({
+ displayName: 'Group Name',
+ description: 'Name of the contact group to find or create.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const name = context.propsValue.name.trim();
+ if (name.length === 0) {
+ throw new Error('Group Name must not be empty.');
+ }
+ const accessToken = context.auth.access_token;
+ try {
+ const existing = await findGroupByName({ accessToken, name });
+ if (existing !== undefined) {
+ return {
+ created: false,
+ contactGroup: googleContactsGroup.summarizeGroup({ group: existing }),
+ };
+ }
+ } catch (error) {
+ throw googleContactsApi.toApiError({
+ error,
+ operation: 'Create Contact Group (looking up existing groups)',
+ });
+ }
+ try {
+ const response = await googleContactsApi.sendRequest({
+ accessToken,
+ method: HttpMethod.POST,
+ path: '/contactGroups',
+ body: {
+ contactGroup: { name },
+ readGroupFields: googleContactsApi.contactGroupFields.join(','),
+ },
+ });
+ return {
+ created: true,
+ contactGroup: googleContactsGroup.summarizeGroup({ group: response }),
+ };
+ } catch (error) {
+ if (!googleContactsApi.isConflict({ error })) {
+ throw googleContactsApi.toApiError({
+ error,
+ operation: 'Create Contact Group',
+ });
+ }
+ const raced = await findGroupByName({ accessToken, name });
+ if (raced === undefined) {
+ throw googleContactsApi.toApiError({
+ error,
+ operation: 'Create Contact Group',
+ });
+ }
+ return {
+ created: false,
+ contactGroup: googleContactsGroup.summarizeGroup({ group: raced }),
+ };
+ }
+ },
+});
diff --git a/packages/pieces/community/google-contacts/src/lib/action/create-contact.ts b/packages/pieces/community/google-contacts/src/lib/action/create-contact.ts
index f18f304643d..58d8d2cae24 100644
--- a/packages/pieces/community/google-contacts/src/lib/action/create-contact.ts
+++ b/packages/pieces/community/google-contacts/src/lib/action/create-contact.ts
@@ -14,7 +14,7 @@ export const googleContactsAddContactAction = createAction({
name: 'add_contact',
classification: 'WRITE',
description: 'Add a contact to a Google Contacts account',
- audience: 'both',
+ audience: 'human',
aiMetadata: { description: 'Creates a new person in the authenticated Google Contacts account from name, email, phone, company, and job title fields. Use when an agent needs to add someone to address book contacts; first and last name are required. Not idempotent — each call creates a separate contact even with identical input, so guard against duplicates.', idempotent: false },
displayName: 'Add Contact',
outputSchema: addContactOutputSchema,
diff --git a/packages/pieces/community/google-contacts/src/lib/action/delete-contact-group.ts b/packages/pieces/community/google-contacts/src/lib/action/delete-contact-group.ts
new file mode 100644
index 00000000000..fbad577734b
--- /dev/null
+++ b/packages/pieces/community/google-contacts/src/lib/action/delete-contact-group.ts
@@ -0,0 +1,53 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { googleContactsAuth } from '../auth';
+import { googleContactsApi } from '../common';
+import { deleteContactGroupOutputSchema } from '../output-schemas';
+
+export const googleContactsDeleteContactGroupAction = createAction({
+ auth: googleContactsAuth,
+ name: 'delete_contact_group',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Contact Group',
+ description: 'Delete a user-created contact group.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Deletes one user-created Google Contacts group by its opaque resourceName (contactGroups/{id}). By default only the group is removed and its members stay in the address book; turning on Delete Contacts also permanently deletes every contact in the group, which cannot be undone. Resolve the resourceName with List Contact Groups; Google-managed system groups cannot be deleted. Not idempotent: a repeat call fails because the group is already gone.',
+ idempotent: false,
+ },
+ outputSchema: deleteContactGroupOutputSchema,
+ props: {
+ resourceName: Property.ShortText({
+ displayName: 'Resource Name',
+ description:
+ 'Opaque contact group resource name such as contactGroups/abc123. Resolve it with List Contact Groups.',
+ required: true,
+ }),
+ deleteContacts: Property.Checkbox({
+ displayName: 'Also Delete Contacts',
+ description:
+ 'When enabled, every contact in the group is permanently deleted as well. Leave off to remove only the group.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ async run(context) {
+ const resourceName = context.propsValue.resourceName.trim();
+ const deleteContacts = context.propsValue.deleteContacts === true;
+ try {
+ await googleContactsApi.sendRequest({
+ accessToken: context.auth.access_token,
+ method: HttpMethod.DELETE,
+ path: `/${resourceName}`,
+ queryParams: { deleteContacts: String(deleteContacts) },
+ });
+ } catch (error) {
+ throw googleContactsApi.toApiError({
+ error,
+ operation: 'Delete Contact Group',
+ });
+ }
+ return { deleted: true, resourceName, deletedContacts: deleteContacts };
+ },
+});
diff --git a/packages/pieces/community/google-contacts/src/lib/action/delete-contact-photo.ts b/packages/pieces/community/google-contacts/src/lib/action/delete-contact-photo.ts
new file mode 100644
index 00000000000..78d48714a3e
--- /dev/null
+++ b/packages/pieces/community/google-contacts/src/lib/action/delete-contact-photo.ts
@@ -0,0 +1,57 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { googleContactsAuth } from '../auth';
+import { googleContactsApi } from '../common';
+import { deleteContactPhotoOutputSchema } from '../output-schemas';
+
+export const googleContactsDeleteContactPhotoAction = createAction({
+ auth: googleContactsAuth,
+ name: 'delete_contact_photo',
+ classification: 'WRITE',
+ displayName: 'Delete Contact Photo',
+ description: 'Remove the photo of an existing contact.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Removes the photo from one Google Contacts person, leaving the rest of the contact untouched. Supply the opaque resourceName from List Contacts or Search Contacts; use Update Contact Photo to set a new image instead. The removed image is not recoverable through this API.',
+ idempotent: false,
+ },
+ outputSchema: deleteContactPhotoOutputSchema,
+ props: {
+ resourceName: Property.ShortText({
+ displayName: 'Resource Name',
+ description:
+ 'Opaque contact resource name such as people/c12345. Resolve it with List Contacts or Search Contacts.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const resourceName = context.propsValue.resourceName.trim();
+ let response: Record<string, unknown>;
+ try {
+ response = await googleContactsApi.sendRequest({
+ accessToken: context.auth.access_token,
+ method: HttpMethod.DELETE,
+ path: `/${resourceName}:deleteContactPhoto`,
+ queryParams: {
+ personFields: googleContactsApi.contactReadMask.join(','),
+ },
+ });
+ } catch (error) {
+ throw googleContactsApi.toApiError({
+ error,
+ operation: 'Delete Contact Photo',
+ });
+ }
+ const person = googleContactsApi.readRecord({
+ source: response,
+ path: ['person'],
+ });
+ if (person === undefined) {
+ throw new Error(
+ 'Delete Contact Photo could not read the updated contact back from Google Contacts; re-read the contact with Get Contact to confirm the photo was removed.'
+ );
+ }
+ return person;
+ },
+});
diff --git a/packages/pieces/community/google-contacts/src/lib/action/delete-contact.ts b/packages/pieces/community/google-contacts/src/lib/action/delete-contact.ts
new file mode 100644
index 00000000000..2c2a325b792
--- /dev/null
+++ b/packages/pieces/community/google-contacts/src/lib/action/delete-contact.ts
@@ -0,0 +1,41 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { googleContactsAuth } from '../auth';
+import { googleContactsApi } from '../common';
+import { deleteContactOutputSchema } from '../output-schemas';
+
+export const googleContactsDeleteContactAction = createAction({
+ auth: googleContactsAuth,
+ name: 'delete_contact',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Contact',
+ description: 'Permanently delete a contact by its resource name.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Permanently deletes one Google Contacts person by its opaque resourceName (people/{id}). Irreversible — the People API has no trash, so confirm the contact with Get Contact or List Contacts first; use Batch Delete Contacts for many at once. Not idempotent: a repeat call fails because the contact is already gone.',
+ idempotent: false,
+ },
+ outputSchema: deleteContactOutputSchema,
+ props: {
+ resourceName: Property.ShortText({
+ displayName: 'Resource Name',
+ description:
+ 'Opaque contact resource name such as people/c12345. Resolve it with List Contacts or Search Contacts. Deletion cannot be undone.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const resourceName = context.propsValue.resourceName.trim();
+ try {
+ await googleContactsApi.sendRequest({
+ accessToken: context.auth.access_token,
+ method: HttpMethod.DELETE,
+ path: `/${resourceName}:deleteContact`,
+ });
+ } catch (error) {
+ throw googleContactsApi.toApiError({ error, operation: 'Delete Contact' });
+ }
+ return { deleted: true, resourceName };
+ },
+});
diff --git a/packages/pieces/community/google-contacts/src/lib/action/get-contact-group.ts b/packages/pieces/community/google-contacts/src/lib/action/get-contact-group.ts
new file mode 100644
index 00000000000..be536800981
--- /dev/null
+++ b/packages/pieces/community/google-contacts/src/lib/action/get-contact-group.ts
@@ -0,0 +1,56 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { googleContactsAuth } from '../auth';
+import { googleContactsApi } from '../common';
+import { googleContactsGroup } from '../common/contact-group';
+import { getContactGroupOutputSchema } from '../output-schemas';
+
+export const googleContactsGetContactGroupAction = createAction({
+ auth: googleContactsAuth,
+ name: 'get_contact_group',
+ classification: 'READ',
+ displayName: 'Get Contact Group',
+ description: 'Read one contact group, optionally with its member resource names.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Reads one Google Contacts group by its opaque resourceName (contactGroups/{id}) and returns its name, type, member count and, when Max Members is above zero, the resource names of its members. Resolve the resourceName with List Contact Groups; use Batch Get Contact Groups for several groups. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: getContactGroupOutputSchema,
+ props: {
+ resourceName: Property.ShortText({
+ displayName: 'Resource Name',
+ description:
+ 'Opaque contact group resource name such as contactGroups/abc123, or a system group like contactGroups/myContacts. Resolve it with List Contact Groups.',
+ required: true,
+ }),
+ maxMembers: Property.Number({
+ displayName: 'Max Members',
+ description:
+ 'How many member resource names to return. Defaults to 0, which returns none.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const resourceName = context.propsValue.resourceName.trim();
+ const maxMembers = Math.max(0, context.propsValue.maxMembers ?? 0);
+ try {
+ const response = await googleContactsApi.sendRequest({
+ accessToken: context.auth.access_token,
+ method: HttpMethod.GET,
+ path: `/${resourceName}`,
+ queryParams: {
+ groupFields: googleContactsApi.contactGroupFields.join(','),
+ maxMembers: String(maxMembers),
+ },
+ });
+ return googleContactsGroup.summarizeGroup({ group: response });
+ } catch (error) {
+ throw googleContactsApi.toApiError({
+ error,
+ operation: 'Get Contact Group',
+ });
+ }
+ },
+});
diff --git a/packages/pieces/community/google-contacts/src/lib/action/get-contact.ts b/packages/pieces/community/google-contacts/src/lib/action/get-contact.ts
new file mode 100644
index 00000000000..2558df57c15
--- /dev/null
+++ b/packages/pieces/community/google-contacts/src/lib/action/get-contact.ts
@@ -0,0 +1,43 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { googleContactsAuth } from '../auth';
+import { googleContactsApi } from '../common';
+import { getContactOutputSchema } from '../output-schemas';
+
+export const googleContactsGetContactAction = createAction({
+ auth: googleContactsAuth,
+ name: 'get_contact',
+ classification: 'READ',
+ displayName: 'Get Contact',
+ description: 'Read a single contact by its resource name.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Reads one Google Contacts person by its opaque resourceName (people/{id}) and returns names, emails, phone numbers, organizations, memberships and the current etag. Obtain the resourceName from List Contacts or Search Contacts; do not construct or parse it. Use Batch Get Contacts for more than one contact. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: getContactOutputSchema,
+ props: {
+ resourceName: Property.ShortText({
+ displayName: 'Resource Name',
+ description:
+ 'Opaque contact resource name such as people/c12345. Resolve it with List Contacts or Search Contacts.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const resourceName = context.propsValue.resourceName.trim();
+ try {
+ return await googleContactsApi.sendRequest({
+ accessToken: context.auth.access_token,
+ method: HttpMethod.GET,
+ path: `/${resourceName}`,
+ queryParams: {
+ personFields: googleContactsApi.contactReadMask.join(','),
+ },
+ });
+ } catch (error) {
+ throw googleContactsApi.toApiError({ error, operation: 'Get Contact' });
+ }
+ },
+});
diff --git a/packages/pieces/community/google-contacts/src/lib/action/list-contact-groups.ts b/packages/pieces/community/google-contacts/src/lib/action/list-contact-groups.ts
new file mode 100644
index 00000000000..e5c2a68475b
--- /dev/null
+++ b/packages/pieces/community/google-contacts/src/lib/action/list-contact-groups.ts
@@ -0,0 +1,66 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { googleContactsAuth } from '../auth';
+import { googleContactsApi } from '../common';
+import { googleContactsGroup } from '../common/contact-group';
+import { listContactGroupsOutputSchema } from '../output-schemas';
+
+const maxPages = 10;
+
+export const googleContactsListContactGroupsAction = createAction({
+ auth: googleContactsAuth,
+ name: 'list_contact_groups',
+ classification: 'SEARCH',
+ displayName: 'List Contact Groups',
+ description: 'List every contact group of the connected Google account.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the contact groups (labels) of the connected Google account with the opaque resourceName, name, type and member count of each. Use it to resolve a group name to its resourceName before Get Contact Group, Update Contact Group, Delete Contact Group or Add Or Remove Contact Group Members. Member resource names are not included here — read a single group with Get Contact Group for those. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: listContactGroupsOutputSchema,
+ props: {},
+ async run(context) {
+ const groups: Record<string, unknown>[] = [];
+ let pageToken: string | undefined = undefined;
+ try {
+ for (let page = 0; page < maxPages; page++) {
+ const response: Record<string, unknown> =
+ await googleContactsApi.sendRequest({
+ accessToken: context.auth.access_token,
+ method: HttpMethod.GET,
+ path: '/contactGroups',
+ queryParams: {
+ groupFields: googleContactsApi.contactGroupFields.join(','),
+ pageSize: '1000',
+ pageToken,
+ },
+ });
+ for (const group of googleContactsApi.readArray({
+ source: response,
+ path: ['contactGroups'],
+ })) {
+ groups.push(googleContactsGroup.summarizeGroup({ group }));
+ }
+ pageToken = googleContactsApi.readString({
+ source: response,
+ path: ['nextPageToken'],
+ });
+ if (pageToken === undefined) {
+ break;
+ }
+ }
+ } catch (error) {
+ throw googleContactsApi.toApiError({
+ error,
+ operation: 'List Contact Groups',
+ });
+ }
+ return {
+ contactGroups: groups,
+ count: groups.length,
+ hasMore: pageToken !== undefined,
+ };
+ },
+});
diff --git a/packages/pieces/community/google-contacts/src/lib/action/list-contacts.ts b/packages/pieces/community/google-contacts/src/lib/action/list-contacts.ts
new file mode 100644
index 00000000000..fec807de864
--- /dev/null
+++ b/packages/pieces/community/google-contacts/src/lib/action/list-contacts.ts
@@ -0,0 +1,73 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { googleContactsAuth } from '../auth';
+import { googleContactsApi } from '../common';
+import { googleContactsPerson } from '../common/person';
+import { listContactsOutputSchema } from '../output-schemas';
+
+const maxPages = 10;
+
+export const googleContactsListContactsAction = createAction({
+ auth: googleContactsAuth,
+ name: 'list_contacts',
+ classification: 'SEARCH',
+ displayName: 'List Contacts',
+ description: 'List the contacts of the connected Google account.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the connected account contacts with the resourceName and etag every write action needs, plus display name, emails, phone numbers and organization. Use this to resolve a person name to a resourceName before Update Contact Fields, Delete Contact or group membership changes; use Search Contacts when you already have a query string. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: listContactsOutputSchema,
+ props: {
+ maxResults: Property.Number({
+ displayName: 'Max Results',
+ description: 'Maximum number of contacts to return. Defaults to 200.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const limit = context.propsValue.maxResults ?? 200;
+ const collected: Record<string, unknown>[] = [];
+ let pageToken: string | undefined = undefined;
+ try {
+ for (let page = 0; page < maxPages; page++) {
+ const pageSize = Math.min(1000, Math.max(1, limit - collected.length));
+ const response: Record<string, unknown> =
+ await googleContactsApi.sendRequest({
+ accessToken: context.auth.access_token,
+ method: HttpMethod.GET,
+ path: '/people/me/connections',
+ queryParams: {
+ personFields: googleContactsApi.contactReadMask.join(','),
+ pageSize: String(pageSize),
+ pageToken,
+ },
+ });
+ const connections = googleContactsApi.readArray({
+ source: response,
+ path: ['connections'],
+ });
+ for (const person of connections) {
+ collected.push(googleContactsPerson.summarizePerson({ person }));
+ }
+ pageToken = googleContactsApi.readString({
+ source: response,
+ path: ['nextPageToken'],
+ });
+ if (pageToken === undefined || collected.length >= limit) {
+ break;
+ }
+ }
+ } catch (error) {
+ throw googleContactsApi.toApiError({ error, operation: 'List Contacts' });
+ }
+ const contacts = collected.slice(0, limit);
+ return {
+ contacts,
+ count: contacts.length,
+ hasMore: pageToken !== undefined,
+ };
+ },
+});
diff --git a/packages/pieces/community/google-contacts/src/lib/action/modify-contact-group-members.ts b/packages/pieces/community/google-contacts/src/lib/action/modify-contact-group-members.ts
new file mode 100644
index 00000000000..782c5b2f62c
--- /dev/null
+++ b/packages/pieces/community/google-contacts/src/lib/action/modify-contact-group-members.ts
@@ -0,0 +1,102 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { googleContactsAuth } from '../auth';
+import { googleContactsApi } from '../common';
+import { modifyContactGroupMembersOutputSchema } from '../output-schemas';
+
+export const googleContactsModifyContactGroupMembersAction = createAction({
+ auth: googleContactsAuth,
+ name: 'modify_contact_group_members',
+ classification: 'WRITE',
+ displayName: 'Add Or Remove Contact Group Members',
+ description: 'Add contacts to a contact group or remove them from it.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Adds contacts to a Google Contacts group and removes contacts from it in one call, taking opaque people/{id} resource names resolved with List Contacts or Search Contacts and a contactGroups/{id} group resolved with List Contact Groups. Additions are accepted by user-created groups and by the system groups contactGroups/myContacts and contactGroups/starred only; other system groups accept removals only. Combined additions and removals are capped at 1000, and the response reports contacts that were not found. Safe to retry — re-applying the same membership changes converges.',
+ idempotent: true,
+ },
+ outputSchema: modifyContactGroupMembersOutputSchema,
+ props: {
+ resourceName: Property.ShortText({
+ displayName: 'Contact Group Resource Name',
+ description:
+ 'Opaque contact group resource name such as contactGroups/abc123, contactGroups/myContacts or contactGroups/starred. Resolve it with List Contact Groups.',
+ required: true,
+ }),
+ resourceNamesToAdd: Property.Array({
+ displayName: 'Contacts To Add',
+ description:
+ 'Opaque contact resource names such as people/c12345 to add to the group.',
+ required: false,
+ }),
+ resourceNamesToRemove: Property.Array({
+ displayName: 'Contacts To Remove',
+ description:
+ 'Opaque contact resource names such as people/c12345 to remove from the group.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const resourceName = context.propsValue.resourceName.trim();
+ const resourceNamesToAdd = googleContactsApi.toStringList({
+ value: context.propsValue.resourceNamesToAdd,
+ label: 'Contacts To Add',
+ });
+ const resourceNamesToRemove = googleContactsApi.toStringList({
+ value: context.propsValue.resourceNamesToRemove,
+ label: 'Contacts To Remove',
+ });
+ const total = resourceNamesToAdd.length + resourceNamesToRemove.length;
+ if (total === 0) {
+ throw new Error(
+ 'Add Or Remove Contact Group Members needs at least one contact to add or remove.'
+ );
+ }
+ if (total > 1000) {
+ throw new Error(
+ `Contacts to add and remove are capped at 1000 combined, received ${total}.`
+ );
+ }
+ if (
+ resourceNamesToAdd.length > 0 &&
+ googleContactsApi.systemGroupsRejectingAdds.includes(resourceName)
+ ) {
+ throw new Error(
+ `The system group ${resourceName} does not accept added members; only contactGroups/myContacts, contactGroups/starred and user-created groups do.`
+ );
+ }
+ let response: Record<string, unknown>;
+ try {
+ response = await googleContactsApi.sendRequest({
+ accessToken: context.auth.access_token,
+ method: HttpMethod.POST,
+ path: `/${resourceName}/members:modify`,
+ body: { resourceNamesToAdd, resourceNamesToRemove },
+ });
+ } catch (error) {
+ throw googleContactsApi.toApiError({
+ error,
+ operation: 'Add Or Remove Contact Group Members',
+ });
+ }
+ const notFound = googleContactsApi
+ .readArray({ source: response, path: ['notFoundResourceNames'] })
+ .filter((value): value is string => typeof value === 'string');
+ const notRemovable = googleContactsApi
+ .readArray({
+ source: response,
+ path: ['canNotRemoveLastContactGroupResourceNames'],
+ })
+ .filter((value): value is string => typeof value === 'string');
+ return {
+ resourceName,
+ added: resourceNamesToAdd.filter((name) => !notFound.includes(name)),
+ removed: resourceNamesToRemove.filter(
+ (name) => !notFound.includes(name) && !notRemovable.includes(name)
+ ),
+ notFoundResourceNames: notFound,
+ canNotRemoveLastContactGroupResourceNames: notRemovable,
+ };
+ },
+});
diff --git a/packages/pieces/community/google-contacts/src/lib/action/search-contact.ts b/packages/pieces/community/google-contacts/src/lib/action/search-contact.ts
index b2ce4832e45..8457e050f3b 100644
--- a/packages/pieces/community/google-contacts/src/lib/action/search-contact.ts
+++ b/packages/pieces/community/google-contacts/src/lib/action/search-contact.ts
@@ -15,7 +15,7 @@ export const googleContactsSearchContactsAction = createAction({
name: 'search_contact',
classification: 'SEARCH',
description: 'Search contacts in Google Contacts account.',
- audience: 'both',
+ audience: 'human',
aiMetadata: { description: 'Searches the authenticated Google Contacts account for people matching a plain-text query, which prefix-matches against contact fields. Use when an agent needs to find a contact or its resourceName before updating it; the query is required and a read mask selects which fields come back (max 30 results). Read-only and idempotent.', idempotent: true },
displayName: 'Search Contacts',
outputSchema: searchContactsOutputSchema,
diff --git a/packages/pieces/community/google-contacts/src/lib/action/search-contacts.ts b/packages/pieces/community/google-contacts/src/lib/action/search-contacts.ts
new file mode 100644
index 00000000000..c220d48c8b1
--- /dev/null
+++ b/packages/pieces/community/google-contacts/src/lib/action/search-contacts.ts
@@ -0,0 +1,73 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { googleContactsAuth } from '../auth';
+import { googleContactsApi } from '../common';
+import { googleContactsPerson } from '../common/person';
+import { searchContactsAtomicOutputSchema } from '../output-schemas';
+
+export const googleContactsSearchContactsAtomicAction = createAction({
+ auth: googleContactsAuth,
+ name: 'search_contacts',
+ classification: 'SEARCH',
+ displayName: 'Search Contacts',
+ description: 'Search the connected account contacts by a plain-text query.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Searches the connected Google Contacts account for people whose fields prefix-match a plain-text query and returns each match with its resourceName and etag. Use it to resolve a name, email or phone fragment into a resourceName before an update or delete; use List Contacts to enumerate everything instead. Matching is prefix-only ("foo n" matches "foo name", "oo n" does not) and capped at 30 results. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: searchContactsAtomicOutputSchema,
+ props: {
+ query: Property.ShortText({
+ displayName: 'Query',
+ description:
+ 'Plain-text query prefix-matched against contact fields such as name, email and phone number.',
+ required: true,
+ }),
+ pageSize: Property.Number({
+ displayName: 'Page Size',
+ description: 'Number of results to return, maximum 30. Defaults to 30.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const readMask = googleContactsApi.contactReadMask.join(',');
+ const pageSize = Math.min(30, Math.max(1, context.propsValue.pageSize ?? 30));
+ try {
+ await googleContactsApi.sendRequest({
+ accessToken: context.auth.access_token,
+ method: HttpMethod.GET,
+ path: '/people:searchContacts',
+ queryParams: { query: '', readMask, pageSize: '1' },
+ });
+ } catch (error) {
+ throw googleContactsApi.toApiError({
+ error,
+ operation: 'Search Contacts warm-up',
+ });
+ }
+ try {
+ const response = await googleContactsApi.sendRequest({
+ accessToken: context.auth.access_token,
+ method: HttpMethod.GET,
+ path: '/people:searchContacts',
+ queryParams: {
+ query: context.propsValue.query,
+ readMask,
+ pageSize: String(pageSize),
+ },
+ });
+ const results = googleContactsApi
+ .readArray({ source: response, path: ['results'] })
+ .map((result) =>
+ googleContactsPerson.summarizePerson({
+ person: googleContactsApi.readValue({ source: result, path: ['person'] }),
+ })
+ );
+ return { results, count: results.length };
+ } catch (error) {
+ throw googleContactsApi.toApiError({ error, operation: 'Search Contacts' });
+ }
+ },
+});
diff --git a/packages/pieces/community/google-contacts/src/lib/action/update-contact-fields.ts b/packages/pieces/community/google-contacts/src/lib/action/update-contact-fields.ts
new file mode 100644
index 00000000000..d5f7010b968
--- /dev/null
+++ b/packages/pieces/community/google-contacts/src/lib/action/update-contact-fields.ts
@@ -0,0 +1,163 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { googleContactsAuth } from '../auth';
+import { googleContactsApi } from '../common';
+import { googleContactsPerson } from '../common/person';
+import { updateContactFieldsOutputSchema } from '../output-schemas';
+
+export const googleContactsUpdateContactFieldsAction = createAction({
+ auth: googleContactsAuth,
+ name: 'update_contact_fields',
+ classification: 'WRITE',
+ displayName: 'Update Contact Fields',
+ description: 'Update only the supplied fields on an existing contact.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Updates an existing Google Contacts person, changing only the fields you supply and leaving every other field untouched. It reads the contact first, so it resolves the required etag and field mask itself — you never pass them. Supply the opaque resourceName from List Contacts or Search Contacts. A non-empty email or phone list replaces the stored list for that field wholesale; first/middle/last name and company/job title are merged over the current values. Leaving a list empty does NOT clear it, because the platform cannot distinguish an untouched list from an emptied one: to remove every email address or every phone number, including the last one, set clearEmails or clearPhoneNumbers to true. Setting a clear flag while also supplying a non-empty list for the same field is rejected. Safe to retry: re-applying the same values converges, and a concurrent edit surfaces as a re-read-and-retry error.',
+ idempotent: true,
+ },
+ outputSchema: updateContactFieldsOutputSchema,
+ props: {
+ resourceName: Property.ShortText({
+ displayName: 'Resource Name',
+ description:
+ 'Opaque contact resource name such as people/c12345. Resolve it with List Contacts or Search Contacts.',
+ required: true,
+ }),
+ firstName: Property.ShortText({
+ displayName: 'First Name',
+ required: false,
+ }),
+ middleName: Property.ShortText({
+ displayName: 'Middle Name',
+ required: false,
+ }),
+ lastName: Property.ShortText({
+ displayName: 'Last Name',
+ required: false,
+ }),
+ nickname: Property.ShortText({
+ displayName: 'Nickname',
+ required: false,
+ }),
+ emails: Property.Array({
+ displayName: 'Email Addresses',
+ description:
+ 'Array of email address strings, for example ["[email protected]"]. Replaces every email address stored on the contact. Leaving it empty keeps the stored addresses; it does not clear them, because an untouched list and an emptied one cannot be told apart. Use Clear Email Addresses to remove them.',
+ required: false,
+ }),
+ clearEmails: Property.Checkbox({
+ displayName: 'Clear Email Addresses',
+ description:
+ 'Remove every email address from the contact, including the last one. This is the only way to clear them. Cannot be combined with a non-empty Email Addresses list.',
+ required: false,
+ defaultValue: false,
+ }),
+ phoneNumbers: Property.Array({
+ displayName: 'Phone Numbers',
+ description:
+ 'Array of phone number strings, for example ["+1 555 0100"]. Replaces every phone number stored on the contact. Leaving it empty keeps the stored numbers; it does not clear them, because an untouched list and an emptied one cannot be told apart. Use Clear Phone Numbers to remove them.',
+ required: false,
+ }),
+ clearPhoneNumbers: Property.Checkbox({
+ displayName: 'Clear Phone Numbers',
+ description:
+ 'Remove every phone number from the contact, including the last one. This is the only way to clear them. Cannot be combined with a non-empty Phone Numbers list.',
+ required: false,
+ defaultValue: false,
+ }),
+ company: Property.ShortText({
+ displayName: 'Company',
+ required: false,
+ }),
+ jobTitle: Property.ShortText({
+ displayName: 'Job Title',
+ required: false,
+ }),
+ biography: Property.LongText({
+ displayName: 'Notes',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const resourceName = context.propsValue.resourceName.trim();
+ const clearEmails = context.propsValue.clearEmails === true;
+ const clearPhoneNumbers = context.propsValue.clearPhoneNumbers === true;
+ const emails = googleContactsApi.toStringList({
+ value: context.propsValue.emails,
+ label: 'Email Addresses',
+ });
+ const phoneNumbers = googleContactsApi.toStringList({
+ value: context.propsValue.phoneNumbers,
+ label: 'Phone Numbers',
+ });
+ if (clearEmails && emails.length > 0) {
+ throw new Error(
+ 'Clear Email Addresses removes every email address, so it cannot be combined with an Email Addresses list. Either clear the list or turn the checkbox off.'
+ );
+ }
+ if (clearPhoneNumbers && phoneNumbers.length > 0) {
+ throw new Error(
+ 'Clear Phone Numbers removes every phone number, so it cannot be combined with a Phone Numbers list. Either clear the list or turn the checkbox off.'
+ );
+ }
+ const input = {
+ firstName: context.propsValue.firstName,
+ middleName: context.propsValue.middleName,
+ lastName: context.propsValue.lastName,
+ nickname: context.propsValue.nickname,
+ emails,
+ phoneNumbers,
+ clearEmails,
+ clearPhoneNumbers,
+ company: context.propsValue.company,
+ jobTitle: context.propsValue.jobTitle,
+ biography: context.propsValue.biography,
+ };
+ const { fields: requestedFields } = googleContactsPerson.buildPerson({ input });
+ if (requestedFields.length === 0) {
+ throw new Error(
+ 'Update Contact Fields needs at least one field to change; every field prop was left empty.'
+ );
+ }
+ let current: Record<string, unknown>;
+ try {
+ current = await googleContactsApi.sendRequest({
+ accessToken: context.auth.access_token,
+ method: HttpMethod.GET,
+ path: `/${resourceName}`,
+ queryParams: { personFields: requestedFields.join(',') },
+ });
+ } catch (error) {
+ throw googleContactsApi.toApiError({
+ error,
+ operation: 'Update Contact Fields (reading the contact)',
+ });
+ }
+ const etag = googleContactsApi.readString({ source: current, path: ['etag'] });
+ if (etag === undefined) {
+ throw new Error(
+ 'Update Contact Fields could not read the current etag of the contact; re-read the contact and retry.'
+ );
+ }
+ const { person, fields } = googleContactsPerson.buildPerson({ input, current });
+ try {
+ return await googleContactsApi.sendRequest({
+ accessToken: context.auth.access_token,
+ method: HttpMethod.PATCH,
+ path: `/${resourceName}:updateContact`,
+ queryParams: {
+ updatePersonFields: fields.join(','),
+ personFields: googleContactsApi.contactReadMask.join(','),
+ },
+ body: { etag, ...person },
+ });
+ } catch (error) {
+ throw googleContactsApi.toApiError({
+ error,
+ operation: 'Update Contact Fields',
+ });
+ }
+ },
+});
diff --git a/packages/pieces/community/google-contacts/src/lib/action/update-contact-group.ts b/packages/pieces/community/google-contacts/src/lib/action/update-contact-group.ts
new file mode 100644
index 00000000000..8582ab92e39
--- /dev/null
+++ b/packages/pieces/community/google-contacts/src/lib/action/update-contact-group.ts
@@ -0,0 +1,79 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { googleContactsAuth } from '../auth';
+import { googleContactsApi } from '../common';
+import { googleContactsGroup } from '../common/contact-group';
+import { updateContactGroupOutputSchema } from '../output-schemas';
+
+export const googleContactsUpdateContactGroupAction = createAction({
+ auth: googleContactsAuth,
+ name: 'update_contact_group',
+ classification: 'WRITE',
+ displayName: 'Update Contact Group',
+ description: 'Rename an existing user-created contact group.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Renames one user-created Google Contacts group identified by its opaque resourceName (contactGroups/{id}). It reads the group first to resolve the required etag and sends an explicit name-only field mask, so members and other group data are untouched. Resolve the resourceName with List Contact Groups; Google-managed system groups cannot be renamed. Safe to retry: re-applying the same name converges, and a concurrent edit surfaces as a re-read-and-retry error.',
+ idempotent: true,
+ },
+ outputSchema: updateContactGroupOutputSchema,
+ props: {
+ resourceName: Property.ShortText({
+ displayName: 'Resource Name',
+ description:
+ 'Opaque contact group resource name such as contactGroups/abc123. Resolve it with List Contact Groups.',
+ required: true,
+ }),
+ name: Property.ShortText({
+ displayName: 'New Group Name',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const resourceName = context.propsValue.resourceName.trim();
+ const name = context.propsValue.name.trim();
+ if (name.length === 0) {
+ throw new Error('New Group Name must not be empty.');
+ }
+ const groupFields = googleContactsApi.contactGroupFields.join(',');
+ let current: Record<string, unknown>;
+ try {
+ current = await googleContactsApi.sendRequest({
+ accessToken: context.auth.access_token,
+ method: HttpMethod.GET,
+ path: `/${resourceName}`,
+ queryParams: { groupFields, maxMembers: '0' },
+ });
+ } catch (error) {
+ throw googleContactsApi.toApiError({
+ error,
+ operation: 'Update Contact Group (reading the group)',
+ });
+ }
+ const etag = googleContactsApi.readString({ source: current, path: ['etag'] });
+ if (etag === undefined) {
+ throw new Error(
+ 'Update Contact Group could not read the current etag of the group; re-read the group and retry.'
+ );
+ }
+ try {
+ const response = await googleContactsApi.sendRequest({
+ accessToken: context.auth.access_token,
+ method: HttpMethod.PUT,
+ path: `/${resourceName}`,
+ body: {
+ contactGroup: { etag, name },
+ updateGroupFields: 'name',
+ readGroupFields: groupFields,
+ },
+ });
+ return googleContactsGroup.summarizeGroup({ group: response });
+ } catch (error) {
+ throw googleContactsApi.toApiError({
+ error,
+ operation: 'Update Contact Group',
+ });
+ }
+ },
+});
diff --git a/packages/pieces/community/google-contacts/src/lib/action/update-contact-photo.ts b/packages/pieces/community/google-contacts/src/lib/action/update-contact-photo.ts
new file mode 100644
index 00000000000..f34f77f3899
--- /dev/null
+++ b/packages/pieces/community/google-contacts/src/lib/action/update-contact-photo.ts
@@ -0,0 +1,75 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { googleContactsAuth } from '../auth';
+import { googleContactsApi } from '../common';
+import { updateContactPhotoOutputSchema } from '../output-schemas';
+
+const base64Marker = 'base64,';
+
+export const googleContactsUpdateContactPhotoAction = createAction({
+ auth: googleContactsAuth,
+ name: 'update_contact_photo',
+ classification: 'WRITE',
+ displayName: 'Update Contact Photo',
+ description: 'Set the photo of an existing contact from base64 image bytes.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Replaces the photo of one Google Contacts person with the supplied base64-encoded JPEG, PNG or WebP image. Supply the opaque resourceName from List Contacts or Search Contacts; use Delete Contact Photo to remove a photo instead. Safe to retry — re-sending the same bytes converges on the same photo.',
+ idempotent: true,
+ },
+ outputSchema: updateContactPhotoOutputSchema,
+ props: {
+ resourceName: Property.ShortText({
+ displayName: 'Resource Name',
+ description:
+ 'Opaque contact resource name such as people/c12345. Resolve it with List Contacts or Search Contacts.',
+ required: true,
+ }),
+ photoBytes: Property.LongText({
+ displayName: 'Photo Bytes',
+ description:
+ 'Base64-encoded JPEG, PNG or WebP image. A data URL prefix is accepted and stripped.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const resourceName = context.propsValue.resourceName.trim();
+ const supplied = context.propsValue.photoBytes.trim();
+ const markerIndex = supplied.indexOf(base64Marker);
+ const photoBytes =
+ markerIndex === -1
+ ? supplied
+ : supplied.slice(markerIndex + base64Marker.length);
+ if (photoBytes.length === 0) {
+ throw new Error('Update Contact Photo needs base64-encoded image bytes.');
+ }
+ let response: Record<string, unknown>;
+ try {
+ response = await googleContactsApi.sendRequest({
+ accessToken: context.auth.access_token,
+ method: HttpMethod.PATCH,
+ path: `/${resourceName}:updateContactPhoto`,
+ body: {
+ photoBytes,
+ personFields: googleContactsApi.contactReadMask.join(','),
+ },
+ });
+ } catch (error) {
+ throw googleContactsApi.toApiError({
+ error,
+ operation: 'Update Contact Photo',
+ });
+ }
+ const person = googleContactsApi.readRecord({
+ source: response,
+ path: ['person'],
+ });
+ if (person === undefined) {
+ throw new Error(
+ 'Update Contact Photo could not read the updated contact back from Google Contacts; re-read the contact with Get Contact to confirm the photo was set.'
+ );
+ }
+ return person;
+ },
+});
diff --git a/packages/pieces/community/google-contacts/src/lib/action/update-contact.ts b/packages/pieces/community/google-contacts/src/lib/action/update-contact.ts
index 3d7e75ec0d7..b6c78343740 100644
--- a/packages/pieces/community/google-contacts/src/lib/action/update-contact.ts
+++ b/packages/pieces/community/google-contacts/src/lib/action/update-contact.ts
@@ -18,7 +18,7 @@ export const googleContactsUpdateContactAction = createAction({
name: 'update_contact',
classification: 'WRITE',
description: 'Update a contact in Google Contacts account.',
- audience: 'both',
+ audience: 'human',
aiMetadata: { description: 'Updates fields (name, email, phone, company, job title) on an existing Google Contacts person identified by its resourceName (people/{id}). Use when an agent needs to modify a known contact; requires both the resourceName and the current etag, and a field mask listing which fields to update — the call is rejected if the contact changed since the etag was fetched. Repeating the same update with the same etag/values is safe and yields the same result.', idempotent: true },
displayName: 'Update Contact',
outputSchema: updateContactOutputSchema,
diff --git a/packages/pieces/community/google-contacts/src/lib/common/contact-group.ts b/packages/pieces/community/google-contacts/src/lib/common/contact-group.ts
new file mode 100644
index 00000000000..50d370388d4
--- /dev/null
+++ b/packages/pieces/community/google-contacts/src/lib/common/contact-group.ts
@@ -0,0 +1,43 @@
+import { googleContactsApi } from './index';
+
+function summarizeGroup({ group }: { group: unknown }): Record<string, unknown> {
+ const memberCount = googleContactsApi.readValue({
+ source: group,
+ path: ['memberCount'],
+ });
+ return {
+ resourceName: googleContactsApi.readString({
+ source: group,
+ path: ['resourceName'],
+ }),
+ etag: googleContactsApi.readString({ source: group, path: ['etag'] }),
+ name: googleContactsApi.readString({ source: group, path: ['name'] }),
+ formattedName: googleContactsApi.readString({
+ source: group,
+ path: ['formattedName'],
+ }),
+ groupType: googleContactsApi.readString({ source: group, path: ['groupType'] }),
+ memberCount: typeof memberCount === 'number' ? memberCount : 0,
+ memberResourceNames: googleContactsApi
+ .readArray({ source: group, path: ['memberResourceNames'] })
+ .filter((value): value is string => typeof value === 'string'),
+ };
+}
+
+function matchesName({ group, name }: { group: unknown; name: string }): boolean {
+ const target = name.trim().toLowerCase();
+ const groupName = googleContactsApi.readString({ source: group, path: ['name'] });
+ const formatted = googleContactsApi.readString({
+ source: group,
+ path: ['formattedName'],
+ });
+ return (
+ groupName?.trim().toLowerCase() === target ||
+ formatted?.trim().toLowerCase() === target
+ );
+}
+
+export const googleContactsGroup = {
+ summarizeGroup,
+ matchesName,
+};
diff --git a/packages/pieces/community/google-contacts/src/lib/common/index.ts b/packages/pieces/community/google-contacts/src/lib/common/index.ts
index 4532fbae00c..ae87ea58750 100644
--- a/packages/pieces/community/google-contacts/src/lib/common/index.ts
+++ b/packages/pieces/community/google-contacts/src/lib/common/index.ts
@@ -1,3 +1,343 @@
+import {
+ AuthenticationType,
+ HttpMethod,
+ HttpRequest,
+ httpClient,
+} from '@activepieces/pieces-common';
+
+const apiRoot = 'https://people.googleapis.com/v1';
+
+const contactReadMask = [
+ 'names',
+ 'nicknames',
+ 'emailAddresses',
+ 'phoneNumbers',
+ 'organizations',
+ 'addresses',
+ 'biographies',
+ 'urls',
+ 'memberships',
+ 'photos',
+ 'metadata',
+];
+
+const contactGroupFields = [
+ 'clientData',
+ 'groupType',
+ 'memberCount',
+ 'metadata',
+ 'name',
+];
+
+const updatablePersonFields = [
+ 'addresses',
+ 'biographies',
+ 'birthdays',
+ 'calendarUrls',
+ 'clientData',
+ 'emailAddresses',
+ 'events',
+ 'externalIds',
+ 'genders',
+ 'imClients',
+ 'interests',
+ 'locales',
+ 'locations',
+ 'memberships',
+ 'miscKeywords',
+ 'names',
+ 'nicknames',
+ 'occupations',
+ 'organizations',
+ 'phoneNumbers',
+ 'relations',
+ 'sipAddresses',
+ 'urls',
+ 'userDefined',
+];
+
+const systemGroupsRejectingAdds = [
+ 'contactGroups/all',
+ 'contactGroups/blocked',
+ 'contactGroups/chatBuddies',
+ 'contactGroups/coworkers',
+ 'contactGroups/family',
+ 'contactGroups/friends',
+];
+
+function buildUrl({
+ path,
+ queryParams,
+ repeatedQueryParams,
+}: {
+ path: string;
+ queryParams?: Record<string, string | undefined>;
+ repeatedQueryParams?: Record<string, string[]>;
+}): string {
+ const search = new URLSearchParams();
+ for (const [key, value] of Object.entries(queryParams ?? {})) {
+ if (value !== undefined) {
+ search.append(key, value);
+ }
+ }
+ for (const [key, values] of Object.entries(repeatedQueryParams ?? {})) {
+ for (const value of values) {
+ search.append(key, value);
+ }
+ }
+ const query = search.toString();
+ return query.length > 0 ? `${apiRoot}${path}?${query}` : `${apiRoot}${path}`;
+}
+
+function readValue({ source, path }: { source: unknown; path: string[] }): unknown {
+ let current: unknown = source;
+ for (const key of path) {
+ if (typeof current !== 'object' || current === null || !(key in current)) {
+ return undefined;
+ }
+ current = Reflect.get(current, key);
+ }
+ return current;
+}
+
+function readString({
+ source,
+ path,
+}: {
+ source: unknown;
+ path: string[];
+}): string | undefined {
+ const value = readValue({ source, path });
+ return typeof value === 'string' ? value : undefined;
+}
+
+function readRecord({
+ source,
+ path,
+}: {
+ source: unknown;
+ path: string[];
+}): Record<string, unknown> | undefined {
+ const value = readValue({ source, path });
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
+ return undefined;
+ }
+ return Object.fromEntries(Object.entries(value));
+}
+
+function readArray({ source, path }: { source: unknown; path: string[] }): unknown[] {
+ const value = readValue({ source, path });
+ return Array.isArray(value) ? value : [];
+}
+
+function parseStringList({ value, label }: { value: string; label: string }): unknown[] {
+ try {
+ const parsed: unknown = JSON.parse(value);
+ if (Array.isArray(parsed)) {
+ return parsed;
+ }
+ } catch {
+ throw new Error(`${label} must be a list of strings.`);
+ }
+ throw new Error(`${label} must be a list of strings.`);
+}
+
+function toStringList({ value, label }: { value: unknown; label: string }): string[] {
+ if (value === undefined || value === null) {
+ return [];
+ }
+ const entries =
+ typeof value === 'string' ? parseStringList({ value, label }) : value;
+ if (!Array.isArray(entries)) {
+ throw new Error(`${label} must be a list of strings.`);
+ }
+ return entries.map((item) => {
+ if (typeof item !== 'string' || item.trim().length === 0) {
+ throw new Error(`${label} must be a list of non-empty strings.`);
+ }
+ return item.trim();
+ });
+}
+
+function assertBatchSize({
+ values,
+ max,
+ label,
+}: {
+ values: string[];
+ max: number;
+ label: string;
+}): void {
+ if (values.length === 0) {
+ throw new Error(`${label} must contain at least one entry.`);
+ }
+ if (values.length > max) {
+ throw new Error(
+ `${label} accepts at most ${max} entries, received ${values.length}.`
+ );
+ }
+}
+
+function describeStatus({ status }: { status: unknown }): string {
+ const message = readString({ source: status, path: ['message'] });
+ const code = readValue({ source: status, path: ['code'] });
+ if (message !== undefined) {
+ return message;
+ }
+ if (typeof code === 'number') {
+ return `Google returned status code ${code}.`;
+ }
+ return 'Google returned an unspecified failure for this item.';
+}
+
+function isFailedItem({ response }: { response: unknown }): boolean {
+ const status = readValue({ source: response, path: ['status'] });
+ if (status === undefined || status === null) {
+ return false;
+ }
+ const code = readValue({ source: status, path: ['code'] });
+ const message = readValue({ source: status, path: ['message'] });
+ if (typeof code === 'number' && code !== 0) {
+ return true;
+ }
+ return typeof message === 'string' && message.length > 0;
+}
+
+function splitItemResponses({
+ items,
+ payloadKey,
+}: {
+ items: { resourceName: string; response: unknown }[];
+ payloadKey: string;
+}): {
+ succeeded: { resourceName: string; payload: unknown }[];
+ failed: { resourceName: string; status: string }[];
+} {
+ const succeeded = items
+ .filter((item) => !isFailedItem({ response: item.response }))
+ .map((item) => ({
+ resourceName:
+ readString({
+ source: item.response,
+ path: [payloadKey, 'resourceName'],
+ }) ?? item.resourceName,
+ payload: readValue({ source: item.response, path: [payloadKey] }),
+ }));
+ const failed = items
+ .filter((item) => isFailedItem({ response: item.response }))
+ .map((item) => ({
+ resourceName: item.resourceName,
+ status: describeStatus({
+ status: readValue({ source: item.response, path: ['status'] }),
+ }),
+ }));
+ return { succeeded, failed };
+}
+
+function toApiError({
+ error,
+ operation,
+}: {
+ error: unknown;
+ operation: string;
+}): Error {
+ const status = readValue({ source: error, path: ['response', 'status'] });
+ const reason = readString({
+ source: error,
+ path: ['response', 'body', 'error', 'status'],
+ });
+ const message = readString({
+ source: error,
+ path: ['response', 'body', 'error', 'message'],
+ });
+ const suffix = message === undefined ? '' : ` ${message}`;
+ if (status === 400 && reason === 'FAILED_PRECONDITION') {
+ return new Error(
+ `${operation} failed because the record changed since it was read. Re-read the record to get a fresh etag and retry.${suffix}`
+ );
+ }
+ if (status === 400) {
+ return new Error(
+ `${operation} was rejected as invalid by Google Contacts.${suffix}`
+ );
+ }
+ if (status === 401) {
+ return new Error(
+ `${operation} failed: the Google Contacts connection is no longer authorized. Reconnect the account.${suffix}`
+ );
+ }
+ if (status === 403) {
+ return new Error(
+ `${operation} failed: the connected Google account is not allowed to perform it, or the connection is missing the required scope.${suffix}`
+ );
+ }
+ if (status === 404) {
+ return new Error(
+ `${operation} failed: the resource was not found. Resource names are opaque, so resolve a current one with the matching list or search action.${suffix}`
+ );
+ }
+ if (status === 409) {
+ return new Error(`${operation} failed: the resource already exists.${suffix}`);
+ }
+ if (status === 429) {
+ return new Error(
+ `${operation} failed: Google Contacts rate limit reached. Retry later.${suffix}`
+ );
+ }
+ return new Error(`${operation} failed.${suffix}`);
+}
+
+function isConflict({ error }: { error: unknown }): boolean {
+ return readValue({ source: error, path: ['response', 'status'] }) === 409;
+}
+
+async function sendRequest({
+ accessToken,
+ method,
+ path,
+ queryParams,
+ repeatedQueryParams,
+ body,
+}: {
+ accessToken: string;
+ method: HttpMethod;
+ path: string;
+ queryParams?: Record<string, string | undefined>;
+ repeatedQueryParams?: Record<string, string[]>;
+ body?: Record<string, unknown>;
+}): Promise<Record<string, unknown>> {
+ const request: HttpRequest<Record<string, unknown>> = {
+ method,
+ url: buildUrl({ path, queryParams, repeatedQueryParams }),
+ body,
+ authentication: {
+ type: AuthenticationType.BEARER_TOKEN,
+ token: accessToken,
+ },
+ };
+ const response = await httpClient.sendRequest<Record<string, unknown>>(request);
+ return response.body ?? {};
+}
+
export const googleContactsCommon = {
baseUrl: `https://people.googleapis.com/v1/people`,
};
+
+export const googleContactsApi = {
+ contactReadMask,
+ contactGroupFields,
+ updatablePersonFields,
+ systemGroupsRejectingAdds,
+ sendRequest,
+ toApiError,
+ isConflict,
+ readValue,
+ readString,
+ readRecord,
+ readArray,
+ toStringList,
+ assertBatchSize,
+ splitItemResponses,
+ describeStatus,
+ isFailedItem,
+};
diff --git a/packages/pieces/community/google-contacts/src/lib/common/person.ts b/packages/pieces/community/google-contacts/src/lib/common/person.ts
new file mode 100644
index 00000000000..289f1ddb00c
--- /dev/null
+++ b/packages/pieces/community/google-contacts/src/lib/common/person.ts
@@ -0,0 +1,157 @@
+import { googleContactsApi } from './index';
+
+function mergeFirstEntry({
+ current,
+ group,
+ overrides,
+ defaults,
+}: {
+ current: Record<string, unknown> | undefined;
+ group: string;
+ overrides: Record<string, unknown>;
+ defaults?: Record<string, unknown>;
+}): unknown[] {
+ const entries = googleContactsApi.readArray({ source: current, path: [group] });
+ const head = entries[0];
+ const base =
+ typeof head === 'object' && head !== null && !Array.isArray(head)
+ ? Object.fromEntries(Object.entries(head))
+ : {};
+ return [{ ...defaults, ...base, ...overrides }, ...entries.slice(1)];
+}
+
+function buildPerson({
+ input,
+ current,
+}: {
+ input: ContactInput;
+ current?: Record<string, unknown>;
+}): { person: Record<string, unknown>; fields: string[] } {
+ const person: Record<string, unknown> = {};
+ const fields: string[] = [];
+
+ const nameSupplied =
+ input.firstName !== undefined ||
+ input.middleName !== undefined ||
+ input.lastName !== undefined;
+ if (nameSupplied) {
+ person['names'] = mergeFirstEntry({
+ current,
+ group: 'names',
+ overrides: {
+ ...(input.firstName === undefined ? {} : { givenName: input.firstName }),
+ ...(input.middleName === undefined ? {} : { middleName: input.middleName }),
+ ...(input.lastName === undefined ? {} : { familyName: input.lastName }),
+ },
+ });
+ fields.push('names');
+ }
+
+ if (input.nickname !== undefined) {
+ person['nicknames'] = mergeFirstEntry({
+ current,
+ group: 'nicknames',
+ overrides: { value: input.nickname },
+ });
+ fields.push('nicknames');
+ }
+
+ if (input.clearEmails === true) {
+ person['emailAddresses'] = [];
+ fields.push('emailAddresses');
+ } else if (input.emails !== undefined && input.emails.length > 0) {
+ person['emailAddresses'] = input.emails.map((value) => ({ value }));
+ fields.push('emailAddresses');
+ }
+
+ if (input.clearPhoneNumbers === true) {
+ person['phoneNumbers'] = [];
+ fields.push('phoneNumbers');
+ } else if (input.phoneNumbers !== undefined && input.phoneNumbers.length > 0) {
+ person['phoneNumbers'] = input.phoneNumbers.map((value) => ({ value }));
+ fields.push('phoneNumbers');
+ }
+
+ const organizationSupplied =
+ input.company !== undefined || input.jobTitle !== undefined;
+ if (organizationSupplied) {
+ person['organizations'] = mergeFirstEntry({
+ current,
+ group: 'organizations',
+ overrides: {
+ ...(input.company === undefined ? {} : { name: input.company }),
+ ...(input.jobTitle === undefined ? {} : { title: input.jobTitle }),
+ },
+ });
+ fields.push('organizations');
+ }
+
+ if (input.biography !== undefined) {
+ person['biographies'] = mergeFirstEntry({
+ current,
+ group: 'biographies',
+ overrides: { value: input.biography },
+ defaults: { contentType: 'TEXT_PLAIN' },
+ });
+ fields.push('biographies');
+ }
+
+ return { person, fields };
+}
+
+function valuesOf({
+ person,
+ group,
+}: {
+ person: unknown;
+ group: string;
+}): string[] {
+ const entries = googleContactsApi.readArray({ source: person, path: [group] });
+ const values = entries.map((entry) =>
+ googleContactsApi.readString({ source: entry, path: ['value'] })
+ );
+ return values.filter((value): value is string => value !== undefined);
+}
+
+function summarizePerson({ person }: { person: unknown }): Record<string, unknown> {
+ const name = googleContactsApi.readArray({ source: person, path: ['names'] })[0];
+ const organization = googleContactsApi.readArray({
+ source: person,
+ path: ['organizations'],
+ })[0];
+ const source = googleContactsApi.readArray({
+ source: person,
+ path: ['metadata', 'sources'],
+ })[0];
+ return {
+ resourceName: googleContactsApi.readString({ source: person, path: ['resourceName'] }),
+ etag: googleContactsApi.readString({ source: person, path: ['etag'] }),
+ displayName: googleContactsApi.readString({ source: name, path: ['displayName'] }),
+ givenName: googleContactsApi.readString({ source: name, path: ['givenName'] }),
+ familyName: googleContactsApi.readString({ source: name, path: ['familyName'] }),
+ emails: valuesOf({ person, group: 'emailAddresses' }),
+ phoneNumbers: valuesOf({ person, group: 'phoneNumbers' }),
+ company: googleContactsApi.readString({ source: organization, path: ['name'] }),
+ jobTitle: googleContactsApi.readString({ source: organization, path: ['title'] }),
+ updateTime: googleContactsApi.readString({ source: source, path: ['updateTime'] }),
+ };
+}
+
+export const googleContactsPerson = {
+ buildPerson,
+ summarizePerson,
+};
+
+export type ContactInput = {
+ firstName?: string;
+ middleName?: string;
+ lastName?: string;
+ nickname?: string;
+ emails?: string[];
+ phoneNumbers?: string[];
+ clearEmails?: boolean;
+ clearPhoneNumbers?: boolean;
+ company?: string;
+ jobTitle?: string;
+ biography?: string;
+};
diff --git a/packages/pieces/community/google-contacts/src/lib/output-schemas.ts b/packages/pieces/community/google-contacts/src/lib/output-schemas.ts
index 7576a5c9257..988b789e985 100644
--- a/packages/pieces/community/google-contacts/src/lib/output-schemas.ts
+++ b/packages/pieces/community/google-contacts/src/lib/output-schemas.ts
@@ -1,9 +1,5 @@
import { OutputSchema } from '@activepieces/pieces-framework';
-// Google People returns every contact detail as a repeated field: a contact can hold several
-// names, emails, phone numbers and organizations, each carrying its own `metadata`. Only the
-// `metadata.primary` flag is surfaced from that block -- the rest (source ids, per-field etags)
-// is server bookkeeping that says nothing about the contact.
const nameFields: OutputSchema['fields'] = [
{ key: 'displayName', label: 'Display Name' },
{ key: 'givenName', label: 'First Name' },
@@ -21,11 +17,21 @@ const emailFields: OutputSchema['fields'] = [
const phoneFields: OutputSchema['fields'] = [
{ key: 'value', label: 'Phone Number' },
- // Google normalises to E.164 here; the raw `value` keeps whatever the user typed.
{ key: 'canonicalForm', label: 'Canonical Form' },
{ key: 'primary', label: 'Primary', value: 'metadata.primary', format: 'boolean' },
];
+const nicknameFields: OutputSchema['fields'] = [
+ { key: 'value', label: 'Nickname' },
+ { key: 'primary', label: 'Primary', value: 'metadata.primary', format: 'boolean' },
+];
+
+const biographyFields: OutputSchema['fields'] = [
+ { key: 'value', label: 'Notes' },
+ { key: 'contentType', label: 'Content Type' },
+ { key: 'primary', label: 'Primary', value: 'metadata.primary', format: 'boolean' },
+];
+
const organizationFields: OutputSchema['fields'] = [
{ key: 'name', label: 'Company' },
{ key: 'title', label: 'Job Title' },
@@ -34,7 +40,6 @@ const organizationFields: OutputSchema['fields'] = [
const photoFields: OutputSchema['fields'] = [
{ key: 'url', label: 'Photo URL', format: 'image' },
- // True when this is Google's generated placeholder rather than a photo the contact has.
{ key: 'default', label: 'Is Placeholder', format: 'boolean' },
{ key: 'primary', label: 'Primary', value: 'metadata.primary', format: 'boolean' },
];
@@ -61,18 +66,13 @@ const metadataFields: OutputSchema['fields'] = [
listItems: [
{ key: 'type', label: 'Source Type' },
{ key: 'id', label: 'Source ID' },
- // The only timestamp on a contact, and what the polling trigger orders and dedupes on.
{ key: 'updateTime', label: 'Last Updated', format: 'datetime' },
],
},
];
-// One person record. Shared by every action and the trigger, because People returns the same
-// shape whether the contact was just created, just updated, matched by a search, or polled.
const personFields: OutputSchema['fields'] = [
- // `people/{person_id}` -- the id Update Contact requires.
{ key: 'resourceName', label: 'Resource Name' },
- // Required alongside resourceName on update; the call is rejected if the contact moved on.
{ key: 'etag', label: 'ETag' },
{ key: 'names', label: 'Names', labelKey: 'displayName', listItems: nameFields },
{
@@ -87,6 +87,8 @@ const personFields: OutputSchema['fields'] = [
labelKey: 'value',
listItems: phoneFields,
},
+ { key: 'nicknames', label: 'Nicknames', labelKey: 'value', listItems: nicknameFields },
+ { key: 'biographies', label: 'Notes', labelKey: 'value', listItems: biographyFields },
{
key: 'organizations',
label: 'Organizations',
@@ -97,14 +99,51 @@ const personFields: OutputSchema['fields'] = [
{
key: 'memberships',
label: 'Group Memberships',
- // labelKey resolves by dot path against the raw item, so it has to name the nested
- // property rather than the flattened key used in membershipFields.
labelKey: 'contactGroupMembership.contactGroupId',
listItems: membershipFields,
},
{ key: 'metadata', label: 'Metadata', children: metadataFields },
];
+const contactSummaryFields: OutputSchema['fields'] = [
+ { key: 'resourceName', label: 'Resource Name' },
+ { key: 'etag', label: 'ETag' },
+ { key: 'displayName', label: 'Display Name' },
+ { key: 'givenName', label: 'First Name' },
+ { key: 'familyName', label: 'Last Name' },
+ { key: 'emails', label: 'Email Addresses' },
+ { key: 'phoneNumbers', label: 'Phone Numbers' },
+ { key: 'company', label: 'Company' },
+ { key: 'jobTitle', label: 'Job Title' },
+ { key: 'updateTime', label: 'Last Updated', format: 'datetime' },
+];
+
+const contactGroupSummaryFields: OutputSchema['fields'] = [
+ { key: 'resourceName', label: 'Resource Name' },
+ { key: 'etag', label: 'ETag' },
+ { key: 'name', label: 'Name' },
+ { key: 'formattedName', label: 'Formatted Name' },
+ { key: 'groupType', label: 'Group Type' },
+ { key: 'memberCount', label: 'Member Count', format: 'number' },
+ { key: 'memberResourceNames', label: 'Member Resource Names' },
+];
+
+const batchFailureFields: OutputSchema['fields'] = [
+ { key: 'resourceName', label: 'Resource Name' },
+ { key: 'status', label: 'Failure Reason' },
+];
+
+const batchUpdateFailureFields: OutputSchema['fields'] = [
+ { key: 'resourceName', label: 'Resource Name' },
+ { key: 'status', label: 'Failure Reason' },
+ { key: 'updateMask', label: 'Field Groups Not Applied' },
+];
+
+const batchCreateFailureFields: OutputSchema['fields'] = [
+ { key: 'requestIndex', label: 'Request Index', format: 'number' },
+ { key: 'status', label: 'Failure Reason' },
+];
+
export const addContactOutputSchema: OutputSchema = {
fields: personFields,
};
@@ -113,9 +152,6 @@ export const updateContactOutputSchema: OutputSchema = {
fields: personFields,
};
-// searchContacts wraps each hit as `{ person: {...} }` under a `results` array, so the person
-// fields sit one level deeper than they do on the other three steps. Which of them are actually
-// populated follows the caller's Read Mask -- the default is names and email addresses only.
export const searchContactsOutputSchema: OutputSchema = {
fields: [
{
@@ -128,7 +164,209 @@ export const searchContactsOutputSchema: OutputSchema = {
],
};
-// The polling trigger emits one person per run, so its payload is a person record directly.
export const newOrUpdatedContactOutputSchema: OutputSchema = {
fields: personFields,
};
+
+export const createContactOutputSchema: OutputSchema = {
+ fields: personFields,
+};
+
+export const getContactOutputSchema: OutputSchema = {
+ fields: personFields,
+};
+
+export const updateContactFieldsOutputSchema: OutputSchema = {
+ fields: personFields,
+};
+
+export const listContactsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'contacts',
+ label: 'Contacts',
+ labelKey: 'displayName',
+ listItems: contactSummaryFields,
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ { key: 'hasMore', label: 'Has More', format: 'boolean' },
+ ],
+};
+
+export const searchContactsAtomicOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'results',
+ label: 'Matching Contacts',
+ labelKey: 'displayName',
+ listItems: contactSummaryFields,
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+};
+
+export const deleteContactOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ { key: 'resourceName', label: 'Resource Name' },
+ ],
+};
+
+export const batchDeleteContactsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ { key: 'resourceNames', label: 'Resource Names' },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+};
+
+export const batchGetContactsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'succeeded',
+ label: 'Contacts Read',
+ labelKey: 'contact.displayName',
+ listItems: [
+ { key: 'resourceName', label: 'Resource Name' },
+ { key: 'contact', label: 'Contact', children: contactSummaryFields },
+ { key: 'person', label: 'Full Person', children: personFields },
+ ],
+ },
+ {
+ key: 'failed',
+ label: 'Failures',
+ labelKey: 'resourceName',
+ listItems: batchFailureFields,
+ },
+ { key: 'succeededCount', label: 'Succeeded Count', format: 'number' },
+ { key: 'failedCount', label: 'Failed Count', format: 'number' },
+ ],
+};
+
+export const batchCreateContactsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'succeeded',
+ label: 'Contacts Created',
+ labelKey: 'contact.displayName',
+ listItems: [
+ { key: 'requestIndex', label: 'Request Index', format: 'number' },
+ { key: 'resourceName', label: 'Resource Name' },
+ { key: 'contact', label: 'Contact', children: contactSummaryFields },
+ ],
+ },
+ {
+ key: 'failed',
+ label: 'Failures',
+ labelKey: 'requestIndex',
+ listItems: batchCreateFailureFields,
+ },
+ { key: 'succeededCount', label: 'Succeeded Count', format: 'number' },
+ { key: 'failedCount', label: 'Failed Count', format: 'number' },
+ { key: 'requestedCount', label: 'Requested Count', format: 'number' },
+ ],
+};
+
+export const batchUpdateContactsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'succeeded',
+ label: 'Contacts Updated',
+ labelKey: 'contact.displayName',
+ listItems: [
+ { key: 'resourceName', label: 'Resource Name' },
+ { key: 'contact', label: 'Contact', children: contactSummaryFields },
+ { key: 'person', label: 'Full Person', children: personFields },
+ ],
+ },
+ {
+ key: 'failed',
+ label: 'Failures',
+ labelKey: 'resourceName',
+ listItems: batchUpdateFailureFields,
+ },
+ { key: 'succeededCount', label: 'Succeeded Count', format: 'number' },
+ { key: 'failedCount', label: 'Failed Count', format: 'number' },
+ { key: 'updateMasks', label: 'Update Masks' },
+ ],
+};
+
+export const updateContactPhotoOutputSchema: OutputSchema = {
+ fields: personFields,
+};
+
+export const deleteContactPhotoOutputSchema: OutputSchema = {
+ fields: personFields,
+};
+
+export const listContactGroupsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'contactGroups',
+ label: 'Contact Groups',
+ labelKey: 'formattedName',
+ listItems: contactGroupSummaryFields,
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ { key: 'hasMore', label: 'Has More', format: 'boolean' },
+ ],
+};
+
+export const getContactGroupOutputSchema: OutputSchema = {
+ fields: contactGroupSummaryFields,
+};
+
+export const updateContactGroupOutputSchema: OutputSchema = {
+ fields: contactGroupSummaryFields,
+};
+
+export const batchGetContactGroupsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'succeeded',
+ label: 'Contact Groups Read',
+ labelKey: 'formattedName',
+ listItems: contactGroupSummaryFields,
+ },
+ {
+ key: 'failed',
+ label: 'Failures',
+ labelKey: 'resourceName',
+ listItems: batchFailureFields,
+ },
+ { key: 'succeededCount', label: 'Succeeded Count', format: 'number' },
+ { key: 'failedCount', label: 'Failed Count', format: 'number' },
+ ],
+};
+
+export const createContactGroupOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'created', label: 'Created', format: 'boolean' },
+ {
+ key: 'contactGroup',
+ label: 'Contact Group',
+ children: contactGroupSummaryFields,
+ },
+ ],
+};
+
+export const deleteContactGroupOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ { key: 'resourceName', label: 'Resource Name' },
+ { key: 'deletedContacts', label: 'Contacts Also Deleted', format: 'boolean' },
+ ],
+};
+
+export const modifyContactGroupMembersOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'resourceName', label: 'Contact Group Resource Name' },
+ { key: 'added', label: 'Added Contacts' },
+ { key: 'removed', label: 'Removed Contacts' },
+ { key: 'notFoundResourceNames', label: 'Not Found Contacts' },
+ {
+ key: 'canNotRemoveLastContactGroupResourceNames',
+ label: 'Cannot Remove Last Group',
+ },
+ ],
+};