Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
feat(SKY-12068): add Email Inbox workflow block (Gmail + Outlook) (#7303)
Suchintan20845c8f1e6f
diff --git a/alembic/versions/2026_07_11_0215-062b0fc39d36_add_microsoft_oauth_credentials.py b/alembic/versions/2026_07_11_0215-062b0fc39d36_add_microsoft_oauth_credentials.pynew file mode 100644index 000000000..b1d47ecf1--- /dev/null+++ b/alembic/versions/2026_07_11_0215-062b0fc39d36_add_microsoft_oauth_credentials.py@@ -0,0 +1,80 @@+"""add microsoft_oauth_credentials++Revision ID: 062b0fc39d36+Revises: 7a729fa75d9b+Create Date: 2026-07-11T02:15:25.519747+00:00++"""++from typing import Sequence, Union++import sqlalchemy as sa++from alembic import op++# revision identifiers, used by Alembic.+revision: str = "062b0fc39d36"+down_revision: Union[str, None] = "7a729fa75d9b"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ op.create_table(+ "microsoft_oauth_credentials",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("organization_id", sa.String(), nullable=False),+ sa.Column("credential_name", sa.String(), nullable=False, server_default="Default"),+ sa.Column("state", sa.String(), nullable=False, server_default="pending_consent"),+ sa.Column(+ "scopes_requested",+ sa.JSON(),+ nullable=False,+ server_default=sa.text("'[]'"),+ ),+ sa.Column(+ "scopes_granted",+ sa.JSON(),+ nullable=False,+ server_default=sa.text("'[]'"),+ ),+ sa.Column("encrypted_refresh_token", sa.String(), nullable=True),+ sa.Column("encrypted_method", sa.String(), nullable=True),+ sa.Column("consent_nonce", sa.String(), nullable=True),+ sa.Column("consent_redirect_uri", sa.String(), nullable=True),+ sa.Column("consent_code_verifier", sa.String(), nullable=True),+ sa.Column("consent_app_origin", sa.String(), nullable=True),+ sa.Column("consent_expires_at", sa.DateTime(), nullable=True),+ sa.Column("created_at", sa.DateTime(), nullable=False, server_default=sa.func.now()),+ sa.Column("modified_at", sa.DateTime(), nullable=False, server_default=sa.func.now()),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.organization_id"]),+ sa.PrimaryKeyConstraint("id"),+ sa.CheckConstraint(+ "state IN ('pending_consent', 'active', 'revoked', 'error')",+ name="ck_microsoft_oauth_credentials_state",+ ),+ )+ op.create_index(+ "ix_microsoft_oauth_credentials_organization_id",+ "microsoft_oauth_credentials",+ ["organization_id"],+ )+ op.create_index(+ "ix_microsoft_oauth_credentials_state",+ "microsoft_oauth_credentials",+ ["state"],+ )+ op.create_index(+ "ux_microsoft_oauth_credentials_consent_nonce",+ "microsoft_oauth_credentials",+ ["consent_nonce"],+ unique=True,+ postgresql_where=sa.text("consent_nonce IS NOT NULL"),+ )+++def downgrade() -> None:+ op.drop_index("ux_microsoft_oauth_credentials_consent_nonce", table_name="microsoft_oauth_credentials")+ op.drop_index("ix_microsoft_oauth_credentials_state", table_name="microsoft_oauth_credentials")+ op.drop_index("ix_microsoft_oauth_credentials_organization_id", table_name="microsoft_oauth_credentials")+ op.drop_table("microsoft_oauth_credentials")diff --git a/docs/pr-screenshots/email-inbox-editor-gmail.png b/docs/pr-screenshots/email-inbox-editor-gmail.pngnew file mode 100644index 000000000..a4526c50bBinary files /dev/null and b/docs/pr-screenshots/email-inbox-editor-gmail.png differdiff --git a/docs/pr-screenshots/email-inbox-editor-outlook.png b/docs/pr-screenshots/email-inbox-editor-outlook.pngnew file mode 100644index 000000000..daad32a3aBinary files /dev/null and b/docs/pr-screenshots/email-inbox-editor-outlook.png differdiff --git a/docs/pr-screenshots/email-inbox-node-canvas.png b/docs/pr-screenshots/email-inbox-node-canvas.pngnew file mode 100644index 000000000..32c9a1149Binary files /dev/null and b/docs/pr-screenshots/email-inbox-node-canvas.png differdiff --git a/skyvern-frontend/src/api/types.ts b/skyvern-frontend/src/api/types.tsindex 9cd2ce707..d98b97217 100644--- a/skyvern-frontend/src/api/types.ts+++ b/skyvern-frontend/src/api/types.ts@@ -416,6 +416,45 @@ export interface CreateGoogleOAuthCallbackRequest {state: string;}+export interface MicrosoftOAuthCredential {+ id: string;+ organization_id: string;+ credential_name: string;+ state?: string;+ scopes_requested?: string[] | string | null;+ scopes_granted?: string[] | string | null;+ scopes?: string[] | string | null;+ valid?: boolean | null;+ created_at: string;+ modified_at: string;+}++export interface MicrosoftOAuthCredentialResponse {+ credential: MicrosoftOAuthCredential;+ app_origin?: string | null;+}++export interface MicrosoftOAuthCredentialListResponse {+ credentials: MicrosoftOAuthCredential[];+}++export interface CreateMicrosoftOAuthAuthorizeRequest {+ redirect_uri: string;+ credential_name?: string;+ scope_profile?: "outlook_mail";+ app_origin?: string;+}++export interface MicrosoftOAuthAuthorizeResponse {+ authorize_url: string;+ state: string;+}++export interface CreateMicrosoftOAuthCallbackRequest {+ code: string;+ state: string;+}+export interface GoogleSpreadsheetSummary {id: string;name: string;diff --git a/skyvern-frontend/src/components/icons/OutlookIcon.tsx b/skyvern-frontend/src/components/icons/OutlookIcon.tsxnew file mode 100644index 000000000..62fff7d26--- /dev/null+++ b/skyvern-frontend/src/components/icons/OutlookIcon.tsx@@ -0,0 +1,30 @@+type Props = {+ className?: string;+};++function OutlookIcon({ className }: Props) {+ return (+ <svg+ width="24"+ height="24"+ viewBox="0 0 256 256"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ className={className}+ >+ <path d="M96 48H224V208H96V48Z" fill="#0A6ED1" />+ <path d="M96 64H208V96H96V64Z" fill="#28A8EA" />+ <path d="M96 96H208V128H96V96Z" fill="#0078D4" />+ <path d="M96 128H208V192H96V128Z" fill="#0364B8" />+ <path d="M208 80L144 128L208 176V80Z" fill="#50D9FF" fillOpacity="0.7" />+ <path d="M80 64L16 76V180L80 192V64Z" fill="#0078D4" />+ <path d="M80 64H128V192H80V64Z" fill="#005A9E" />+ <path+ d="M47.5 153.5C38.2 153.5 31 146.2 31 128.1C31 109.8 38.5 102.5 48 102.5C57.3 102.5 64.5 109.8 64.5 127.9C64.5 146.2 57 153.5 47.5 153.5ZM47.8 140.2C51.1 140.2 53.5 136.7 53.5 128.1C53.5 119.1 51 115.8 47.7 115.8C44.4 115.8 42 119.3 42 127.9C42 136.9 44.5 140.2 47.8 140.2Z"+ fill="white"+ />+ </svg>+ );+}++export { OutlookIcon };diff --git a/skyvern-frontend/src/hooks/useMicrosoftOAuthCredentials.ts b/skyvern-frontend/src/hooks/useMicrosoftOAuthCredentials.tsnew file mode 100644index 000000000..b7dc82fde--- /dev/null+++ b/skyvern-frontend/src/hooks/useMicrosoftOAuthCredentials.ts@@ -0,0 +1,293 @@+import { useEffect } from "react";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { getClient } from "@/api/AxiosClient";+import { useCredentialGetter } from "./useCredentialGetter";+import {+ CreateMicrosoftOAuthAuthorizeRequest,+ CreateMicrosoftOAuthCallbackRequest,+ MicrosoftOAuthAuthorizeResponse,+ MicrosoftOAuthCredential,+ MicrosoftOAuthCredentialListResponse,+ MicrosoftOAuthCredentialResponse,+} from "@/api/types";+import { useToast } from "@/components/ui/use-toast";+export { MICROSOFT_MAIL_REQUIRED_SCOPES } from "@/util/microsoftScopes";++const BROADCAST_CHANNEL_NAME = "skyvern:microsoft-oauth-credentials";++const credentialBroadcastChannel: BroadcastChannel | null =+ typeof BroadcastChannel !== "undefined"+ ? new BroadcastChannel(BROADCAST_CHANNEL_NAME)+ : null;++function safePostCredentialsInvalidate(+ channel: Pick<BroadcastChannel, "postMessage"> | null,+): void {+ try {+ channel?.postMessage("invalidate");+ } catch (error) {+ if (error instanceof DOMException && error.name === "InvalidStateError") {+ return;+ }+ throw error;+ }+}++function broadcastCredentialsChanged() {+ safePostCredentialsInvalidate(credentialBroadcastChannel);+}++export function normalizeMicrosoftOAuthScopes(+ scopes: readonly string[] | string | null | undefined,+): readonly string[] | undefined {+ if (Array.isArray(scopes)) {+ return scopes;+ }+ if (typeof scopes === "string") {+ return scopes+ .split(/[\s,]+/)+ .map((scope) => scope.trim())+ .filter(Boolean);+ }+ return undefined;+}++export function normalizeMicrosoftScopeSegment(scope: string): string {+ const parts = scope.split("/").filter(Boolean);+ return parts[parts.length - 1] ?? scope;+}++export function getMicrosoftOAuthCredentialScopesGranted(+ credential: MicrosoftOAuthCredential,+): readonly string[] {+ return (+ normalizeMicrosoftOAuthScopes(credential.scopes_granted) ??+ normalizeMicrosoftOAuthScopes(credential.scopes) ??+ []+ );+}++export function getMicrosoftOAuthCredentialScopesRequested(+ credential: MicrosoftOAuthCredential,+): readonly string[] {+ return normalizeMicrosoftOAuthScopes(credential.scopes_requested) ?? [];+}++export function isMicrosoftOAuthCredentialActive(+ credential: MicrosoftOAuthCredential,+): boolean {+ if (credential.state) {+ return credential.state === "active";+ }+ return credential.valid === true;+}++export function hasMicrosoftOAuthCredentialScopes(+ credential: MicrosoftOAuthCredential,+ requiredScopes: readonly string[],+): boolean {+ const granted = new Set(+ getMicrosoftOAuthCredentialScopesGranted(credential).map(+ normalizeMicrosoftScopeSegment,+ ),+ );+ return requiredScopes.every((scope) =>+ granted.has(normalizeMicrosoftScopeSegment(scope)),+ );+}++export function matchesMicrosoftOAuthIntegrationScopes(+ credential: MicrosoftOAuthCredential,+ requiredScopes: readonly string[],+): boolean {+ const requested = getMicrosoftOAuthCredentialScopesRequested(credential);+ if (requested.length > 0) {+ const requestedSet = new Set(requested.map(normalizeMicrosoftScopeSegment));+ return requiredScopes.every((scope) =>+ requestedSet.has(normalizeMicrosoftScopeSegment(scope)),+ );+ }+ return hasMicrosoftOAuthCredentialScopes(credential, requiredScopes);+}++export function getDefaultMicrosoftOAuthCredentialId(+ credentials: MicrosoftOAuthCredential[],+): string | undefined {+ return (+ credentials.find(isMicrosoftOAuthCredentialActive)?.id ?? credentials[0]?.id+ );+}++type ApiError = { response?: { data?: { detail?: string } } } & Error;++function extractApiErrorMessage(error: unknown, fallback: string): string {+ const err = error as ApiError | undefined;+ return err?.response?.data?.detail || err?.message || fallback;+}++export function useMicrosoftOAuthCredentials({+ enabled = true,+}: { enabled?: boolean } = {}) {+ const credentialGetter = useCredentialGetter();+ const queryClient = useQueryClient();+ const { toast } = useToast();++ useEffect(() => {+ if (!credentialBroadcastChannel) return;+ const listener = () => {+ queryClient.invalidateQueries({+ queryKey: ["microsoftOAuthCredentials"],+ });+ };+ credentialBroadcastChannel.addEventListener("message", listener);+ return () => {+ credentialBroadcastChannel.removeEventListener("message", listener);+ };+ }, [queryClient]);++ const {+ data: credentials,+ isLoading,+ isFetching,+ error,+ } = useQuery<MicrosoftOAuthCredential[]>({+ queryKey: ["microsoftOAuthCredentials"],+ enabled,+ queryFn: async () => {+ const client = await getClient(credentialGetter);+ const response = await client.get("/microsoft/oauth/credentials");+ return (response.data as MicrosoftOAuthCredentialListResponse)+ .credentials;+ },+ staleTime: 30_000,+ refetchOnWindowFocus: true,+ });++ const authorizeMutation = useMutation({+ mutationFn: async (data: CreateMicrosoftOAuthAuthorizeRequest) => {+ const client = await getClient(credentialGetter);+ return await client+ .post("/microsoft/oauth/authorize", data)+ .then((response) => response.data as MicrosoftOAuthAuthorizeResponse);+ },+ onError: (error: unknown) => {+ toast({+ title: "Error",+ description: extractApiErrorMessage(+ error,+ "Failed to start Microsoft OAuth flow",+ ),+ variant: "destructive",+ });+ },+ });++ const oauthCallbackMutation = useMutation({+ mutationFn: async (data: CreateMicrosoftOAuthCallbackRequest) => {+ const client = await getClient(credentialGetter);+ return await client+ .post("/microsoft/oauth/callback", data)+ .then((response) => response.data as MicrosoftOAuthCredentialResponse);+ },+ onSuccess: () => {+ queryClient.invalidateQueries({+ queryKey: ["microsoftOAuthCredentials"],+ });+ broadcastCredentialsChanged();+ toast({+ title: "Success",+ description: "Microsoft account connected successfully",+ });+ },+ onError: (error: unknown) => {+ toast({+ title: "Error",+ description: extractApiErrorMessage(+ error,+ "Failed to connect Microsoft account",+ ),+ variant: "destructive",+ });+ },+ });++ const renameCredentialMutation = useMutation({+ mutationFn: async (input: {+ credentialId: string;+ credentialName: string;+ }) => {+ const client = await getClient(credentialGetter);+ return await client+ .patch(`/microsoft/oauth/credentials/${input.credentialId}`, {+ credential_name: input.credentialName,+ })+ .then((response) => response.data as MicrosoftOAuthCredentialResponse);+ },+ onSuccess: () => {+ queryClient.invalidateQueries({+ queryKey: ["microsoftOAuthCredentials"],+ });+ broadcastCredentialsChanged();+ toast({+ title: "Success",+ description: "Connection renamed",+ });+ },+ onError: (error: unknown) => {+ toast({+ title: "Error",+ description: extractApiErrorMessage(+ error,+ "Failed to rename credential",+ ),+ variant: "destructive",+ });+ },+ });++ const deleteCredentialMutation = useMutation({+ mutationFn: async (credentialId: string) => {+ const client = await getClient(credentialGetter);+ return await client.delete(+ `/microsoft/oauth/credentials/${credentialId}`,+ );+ },+ onSuccess: () => {+ queryClient.invalidateQueries({+ queryKey: ["microsoftOAuthCredentials"],+ });+ broadcastCredentialsChanged();+ toast({+ title: "Success",+ description: "Microsoft credential disconnected",+ });+ },+ onError: (error: unknown) => {+ toast({+ title: "Error",+ description: extractApiErrorMessage(+ error,+ "Failed to disconnect credential",+ ),+ variant: "destructive",+ });+ },+ });++ return {+ credentials: credentials ?? [],+ isLoading,+ isFetching,+ error,+ startAuthorize: authorizeMutation.mutateAsync,+ isStartingAuthorize: authorizeMutation.isPending,+ submitOAuthCallback: oauthCallbackMutation.mutate,+ submitOAuthCallbackAsync: oauthCallbackMutation.mutateAsync,+ isSubmittingCallback: oauthCallbackMutation.isPending,+ deleteCredential: deleteCredentialMutation.mutate,+ deleteCredentialAsync: deleteCredentialMutation.mutateAsync,+ isDeletingCredential: deleteCredentialMutation.isPending,+ renameCredentialAsync: renameCredentialMutation.mutateAsync,+ isRenamingCredential: renameCredentialMutation.isPending,+ };+}diff --git a/skyvern-frontend/src/router.tsx b/skyvern-frontend/src/router.tsxindex 297d896f9..e012fce4f 100644--- a/skyvern-frontend/src/router.tsx+++ b/skyvern-frontend/src/router.tsx@@ -405,6 +405,10 @@ const router = createBrowserRouter([path: "google/callback",element: <GoogleOAuthCallback />,},+ {+ path: "microsoft/callback",+ element: <Navigate to="/integrations" replace />,+ },],},],diff --git a/skyvern-frontend/src/routes/workflows/components/MicrosoftOAuthCredentialSelector.tsx b/skyvern-frontend/src/routes/workflows/components/MicrosoftOAuthCredentialSelector.tsxnew file mode 100644index 000000000..f28e77ad1--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/components/MicrosoftOAuthCredentialSelector.tsx@@ -0,0 +1,162 @@+import { useEffect, useRef, useState } from "react";+import {+ CustomSelectItem,+ Select,+ SelectContent,+ SelectItem,+ SelectItemText,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { Skeleton } from "@/components/ui/skeleton";+import { WorkflowBlockInputTextarea } from "@/components/WorkflowBlockInputTextarea";+import {+ getDefaultMicrosoftOAuthCredentialId,+ hasMicrosoftOAuthCredentialScopes,+ useMicrosoftOAuthCredentials,+} from "@/hooks/useMicrosoftOAuthCredentials";+import { MICROSOFT_MAIL_REQUIRED_SCOPES } from "@/util/microsoftScopes";+import { PlusIcon } from "@radix-ui/react-icons";++type Props = {+ nodeId: string;+ value: string;+ onChange: (value: string) => void;+ requiredScopes: readonly string[];+};++const ADVANCED_OPTION = "__advanced__";+const SETTINGS_OPTION = "__settings__";++function MicrosoftOAuthCredentialSelector({+ nodeId,+ value,+ onChange,+ requiredScopes,+}: Readonly<Props>) {+ const {+ credentials: allCredentials,+ isLoading,+ isFetching,+ } = useMicrosoftOAuthCredentials();+ const [showAdvanced, setShowAdvanced] = useState(false);+ const credentials = allCredentials.filter((credential) =>+ hasMicrosoftOAuthCredentialScopes(credential, requiredScopes),+ );++ const onChangeRef = useRef(onChange);+ onChangeRef.current = onChange;++ const isTemplateValue = value.includes("{{") || value.includes("{%");+ const useAdvanced = showAdvanced || isTemplateValue;++ const hasCredentials = credentials.length > 0;+ const isKnownCredential = credentials.some((c) => c.id === value);+ const firstValidId = getDefaultMicrosoftOAuthCredentialId(credentials);+ const needsAutoFill = !value;++ useEffect(() => {+ if (+ isLoading ||+ isFetching ||+ !hasCredentials ||+ !needsAutoFill ||+ !firstValidId+ ) {+ return;+ }+ onChangeRef.current(firstValidId);+ }, [isLoading, isFetching, hasCredentials, needsAutoFill, firstValidId]);++ const handlePickerValueChange = (selected: string) => {+ if (selected === ADVANCED_OPTION) {+ setShowAdvanced(true);+ return;+ }++ if (selected === SETTINGS_OPTION) {+ window.open("/integrations", "_blank");+ return;+ }++ onChange(selected);+ };++ const handleUseAccountPicker = () => {+ setShowAdvanced(false);++ if (isTemplateValue) {+ onChange("");+ }+ };++ if (isLoading) {+ return <Skeleton className="h-9 w-full" />;+ }++ return (+ <div className="space-y-2">+ {useAdvanced ? (+ <>+ <WorkflowBlockInputTextarea+ nodeId={nodeId}+ value={value}+ onChange={onChange}+ placeholder="{{ microsoft_credential_id }}"+ className="nopan text-xs"+ />+ <button+ type="button"+ onClick={handleUseAccountPicker}+ className="text-xs text-slate-400 underline hover:text-slate-300"+ >+ Use account picker+ </button>+ </>+ ) : (+ <>+ {value && hasCredentials && !isKnownCredential ? (+ <p className="rounded-md border border-amber-600/40 bg-amber-900/20 px-2 py-1 text-[0.7rem] text-amber-200">+ Saved Microsoft account is no longer connected. Pick another+ below.+ </p>+ ) : null}++ <Select value={value} onValueChange={handlePickerValueChange}>+ <SelectTrigger className="nopan text-xs">+ <SelectValue placeholder="Select a Microsoft account" />+ </SelectTrigger>+ <SelectContent>+ {credentials.map((cred) => (+ <CustomSelectItem key={cred.id} value={cred.id}>+ <div className="space-y-0.5">+ <p className="text-sm font-medium">+ <SelectItemText>{cred.credential_name}</SelectItemText>+ </p>+ <p className="text-xs text-slate-400">{cred.id}</p>+ </div>+ </CustomSelectItem>+ ))}++ <SelectItem value={SETTINGS_OPTION}>+ <div className="flex items-center gap-2">+ <PlusIcon className="size-4" />+ <span>Connect new account</span>+ </div>+ </SelectItem>++ <SelectItem value={ADVANCED_OPTION}>+ <div className="flex items-center gap-2">+ <span className="font-mono text-xs">{"{{}}"}</span>+ <span>Use template expression</span>+ </div>+ </SelectItem>+ </SelectContent>+ </Select>+ </>+ )}+ </div>+ );+}++export { MICROSOFT_MAIL_REQUIRED_SCOPES, MicrosoftOAuthCredentialSelector };diff --git a/skyvern-frontend/src/routes/workflows/editor/collapse/collapsibleBlockTypes.ts b/skyvern-frontend/src/routes/workflows/editor/collapse/collapsibleBlockTypes.tsindex c0ea4f59e..6a9ebab72 100644--- a/skyvern-frontend/src/routes/workflows/editor/collapse/collapsibleBlockTypes.ts+++ b/skyvern-frontend/src/routes/workflows/editor/collapse/collapsibleBlockTypes.ts@@ -27,6 +27,7 @@ const COLLAPSIBLE_NODE_TYPE_TO_BLOCK_TYPE: Record<string, WorkflowBlockType> = {http_request: "http_request",printPage: "print_page",workflowTrigger: "workflow_trigger",+ emailInbox: "email_inbox",googleSheetsRead: "google_sheets_read",googleSheetsWrite: "google_sheets_write",pdfFill: "pdf_fill",diff --git a/skyvern-frontend/src/routes/workflows/editor/helpContent.ts b/skyvern-frontend/src/routes/workflows/editor/helpContent.tsindex 2f6737440..3fe5f2612 100644--- a/skyvern-frontend/src/routes/workflows/editor/helpContent.ts+++ b/skyvern-frontend/src/routes/workflows/editor/helpContent.ts@@ -102,6 +102,18 @@ export const helpTooltips = {hasHeaderRow:"If enabled, the first row is used as column headers for the output objects",},+ email_inbox: {+ ...baseHelpTooltipContent,+ emailClient: "Choose Gmail or Outlook as the inbox provider.",+ credentialId: "The connected email account used to read inbox messages.",+ folder: "Gmail label e.g. INBOX / Outlook folder e.g. inbox.",+ prompt: "Describe which emails to keep. Leave blank to keep all.",+ sender: "Only include emails from this sender.",+ subject: "Only include emails matching this subject.",+ newerThanDays: "Only include emails newer than this many days.",+ maxResults: "Maximum number of emails to return.",+ includeBody: "Include email body text in matching results.",+ },google_sheets_write: {...baseHelpTooltipContent,spreadsheetUrl:diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/EmailInboxNode/EmailInboxEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/EmailInboxNode/EmailInboxEditor.tsxnew file mode 100644index 000000000..5f43ef2cc--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/EmailInboxNode/EmailInboxEditor.tsx@@ -0,0 +1,306 @@+import { useEdges, useNodes, useNodesData } from "@xyflow/react";++import { HelpTooltip } from "@/components/HelpTooltip";+import { WorkflowBlockInputTextarea } from "@/components/WorkflowBlockInputTextarea";+import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,+} from "@/components/ui/accordion";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { Separator } from "@/components/ui/separator";+import { Switch } from "@/components/ui/switch";+import { GoogleOAuthCredentialSelector } from "@/routes/workflows/components/GoogleOAuthCredentialSelector";+import {+ MicrosoftOAuthCredentialSelector,+ MICROSOFT_MAIL_REQUIRED_SCOPES,+} from "@/routes/workflows/components/MicrosoftOAuthCredentialSelector";+import { GOOGLE_GMAIL_REQUIRED_SCOPES } from "@/util/googleScopes";++import { helpTooltips } from "../../helpContent";+import { useUpdate } from "../../useUpdate";+import { getAvailableOutputParameterKeys } from "../../workflowEditorUtils";+import { type AppNode } from "..";+import { ParametersMultiSelect } from "../TaskNode/ParametersMultiSelect";+import {+ type EmailClient,+ type EmailInboxNode,+ type EmailInboxNodeData,+} from "./types";++function parseNullablePositiveInteger(value: string): number | null {+ if (!value.trim()) {+ return null;+ }+ const parsed = Number.parseInt(value, 10);+ return Number.isNaN(parsed) ? null : parsed;+}++function parsePositiveInteger(value: string, fallback: number): number {+ const parsed = Number.parseInt(value, 10);+ return Number.isNaN(parsed) ? fallback : parsed;+}++function FieldLabel({+ field,+ label,+ fallback,+}: {+ field: keyof (typeof helpTooltips)["email_inbox"];+ label: string;+ fallback: string;+}) {+ return (+ <div className="flex gap-2">+ <Label className="text-xs text-slate-300">{label}</Label>+ <HelpTooltip content={helpTooltips["email_inbox"]?.[field] ?? fallback} />+ </div>+ );+}++function EmailInboxEditor({ blockId }: { blockId: string }) {+ const nodeSlice = useNodesData<EmailInboxNode>(blockId);+ if (!nodeSlice || nodeSlice.type !== "emailInbox") {+ return null;+ }+ return <EmailInboxEditorBody blockId={blockId} data={nodeSlice.data} />;+}++function EmailInboxEditorBody({+ blockId,+ data,+}: {+ blockId: string;+ data: EmailInboxNodeData;+}) {+ const { editable } = data;+ const update = useUpdate<EmailInboxNodeData>({ id: blockId, editable });+ const nodes = useNodes<AppNode>();+ const edges = useEdges();+ const outputParameterKeys = getAvailableOutputParameterKeys(+ nodes,+ edges,+ blockId,+ );++ const updateEmailClient = (emailClient: EmailClient) => {+ update({ emailClient, credentialId: "" });+ };++ return (+ <div data-testid="email-inbox-block-form" className="space-y-4">+ <div className="space-y-3">+ <div className="text-xs font-medium uppercase tracking-wider text-slate-400">+ Connection+ </div>++ <div className="space-y-2">+ <FieldLabel+ field="emailClient"+ label="Email Client"+ fallback="The email provider to read from."+ />+ <Select+ value={data.emailClient}+ onValueChange={(value) => updateEmailClient(value as EmailClient)}+ >+ <SelectTrigger className="nopan text-xs">+ <SelectValue placeholder="Select an email client" />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="gmail">Gmail</SelectItem>+ <SelectItem value="outlook">Outlook</SelectItem>+ </SelectContent>+ </Select>+ </div>++ <div className="space-y-2">+ <FieldLabel+ field="credentialId"+ label={+ data.emailClient === "gmail"+ ? "Google Account"+ : "Microsoft Account"+ }+ fallback="The connected account used to read email."+ />+ {data.emailClient === "gmail" ? (+ <GoogleOAuthCredentialSelector+ nodeId={blockId}+ value={data.credentialId}+ onChange={(next) => update({ credentialId: next })}+ requiredScopes={GOOGLE_GMAIL_REQUIRED_SCOPES}+ />+ ) : (+ <MicrosoftOAuthCredentialSelector+ nodeId={blockId}+ value={data.credentialId}+ onChange={(next) => update({ credentialId: next })}+ requiredScopes={MICROSOFT_MAIL_REQUIRED_SCOPES}+ />+ )}+ </div>+ </div>++ <Separator />++ <Accordion type="multiple" defaultValue={["data", "filters"]}>+ <AccordionItem value="data" className="border-b-0">+ <AccordionTrigger className="py-2">Data</AccordionTrigger>+ <AccordionContent className="pl-6 pr-1 pt-4">+ <div className="space-y-3">+ <div className="space-y-2">+ <FieldLabel+ field="folder"+ label="Folder"+ fallback="Gmail label e.g. INBOX / Outlook folder e.g. inbox."+ />+ <WorkflowBlockInputTextarea+ nodeId={blockId}+ onChange={(next) => update({ folder: next })}+ value={data.folder}+ placeholder="INBOX"+ className="nopan text-xs"+ />+ </div>++ <div className="space-y-2">+ <FieldLabel+ field="prompt"+ label="Match prompt"+ fallback="Describe which emails to keep. Leave blank to keep all."+ />+ <WorkflowBlockInputTextarea+ nodeId={blockId}+ onChange={(next) => update({ prompt: next })}+ value={data.prompt}+ placeholder="Describe which emails to keep. Leave blank to keep all."+ className="nopan text-xs"+ />+ </div>+ </div>+ </AccordionContent>+ </AccordionItem>++ <AccordionItem value="filters" className="border-b-0">+ <AccordionTrigger className="py-2">Optional Filters</AccordionTrigger>+ <AccordionContent className="pl-6 pr-1 pt-4">+ <div className="space-y-3">+ <div className="space-y-2">+ <FieldLabel+ field="sender"+ label="Sender"+ fallback="Only include emails from this sender."+ />+ <WorkflowBlockInputTextarea+ nodeId={blockId}+ onChange={(next) => update({ sender: next })}+ value={data.sender}+ placeholder="[email protected]"+ className="nopan text-xs"+ />+ </div>++ <div className="space-y-2">+ <FieldLabel+ field="subject"+ label="Subject"+ fallback="Only include emails matching this subject."+ />+ <WorkflowBlockInputTextarea+ nodeId={blockId}+ onChange={(next) => update({ subject: next })}+ value={data.subject}+ placeholder="Subject contains..."+ className="nopan text-xs"+ />+ </div>++ <div className="space-y-2">+ <FieldLabel+ field="newerThanDays"+ label="Newer Than Days"+ fallback="Only include emails newer than this many days."+ />+ <Input+ type="number"+ min={1}+ value={data.newerThanDays ?? ""}+ onChange={(event) =>+ update({+ newerThanDays: parseNullablePositiveInteger(+ event.currentTarget.value,+ ),+ })+ }+ placeholder="Any age"+ className="nopan text-xs"+ />+ </div>++ <div className="space-y-2">+ <FieldLabel+ field="maxResults"+ label="Max Results"+ fallback="Maximum number of emails to return."+ />+ <Input+ type="number"+ min={1}+ value={data.maxResults}+ onChange={(event) =>+ update({+ maxResults: parsePositiveInteger(+ event.currentTarget.value,+ data.maxResults,+ ),+ })+ }+ className="nopan text-xs"+ />+ </div>++ <div className="flex items-center justify-between">+ <FieldLabel+ field="includeBody"+ label="Include Body"+ fallback="Include email body text in matching results."+ />+ <Switch+ checked={data.includeBody}+ onCheckedChange={(checked) =>+ update({ includeBody: checked })+ }+ />+ </div>+ </div>+ </AccordionContent>+ </AccordionItem>++ <AccordionItem value="advanced" className="border-b-0">+ <AccordionTrigger className="py-2">+ Advanced Settings+ </AccordionTrigger>+ <AccordionContent className="pl-6 pr-1 pt-4">+ <ParametersMultiSelect+ availableOutputParameters={outputParameterKeys}+ parameters={data.parameterKeys}+ onParametersChange={(parameterKeys) => update({ parameterKeys })}+ />+ </AccordionContent>+ </AccordionItem>+ </Accordion>+ </div>+ );+}++export { EmailInboxEditor };diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/EmailInboxNode/EmailInboxNode.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/EmailInboxNode/EmailInboxNode.tsxnew file mode 100644index 000000000..ba5c8223b--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/EmailInboxNode/EmailInboxNode.tsx@@ -0,0 +1,76 @@+import { Handle, NodeProps, Position } from "@xyflow/react";+import { useParams } from "react-router-dom";++import { statusIsRunningOrQueued } from "@/routes/tasks/types";+import { useWorkflowRunQuery } from "@/routes/workflows/hooks/useWorkflowRunQuery";+import { useRecordingStore } from "@/store/useRecordingStore";+import { cn } from "@/util/utils";++import { useCollapseContext } from "../../collapse/CollapseContext";+import { NodeBody } from "../../collapse/NodeBody";+import { BuildModeOnly } from "../BuildModeOnly";+import { NodeHeader } from "../components/NodeHeader";+import { EmailInboxEditor } from "./EmailInboxEditor";+import type { EmailInboxNode as EmailInboxNodeType } from "./types";++function EmailInboxNode({ id, data }: NodeProps<EmailInboxNodeType>) {+ const { editable, label } = data;+ const { blockLabel: urlBlockLabel } = useParams();+ const { data: workflowRun } = useWorkflowRunQuery();+ const workflowRunIsRunningOrQueued =+ workflowRun && statusIsRunningOrQueued(workflowRun);+ const thisBlockIsTargetted =+ urlBlockLabel !== undefined && urlBlockLabel === label;+ const thisBlockIsPlaying =+ workflowRunIsRunningOrQueued && thisBlockIsTargetted;+ const recordingStore = useRecordingStore();+ const { open } = useCollapseContext();++ return (+ <div+ className={cn({+ "pointer-events-none opacity-50": recordingStore.isRecording,+ })}+ >+ <Handle+ type="source"+ position={Position.Bottom}+ id="a"+ className="opacity-0"+ />+ <Handle+ type="target"+ position={Position.Top}+ id="b"+ className="opacity-0"+ />+ <div+ className={cn(+ "transform-origin-center w-[30rem] space-y-4 rounded-lg bg-slate-elevation3 px-6 py-4 transition-shadow motion-reduce:transition-none",+ open ? "shadow-md" : "shadow-sm",+ {+ "pointer-events-none": thisBlockIsPlaying,+ "bg-slate-950 outline outline-2 outline-slate-300":+ thisBlockIsTargetted,+ },+ )}+ >+ <NodeHeader+ blockLabel={label}+ editable={editable}+ nodeId={id}+ totpIdentifier={null}+ totpUrl={null}+ type="email_inbox"+ />+ <NodeBody>+ <BuildModeOnly renderInReadOnlyComparison={false}>+ <EmailInboxEditor blockId={id} />+ </BuildModeOnly>+ </NodeBody>+ </div>+ </div>+ );+}++export { EmailInboxNode };diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/EmailInboxNode/index.ts b/skyvern-frontend/src/routes/workflows/editor/nodes/EmailInboxNode/index.tsnew file mode 100644index 000000000..4618e50d0--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/EmailInboxNode/index.ts@@ -0,0 +1,2 @@+export { EmailInboxNode } from "./EmailInboxNode";+export type { EmailInboxNode as EmailInboxNodeType } from "./types";diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/EmailInboxNode/types.ts b/skyvern-frontend/src/routes/workflows/editor/nodes/EmailInboxNode/types.tsnew file mode 100644index 000000000..da1067414--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/EmailInboxNode/types.ts@@ -0,0 +1,42 @@+import type { Node } from "@xyflow/react";+import { NodeBaseData } from "../types";+import { debuggableWorkflowBlockTypes } from "@/routes/workflows/types/workflowTypes";++export type EmailClient = "gmail" | "outlook";++export type EmailInboxNodeData = NodeBaseData & {+ emailClient: EmailClient;+ credentialId: string;+ folder: string;+ prompt: string;+ sender: string;+ subject: string;+ newerThanDays: number | null;+ maxResults: number;+ includeBody: boolean;+ parameterKeys: Array<string>;+};++export type EmailInboxNode = Node<EmailInboxNodeData, "emailInbox">;++export const emailInboxNodeDefaultData: EmailInboxNodeData = {+ debuggable: debuggableWorkflowBlockTypes.has("email_inbox"),+ label: "",+ continueOnFailure: false,+ editable: true,+ model: null,+ emailClient: "gmail",+ credentialId: "",+ folder: "INBOX",+ prompt: "",+ sender: "",+ subject: "",+ newerThanDays: null,+ maxResults: 25,+ includeBody: true,+ parameterKeys: [],+};++export function isEmailInboxNode(node: Node): node is EmailInboxNode {+ return node.type === "emailInbox";+}diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/EmailInboxNode/validate.ts b/skyvern-frontend/src/routes/workflows/editor/nodes/EmailInboxNode/validate.tsnew file mode 100644index 000000000..968ae660d--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/EmailInboxNode/validate.ts@@ -0,0 +1,15 @@+import type { EmailInboxNode } from "./types";++const missing = (value: string): boolean => !value.trim();++export function validateEmailInboxNode(node: EmailInboxNode): Array<string> {+ const errors: Array<string> = [];+ const { label } = node.data;+ if (missing(node.data.emailClient)) {+ errors.push(`${label}: Email client is required.`);+ }+ if (missing(node.data.credentialId)) {+ errors.push(`${label}: Email account is required.`);+ }+ return errors;+}diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/WorkflowBlockIcon.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/WorkflowBlockIcon.tsxindex ae5c96ff2..ec9f64e6f 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/WorkflowBlockIcon.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/WorkflowBlockIcon.tsx@@ -64,6 +64,9 @@ function WorkflowBlockIcon({ workflowBlockType, className }: Props) {case "send_email": {return <EnvelopeClosedIcon className={className} />;}+ case "email_inbox": {+ return <EnvelopeClosedIcon className={className} />;+ }case "task": {return <ListBulletIcon className={className} />;}diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/blockTypeFromNode.test.ts b/skyvern-frontend/src/routes/workflows/editor/nodes/blockTypeFromNode.test.tsindex 8789384c1..7b2743eb3 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/blockTypeFromNode.test.ts+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/blockTypeFromNode.test.ts@@ -12,6 +12,10 @@ describe("blockTypeFromNode", () => {);});+ it("maps emailInbox to email_inbox", () => {+ expect(blockTypeFromNode({ type: "emailInbox" })).toBe("email_inbox");+ });+it("maps googleSheetsWrite to google_sheets_write", () => {expect(blockTypeFromNode({ type: "googleSheetsWrite" })).toBe("google_sheets_write",diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/blockTypeFromNode.ts b/skyvern-frontend/src/routes/workflows/editor/nodes/blockTypeFromNode.tsindex bb7a5edc2..1a49438bf 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/blockTypeFromNode.ts+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/blockTypeFromNode.ts@@ -26,6 +26,7 @@ const REACT_FLOW_TYPE_TO_BLOCK_TYPE: Record<string, string> = {http_request: "http_request",printPage: "print_page",workflowTrigger: "workflow_trigger",+ emailInbox: "email_inbox",googleSheetsRead: "google_sheets_read",googleSheetsWrite: "google_sheets_write",pdfFill: "pdf_fill",diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/index.ts b/skyvern-frontend/src/routes/workflows/editor/nodes/index.tsindex 8a62ab13b..92f45d7b8 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/index.ts+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/index.ts@@ -52,6 +52,8 @@ import { PrintPageNode } from "./PrintPageNode/types";import { PrintPageNode as PrintPageNodeComponent } from "./PrintPageNode/PrintPageNode";import { WorkflowTriggerNode } from "./WorkflowTriggerNode/types";import { WorkflowTriggerNode as WorkflowTriggerNodeComponent } from "./WorkflowTriggerNode/WorkflowTriggerNode";+import { EmailInboxNode } from "./EmailInboxNode/types";+import { EmailInboxNode as EmailInboxNodeComponent } from "./EmailInboxNode/EmailInboxNode";import { GoogleSheetsReadNode } from "./GoogleSheetsReadNode/types";import { GoogleSheetsReadNode as GoogleSheetsReadNodeComponent } from "./GoogleSheetsReadNode/GoogleSheetsReadNode";import { GoogleSheetsWriteNode } from "./GoogleSheetsWriteNode/types";@@ -91,6 +93,7 @@ export type WorkflowBlockNode =| HttpRequestNode| PrintPageNode| WorkflowTriggerNode+ | EmailInboxNode| GoogleSheetsReadNode| GoogleSheetsWriteNode| PdfFillNode@@ -154,6 +157,7 @@ export const nodeTypes = {http_request: wrapBlock(HttpRequestNodeComponent),printPage: wrapBlock(PrintPageNodeComponent),workflowTrigger: wrapBlock(WorkflowTriggerNodeComponent),+ emailInbox: wrapBlock(EmailInboxNodeComponent),googleSheetsRead: wrapBlock(GoogleSheetsReadNodeComponent),googleSheetsWrite: wrapBlock(GoogleSheetsWriteNodeComponent),pdfFill: wrapBlock(PdfFillNodeComponent),diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/types.ts b/skyvern-frontend/src/routes/workflows/editor/nodes/types.tsindex d4221b267..303439d45 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/types.ts+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/types.ts@@ -96,6 +96,7 @@ export const workflowBlockTitle: {http_request: "HTTP Request",print_page: "Print Page",workflow_trigger: "Agent Trigger",+ email_inbox: "Email Inbox",google_sheets_read: "Google Sheets Read",google_sheets_write: "Google Sheets Write",pdf_fill: "PDF Fill",diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/wrap.test.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/wrap.test.tsxindex 720d36a1a..a26a11a6f 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/wrap.test.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/wrap.test.tsx@@ -45,6 +45,7 @@ describe("nodeTypes composition order", () => {"googleSheetsWrite","pdfFill","splitPdf",+ "emailInbox",]),);});diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm.test.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm.test.tsxindex b9d6e0986..35a2d5e43 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm.test.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm.test.tsx@@ -84,7 +84,7 @@ describe("BLOCK_FORMS dispatcher", () => {}});- test("contains the 27 expected node.type keys", () => {+ test("contains the 29 expected node.type keys", () => {expect(new Set(BLOCK_FORM_KEYS)).toEqual(new Set(["task",@@ -115,9 +115,10 @@ describe("BLOCK_FORMS dispatcher", () => {"googleSheetsWrite","pdfFill","splitPdf",+ "emailInbox",]),);- expect(BLOCK_FORM_KEYS).toHaveLength(28);+ expect(BLOCK_FORM_KEYS).toHaveLength(29);});test("conditional routes to a sidebar form that shows branch prompts", () => {diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm.tsxindex 3a6a49795..04d49a462 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm.tsx@@ -8,6 +8,7 @@ import { ActionBlockForm } from "./BlockConfigForm/ActionBlockForm";import { CodeBlockBlockForm } from "./BlockConfigForm/CodeBlockBlockForm";import { ConditionalBlockForm } from "./BlockConfigForm/ConditionalBlockForm";import { DownloadBlockForm } from "./BlockConfigForm/DownloadBlockForm";+import { EmailInboxBlockForm } from "./BlockConfigForm/EmailInboxBlockForm";import { ExtractionBlockForm } from "./BlockConfigForm/ExtractionBlockForm";import { FileDownloadBlockForm } from "./BlockConfigForm/FileDownloadBlockForm";import { FileParserBlockForm } from "./BlockConfigForm/FileParserBlockForm";@@ -50,6 +51,7 @@ const BLOCK_FORMS: Record<WorkflowBlockNodeType, BlockFormComponent> = {conditional: ConditionalBlockForm,textPrompt: TextPromptBlockForm,sendEmail: SendEmailBlockForm,+ emailInbox: EmailInboxBlockForm,codeBlock: CodeBlockBlockForm,fileParser: FileParserBlockForm,fileDownload: FileDownloadBlockForm,diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/EmailInboxBlockForm.test.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/EmailInboxBlockForm.test.tsxnew file mode 100644index 000000000..c1c70a23d--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/EmailInboxBlockForm.test.tsx@@ -0,0 +1,129 @@+// @vitest-environment jsdom++import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import type { ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";++const mockNodes = new Map<+ string,+ { id: string; type: string; data?: Record<string, unknown> } | undefined+>();+const updateNodeData = vi.fn();++vi.mock("@xyflow/react", async () => {+ const actual =+ await vi.importActual<typeof import("@xyflow/react")>("@xyflow/react");+ return {+ ...actual,+ useReactFlow: () => ({+ getNode: (id: string) => mockNodes.get(id),+ updateNodeData,+ }),+ useNodesData: (id: string) => {+ const node = mockNodes.get(id);+ return node ? { id: node.id, type: node.type, data: node.data } : null;+ },+ useNodes: () => [],+ useEdges: () => [],+ };+});++vi.mock("../../nodes", () => ({+ isWorkflowBlockNode: () => true,+}));++vi.mock("../../workflowEditorUtils", () => ({+ getAvailableOutputParameterKeys: () => [],+}));++vi.mock("@/components/WorkflowBlockInputTextarea", () => ({+ WorkflowBlockInputTextarea: () => <textarea />,+}));++vi.mock("@/routes/workflows/components/GoogleOAuthCredentialSelector", () => ({+ GoogleOAuthCredentialSelector: () => <div />,+}));++vi.mock(+ "@/routes/workflows/components/MicrosoftOAuthCredentialSelector",+ () => ({+ MicrosoftOAuthCredentialSelector: () => <div />,+ MICROSOFT_MAIL_REQUIRED_SCOPES: [],+ }),+);++vi.mock("@/components/ui/accordion", () => {+ const Pass = ({ children }: { children?: ReactNode }) => <>{children}</>;+ return {+ Accordion: Pass,+ AccordionContent: Pass,+ AccordionItem: Pass,+ AccordionTrigger: Pass,+ };+});++vi.mock("../../nodes/TaskNode/ParametersMultiSelect", () => ({+ ParametersMultiSelect: ({+ parameters,+ onParametersChange,+ }: {+ parameters: Array<string>;+ onParametersChange: (next: Array<string>) => void;+ }) => (+ <select+ data-testid="parameters-multi-select"+ multiple+ value={parameters}+ onChange={(event) =>+ onParametersChange(+ Array.from(event.target.selectedOptions, (option) => option.value),+ )+ }+ >+ <option value="microsoft_credential_id">microsoft_credential_id</option>+ </select>+ ),+}));++import { usePendingCommitsStore } from "@/store/PendingCommitsStore";++import { emailInboxNodeDefaultData } from "../../nodes/EmailInboxNode/types";+import { EmailInboxBlockForm } from "./EmailInboxBlockForm";++beforeEach(() => {+ mockNodes.clear();+ updateNodeData.mockReset();+ usePendingCommitsStore.setState({ commits: {} });+ mockNodes.set("email-1", {+ id: "email-1",+ type: "emailInbox",+ data: {+ ...emailInboxNodeDefaultData,+ emailClient: "outlook",+ credentialId: "{{ microsoft_credential_id }}",+ },+ });+});++afterEach(() => {+ cleanup();+});++describe("EmailInboxBlockForm", () => {+ test("updates parameter keys used by a templated credential", () => {+ render(<EmailInboxBlockForm blockId="email-1" />);++ const select = screen.getByTestId(+ "parameters-multi-select",+ ) as HTMLSelectElement;+ const option = select.querySelector(+ 'option[value="microsoft_credential_id"]',+ ) as HTMLOptionElement;+ option.selected = true;+ fireEvent.change(select);++ expect(updateNodeData).toHaveBeenCalledWith("email-1", {+ parameterKeys: ["microsoft_credential_id"],+ });+ });+});diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/EmailInboxBlockForm.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/EmailInboxBlockForm.tsxnew file mode 100644index 000000000..97e704c49--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/EmailInboxBlockForm.tsx@@ -0,0 +1,71 @@+import { useReactFlow } from "@xyflow/react";+import { useEffect, useMemo } from "react";++import { usePendingCommitsStore } from "@/store/PendingCommitsStore";++import { type AppNode, isWorkflowBlockNode } from "../../nodes";+import { EmailInboxEditor } from "../../nodes/EmailInboxNode/EmailInboxEditor";+import { type EmailInboxNode } from "../../nodes/EmailInboxNode/types";+import { useDebouncedSidebarSave } from "../useDebouncedSidebarSave";++function EmailInboxBlockForm({ blockId }: { blockId: string }) {+ const rf = useReactFlow<AppNode>();+ const node = rf.getNode(blockId);+ if (!node || !isWorkflowBlockNode(node) || node.type !== "emailInbox") {+ return null;+ }+ return (+ <EmailInboxBlockFormBody blockId={blockId} node={node as EmailInboxNode} />+ );+}++function EmailInboxBlockFormBody({+ blockId,+ node,+}: {+ blockId: string;+ node: EmailInboxNode;+}) {+ const data = node.data;++ const value = useMemo(+ () => ({+ emailClient: data.emailClient,+ credentialId: data.credentialId,+ folder: data.folder,+ prompt: data.prompt,+ sender: data.sender,+ subject: data.subject,+ newerThanDays: data.newerThanDays,+ maxResults: data.maxResults,+ includeBody: data.includeBody,+ parameterKeys: data.parameterKeys,+ }),+ [+ data.emailClient,+ data.credentialId,+ data.folder,+ data.prompt,+ data.sender,+ data.subject,+ data.newerThanDays,+ data.maxResults,+ data.includeBody,+ data.parameterKeys,+ ],+ );+ const { commit } = useDebouncedSidebarSave<typeof value>({+ blockId,+ value,+ });++ useEffect(() => {+ const store = usePendingCommitsStore.getState();+ store.register(blockId, commit);+ return () => store.unregister(blockId);+ }, [blockId, commit]);++ return <EmailInboxEditor blockId={blockId} />;+}++export { EmailInboxBlockForm };diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigSidebar.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigSidebar.tsxindex 4d088e63d..7f90d47bf 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigSidebar.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigSidebar.tsx@@ -48,6 +48,7 @@ const NODE_TYPE_TO_BLOCK_TYPE: Record<task: "task",textPrompt: "text_prompt",sendEmail: "send_email",+ emailInbox: "email_inbox",codeBlock: "code",fileParser: "file_url_parser",upload: "upload_to_s3",diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsxindex 17057fa09..8339b58f4 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsx@@ -64,6 +64,7 @@ const BLOCK_TYPE_TO_NODE_TYPE: Record<string, string> = {http_request: "http_request",pdf_fill: "pdfFill",split_pdf: "splitPdf",+ email_inbox: "emailInbox",google_sheets_read: "googleSheetsRead",google_sheets_write: "googleSheetsWrite",};diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowNodeLibraryPanel.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowNodeLibraryPanel.tsxindex 1d815cb62..8f189b20b 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowNodeLibraryPanel.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowNodeLibraryPanel.tsx@@ -292,6 +292,17 @@ const nodeLibraryItems: Array<{title: "Agent Trigger Block",description: "Trigger another agent",},+ {+ nodeType: "emailInbox",+ icon: (+ <WorkflowBlockIcon+ workflowBlockType={WorkflowBlockTypes.EmailInbox}+ className="size-6"+ />+ ),+ title: "Email Inbox",+ description: "Search Gmail or Outlook inboxes",+ },{nodeType: "googleSheetsRead",icon: (diff --git a/skyvern-frontend/src/routes/workflows/editor/sortable/roundTrip.test.ts b/skyvern-frontend/src/routes/workflows/editor/sortable/roundTrip.test.tsindex 797547833..63e6a822f 100644--- a/skyvern-frontend/src/routes/workflows/editor/sortable/roundTrip.test.ts+++ b/skyvern-frontend/src/routes/workflows/editor/sortable/roundTrip.test.ts@@ -11,8 +11,10 @@ import {} from "../workflowEditorUtils";import {type CodeBlock,+ type EmailInboxBlock,type OutputParameter,type WorkflowBlock,+ type WorkflowParameter,type WorkflowSettings,} from "../../types/workflowTypes";import type { CodeBlockYAML } from "../../types/workflowYamlTypes";@@ -76,6 +78,21 @@ function makeOutputParameter(label: string): OutputParameter {};}+function makeWorkflowParameter(key: string): WorkflowParameter {+ return {+ parameter_type: "workflow",+ key,+ description: null,+ workflow_id: "wf-fixture",+ workflow_parameter_id: `wp-${key}`,+ workflow_parameter_type: "string",+ default_value: "",+ created_at: "2026-04-20T00:00:00Z",+ modified_at: "2026-04-20T00:00:00Z",+ deleted_at: null,+ };+}+function makeCodeBlock(label: string,nextBlockLabel: string | null,@@ -92,6 +109,30 @@ function makeCodeBlock(};}+function makeEmailInboxBlock(+ label: string,+ parameters: Array<WorkflowParameter>,+): EmailInboxBlock {+ return {+ label,+ block_type: "email_inbox",+ continue_on_failure: false,+ model: null,+ next_block_label: null,+ output_parameter: makeOutputParameter(label),+ email_client: "outlook",+ credential_id: "{{ microsoft_credential_id }}",+ folder: "Inbox",+ prompt: "",+ sender: null,+ subject: null,+ newer_than_days: null,+ max_results: 25,+ include_body: true,+ parameters,+ };+}+/** Flat 5-block fixture: B1 → B2 → B3 → B4 → B5. */function buildFiveBlockFixture(): Array<WorkflowBlock> {return [@@ -220,6 +261,29 @@ function reloadFromSavedYaml(}describe("round-trip reorder → save → reload (M1 top-level)", () => {+ test("email inbox preserves parameter keys across load and save", () => {+ const credentialParameter = makeWorkflowParameter(+ "microsoft_credential_id",+ );+ const initialBlocks: Array<WorkflowBlock> = [+ makeEmailInboxBlock("Read Inbox", [credentialParameter]),+ ];++ const { nodes, edges } = getElements(initialBlocks, DEFAULT_SETTINGS, true);++ const emailNode = nodes.find((node) => node.type === "emailInbox");+ expect(emailNode?.data).toMatchObject({+ parameterKeys: ["microsoft_credential_id"],+ });++ const saved = getWorkflowBlocks(nodes, edges);+ expect(saved).toHaveLength(1);+ expect(saved[0]).toMatchObject({+ block_type: "email_inbox",+ parameter_keys: ["microsoft_credential_id"],+ });+ });+test("drag B3 above B1 persists as B3 → B1 → B2 → B4 → B5 chain", () => {// 1. Load the workflow: YAML-like blocks → nodes + edges via getElements.const initialBlocks = buildFiveBlockFixture();diff --git a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.tsindex 2461acb72..17c91da72 100644--- a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts+++ b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts@@ -53,6 +53,7 @@ import {HttpRequestBlockYAML,PrintPageBlockYAML,WorkflowTriggerBlockYAML,+ EmailInboxBlockYAML,GoogleSheetsReadBlockYAML,GoogleSheetsWriteBlockYAML,PdfFillBlockYAML,@@ -150,6 +151,11 @@ import {isWorkflowTriggerNode,workflowTriggerNodeDefaultData,} from "./nodes/WorkflowTriggerNode/types";+import {+ emailInboxNodeDefaultData,+ isEmailInboxNode,+} from "./nodes/EmailInboxNode/types";+import { validateEmailInboxNode } from "./nodes/EmailInboxNode/validate";import {googleSheetsReadNodeDefaultData,isGoogleSheetsReadNode,@@ -1191,6 +1197,26 @@ function convertToNode(},};}+ case "email_inbox": {+ return {+ ...identifiers,+ ...common,+ type: "emailInbox",+ data: {+ ...commonData,+ emailClient: block.email_client ?? "gmail",+ credentialId: block.credential_id ?? "",+ folder: block.folder ?? "INBOX",+ prompt: block.prompt ?? "",+ sender: block.sender ?? "",+ subject: block.subject ?? "",+ newerThanDays: block.newer_than_days ?? null,+ maxResults: block.max_results ?? 25,+ includeBody: block.include_body ?? true,+ parameterKeys: block.parameters.map((p) => p.key),+ },+ };+ }case "google_sheets_read": {return {...identifiers,@@ -2615,6 +2641,17 @@ function createNode(},};}+ case "emailInbox": {+ return {+ ...identifiers,+ ...common,+ type: "emailInbox",+ data: {+ ...emailInboxNodeDefaultData,+ label,+ },+ };+ }case "googleSheetsRead": {return {...identifiers,@@ -3226,6 +3263,22 @@ function getWorkflowBlock(parameter_keys: node.data.parameterKeys,};}+ case "emailInbox": {+ return {+ ...base,+ block_type: "email_inbox",+ email_client: node.data.emailClient,+ credential_id: node.data.credentialId || null,+ folder: node.data.folder,+ prompt: node.data.prompt,+ sender: node.data.sender || null,+ subject: node.data.subject || null,+ newer_than_days: node.data.newerThanDays,+ max_results: node.data.maxResults,+ include_body: node.data.includeBody,+ parameter_keys: node.data.parameterKeys,+ };+ }case "googleSheetsRead": {return {...base,@@ -4585,6 +4638,23 @@ function convertBlocksToBlockYAML(};return blockYaml;}+ case "email_inbox": {+ const blockYaml: EmailInboxBlockYAML = {+ ...base,+ block_type: "email_inbox",+ email_client: block.email_client,+ credential_id: block.credential_id,+ folder: block.folder,+ prompt: block.prompt,+ sender: block.sender,+ subject: block.subject,+ newer_than_days: block.newer_than_days,+ max_results: block.max_results,+ include_body: block.include_body,+ parameter_keys: block.parameters.map((p) => p.key),+ };+ return blockYaml;+ }case "google_sheets_read": {const blockYaml: GoogleSheetsReadBlockYAML = {...base,@@ -4917,6 +4987,10 @@ function getWorkflowErrors(nodes: Array<AppNode>): Array<string> {.filter(isGoogleSheetsReadNode).forEach((node) => errors.push(...validateGoogleSheetsReadNode(node)));+ nodes+ .filter(isEmailInboxNode)+ .forEach((node) => errors.push(...validateEmailInboxNode(node)));+nodes.filter(isGoogleSheetsWriteNode).forEach((node) => errors.push(...validateGoogleSheetsWriteNode(node)));diff --git a/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts b/skyvern-frontend/src/routes/workflows/types/workflowTypes.tsindex feb251607..5ff4f51d4 100644--- a/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts+++ b/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts@@ -219,6 +219,7 @@ export type WorkflowBlock =| HttpRequestBlock| PrintPageBlock| WorkflowTriggerBlock+ | EmailInboxBlock| GoogleSheetsReadBlock| GoogleSheetsWriteBlock| PdfFillBlock@@ -250,6 +251,7 @@ export const WorkflowBlockTypes = {HttpRequest: "http_request",PrintPage: "print_page",WorkflowTrigger: "workflow_trigger",+ EmailInbox: "email_inbox",GoogleSheetsRead: "google_sheets_read",GoogleSheetsWrite: "google_sheets_write",PDFFill: "pdf_fill",@@ -621,6 +623,20 @@ export type WorkflowTriggerBlock = WorkflowBlockBase & {parameters: Array<WorkflowParameter>;};+export type EmailInboxBlock = WorkflowBlockBase & {+ block_type: "email_inbox";+ email_client: "gmail" | "outlook";+ credential_id: string | null;+ folder: string;+ prompt: string;+ sender: string | null;+ subject: string | null;+ newer_than_days: number | null;+ max_results: number;+ include_body: boolean;+ parameters: Array<WorkflowParameter>;+};+export type GoogleSheetsReadBlock = WorkflowBlockBase & {block_type: "google_sheets_read";spreadsheet_url: string;diff --git a/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts b/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.tsindex 9aa1a66a2..3cd61eab3 100644--- a/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts+++ b/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts@@ -161,6 +161,7 @@ export type BlockYAML =| HttpRequestBlockYAML| PrintPageBlockYAML| WorkflowTriggerBlockYAML+ | EmailInboxBlockYAML| GoogleSheetsReadBlockYAML| GoogleSheetsWriteBlockYAML| PdfFillBlockYAML@@ -470,6 +471,20 @@ export type WorkflowTriggerBlockYAML = BlockYAMLBase & {parameter_keys?: Array<string> | null;};+export type EmailInboxBlockYAML = BlockYAMLBase & {+ block_type: "email_inbox";+ email_client: "gmail" | "outlook";+ credential_id: string | null;+ folder: string;+ prompt: string;+ sender: string | null;+ subject: string | null;+ newer_than_days: number | null;+ max_results: number;+ include_body: boolean;+ parameter_keys?: Array<string> | null;+};+export type GoogleSheetsReadBlockYAML = BlockYAMLBase & {block_type: "google_sheets_read";spreadsheet_url: string;diff --git a/skyvern-frontend/src/util/microsoftScopes.ts b/skyvern-frontend/src/util/microsoftScopes.tsnew file mode 100644index 000000000..dd0d04f23--- /dev/null+++ b/skyvern-frontend/src/util/microsoftScopes.ts@@ -0,0 +1 @@+export const MICROSOFT_MAIL_REQUIRED_SCOPES = ["Mail.Read"] as const;diff --git a/skyvern/cli/mcp_tools/blocks.py b/skyvern/cli/mcp_tools/blocks.pyindex 80f86b0e8..c8e2e593f 100644--- a/skyvern/cli/mcp_tools/blocks.py+++ b/skyvern/cli/mcp_tools/blocks.py@@ -23,6 +23,7 @@ from skyvern.schemas.workflows import (CodeBlockYAML,ConditionalBlockYAML,DownloadToS3BlockYAML,+ EmailInboxBlockYAML,ExtractionBlockYAML,FileDownloadBlockYAML,FileParserBlockYAML,@@ -87,6 +88,7 @@ BLOCK_TYPE_MAP: dict[str, type[BlockYAML]] = {BlockType.SPLIT_PDF.value: SplitPdfBlockYAML,BlockType.WORKFLOW_TRIGGER.value: WorkflowTriggerBlockYAML,BlockType.GOOGLE_SHEETS_READ.value: GoogleSheetsReadBlockYAML,+ BlockType.EMAIL_INBOX.value: EmailInboxBlockYAML,BlockType.GOOGLE_SHEETS_WRITE.value: GoogleSheetsWriteBlockYAML,}@@ -121,6 +123,7 @@ BLOCK_SUMMARIES: dict[str, str] = {"split_pdf": "Split one PDF into multiple PDFs by prompt and save each to S3","workflow_trigger": "Trigger another workflow by permanent ID, with optional payload and wait-for-completion","google_sheets_read": "Read rows from a Google Sheet as structured data (list of dicts)",+ "email_inbox": "Read matching messages from a Gmail or Outlook inbox","google_sheets_write": "Write rows to a Google Sheet (append new rows or update existing cells)",}@@ -277,6 +280,14 @@ BLOCK_EXAMPLES: dict[str, dict[str, Any]] = {"credential_id": "{{ google_credential_id }}","has_header_row": True,},+ "email_inbox": {+ "block_type": "email_inbox",+ "label": "find_invoice_email",+ "email_client": "gmail",+ "credential_id": "{{ gmail_credential_id }}",+ "folder": "INBOX",+ "prompt": "Find invoice approval emails that need a reply.",+ },"google_sheets_write": {"block_type": "google_sheets_write","label": "write_sheet_data",diff --git a/skyvern/config.py b/skyvern/config.pyindex e05234200..937f2aab5 100644--- a/skyvern/config.py+++ b/skyvern/config.py@@ -728,6 +728,12 @@ class Settings(BaseSettings):# through Settings. Skyvern Cloud keeps the centrally managed OAuth client.ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG: bool = True+ MICROSOFT_OAUTH_CLIENT_ID: str | None = None+ MICROSOFT_OAUTH_CLIENT_SECRET: str | None = None+ MICROSOFT_OAUTH_TENANT: str = "common"+ MICROSOFT_OAUTH_REDIRECT_HOSTS: list[str] = Field(default_factory=list)+ MICROSOFT_OAUTH_APP_ORIGINS: list[str] = Field(default_factory=list)+# Google Sheets API runtime tuningGOOGLE_SHEETS_API_TIMEOUT_SECONDS: float = 30.0GOOGLE_SHEETS_API_MAX_RETRIES: int = 3diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.pyindex 094a8c023..caad33284 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -44,6 +44,7 @@ from skyvern.forge.sdk.services import (google_gmail_service,google_oauth_service,google_sheets_service,+ microsoft_oauth_service,sftp_service,)from skyvern.forge.sdk.services.credentials import AuthenticatorTotpParseResult@@ -1221,6 +1222,38 @@ class AgentFunction:)return None+ async def get_microsoft_credentials(+ self,+ organization_id: str,+ credential_id: str,+ required_scopes: list[str] | None = None,+ ) -> str | None:+ try:+ secrets = await microsoft_oauth_service.load_credential_secrets(+ organization_id=organization_id,+ credential_id=credential_id,+ )+ if required_scopes and not microsoft_oauth_service.has_required_scopes(secrets.scopes, required_scopes):+ LOG.info(+ "Microsoft OAuth credential missing required scopes",+ organization_id=organization_id,+ credential_id=credential_id,+ required_scopes=required_scopes,+ )+ return None+ return await microsoft_oauth_service.refresh_and_rotate(+ organization_id=organization_id,+ credential_id=credential_id,+ credential_secrets=secrets,+ )+ except Exception:+ LOG.exception(+ "Failed to get Microsoft credentials",+ organization_id=organization_id,+ credential_id=credential_id,+ )+ return None+async def get_google_workspace_credentials(self,organization_id: str,diff --git a/skyvern/forge/api_app.py b/skyvern/forge/api_app.pyindex 81e196113..51f65b055 100644--- a/skyvern/forge/api_app.py+++ b/skyvern/forge/api_app.py@@ -42,6 +42,7 @@ from skyvern.forge.sdk.db.models import Basefrom skyvern.forge.sdk.routes import internal_authfrom skyvern.forge.sdk.routes.google_oauth import google_oauth_routerfrom skyvern.forge.sdk.routes.google_sheets import google_sheets_router+from skyvern.forge.sdk.routes.microsoft_oauth import microsoft_oauth_routerfrom skyvern.forge.sdk.routes.routers import base_router, legacy_base_router, legacy_v2_routerfrom skyvern.forge.sdk.services.local_org_auth_token_service import (ensure_local_api_key,@@ -399,6 +400,8 @@ def create_api_app() -> FastAPI:# the frontend, not by SDK users.fastapi_app.include_router(google_oauth_router, prefix="/v1/google", include_in_schema=False)fastapi_app.include_router(google_oauth_router, prefix="/api/v1/google", include_in_schema=False)+ fastapi_app.include_router(microsoft_oauth_router, prefix="/v1/microsoft", include_in_schema=False)+ fastapi_app.include_router(microsoft_oauth_router, prefix="/api/v1/microsoft", include_in_schema=False)fastapi_app.include_router(google_sheets_router, prefix="/v1/google/sheets", include_in_schema=False)fastapi_app.include_router(google_sheets_router, prefix="/api/v1/google/sheets", include_in_schema=False)diff --git a/skyvern/forge/prompts/skyvern/match-email.j2 b/skyvern/forge/prompts/skyvern/match-email.j2new file mode 100644index 000000000..97cffaad1--- /dev/null+++ b/skyvern/forge/prompts/skyvern/match-email.j2@@ -0,0 +1,26 @@+You are evaluating whether an email matches a user's criteria.++Return strict JSON only. Do not include text before or after the JSON.++Reply in this JSON format:+{+ "reasoning": str,+ "matches": bool+}++User criteria:+```+{{ criteria }}+```++Email:+Subject: {{ subject | untrusted }}+Sender: {{ sender | untrusted }}+Snippet:+```+{{ snippet | untrusted }}+```+Body:+```+{{ body | untrusted }}+```diff --git a/skyvern/forge/sdk/db/agent_db.py b/skyvern/forge/sdk/db/agent_db.pyindex 0b32b8c8d..2d512645d 100644--- a/skyvern/forge/sdk/db/agent_db.py+++ b/skyvern/forge/sdk/db/agent_db.py@@ -25,6 +25,7 @@ from skyvern.forge.sdk.db.repositories.credentials import CredentialRepositoryfrom skyvern.forge.sdk.db.repositories.debug import DebugRepositoryfrom skyvern.forge.sdk.db.repositories.folders import FoldersRepositoryfrom skyvern.forge.sdk.db.repositories.google_oauth import GoogleOAuthRepository+from skyvern.forge.sdk.db.repositories.microsoft_oauth import MicrosoftOAuthRepositoryfrom skyvern.forge.sdk.db.repositories.observer import ObserverRepositoryfrom skyvern.forge.sdk.db.repositories.organizations import OrganizationsRepositoryfrom skyvern.forge.sdk.db.repositories.otp import OTPRepository@@ -385,6 +386,7 @@ class AgentDB(BaseAlchemyDB):self.tags = TagsRepository(self.Session, debug_enabled, self.is_retryable_error)self.browser_sessions = BrowserSessionsRepository(self.Session, debug_enabled, self.is_retryable_error)self.google_oauth = GoogleOAuthRepository(self.Session, debug_enabled, self.is_retryable_error)+ self.microsoft_oauth = MicrosoftOAuthRepository(self.Session, debug_enabled, self.is_retryable_error)self.schedules = SchedulesRepository(self.Session,debug_enabled,diff --git a/skyvern/forge/sdk/db/id.py b/skyvern/forge/sdk/db/id.pyindex 6f795aebd..25127029f 100644--- a/skyvern/forge/sdk/db/id.py+++ b/skyvern/forge/sdk/db/id.py@@ -46,6 +46,7 @@ DEBUG_SESSION_PREFIX = "ds"FOLDER_PREFIX = "fld"BROWSER_PROFILE_PREFIX = "bp"GOOGLE_OAUTH_CREDENTIAL_PREFIX = "goac"+MICROSOFT_OAUTH_CREDENTIAL_PREFIX = "moac"ORGANIZATION_BITWARDEN_COLLECTION_PREFIX = "obc"TASK_V2_ID = "tsk_v2"THOUGHT_ID = "ot"@@ -286,6 +287,11 @@ def generate_google_oauth_credential_id() -> str:return f"{GOOGLE_OAUTH_CREDENTIAL_PREFIX}_{int_id}"+def generate_microsoft_oauth_credential_id() -> str:+ int_id = generate_id()+ return f"{MICROSOFT_OAUTH_CREDENTIAL_PREFIX}_{int_id}"++def generate_organization_bitwarden_collection_id() -> str:int_id = generate_id()return f"{ORGANIZATION_BITWARDEN_COLLECTION_PREFIX}_{int_id}"diff --git a/skyvern/forge/sdk/db/models.py b/skyvern/forge/sdk/db/models.pyindex 7c5fd4721..45f62107d 100644--- a/skyvern/forge/sdk/db/models.py+++ b/skyvern/forge/sdk/db/models.py@@ -42,6 +42,7 @@ from skyvern.forge.sdk.db.id import (generate_google_oauth_credential_id,generate_heal_episode_id,generate_heal_proposal_id,+ generate_microsoft_oauth_credential_id,generate_onepassword_credential_parameter_id,generate_org_id,generate_organization_auth_token_id,@@ -1875,3 +1876,40 @@ class GoogleOAuthCredentialModel(Base):onupdate=datetime.datetime.utcnow,nullable=False,)+++class MicrosoftOAuthCredentialModel(Base):+ __tablename__ = "microsoft_oauth_credentials"+ __table_args__ = (+ Index(+ "ux_microsoft_oauth_credentials_consent_nonce",+ "consent_nonce",+ unique=True,+ postgresql_where=text("consent_nonce IS NOT NULL"),+ ),+ CheckConstraint(+ "state IN ('pending_consent', 'active', 'revoked', 'error')",+ name="ck_microsoft_oauth_credentials_state",+ ),+ )++ id = Column(String, primary_key=True, default=generate_microsoft_oauth_credential_id)+ organization_id = Column(String, ForeignKey("organizations.organization_id"), index=True, nullable=False)+ credential_name = Column(String, nullable=False, default="Default")+ state = Column(String, nullable=False, default="pending_consent", index=True)+ scopes_requested = Column(JSON, nullable=False, default=list)+ scopes_granted = Column(JSON, nullable=False, default=list)+ encrypted_refresh_token = Column(String, nullable=True)+ encrypted_method = Column(String, nullable=True)+ consent_nonce = Column(String, nullable=True)+ consent_redirect_uri = Column(String, nullable=True)+ consent_code_verifier = Column(String, nullable=True)+ consent_app_origin = Column(String, nullable=True)+ consent_expires_at = Column(DateTime, nullable=True)+ created_at = Column(DateTime, default=datetime.datetime.utcnow, nullable=False)+ modified_at = Column(+ DateTime,+ default=datetime.datetime.utcnow,+ onupdate=datetime.datetime.utcnow,+ nullable=False,+ )diff --git a/skyvern/forge/sdk/db/repositories/microsoft_oauth.py b/skyvern/forge/sdk/db/repositories/microsoft_oauth.pynew file mode 100644index 000000000..2f428defb--- /dev/null+++ b/skyvern/forge/sdk/db/repositories/microsoft_oauth.py@@ -0,0 +1,327 @@+from __future__ import annotations++import datetime+from dataclasses import dataclass++import structlog+from sqlalchemy import select, update++from skyvern.forge.sdk.db._error_handling import db_operation+from skyvern.forge.sdk.db.base_repository import BaseRepository+from skyvern.forge.sdk.db.models import MicrosoftOAuthCredentialModel+from skyvern.forge.sdk.encrypt.base import EncryptMethod+from skyvern.forge.sdk.schemas.microsoft_oauth import MicrosoftOAuthCredentialBase++LOG = structlog.get_logger()++STATE_PENDING_CONSENT = "pending_consent"+STATE_ACTIVE = "active"+STATE_REVOKED = "revoked"+STATE_ERROR = "error"+++class InvalidConsentNonceError(ValueError):+ pass+++@dataclass(frozen=True)+class PendingConsentContext:+ credential_id: str+ consent_redirect_uri: str | None+ consent_code_verifier: str | None+ consent_app_origin: str | None = None+ scopes_requested: list[str] | None = None+++@dataclass(frozen=True)+class ActiveCredentialCiphertext:+ encrypted_refresh_token: str+ encrypted_method: EncryptMethod+ scopes_granted: list[str]+++@dataclass(frozen=True)+class RevocableCiphertext:+ exists: bool+ encrypted_refresh_token: str | None = None+ encrypted_method: EncryptMethod | None = None+++class MicrosoftOAuthRepository(BaseRepository):+ @db_operation("insert_pending_credential")+ async def insert_pending_credential(+ self,+ credential_id: str,+ organization_id: str,+ credential_name: str,+ scopes_requested: list[str],+ consent_nonce: str,+ consent_redirect_uri: str,+ consent_expires_at: datetime.datetime,+ consent_code_verifier: str,+ consent_app_origin: str | None = None,+ ) -> MicrosoftOAuthCredentialBase:+ async with self.Session() as session:+ model = MicrosoftOAuthCredentialModel(+ id=credential_id,+ organization_id=organization_id,+ credential_name=credential_name,+ state=STATE_PENDING_CONSENT,+ scopes_requested=scopes_requested,+ scopes_granted=[],+ consent_nonce=consent_nonce,+ consent_redirect_uri=consent_redirect_uri,+ consent_expires_at=consent_expires_at,+ consent_app_origin=consent_app_origin,+ consent_code_verifier=consent_code_verifier,+ )+ session.add(model)+ await session.flush()+ result = MicrosoftOAuthCredentialBase.model_validate(model, from_attributes=True)+ await session.commit()+ return result++ @db_operation("load_pending_by_nonce")+ async def load_pending_by_nonce(+ self,+ organization_id: str,+ nonce: str,+ now: datetime.datetime | None = None,+ ) -> PendingConsentContext | None:+ cutoff = now if now is not None else datetime.datetime.now(datetime.UTC).replace(tzinfo=None)+ async with self.Session() as session:+ stmt = select(+ MicrosoftOAuthCredentialModel.id,+ MicrosoftOAuthCredentialModel.consent_redirect_uri,+ MicrosoftOAuthCredentialModel.consent_code_verifier,+ MicrosoftOAuthCredentialModel.consent_app_origin,+ MicrosoftOAuthCredentialModel.scopes_requested,+ ).where(+ MicrosoftOAuthCredentialModel.consent_nonce == nonce,+ MicrosoftOAuthCredentialModel.organization_id == organization_id,+ MicrosoftOAuthCredentialModel.state == STATE_PENDING_CONSENT,+ MicrosoftOAuthCredentialModel.consent_expires_at >= cutoff,+ )+ row = (await session.execute(stmt)).one_or_none()+ if row is None:+ return None+ return PendingConsentContext(+ credential_id=row[0],+ consent_redirect_uri=row[1],+ consent_code_verifier=row[2],+ consent_app_origin=row[3],+ scopes_requested=list(row[4] or []),+ )++ @db_operation("promote_pending_to_active")+ async def promote_pending_to_active(+ self,+ organization_id: str,+ nonce: str,+ encrypted_refresh_token: str,+ encrypted_method: EncryptMethod,+ scopes_granted: list[str],+ now: datetime.datetime,+ ) -> MicrosoftOAuthCredentialBase:+ async with self.Session() as session:+ stmt = (+ update(MicrosoftOAuthCredentialModel)+ .where(+ MicrosoftOAuthCredentialModel.consent_nonce == nonce,+ MicrosoftOAuthCredentialModel.organization_id == organization_id,+ MicrosoftOAuthCredentialModel.state == STATE_PENDING_CONSENT,+ MicrosoftOAuthCredentialModel.consent_expires_at >= now,+ )+ .values(+ state=STATE_ACTIVE,+ encrypted_refresh_token=encrypted_refresh_token,+ encrypted_method=encrypted_method.value,+ scopes_granted=scopes_granted,+ consent_nonce=None,+ consent_redirect_uri=None,+ consent_expires_at=None,+ consent_code_verifier=None,+ consent_app_origin=None,+ modified_at=now,+ )+ .returning(MicrosoftOAuthCredentialModel)+ )+ promoted = (await session.execute(stmt)).scalar_one_or_none()+ if promoted is None:+ fallback = (+ await session.execute(+ select(MicrosoftOAuthCredentialModel).where(+ MicrosoftOAuthCredentialModel.consent_nonce == nonce,+ MicrosoftOAuthCredentialModel.organization_id == organization_id,+ )+ )+ ).scalar_one_or_none()+ if fallback is None:+ raise InvalidConsentNonceError("Unknown OAuth consent nonce")+ if fallback.state == STATE_ERROR:+ raise InvalidConsentNonceError("OAuth consent row is in error state")+ if fallback.state != STATE_PENDING_CONSENT:+ raise InvalidConsentNonceError("OAuth consent nonce already consumed")+ raise InvalidConsentNonceError("OAuth consent nonce expired")+ result = MicrosoftOAuthCredentialBase.model_validate(promoted, from_attributes=True)+ await session.commit()+ LOG.info(+ "Promoted pending Microsoft OAuth credential",+ credential_id=result.id,+ organization_id=organization_id,+ )+ return result++ @db_operation("list_active_for_org")+ async def list_active_for_org(self, organization_id: str) -> list[MicrosoftOAuthCredentialBase]:+ async with self.Session() as session:+ stmt = (+ select(MicrosoftOAuthCredentialModel)+ .where(+ MicrosoftOAuthCredentialModel.organization_id == organization_id,+ MicrosoftOAuthCredentialModel.state == STATE_ACTIVE,+ )+ .order_by(MicrosoftOAuthCredentialModel.created_at.desc())+ )+ rows = (await session.execute(stmt)).scalars().all()+ return [MicrosoftOAuthCredentialBase.model_validate(r, from_attributes=True) for r in rows]++ @db_operation("load_active_ciphertext")+ async def load_active_ciphertext(+ self,+ organization_id: str,+ credential_id: str,+ ) -> ActiveCredentialCiphertext | None:+ async with self.Session() as session:+ stmt = select(+ MicrosoftOAuthCredentialModel.encrypted_refresh_token,+ MicrosoftOAuthCredentialModel.encrypted_method,+ MicrosoftOAuthCredentialModel.scopes_granted,+ ).where(+ MicrosoftOAuthCredentialModel.id == credential_id,+ MicrosoftOAuthCredentialModel.organization_id == organization_id,+ MicrosoftOAuthCredentialModel.state == STATE_ACTIVE,+ )+ row = (await session.execute(stmt)).one_or_none()+ if row is None:+ return None+ ciphertext, method, scopes = row+ if not ciphertext or not method:+ return None+ return ActiveCredentialCiphertext(+ encrypted_refresh_token=ciphertext,+ encrypted_method=EncryptMethod(method),+ scopes_granted=list(scopes or []),+ )++ @db_operation("load_ciphertext_for_revoke")+ async def load_ciphertext_for_revoke(+ self,+ organization_id: str,+ credential_id: str,+ ) -> RevocableCiphertext:+ async with self.Session() as session:+ stmt = select(+ MicrosoftOAuthCredentialModel.encrypted_refresh_token,+ MicrosoftOAuthCredentialModel.encrypted_method,+ ).where(+ MicrosoftOAuthCredentialModel.id == credential_id,+ MicrosoftOAuthCredentialModel.organization_id == organization_id,+ MicrosoftOAuthCredentialModel.state != STATE_REVOKED,+ )+ row = (await session.execute(stmt)).one_or_none()+ if row is None:+ return RevocableCiphertext(exists=False)+ ciphertext, method = row+ if not ciphertext or not method:+ return RevocableCiphertext(exists=True)+ return RevocableCiphertext(+ exists=True,+ encrypted_refresh_token=ciphertext,+ encrypted_method=EncryptMethod(method),+ )++ @db_operation("rename_active")+ async def rename_active(+ self,+ organization_id: str,+ credential_id: str,+ credential_name: str,+ now: datetime.datetime,+ ) -> MicrosoftOAuthCredentialBase | None:+ async with self.Session() as session:+ stmt = (+ update(MicrosoftOAuthCredentialModel)+ .where(+ MicrosoftOAuthCredentialModel.id == credential_id,+ MicrosoftOAuthCredentialModel.organization_id == organization_id,+ MicrosoftOAuthCredentialModel.state == STATE_ACTIVE,+ )+ .values(credential_name=credential_name, modified_at=now)+ .returning(MicrosoftOAuthCredentialModel)+ )+ row = (await session.execute(stmt)).scalar_one_or_none()+ if row is None:+ return None+ result = MicrosoftOAuthCredentialBase.model_validate(row, from_attributes=True)+ await session.commit()+ return result++ @db_operation("update_active_refresh_token")+ async def update_active_refresh_token(+ self,+ *,+ organization_id: str,+ credential_id: str,+ encrypted_refresh_token: str,+ encrypted_method: EncryptMethod,+ now: datetime.datetime,+ ) -> None:+ async with self.Session() as session:+ stmt = (+ update(MicrosoftOAuthCredentialModel)+ .where(+ MicrosoftOAuthCredentialModel.id == credential_id,+ MicrosoftOAuthCredentialModel.organization_id == organization_id,+ MicrosoftOAuthCredentialModel.state == STATE_ACTIVE,+ )+ .values(+ encrypted_refresh_token=encrypted_refresh_token,+ encrypted_method=encrypted_method.value,+ modified_at=now,+ )+ )+ await session.execute(stmt)+ await session.commit()++ @db_operation("mark_revoked_and_scrub")+ async def mark_revoked_and_scrub(+ self,+ organization_id: str,+ credential_id: str,+ now: datetime.datetime,+ ) -> str | None:+ async with self.Session() as session:+ stmt = (+ update(MicrosoftOAuthCredentialModel)+ .where(+ MicrosoftOAuthCredentialModel.id == credential_id,+ MicrosoftOAuthCredentialModel.organization_id == organization_id,+ MicrosoftOAuthCredentialModel.state != STATE_REVOKED,+ )+ .values(+ state=STATE_REVOKED,+ encrypted_refresh_token=None,+ encrypted_method=None,+ consent_nonce=None,+ consent_redirect_uri=None,+ consent_expires_at=None,+ consent_code_verifier=None,+ consent_app_origin=None,+ modified_at=now,+ )+ .returning(MicrosoftOAuthCredentialModel.id)+ )+ revoked_id = (await session.execute(stmt)).scalar_one_or_none()+ await session.commit()+ return revoked_iddiff --git a/skyvern/forge/sdk/routes/microsoft_oauth.py b/skyvern/forge/sdk/routes/microsoft_oauth.pynew file mode 100644index 000000000..ab9cd58ed--- /dev/null+++ b/skyvern/forge/sdk/routes/microsoft_oauth.py@@ -0,0 +1,181 @@+from typing import Annotated++import structlog+from fastapi import APIRouter, Depends, HTTPException, status++from skyvern.forge.sdk.schemas.microsoft_oauth import (+ CreateMicrosoftOAuthAuthorizeRequest,+ CreateMicrosoftOAuthCallbackRequest,+ MicrosoftOAuthAuthorizeResponse,+ MicrosoftOAuthCredentialListResponse,+ MicrosoftOAuthCredentialResponse,+ UpdateMicrosoftOAuthCredentialRequest,+)+from skyvern.forge.sdk.schemas.organizations import Organization+from skyvern.forge.sdk.services import microsoft_oauth_service, org_auth_service+from skyvern.forge.sdk.services.microsoft_oauth_service import InvalidAppOriginError++LOG = structlog.get_logger()++microsoft_oauth_router = APIRouter()+++def _require_scopes_from_token(token_data: dict) -> list[str]:+ raw = token_data.get("scope")+ if raw is None:+ raise HTTPException(+ status_code=400,+ detail="Microsoft did not return any granted scopes. Please re-authorize and grant all requested scopes.",+ )+ if isinstance(raw, str):+ parts = [p for p in raw.replace(",", " ").split() if p]+ if not parts:+ raise HTTPException(+ status_code=400,+ detail="Microsoft returned an empty scope. Please re-authorize and grant all requested scopes.",+ )+ return parts+ parts = [p for p in (str(s).strip() for s in raw) if p]+ if not parts:+ raise HTTPException(+ status_code=400,+ detail="Microsoft returned no granted scopes. Please re-authorize and grant all requested scopes.",+ )+ return parts+++@microsoft_oauth_router.post("/oauth/authorize")+async def microsoft_oauth_authorize(+ request: CreateMicrosoftOAuthAuthorizeRequest,+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+) -> MicrosoftOAuthAuthorizeResponse:+ try:+ start = await microsoft_oauth_service.start_authorization(+ organization_id=current_org.organization_id,+ redirect_uri=request.redirect_uri,+ credential_name=request.credential_name,+ scope_profile=request.scope_profile,+ app_origin=request.app_origin,+ )+ except InvalidAppOriginError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ except microsoft_oauth_service.UnsupportedScopeProfileError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ except microsoft_oauth_service.InvalidRedirectURIError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ except microsoft_oauth_service.EncryptionNotConfiguredError as exc:+ raise HTTPException(status_code=503, detail=str(exc)) from exc+ except ValueError as exc:+ raise HTTPException(status_code=503, detail=str(exc)) from exc++ return MicrosoftOAuthAuthorizeResponse(authorize_url=start.authorize_url, state=start.state)+++@microsoft_oauth_router.post("/oauth/callback")+async def microsoft_oauth_callback(+ request: CreateMicrosoftOAuthCallbackRequest,+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+) -> MicrosoftOAuthCredentialResponse:+ context = await microsoft_oauth_service.load_pending_consent_context(+ organization_id=current_org.organization_id,+ nonce=request.state,+ )+ if context is None or not context.consent_redirect_uri:+ raise HTTPException(status_code=400, detail="Unknown or consumed OAuth consent nonce")+ if not context.consent_code_verifier:+ raise HTTPException(+ status_code=400,+ detail="OAuth consent row is missing the PKCE verifier; restart the consent flow",+ )++ try:+ token_data = await microsoft_oauth_service.exchange_code_for_tokens(+ code=request.code,+ redirect_uri=context.consent_redirect_uri,+ code_verifier=context.consent_code_verifier,+ scopes=context.scopes_requested,+ )+ except ValueError as exc:+ LOG.exception("Microsoft OAuth client credentials not configured")+ raise HTTPException(status_code=503, detail=str(exc)) from exc+ except microsoft_oauth_service.MicrosoftOAuthError as exc:+ LOG.warning("Microsoft OAuth exchange failed", error=str(exc))+ raise HTTPException(+ status_code=400,+ detail="Microsoft authorization failed. Please reconnect the Microsoft account.",+ ) from exc+ except microsoft_oauth_service.MissingAccessTokenError as exc:+ LOG.warning("Microsoft OAuth token response missing access token", error=str(exc))+ raise HTTPException(status_code=502, detail=str(exc)) from exc+ except Exception as exc:+ LOG.exception("Unexpected failure exchanging Microsoft OAuth code for tokens")+ raise HTTPException(status_code=500, detail="Failed to exchange authorization code") from exc++ refresh_token = token_data.get("refresh_token")+ if not refresh_token:+ raise HTTPException(+ status_code=400,+ detail="No refresh token received. Ensure offline_access is included in the OAuth flow.",+ )+ scopes_granted = _require_scopes_from_token(token_data)+ if not microsoft_oauth_service.has_required_scopes(scopes_granted, ["Mail.Read"]):+ raise HTTPException(+ status_code=400,+ detail="Microsoft did not grant Mail.Read. Please re-connect and accept all requested permissions.",+ )++ try:+ credential = await microsoft_oauth_service.promote_pending_credential(+ organization_id=current_org.organization_id,+ nonce=request.state,+ refresh_token=refresh_token,+ scopes_granted=scopes_granted,+ )+ except microsoft_oauth_service.InvalidConsentNonceError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ except microsoft_oauth_service.EncryptionNotConfiguredError as exc:+ raise HTTPException(status_code=503, detail=str(exc)) from exc++ return MicrosoftOAuthCredentialResponse(credential=credential, app_origin=context.consent_app_origin)+++@microsoft_oauth_router.get("/oauth/credentials")+async def list_microsoft_oauth_credentials(+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+) -> MicrosoftOAuthCredentialListResponse:+ credentials = await microsoft_oauth_service.get_credentials_for_org(+ organization_id=current_org.organization_id,+ )+ return MicrosoftOAuthCredentialListResponse(credentials=credentials)+++@microsoft_oauth_router.patch("/oauth/credentials/{credential_id}")+async def rename_microsoft_oauth_credential(+ credential_id: str,+ request: UpdateMicrosoftOAuthCredentialRequest,+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+) -> MicrosoftOAuthCredentialResponse:+ updated = await microsoft_oauth_service.rename_credential(+ organization_id=current_org.organization_id,+ credential_id=credential_id,+ credential_name=request.credential_name,+ )+ if updated is None:+ raise HTTPException(status_code=404, detail="Credential not found")+ return MicrosoftOAuthCredentialResponse(credential=updated)+++@microsoft_oauth_router.delete(+ "/oauth/credentials/{credential_id}",+ status_code=status.HTTP_204_NO_CONTENT,+)+async def delete_microsoft_oauth_credential(+ credential_id: str,+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+) -> None:+ revoked = await microsoft_oauth_service.revoke_credential(+ organization_id=current_org.organization_id,+ credential_id=credential_id,+ )+ if not revoked:+ raise HTTPException(status_code=404, detail="Credential not found")diff --git a/skyvern/forge/sdk/schemas/microsoft_oauth.py b/skyvern/forge/sdk/schemas/microsoft_oauth.pynew file mode 100644index 000000000..ae6a65894--- /dev/null+++ b/skyvern/forge/sdk/schemas/microsoft_oauth.py@@ -0,0 +1,65 @@+from datetime import datetime+from typing import Literal++from pydantic import BaseModel, Field, field_validator+++class MicrosoftOAuthCredentialBase(BaseModel):+ id: str+ organization_id: str+ credential_name: str+ state: str+ scopes_requested: list[str] = Field(default_factory=list)+ scopes_granted: list[str] = Field(default_factory=list)+ created_at: datetime+ modified_at: datetime+++class MicrosoftOAuthCredentialResponse(BaseModel):+ credential: MicrosoftOAuthCredentialBase+ app_origin: str | None = None+++class MicrosoftOAuthCredentialListResponse(BaseModel):+ credentials: list[MicrosoftOAuthCredentialBase]+++class CreateMicrosoftOAuthAuthorizeRequest(BaseModel):+ redirect_uri: str = Field(..., description="Redirect URI the consent flow will return to")+ credential_name: str = Field(default="Default", description="Human-readable name for this credential")+ scope_profile: Literal["outlook_mail"] | None = Field(+ default=None,+ description="Allowed Microsoft OAuth scope profile to request. Defaults to outlook_mail.",+ examples=["outlook_mail"],+ )+ app_origin: str | None = Field(+ default=None,+ description="Origin the callback should bounce back to. Must be on the MICROSOFT_OAUTH_APP_ORIGINS allowlist.",+ )+++class MicrosoftOAuthAuthorizeResponse(BaseModel):+ authorize_url: str+ state: str+++class CreateMicrosoftOAuthCallbackRequest(BaseModel):+ code: str = Field(..., description="Authorization code from Microsoft OAuth consent flow")+ state: str = Field(..., description="State token returned by Microsoft; must match a pending authorize request")+++class UpdateMicrosoftOAuthCredentialRequest(BaseModel):+ credential_name: str = Field(+ ...,+ min_length=1,+ max_length=128,+ description="New human-readable name for this credential",+ )++ @field_validator("credential_name")+ @classmethod+ def _strip_and_reject_blank(cls, v: str) -> str:+ stripped = v.strip()+ if not stripped:+ raise ValueError("credential_name must not be blank")+ return strippeddiff --git a/skyvern/forge/sdk/services/google_gmail_service.py b/skyvern/forge/sdk/services/google_gmail_service.pyindex 7c2ff8924..8d90df5b1 100644--- a/skyvern/forge/sdk/services/google_gmail_service.py+++ b/skyvern/forge/sdk/services/google_gmail_service.py@@ -1,5 +1,3 @@-import base64-import binasciiimport refrom dataclasses import dataclassfrom datetime import datetime, timezone@@ -10,11 +8,17 @@ from urllib.parse import quoteimport httpximport structlog-GMAIL_API_BASE = "https://gmail.googleapis.com/gmail/v1"+from skyvern.services.email import gmail_client++GMAIL_API_BASE = gmail_client.GMAIL_API_BASE+GmailAPIError = gmail_client.GmailAPIErrorLOG = structlog.get_logger()_OTP_QUERY_TERMS = "(verification OR verify OR code OR passcode OR otp OR 2fa OR one-time OR password)"_SAFE_EMAIL_QUERY_IDENTIFIER = re.compile(r"^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9.-]+$")+_decode = gmail_client.decode+_get_json = gmail_client.get_json+_payload_text = gmail_client.payload_text@dataclass(frozen=True)@@ -24,44 +28,6 @@ class GmailMessageCandidate:internal_date: datetime | None = None-class GmailAPIError(RuntimeError):- def __init__(self, *, status: int, code: str | None, message: str) -> None:- super().__init__(message)- self.status = status- self.code = code---async def _get_json(- client: httpx.AsyncClient,- url: str,- *,- access_token: str,- params: dict[str, Any] | None = None,-) -> dict[str, Any]:- response = await client.get(- url,- params=params,- headers={"Authorization": f"Bearer {access_token}", "Accept": "application/json"},- )- if response.is_success:- return response.json() or {}-- code = None- message = response.text[:500] or "Gmail API error"- try:- err = (response.json() or {}).get("error")- if isinstance(err, dict):- message = err.get("message") or message- details = err.get("errors")- if isinstance(details, list) and details and isinstance(details[0], dict):- code = details[0].get("reason")- except ValueError:- pass- if response.status_code == 403 and code in {"insufficientPermissions", "insufficientScopes"}:- code = "reconnect_required"- raise GmailAPIError(status=response.status_code, code=code, message=message)--def _as_utc(value: datetime) -> datetime:return value.replace(tzinfo=timezone.utc) if value.tzinfo is None else value.astimezone(timezone.utc)@@ -82,28 +48,6 @@ def _build_query(totp_identifier: str, *, created_after: datetime | None = None)return f"{_newer_than_query(created_after)} {_OTP_QUERY_TERMS} (to:{quoted} OR deliveredto:{quoted})"-def _decode(data: str | None) -> str:- if not data:- return ""- try:- return base64.urlsafe_b64decode(f"{data}{'=' * (-len(data) % 4)}").decode("utf-8", errors="replace")- except (binascii.Error, UnicodeDecodeError, ValueError):- return ""---def _payload_text(payload: dict[str, Any]) -> list[str]:- texts: list[str] = []- body = payload.get("body") if isinstance(payload.get("body"), dict) else {}- decoded = _decode(body.get("data") if isinstance(body, dict) else None)- mime_type = str(payload.get("mimeType") or "").lower()- if decoded and mime_type in {"text/plain", "text/html"}:- texts.append(decoded)- for part in payload.get("parts") or []:- if isinstance(part, dict):- texts.extend(_payload_text(part))- return texts--def _internal_date(message: dict[str, Any]) -> datetime | None:try:return datetime.fromtimestamp(int(message["internalDate"]) / 1000, tz=timezone.utc)diff --git a/skyvern/forge/sdk/services/microsoft_oauth_service.py b/skyvern/forge/sdk/services/microsoft_oauth_service.pynew file mode 100644index 000000000..c58929729--- /dev/null+++ b/skyvern/forge/sdk/services/microsoft_oauth_service.py@@ -0,0 +1,476 @@+from __future__ import annotations++import base64+import datetime+import hashlib+import secrets+from dataclasses import dataclass, field+from urllib.parse import urlencode, urlparse++import httpx+import structlog++from skyvern.config import settings+from skyvern.forge import app+from skyvern.forge.sdk.db.id import generate_microsoft_oauth_credential_id+from skyvern.forge.sdk.db.repositories.microsoft_oauth import ( # noqa: F401+ STATE_ACTIVE,+ STATE_ERROR,+ STATE_PENDING_CONSENT,+ STATE_REVOKED,+ InvalidConsentNonceError,+ PendingConsentContext,+)+from skyvern.forge.sdk.encrypt import encryptor+from skyvern.forge.sdk.encrypt.base import EncryptMethod+from skyvern.forge.sdk.schemas.microsoft_oauth import MicrosoftOAuthCredentialBase++LOG = structlog.get_logger()++MICROSOFT_AUTHORIZE_ENDPOINT_TEMPLATE = "https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize"+MICROSOFT_TOKEN_ENDPOINT_TEMPLATE = "https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token"++MICROSOFT_OAUTH_SCOPE_PROFILE_OUTLOOK_MAIL = "outlook_mail"+OUTLOOK_MAIL_SCOPES = ("Mail.Read", "offline_access", "openid", "profile", "User.Read")+MICROSOFT_OAUTH_SCOPE_PROFILES: dict[str, tuple[str, ...]] = {+ MICROSOFT_OAUTH_SCOPE_PROFILE_OUTLOOK_MAIL: OUTLOOK_MAIL_SCOPES,+}++CONSENT_TTL_SECONDS = 600+++def microsoft_access_token_cache_key(organization_id: str, credential_id: str) -> str:+ return f"microsoft:access_token:{organization_id}:{credential_id}"+++class EncryptionNotConfiguredError(RuntimeError):+ pass+++class MissingAccessTokenError(RuntimeError):+ pass+++class MicrosoftOAuthError(RuntimeError):+ pass+++class InvalidRedirectURIError(ValueError):+ pass+++class InvalidAppOriginError(ValueError):+ pass+++class UnsupportedScopeProfileError(ValueError):+ pass+++@dataclass(frozen=True)+class MicrosoftCredentialSecrets:+ refresh_token: str+ scopes: list[str] = field(default_factory=list)+++@dataclass(frozen=True)+class MicrosoftAuthorizationStart:+ authorize_url: str+ state: str+++def _authorize_endpoint() -> str:+ return MICROSOFT_AUTHORIZE_ENDPOINT_TEMPLATE.format(tenant=settings.MICROSOFT_OAUTH_TENANT)+++def _token_endpoint() -> str:+ return MICROSOFT_TOKEN_ENDPOINT_TEMPLATE.format(tenant=settings.MICROSOFT_OAUTH_TENANT)+++def _require_encryption() -> None:+ if not settings.ENABLE_ENCRYPTION:+ raise EncryptionNotConfiguredError(+ "Microsoft OAuth credentials require AES encryption. Set ENABLE_ENCRYPTION=true and "+ "configure ENCRYPTOR_AES_SECRET_KEY/SALT/IV on the deployment."+ )+++def _require_client_credentials() -> tuple[str, str]:+ client_id = settings.MICROSOFT_OAUTH_CLIENT_ID+ client_secret = settings.MICROSOFT_OAUTH_CLIENT_SECRET+ if not client_id or not client_secret:+ raise ValueError("Microsoft OAuth client credentials are not configured")+ return client_id, client_secret+++def _coerce_scopes(scopes: str | list[str] | tuple[str, ...] | None) -> list[str]:+ if scopes is None:+ return list(OUTLOOK_MAIL_SCOPES)+ if isinstance(scopes, str):+ parts = [p for p in scopes.replace(",", " ").split() if p]+ else:+ parts = [p for p in (str(s).strip() for s in scopes) if p]+ return parts or list(OUTLOOK_MAIL_SCOPES)+++def scopes_for_profile(scope_profile: str | None) -> list[str]:+ if scope_profile is None:+ scope_profile = MICROSOFT_OAUTH_SCOPE_PROFILE_OUTLOOK_MAIL+ if scope_profile not in MICROSOFT_OAUTH_SCOPE_PROFILES:+ raise UnsupportedScopeProfileError(f"Unsupported Microsoft OAuth scope profile: {scope_profile}")+ return list(MICROSOFT_OAUTH_SCOPE_PROFILES[scope_profile])+++def _scope_segment(scope: str) -> str:+ return scope.rsplit("/", 1)[-1]+++def has_required_scopes(+ granted_scopes: list[str] | tuple[str, ...] | None,+ required_scopes: list[str] | tuple[str, ...],+) -> bool:+ granted = {_scope_segment(scope) for scope in (granted_scopes or [])}+ return all(_scope_segment(scope) in granted for scope in required_scopes)+++_LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})+++def _validate_redirect_uri(redirect_uri: str) -> None:+ allowlist = settings.MICROSOFT_OAUTH_REDIRECT_HOSTS+ if not allowlist:+ if settings.MICROSOFT_OAUTH_CLIENT_ID:+ raise InvalidRedirectURIError(+ "MICROSOFT_OAUTH_REDIRECT_HOSTS must be configured when MICROSOFT_OAUTH_CLIENT_ID is set"+ )+ return+ try:+ parsed = urlparse(redirect_uri)+ scheme = parsed.scheme+ host = parsed.hostname or ""+ except Exception as exc:+ raise InvalidRedirectURIError(f"Invalid redirect_uri: {exc}") from exc+ if host not in {h.strip().lower() for h in allowlist if h and h.strip()}:+ raise InvalidRedirectURIError(f"redirect_uri host not allowed: {host}")+ if scheme != "https" and host not in _LOOPBACK_HOSTS:+ raise InvalidRedirectURIError(f"redirect_uri must use https for non-loopback host: {host}")+++def _validate_app_origin(app_origin: str) -> None:+ allowlist = settings.MICROSOFT_OAUTH_APP_ORIGINS+ if not allowlist:+ raise InvalidAppOriginError("MICROSOFT_OAUTH_APP_ORIGINS is not configured; app_origin is not accepted")++ try:+ parsed = urlparse(app_origin)+ scheme = parsed.scheme+ netloc = parsed.netloc+ host = parsed.hostname or ""+ except Exception as exc:+ raise InvalidAppOriginError(f"Invalid app_origin URL: {exc}") from exc++ if not scheme or not netloc:+ raise InvalidAppOriginError(f"app_origin must include scheme and hostname: {app_origin!r}")++ canonical = f"{scheme}://{netloc}"++ for entry in allowlist:+ stripped = entry.strip()+ if not stripped:+ continue+ if stripped.startswith("*."):+ if scheme != "https":+ continue+ suffix = stripped[1:].lower()+ if host.endswith(suffix) and host != suffix.lstrip("."):+ return+ elif canonical == stripped:+ return++ raise InvalidAppOriginError(f"app_origin not allowed: {app_origin!r}")+++def _code_challenge_for_verifier(code_verifier: str) -> str:+ digest = hashlib.sha256(code_verifier.encode()).digest()+ return base64.urlsafe_b64encode(digest).rstrip(b"=").decode()+++def build_authorize_url(+ redirect_uri: str,+ state: str,+ scopes: str | list[str] | tuple[str, ...] | None = None,+ code_verifier: str | None = None,+) -> tuple[str, str]:+ client_id, _client_secret = _require_client_credentials()+ _validate_redirect_uri(redirect_uri)++ scope_list = _coerce_scopes(scopes)+ if code_verifier is None:+ code_verifier = secrets.token_urlsafe(64)++ params = {+ "client_id": client_id,+ "response_type": "code",+ "redirect_uri": redirect_uri,+ "response_mode": "query",+ "scope": " ".join(scope_list),+ "state": state,+ "code_challenge": _code_challenge_for_verifier(code_verifier),+ "code_challenge_method": "S256",+ "prompt": "select_account",+ }+ return f"{_authorize_endpoint()}?{urlencode(params)}", code_verifier+++async def start_authorization(+ organization_id: str,+ redirect_uri: str,+ credential_name: str = "Default",+ scopes_requested: str | list[str] | tuple[str, ...] | None = None,+ scope_profile: str | None = None,+ app_origin: str | None = None,+) -> MicrosoftAuthorizationStart:+ _require_encryption()+ _validate_redirect_uri(redirect_uri)+ if app_origin is not None:+ _validate_app_origin(app_origin)++ credential_id = generate_microsoft_oauth_credential_id()+ nonce = secrets.token_urlsafe(32)+ code_verifier = secrets.token_urlsafe(64)+ now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)+ requested_scopes = (+ scopes_for_profile(scope_profile) if scopes_requested is None else _coerce_scopes(scopes_requested)+ )++ await app.DATABASE.microsoft_oauth.insert_pending_credential(+ credential_id=credential_id,+ organization_id=organization_id,+ credential_name=credential_name,+ scopes_requested=requested_scopes,+ consent_nonce=nonce,+ consent_redirect_uri=redirect_uri,+ consent_expires_at=now + datetime.timedelta(seconds=CONSENT_TTL_SECONDS),+ consent_app_origin=app_origin,+ consent_code_verifier=code_verifier,+ )++ authorize_url, _ = build_authorize_url(+ redirect_uri=redirect_uri,+ state=nonce,+ scopes=requested_scopes,+ code_verifier=code_verifier,+ )++ return MicrosoftAuthorizationStart(authorize_url=authorize_url, state=nonce)+++async def promote_pending_credential(+ organization_id: str,+ nonce: str,+ refresh_token: str,+ scopes_granted: str | list[str] | tuple[str, ...] | None,+) -> MicrosoftOAuthCredentialBase:+ _require_encryption()+ encrypted_token = await encryptor.encrypt(refresh_token, EncryptMethod.AES)+ now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)+ return await app.DATABASE.microsoft_oauth.promote_pending_to_active(+ organization_id=organization_id,+ nonce=nonce,+ encrypted_refresh_token=encrypted_token,+ encrypted_method=EncryptMethod.AES,+ scopes_granted=_coerce_scopes(scopes_granted),+ now=now,+ )+++async def load_pending_consent_context(organization_id: str, nonce: str) -> PendingConsentContext | None:+ return await app.DATABASE.microsoft_oauth.load_pending_by_nonce(+ organization_id=organization_id,+ nonce=nonce,+ )+++async def _post_token_form(data: dict[str, str]) -> dict:+ try:+ async with httpx.AsyncClient(timeout=10) as client:+ response = await client.post(+ _token_endpoint(),+ data=data,+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ except httpx.HTTPError as exc:+ raise MicrosoftOAuthError(f"Microsoft token endpoint failed: {exc}") from exc++ if response.status_code >= 400:+ error = None+ try:+ payload = response.json()+ error = payload.get("error")+ except ValueError:+ payload = {}+ if response.status_code in (400, 401) and error == "invalid_grant":+ raise MicrosoftOAuthError(+ "Microsoft authorization expired or was revoked. Reconnect the Microsoft account."+ )+ detail = payload.get("error_description") or response.text[:200]+ raise MicrosoftOAuthError(f"Microsoft token endpoint returned HTTP {response.status_code}: {detail}")++ try:+ return response.json()+ except ValueError as exc:+ raise MicrosoftOAuthError("Microsoft token endpoint returned invalid JSON") from exc+++async def exchange_code_for_tokens(+ code: str,+ redirect_uri: str,+ code_verifier: str | None,+ scopes: str | list[str] | tuple[str, ...] | None = None,+) -> dict:+ client_id, client_secret = _require_client_credentials()+ if not code_verifier:+ raise MicrosoftOAuthError("OAuth consent row is missing the PKCE verifier")++ token_data = await _post_token_form(+ {+ "client_id": client_id,+ "client_secret": client_secret,+ "grant_type": "authorization_code",+ "code": code,+ "redirect_uri": redirect_uri,+ "code_verifier": code_verifier,+ "scope": " ".join(_coerce_scopes(scopes)),+ }+ )+ if not token_data.get("refresh_token"):+ raise MicrosoftOAuthError("Microsoft token response did not include refresh_token")+ if not token_data.get("access_token"):+ raise MissingAccessTokenError("Microsoft token response did not include access_token")+ return token_data+++async def refresh_access_token(refresh_token: str, scopes: str | list[str] | tuple[str, ...] | None = None) -> dict:+ client_id, client_secret = _require_client_credentials()+ refresh_scopes = _coerce_scopes(scopes)+ if not has_required_scopes(refresh_scopes, ["offline_access"]):+ refresh_scopes.append("offline_access")+ token_data = await _post_token_form(+ {+ "client_id": client_id,+ "client_secret": client_secret,+ "grant_type": "refresh_token",+ "refresh_token": refresh_token,+ "scope": " ".join(refresh_scopes),+ }+ )+ if not token_data.get("access_token"):+ raise MissingAccessTokenError("Microsoft token response did not include access_token")+ return token_data+++async def load_credential_secrets(+ organization_id: str,+ credential_id: str,+) -> MicrosoftCredentialSecrets:+ payload = await app.DATABASE.microsoft_oauth.load_active_ciphertext(+ organization_id=organization_id,+ credential_id=credential_id,+ )+ if payload is None:+ raise ValueError(f"No active Microsoft OAuth credential found: {credential_id}")+ refresh_token = await encryptor.decrypt(payload.encrypted_refresh_token, payload.encrypted_method)+ return MicrosoftCredentialSecrets(refresh_token=refresh_token, scopes=payload.scopes_granted)+++async def access_token_from_secrets(credential_secrets: MicrosoftCredentialSecrets) -> str:+ if not credential_secrets.refresh_token:+ raise ValueError("OAuth credential is missing refresh_token")+ token_data = await refresh_access_token(credential_secrets.refresh_token)+ access_token = token_data.get("access_token")+ if not isinstance(access_token, str) or not access_token:+ raise MissingAccessTokenError("Microsoft token response did not include access_token")+ return access_token+++async def refresh_and_rotate(+ *,+ organization_id: str,+ credential_id: str,+ credential_secrets: MicrosoftCredentialSecrets,+) -> str:+ if not credential_secrets.refresh_token:+ raise ValueError("OAuth credential is missing refresh_token")+ token_data = await refresh_access_token(credential_secrets.refresh_token, credential_secrets.scopes)+ access_token = token_data.get("access_token")+ if not isinstance(access_token, str) or not access_token:+ raise MissingAccessTokenError("Microsoft token response did not include access_token")++ new_refresh_token = token_data.get("refresh_token")+ if (+ isinstance(new_refresh_token, str)+ and new_refresh_token+ and new_refresh_token != credential_secrets.refresh_token+ ):+ encrypted_refresh_token = await encryptor.encrypt(new_refresh_token, EncryptMethod.AES)+ now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)+ await app.DATABASE.microsoft_oauth.update_active_refresh_token(+ organization_id=organization_id,+ credential_id=credential_id,+ encrypted_refresh_token=encrypted_refresh_token,+ encrypted_method=EncryptMethod.AES,+ now=now,+ )+ return access_token+++async def get_credentials_for_org(organization_id: str) -> list[MicrosoftOAuthCredentialBase]:+ return await app.DATABASE.microsoft_oauth.list_active_for_org(organization_id=organization_id)+++async def rename_credential(+ organization_id: str,+ credential_id: str,+ credential_name: str,+) -> MicrosoftOAuthCredentialBase | None:+ now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)+ return await app.DATABASE.microsoft_oauth.rename_active(+ organization_id=organization_id,+ credential_id=credential_id,+ credential_name=credential_name,+ now=now,+ )+++async def revoke_credential(organization_id: str, credential_id: str) -> bool:+ payload = await app.DATABASE.microsoft_oauth.load_ciphertext_for_revoke(+ organization_id=organization_id,+ credential_id=credential_id,+ )+ if not payload.exists:+ return False++ now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)+ revoked_id = await app.DATABASE.microsoft_oauth.mark_revoked_and_scrub(+ organization_id=organization_id,+ credential_id=credential_id,+ now=now,+ )++ if revoked_id is not None:+ try:+ cache_key = microsoft_access_token_cache_key(organization_id, credential_id)+ await app.CACHE.set(cache_key, "", ex=datetime.timedelta(seconds=30))+ except Exception:+ LOG.warning(+ "Failed to invalidate Microsoft access-token cache on revoke",+ credential_id=credential_id,+ exc_info=True,+ )+ LOG.info(+ "Revoked Microsoft OAuth credential",+ credential_id=credential_id,+ organization_id=organization_id,+ )+ return True+ return Falsediff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.pyindex 024e7c00c..2c941d5a0 100644--- a/skyvern/forge/sdk/workflow/models/block.py+++ b/skyvern/forge/sdk/workflow/models/block.py@@ -11416,6 +11416,7 @@ def get_all_blocks(blocks: list[BlockTypeVar]) -> list[BlockTypeVar]:# Late import: google_sheets_blocks imports Block from this module, so top-level import would cycle.+from skyvern.forge.sdk.workflow.models.email_inbox_block import EmailInboxBlock # noqa: E402from skyvern.forge.sdk.workflow.models.google_sheets_blocks import ( # noqa: E402GoogleSheetsReadBlock,GoogleSheetsWriteBlock,@@ -11450,6 +11451,7 @@ BlockSubclasses = Union[PrintPageBlock,WorkflowTriggerBlock,GoogleSheetsReadBlock,+ EmailInboxBlock,GoogleSheetsWriteBlock,PdfFillBlock,SplitPdfBlock,diff --git a/skyvern/forge/sdk/workflow/models/email_inbox_block.py b/skyvern/forge/sdk/workflow/models/email_inbox_block.pynew file mode 100644index 000000000..d542dc39f--- /dev/null+++ b/skyvern/forge/sdk/workflow/models/email_inbox_block.py@@ -0,0 +1,226 @@+import asyncio+from typing import Any, Literal++from skyvern.forge import app+from skyvern.forge.sdk.services import google_oauth_service+from skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext+from skyvern.forge.sdk.workflow.models.block import Block+from skyvern.forge.sdk.workflow.models.parameter import PARAMETER_TYPE+from skyvern.schemas.workflows import BlockResult, BlockStatus, BlockType+from skyvern.services import email+++class EmailInboxBlock(Block):+ block_type: Literal[BlockType.EMAIL_INBOX] = BlockType.EMAIL_INBOX # type: ignore++ email_client: Literal["gmail", "outlook"]+ credential_id: str | None = None+ folder: str | None = None+ prompt: str | None = None+ sender: str | None = None+ subject: str | None = None+ newer_than_days: int | None = None+ max_results: int = 25+ include_body: bool = True+ parameters: list[PARAMETER_TYPE] = []++ def get_all_parameters(self, workflow_run_id: str) -> list[PARAMETER_TYPE]:+ return self.parameters++ def _render_templates(self, workflow_run_context: WorkflowRunContext) -> None:+ if self.credential_id:+ self.credential_id = self.format_block_parameter_template_from_workflow_run_context(+ self.credential_id, workflow_run_context+ )+ if self.folder:+ self.folder = self.format_block_parameter_template_from_workflow_run_context(+ self.folder, workflow_run_context+ )+ if self.prompt:+ self.prompt = self.format_block_parameter_template_from_workflow_run_context(+ self.prompt, workflow_run_context+ )+ if self.sender:+ self.sender = self.format_block_parameter_template_from_workflow_run_context(+ self.sender, workflow_run_context+ )+ if self.subject:+ self.subject = self.format_block_parameter_template_from_workflow_run_context(+ self.subject, workflow_run_context+ )++ async def _failure(+ self,+ *,+ failure_reason: str,+ workflow_run_block_id: str,+ organization_id: str | None,+ output_parameter_value: dict[str, Any] | None = None,+ ) -> BlockResult:+ return await self.build_block_result(+ success=False,+ failure_reason=failure_reason,+ output_parameter_value=output_parameter_value,+ status=BlockStatus.failed,+ workflow_run_block_id=workflow_run_block_id,+ organization_id=organization_id,+ )++ async def _match_emails(+ self,+ candidates: list[email.EmailMessage],+ *,+ criteria: str,+ organization_id: str,+ ) -> list[email.EmailMessage]:+ semaphore = asyncio.Semaphore(8)++ async def _match(candidate: email.EmailMessage) -> bool:+ async with semaphore:+ return await email.match_email(+ criteria=criteria,+ email=candidate,+ organization_id=organization_id,+ )++ results = await asyncio.gather(*(_match(candidate) for candidate in candidates))+ return [candidate for candidate, matches in zip(candidates, results) if matches]++ async def execute(+ self,+ workflow_run_id: str,+ workflow_run_block_id: str,+ organization_id: str | None = None,+ browser_session_id: str | None = None,+ **kwargs: Any,+ ) -> BlockResult:+ workflow_run_context = self.get_workflow_run_context(workflow_run_id)++ try:+ self._render_templates(workflow_run_context)+ except Exception as e:+ return await self._failure(+ failure_reason=f"Failed to format jinja template: {str(e)}",+ workflow_run_block_id=workflow_run_block_id,+ organization_id=organization_id,+ )++ if self.email_client not in {"gmail", "outlook"}:+ return await self._failure(+ failure_reason=f"Unsupported email_client: {self.email_client}",+ workflow_run_block_id=workflow_run_block_id,+ organization_id=organization_id,+ )+ if not self.credential_id:+ return await self._failure(+ failure_reason="credential_id is required",+ workflow_run_block_id=workflow_run_block_id,+ organization_id=organization_id,+ )++ effective_org_id = organization_id or workflow_run_context.organization_id+ if not effective_org_id:+ return await self._failure(+ failure_reason="organization_id is required to load email credentials",+ workflow_run_block_id=workflow_run_block_id,+ organization_id=organization_id,+ )++ if self.email_client == "gmail":+ creds = await app.AGENT_FUNCTION.get_google_workspace_credentials(+ organization_id=effective_org_id,+ credential_id=self.credential_id,+ required_scopes=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),+ )+ access_token = creds.token if creds else None+ reconnect_label = "Gmail"+ else:+ access_token = await app.AGENT_FUNCTION.get_microsoft_credentials(+ organization_id=effective_org_id,+ credential_id=self.credential_id,+ required_scopes=["Mail.Read"],+ )+ reconnect_label = "Outlook"+ if not access_token:+ return await self._failure(+ failure_reason=f"Reconnect the {reconnect_label} account: no valid access token",+ workflow_run_block_id=workflow_run_block_id,+ organization_id=organization_id,+ )++ folder_used = self.folder or ("INBOX" if self.email_client == "gmail" else "inbox")+ try:+ candidates = await email.list_folder_messages(+ email_client=self.email_client,+ access_token=access_token,+ folder=folder_used,+ sender=self.sender,+ subject=self.subject,+ newer_than_days=self.newer_than_days,+ max_results=self.max_results,+ include_body=self.include_body,+ )+ except email.GmailAPIError as e:+ return await self._api_failure(+ provider="Gmail",+ exc=e,+ workflow_run_context=workflow_run_context,+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=workflow_run_block_id,+ organization_id=organization_id,+ )+ except email.OutlookAPIError as e:+ return await self._api_failure(+ provider="Outlook",+ exc=e,+ workflow_run_context=workflow_run_context,+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=workflow_run_block_id,+ organization_id=organization_id,+ )++ criteria = self.prompt.strip() if self.prompt else ""+ matched = (+ await self._match_emails(candidates, criteria=criteria, organization_id=effective_org_id)+ if criteria+ else candidates+ )+ output_data: dict[str, Any] = {+ "email_client": self.email_client,+ "folder": folder_used,+ "candidate_count": len(candidates),+ "matched_count": len(matched),+ "emails": [message.model_dump(mode="json") for message in matched],+ }+ await self.record_output_parameter_value(workflow_run_context, workflow_run_id, output_data)+ return await self.build_block_result(+ success=True,+ failure_reason=None,+ output_parameter_value=output_data,+ status=BlockStatus.completed,+ workflow_run_block_id=workflow_run_block_id,+ organization_id=organization_id,+ )++ async def _api_failure(+ self,+ *,+ provider: str,+ exc: email.GmailAPIError | email.OutlookAPIError,+ workflow_run_context: WorkflowRunContext,+ workflow_run_id: str,+ workflow_run_block_id: str,+ organization_id: str | None,+ ) -> BlockResult:+ error_data = {"status_code": exc.status, "code": exc.code, "error": exc.message}+ await self.record_output_parameter_value(workflow_run_context, workflow_run_id, error_data)+ if exc.code == "reconnect_required":+ failure_reason = f"Reconnect the {provider} account: {exc.message}"+ else:+ failure_reason = f"{provider} email fetch failed (HTTP {exc.status}): {exc.message}"+ return await self._failure(+ failure_reason=failure_reason,+ workflow_run_block_id=workflow_run_block_id,+ organization_id=organization_id,+ output_parameter_value=error_data,+ )diff --git a/skyvern/forge/sdk/workflow/workflow_definition_converter.py b/skyvern/forge/sdk/workflow/workflow_definition_converter.pyindex ae22cdadf..5b45d2f6f 100644--- a/skyvern/forge/sdk/workflow/workflow_definition_converter.py+++ b/skyvern/forge/sdk/workflow/workflow_definition_converter.py@@ -63,6 +63,7 @@ from skyvern.forge.sdk.workflow.models.block import (WhileLoopBlock,WorkflowTriggerBlock,)+from skyvern.forge.sdk.workflow.models.email_inbox_block import EmailInboxBlockfrom skyvern.forge.sdk.workflow.models.google_sheets_blocks import (GoogleSheetsReadBlock,GoogleSheetsWriteBlock,@@ -935,6 +936,21 @@ def block_yaml_to_block(has_header_row=block_yaml.has_header_row,parameters=google_sheets_read_parameters,)+ elif block_yaml.block_type == BlockType.EMAIL_INBOX:+ email_inbox_parameters = _resolve_block_parameters(block_yaml, parameters)+ return EmailInboxBlock(+ **base_kwargs,+ email_client=block_yaml.email_client,+ credential_id=block_yaml.credential_id,+ folder=block_yaml.folder,+ prompt=block_yaml.prompt,+ sender=block_yaml.sender,+ subject=block_yaml.subject,+ newer_than_days=block_yaml.newer_than_days,+ max_results=block_yaml.max_results,+ include_body=block_yaml.include_body,+ parameters=email_inbox_parameters,+ )elif block_yaml.block_type == BlockType.GOOGLE_SHEETS_WRITE:google_sheets_write_parameters = _resolve_block_parameters(block_yaml, parameters)return GoogleSheetsWriteBlock(diff --git a/skyvern/schemas/emails.py b/skyvern/schemas/emails.pynew file mode 100644index 000000000..1e3b219b3--- /dev/null+++ b/skyvern/schemas/emails.py@@ -0,0 +1,26 @@+from pydantic import BaseModel, Field+++class EmailAttachment(BaseModel):+ name: str+ mime_type: str | None = None+ size: int | None = None+ attachment_id: str | None = None+++class EmailMessage(BaseModel):+ id: str+ thread_id: str | None = None+ subject: str = ""+ from_email: str = ""+ from_name: str | None = None+ to: list[str] = Field(default_factory=list)+ cc: list[str] = Field(default_factory=list)+ date: str | None = None+ snippet: str = ""+ body_text: str = ""+ body_html: str | None = None+ has_attachments: bool | None = None+ attachments: list[EmailAttachment] = Field(default_factory=list)+ is_read: bool = True+ web_link: str | None = Nonediff --git a/skyvern/schemas/workflows.py b/skyvern/schemas/workflows.pyindex d6fbc40ac..b81937649 100644--- a/skyvern/schemas/workflows.py+++ b/skyvern/schemas/workflows.py@@ -444,6 +444,7 @@ class BlockType(StrEnum):GOOGLE_SHEETS_WRITE = "google_sheets_write"PDF_FILL = "pdf_fill"SPLIT_PDF = "split_pdf"+ EMAIL_INBOX = "email_inbox"class AIFallbackMode(StrEnum):@@ -1265,6 +1266,20 @@ class GoogleSheetsReadBlockYAML(BlockYAML):parameter_keys: list[str] | None = None+class EmailInboxBlockYAML(BlockYAML):+ block_type: Literal[BlockType.EMAIL_INBOX] = BlockType.EMAIL_INBOX # type: ignore+ email_client: Literal["gmail", "outlook"]+ credential_id: str | None = None+ folder: str | None = None+ prompt: str | None = None+ sender: str | None = None+ subject: str | None = None+ newer_than_days: int | None = None+ max_results: int = 25+ include_body: bool = True+ parameter_keys: list[str] | None = None++class GoogleSheetsWriteBlockYAML(BlockYAML):block_type: Literal[BlockType.GOOGLE_SHEETS_WRITE] = BlockType.GOOGLE_SHEETS_WRITE # type: ignorespreadsheet_url: str@@ -1321,6 +1336,7 @@ BLOCK_YAML_SUBCLASSES = (| SplitPdfBlockYAML| WorkflowTriggerBlockYAML| GoogleSheetsReadBlockYAML+ | EmailInboxBlockYAML| GoogleSheetsWriteBlockYAML)BLOCK_YAML_TYPES = Annotated[BLOCK_YAML_SUBCLASSES, Field(discriminator="block_type")]diff --git a/skyvern/services/email/__init__.py b/skyvern/services/email/__init__.pynew file mode 100644index 000000000..27642f4ef--- /dev/null+++ b/skyvern/services/email/__init__.py@@ -0,0 +1,17 @@+from skyvern.services.email import gmail, outlook+from skyvern.services.email.gmail_client import GmailAPIError+from skyvern.services.email.inbox import EmailMatchResult, list_folder_messages, match_email+from skyvern.services.email.outlook import OutlookAPIError+from skyvern.services.email.types import EmailAttachment, EmailMessage++__all__ = [+ "EmailAttachment",+ "EmailMatchResult",+ "EmailMessage",+ "GmailAPIError",+ "OutlookAPIError",+ "gmail",+ "list_folder_messages",+ "match_email",+ "outlook",+]diff --git a/skyvern/services/email/gmail.py b/skyvern/services/email/gmail.pynew file mode 100644index 000000000..f7864383e--- /dev/null+++ b/skyvern/services/email/gmail.py@@ -0,0 +1,209 @@+from datetime import timezone+from email.utils import getaddresses, parseaddr, parsedate_to_datetime+from typing import Any+from urllib.parse import quote++import httpx++from skyvern.services.email.gmail_client import (+ GMAIL_API_BASE,+ GmailAPIError,+ decode,+ get_json,+ payload_text,+)+from skyvern.services.email.types import EmailAttachment, EmailMessage++_SYSTEM_LABELS = {"INBOX", "SENT", "DRAFT", "SPAM", "TRASH", "STARRED", "IMPORTANT", "UNREAD"}+++def _is_system_label(label: str) -> bool:+ normalized = label.upper()+ return normalized in _SYSTEM_LABELS or normalized.startswith("CATEGORY_")+++async def _resolve_label_id(client: httpx.AsyncClient, access_token: str, label: str) -> str:+ normalized = label.strip() or "INBOX"+ if _is_system_label(normalized):+ return normalized.upper()+ payload = await get_json(client, f"{GMAIL_API_BASE}/users/me/labels", access_token=access_token)+ for item in payload.get("labels") or []:+ if not isinstance(item, dict):+ continue+ name = item.get("name")+ label_id = item.get("id")+ if isinstance(name, str) and isinstance(label_id, str) and name.casefold() == normalized.casefold():+ return label_id+ raise GmailAPIError(status=404, code="folder_not_found", message=f"Gmail folder not found: {label}")+++def _quote_gmail_value(value: str) -> str | None:+ sanitized = value.replace("\\", "").replace('"', "").strip()+ if not sanitized:+ return None+ return f'"{sanitized}"'+++def _build_folder_query(sender: str | None, subject: str | None, newer_than_days: int | None) -> str:+ query_parts: list[str] = []+ if sender:+ quoted_sender = _quote_gmail_value(sender)+ if quoted_sender:+ query_parts.append(f"from:{quoted_sender}")+ if subject:+ quoted_subject = _quote_gmail_value(subject)+ if quoted_subject:+ query_parts.append(f"subject:{quoted_subject}")+ if newer_than_days is not None:+ query_parts.append(f"newer_than:{max(1, newer_than_days)}d")+ return " ".join(query_parts)+++def _payload_text_by_mime(payload: dict[str, Any], mime_types: set[str]) -> list[str]:+ texts: list[str] = []+ raw_body = payload.get("body")+ body = raw_body if isinstance(raw_body, dict) else {}+ decoded = decode(body.get("data"))+ mime_type = str(payload.get("mimeType") or "").lower()+ if decoded and mime_type in mime_types:+ texts.append(decoded)+ for part in payload.get("parts") or []:+ if isinstance(part, dict):+ texts.extend(_payload_text_by_mime(part, mime_types))+ return texts+++def _attachments(payload: dict[str, Any]) -> list[EmailAttachment]:+ attachments: list[EmailAttachment] = []+ filename = payload.get("filename")+ raw_body = payload.get("body")+ body = raw_body if isinstance(raw_body, dict) else {}+ attachment_id = body.get("attachmentId")+ if isinstance(filename, str) and filename and isinstance(attachment_id, str):+ size = body.get("size")+ mime_type = payload.get("mimeType")+ attachments.append(+ EmailAttachment(+ name=filename,+ mime_type=mime_type if isinstance(mime_type, str) else None,+ size=size if isinstance(size, int) else None,+ attachment_id=attachment_id,+ )+ )+ for part in payload.get("parts") or []:+ if isinstance(part, dict):+ attachments.extend(_attachments(part))+ return attachments+++def _headers(payload: dict[str, Any]) -> dict[str, str]:+ return {+ h["name"].lower(): h["value"]+ for h in payload.get("headers") or []+ if isinstance(h, dict) and isinstance(h.get("name"), str) and isinstance(h.get("value"), str)+ }+++def _date_header_to_iso(value: str | None) -> str | None:+ if not value:+ return None+ try:+ parsed = parsedate_to_datetime(value)+ except (TypeError, ValueError, IndexError, OverflowError):+ return None+ if parsed.tzinfo is None:+ parsed = parsed.replace(tzinfo=timezone.utc)+ return parsed.astimezone(timezone.utc).isoformat()+++def _message_from_gmail(message: dict[str, Any], include_body: bool) -> EmailMessage | None:+ message_id = message.get("id")+ if not isinstance(message_id, str):+ return None+ raw_payload = message.get("payload")+ payload = raw_payload if isinstance(raw_payload, dict) else {}+ headers = _headers(payload)+ from_name, from_email = parseaddr(headers.get("from") or "")+ body_text = ""+ body_html = None+ if include_body:+ text_parts = _payload_text_by_mime(payload, {"text/plain"})+ html_parts = _payload_text_by_mime(payload, {"text/html"})+ body_text = "\n".join(text_parts) if text_parts else "\n".join(payload_text(payload))+ body_html = "\n".join(html_parts) if html_parts else None+ attachments = _attachments(payload) if include_body else []+ raw_label_ids = message.get("labelIds")+ label_ids = raw_label_ids if isinstance(raw_label_ids, list) else []+ thread_id = message.get("threadId") if isinstance(message.get("threadId"), str) else None+ link_id = thread_id or message_id+ return EmailMessage(+ id=message_id,+ thread_id=thread_id,+ subject=headers.get("subject") or "",+ from_email=from_email,+ from_name=from_name or None,+ to=[address for _, address in getaddresses([headers.get("to") or ""]) if address],+ cc=[address for _, address in getaddresses([headers.get("cc") or ""]) if address],+ date=_date_header_to_iso(headers.get("date")),+ snippet=message.get("snippet") if isinstance(message.get("snippet"), str) else "",+ body_text=body_text,+ body_html=body_html,+ has_attachments=bool(attachments) if include_body else None,+ attachments=attachments,+ is_read="UNREAD" not in label_ids,+ web_link=f"https://mail.google.com/mail/u/0/#all/{link_id}",+ )+++def _clamp_max_results(max_results: int) -> int:+ return max(1, min(max_results, 100))+++async def list_folder_messages(+ *,+ access_token: str,+ label: str = "INBOX",+ sender: str | None = None,+ subject: str | None = None,+ newer_than_days: int | None = None,+ max_results: int = 25,+ include_body: bool = True,+ client: httpx.AsyncClient | None = None,+) -> list[EmailMessage]:+ async def _list(client_: httpx.AsyncClient) -> list[EmailMessage]:+ label_id = await _resolve_label_id(client_, access_token, label)+ max_results_clamped = _clamp_max_results(max_results)+ params: dict[str, Any] = {+ "labelIds": label_id,+ "maxResults": max_results_clamped,+ "includeSpamTrash": "true" if label_id in {"SPAM", "TRASH"} else "false",+ }+ query = _build_folder_query(sender, subject, newer_than_days)+ if query:+ params["q"] = query+ payload = await get_json(+ client_,+ f"{GMAIL_API_BASE}/users/me/messages",+ access_token=access_token,+ params=params,+ )+ messages: list[EmailMessage] = []+ for ref in (payload.get("messages") or [])[:max_results_clamped]:+ message_id = ref.get("id") if isinstance(ref, dict) else None+ if not isinstance(message_id, str):+ continue+ message = await get_json(+ client_,+ f"{GMAIL_API_BASE}/users/me/messages/{quote(message_id, safe='')}",+ access_token=access_token,+ params={"format": "full" if include_body else "metadata"},+ )+ normalized = _message_from_gmail(message, include_body)+ if normalized:+ messages.append(normalized)+ return messages++ if client is None:+ async with httpx.AsyncClient(timeout=20.0) as owned_client:+ return await _list(owned_client)+ return await _list(client)diff --git a/skyvern/services/email/gmail_client.py b/skyvern/services/email/gmail_client.pynew file mode 100644index 000000000..34e904908--- /dev/null+++ b/skyvern/services/email/gmail_client.py@@ -0,0 +1,112 @@+import asyncio+import base64+import binascii+from datetime import UTC, datetime+from email.utils import parsedate_to_datetime+from typing import Any++import httpx++GMAIL_API_BASE = "https://gmail.googleapis.com/gmail/v1"+_RETRYABLE_STATUSES = {429, 500, 502, 503, 504}+_MAX_ATTEMPTS = 3+_MAX_BACKOFF_SECONDS = 5.0+++class GmailAPIError(RuntimeError):+ def __init__(self, *, status: int, code: str | None, message: str) -> None:+ super().__init__(message)+ self.status = status+ self.code = code+ self.message = message+++def _compute_backoff(attempt: int, retry_after: str | None) -> float:+ if retry_after:+ value = retry_after.strip()+ try:+ return min(max(0.0, float(value)), _MAX_BACKOFF_SECONDS)+ except ValueError:+ pass+ try:+ target = parsedate_to_datetime(value)+ except (TypeError, ValueError):+ target = None+ if target is not None:+ if target.tzinfo is None:+ target = target.replace(tzinfo=UTC)+ delta = (target - datetime.now(UTC)).total_seconds()+ return min(max(0.0, delta), _MAX_BACKOFF_SECONDS)+ return min(0.5 * (3 ** (attempt - 1)), _MAX_BACKOFF_SECONDS)+++async def get_json(+ client: httpx.AsyncClient,+ url: str,+ *,+ access_token: str,+ params: dict[str, Any] | None = None,+) -> dict[str, Any]:+ response: httpx.Response | None = None+ for attempt in range(1, _MAX_ATTEMPTS + 1):+ try:+ response = await client.get(+ url,+ params=params,+ headers={"Authorization": f"Bearer {access_token}", "Accept": "application/json"},+ )+ except (httpx.TransportError, httpx.TimeoutException) as exc:+ if attempt == _MAX_ATTEMPTS:+ raise GmailAPIError(+ status=503,+ code="upstream_unavailable",+ message=f"Gmail transport failure: {exc}",+ ) from exc+ await asyncio.sleep(_compute_backoff(attempt, None))+ continue+ if response.is_success or response.status_code not in _RETRYABLE_STATUSES or attempt == _MAX_ATTEMPTS:+ break+ await asyncio.sleep(_compute_backoff(attempt, response.headers.get("Retry-After")))++ if response is None:+ raise GmailAPIError(status=503, code="upstream_unavailable", message="Gmail transport failure")+ if response.is_success:+ return response.json() or {}++ code = None+ message = response.text[:500] or "Gmail API error"+ try:+ err = (response.json() or {}).get("error")+ if isinstance(err, dict):+ message = err.get("message") or message+ details = err.get("errors")+ if isinstance(details, list) and details and isinstance(details[0], dict):+ code = details[0].get("reason")+ except ValueError:+ pass+ if response.status_code == 403 and code in {"insufficientPermissions", "insufficientScopes"}:+ code = "reconnect_required"+ raise GmailAPIError(status=response.status_code, code=code, message=message)+++def decode(data: str | None) -> str:+ if not data:+ return ""+ try:+ return base64.urlsafe_b64decode(f"{data}{'=' * (-len(data) % 4)}").decode("utf-8", errors="replace")+ except (binascii.Error, UnicodeDecodeError, ValueError):+ return ""+++def payload_text(payload: dict[str, Any]) -> list[str]:+ texts: list[str] = []+ raw_body = payload.get("body")+ body = raw_body if isinstance(raw_body, dict) else {}+ decoded = decode(body.get("data"))+ mime_type = str(payload.get("mimeType") or "").lower()+ if decoded and mime_type in {"text/plain", "text/html"}:+ texts.append(decoded)+ for part in payload.get("parts") or []:+ if isinstance(part, dict):+ texts.extend(payload_text(part))+ return textsdiff --git a/skyvern/services/email/inbox.py b/skyvern/services/email/inbox.pynew file mode 100644index 000000000..dc762db5c--- /dev/null+++ b/skyvern/services/email/inbox.py@@ -0,0 +1,70 @@+import httpx+from pydantic import BaseModel++from skyvern.forge import app+from skyvern.forge.prompts import prompt_engine+from skyvern.services.email import gmail, outlook+from skyvern.services.email.types import EmailMessage++_BODY_LIMIT = 4000+++class EmailMatchResult(BaseModel):+ reasoning: str+ matches: bool+++async def list_folder_messages(+ *,+ email_client: str,+ access_token: str,+ folder: str,+ sender: str | None,+ subject: str | None,+ newer_than_days: int | None,+ max_results: int,+ include_body: bool,+ client: httpx.AsyncClient | None = None,+) -> list[EmailMessage]:+ if email_client == "gmail":+ return await gmail.list_folder_messages(+ access_token=access_token,+ label=folder,+ sender=sender,+ subject=subject,+ newer_than_days=newer_than_days,+ max_results=max_results,+ include_body=include_body,+ client=client,+ )+ if email_client == "outlook":+ return await outlook.list_folder_messages(+ access_token=access_token,+ folder=folder,+ sender=sender,+ subject=subject,+ newer_than_days=newer_than_days,+ max_results=max_results,+ include_body=include_body,+ client=client,+ )+ raise ValueError(f"Unsupported email_client: {email_client}")+++async def match_email(*, criteria: str, email: EmailMessage, organization_id: str) -> bool:+ body = email.body_text or email.body_html or ""+ prompt = prompt_engine.load_prompt(+ "match-email",+ criteria=criteria,+ subject=email.subject,+ sender=email.from_email,+ snippet=email.snippet,+ body=body[:_BODY_LIMIT],+ )+ resp = await app.SECONDARY_LLM_API_HANDLER(+ prompt=prompt,+ prompt_name="match-email",+ organization_id=organization_id,+ )+ result = EmailMatchResult.model_validate(resp)+ return result.matchesdiff --git a/skyvern/services/email/outlook.py b/skyvern/services/email/outlook.pynew file mode 100644index 000000000..e82427362--- /dev/null+++ b/skyvern/services/email/outlook.py@@ -0,0 +1,444 @@+import asyncio+from datetime import UTC, datetime, timedelta+from email.utils import parsedate_to_datetime+from typing import Any+from urllib.parse import quote, urlparse++import httpx+import structlog++from skyvern.services.email.types import EmailAttachment, EmailMessage++GRAPH_API_BASE = "https://graph.microsoft.com/v1.0"+LOG = structlog.get_logger()+_MAX_SUBJECT_FILTER_PAGES = 10+_MAX_SUBJECT_FILTER_FETCHED = 250+_MAX_ATTACHMENT_PAGES = 4+_MAX_FOLDER_SEARCH_DEPTH = 5+_MAX_FOLDER_SEARCH_FOLDERS = 500+_PERMISSIVE_RECEIVED_DATETIME_LOWER_BOUND = "1900-01-01T00:00:00Z"+_RECONNECT_ERROR_CODES = {+ "invalidauthenticationtoken",+ "accessdenied",+ "erroraccessdenied",+ "authorization_requestdenied",+}+_RETRYABLE_STATUSES = {429, 500, 502, 503, 504}+_MAX_ATTEMPTS = 3+_MAX_BACKOFF_SECONDS = 5.0+_WELL_KNOWN_FOLDERS = {"inbox", "drafts", "sentitems", "deleteditems", "junkemail", "archive", "clutter", "outbox"}+++class OutlookAPIError(RuntimeError):+ def __init__(self, *, status: int, code: str | None, message: str) -> None:+ super().__init__(message)+ self.status = status+ self.code = code+ self.message = message+++def _compute_backoff(attempt: int, retry_after: str | None) -> float:+ if retry_after:+ value = retry_after.strip()+ try:+ return min(max(0.0, float(value)), _MAX_BACKOFF_SECONDS)+ except ValueError:+ pass+ try:+ target = parsedate_to_datetime(value)+ except (TypeError, ValueError):+ target = None+ if target is not None:+ if target.tzinfo is None:+ target = target.replace(tzinfo=UTC)+ delta = (target - datetime.now(UTC)).total_seconds()+ return min(max(0.0, delta), _MAX_BACKOFF_SECONDS)+ return min(0.5 * (3 ** (attempt - 1)), _MAX_BACKOFF_SECONDS)+++async def _get_json(+ client: httpx.AsyncClient,+ url: str,+ *,+ access_token: str,+ params: dict[str, Any] | None = None,+) -> dict[str, Any]:+ response: httpx.Response | None = None+ for attempt in range(1, _MAX_ATTEMPTS + 1):+ try:+ response = await client.get(+ url,+ params=params,+ headers={"Authorization": f"Bearer {access_token}", "Accept": "application/json"},+ )+ except (httpx.TransportError, httpx.TimeoutException) as exc:+ if attempt == _MAX_ATTEMPTS:+ raise OutlookAPIError(+ status=503,+ code="upstream_unavailable",+ message=f"Microsoft Graph transport failure: {exc}",+ ) from exc+ await asyncio.sleep(_compute_backoff(attempt, None))+ continue+ if response.is_success or response.status_code not in _RETRYABLE_STATUSES or attempt == _MAX_ATTEMPTS:+ break+ await asyncio.sleep(_compute_backoff(attempt, response.headers.get("Retry-After")))++ if response is None:+ raise OutlookAPIError(status=503, code="upstream_unavailable", message="Microsoft Graph transport failure")+ if response.is_success:+ return response.json() or {}++ code = None+ message = response.text[:500] or "Microsoft Graph API error"+ try:+ err = (response.json() or {}).get("error")+ if isinstance(err, dict):+ code = err.get("code")+ message = err.get("message") or message+ except ValueError:+ pass+ if response.status_code == 401 or (+ response.status_code == 403 and isinstance(code, str) and code.casefold() in _RECONNECT_ERROR_CODES+ ):+ code = "reconnect_required"+ raise OutlookAPIError(status=response.status_code, code=code, message=message)+++def _clamp_max_results(max_results: int) -> int:+ return max(1, min(max_results, 100))+++def _escape_odata_string(value: str) -> str:+ return value.replace("'", "''")+++def _validated_next_link(raw_next_link: Any) -> str | None:+ if not isinstance(raw_next_link, str) or not raw_next_link:+ return None+ try:+ parsed = urlparse(raw_next_link)+ hostname = parsed.hostname+ except ValueError:+ LOG.warning("Ignoring malformed Outlook pagination URL", next_link_host=None)+ return None+ if parsed.scheme != "https" or hostname is None or hostname.casefold() != "graph.microsoft.com":+ LOG.warning(+ "Ignoring untrusted Outlook pagination URL",+ next_link_host=hostname,+ )+ return None+ return raw_next_link+++async def _find_folder_id_by_display_name(+ client: httpx.AsyncClient,+ access_token: str,+ url: str,+ display_name: str,+) -> str | None:+ payload = await _get_json(+ client,+ url,+ access_token=access_token,+ params={+ "$filter": f"displayName eq '{_escape_odata_string(display_name)}'",+ "$select": "id,displayName",+ },+ )+ for item in payload.get("value") or []:+ folder_id = item.get("id") if isinstance(item, dict) else None+ if isinstance(folder_id, str) and folder_id:+ return folder_id+ return None+++async def _search_folder_tree_by_display_name(+ client: httpx.AsyncClient,+ access_token: str,+ display_name: str,+) -> str | None:+ queue: list[tuple[str, dict[str, Any] | None, int]] = [+ (f"{GRAPH_API_BASE}/me/mailFolders", {"$select": "id,displayName"}, 0)+ ]+ visited = 0+ target = display_name.casefold()+ while queue and visited < _MAX_FOLDER_SEARCH_FOLDERS:+ url, params, depth = queue.pop(0)+ payload = await _get_json(client, url, access_token=access_token, params=params)+ items = payload.get("value")+ for item in items if isinstance(items, list) else []:+ if visited >= _MAX_FOLDER_SEARCH_FOLDERS or not isinstance(item, dict):+ break+ visited += 1+ folder_id = item.get("id")+ folder_name = item.get("displayName")+ if isinstance(folder_id, str) and isinstance(folder_name, str):+ if folder_name.casefold() == target:+ return folder_id+ if depth < _MAX_FOLDER_SEARCH_DEPTH:+ queue.append(+ (+ f"{GRAPH_API_BASE}/me/mailFolders/{quote(folder_id, safe='')}/childFolders",+ {"$select": "id,displayName"},+ depth + 1,+ )+ )+ next_link = _validated_next_link(payload.get("@odata.nextLink"))+ if next_link and visited < _MAX_FOLDER_SEARCH_FOLDERS:+ queue.insert(0, (next_link, None, depth))+ return None+++async def _resolve_folder_id(client: httpx.AsyncClient, access_token: str, folder: str) -> str:+ normalized = folder.strip() or "inbox"+ lower = normalized.lower()+ if lower in _WELL_KNOWN_FOLDERS:+ return lower+ if "/" in normalized:+ segments = [segment.strip() for segment in normalized.split("/") if segment.strip()]+ if segments:+ folder_id = await _find_folder_id_by_display_name(+ client,+ access_token,+ f"{GRAPH_API_BASE}/me/mailFolders",+ segments[0],+ )+ for segment in segments[1:]:+ if not folder_id:+ break+ folder_id = await _find_folder_id_by_display_name(+ client,+ access_token,+ f"{GRAPH_API_BASE}/me/mailFolders/{quote(folder_id, safe='')}/childFolders",+ segment,+ )+ if folder_id:+ return folder_id+ raise OutlookAPIError(status=404, code="folder_not_found", message=f"Outlook folder not found: {folder}")+ folder_id = await _find_folder_id_by_display_name(+ client,+ access_token,+ f"{GRAPH_API_BASE}/me/mailFolders",+ normalized,+ )+ if folder_id:+ return folder_id+ folder_id = await _search_folder_tree_by_display_name(client, access_token, normalized)+ if folder_id:+ return folder_id+ raise OutlookAPIError(status=404, code="folder_not_found", message=f"Outlook folder not found: {folder}")+++def _email_address(value: dict[str, Any] | None) -> tuple[str, str | None]:+ if not isinstance(value, dict):+ return "", None+ email_address = value.get("emailAddress")+ if not isinstance(email_address, dict):+ return "", None+ address = email_address.get("address")+ name = email_address.get("name")+ return (address if isinstance(address, str) else "", name if isinstance(name, str) else None)+++def _recipient_addresses(recipients: list[Any] | None) -> list[str]:+ addresses: list[str] = []+ for recipient in recipients or []:+ if not isinstance(recipient, dict):+ continue+ address, _ = _email_address(recipient)+ if address:+ addresses.append(address)+ return addresses+++async def _attachments(+ client: httpx.AsyncClient,+ *,+ access_token: str,+ message_id: str,+) -> list[EmailAttachment]:+ attachments: list[EmailAttachment] = []+ request_url: str | None = f"{GRAPH_API_BASE}/me/messages/{quote(message_id, safe='')}/attachments"+ request_params: dict[str, Any] | None = {"$select": "id,name,contentType,size"}+ page_count = 0+ try:+ while request_url and page_count < _MAX_ATTACHMENT_PAGES:+ payload = await _get_json(client, request_url, access_token=access_token, params=request_params)+ page_count += 1+ for item in payload.get("value") or []:+ if not isinstance(item, dict):+ continue+ name = item.get("name")+ if not isinstance(name, str) or not name:+ continue+ size = item.get("size")+ attachment_id = item.get("id")+ content_type = item.get("contentType")+ attachments.append(+ EmailAttachment(+ name=name,+ mime_type=content_type if isinstance(content_type, str) else None,+ size=size if isinstance(size, int) else None,+ attachment_id=attachment_id if isinstance(attachment_id, str) else None,+ )+ )+ request_url = _validated_next_link(payload.get("@odata.nextLink"))+ request_params = None+ except OutlookAPIError as exc:+ if exc.code == "reconnect_required":+ raise+ LOG.warning(+ "Failed to fetch Outlook message attachments",+ status=exc.status,+ code=exc.code,+ )+ return attachments+++def _message_from_graph(+ message: dict[str, Any],+ attachments: list[EmailAttachment],+ *,+ include_body: bool,+) -> EmailMessage | None:+ message_id = message.get("id")+ if not isinstance(message_id, str):+ return None+ from_email, from_name = _email_address(message.get("from") if isinstance(message.get("from"), dict) else None)+ body_text = ""+ body_html = None+ raw_body = message.get("body")+ body = raw_body if include_body and isinstance(raw_body, dict) else {}+ body_content = body.get("content")+ if isinstance(body_content, str):+ if str(body.get("contentType") or "").lower() == "html":+ body_html = body_content+ else:+ body_text = body_content+ return EmailMessage(+ id=message_id,+ thread_id=message.get("conversationId") if isinstance(message.get("conversationId"), str) else None,+ subject=message.get("subject") if isinstance(message.get("subject"), str) else "",+ from_email=from_email,+ from_name=from_name,+ to=_recipient_addresses(message.get("toRecipients") if isinstance(message.get("toRecipients"), list) else []),+ cc=_recipient_addresses(message.get("ccRecipients") if isinstance(message.get("ccRecipients"), list) else []),+ date=message.get("receivedDateTime") if isinstance(message.get("receivedDateTime"), str) else None,+ snippet=message.get("bodyPreview") if isinstance(message.get("bodyPreview"), str) else "",+ body_text=body_text,+ body_html=body_html,+ has_attachments=bool(message.get("hasAttachments")),+ attachments=attachments,+ is_read=bool(message.get("isRead", True)),+ web_link=message.get("webLink") if isinstance(message.get("webLink"), str) else None,+ )+++def _filter_expression(sender: str | None, newer_than_days: int | None) -> str | None:+ filters: list[str] = []+ if newer_than_days is not None:+ cutoff = datetime.now(UTC) - timedelta(days=max(0, newer_than_days))+ filters.append(f"receivedDateTime ge {cutoff.isoformat().replace('+00:00', 'Z')}")+ elif sender:+ filters.append(f"receivedDateTime ge {_PERMISSIVE_RECEIVED_DATETIME_LOWER_BOUND}")+ if sender:+ filters.append(f"from/emailAddress/address eq '{_escape_odata_string(sender)}'")+ return " and ".join(filters) if filters else None+++def _subject_matches(message: dict[str, Any], subject_filter: str | None) -> bool:+ if not subject_filter:+ return True+ raw_subject = message.get("subject")+ item_subject = raw_subject if isinstance(raw_subject, str) else ""+ return subject_filter in item_subject.lower()+++async def list_folder_messages(+ *,+ access_token: str,+ folder: str = "inbox",+ sender: str | None = None,+ subject: str | None = None,+ newer_than_days: int | None = None,+ max_results: int = 25,+ include_body: bool = True,+ client: httpx.AsyncClient | None = None,+) -> list[EmailMessage]:+ async def _list(client_: httpx.AsyncClient) -> list[EmailMessage]:+ folder_id = await _resolve_folder_id(client_, access_token, folder)+ select_fields = [+ "id",+ "conversationId",+ "subject",+ "from",+ "toRecipients",+ "ccRecipients",+ "receivedDateTime",+ "bodyPreview",+ "hasAttachments",+ "isRead",+ "webLink",+ ]+ if include_body:+ select_fields.append("body")+ max_results_clamped = _clamp_max_results(max_results)+ params: dict[str, Any] = {+ "$top": max_results_clamped,+ "$orderby": "receivedDateTime desc",+ "$select": ",".join(select_fields),+ }+ filter_expression = _filter_expression(sender, newer_than_days)+ if filter_expression:+ params["$filter"] = filter_expression+ subject_filter = subject.lower() if subject else None+ messages: list[EmailMessage] = []+ page_count = 0+ fetched_count = 0+ request_url: str | None = f"{GRAPH_API_BASE}/me/mailFolders/{quote(folder_id, safe='')}/messages"+ request_params: dict[str, Any] | None = params+ truncated = False++ while request_url and len(messages) < max_results_clamped:+ payload = await _get_json(client_, request_url, access_token=access_token, params=request_params)+ page_count += 1+ raw_items = payload.get("value")+ items = raw_items if isinstance(raw_items, list) else []+ for item in items:+ if fetched_count >= _MAX_SUBJECT_FILTER_FETCHED:+ truncated = True+ break+ fetched_count += 1+ if not isinstance(item, dict) or not _subject_matches(item, subject_filter):+ continue+ message_id = item.get("id")+ item_attachments: list[EmailAttachment] = []+ if include_body and bool(item.get("hasAttachments")) and isinstance(message_id, str):+ item_attachments = await _attachments(client_, access_token=access_token, message_id=message_id)+ message = _message_from_graph(item, item_attachments, include_body=include_body)+ if message:+ messages.append(message)+ if len(messages) >= max_results_clamped:+ break+ if not subject_filter or len(messages) >= max_results_clamped or truncated:+ break+ if page_count >= _MAX_SUBJECT_FILTER_PAGES:+ truncated = True+ break+ request_url = _validated_next_link(payload.get("@odata.nextLink"))+ request_params = None+ if truncated:+ LOG.debug(+ "Truncated Outlook subject pagination",+ pages=page_count,+ fetched=fetched_count,+ max_pages=_MAX_SUBJECT_FILTER_PAGES,+ max_fetched=_MAX_SUBJECT_FILTER_FETCHED,+ )+ return messages++ if client is None:+ async with httpx.AsyncClient(timeout=20.0) as owned_client:+ return await _list(owned_client)+ return await _list(client)diff --git a/skyvern/services/email/types.py b/skyvern/services/email/types.pynew file mode 100644index 000000000..de228d9b9--- /dev/null+++ b/skyvern/services/email/types.py@@ -0,0 +1,3 @@+from skyvern.schemas.emails import EmailAttachment, EmailMessage++__all__ = ["EmailAttachment", "EmailMessage"]diff --git a/tests/unit/test_email_inbox_block.py b/tests/unit/test_email_inbox_block.pynew file mode 100644index 000000000..60f31f2ec--- /dev/null+++ b/tests/unit/test_email_inbox_block.py@@ -0,0 +1,252 @@+from __future__ import annotations++from datetime import UTC, datetime+from types import SimpleNamespace+from typing import Any+from unittest.mock import AsyncMock, patch++import pytest++from skyvern.forge import app+from skyvern.forge.sdk.workflow.models.block import Block+from skyvern.forge.sdk.workflow.models.email_inbox_block import EmailInboxBlock+from skyvern.forge.sdk.workflow.models.parameter import OutputParameter+from skyvern.forge.sdk.workflow.workflow_definition_converter import block_yaml_to_block+from skyvern.schemas.emails import EmailMessage+from skyvern.schemas.workflows import BlockResult, BlockStatus, EmailInboxBlockYAML, WorkflowDefinitionYAML+from skyvern.services import email++_NOW = datetime.now(UTC)+++class _FakeContextForTest:+ def __init__(self, organization_id: str) -> None:+ self.values: dict[str, Any] = {}+ self.secrets: dict[str, Any] = {}+ self.include_secrets_in_templates = False+ self.workflow_title = "wf-title"+ self.workflow_id = "wf-id"+ self.workflow_permanent_id = "wf-perm-id"+ self.workflow_run_id = "wr_test"+ self.workflow_run_outputs: dict[str, Any] = {}+ self.browser_session_id: str | None = None+ self.organization_id: str | None = organization_id++ def get_block_metadata(self, label: str) -> dict[str, Any]:+ return {}++ def build_workflow_run_summary(self) -> str:+ return ""+++def _make_output_parameter(label: str = "read_email") -> OutputParameter:+ return OutputParameter(+ parameter_type="output",+ key=f"{label}_output",+ workflow_id="test_wf",+ output_parameter_id=f"op_{label}",+ created_at=_NOW,+ modified_at=_NOW,+ )+++def _make_block(**overrides: Any) -> EmailInboxBlock:+ data: dict[str, Any] = {+ "label": "read_email",+ "output_parameter": _make_output_parameter(),+ "email_client": "gmail",+ "credential_id": "cred_123",+ }+ data.update(overrides)+ return EmailInboxBlock(**data)+++async def _execute_block_for_test(+ block: EmailInboxBlock,+ *,+ workflow_run_id: str = "wr_test",+ organization_id: str = "org_1",+) -> BlockResult:+ ctx = _FakeContextForTest(organization_id=organization_id)++ async def _fake_build(self: Block, **kwargs: Any) -> BlockResult:+ return BlockResult(+ success=kwargs.get("success", False),+ failure_reason=kwargs.get("failure_reason"),+ output_parameter=self.output_parameter,+ output_parameter_value=kwargs.get("output_parameter_value"),+ status=kwargs.get("status", BlockStatus.failed),+ workflow_run_block_id=kwargs.get("workflow_run_block_id"),+ )++ with (+ patch.object(EmailInboxBlock, "get_workflow_run_context", staticmethod(lambda _wr_id: ctx)),+ patch.object(EmailInboxBlock, "record_output_parameter_value", new=AsyncMock(return_value=None)),+ patch.object(EmailInboxBlock, "build_block_result", new=_fake_build),+ ):+ return await block.execute(+ workflow_run_id=workflow_run_id,+ workflow_run_block_id="wrb_test",+ organization_id=organization_id,+ )+++def _messages() -> list[EmailMessage]:+ return [+ EmailMessage(+ id="msg_1",+ thread_id="thread_1",+ subject="First",+ from_email="[email protected]",+ snippet="first snippet",+ body_text="first body",+ ),+ EmailMessage(+ id="msg_2",+ thread_id="thread_2",+ subject="Second",+ from_email="[email protected]",+ snippet="second snippet",+ body_text="second body",+ ),+ ]+++async def test_execute_reads_gmail_messages(monkeypatch: pytest.MonkeyPatch) -> None:+ list_messages = AsyncMock(return_value=_messages())+ monkeypatch.setattr(+ app.AGENT_FUNCTION, "get_google_workspace_credentials", AsyncMock(return_value=SimpleNamespace(token="AT"))+ )+ monkeypatch.setattr(email, "list_folder_messages", list_messages)++ result = await _execute_block_for_test(_make_block(folder="INBOX"))++ assert result.success is True+ assert result.output_parameter_value is not None+ assert result.output_parameter_value["email_client"] == "gmail"+ assert result.output_parameter_value["folder"] == "INBOX"+ assert result.output_parameter_value["candidate_count"] == 2+ assert result.output_parameter_value["matched_count"] == 2+ assert [email["id"] for email in result.output_parameter_value["emails"]] == ["msg_1", "msg_2"]+ list_messages.assert_awaited_once()+ assert list_messages.await_args.kwargs["email_client"] == "gmail"+ assert list_messages.await_args.kwargs["folder"] == "INBOX"+++async def test_execute_reads_outlook_messages(monkeypatch: pytest.MonkeyPatch) -> None:+ list_messages = AsyncMock(return_value=_messages())+ monkeypatch.setattr(app.AGENT_FUNCTION, "get_microsoft_credentials", AsyncMock(return_value="AT"), raising=False)+ monkeypatch.setattr(email, "list_folder_messages", list_messages)++ result = await _execute_block_for_test(_make_block(email_client="outlook", folder="inbox"))++ assert result.success is True+ assert result.output_parameter_value is not None+ assert result.output_parameter_value["email_client"] == "outlook"+ assert result.output_parameter_value["folder"] == "inbox"+ assert result.output_parameter_value["candidate_count"] == 2+ assert result.output_parameter_value["matched_count"] == 2+ assert [email["id"] for email in result.output_parameter_value["emails"]] == ["msg_1", "msg_2"]+ list_messages.assert_awaited_once()+ assert list_messages.await_args.kwargs["email_client"] == "outlook"+ assert list_messages.await_args.kwargs["folder"] == "inbox"+++async def test_execute_filters_with_prompt_preserving_order(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ app.AGENT_FUNCTION, "get_google_workspace_credentials", AsyncMock(return_value=SimpleNamespace(token="AT"))+ )+ monkeypatch.setattr(email, "list_folder_messages", AsyncMock(return_value=_messages()))++ async def match_email(*, criteria: str, email: EmailMessage, organization_id: str) -> bool:+ return email.id == "msg_2"++ monkeypatch.setattr(email, "match_email", match_email)++ result = await _execute_block_for_test(_make_block(prompt="Find the second email"))++ assert result.success is True+ assert result.output_parameter_value is not None+ assert result.output_parameter_value["candidate_count"] == 2+ assert result.output_parameter_value["matched_count"] == 1+ assert [email["id"] for email in result.output_parameter_value["emails"]] == ["msg_2"]+++async def test_execute_missing_credential_fails() -> None:+ result = await _execute_block_for_test(_make_block(credential_id=None))++ assert result.success is False+ assert result.status == BlockStatus.failed+ assert result.failure_reason == "credential_id is required"+++async def test_execute_reconnect_required_failure(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ app.AGENT_FUNCTION, "get_google_workspace_credentials", AsyncMock(return_value=SimpleNamespace(token="AT"))+ )+ monkeypatch.setattr(+ email,+ "list_folder_messages",+ AsyncMock(+ side_effect=email.GmailAPIError(+ status=403,+ code="reconnect_required",+ message="Insufficient scopes",+ )+ ),+ )++ result = await _execute_block_for_test(_make_block())++ assert result.success is False+ assert result.status == BlockStatus.failed+ assert result.failure_reason == "Reconnect the Gmail account: Insufficient scopes"+ assert result.output_parameter_value == {+ "status_code": 403,+ "code": "reconnect_required",+ "error": "Insufficient scopes",+ }+++def test_email_inbox_yaml_workflow_converts_to_runtime_block() -> None:+ output = _make_output_parameter("read_email")+ definition = WorkflowDefinitionYAML.model_validate(+ {+ "parameters": [],+ "blocks": [+ {+ "block_type": "email_inbox",+ "label": "read_email",+ "email_client": "gmail",+ "credential_id": "{{ gmail_credential_id }}",+ "folder": "INBOX",+ "prompt": "Find receipts",+ "sender": "[email protected]",+ "subject": "receipt",+ "newer_than_days": 7,+ "max_results": 10,+ "include_body": False,+ }+ ],+ }+ )+ block_yaml = definition.blocks[0]+ assert isinstance(block_yaml, EmailInboxBlockYAML)++ block = block_yaml_to_block(block_yaml, {output.key: output})++ assert isinstance(block, EmailInboxBlock)+ assert block.email_client == "gmail"+ assert block.credential_id == "{{ gmail_credential_id }}"+ assert block.folder == "INBOX"+ assert block.prompt == "Find receipts"+ assert block.sender == "[email protected]"+ assert block.subject == "receipt"+ assert block.newer_than_days == 7+ assert block.max_results == 10+ assert block.include_body is Falsediff --git a/tests/unit/test_email_service.py b/tests/unit/test_email_service.pynew file mode 100644index 000000000..22e960de1--- /dev/null+++ b/tests/unit/test_email_service.py@@ -0,0 +1,713 @@+from __future__ import annotations++from typing import Any++import httpx+import pytest++from skyvern.services import email+from skyvern.services.email import gmail_client+++async def test_match_email_propagates_llm_failure(monkeypatch: pytest.MonkeyPatch) -> None:+ async def fail_llm(**_kwargs: Any) -> dict[str, Any]:+ raise RuntimeError("LLM unavailable")++ monkeypatch.setattr(email.inbox.app, "SECONDARY_LLM_API_HANDLER", fail_llm)++ with pytest.raises(RuntimeError, match="LLM unavailable"):+ await email.match_email(+ criteria="invoice",+ email=email.EmailMessage(id="msg-1", subject="Invoice"),+ organization_id="org-1",+ )+++def _mock_response(status_code: int, *, json: dict[str, Any] | None = None) -> httpx.Response:+ return httpx.Response(status_code, json=json or {})+++def test_gmail_build_folder_query_quotes_untrusted_values() -> None:+ query = email.gmail._build_folder_query("x OR label:SENT newer_than:10y", 'a" OR b', 3)++ assert query == 'from:"x OR label:SENT newer_than:10y" subject:"a OR b" newer_than:3d'+ assert email.gmail._quote_gmail_value('a" \\ b') == '"a b"'+ assert email.gmail._quote_gmail_value(' " \\ ') is None+ assert "from:x OR label:SENT" not in query+ assert 'subject:a" OR b' not in query+ assert 'subject:"a OR b"' in query+++def test_gmail_build_folder_query_clamps_newer_than_days() -> None:+ assert email.gmail._build_folder_query(None, None, 0) == "newer_than:1d"+++async def test_gmail_list_folder_messages_uses_escaped_query(monkeypatch: pytest.MonkeyPatch) -> None:+ captured_query = None++ async def fake_get_json(+ client: httpx.AsyncClient,+ url: str,+ *,+ access_token: str,+ params: dict[str, Any] | None = None,+ ) -> dict[str, Any]:+ nonlocal captured_query+ if url.endswith("/users/me/messages"):+ captured_query = (params or {}).get("q")+ return {"messages": [{"id": "msg_1"}]}+ return {+ "id": "msg_1",+ "threadId": "thread_1",+ "labelIds": ["INBOX"],+ "snippet": "snippet",+ "payload": {"headers": [{"name": "Subject", "value": "subject"}]},+ }++ monkeypatch.setattr(email.gmail, "get_json", fake_get_json)++ messages = await email.gmail.list_folder_messages(+ access_token="AT",+ label="INBOX",+ sender="x OR label:SENT newer_than:10y",+ subject='a" OR b',+ newer_than_days=10,+ include_body=False,+ )++ assert [message.id for message in messages] == ["msg_1"]+ assert captured_query == 'from:"x OR label:SENT newer_than:10y" subject:"a OR b" newer_than:10d'+ assert "from:x OR label:SENT" not in captured_query+ assert 'subject:a" OR b' not in captured_query+ assert messages[0].has_attachments is None+ assert messages[0].web_link == "https://mail.google.com/mail/u/0/#all/thread_1"+++async def test_gmail_list_folder_messages_sets_include_spam_trash(monkeypatch: pytest.MonkeyPatch) -> None:+ captured: dict[str, str] = {}++ async def fake_get_json(+ client: httpx.AsyncClient,+ url: str,+ *,+ access_token: str,+ params: dict[str, Any] | None = None,+ ) -> dict[str, Any]:+ if url.endswith("/users/me/messages"):+ captured[str((params or {}).get("labelIds"))] = str((params or {}).get("includeSpamTrash"))+ return {"messages": []}++ monkeypatch.setattr(email.gmail, "get_json", fake_get_json)++ await email.gmail.list_folder_messages(access_token="AT", label="TRASH", include_body=False)+ await email.gmail.list_folder_messages(access_token="AT", label="INBOX", include_body=False)++ assert captured == {"TRASH": "true", "INBOX": "false"}+++def test_email_provider_clamp_max_results_boundaries() -> None:+ for provider in (email.gmail, email.outlook):+ assert provider._clamp_max_results(0) == 1+ assert provider._clamp_max_results(100) == 100+ assert provider._clamp_max_results(101) == 100+++async def test_gmail_get_json_retries_429_then_succeeds(monkeypatch: pytest.MonkeyPatch) -> None:+ calls = 0+ sleeps: list[float] = []++ async def fake_sleep(seconds: float) -> None:+ sleeps.append(seconds)++ def handler(_request: httpx.Request) -> httpx.Response:+ nonlocal calls+ calls += 1+ if calls == 1:+ return httpx.Response(429, json={"error": {"message": "rate limited"}}, headers={"Retry-After": "0"})+ return httpx.Response(200, json={"ok": True})++ monkeypatch.setattr(gmail_client.asyncio, "sleep", fake_sleep)++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:+ payload = await gmail_client.get_json(client, "https://gmail.example/messages", access_token="AT")++ assert payload == {"ok": True}+ assert calls == 2+ assert sleeps == [0.0]+++async def test_gmail_get_json_raises_after_retryable_errors(monkeypatch: pytest.MonkeyPatch) -> None:+ calls = 0++ async def fake_sleep(_seconds: float) -> None:+ return None++ def handler(_request: httpx.Request) -> httpx.Response:+ nonlocal calls+ calls += 1+ return httpx.Response(500, json={"error": {"message": "server error"}})++ monkeypatch.setattr(gmail_client.asyncio, "sleep", fake_sleep)++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:+ with pytest.raises(email.GmailAPIError) as exc_info:+ await gmail_client.get_json(client, "https://gmail.example/messages", access_token="AT")++ assert calls == 3+ assert exc_info.value.status == 500+++async def test_outlook_get_json_retries_429_then_succeeds(monkeypatch: pytest.MonkeyPatch) -> None:+ calls = 0+ sleeps: list[float] = []++ async def fake_sleep(seconds: float) -> None:+ sleeps.append(seconds)++ def handler(_request: httpx.Request) -> httpx.Response:+ nonlocal calls+ calls += 1+ if calls == 1:+ return httpx.Response(429, json={"error": {"code": "TooManyRequests"}}, headers={"Retry-After": "0"})+ return httpx.Response(200, json={"ok": True})++ monkeypatch.setattr(email.outlook.asyncio, "sleep", fake_sleep)++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:+ payload = await email.outlook._get_json(client, "https://graph.example/messages", access_token="AT")++ assert payload == {"ok": True}+ assert calls == 2+ assert sleeps == [0.0]+++async def test_outlook_get_json_raises_after_retryable_errors(monkeypatch: pytest.MonkeyPatch) -> None:+ calls = 0++ async def fake_sleep(_seconds: float) -> None:+ return None++ def handler(_request: httpx.Request) -> httpx.Response:+ nonlocal calls+ calls += 1+ return httpx.Response(500, json={"error": {"code": "ServiceUnavailable", "message": "server error"}})++ monkeypatch.setattr(email.outlook.asyncio, "sleep", fake_sleep)++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:+ with pytest.raises(email.OutlookAPIError) as exc_info:+ await email.outlook._get_json(client, "https://graph.example/messages", access_token="AT")++ assert calls == 3+ assert exc_info.value.status == 500+ assert exc_info.value.code == "ServiceUnavailable"+++ ("status_code", "graph_code", "expected_code"),+ [+ (401, "InvalidAuthenticationToken", "reconnect_required"),+ (403, "ErrorAccessDenied", "reconnect_required"),+ (403, "ErrorQuotaExceeded", "ErrorQuotaExceeded"),+ ],+)+async def test_outlook_get_json_reconnect_required_mapping(+ status_code: int,+ graph_code: str,+ expected_code: str,+) -> None:+ def handler(_request: httpx.Request) -> httpx.Response:+ return httpx.Response(status_code, json={"error": {"code": graph_code, "message": "graph error"}})++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:+ with pytest.raises(email.OutlookAPIError) as exc_info:+ await email.outlook._get_json(client, "https://graph.example/messages", access_token="AT")++ assert exc_info.value.code == expected_code+++async def test_outlook_list_folder_messages_omits_body_when_include_body_false(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ captured_select = None+ attachment_fetch_count = 0++ async def fake_get_json(+ client: httpx.AsyncClient,+ url: str,+ *,+ access_token: str,+ params: dict[str, Any] | None = None,+ ) -> dict[str, Any]:+ nonlocal captured_select, attachment_fetch_count+ if url.endswith("/attachments"):+ attachment_fetch_count += 1+ return {"value": [{"id": "att_1", "name": "receipt.pdf"}]}+ captured_select = (params or {}).get("$select")+ return {+ "value": [+ {+ "id": "msg_1",+ "conversationId": "thread_1",+ "subject": "Receipt",+ "from": {"emailAddress": {"address": "[email protected]", "name": "Sender"}},+ "toRecipients": [],+ "ccRecipients": [],+ "receivedDateTime": "2026-07-09T12:00:00Z",+ "bodyPreview": "preview text",+ "body": {"contentType": "html", "content": "<p>body</p>"},+ "hasAttachments": True,+ "isRead": False,+ "webLink": "https://example.com/message",+ }+ ]+ }++ monkeypatch.setattr(email.outlook, "_get_json", fake_get_json)++ messages = await email.outlook.list_folder_messages(+ access_token="AT",+ folder="inbox",+ include_body=False,+ )++ assert captured_select is not None+ assert "bodyPreview" in captured_select.split(",")+ assert "body" not in captured_select.split(",")+ assert attachment_fetch_count == 0+ assert len(messages) == 1+ assert messages[0].snippet == "preview text"+ assert messages[0].body_text == ""+ assert messages[0].body_html is None+ assert messages[0].attachments == []+++def test_outlook_html_message_uses_full_body_for_prompt_matching() -> None:+ message = email.outlook._message_from_graph(+ {+ "id": "msg_1",+ "bodyPreview": "preview text",+ "body": {"contentType": "html", "content": "<p>full body with matching criteria</p>"},+ },+ [],+ include_body=True,+ )++ assert message is not None+ assert message.snippet == "preview text"+ assert message.body_text == ""+ assert message.body_html == "<p>full body with matching criteria</p>"+++async def test_outlook_list_folder_messages_orders_filter_by_received_datetime(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ captured_params: dict[str, Any] | None = None++ async def fake_get_json(+ client: httpx.AsyncClient,+ url: str,+ *,+ access_token: str,+ params: dict[str, Any] | None = None,+ ) -> dict[str, Any]:+ nonlocal captured_params+ captured_params = params+ return {"value": []}++ monkeypatch.setattr(email.outlook, "_get_json", fake_get_json)++ messages = await email.outlook.list_folder_messages(+ access_token="AT",+ folder="inbox",+ sender="o'[email protected]",+ include_body=False,+ )++ assert messages == []+ assert captured_params is not None+ order_by = captured_params.get("$orderby")+ filter_expression = captured_params.get("$filter")+ assert order_by == "receivedDateTime desc"+ assert isinstance(filter_expression, str)+ assert filter_expression.startswith("receivedDateTime ge 1900-01-01T00:00:00Z")+ assert "from/emailAddress/address eq 'o''[email protected]'" in filter_expression+ assert not filter_expression.startswith("from/emailAddress/address")+++async def test_outlook_list_folder_messages_paginates_for_subject_matches(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ next_link = f"{email.outlook.GRAPH_API_BASE}/me/mailFolders/inbox/messages?$skip=1"+ calls: list[tuple[str, dict[str, Any] | None]] = []++ async def fake_get_json(+ client: httpx.AsyncClient,+ url: str,+ *,+ access_token: str,+ params: dict[str, Any] | None = None,+ ) -> dict[str, Any]:+ calls.append((url, params))+ if url == next_link:+ return {+ "value": [+ {+ "id": "msg_match",+ "conversationId": "thread_2",+ "subject": "Invoice from June",+ "from": {"emailAddress": {"address": "[email protected]"}},+ "toRecipients": [],+ "ccRecipients": [],+ "receivedDateTime": "2026-07-08T12:00:00Z",+ "bodyPreview": "invoice",+ "hasAttachments": False,+ "isRead": True,+ }+ ]+ }+ return {+ "value": [+ {+ "id": "msg_skip",+ "conversationId": "thread_1",+ "subject": "Welcome",+ "from": {"emailAddress": {"address": "[email protected]"}},+ "toRecipients": [],+ "ccRecipients": [],+ "receivedDateTime": "2026-07-09T12:00:00Z",+ "bodyPreview": "welcome",+ "hasAttachments": False,+ "isRead": True,+ }+ ],+ "@odata.nextLink": next_link,+ }++ monkeypatch.setattr(email.outlook, "_get_json", fake_get_json)++ messages = await email.outlook.list_folder_messages(+ access_token="AT",+ folder="inbox",+ subject="invoice",+ max_results=1,+ include_body=False,+ )++ assert [message.id for message in messages] == ["msg_match"]+ assert len(calls) == 2+ assert calls[0][1] is not None+ assert calls[1] == (next_link, None)+++async def test_outlook_list_folder_messages_rejects_untrusted_next_link(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ calls: list[str] = []++ async def fake_get_json(+ client: httpx.AsyncClient,+ url: str,+ *,+ access_token: str,+ params: dict[str, Any] | None = None,+ ) -> dict[str, Any]:+ del client, access_token, params+ calls.append(url)+ return {+ "value": [+ {+ "id": "msg_1",+ "subject": "Invoice",+ "from": {"emailAddress": {"address": "[email protected]"}},+ "toRecipients": [],+ "ccRecipients": [],+ "hasAttachments": False,+ }+ ],+ "@odata.nextLink": "https://evil.example.com/messages?$skip=1",+ }++ monkeypatch.setattr(email.outlook, "_get_json", fake_get_json)++ messages = await email.outlook.list_folder_messages(+ access_token="AT",+ folder="inbox",+ subject="invoice",+ max_results=2,+ include_body=False,+ )++ assert [message.id for message in messages] == ["msg_1"]+ assert len(calls) == 1+++async def test_outlook_subject_pagination_stops_at_page_cap(monkeypatch: pytest.MonkeyPatch) -> None:+ calls: list[str] = []++ async def fake_get_json(+ client: httpx.AsyncClient,+ url: str,+ *,+ access_token: str,+ params: dict[str, Any] | None = None,+ ) -> dict[str, Any]:+ del client, access_token, params+ calls.append(url)+ index = len(calls)+ subject = "Invoice match" if index == 1 else "Welcome"+ return {+ "value": [+ {+ "id": f"msg_{index}",+ "conversationId": f"thread_{index}",+ "subject": subject,+ "from": {"emailAddress": {"address": "[email protected]"}},+ "toRecipients": [],+ "ccRecipients": [],+ "receivedDateTime": "2026-07-09T12:00:00Z",+ "bodyPreview": subject,+ "hasAttachments": False,+ "isRead": True,+ }+ ],+ "@odata.nextLink": f"{email.outlook.GRAPH_API_BASE}/me/mailFolders/inbox/messages?$skip={index}",+ }++ monkeypatch.setattr(email.outlook, "_get_json", fake_get_json)++ messages = await email.outlook.list_folder_messages(+ access_token="AT",+ folder="inbox",+ subject="invoice",+ max_results=2,+ include_body=False,+ )++ assert [message.id for message in messages] == ["msg_1"]+ assert len(calls) == email.outlook._MAX_SUBJECT_FILTER_PAGES+++async def test_outlook_resolve_nested_folder_by_path(monkeypatch: pytest.MonkeyPatch) -> None:+ calls: list[tuple[str, dict[str, Any] | None]] = []++ async def fake_get_json(+ client: httpx.AsyncClient,+ url: str,+ *,+ access_token: str,+ params: dict[str, Any] | None = None,+ ) -> dict[str, Any]:+ del client, access_token+ calls.append((url, params))+ filter_expression = (params or {}).get("$filter")+ if url.endswith("/me/mailFolders") and filter_expression == "displayName eq 'A'":+ return {"value": [{"id": "folder_a", "displayName": "A"}]}+ if url.endswith("/me/mailFolders/folder_a/childFolders") and filter_expression == "displayName eq 'B'":+ return {"value": [{"id": "folder_b", "displayName": "B"}]}+ return {"value": []}++ monkeypatch.setattr(email.outlook, "_get_json", fake_get_json)++ folder_id = await email.outlook._resolve_folder_id(httpx.AsyncClient(), "AT", "A/B")++ assert folder_id == "folder_b"+ assert len(calls) == 2+++async def test_outlook_resolve_nested_folder_by_bare_name_bfs(monkeypatch: pytest.MonkeyPatch) -> None:+ calls: list[tuple[str, dict[str, Any] | None]] = []++ async def fake_get_json(+ client: httpx.AsyncClient,+ url: str,+ *,+ access_token: str,+ params: dict[str, Any] | None = None,+ ) -> dict[str, Any]:+ del client, access_token+ calls.append((url, params))+ if (params or {}).get("$filter") == "displayName eq 'B'":+ return {"value": []}+ if url.endswith("/me/mailFolders"):+ return {"value": [{"id": "folder_a", "displayName": "A"}]}+ if url.endswith("/me/mailFolders/folder_a/childFolders"):+ return {"value": [{"id": "folder_b", "displayName": "B"}]}+ return {"value": []}++ monkeypatch.setattr(email.outlook, "_get_json", fake_get_json)++ folder_id = await email.outlook._resolve_folder_id(httpx.AsyncClient(), "AT", "B")++ assert folder_id == "folder_b"+ assert [call[0] for call in calls] == [+ f"{email.outlook.GRAPH_API_BASE}/me/mailFolders",+ f"{email.outlook.GRAPH_API_BASE}/me/mailFolders",+ f"{email.outlook.GRAPH_API_BASE}/me/mailFolders/folder_a/childFolders",+ ]+++async def test_outlook_resolve_missing_nested_folder_raises(monkeypatch: pytest.MonkeyPatch) -> None:+ async def fake_get_json(+ client: httpx.AsyncClient,+ url: str,+ *,+ access_token: str,+ params: dict[str, Any] | None = None,+ ) -> dict[str, Any]:+ del client, url, access_token, params+ return {"value": []}++ monkeypatch.setattr(email.outlook, "_get_json", fake_get_json)++ with pytest.raises(email.OutlookAPIError) as exc_info:+ await email.outlook._resolve_folder_id(httpx.AsyncClient(), "AT", "A/B")++ assert exc_info.value.status == 404+ assert exc_info.value.code == "folder_not_found"+++async def test_outlook_attachments_follow_next_link(monkeypatch: pytest.MonkeyPatch) -> None:+ next_link = f"{email.outlook.GRAPH_API_BASE}/me/messages/msg_1/attachments?$skip=1"+ calls: list[tuple[str, dict[str, Any] | None]] = []++ async def fake_get_json(+ client: httpx.AsyncClient,+ url: str,+ *,+ access_token: str,+ params: dict[str, Any] | None = None,+ ) -> dict[str, Any]:+ del client, access_token+ calls.append((url, params))+ if url == next_link:+ return {"value": [{"id": "att_2", "name": "b.pdf", "contentType": "application/pdf", "size": 2}]}+ return {+ "value": [{"id": "att_1", "name": "a.pdf", "contentType": "application/pdf", "size": 1}],+ "@odata.nextLink": next_link,+ }++ monkeypatch.setattr(email.outlook, "_get_json", fake_get_json)++ attachments = await email.outlook._attachments(httpx.AsyncClient(), access_token="AT", message_id="msg_1")++ assert [attachment.name for attachment in attachments] == ["a.pdf", "b.pdf"]+ assert calls[0][1] == {"$select": "id,name,contentType,size"}+ assert calls[1] == (next_link, None)+++async def test_outlook_attachments_reject_untrusted_next_link(monkeypatch: pytest.MonkeyPatch) -> None:+ calls: list[str] = []++ async def fake_get_json(+ client: httpx.AsyncClient,+ url: str,+ *,+ access_token: str,+ params: dict[str, Any] | None = None,+ ) -> dict[str, Any]:+ del client, access_token, params+ calls.append(url)+ return {+ "value": [{"id": "att_1", "name": "a.pdf", "contentType": "application/pdf", "size": 1}],+ "@odata.nextLink": "https://evil.example.com/attachments?$skip=1",+ }++ monkeypatch.setattr(email.outlook, "_get_json", fake_get_json)++ attachments = await email.outlook._attachments(httpx.AsyncClient(), access_token="AT", message_id="msg_1")++ assert [attachment.name for attachment in attachments] == ["a.pdf"]+ assert len(calls) == 1+++async def test_outlook_list_folder_messages_raises_when_attachment_fetch_requires_reconnect() -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ if request.url.path.endswith("/attachments"):+ return httpx.Response(+ 401,+ json={"error": {"code": "InvalidAuthenticationToken", "message": "token expired"}},+ )+ return httpx.Response(+ 200,+ json={+ "value": [+ {+ "id": "msg_1",+ "subject": "Invoice",+ "from": {"emailAddress": {"address": "[email protected]"}},+ "toRecipients": [],+ "ccRecipients": [],+ "hasAttachments": True,+ }+ ]+ },+ )++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:+ with pytest.raises(email.OutlookAPIError) as exc_info:+ await email.outlook.list_folder_messages(access_token="AT", include_body=True, client=client)++ assert exc_info.value.code == "reconnect_required"+++async def test_outlook_list_folder_messages_keeps_message_when_attachment_fetch_fails_after_retries(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ attachment_calls = 0++ async def fake_sleep(_seconds: float) -> None:+ return None++ def handler(request: httpx.Request) -> httpx.Response:+ nonlocal attachment_calls+ if request.url.path.endswith("/attachments"):+ attachment_calls += 1+ return httpx.Response(+ 500,+ json={"error": {"code": "ServiceUnavailable", "message": "server error"}},+ )+ return httpx.Response(+ 200,+ json={+ "value": [+ {+ "id": "msg_1",+ "subject": "Invoice",+ "from": {"emailAddress": {"address": "[email protected]"}},+ "toRecipients": [],+ "ccRecipients": [],+ "hasAttachments": True,+ }+ ]+ },+ )++ monkeypatch.setattr(email.outlook.asyncio, "sleep", fake_sleep)++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:+ messages = await email.outlook.list_folder_messages(access_token="AT", include_body=True, client=client)++ assert attachment_calls == 3+ assert [message.id for message in messages] == ["msg_1"]+ assert messages[0].attachments == []diff --git a/tests/unit/test_mcp_block_type_parity.py b/tests/unit/test_mcp_block_type_parity.pyindex c558f60fd..99d8bb925 100644--- a/tests/unit/test_mcp_block_type_parity.py+++ b/tests/unit/test_mcp_block_type_parity.py@@ -109,6 +109,13 @@ _KNOWN_DRIFT_ALLOWLIST: tuple[BlockDriftEntry, ...] = (added_at=date(2026, 7, 8),notes="Fern SDK regen happens via CI post-deploy",),+ BlockDriftEntry(+ block_type="email_inbox",+ ticket="SKY-12068",+ owner="@suchintan",+ added_at=date(2026, 7, 8),+ notes="Fern SDK regen happens via CI post-deploy",+ ),)diff --git a/tests/unit/test_microsoft_oauth_service.py b/tests/unit/test_microsoft_oauth_service.pynew file mode 100644index 000000000..5697f6150--- /dev/null+++ b/tests/unit/test_microsoft_oauth_service.py@@ -0,0 +1,390 @@+import datetime+from types import SimpleNamespace+from typing import Any, Awaitable, Callable+from unittest.mock import AsyncMock+from urllib.parse import parse_qs, urlparse++import httpx+import pytest+from fastapi import HTTPException++from skyvern.forge.sdk.db.repositories.microsoft_oauth import PendingConsentContext+from skyvern.forge.sdk.routes import microsoft_oauth as microsoft_oauth_routes+from skyvern.forge.sdk.schemas.microsoft_oauth import CreateMicrosoftOAuthCallbackRequest+from skyvern.forge.sdk.services import microsoft_oauth_service+++def _install_microsoft_transport(+ monkeypatch: pytest.MonkeyPatch,+ handler: Callable[[httpx.Request], httpx.Response | Awaitable[httpx.Response]],+) -> None:+ transport = httpx.MockTransport(handler)+ real_client = httpx.AsyncClient++ def fake_async_client(*args: Any, **kwargs: Any) -> httpx.AsyncClient:+ kwargs["transport"] = transport+ return real_client(*args, **kwargs)++ monkeypatch.setattr(microsoft_oauth_service.httpx, "AsyncClient", fake_async_client)+++def test_build_authorize_url_includes_required_params(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(microsoft_oauth_service.settings, "MICROSOFT_OAUTH_CLIENT_ID", "cid", raising=False)+ monkeypatch.setattr(microsoft_oauth_service.settings, "MICROSOFT_OAUTH_CLIENT_SECRET", "secret", raising=False)+ monkeypatch.setattr(microsoft_oauth_service.settings, "MICROSOFT_OAUTH_TENANT", "common", raising=False)+ monkeypatch.setattr(microsoft_oauth_service.settings, "MICROSOFT_OAUTH_REDIRECT_HOSTS", ["app"], raising=False)++ url, code_verifier = microsoft_oauth_service.build_authorize_url(+ redirect_uri="https://app/settings/microsoft/callback",+ state="abc123",+ )++ parsed = urlparse(url)+ assert f"{parsed.scheme}://{parsed.netloc}{parsed.path}" == (+ "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"+ )+ params = {k: v[0] for k, v in parse_qs(parsed.query).items()}+ assert params["client_id"] == "cid"+ assert params["response_type"] == "code"+ assert params["redirect_uri"] == "https://app/settings/microsoft/callback"+ assert params["response_mode"] == "query"+ assert params["scope"] == " ".join(microsoft_oauth_service.OUTLOOK_MAIL_SCOPES)+ assert "offline_access" in params["scope"].split()+ assert params["state"] == "abc123"+ assert params["code_challenge_method"] == "S256"+ assert params["prompt"] == "select_account"+ assert params["code_challenge"]+ assert code_verifier and len(code_verifier) >= 43+++def test_pkce_challenge_derivation(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(microsoft_oauth_service.settings, "MICROSOFT_OAUTH_CLIENT_ID", "cid", raising=False)+ monkeypatch.setattr(microsoft_oauth_service.settings, "MICROSOFT_OAUTH_CLIENT_SECRET", "secret", raising=False)+ monkeypatch.setattr(microsoft_oauth_service.settings, "MICROSOFT_OAUTH_REDIRECT_HOSTS", ["app"], raising=False)++ verifier = "fixed-verifier"+ url, returned_verifier = microsoft_oauth_service.build_authorize_url(+ redirect_uri="https://app/cb",+ state="state",+ code_verifier=verifier,+ )++ params = {k: v[0] for k, v in parse_qs(urlparse(url).query).items()}+ assert returned_verifier == verifier+ assert params["code_challenge"] == microsoft_oauth_service._code_challenge_for_verifier(verifier)+ assert params["code_challenge"] == "7MosA1dS6hiqNcSny0SqUWJbJo82pR0lNczg5YZ-GLI"+++def test_scopes_for_profile() -> None:+ assert microsoft_oauth_service.scopes_for_profile(None) == list(microsoft_oauth_service.OUTLOOK_MAIL_SCOPES)+ assert microsoft_oauth_service.scopes_for_profile("outlook_mail") == list(+ microsoft_oauth_service.OUTLOOK_MAIL_SCOPES+ )+ with pytest.raises(microsoft_oauth_service.UnsupportedScopeProfileError):+ microsoft_oauth_service.scopes_for_profile("calendar")+++def test_has_required_scopes_matches_trailing_segments() -> None:+ granted = ["https://graph.microsoft.com/Mail.Read", "https://graph.microsoft.com/User.Read"]+ assert microsoft_oauth_service.has_required_scopes(granted, ["Mail.Read"])+ assert microsoft_oauth_service.has_required_scopes(granted, ["https://graph.microsoft.com/Mail.Read"])+ assert microsoft_oauth_service.has_required_scopes(["Mail.Read"], ["https://graph.microsoft.com/Mail.Read"])+ assert not microsoft_oauth_service.has_required_scopes(["Mail.Read"], ["Mail.Send"])+++def test_validate_redirect_uri_allowlist(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ microsoft_oauth_service.settings,+ "MICROSOFT_OAUTH_REDIRECT_HOSTS",+ ["app.skyvern.com"],+ raising=False,+ )++ microsoft_oauth_service._validate_redirect_uri("https://app.skyvern.com/microsoft/callback")++ with pytest.raises(microsoft_oauth_service.InvalidRedirectURIError):+ microsoft_oauth_service._validate_redirect_uri("https://evil.example.com/callback")+++def test_validate_redirect_uri_rejects_http_for_non_loopback(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ microsoft_oauth_service.settings,+ "MICROSOFT_OAUTH_REDIRECT_HOSTS",+ ["app.skyvern.com"],+ raising=False,+ )++ with pytest.raises(microsoft_oauth_service.InvalidRedirectURIError, match="https"):+ microsoft_oauth_service._validate_redirect_uri("http://app.skyvern.com/callback")+++def test_validate_app_origin_allowlist(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ microsoft_oauth_service.settings,+ "MICROSOFT_OAUTH_APP_ORIGINS",+ ["https://app.skyvern.com", "*.vercel.app"],+ raising=False,+ )++ microsoft_oauth_service._validate_app_origin("https://app.skyvern.com")+ microsoft_oauth_service._validate_app_origin("https://preview.vercel.app:3000")++ with pytest.raises(microsoft_oauth_service.InvalidAppOriginError):+ microsoft_oauth_service._validate_app_origin("https://vercel.app")+ with pytest.raises(microsoft_oauth_service.InvalidAppOriginError):+ microsoft_oauth_service._validate_app_origin("https://evil.example.com")+++async def test_exchange_code_for_tokens_posts_form(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(microsoft_oauth_service.settings, "MICROSOFT_OAUTH_CLIENT_ID", "cid", raising=False)+ monkeypatch.setattr(microsoft_oauth_service.settings, "MICROSOFT_OAUTH_CLIENT_SECRET", "secret", raising=False)+ monkeypatch.setattr(microsoft_oauth_service.settings, "MICROSOFT_OAUTH_TENANT", "tenant-1", raising=False)+ captured: dict[str, str] = {}++ def handler(request: httpx.Request) -> httpx.Response:+ captured["url"] = str(request.url)+ captured["content_type"] = request.headers["content-type"]+ captured["body"] = request.content.decode()+ return httpx.Response(+ 200,+ json={+ "access_token": "at",+ "refresh_token": "rt",+ "expires_in": 3600,+ "scope": "Mail.Read User.Read",+ "id_token": "id",+ },+ )++ _install_microsoft_transport(monkeypatch, handler)++ result = await microsoft_oauth_service.exchange_code_for_tokens(+ code="code-1",+ redirect_uri="https://app/cb",+ code_verifier="verifier-1",+ )++ assert result["access_token"] == "at"+ assert result["refresh_token"] == "rt"+ assert captured["url"] == "https://login.microsoftonline.com/tenant-1/oauth2/v2.0/token"+ assert captured["content_type"] == "application/x-www-form-urlencoded"+ form = {k: v[0] for k, v in parse_qs(captured["body"]).items()}+ assert form["client_id"] == "cid"+ assert form["client_secret"] == "secret"+ assert form["grant_type"] == "authorization_code"+ assert form["code"] == "code-1"+ assert form["redirect_uri"] == "https://app/cb"+ assert form["code_verifier"] == "verifier-1"+ assert form["scope"] == " ".join(microsoft_oauth_service.OUTLOOK_MAIL_SCOPES)+++async def test_exchange_code_for_tokens_requires_refresh_token(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(microsoft_oauth_service.settings, "MICROSOFT_OAUTH_CLIENT_ID", "cid", raising=False)+ monkeypatch.setattr(microsoft_oauth_service.settings, "MICROSOFT_OAUTH_CLIENT_SECRET", "secret", raising=False)++ def handler(_request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json={"access_token": "at", "scope": "Mail.Read"})++ _install_microsoft_transport(monkeypatch, handler)++ with pytest.raises(microsoft_oauth_service.MicrosoftOAuthError, match="refresh_token"):+ await microsoft_oauth_service.exchange_code_for_tokens(+ code="code-1",+ redirect_uri="https://app/cb",+ code_verifier="verifier-1",+ )+++async def test_refresh_access_token_posts_form_and_ignores_rotation(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(microsoft_oauth_service.settings, "MICROSOFT_OAUTH_CLIENT_ID", "cid", raising=False)+ monkeypatch.setattr(microsoft_oauth_service.settings, "MICROSOFT_OAUTH_CLIENT_SECRET", "secret", raising=False)+ captured: dict[str, str] = {}++ def handler(request: httpx.Request) -> httpx.Response:+ captured["body"] = request.content.decode()+ return httpx.Response(+ 200,+ json={+ "access_token": "at-refreshed",+ "refresh_token": "rt-rotated",+ "expires_in": 3600,+ "scope": "Mail.Read",+ },+ )++ _install_microsoft_transport(monkeypatch, handler)++ result = await microsoft_oauth_service.refresh_access_token("rt-1", scopes=["Mail.Read"])++ assert result["access_token"] == "at-refreshed"+ assert result["refresh_token"] == "rt-rotated"+ form = {k: v[0] for k, v in parse_qs(captured["body"]).items()}+ assert form["grant_type"] == "refresh_token"+ assert form["refresh_token"] == "rt-1"+ assert form["scope"].split() == ["Mail.Read", "offline_access"]+++async def test_refresh_and_rotate_persists_rotated_refresh_token(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(microsoft_oauth_service.settings, "MICROSOFT_OAUTH_CLIENT_ID", "cid", raising=False)+ monkeypatch.setattr(microsoft_oauth_service.settings, "MICROSOFT_OAUTH_CLIENT_SECRET", "secret", raising=False)++ def handler(_request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 200,+ json={+ "access_token": "at-refreshed",+ "refresh_token": "rt-rotated",+ "expires_in": 3600,+ "scope": "Mail.Read",+ },+ )++ _install_microsoft_transport(monkeypatch, handler)+ update_active_refresh_token = AsyncMock()+ repository = SimpleNamespace(update_active_refresh_token=update_active_refresh_token)+ monkeypatch.setattr(microsoft_oauth_service.app, "DATABASE", SimpleNamespace(microsoft_oauth=repository))+ encrypt = AsyncMock(return_value="encrypted-rt-rotated")+ monkeypatch.setattr(microsoft_oauth_service, "encryptor", SimpleNamespace(encrypt=encrypt))++ access_token = await microsoft_oauth_service.refresh_and_rotate(+ organization_id="org-1",+ credential_id="cred-1",+ credential_secrets=microsoft_oauth_service.MicrosoftCredentialSecrets(+ refresh_token="rt-original",+ scopes=["Mail.Read"],+ ),+ )++ assert access_token == "at-refreshed"+ encrypt.assert_awaited_once_with("rt-rotated", microsoft_oauth_service.EncryptMethod.AES)+ update_active_refresh_token.assert_awaited_once()+ kwargs = update_active_refresh_token.await_args.kwargs+ assert kwargs["organization_id"] == "org-1"+ assert kwargs["credential_id"] == "cred-1"+ assert kwargs["encrypted_refresh_token"] == "encrypted-rt-rotated"+ assert kwargs["encrypted_method"] == microsoft_oauth_service.EncryptMethod.AES+ assert isinstance(kwargs["now"], datetime.datetime)+++async def test_refresh_and_rotate_propagates_rotated_token_persist_failure(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ microsoft_oauth_service,+ "refresh_access_token",+ AsyncMock(return_value={"access_token": "at-refreshed", "refresh_token": "rt-rotated"}),+ )+ repository = SimpleNamespace(+ update_active_refresh_token=AsyncMock(side_effect=RuntimeError("database unavailable"))+ )+ monkeypatch.setattr(microsoft_oauth_service.app, "DATABASE", SimpleNamespace(microsoft_oauth=repository))+ monkeypatch.setattr(+ microsoft_oauth_service,+ "encryptor",+ SimpleNamespace(encrypt=AsyncMock(return_value="encrypted-rt-rotated")),+ )++ with pytest.raises(RuntimeError, match="database unavailable"):+ await microsoft_oauth_service.refresh_and_rotate(+ organization_id="org-1",+ credential_id="cred-1",+ credential_secrets=microsoft_oauth_service.MicrosoftCredentialSecrets(+ refresh_token="rt-original",+ scopes=["Mail.Read"],+ ),+ )++[email protected]("refresh_token", ["rt-original", None])+async def test_refresh_and_rotate_skips_persist_without_new_refresh_token(+ monkeypatch: pytest.MonkeyPatch,+ refresh_token: str | None,+) -> None:+ monkeypatch.setattr(microsoft_oauth_service.settings, "MICROSOFT_OAUTH_CLIENT_ID", "cid", raising=False)+ monkeypatch.setattr(microsoft_oauth_service.settings, "MICROSOFT_OAUTH_CLIENT_SECRET", "secret", raising=False)+ response_json: dict[str, str | int] = {+ "access_token": "at-refreshed",+ "expires_in": 3600,+ "scope": "Mail.Read",+ }+ if refresh_token is not None:+ response_json["refresh_token"] = refresh_token++ def handler(_request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json=response_json)++ _install_microsoft_transport(monkeypatch, handler)+ update_active_refresh_token = AsyncMock()+ repository = SimpleNamespace(update_active_refresh_token=update_active_refresh_token)+ monkeypatch.setattr(microsoft_oauth_service.app, "DATABASE", SimpleNamespace(microsoft_oauth=repository))+ encrypt = AsyncMock(return_value="encrypted-rt-rotated")+ monkeypatch.setattr(microsoft_oauth_service, "encryptor", SimpleNamespace(encrypt=encrypt))++ access_token = await microsoft_oauth_service.refresh_and_rotate(+ organization_id="org-1",+ credential_id="cred-1",+ credential_secrets=microsoft_oauth_service.MicrosoftCredentialSecrets(+ refresh_token="rt-original",+ scopes=["Mail.Read"],+ ),+ )++ assert access_token == "at-refreshed"+ encrypt.assert_not_awaited()+ update_active_refresh_token.assert_not_awaited()+++async def test_invalid_grant_raises_reconnect_message(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(microsoft_oauth_service.settings, "MICROSOFT_OAUTH_CLIENT_ID", "cid", raising=False)+ monkeypatch.setattr(microsoft_oauth_service.settings, "MICROSOFT_OAUTH_CLIENT_SECRET", "secret", raising=False)++ def handler(_request: httpx.Request) -> httpx.Response:+ return httpx.Response(400, json={"error": "invalid_grant", "error_description": "expired"})++ _install_microsoft_transport(monkeypatch, handler)++ with pytest.raises(microsoft_oauth_service.MicrosoftOAuthError, match="Reconnect"):+ await microsoft_oauth_service.refresh_access_token("rt-1")+++async def test_callback_rejects_missing_mail_read_before_promoting(monkeypatch: pytest.MonkeyPatch) -> None:+ promote = AsyncMock()+ monkeypatch.setattr(+ microsoft_oauth_routes.microsoft_oauth_service,+ "load_pending_consent_context",+ AsyncMock(+ return_value=PendingConsentContext(+ credential_id="cred_1",+ consent_redirect_uri="https://app/cb",+ consent_code_verifier="verifier",+ consent_app_origin="https://app",+ scopes_requested=["Mail.Read", "offline_access"],+ )+ ),+ )+ monkeypatch.setattr(+ microsoft_oauth_routes.microsoft_oauth_service,+ "exchange_code_for_tokens",+ AsyncMock(return_value={"refresh_token": "rt", "scope": "User.Read offline_access"}),+ )+ monkeypatch.setattr(microsoft_oauth_routes.microsoft_oauth_service, "promote_pending_credential", promote)++ with pytest.raises(HTTPException) as exc_info:+ await microsoft_oauth_routes.microsoft_oauth_callback(+ CreateMicrosoftOAuthCallbackRequest(code="code", state="state"),+ SimpleNamespace(organization_id="org_1"),+ )++ assert exc_info.value.status_code == 400+ assert exc_info.value.detail == (+ "Microsoft did not grant Mail.Read. Please re-connect and accept all requested permissions."+ )+ promote.assert_not_awaited()