AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(blocks): Add Airtable Integration (#10338)
Swiftyc955e9a4d73e
diff --git a/autogpt_platform/backend/backend/blocks/airtable/__init__.py b/autogpt_platform/backend/backend/blocks/airtable/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/autogpt_platform/backend/backend/blocks/airtable/_api.py b/autogpt_platform/backend/backend/blocks/airtable/_api.pynew file mode 100644index 0000000000..2c3c8509c1--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/airtable/_api.py@@ -0,0 +1,1143 @@+import base64+from enum import Enum+from logging import getLogger+from typing import Any+from urllib.parse import quote, urlencode++from backend.sdk import BaseModel, Credentials, Requests++logger = getLogger(__name__)+++class WebhookFilters(BaseModel):+ dataTypes: list[str]+ changeTypes: list[str] | None = None+ fromSources: list[str] | None = None+ sourceOptions: dict | None = None+ watchDataInFieldIds: list[str] | None = None+ watchSchemasOfFieldIds: list[str] | None = None+++class WebhookIncludes(BaseModel):+ includeCellValuesInFieldIds: list[str] | str | None = None+ includePreviousCellValues: bool | None = None+ includePreviousFieldDefinitions: bool | None = None+++class WebhookSpecification(BaseModel):+ recordChangeScope: str | None = None+ filters: WebhookFilters+ includes: WebhookIncludes | None = None+++class WebhookPayload(BaseModel):+ actionMetadata: dict+ baseTransactionNumber: int+ payloadFormat: str+ timestamp: str+ changedTablesById: dict | None = None+ createdTablesById: dict | None = None+ destroyedTableIds: list[str] | None = None+ error: bool | None = None+ code: str | None = None+++class ListWebhookPayloadsResponse(BaseModel):+ payloads: list[WebhookPayload]+ cursor: int | None = None+ might_have_more: bool | None = None+ payloadFormat: str+++class TableFieldType(str, Enum):+ SINGLE_LINE_TEXT = "singleLineText"+ EMAIL = "email"+ URL = "url"+ MULTILINE_TEXT = "multilineText"+ NUMBER = "number"+ PERCENT = "percent"+ CURRENCY = "currency"+ SINGLE_SELECT = "singleSelect"+ MULTIPLE_SELECTS = "multipleSelects"+ SINGLE_COLLABORATOR = "singleCollaborator"+ MULTIPLE_COLLABORATORS = "multipleCollaborators"+ MULTIPLE_RECORD_LINKS = "multipleRecordLinks"+ DATE = "date"+ DATE_TIME = "dateTime"+ PHONE_NUMBER = "phoneNumber"+ MULTIPLE_ATTACHMENTS = "multipleAttachments"+ CHECKBOX = "checkbox"+ FORMULA = "formula"+ CREATED_TIME = "createdTime"+ ROLLUP = "rollup"+ COUNT = "count"+ LOOKUP = "lookup"+ MULTIPLE_LOOKUP_VALUES = "multipleLookupValues"+ AUTO_NUMBER = "autoNumber"+ BARCODE = "barcode"+ RATING = "rating"+ RICH_TEXT = "richText"+ DURATION = "duration"+ LAST_MODIFIED_TIME = "lastModifiedTime"+ BUTTON = "button"+ CREATED_BY = "createdBy"+ LAST_MODIFIED_BY = "lastModifiedBy"+ EXTERNAL_SYNC_SOURCE = "externalSyncSource"+ AI_TEXT = "aiText"+++TABLE_FIELD_TYPES = set(type.value for type in TableFieldType)+++class AirtableTimeZones(str, Enum):+ UTC = "utc"+ CLIENT = "client"+ AFRICA_ABIDJAN = "Africa/Abidjan"+ AFRICA_ACCRA = "Africa/Accra"+ AFRICA_ADDIS_ABABA = "Africa/Addis_Ababa"+ AFRICA_ALGIERS = "Africa/Algiers"+ AFRICA_ASMARA = "Africa/Asmara"+ AFRICA_BAMAKO = "Africa/Bamako"+ AFRICA_BANGUI = "Africa/Bangui"+ AFRICA_BANJUL = "Africa/Banjul"+ AFRICA_BISSAU = "Africa/Bissau"+ AFRICA_BLANTYRE = "Africa/Blantyre"+ AFRICA_BRAZZAVILLE = "Africa/Brazzaville"+ AFRICA_BUJUMBURA = "Africa/Bujumbura"+ AFRICA_CAIRO = "Africa/Cairo"+ AFRICA_CASABLANCA = "Africa/Casablanca"+ AFRICA_CEUTA = "Africa/Ceuta"+ AFRICA_CONAKRY = "Africa/Conakry"+ AFRICA_DAKAR = "Africa/Dakar"+ AFRICA_DAR_ES_SALAAM = "Africa/Dar_es_Salaam"+ AFRICA_DJIBOUTI = "Africa/Djibouti"+ AFRICA_DOUALA = "Africa/Douala"+ AFRICA_EL_AAIUN = "Africa/El_Aaiun"+ AFRICA_FREETOWN = "Africa/Freetown"+ AFRICA_GABORONE = "Africa/Gaborone"+ AFRICA_HARARE = "Africa/Harare"+ AFRICA_JOHANNESBURG = "Africa/Johannesburg"+ AFRICA_JUBA = "Africa/Juba"+ AFRICA_KAMPALA = "Africa/Kampala"+ AFRICA_KHARTOUM = "Africa/Khartoum"+ AFRICA_KIGALI = "Africa/Kigali"+ AFRICA_KINSHASA = "Africa/Kinshasa"+ AFRICA_LAGOS = "Africa/Lagos"+ AFRICA_LIBREVILLE = "Africa/Libreville"+ AFRICA_LOME = "Africa/Lome"+ AFRICA_LUANDA = "Africa/Luanda"+ AFRICA_LUBUMBASHI = "Africa/Lubumbashi"+ AFRICA_LUSAKA = "Africa/Lusaka"+ AFRICA_MALABO = "Africa/Malabo"+ AFRICA_MAPUTO = "Africa/Maputo"+ AFRICA_MASERU = "Africa/Maseru"+ AFRICA_MBABANE = "Africa/Mbabane"+ AFRICA_MOGADISHU = "Africa/Mogadishu"+ AFRICA_MONROVIA = "Africa/Monrovia"+ AFRICA_NAIROBI = "Africa/Nairobi"+ AFRICA_NDJAMENA = "Africa/Ndjamena"+ AFRICA_NIAMEY = "Africa/Niamey"+ AFRICA_NOUAKCHOTT = "Africa/Nouakchott"+ AFRICA_OUAGADOUGOU = "Africa/Ouagadougou"+ AFRICA_PORTO_NOVO = "Africa/Porto-Novo"+ AFRICA_SAO_TOME = "Africa/Sao_Tome"+ AFRICA_TRIPOLI = "Africa/Tripoli"+ AFRICA_TUNIS = "Africa/Tunis"+ AFRICA_WINDHOEK = "Africa/Windhoek"+ AMERICA_ADAK = "America/Adak"+ AMERICA_ANCHORAGE = "America/Anchorage"+ AMERICA_ANGUILLA = "America/Anguilla"+ AMERICA_ANTIGUA = "America/Antigua"+ AMERICA_ARAGUAINA = "America/Araguaina"+ AMERICA_ARGENTINA_BUENOS_AIRES = "America/Argentina/Buenos_Aires"+ AMERICA_ARGENTINA_CATAMARCA = "America/Argentina/Catamarca"+ AMERICA_ARGENTINA_CORDOBA = "America/Argentina/Cordoba"+ AMERICA_ARGENTINA_JUJUY = "America/Argentina/Jujuy"+ AMERICA_ARGENTINA_LA_RIOJA = "America/Argentina/La_Rioja"+ AMERICA_ARGENTINA_MENDOZA = "America/Argentina/Mendoza"+ AMERICA_ARGENTINA_RIO_GALLEGOS = "America/Argentina/Rio_Gallegos"+ AMERICA_ARGENTINA_SALTA = "America/Argentina/Salta"+ AMERICA_ARGENTINA_SAN_JUAN = "America/Argentina/San_Juan"+ AMERICA_ARGENTINA_SAN_LUIS = "America/Argentina/San_Luis"+ AMERICA_ARGENTINA_TUCUMAN = "America/Argentina/Tucuman"+ AMERICA_ARGENTINA_USHUAIA = "America/Argentina/Ushuaia"+ AMERICA_ARUBA = "America/Aruba"+ AMERICA_ASUNCION = "America/Asuncion"+ AMERICA_ATIKOKAN = "America/Atikokan"+ AMERICA_BAHIA = "America/Bahia"+ AMERICA_BAHIA_BANDERAS = "America/Bahia_Banderas"+ AMERICA_BARBADOS = "America/Barbados"+ AMERICA_BELEM = "America/Belem"+ AMERICA_BELIZE = "America/Belize"+ AMERICA_BLANC_SABLON = "America/Blanc-Sablon"+ AMERICA_BOA_VISTA = "America/Boa_Vista"+ AMERICA_BOGOTA = "America/Bogota"+ AMERICA_BOISE = "America/Boise"+ AMERICA_CAMBRIDGE_BAY = "America/Cambridge_Bay"+ AMERICA_CAMPO_GRANDE = "America/Campo_Grande"+ AMERICA_CANCUN = "America/Cancun"+ AMERICA_CARACAS = "America/Caracas"+ AMERICA_CAYENNE = "America/Cayenne"+ AMERICA_CAYMAN = "America/Cayman"+ AMERICA_CHICAGO = "America/Chicago"+ AMERICA_CHIHUAHUA = "America/Chihuahua"+ AMERICA_COSTA_RICA = "America/Costa_Rica"+ AMERICA_CRESTON = "America/Creston"+ AMERICA_CUIABA = "America/Cuiaba"+ AMERICA_CURACAO = "America/Curacao"+ AMERICA_DANMARKSHAVN = "America/Danmarkshavn"+ AMERICA_DAWSON = "America/Dawson"+ AMERICA_DAWSON_CREEK = "America/Dawson_Creek"+ AMERICA_DENVER = "America/Denver"+ AMERICA_DETROIT = "America/Detroit"+ AMERICA_DOMINICA = "America/Dominica"+ AMERICA_EDMONTON = "America/Edmonton"+ AMERICA_EIRUNEPE = "America/Eirunepe"+ AMERICA_EL_SALVADOR = "America/El_Salvador"+ AMERICA_FORT_NELSON = "America/Fort_Nelson"+ AMERICA_FORTALEZA = "America/Fortaleza"+ AMERICA_GLACE_BAY = "America/Glace_Bay"+ AMERICA_GODTHAB = "America/Godthab"+ AMERICA_GOOSE_BAY = "America/Goose_Bay"+ AMERICA_GRAND_TURK = "America/Grand_Turk"+ AMERICA_GRENADA = "America/Grenada"+ AMERICA_GUADELOUPE = "America/Guadeloupe"+ AMERICA_GUATEMALA = "America/Guatemala"+ AMERICA_GUAYAQUIL = "America/Guayaquil"+ AMERICA_GUYANA = "America/Guyana"+ AMERICA_HALIFAX = "America/Halifax"+ AMERICA_HAVANA = "America/Havana"+ AMERICA_HERMOSILLO = "America/Hermosillo"+ AMERICA_INDIANA_INDIANAPOLIS = "America/Indiana/Indianapolis"+ AMERICA_INDIANA_KNOX = "America/Indiana/Knox"+ AMERICA_INDIANA_MARENGO = "America/Indiana/Marengo"+ AMERICA_INDIANA_PETERSBURG = "America/Indiana/Petersburg"+ AMERICA_INDIANA_TELL_CITY = "America/Indiana/Tell_City"+ AMERICA_INDIANA_VEVAY = "America/Indiana/Vevay"+ AMERICA_INDIANA_VINCENNES = "America/Indiana/Vincennes"+ AMERICA_INDIANA_WINAMAC = "America/Indiana/Winamac"+ AMERICA_INUVIK = "America/Inuvik"+ AMERICA_IQALUIT = "America/Iqaluit"+ AMERICA_JAMAICA = "America/Jamaica"+ AMERICA_JUNEAU = "America/Juneau"+ AMERICA_KENTUCKY_LOUISVILLE = "America/Kentucky/Louisville"+ AMERICA_KENTUCKY_MONTICELLO = "America/Kentucky/Monticello"+ AMERICA_KRALENDIJK = "America/Kralendijk"+ AMERICA_LA_PAZ = "America/La_Paz"+ AMERICA_LIMA = "America/Lima"+ AMERICA_LOS_ANGELES = "America/Los_Angeles"+ AMERICA_LOWER_PRINCES = "America/Lower_Princes"+ AMERICA_MACEIO = "America/Maceio"+ AMERICA_MANAGUA = "America/Managua"+ AMERICA_MANAUS = "America/Manaus"+ AMERICA_MARIGOT = "America/Marigot"+ AMERICA_MARTINIQUE = "America/Martinique"+ AMERICA_MATAMOROS = "America/Matamoros"+ AMERICA_MAZATLAN = "America/Mazatlan"+ AMERICA_MENOMINEE = "America/Menominee"+ AMERICA_MERIDA = "America/Merida"+ AMERICA_METLAKATLA = "America/Metlakatla"+ AMERICA_MEXICO_CITY = "America/Mexico_City"+ AMERICA_MIQUELON = "America/Miquelon"+ AMERICA_MONCTON = "America/Moncton"+ AMERICA_MONTERREY = "America/Monterrey"+ AMERICA_MONTEVIDEO = "America/Montevideo"+ AMERICA_MONTSERRAT = "America/Montserrat"+ AMERICA_NASSAU = "America/Nassau"+ AMERICA_NEW_YORK = "America/New_York"+ AMERICA_NIPIGON = "America/Nipigon"+ AMERICA_NOME = "America/Nome"+ AMERICA_NORONHA = "America/Noronha"+ AMERICA_NORTH_DAKOTA_BEULAH = "America/North_Dakota/Beulah"+ AMERICA_NORTH_DAKOTA_CENTER = "America/North_Dakota/Center"+ AMERICA_NORTH_DAKOTA_NEW_SALEM = "America/North_Dakota/New_Salem"+ AMERICA_NUUK = "America/Nuuk"+ AMERICA_OJINAGA = "America/Ojinaga"+ AMERICA_PANAMA = "America/Panama"+ AMERICA_PANGNIRTUNG = "America/Pangnirtung"+ AMERICA_PARAMARIBO = "America/Paramaribo"+ AMERICA_PHOENIX = "America/Phoenix"+ AMERICA_PORT_AU_PRINCE = "America/Port-au-Prince"+ AMERICA_PORT_OF_SPAIN = "America/Port_of_Spain"+ AMERICA_PORTO_VELHO = "America/Porto_Velho"+ AMERICA_PUERTO_RICO = "America/Puerto_Rico"+ AMERICA_PUNTA_ARENAS = "America/Punta_Arenas"+ AMERICA_RAINY_RIVER = "America/Rainy_River"+ AMERICA_RANKIN_INLET = "America/Rankin_Inlet"+ AMERICA_RECIFE = "America/Recife"+ AMERICA_REGINA = "America/Regina"+ AMERICA_RESOLUTE = "America/Resolute"+ AMERICA_RIO_BRANCO = "America/Rio_Branco"+ AMERICA_SANTAREM = "America/Santarem"+ AMERICA_SANTIAGO = "America/Santiago"+ AMERICA_SANTO_DOMINGO = "America/Santo_Domingo"+ AMERICA_SAO_PAULO = "America/Sao_Paulo"+ AMERICA_SCORESBYSUND = "America/Scoresbysund"+ AMERICA_SITKA = "America/Sitka"+ AMERICA_ST_BARTHELEMY = "America/St_Barthelemy"+ AMERICA_ST_JOHNS = "America/St_Johns"+ AMERICA_ST_KITTS = "America/St_Kitts"+ AMERICA_ST_LUCIA = "America/St_Lucia"+ AMERICA_ST_THOMAS = "America/St_Thomas"+ AMERICA_ST_VINCENT = "America/St_Vincent"+ AMERICA_SWIFT_CURRENT = "America/Swift_Current"+ AMERICA_TEGUCIGALPA = "America/Tegucigalpa"+ AMERICA_THULE = "America/Thule"+ AMERICA_THUNDER_BAY = "America/Thunder_Bay"+ AMERICA_TIJUANA = "America/Tijuana"+ AMERICA_TORONTO = "America/Toronto"+ AMERICA_TORTOLA = "America/Tortola"+ AMERICA_VANCOUVER = "America/Vancouver"+ AMERICA_WHITEHORSE = "America/Whitehorse"+ AMERICA_WINNIPEG = "America/Winnipeg"+ AMERICA_YAKUTAT = "America/Yakutat"+ AMERICA_YELLOWKNIFE = "America/Yellowknife"+ ANTARCTICA_CASEY = "Antarctica/Casey"+ ANTARCTICA_DAVIS = "Antarctica/Davis"+ ANTARCTICA_DUMONT_DURVILLE = "Antarctica/DumontDUrville"+ ANTARCTICA_MACQUARIE = "Antarctica/Macquarie"+ ANTARCTICA_MAWSON = "Antarctica/Mawson"+ ANTARCTICA_MCMURDO = "Antarctica/McMurdo"+ ANTARCTICA_PALMER = "Antarctica/Palmer"+ ANTARCTICA_ROTHERA = "Antarctica/Rothera"+ ANTARCTICA_SYOWA = "Antarctica/Syowa"+ ANTARCTICA_TROLL = "Antarctica/Troll"+ ANTARCTICA_VOSTOK = "Antarctica/Vostok"+ ARCTIC_LONGYEARBYEN = "Arctic/Longyearbyen"+ ASIA_ADEN = "Asia/Aden"+ ASIA_ALMATY = "Asia/Almaty"+ ASIA_AMMAN = "Asia/Amman"+ ASIA_ANADYR = "Asia/Anadyr"+ ASIA_AQTAU = "Asia/Aqtau"+ ASIA_AQTOBE = "Asia/Aqtobe"+ ASIA_ASHGABAT = "Asia/Ashgabat"+ ASIA_ATYRAU = "Asia/Atyrau"+ ASIA_BAGHDAD = "Asia/Baghdad"+ ASIA_BAHRAIN = "Asia/Bahrain"+ ASIA_BAKU = "Asia/Baku"+ ASIA_BANGKOK = "Asia/Bangkok"+ ASIA_BARNAUL = "Asia/Barnaul"+ ASIA_BEIRUT = "Asia/Beirut"+ ASIA_BISHKEK = "Asia/Bishkek"+ ASIA_BRUNEI = "Asia/Brunei"+ ASIA_CHITA = "Asia/Chita"+ ASIA_CHOIBALSAN = "Asia/Choibalsan"+ ASIA_COLOMBO = "Asia/Colombo"+ ASIA_DAMASCUS = "Asia/Damascus"+ ASIA_DHAKA = "Asia/Dhaka"+ ASIA_DILI = "Asia/Dili"+ ASIA_DUBAI = "Asia/Dubai"+ ASIA_DUSHANBE = "Asia/Dushanbe"+ ASIA_FAMAGUSTA = "Asia/Famagusta"+ ASIA_GAZA = "Asia/Gaza"+ ASIA_HEBRON = "Asia/Hebron"+ ASIA_HO_CHI_MINH = "Asia/Ho_Chi_Minh"+ ASIA_HONG_KONG = "Asia/Hong_Kong"+ ASIA_HOVD = "Asia/Hovd"+ ASIA_IRKUTSK = "Asia/Irkutsk"+ ASIA_ISTANBUL = "Asia/Istanbul"+ ASIA_JAKARTA = "Asia/Jakarta"+ ASIA_JAYAPURA = "Asia/Jayapura"+ ASIA_JERUSALEM = "Asia/Jerusalem"+ ASIA_KABUL = "Asia/Kabul"+ ASIA_KAMCHATKA = "Asia/Kamchatka"+ ASIA_KARACHI = "Asia/Karachi"+ ASIA_KATHMANDU = "Asia/Kathmandu"+ ASIA_KHANDYGA = "Asia/Khandyga"+ ASIA_KOLKATA = "Asia/Kolkata"+ ASIA_KRASNOYARSK = "Asia/Krasnoyarsk"+ ASIA_KUALA_LUMPUR = "Asia/Kuala_Lumpur"+ ASIA_KUCHING = "Asia/Kuching"+ ASIA_KUWAIT = "Asia/Kuwait"+ ASIA_MACAU = "Asia/Macau"+ ASIA_MAGADAN = "Asia/Magadan"+ ASIA_MAKASSAR = "Asia/Makassar"+ ASIA_MANILA = "Asia/Manila"+ ASIA_MUSCAT = "Asia/Muscat"+ ASIA_NICOSIA = "Asia/Nicosia"+ ASIA_NOVOKUZNETSK = "Asia/Novokuznetsk"+ ASIA_NOVOSIBIRSK = "Asia/Novosibirsk"+ ASIA_OMSK = "Asia/Omsk"+ ASIA_ORAL = "Asia/Oral"+ ASIA_PHNOM_PENH = "Asia/Phnom_Penh"+ ASIA_PONTIANAK = "Asia/Pontianak"+ ASIA_PYONGYANG = "Asia/Pyongyang"+ ASIA_QATAR = "Asia/Qatar"+ ASIA_QOSTANAY = "Asia/Qostanay"+ ASIA_QYZYLORDA = "Asia/Qyzylorda"+ ASIA_RANGOON = "Asia/Rangoon"+ ASIA_RIYADH = "Asia/Riyadh"+ ASIA_SAKHALIN = "Asia/Sakhalin"+ ASIA_SAMARKAND = "Asia/Samarkand"+ ASIA_SEOUL = "Asia/Seoul"+ ASIA_SHANGHAI = "Asia/Shanghai"+ ASIA_SINGAPORE = "Asia/Singapore"+ ASIA_SREDNEKOLYMSK = "Asia/Srednekolymsk"+ ASIA_TAIPEI = "Asia/Taipei"+ ASIA_TASHKENT = "Asia/Tashkent"+ ASIA_TBILISI = "Asia/Tbilisi"+ ASIA_TEHRAN = "Asia/Tehran"+ ASIA_THIMPHU = "Asia/Thimphu"+ ASIA_TOKYO = "Asia/Tokyo"+ ASIA_TOMSK = "Asia/Tomsk"+ ASIA_ULAANBAATAR = "Asia/Ulaanbaatar"+ ASIA_URUMQI = "Asia/Urumqi"+ ASIA_UST_NERA = "Asia/Ust-Nera"+ ASIA_VIENTIANE = "Asia/Vientiane"+ ASIA_VLADIVOSTOK = "Asia/Vladivostok"+ ASIA_YAKUTSK = "Asia/Yakutsk"+ ASIA_YANGON = "Asia/Yangon"+ ASIA_YEKATERINBURG = "Asia/Yekaterinburg"+ ASIA_YEREVAN = "Asia/Yerevan"+ ATLANTIC_AZORES = "Atlantic/Azores"+ ATLANTIC_BERMUDA = "Atlantic/Bermuda"+ ATLANTIC_CANARY = "Atlantic/Canary"+ ATLANTIC_CAPE_VERDE = "Atlantic/Cape_Verde"+ ATLANTIC_FAROE = "Atlantic/Faroe"+ ATLANTIC_MADEIRA = "Atlantic/Madeira"+ ATLANTIC_REYKJAVIK = "Atlantic/Reykjavik"+ ATLANTIC_SOUTH_GEORGIA = "Atlantic/South_Georgia"+ ATLANTIC_ST_HELENA = "Atlantic/St_Helena"+ ATLANTIC_STANLEY = "Atlantic/Stanley"+ AUSTRALIA_ADELAIDE = "Australia/Adelaide"+ AUSTRALIA_BRISBANE = "Australia/Brisbane"+ AUSTRALIA_BROKEN_HILL = "Australia/Broken_Hill"+ AUSTRALIA_CURRIE = "Australia/Currie"+ AUSTRALIA_DARWIN = "Australia/Darwin"+ AUSTRALIA_EUCLA = "Australia/Eucla"+ AUSTRALIA_HOBART = "Australia/Hobart"+ AUSTRALIA_LINDEMAN = "Australia/Lindeman"+ AUSTRALIA_LORD_HOWE = "Australia/Lord_Howe"+ AUSTRALIA_MELBOURNE = "Australia/Melbourne"+ AUSTRALIA_PERTH = "Australia/Perth"+ AUSTRALIA_SYDNEY = "Australia/Sydney"+ EUROPE_AMSTERDAM = "Europe/Amsterdam"+ EUROPE_ANDORRA = "Europe/Andorra"+ EUROPE_ASTRAKHAN = "Europe/Astrakhan"+ EUROPE_ATHENS = "Europe/Athens"+ EUROPE_BELGRADE = "Europe/Belgrade"+ EUROPE_BERLIN = "Europe/Berlin"+ EUROPE_BRATISLAVA = "Europe/Bratislava"+ EUROPE_BRUSSELS = "Europe/Brussels"+ EUROPE_BUCHAREST = "Europe/Bucharest"+ EUROPE_BUDAPEST = "Europe/Budapest"+ EUROPE_BUSINGEN = "Europe/Busingen"+ EUROPE_CHISINAU = "Europe/Chisinau"+ EUROPE_COPENHAGEN = "Europe/Copenhagen"+ EUROPE_DUBLIN = "Europe/Dublin"+ EUROPE_GIBRALTAR = "Europe/Gibraltar"+ EUROPE_GUERNSEY = "Europe/Guernsey"+ EUROPE_HELSINKI = "Europe/Helsinki"+ EUROPE_ISLE_OF_MAN = "Europe/Isle_of_Man"+ EUROPE_ISTANBUL = "Europe/Istanbul"+ EUROPE_JERSEY = "Europe/Jersey"+ EUROPE_KALININGRAD = "Europe/Kaliningrad"+ EUROPE_KIEV = "Europe/Kiev"+ EUROPE_KIROV = "Europe/Kirov"+ EUROPE_LISBON = "Europe/Lisbon"+ EUROPE_LJUBLJANA = "Europe/Ljubljana"+ EUROPE_LONDON = "Europe/London"+ EUROPE_LUXEMBOURG = "Europe/Luxembourg"+ EUROPE_MADRID = "Europe/Madrid"+ EUROPE_MALTA = "Europe/Malta"+ EUROPE_MARIEHAMN = "Europe/Mariehamn"+ EUROPE_MINSK = "Europe/Minsk"+ EUROPE_MONACO = "Europe/Monaco"+ EUROPE_MOSCOW = "Europe/Moscow"+ EUROPE_NICOSIA = "Europe/Nicosia"+ EUROPE_OSLO = "Europe/Oslo"+ EUROPE_PARIS = "Europe/Paris"+ EUROPE_PODGORICA = "Europe/Podgorica"+ EUROPE_PRAGUE = "Europe/Prague"+ EUROPE_RIGA = "Europe/Riga"+ EUROPE_ROME = "Europe/Rome"+ EUROPE_SAMARA = "Europe/Samara"+ EUROPE_SAN_MARINO = "Europe/San_Marino"+ EUROPE_SARAJEVO = "Europe/Sarajevo"+ EUROPE_SARATOV = "Europe/Saratov"+ EUROPE_SIMFEROPOL = "Europe/Simferopol"+ EUROPE_SKOPJE = "Europe/Skopje"+ EUROPE_SOFIA = "Europe/Sofia"+ EUROPE_STOCKHOLM = "Europe/Stockholm"+ EUROPE_TALLINN = "Europe/Tallinn"+ EUROPE_TIRANE = "Europe/Tirane"+ EUROPE_ULYANOVSK = "Europe/Ulyanovsk"+ EUROPE_UZHGOROD = "Europe/Uzhgorod"+ EUROPE_VADUZ = "Europe/Vaduz"+ EUROPE_VATICAN = "Europe/Vatican"+ EUROPE_VIENNA = "Europe/Vienna"+ EUROPE_VILNIUS = "Europe/Vilnius"+ EUROPE_VOLGOGRAD = "Europe/Volgograd"+ EUROPE_WARSAW = "Europe/Warsaw"+ EUROPE_ZAGREB = "Europe/Zagreb"+ EUROPE_ZAPOROZHYE = "Europe/Zaporozhye"+ EUROPE_ZURICH = "Europe/Zurich"+ INDIAN_ANTANANARIVO = "Indian/Antananarivo"+ INDIAN_CHAGOS = "Indian/Chagos"+ INDIAN_CHRISTMAS = "Indian/Christmas"+ INDIAN_COCOS = "Indian/Cocos"+ INDIAN_COMORO = "Indian/Comoro"+ INDIAN_KERGUELEN = "Indian/Kerguelen"+ INDIAN_MAHE = "Indian/Mahe"+ INDIAN_MALDIVES = "Indian/Maldives"+ INDIAN_MAURITIUS = "Indian/Mauritius"+ INDIAN_MAYOTTE = "Indian/Mayotte"+ INDIAN_REUNION = "Indian/Reunion"+ PACIFIC_APIA = "Pacific/Apia"+ PACIFIC_AUCKLAND = "Pacific/Auckland"+ PACIFIC_BOUGAINVILLE = "Pacific/Bougainville"+ PACIFIC_CHATHAM = "Pacific/Chatham"+ PACIFIC_CHUUK = "Pacific/Chuuk"+ PACIFIC_EASTER = "Pacific/Easter"+ PACIFIC_EFATE = "Pacific/Efate"+ PACIFIC_ENDERBURY = "Pacific/Enderbury"+ PACIFIC_FAKAOFO = "Pacific/Fakaofo"+ PACIFIC_FIJI = "Pacific/Fiji"+ PACIFIC_FUNAFUTI = "Pacific/Funafuti"+ PACIFIC_GALAPAGOS = "Pacific/Galapagos"+ PACIFIC_GAMBIER = "Pacific/Gambier"+ PACIFIC_GUADALCANAL = "Pacific/Guadalcanal"+ PACIFIC_GUAM = "Pacific/Guam"+ PACIFIC_HONOLULU = "Pacific/Honolulu"+ PACIFIC_KANTON = "Pacific/Kanton"+ PACIFIC_KIRITIMATI = "Pacific/Kiritimati"+ PACIFIC_KOSRAE = "Pacific/Kosrae"+ PACIFIC_KWAJALEIN = "Pacific/Kwajalein"+ PACIFIC_MAJURO = "Pacific/Majuro"+ PACIFIC_MARQUESAS = "Pacific/Marquesas"+ PACIFIC_MIDWAY = "Pacific/Midway"+ PACIFIC_NAURU = "Pacific/Nauru"+ PACIFIC_NIUE = "Pacific/Niue"+ PACIFIC_NORFOLK = "Pacific/Norfolk"+ PACIFIC_NOUMEA = "Pacific/Noumea"+ PACIFIC_PAGO_PAGO = "Pacific/Pago_Pago"+ PACIFIC_PALAU = "Pacific/Palau"+ PACIFIC_PITCAIRN = "Pacific/Pitcairn"+ PACIFIC_POHNPEI = "Pacific/Pohnpei"+ PACIFIC_PORT_MORESBY = "Pacific/Port_Moresby"+ PACIFIC_RAROTONGA = "Pacific/Rarotonga"+ PACIFIC_SAIPAN = "Pacific/Saipan"+ PACIFIC_TAHITI = "Pacific/Tahiti"+ PACIFIC_TARAWA = "Pacific/Tarawa"+ PACIFIC_TONGATAPU = "Pacific/Tongatapu"+ PACIFIC_WAKE = "Pacific/Wake"+ PACIFIC_WALLIS = "Pacific/Wallis"+++#################################################################+# Schema Management (Tables and Fields)+# NOTE: No delete operations are available in the Airtable API+#################################################################+++async def create_table(+ credentials: Credentials,+ base_id: str,+ table_name: str,+ table_fields: list[dict],+) -> dict:+ for field in table_fields:+ assert field.get("name"), "Field name is required"+ assert (+ field.get("type") in TABLE_FIELD_TYPES+ ), f"Field type {field.get('type')} is not valid. Valid types are {TABLE_FIELD_TYPES}."+ # Note fields have differnet options for different types we are not currently validating them++ response = await Requests().post(+ f"https://api.airtable.com/v0/meta/bases/{base_id}/tables",+ headers={"Authorization": credentials.auth_header()},+ json={+ "name": table_name,+ "fields": table_fields,+ },+ )++ return response.json()+++async def update_table(+ credentials: Credentials,+ base_id: str,+ table_id: str,+ table_name: str | None = None,+ table_description: str | None = None,+ date_dependency: dict | None = None,+) -> dict:++ assert (+ table_name or table_description or date_dependency+ ), "At least one of table_name, table_description, or date_dependency must be provided"++ params: dict[str, str | dict[str, str]] = {}+ if table_name:+ params["name"] = table_name+ if table_description:+ params["description"] = table_description+ if date_dependency:+ params["dateDependency"] = date_dependency++ response = await Requests().patch(+ f"https://api.airtable.com/v0/meta/bases/{base_id}/tables/{table_id}",+ headers={"Authorization": credentials.auth_header()},+ json=params,+ )++ return response.json()+++async def create_field(+ credentials: Credentials,+ base_id: str,+ table_id: str,+ field_type: TableFieldType,+ name: str,+ description: str | None = None,+ options: dict[str, str] | None = None,+) -> dict[str, str | dict[str, str]]:++ assert (+ field_type in TABLE_FIELD_TYPES+ ), f"Field type {field_type} is not valid. Valid types are {TABLE_FIELD_TYPES}."+ params: dict[str, str | dict[str, str]] = {}+ params["type"] = field_type+ params["name"] = name+ if description:+ params["description"] = description+ if options:+ params["options"] = options++ response = await Requests().post(+ f"https://api.airtable.com/v0/meta/bases/{base_id}/tables/{table_id}/fields",+ headers={"Authorization": credentials.auth_header()},+ json=params,+ )+ return response.json()+++async def update_field(+ credentials: Credentials,+ base_id: str,+ table_id: str,+ field_id: str,+ name: str | None = None,+ description: str | None = None,+) -> dict[str, str]:++ assert name or description, "At least one of name or description must be provided"+ params: dict[str, str | dict[str, str]] = {}+ if name:+ params["name"] = name+ if description:+ params["description"] = description++ response = await Requests().patch(+ f"https://api.airtable.com/v0/meta/bases/{base_id}/tables/{table_id}/fields/{field_id}",+ headers={"Authorization": credentials.auth_header()},+ json=params,+ )+ return response.json()+++#################################################################+# Record Management+#################################################################+++async def list_records(+ credentials: Credentials,+ base_id: str,+ table_id_or_name: str,+ # Query parameters+ time_zone: AirtableTimeZones | None = None,+ user_local: str | None = None,+ page_size: int | None = None,+ max_records: int | None = None,+ offset: str | None = None,+ view: str | None = None,+ sort: list[dict[str, str]] | None = None,+ filter_by_formula: str | None = None,+ cell_format: dict[str, str] | None = None,+ fields: list[str] | None = None,+ return_fields_by_field_id: bool | None = None,+ record_metadata: list[str] | None = None,+) -> dict[str, list[dict[str, dict[str, str]]]]:++ params: dict[str, str | dict[str, str] | list[dict[str, str]] | list[str]] = {}+ if time_zone:+ params["timeZone"] = time_zone+ if user_local:+ params["userLocal"] = user_local+ if page_size:+ params["pageSize"] = str(page_size)+ if max_records:+ params["maxRecords"] = str(max_records)+ if offset:+ params["offset"] = offset+ if view:+ params["view"] = view+ if sort:+ params["sort"] = sort+ if filter_by_formula:+ params["filterByFormula"] = filter_by_formula+ if cell_format:+ params["cellFormat"] = cell_format+ if fields:+ params["fields"] = fields+ if return_fields_by_field_id:+ params["returnFieldsByFieldId"] = str(return_fields_by_field_id)+ if record_metadata:+ params["recordMetadata"] = record_metadata++ response = await Requests().get(+ f"https://api.airtable.com/v0/{base_id}/{table_id_or_name}",+ headers={"Authorization": credentials.auth_header()},+ params=params,+ )+ return response.json()+++async def get_record(+ credentials: Credentials,+ base_id: str,+ table_id_or_name: str,+ record_id: str,+) -> dict[str, dict[str, dict[str, str]]]:++ response = await Requests().get(+ f"https://api.airtable.com/v0/{base_id}/{table_id_or_name}/{record_id}",+ headers={"Authorization": credentials.auth_header()},+ )+ return response.json()+++async def update_multiple_records(+ credentials: Credentials,+ base_id: str,+ table_id_or_name: str,+ records: list[dict[str, dict[str, str]]],+ perform_upsert: dict[str, list[str]] | None = None,+ return_fields_by_field_id: bool | None = None,+ typecast: bool | None = None,+) -> dict[str, dict[str, dict[str, str]]]:++ params: dict[str, str | dict[str, list[str]] | list[dict[str, dict[str, str]]]] = {}+ if perform_upsert:+ params["performUpsert"] = perform_upsert+ if return_fields_by_field_id:+ params["returnFieldsByFieldId"] = str(return_fields_by_field_id)+ if typecast:+ params["typecast"] = str(typecast)++ params["records"] = records++ response = await Requests().patch(+ f"https://api.airtable.com/v0/{base_id}/{table_id_or_name}",+ headers={"Authorization": credentials.auth_header()},+ json=params,+ )+ return response.json()+++async def update_record(+ credentials: Credentials,+ base_id: str,+ table_id_or_name: str,+ record_id: str,+ return_fields_by_field_id: bool | None = None,+ typecast: bool | None = None,+ fields: dict[str, Any] | None = None,+) -> dict[str, dict[str, dict[str, str]]]:+ params: dict[str, str | dict[str, Any] | list[dict[str, dict[str, str]]]] = {}+ if return_fields_by_field_id:+ params["returnFieldsByFieldId"] = str(return_fields_by_field_id)+ if typecast:+ params["typecast"] = str(typecast)+ if fields:+ params["fields"] = fields++ response = await Requests().patch(+ f"https://api.airtable.com/v0/{base_id}/{table_id_or_name}/{record_id}",+ headers={"Authorization": credentials.auth_header()},+ json=params,+ )+ return response.json()+++async def create_record(+ credentials: Credentials,+ base_id: str,+ table_id_or_name: str,+ fields: dict[str, Any] | None = None,+ records: list[dict[str, Any]] | None = None,+ return_fields_by_field_id: bool | None = None,+ typecast: bool | None = None,+) -> dict[str, dict[str, dict[str, str]]]:+ assert fields or records, "At least one of fields or records must be provided"+ assert not (fields and records), "Only one of fields or records can be provided"+ if records is not None:+ assert (+ len(records) <= 10+ ), "Only up to 10 records can be provided when using records"++ params: dict[str, str | dict[str, Any] | list[dict[str, Any]]] = {}+ if fields:+ params["fields"] = fields+ if records:+ params["records"] = records+ if return_fields_by_field_id:+ params["returnFieldsByFieldId"] = str(return_fields_by_field_id)+ if typecast:+ params["typecast"] = str(typecast)++ response = await Requests().post(+ f"https://api.airtable.com/v0/{base_id}/{table_id_or_name}",+ headers={"Authorization": credentials.auth_header()},+ json=params,+ )+ return response.json()+++async def delete_multiple_records(+ credentials: Credentials,+ base_id: str,+ table_id_or_name: str,+ records: list[str],+) -> dict[str, dict[str, dict[str, str]]]:++ query_string = "&".join([f"records[]={quote(record)}" for record in records])+ response = await Requests().delete(+ f"https://api.airtable.com/v0/{base_id}/{table_id_or_name}?{query_string}",+ headers={"Authorization": credentials.auth_header()},+ )+ return response.json()+++async def delete_record(+ credentials: Credentials,+ base_id: str,+ table_id_or_name: str,+ record_id: str,+) -> dict[str, dict[str, dict[str, str]]]:++ response = await Requests().delete(+ f"https://api.airtable.com/v0/{base_id}/{table_id_or_name}/{record_id}",+ headers={"Authorization": credentials.auth_header()},+ )+ return response.json()+++async def create_webhook(+ credentials: Credentials,+ base_id: str,+ webhook_specification: WebhookSpecification,+ notification_url: str | None = None,+) -> Any:++ params: dict[str, Any] = {+ "specification": {+ "options": {+ "filters": webhook_specification.filters.model_dump(exclude_unset=True),+ }+ },+ }+ if webhook_specification.includes:+ params["specification"]["options"]["includes"] = (+ webhook_specification.includes.model_dump(exclude_unset=True)+ )+ if notification_url:+ params["notificationUrl"] = notification_url++ response = await Requests().post(+ f"https://api.airtable.com/v0/bases/{base_id}/webhooks",+ headers={"Authorization": credentials.auth_header()},+ json=params,+ )+ return response.json()+++async def delete_webhook(+ credentials: Credentials,+ base_id: str,+ webhook_id: str,+) -> Any:++ response = await Requests().delete(+ f"https://api.airtable.com/v0/bases/{base_id}/webhooks/{webhook_id}",+ headers={"Authorization": credentials.auth_header()},+ )+ return response.json()+++async def list_webhook_payloads(+ credentials: Credentials,+ base_id: str,+ webhook_id: str,+ cursor: str | None = None,+ limit: int | None = None,+) -> ListWebhookPayloadsResponse:++ query_string = ""+ if cursor:+ query_string += f"cursor={cursor}"+ if limit:+ query_string += f"limit={limit}"++ if query_string:+ query_string = f"?{query_string}"++ response = await Requests().get(+ f"https://api.airtable.com/v0/bases/{base_id}/webhooks/{webhook_id}/payloads{query_string}",+ headers={"Authorization": credentials.auth_header()},+ )+ try:+ logger.info(f"Response: {response.json()}")+ return ListWebhookPayloadsResponse(+ payloads=response.json().get("payloads", []),+ cursor=response.json().get("cursor"),+ might_have_more=response.json().get("might_have_more") == "True",+ payloadFormat=response.json().get("payloadFormat", "v0"),+ )+ except Exception as e:+ raise ValueError(+ f"Failed to validate webhook payloads response: {e}\nResponse: {response.json()}"+ )+++async def list_webhooks(+ credentials: Credentials,+ base_id: str,+) -> Any:++ response = await Requests().get(+ f"https://api.airtable.com/v0/bases/{base_id}/webhooks",+ headers={"Authorization": credentials.auth_header()},+ )+ return response.json()+++class OAuthAuthorizeRequest(BaseModel):+ """OAuth authorization request parameters for Airtable.++ Parameters:+ client_id: An opaque string that identifies your integration with Airtable+ redirect_uri: The URI for the authorize response redirect. Must exactly match a redirect URI+ associated with your integration. HTTPS is required for any URI beside localhost.+ response_type: The string "code"+ scope: A space delimited list of unique scopes. All scopes must be valid Airtable defined scopes+ that have been selected for your integration. At least one scope is required.+ state: A cryptographically generated, opaque string for CSRF protection+ code_challenge: The base64 url-encoding of the sha256 of the code_verifier. Protects against+ man-in-the-middle grant code injection attacks. Part of the PKCE extension of OAuth.+ code_challenge_method: The string "S256"+ """++ client_id: str+ redirect_uri: str+ response_type: str = "code"+ scope: str+ state: str+ code_challenge: str+ code_challenge_method: str = "S256"+++class OAuthTokenRequest(BaseModel):+ """OAuth token request parameters for Airtable.++ These parameters must be formatted via application/x-www-form-urlencoded encoding.++ Parameters:+ code: The grant code generated during the authorization request. Can only be used once.+ client_id: The client_id used in the authorization request that generated the code.+ Optional if your integration has a client_secret. Used to prevent MITM attacks.+ redirect_uri: The redirect_uri used in the authorization request that generated the code.+ Used to prevent MITM attacks.+ grant_type: The string "authorization_code".+ code_verifier: A cryptographically generated, opaque string used to generate the+ code_challenge parameter in the authorization request that generated the code.+ """++ code: str+ client_id: str+ redirect_uri: str+ grant_type: str = "authorization_code"+ code_verifier: str+++class OAuthRefreshTokenRequest(BaseModel):+ """OAuth token refresh request parameters for Airtable.++ These parameters must be formatted via application/x-www-form-urlencoded encoding.++ Parameters:+ refresh_token: The saved refresh token from the previous token grant.+ client_id: Required if your integration does not have a client_secret.+ Used to prevent MITM attacks.+ grant_type: The string "refresh_token".+ scope: If specified, a subset of the token's existing scopes. Optional.+ """++ refresh_token: str+ client_id: str | None = None+ grant_type: str = "refresh_token"+ scope: str | None = None+++class OAuthTokenResponse(BaseModel):+ """OAuth token response from Airtable.++ Successful response has HTTP status code 200 (OK).++ Parameters:+ access_token: An opaque string. Can be used to make requests to the Airtable API on behalf+ of the user, and cannot be recovered if lost.+ refresh_token: An opaque string. Can be used to request a new access token after the current+ one expires.+ token_type: The string "Bearer " (space intentional)+ scope: A string that is a space delimited list of scopes granted to this access token. Can be+ recovered using the get userId and scopes endpoint.+ expires_in: An integer. Time in seconds until the access token expires (expected value is 60 minutes).+ refresh_expires_in: An integer. Time in seconds until the refresh token expires (expected value is 60 days).+ """++ access_token: str+ refresh_token: str+ token_type: str+ scope: str+ expires_in: int+ refresh_expires_in: int+++def make_oauth_authorize_url(+ client_id: str,+ redirect_uri: str,+ scopes: list[str],+ state: str,+ code_challenge: str,+) -> str:+ """+ Generate the OAuth authorization URL for Airtable.++ Args:+ client_id: An opaque string that identifies your integration with Airtable+ redirect_uri: The URI for the authorize response redirect+ scope: A space delimited list of unique scopes+ state: A cryptographically generated, opaque string for CSRF protection+ code_challenge: The base64 url-encoding of the sha256 of the code_verifier+ code_challenge_method: The string "S256" (default)+ response_type: The string "code" (default)++ Returns:+ The authorization URL that the user should visit+ """+ # Validate the request parameters+ request_params = OAuthAuthorizeRequest(+ client_id=client_id,+ redirect_uri=redirect_uri,+ scope=" ".join(scopes),+ state=state,+ code_challenge=code_challenge,+ )++ # Build the authorization URL+ base_url = "https://airtable.com/oauth2/v1/authorize"+ query_string = urlencode(request_params.model_dump(exclude_none=True))++ return f"{base_url}?{query_string}"+++async def oauth_exchange_code_for_tokens(+ client_id: str,+ code_verifier: bytes,+ code: str,+ redirect_uri: str,+ client_secret: str | None = None,+) -> OAuthTokenResponse:+ """+ Exchange an authorization code for access and refresh tokens.++ Args:+ client_id: The Airtable integration client ID.+ code_verifier: The original code_verifier (required for PKCE).+ code: The authorization code returned by Airtable.+ redirect_uri: The redirect URI used during authorization.+ client_secret: Integration client secret if available (optional).++ Returns:+ Parsed JSON response containing the access token, refresh token, scope, etc.+ """++ headers = {+ "Content-Type": "application/x-www-form-urlencoded",+ }+ # Add Authorization header for confidential clients+ if client_secret:+ credentials_encoded = base64.urlsafe_b64encode(+ f"{client_id}:{client_secret}".encode()+ ).decode()+ headers["Authorization"] = f"Basic {credentials_encoded}"++ data = OAuthTokenRequest(+ code=code,+ client_id=client_id,+ redirect_uri=redirect_uri,+ grant_type="authorization_code",+ code_verifier=code_verifier.decode("utf-8"),+ ).model_dump(exclude_none=True)++ response = await Requests().post(+ "https://airtable.com/oauth2/v1/token",+ headers=headers,+ data=data,+ )++ if response.ok:+ return OAuthTokenResponse.model_validate(response.json())+ raise ValueError(+ f"Failed to exchange code for tokens: {response.status} {response.text}"+ )+++# NEW helper for refreshing tokens+async def oauth_refresh_tokens(+ client_id: str,+ refresh_token: str,+ client_secret: str | None = None,+) -> OAuthTokenResponse:+ """+ Refresh an expired (or soon-to-expire) access token.++ Args:+ client_id: The Airtable integration client ID.+ refresh_token: The refresh token previously issued by Airtable.+ client_secret: Integration client secret if available (optional).++ Returns:+ Parsed JSON response containing the new tokens and metadata.+ https://airtable.com/oauth2/v1/authorize?client_id=7642abbb-8fbc-494c-b6e0-58484364e28c&redirect_uri=https%3A%2F%2Fdev-builder.agpt.co%2Fauth%2Fintegrations%2Foauth_callback&response_type=code&scope=&state=OcmqX6Y5MTkhHLc6vkbR6uEtSiZHawzEUcxDscqkWRk&code_challenge=v2Ly1CcG8UkCXJ2n--TEKZc6HeKaN1wrZLgIr_qVnJ8&code_challenge_method=S256+ """++ headers = {+ "Content-Type": "application/x-www-form-urlencoded",+ }++ if client_secret:+ credentials_encoded = base64.urlsafe_b64encode(+ f"{client_id}:{client_secret}".encode()+ ).decode()+ headers["Authorization"] = f"Basic {credentials_encoded}"++ data = OAuthRefreshTokenRequest(+ refresh_token=refresh_token,+ client_id=client_id,+ grant_type="refresh_token",+ ).model_dump(exclude_none=True)++ response = await Requests().post(+ "https://airtable.com/oauth2/v1/token",+ headers=headers,+ data=data,+ )++ if response.ok:+ return OAuthTokenResponse.model_validate(response.json())+ raise ValueError(f"Failed to refresh tokens: {response.status} {response.text}")diff --git a/autogpt_platform/backend/backend/blocks/airtable/_api_test.py b/autogpt_platform/backend/backend/blocks/airtable/_api_test.pynew file mode 100644index 0000000000..59d323f551--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/airtable/_api_test.py@@ -0,0 +1,307 @@+from os import getenv+from uuid import uuid4++import pytest++from backend.sdk import APIKeyCredentials, SecretStr++from ._api import (+ TableFieldType,+ WebhookFilters,+ WebhookSpecification,+ create_field,+ create_record,+ create_table,+ create_webhook,+ delete_multiple_records,+ delete_record,+ delete_webhook,+ get_record,+ list_records,+ list_webhook_payloads,+ update_field,+ update_multiple_records,+ update_record,+ update_table,+)+++async def test_create_update_table():++ key = getenv("AIRTABLE_API_KEY")+ if not key:+ return pytest.skip("AIRTABLE_API_KEY is not set")++ credentials = APIKeyCredentials(+ provider="airtable",+ api_key=SecretStr(key),+ )+ postfix = uuid4().hex[:4]+ base_id = "appSbaQLkcYiIOqux"+ table_name = f"test_table_{postfix}"+ table_fields = [{"name": "test_field", "type": "singleLineText"}]+ table = await create_table(credentials, base_id, table_name, table_fields)+ assert table.get("name") == table_name++ table_id = table.get("id")++ assert table_id is not None++ table_name = f"test_table_updated_{postfix}"+ table_description = "test_description_updated"+ table = await update_table(+ credentials,+ base_id,+ table_id,+ table_name=table_name,+ table_description=table_description,+ )+ assert table.get("name") == table_name+ assert table.get("description") == table_description+++async def test_invalid_field_type():++ key = getenv("AIRTABLE_API_KEY")+ if not key:+ return pytest.skip("AIRTABLE_API_KEY is not set")++ credentials = APIKeyCredentials(+ provider="airtable",+ api_key=SecretStr(key),+ )+ postfix = uuid4().hex[:4]+ base_id = "appSbaQLkcYiIOqux"+ table_name = f"test_table_{postfix}"+ table_fields = [{"name": "test_field", "type": "notValid"}]+ with pytest.raises(AssertionError):+ await create_table(credentials, base_id, table_name, table_fields)+++async def test_create_and_update_field():+ key = getenv("AIRTABLE_API_KEY")+ if not key:+ return pytest.skip("AIRTABLE_API_KEY is not set")++ credentials = APIKeyCredentials(+ provider="airtable",+ api_key=SecretStr(key),+ )+ postfix = uuid4().hex[:4]+ base_id = "appSbaQLkcYiIOqux"+ table_name = f"test_table_{postfix}"+ table_fields = [{"name": "test_field", "type": "singleLineText"}]+ table = await create_table(credentials, base_id, table_name, table_fields)+ assert table.get("name") == table_name++ table_id = table.get("id")++ assert table_id is not None++ field_name = f"test_field_{postfix}"+ field_type = TableFieldType.SINGLE_LINE_TEXT+ field = await create_field(credentials, base_id, table_id, field_type, field_name)+ assert field.get("name") == field_name++ field_id = field.get("id")++ assert field_id is not None+ assert isinstance(field_id, str)++ field_name = f"test_field_updated_{postfix}"+ field = await update_field(credentials, base_id, table_id, field_id, field_name)+ assert field.get("name") == field_name++ field_description = "test_description_updated"+ field = await update_field(+ credentials, base_id, table_id, field_id, description=field_description+ )+ assert field.get("description") == field_description+++async def test_record_management():+ key = getenv("AIRTABLE_API_KEY")+ if not key:+ return pytest.skip("AIRTABLE_API_KEY is not set")++ credentials = APIKeyCredentials(+ provider="airtable",+ api_key=SecretStr(key),+ )+ postfix = uuid4().hex[:4]+ base_id = "appSbaQLkcYiIOqux"+ table_name = f"test_table_{postfix}"+ table_fields = [{"name": "test_field", "type": "singleLineText"}]+ table = await create_table(credentials, base_id, table_name, table_fields)+ assert table.get("name") == table_name++ table_id = table.get("id")+ assert table_id is not None++ # Create a record+ record_fields = {"test_field": "test_value"}+ record = await create_record(credentials, base_id, table_id, fields=record_fields)+ fields = record.get("fields")+ assert fields is not None+ assert isinstance(fields, dict)+ assert fields.get("test_field") == "test_value"++ record_id = record.get("id")++ assert record_id is not None+ assert isinstance(record_id, str)++ # Get a record+ record = await get_record(credentials, base_id, table_id, record_id)+ fields = record.get("fields")+ assert fields is not None+ assert isinstance(fields, dict)+ assert fields.get("test_field") == "test_value"++ # Updata a record+ record_fields = {"test_field": "test_value_updated"}+ record = await update_record(+ credentials, base_id, table_id, record_id, fields=record_fields+ )+ fields = record.get("fields")+ assert fields is not None+ assert isinstance(fields, dict)+ assert fields.get("test_field") == "test_value_updated"++ # Delete a record+ record = await delete_record(credentials, base_id, table_id, record_id)+ assert record is not None+ assert record.get("id") == record_id+ assert record.get("deleted")++ # Create 2 records+ records = [+ {"fields": {"test_field": "test_value_1"}},+ {"fields": {"test_field": "test_value_2"}},+ ]+ response = await create_record(credentials, base_id, table_id, records=records)+ created_records = response.get("records")+ assert created_records is not None+ assert isinstance(created_records, list)+ assert len(created_records) == 2, f"Created records: {created_records}"+ first_record = created_records[0] # type: ignore+ second_record = created_records[1] # type: ignore+ first_record_id = first_record.get("id")+ second_record_id = second_record.get("id")+ assert first_record_id is not None+ assert second_record_id is not None+ assert first_record_id != second_record_id+ first_fields = first_record.get("fields")+ second_fields = second_record.get("fields")+ assert first_fields is not None+ assert second_fields is not None+ assert first_fields.get("test_field") == "test_value_1" # type: ignore+ assert second_fields.get("test_field") == "test_value_2" # type: ignore++ # List records+ response = await list_records(credentials, base_id, table_id)+ records = response.get("records")+ assert records is not None+ assert len(records) == 2, f"Records: {records}"+ assert isinstance(records, list), f"Type of records: {type(records)}"++ # Update multiple records+ records = [+ {"id": first_record_id, "fields": {"test_field": "test_value_1_updated"}},+ {"id": second_record_id, "fields": {"test_field": "test_value_2_updated"}},+ ]+ response = await update_multiple_records(+ credentials, base_id, table_id, records=records+ )+ updated_records = response.get("records")+ assert updated_records is not None+ assert len(updated_records) == 2, f"Updated records: {updated_records}"+ assert isinstance(+ updated_records, list+ ), f"Type of updated records: {type(updated_records)}"+ first_updated = updated_records[0] # type: ignore+ second_updated = updated_records[1] # type: ignore+ first_updated_fields = first_updated.get("fields")+ second_updated_fields = second_updated.get("fields")+ assert first_updated_fields is not None+ assert second_updated_fields is not None+ assert first_updated_fields.get("test_field") == "test_value_1_updated" # type: ignore+ assert second_updated_fields.get("test_field") == "test_value_2_updated" # type: ignore++ # Delete multiple records+ assert isinstance(first_record_id, str)+ assert isinstance(second_record_id, str)+ response = await delete_multiple_records(+ credentials, base_id, table_id, records=[first_record_id, second_record_id]+ )+ deleted_records = response.get("records")+ assert deleted_records is not None+ assert len(deleted_records) == 2, f"Deleted records: {deleted_records}"+ assert isinstance(+ deleted_records, list+ ), f"Type of deleted records: {type(deleted_records)}"+ first_deleted = deleted_records[0] # type: ignore+ second_deleted = deleted_records[1] # type: ignore+ assert first_deleted.get("deleted")+ assert second_deleted.get("deleted")+++async def test_webhook_management():+ key = getenv("AIRTABLE_API_KEY")+ if not key:+ return pytest.skip("AIRTABLE_API_KEY is not set")++ credentials = APIKeyCredentials(+ provider="airtable",+ api_key=SecretStr(key),+ )+ postfix = uuid4().hex[:4]+ base_id = "appSbaQLkcYiIOqux"+ table_name = f"test_table_{postfix}"+ table_fields = [{"name": "test_field", "type": "singleLineText"}]+ table = await create_table(credentials, base_id, table_name, table_fields)+ assert table.get("name") == table_name++ table_id = table.get("id")+ assert table_id is not None+ webhook_specification = WebhookSpecification(+ filters=WebhookFilters(+ dataTypes=["tableData", "tableFields", "tableMetadata"],+ changeTypes=["add", "update", "remove"],+ )+ )+ response = await create_webhook(credentials, base_id, webhook_specification)+ assert response is not None, f"Checking create webhook response: {response}"+ assert (+ response.get("id") is not None+ ), f"Checking create webhook response id: {response}"+ assert (+ response.get("macSecretBase64") is not None+ ), f"Checking create webhook response macSecretBase64: {response}"++ webhook_id = response.get("id")+ assert webhook_id is not None, f"Webhook ID: {webhook_id}"+ assert isinstance(webhook_id, str)++ response = await create_record(+ credentials, base_id, table_id, fields={"test_field": "test_value"}+ )+ assert response is not None, f"Checking create record response: {response}"+ assert (+ response.get("id") is not None+ ), f"Checking create record response id: {response}"+ fields = response.get("fields")+ assert fields is not None, f"Checking create record response fields: {response}"+ assert (+ fields.get("test_field") == "test_value"+ ), f"Checking create record response fields test_field: {response}"++ response = await list_webhook_payloads(credentials, base_id, webhook_id)+ assert response is not None, f"Checking list webhook payloads response: {response}"++ response = await delete_webhook(credentials, base_id, webhook_id)diff --git a/autogpt_platform/backend/backend/blocks/airtable/_config.py b/autogpt_platform/backend/backend/blocks/airtable/_config.pynew file mode 100644index 0000000000..d804d84360--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/airtable/_config.py@@ -0,0 +1,45 @@+"""+Shared configuration for all Airtable blocks using the SDK pattern.+"""++import os++from backend.sdk import BlockCostType, ProviderBuilder++from ._oauth import AirtableOAuthHandler, AirtableScope+from ._webhook import AirtableWebhookManager++# Configure the Airtable provider with API key authentication+builder = (+ ProviderBuilder("airtable")+ .with_api_key("AIRTABLE_API_KEY", "Airtable Personal Access Token")+ .with_webhook_manager(AirtableWebhookManager)+ .with_base_cost(1, BlockCostType.RUN)+)+++# Check if Linear OAuth is configured+client_id = os.getenv("AIRTABLE_CLIENT_ID")+client_secret = os.getenv("AIRTABLE_CLIENT_SECRET")+AIRTABLE_OAUTH_IS_CONFIGURED = bool(client_id and client_secret)++# Linear only supports OAuth authentication+if AIRTABLE_OAUTH_IS_CONFIGURED:+ builder = builder.with_oauth(+ AirtableOAuthHandler,+ scopes=[+ v.value+ for v in [+ AirtableScope.DATA_RECORDS_READ,+ AirtableScope.DATA_RECORDS_WRITE,+ AirtableScope.SCHEMA_BASES_READ,+ AirtableScope.SCHEMA_BASES_WRITE,+ AirtableScope.WEBHOOK_MANAGE,+ ]+ ],+ client_id_env_var="AIRTABLE_CLIENT_ID",+ client_secret_env_var="AIRTABLE_CLIENT_SECRET",+ )++# Build the provider+airtable = builder.build()diff --git a/autogpt_platform/backend/backend/blocks/airtable/_oauth.py b/autogpt_platform/backend/backend/blocks/airtable/_oauth.pynew file mode 100644index 0000000000..18771fd5bb--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/airtable/_oauth.py@@ -0,0 +1,184 @@+"""+Airtable OAuth handler implementation.+"""++import time+from enum import Enum+from logging import getLogger+from typing import Optional++from backend.sdk import BaseOAuthHandler, OAuth2Credentials, ProviderName, SecretStr++from ._api import (+ OAuthTokenResponse,+ make_oauth_authorize_url,+ oauth_exchange_code_for_tokens,+ oauth_refresh_tokens,+)++logger = getLogger(__name__)+++class AirtableScope(str, Enum):+ # Basic scopes+ DATA_RECORDS_READ = "data.records:read"+ DATA_RECORDS_WRITE = "data.records:write"+ DATA_RECORD_COMMENTS_READ = "data.recordComments:read"+ DATA_RECORD_COMMENTS_WRITE = "data.recordComments:write"+ SCHEMA_BASES_READ = "schema.bases:read"+ SCHEMA_BASES_WRITE = "schema.bases:write"+ WEBHOOK_MANAGE = "webhook:manage"+ BLOCK_MANAGE = "block:manage"+ USER_EMAIL_READ = "user.email:read"++ # Enterprise member scopes+ ENTERPRISE_GROUPS_READ = "enterprise.groups:read"+ WORKSPACES_AND_BASES_READ = "workspacesAndBases:read"+ WORKSPACES_AND_BASES_WRITE = "workspacesAndBases:write"+ WORKSPACES_AND_BASES_SHARES_MANAGE = "workspacesAndBases.shares:manage"++ # Enterprise admin scopes+ ENTERPRISE_SCIM_USERS_AND_GROUPS_MANAGE = "enterprise.scim.usersAndGroups:manage"+ ENTERPRISE_AUDIT_LOGS_READ = "enterprise.auditLogs:read"+ ENTERPRISE_CHANGE_EVENTS_READ = "enterprise.changeEvents:read"+ ENTERPRISE_EXPORTS_MANAGE = "enterprise.exports:manage"+ ENTERPRISE_ACCOUNT_READ = "enterprise.account:read"+ ENTERPRISE_ACCOUNT_WRITE = "enterprise.account:write"+ ENTERPRISE_USER_READ = "enterprise.user:read"+ ENTERPRISE_USER_WRITE = "enterprise.user:write"+ ENTERPRISE_GROUPS_MANAGE = "enterprise.groups:manage"+ WORKSPACES_AND_BASES_MANAGE = "workspacesAndBases:manage"+ HYPERDB_RECORDS_READ = "hyperDB.records:read"+ HYPERDB_RECORDS_WRITE = "hyperDB.records:write"+++class AirtableOAuthHandler(BaseOAuthHandler):+ """+ OAuth2 handler for Airtable with PKCE support.+ """++ PROVIDER_NAME = ProviderName("airtable")+ DEFAULT_SCOPES = [+ v.value+ for v in [+ AirtableScope.DATA_RECORDS_READ,+ AirtableScope.DATA_RECORDS_WRITE,+ AirtableScope.SCHEMA_BASES_READ,+ AirtableScope.SCHEMA_BASES_WRITE,+ AirtableScope.WEBHOOK_MANAGE,+ ]+ ]++ def __init__(self, client_id: str, client_secret: Optional[str], redirect_uri: str):+ self.client_id = client_id+ self.client_secret = client_secret+ self.redirect_uri = redirect_uri+ self.scopes = self.DEFAULT_SCOPES+ self.auth_base_url = "https://airtable.com/oauth2/v1/authorize"+ self.token_url = "https://airtable.com/oauth2/v1/token"++ def get_login_url(+ self, scopes: list[str], state: str, code_challenge: Optional[str]+ ) -> str:+ logger.debug("Generating Airtable OAuth login URL")+ # Generate code_challenge if not provided (PKCE is required)+ if not scopes:+ logger.debug("No scopes provided, using default scopes")+ scopes = self.scopes++ logger.debug(f"Using scopes: {scopes}")+ logger.debug(f"State: {state}")+ logger.debug(f"Code challenge: {code_challenge}")+ if not code_challenge:+ logger.error("Code challenge is required but none was provided")+ raise ValueError("No code challenge provided")++ try:+ url = make_oauth_authorize_url(+ self.client_id, self.redirect_uri, scopes, state, code_challenge+ )+ logger.debug(f"Generated OAuth URL: {url}")+ return url+ except Exception as e:+ logger.error(f"Failed to generate OAuth URL: {str(e)}")+ raise++ async def exchange_code_for_tokens(+ self, code: str, scopes: list[str], code_verifier: Optional[str]+ ) -> OAuth2Credentials:+ logger.debug("Exchanging authorization code for tokens")+ logger.debug(f"Code: {code[:4]}...") # Log first 4 chars only for security+ logger.debug(f"Scopes: {scopes}")+ if not code_verifier:+ logger.error("Code verifier is required but none was provided")+ raise ValueError("No code verifier provided")++ try:+ response: OAuthTokenResponse = await oauth_exchange_code_for_tokens(+ client_id=self.client_id,+ code=code,+ code_verifier=code_verifier.encode("utf-8"),+ redirect_uri=self.redirect_uri,+ client_secret=self.client_secret,+ )+ logger.info("Successfully exchanged code for tokens")++ credentials = OAuth2Credentials(+ access_token=SecretStr(response.access_token),+ refresh_token=SecretStr(response.refresh_token),+ access_token_expires_at=int(time.time()) + response.expires_in,+ refresh_token_expires_at=int(time.time()) + response.refresh_expires_in,+ provider=self.PROVIDER_NAME,+ scopes=scopes,+ )+ logger.debug(f"Access token expires in {response.expires_in} seconds")+ logger.debug(+ f"Refresh token expires in {response.refresh_expires_in} seconds"+ )+ return credentials++ except Exception as e:+ logger.error(f"Failed to exchange code for tokens: {str(e)}")+ raise++ async def _refresh_tokens(+ self, credentials: OAuth2Credentials+ ) -> OAuth2Credentials:+ logger.debug("Attempting to refresh OAuth tokens")++ if credentials.refresh_token is None:+ logger.error("Cannot refresh tokens - no refresh token available")+ raise ValueError("No refresh token available")++ try:+ response: OAuthTokenResponse = await oauth_refresh_tokens(+ client_id=self.client_id,+ refresh_token=credentials.refresh_token.get_secret_value(),+ client_secret=self.client_secret,+ )+ logger.info("Successfully refreshed tokens")++ new_credentials = OAuth2Credentials(+ access_token=SecretStr(response.access_token),+ refresh_token=SecretStr(response.refresh_token),+ access_token_expires_at=int(time.time()) + response.expires_in,+ refresh_token_expires_at=int(time.time()) + response.refresh_expires_in,+ provider=self.PROVIDER_NAME,+ scopes=self.scopes,+ )+ logger.debug(f"New access token expires in {response.expires_in} seconds")+ logger.debug(+ f"New refresh token expires in {response.refresh_expires_in} seconds"+ )+ return new_credentials++ except Exception as e:+ logger.error(f"Failed to refresh tokens: {str(e)}")+ raise++ async def revoke_tokens(self, credentials: OAuth2Credentials) -> bool:+ logger.debug("Token revocation requested")+ logger.info(+ "Airtable doesn't provide a token revocation endpoint - tokens will expire naturally after 60 minutes"+ )+ return Falsediff --git a/autogpt_platform/backend/backend/blocks/airtable/_webhook.py b/autogpt_platform/backend/backend/blocks/airtable/_webhook.pynew file mode 100644index 0000000000..58e6f95d0c--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/airtable/_webhook.py@@ -0,0 +1,154 @@+"""+Webhook management for Airtable blocks.+"""++import hashlib+import hmac+import logging+from enum import Enum++from backend.sdk import (+ BaseWebhooksManager,+ Credentials,+ ProviderName,+ Webhook,+ update_webhook,+)++from ._api import (+ WebhookFilters,+ WebhookSpecification,+ create_webhook,+ delete_webhook,+ list_webhook_payloads,+)++logger = logging.getLogger(__name__)+++class AirtableWebhookEvent(str, Enum):+ TABLE_DATA = "tableData"+ TABLE_FIELDS = "tableFields"+ TABLE_METADATA = "tableMetadata"+++class AirtableWebhookManager(BaseWebhooksManager):+ """Webhook manager for Airtable API."""++ PROVIDER_NAME = ProviderName("airtable")++ @classmethod+ async def validate_payload(+ cls, webhook: Webhook, request, credentials: Credentials | None+ ) -> tuple[dict, str]:+ """Validate incoming webhook payload and signature."""++ if not credentials:+ raise ValueError("Missing credentials in webhook metadata")++ payload = await request.json()++ # Verify webhook signature using HMAC-SHA256+ if webhook.secret:+ mac_secret = webhook.config.get("mac_secret")+ if mac_secret:+ # Get the raw body for signature verification+ body = await request.body()++ # Calculate expected signature+ mac_secret_decoded = mac_secret.encode()+ hmac_obj = hmac.new(mac_secret_decoded, body, hashlib.sha256)+ expected_mac = f"hmac-sha256={hmac_obj.hexdigest()}"++ # Get signature from headers+ signature = request.headers.get("X-Airtable-Content-MAC")++ if signature and not hmac.compare_digest(signature, expected_mac):+ raise ValueError("Invalid webhook signature")++ # Validate payload structure+ required_fields = ["base", "webhook", "timestamp"]+ if not all(field in payload for field in required_fields):+ raise ValueError("Invalid webhook payload structure")++ if "id" not in payload["base"] or "id" not in payload["webhook"]:+ raise ValueError("Missing required IDs in webhook payload")+ base_id = payload["base"]["id"]+ webhook_id = payload["webhook"]["id"]++ # get payload request parameters+ cursor = webhook.config.get("cursor", 1)++ response = await list_webhook_payloads(credentials, base_id, webhook_id, cursor)++ # update webhook config+ await update_webhook(+ webhook.id,+ config={"base_id": base_id, "cursor": response.cursor},+ )++ event_type = "notification"+ return response.model_dump(), event_type++ async def _register_webhook(+ self,+ credentials: Credentials,+ webhook_type: str,+ resource: str,+ events: list[str],+ ingress_url: str,+ secret: str,+ ) -> tuple[str, dict]:+ """Register webhook with Airtable API."""++ # Parse resource to get base_id and table_id/name+ # Resource format: "{base_id}/{table_id_or_name}"+ parts = resource.split("/", 1)+ if len(parts) != 2:+ raise ValueError("Resource must be in format: {base_id}/{table_id_or_name}")++ base_id, table_id_or_name = parts++ # Prepare webhook specification+ webhook_specification = WebhookSpecification(+ filters=WebhookFilters(+ dataTypes=events,+ )+ )++ # Create webhook+ webhook_data = await create_webhook(+ credentials=credentials,+ base_id=base_id,+ webhook_specification=webhook_specification,+ notification_url=ingress_url,+ )++ webhook_id = webhook_data["id"]+ mac_secret = webhook_data.get("macSecretBase64")++ return webhook_id, {+ "webhook_id": webhook_id,+ "base_id": base_id,+ "table_id_or_name": table_id_or_name,+ "events": events,+ "mac_secret": mac_secret,+ "cursor": 1,+ "expiration_time": webhook_data.get("expirationTime"),+ }++ async def _deregister_webhook(+ self, webhook: Webhook, credentials: Credentials+ ) -> None:+ """Deregister webhook from Airtable API."""++ base_id = webhook.config.get("base_id")+ webhook_id = webhook.config.get("webhook_id")++ if not base_id:+ raise ValueError("Missing base_id in webhook metadata")++ if not webhook_id:+ raise ValueError("Missing webhook_id in webhook metadata")++ await delete_webhook(credentials, base_id, webhook_id)diff --git a/autogpt_platform/backend/backend/blocks/airtable/records.py b/autogpt_platform/backend/backend/blocks/airtable/records.pynew file mode 100644index 0000000000..82e5986e84--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/airtable/records.py@@ -0,0 +1,283 @@+"""+Airtable record operation blocks.+"""++from typing import Optional++from backend.sdk import (+ APIKeyCredentials,+ Block,+ BlockCategory,+ BlockOutput,+ BlockSchema,+ CredentialsMetaInput,+ SchemaField,+)++from ._api import (+ create_record,+ delete_multiple_records,+ get_record,+ list_records,+ update_multiple_records,+)+from ._config import airtable+++class AirtableListRecordsBlock(Block):+ """+ Lists records from an Airtable table with optional filtering, sorting, and pagination.+ """++ class Input(BlockSchema):+ credentials: CredentialsMetaInput = airtable.credentials_field(+ description="Airtable API credentials"+ )+ base_id: str = SchemaField(description="The Airtable base ID")+ table_id_or_name: str = SchemaField(description="Table ID or name")+ filter_formula: str = SchemaField(+ description="Airtable formula to filter records", default=""+ )+ view: str = SchemaField(description="View ID or name to use", default="")+ sort: list[dict] = SchemaField(+ description="Sort configuration (array of {field, direction})", default=[]+ )+ max_records: int = SchemaField(+ description="Maximum number of records to return", default=100+ )+ page_size: int = SchemaField(+ description="Number of records per page (max 100)", default=100+ )+ offset: str = SchemaField(+ description="Pagination offset from previous request", default=""+ )+ return_fields: list[str] = SchemaField(+ description="Specific fields to return (comma-separated)", default=[]+ )++ class Output(BlockSchema):+ records: list[dict] = SchemaField(description="Array of record objects")+ offset: Optional[str] = SchemaField(+ description="Offset for next page (null if no more records)", default=None+ )++ def __init__(self):+ super().__init__(+ id="588a9fde-5733-4da7-b03c-35f5671e960f",+ description="List records from an Airtable table",+ categories={BlockCategory.DATA},+ input_schema=self.Input,+ output_schema=self.Output,+ )++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ data = await list_records(+ credentials,+ input_data.base_id,+ input_data.table_id_or_name,+ filter_by_formula=(+ input_data.filter_formula if input_data.filter_formula else None+ ),+ view=input_data.view if input_data.view else None,+ sort=input_data.sort if input_data.sort else None,+ max_records=input_data.max_records if input_data.max_records else None,+ page_size=min(input_data.page_size, 100) if input_data.page_size else None,+ offset=input_data.offset if input_data.offset else None,+ fields=input_data.return_fields if input_data.return_fields else None,+ )++ yield "records", data.get("records", [])+ yield "offset", data.get("offset", None)+++class AirtableGetRecordBlock(Block):+ """+ Retrieves a single record from an Airtable table by its ID.+ """++ class Input(BlockSchema):+ credentials: CredentialsMetaInput = airtable.credentials_field(+ description="Airtable API credentials"+ )+ base_id: str = SchemaField(description="The Airtable base ID")+ table_id_or_name: str = SchemaField(description="Table ID or name")+ record_id: str = SchemaField(description="The record ID to retrieve")++ class Output(BlockSchema):+ id: str = SchemaField(description="The record ID")+ fields: dict = SchemaField(description="The record fields")+ created_time: str = SchemaField(description="The record created time")++ def __init__(self):+ super().__init__(+ id="c29c5cbf-0aff-40f9-bbb5-f26061792d2b",+ description="Get a single record from Airtable",+ categories={BlockCategory.DATA},+ input_schema=self.Input,+ output_schema=self.Output,+ )++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ record = await get_record(+ credentials,+ input_data.base_id,+ input_data.table_id_or_name,+ input_data.record_id,+ )++ yield "id", record.get("id", None)+ yield "fields", record.get("fields", None)+ yield "created_time", record.get("createdTime", None)+++class AirtableCreateRecordsBlock(Block):+ """+ Creates one or more records in an Airtable table.+ """++ class Input(BlockSchema):+ credentials: CredentialsMetaInput = airtable.credentials_field(+ description="Airtable API credentials"+ )+ base_id: str = SchemaField(description="The Airtable base ID")+ table_id_or_name: str = SchemaField(description="Table ID or name")+ records: list[dict] = SchemaField(+ description="Array of records to create (each with 'fields' object)"+ )+ typecast: bool = SchemaField(+ description="Automatically convert string values to appropriate types",+ default=False,+ )+ return_fields_by_field_id: bool | None = SchemaField(+ description="Return fields by field ID",+ default=None,+ )++ class Output(BlockSchema):+ records: list[dict] = SchemaField(description="Array of created record objects")+ details: dict = SchemaField(description="Details of the created records")++ def __init__(self):+ super().__init__(+ id="42527e98-47b6-44ce-ac0e-86b4883721d3",+ description="Create records in an Airtable table",+ categories={BlockCategory.DATA},+ input_schema=self.Input,+ output_schema=self.Output,+ )++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ # The create_record API expects records in a specific format+ data = await create_record(+ credentials,+ input_data.base_id,+ input_data.table_id_or_name,+ records=[{"fields": record} for record in input_data.records],+ typecast=input_data.typecast if input_data.typecast else None,+ return_fields_by_field_id=input_data.return_fields_by_field_id,+ )++ yield "records", data.get("records", [])+ details = data.get("details", None)+ if details:+ yield "details", details+++class AirtableUpdateRecordsBlock(Block):+ """+ Updates one or more existing records in an Airtable table.+ """++ class Input(BlockSchema):+ credentials: CredentialsMetaInput = airtable.credentials_field(+ description="Airtable API credentials"+ )+ base_id: str = SchemaField(description="The Airtable base ID")+ table_id_or_name: str = SchemaField(+ description="Table ID or name - It's better to use the table ID instead of the name"+ )+ records: list[dict] = SchemaField(+ description="Array of records to update (each with 'id' and 'fields')"+ )+ typecast: bool | None = SchemaField(+ description="Automatically convert string values to appropriate types",+ default=None,+ )++ class Output(BlockSchema):+ records: list[dict] = SchemaField(description="Array of updated record objects")++ def __init__(self):+ super().__init__(+ id="6e7d2590-ac2b-4b5d-b08c-fc039cd77e1f",+ description="Update records in an Airtable table",+ categories={BlockCategory.DATA},+ input_schema=self.Input,+ output_schema=self.Output,+ )++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ # The update_multiple_records API expects records with id and fields+ data = await update_multiple_records(+ credentials,+ input_data.base_id,+ input_data.table_id_or_name,+ records=input_data.records,+ typecast=input_data.typecast if input_data.typecast else None,+ return_fields_by_field_id=False, # Use field names, not IDs+ )++ yield "records", data.get("records", [])+++class AirtableDeleteRecordsBlock(Block):+ """+ Deletes one or more records from an Airtable table.+ """++ class Input(BlockSchema):+ credentials: CredentialsMetaInput = airtable.credentials_field(+ description="Airtable API credentials"+ )+ base_id: str = SchemaField(description="The Airtable base ID")+ table_id_or_name: str = SchemaField(+ description="Table ID or name - It's better to use the table ID instead of the name"+ )+ record_ids: list[str] = SchemaField(+ description="Array of upto 10 record IDs to delete"+ )++ class Output(BlockSchema):+ records: list[dict] = SchemaField(description="Array of deletion results")++ def __init__(self):+ super().__init__(+ id="93e22b8b-3642-4477-aefb-1c0929a4a3a6",+ description="Delete records from an Airtable table",+ categories={BlockCategory.DATA},+ input_schema=self.Input,+ output_schema=self.Output,+ )++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ if len(input_data.record_ids) > 10:+ yield "error", "Only upto 10 record IDs can be deleted at a time"+ else:+ data = await delete_multiple_records(+ credentials,+ input_data.base_id,+ input_data.table_id_or_name,+ input_data.record_ids,+ )++ yield "records", data.get("records", [])diff --git a/autogpt_platform/backend/backend/blocks/airtable/schema.py b/autogpt_platform/backend/backend/blocks/airtable/schema.pynew file mode 100644index 0000000000..5d2006a2ff--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/airtable/schema.py@@ -0,0 +1,252 @@+"""+Airtable schema and table management blocks.+"""++from backend.sdk import (+ APIKeyCredentials,+ Block,+ BlockCategory,+ BlockOutput,+ BlockSchema,+ CredentialsMetaInput,+ Requests,+ SchemaField,+)++from ._api import TableFieldType, create_field, create_table, update_field, update_table+from ._config import airtable+++class AirtableListSchemaBlock(Block):+ """+ Retrieves the complete schema of an Airtable base, including all tables,+ fields, and views.+ """++ class Input(BlockSchema):+ credentials: CredentialsMetaInput = airtable.credentials_field(+ description="Airtable API credentials"+ )+ base_id: str = SchemaField(description="The Airtable base ID")++ class Output(BlockSchema):+ base_schema: dict = SchemaField(+ description="Complete base schema with tables, fields, and views"+ )+ tables: list[dict] = SchemaField(description="Array of table objects")++ def __init__(self):+ super().__init__(+ id="64291d3c-99b5-47b7-a976-6d94293cdb2d",+ description="Get the complete schema of an Airtable base",+ categories={BlockCategory.DATA},+ input_schema=self.Input,+ output_schema=self.Output,+ )++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ api_key = credentials.api_key.get_secret_value()++ # Get base schema+ response = await Requests().get(+ f"https://api.airtable.com/v0/meta/bases/{input_data.base_id}/tables",+ headers={"Authorization": f"Bearer {api_key}"},+ )++ data = response.json()++ yield "base_schema", data+ yield "tables", data.get("tables", [])+++class AirtableCreateTableBlock(Block):+ """+ Creates a new table in an Airtable base with specified fields and views.+ """++ class Input(BlockSchema):+ credentials: CredentialsMetaInput = airtable.credentials_field(+ description="Airtable API credentials"+ )+ base_id: str = SchemaField(description="The Airtable base ID")+ table_name: str = SchemaField(description="The name of the table to create")+ table_fields: list[dict] = SchemaField(+ description="Table fields with name, type, and options",+ default=[{"name": "Name", "type": "singleLineText"}],+ )++ class Output(BlockSchema):+ table: dict = SchemaField(description="Created table object")+ table_id: str = SchemaField(description="ID of the created table")++ def __init__(self):+ super().__init__(+ id="fcc20ced-d817-42ea-9b40-c35e7bf34b4f",+ description="Create a new table in an Airtable base",+ categories={BlockCategory.DATA},+ input_schema=self.Input,+ output_schema=self.Output,+ )++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ table_data = await create_table(+ credentials,+ input_data.base_id,+ input_data.table_name,+ input_data.table_fields,+ )++ yield "table", table_data+ yield "table_id", table_data.get("id", "")+++class AirtableUpdateTableBlock(Block):+ """+ Updates an existing table's properties such as name or description.+ """++ class Input(BlockSchema):+ credentials: CredentialsMetaInput = airtable.credentials_field(+ description="Airtable API credentials"+ )+ base_id: str = SchemaField(description="The Airtable base ID")+ table_id: str = SchemaField(description="The table ID to update")+ table_name: str | None = SchemaField(+ description="The name of the table to update", default=None+ )+ table_description: str | None = SchemaField(+ description="The description of the table to update", default=None+ )+ date_dependency: dict | None = SchemaField(+ description="The date dependency of the table to update", default=None+ )++ class Output(BlockSchema):+ table: dict = SchemaField(description="Updated table object")++ def __init__(self):+ super().__init__(+ id="34077c5f-f962-49f2-9ec6-97c67077013a",+ description="Update table properties",+ categories={BlockCategory.DATA},+ input_schema=self.Input,+ output_schema=self.Output,+ )++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ table_data = await update_table(+ credentials,+ input_data.base_id,+ input_data.table_id,+ input_data.table_name,+ input_data.table_description,+ input_data.date_dependency,+ )++ yield "table", table_data+++class AirtableCreateFieldBlock(Block):+ """+ Adds a new field (column) to an existing Airtable table.+ """++ class Input(BlockSchema):+ credentials: CredentialsMetaInput = airtable.credentials_field(+ description="Airtable API credentials"+ )+ base_id: str = SchemaField(description="The Airtable base ID")+ table_id: str = SchemaField(description="The table ID to add field to")+ field_type: TableFieldType = SchemaField(+ description="The type of the field to create",+ default=TableFieldType.SINGLE_LINE_TEXT,+ advanced=False,+ )+ name: str = SchemaField(description="The name of the field to create")+ description: str | None = SchemaField(+ description="The description of the field to create", default=None+ )+ options: dict[str, str] | None = SchemaField(+ description="The options of the field to create", default=None+ )++ class Output(BlockSchema):+ field: dict = SchemaField(description="Created field object")+ field_id: str = SchemaField(description="ID of the created field")++ def __init__(self):+ super().__init__(+ id="6c98a32f-dbf9-45d8-a2a8-5e97e8326351",+ description="Add a new field to an Airtable table",+ categories={BlockCategory.DATA},+ input_schema=self.Input,+ output_schema=self.Output,+ )++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ field_data = await create_field(+ credentials,+ input_data.base_id,+ input_data.table_id,+ input_data.field_type,+ input_data.name,+ )++ yield "field", field_data+ yield "field_id", field_data.get("id", "")+++class AirtableUpdateFieldBlock(Block):+ """+ Updates an existing field's properties in an Airtable table.+ """++ class Input(BlockSchema):+ credentials: CredentialsMetaInput = airtable.credentials_field(+ description="Airtable API credentials"+ )+ base_id: str = SchemaField(description="The Airtable base ID")+ table_id: str = SchemaField(description="The table ID containing the field")+ field_id: str = SchemaField(description="The field ID to update")+ name: str | None = SchemaField(+ description="The name of the field to update", default=None, advanced=False+ )+ description: str | None = SchemaField(+ description="The description of the field to update",+ default=None,+ advanced=False,+ )++ class Output(BlockSchema):+ field: dict = SchemaField(description="Updated field object")++ def __init__(self):+ super().__init__(+ id="f46ac716-3b18-4da1-92e4-34ca9a464d48",+ description="Update field properties in an Airtable table",+ categories={BlockCategory.DATA},+ input_schema=self.Input,+ output_schema=self.Output,+ )++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ field_data = await update_field(+ credentials,+ input_data.base_id,+ input_data.table_id,+ input_data.field_id,+ input_data.name,+ input_data.description,+ )++ yield "field", field_datadiff --git a/autogpt_platform/backend/backend/blocks/airtable/triggers.py b/autogpt_platform/backend/backend/blocks/airtable/triggers.pynew file mode 100644index 0000000000..2cfc8178e3--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/airtable/triggers.py@@ -0,0 +1,113 @@+from backend.sdk import (+ BaseModel,+ Block,+ BlockCategory,+ BlockOutput,+ BlockSchema,+ BlockType,+ BlockWebhookConfig,+ CredentialsMetaInput,+ ProviderName,+ SchemaField,+)++from ._api import WebhookPayload+from ._config import airtable+++class AirtableEventSelector(BaseModel):+ """+ Selects the Airtable webhook event to trigger on.+ """++ tableData: bool = True+ tableFields: bool = True+ tableMetadata: bool = True+++class AirtableWebhookTriggerBlock(Block):+ """+ Starts a flow whenever Airtable emits a webhook event.++ Thin wrapper just forwards the payloads one at a time to the next block.+ """++ class Input(BlockSchema):+ credentials: CredentialsMetaInput = airtable.credentials_field(+ description="Airtable API credentials"+ )+ base_id: str = SchemaField(description="Airtable base ID")+ table_id_or_name: str = SchemaField(description="Airtable table ID or name")+ payload: dict = SchemaField(hidden=True, default_factory=dict)+ events: AirtableEventSelector = SchemaField(+ description="Airtable webhook event filter"+ )++ class Output(BlockSchema):+ payload: WebhookPayload = SchemaField(description="Airtable webhook payload")++ def __init__(self):+ example_payload = {+ "payloads": [+ {+ "timestamp": "2022-02-01T21:25:05.663Z",+ "baseTransactionNumber": 4,+ "actionMetadata": {+ "source": "client",+ "sourceMetadata": {+ "user": {+ "id": "usr00000000000000",+ "email": "[email protected]",+ "permissionLevel": "create",+ }+ },+ },+ "payloadFormat": "v0",+ }+ ],+ "cursor": 5,+ "mightHaveMore": False,+ }++ super().__init__(+ # NOTE: This is disabled whilst the webhook system is finalised.+ disabled=False,+ id="d0180ce6-ccb9-48c7-8256-b39e93e62801",+ description="Starts a flow whenever Airtable emits a webhook event",+ categories={BlockCategory.INPUT, BlockCategory.DATA},+ input_schema=self.Input,+ output_schema=self.Output,+ block_type=BlockType.WEBHOOK,+ webhook_config=BlockWebhookConfig(+ provider=ProviderName("airtable"),+ webhook_type="not-used",+ event_filter_input="events",+ event_format="{event}",+ resource_format="{base_id}/{table_id_or_name}",+ ),+ test_input={+ "credentials": airtable.get_test_credentials().model_dump(),+ "base_id": "app1234567890",+ "table_id_or_name": "table1234567890",+ "events": AirtableEventSelector(+ tableData=True,+ tableFields=True,+ tableMetadata=False,+ ).model_dump(),+ "payload": example_payload,+ },+ test_credentials=airtable.get_test_credentials(),+ test_output=[+ (+ "payload",+ WebhookPayload.model_validate(example_payload["payloads"][0]),+ ),+ ],+ )++ async def run(self, input_data: Input, **kwargs) -> BlockOutput:+ if len(input_data.payload["payloads"]) > 0:+ for item in input_data.payload["payloads"]:+ yield "payload", WebhookPayload.model_validate(item)+ else:+ yield "error", "No valid payloads found in webhook payload"diff --git a/autogpt_platform/backend/backend/blocks/exa/_webhook.py b/autogpt_platform/backend/backend/blocks/exa/_webhook.pyindex a57efe23cb..725976c68c 100644--- a/autogpt_platform/backend/backend/blocks/exa/_webhook.py+++ b/autogpt_platform/backend/backend/blocks/exa/_webhook.py@@ -51,7 +51,9 @@ class ExaWebhookManager(BaseWebhooksManager):WEBSET = "webset"@classmethod- async def validate_payload(cls, webhook: Webhook, request) -> tuple[dict, str]:+ async def validate_payload(+ cls, webhook: Webhook, request, credentials: Credentials | None+ ) -> tuple[dict, str]:"""Validate incoming webhook payload and signature."""payload = await request.json()diff --git a/autogpt_platform/backend/backend/blocks/generic_webhook/_webhook.py b/autogpt_platform/backend/backend/blocks/generic_webhook/_webhook.pyindex 8a8b55a8eb..9dd4b8c2c7 100644--- a/autogpt_platform/backend/backend/blocks/generic_webhook/_webhook.py+++ b/autogpt_platform/backend/backend/blocks/generic_webhook/_webhook.py@@ -3,7 +3,7 @@ import loggingfrom fastapi import Requestfrom strenum import StrEnum-from backend.sdk import ManualWebhookManagerBase, Webhook+from backend.sdk import Credentials, ManualWebhookManagerBase, Webhooklogger = logging.getLogger(__name__)@@ -17,7 +17,7 @@ class GenericWebhooksManager(ManualWebhookManagerBase):@classmethodasync def validate_payload(- cls, webhook: Webhook, request: Request+ cls, webhook: Webhook, request: Request, credentials: Credentials | None = None) -> tuple[dict, str]:payload = await request.json()event_type = GenericWebhookType.PLAINdiff --git a/autogpt_platform/backend/backend/integrations/credentials_store.py b/autogpt_platform/backend/backend/integrations/credentials_store.pyindex f321da82fa..51c0be4980 100644--- a/autogpt_platform/backend/backend/integrations/credentials_store.py+++ b/autogpt_platform/backend/backend/integrations/credentials_store.py@@ -393,7 +393,7 @@ class IntegrationCredentialsStore:Generate code challenge using SHA256 from the code verifier.Currently only SHA256 is supported.(In future if we want to support more methods we can add them here)"""- code_verifier = secrets.token_urlsafe(128)+ code_verifier = secrets.token_urlsafe(96)sha256_hash = hashlib.sha256(code_verifier.encode("utf-8")).digest()code_challenge = base64.urlsafe_b64encode(sha256_hash).decode("utf-8")return code_challenge.replace("=", ""), code_verifierdiff --git a/autogpt_platform/backend/backend/integrations/webhooks/_base.py b/autogpt_platform/backend/backend/integrations/webhooks/_base.pyindex dd27a853da..9342a6417b 100644--- a/autogpt_platform/backend/backend/integrations/webhooks/_base.py+++ b/autogpt_platform/backend/backend/integrations/webhooks/_base.py@@ -116,7 +116,10 @@ class BaseWebhooksManager(ABC, Generic[WT]):@classmethod@abstractmethodasync def validate_payload(- cls, webhook: integrations.Webhook, request: Request+ cls,+ webhook: integrations.Webhook,+ request: Request,+ credentials: Credentials | None,) -> tuple[dict, str]:"""Validates an incoming webhook request and returns its payload and type.diff --git a/autogpt_platform/backend/backend/integrations/webhooks/compass.py b/autogpt_platform/backend/backend/integrations/webhooks/compass.pyindex 8a2076a1da..6dbfc85604 100644--- a/autogpt_platform/backend/backend/integrations/webhooks/compass.py+++ b/autogpt_platform/backend/backend/integrations/webhooks/compass.py@@ -5,6 +5,7 @@ from strenum import StrEnumfrom backend.data import integrationsfrom backend.integrations.providers import ProviderName+from backend.sdk import Credentialsfrom ._manual_base import ManualWebhookManagerBase@@ -22,7 +23,10 @@ class CompassWebhookManager(ManualWebhookManagerBase):@classmethodasync def validate_payload(- cls, webhook: integrations.Webhook, request: Request+ cls,+ webhook: integrations.Webhook,+ request: Request,+ credentials: Credentials | None,) -> tuple[dict, str]:payload = await request.json()event_type = CompassWebhookType.TRANSCRIPTION # currently the only typediff --git a/autogpt_platform/backend/backend/integrations/webhooks/github.py b/autogpt_platform/backend/backend/integrations/webhooks/github.pyindex 5d2977cacc..a4f74249f5 100644--- a/autogpt_platform/backend/backend/integrations/webhooks/github.py+++ b/autogpt_platform/backend/backend/integrations/webhooks/github.py@@ -30,7 +30,10 @@ class GithubWebhooksManager(BaseWebhooksManager):@classmethodasync def validate_payload(- cls, webhook: integrations.Webhook, request: Request+ cls,+ webhook: integrations.Webhook,+ request: Request,+ credentials: Credentials | None,) -> tuple[dict, str]:if not (event_type := request.headers.get("X-GitHub-Event")):raise HTTPException(diff --git a/autogpt_platform/backend/backend/integrations/webhooks/slant3d.py b/autogpt_platform/backend/backend/integrations/webhooks/slant3d.pyindex bc0337d4c5..059f0ada09 100644--- a/autogpt_platform/backend/backend/integrations/webhooks/slant3d.py+++ b/autogpt_platform/backend/backend/integrations/webhooks/slant3d.py@@ -58,7 +58,10 @@ class Slant3DWebhooksManager(BaseWebhooksManager):@classmethodasync def validate_payload(- cls, webhook: integrations.Webhook, request: Request+ cls,+ webhook: integrations.Webhook,+ request: Request,+ credentials: Credentials | None,) -> tuple[dict, str]:"""Validate incoming webhook payload from Slant3D"""diff --git a/autogpt_platform/backend/backend/sdk/__init__.py b/autogpt_platform/backend/backend/sdk/__init__.pyindex ce4a82a4f0..666ad08835 100644--- a/autogpt_platform/backend/backend/sdk/__init__.py+++ b/autogpt_platform/backend/backend/sdk/__init__.py@@ -26,7 +26,7 @@ from backend.data.block import (BlockType,BlockWebhookConfig,)-from backend.data.integrations import Webhook+from backend.data.integrations import Webhook, update_webhookfrom backend.data.model import APIKeyCredentials, Credentials, CredentialsFieldfrom backend.data.model import CredentialsMetaInput as _CredentialsMetaInputfrom backend.data.model import (@@ -144,6 +144,7 @@ __all__ = ["BaseWebhooksManager","ManualWebhookManagerBase","Webhook",+ "update_webhook",# Provider-Specific (when available)"BaseOAuthHandler",# Utilitiesdiff --git a/autogpt_platform/backend/backend/sdk/provider.py b/autogpt_platform/backend/backend/sdk/provider.pyindex 7a6f91543e..565feab774 100644--- a/autogpt_platform/backend/backend/sdk/provider.py+++ b/autogpt_platform/backend/backend/sdk/provider.py@@ -2,12 +2,18 @@Provider configuration class that holds all provider-related settings."""+import uuidfrom typing import Any, Callable, List, Optional, Set, Type-from pydantic import BaseModel+from pydantic import BaseModel, SecretStrfrom backend.data.cost import BlockCost-from backend.data.model import Credentials, CredentialsField, CredentialsMetaInput+from backend.data.model import (+ APIKeyCredentials,+ Credentials,+ CredentialsField,+ CredentialsMetaInput,+)from backend.integrations.oauth.base import BaseOAuthHandlerfrom backend.integrations.webhooks._base import BaseWebhooksManager@@ -59,6 +65,7 @@ class Provider:# Store any additional configurationself._extra_config = kwargs+ self.test_credentials_uuid = uuid.uuid4()def credentials_field(self, **kwargs) -> CredentialsMetaInput:"""Return a CredentialsField configured for this provider."""@@ -97,6 +104,16 @@ class Provider:**kwargs,)+ def get_test_credentials(self) -> Credentials:+ """Get test credentials for the provider."""+ return APIKeyCredentials(+ id=str(self.test_credentials_uuid),+ provider=self.name,+ api_key=SecretStr("mock-api-key"),+ title=f"Mock {self.name.title()} API key",+ expires_at=None,+ )+def get_api(self, credentials: Credentials) -> Any:"""Get API client instance for the given credentials."""if self._api_client_factory:diff --git a/autogpt_platform/backend/backend/server/integrations/router.py b/autogpt_platform/backend/backend/server/integrations/router.pyindex 0e71d7f0ce..1f0725a250 100644--- a/autogpt_platform/backend/backend/server/integrations/router.py+++ b/autogpt_platform/backend/backend/server/integrations/router.py@@ -327,11 +327,19 @@ async def webhook_ingress_generic(webhook_manager = get_webhook_manager(provider)try:webhook = await get_webhook(webhook_id, include_relations=True)+ user_id = webhook.user_id+ credentials = (+ await creds_manager.get(user_id, webhook.credentials_id)+ if webhook.credentials_id+ else None+ )except NotFoundError as e:logger.warning(f"Webhook payload received for unknown webhook #{webhook_id}")raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))logger.debug(f"Webhook #{webhook_id}: {webhook}")- payload, event_type = await webhook_manager.validate_payload(webhook, request)+ payload, event_type = await webhook_manager.validate_payload(+ webhook, request, credentials+ )logger.debug(f"Validated {provider.value} {webhook.webhook_type} {event_type} event "f"with payload {payload}"diff --git a/autogpt_platform/backend/test/sdk/test_sdk_patching.py b/autogpt_platform/backend/test/sdk/test_sdk_patching.pyindex 21c2d72fb7..42ea47bb43 100644--- a/autogpt_platform/backend/test/sdk/test_sdk_patching.py+++ b/autogpt_platform/backend/test/sdk/test_sdk_patching.py@@ -14,6 +14,7 @@ from backend.sdk import (AutoRegistry,BaseOAuthHandler,BaseWebhooksManager,+ Credentials,ProviderBuilder,)@@ -34,7 +35,7 @@ class MockWebhookManager(BaseWebhooksManager):PROVIDER_NAME = ProviderName.GITHUB@classmethod- async def validate_payload(cls, webhook, request):+ async def validate_payload(cls, webhook, request, credentials: Credentials | None):return {}, "test_event"async def _register_webhook(self, *args, **kwargs):diff --git a/autogpt_platform/backend/test/sdk/test_sdk_webhooks.py b/autogpt_platform/backend/test/sdk/test_sdk_webhooks.pyindex 511448c97f..65101c8fe6 100644--- a/autogpt_platform/backend/test/sdk/test_sdk_webhooks.py+++ b/autogpt_platform/backend/test/sdk/test_sdk_webhooks.py@@ -19,6 +19,7 @@ from backend.sdk import (BlockOutput,BlockSchema,BlockWebhookConfig,+ Credentials,CredentialsField,CredentialsMetaInput,Field,@@ -45,7 +46,9 @@ class TestWebhooksManager(BaseWebhooksManager):TEST = "test"@classmethod- async def validate_payload(cls, webhook, request):+ async def validate_payload(+ cls, webhook, request, credentials: Credentials | None = None+ ):"""Validate incoming webhook payload."""# Mock implementationpayload = {"test": "data"}diff --git a/autogpt_platform/frontend/src/components/integrations/credentials-input.tsx b/autogpt_platform/frontend/src/components/integrations/credentials-input.tsxindex 0bcf8f7d80..078319189a 100644--- a/autogpt_platform/frontend/src/components/integrations/credentials-input.tsx+++ b/autogpt_platform/frontend/src/components/integrations/credentials-input.tsx@@ -411,7 +411,9 @@ export const CredentialsInput: FC<{.map((credentials, index) => (<SelectItem key={index} value={credentials.id}><ProviderIcon className="mr-2 inline h-4 w-4" />- {credentials.username}+ {credentials.title ||+ credentials.username ||+ `Your ${providerName} account`}</SelectItem>))}{savedCredentials