Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Back off failed plan-tier reads (SKY-7437) (#8777)
Aaron Perezba27d8043197
diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.tsindex d1cb734f4..6c4260f6e 100644--- a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts@@ -818,6 +818,7 @@ const TOOL_CALL_KINDS: Record<string, ToolCallKind> = {validate_block: "other",inspect_current_workflow: "other",list_integrations: "other",+ read_google_sheet: "other",get_organization_usage_quota: "other",extend_browser_session: "other",search_web: "other",diff --git a/skyvern/forge/sdk/copilot/blocker_signal.py b/skyvern/forge/sdk/copilot/blocker_signal.pyindex 46c3b37af..2931c621f 100644--- a/skyvern/forge/sdk/copilot/blocker_signal.py+++ b/skyvern/forge/sdk/copilot/blocker_signal.py@@ -87,6 +87,7 @@ _INTERNAL_TOOL_NAME_TOKENS: tuple[str, ...] = ("get_browser_screenshot","list_credentials","list_integrations",+ "read_google_sheet",)diff --git a/skyvern/forge/sdk/copilot/browser_ablation.py b/skyvern/forge/sdk/copilot/browser_ablation.pyindex 6e3853dd8..bc121f96f 100644--- a/skyvern/forge/sdk/copilot/browser_ablation.py+++ b/skyvern/forge/sdk/copilot/browser_ablation.py@@ -71,6 +71,7 @@ BROWSER_ABLATION_PROMPT_TEMPLATE = "workflow-copilot-browser-ablation.j2"BROWSER_ABLATION_NATIVE_TOOLS = ("list_credentials","list_integrations",+ "read_google_sheet","discover_workflow_entrypoint","inspect_page_for_composition","inspect_locator_matches",diff --git a/skyvern/forge/sdk/copilot/hooks.py b/skyvern/forge/sdk/copilot/hooks.pyindex a45ea38e1..ef8f5a91f 100644--- a/skyvern/forge/sdk/copilot/hooks.py+++ b/skyvern/forge/sdk/copilot/hooks.py@@ -214,6 +214,17 @@ class CopilotRunHooks(RunHooksBase):]activity_entry["integrations"] = integrations+ if tool_name == "read_google_sheet" and parsed.get("ok"):+ data = parsed.get("data") or {}+ rows = data.get("connections", []) if isinstance(data, dict) else []+ activity_entry["opened_connection_ids"] = [+ row["connection_id"]+ for row in (rows if isinstance(rows, list) else [])+ if isinstance(row, dict)+ and row.get("status") == "opened"+ and isinstance(row.get("connection_id"), str)+ ]+if tool_name in _BLOCK_OUTPUT_TOOLS and parsed.get("ok"):data = parsed.get("data") or {}blocks = data.get("blocks", []) if isinstance(data, dict) else []diff --git a/skyvern/forge/sdk/copilot/narration.py b/skyvern/forge/sdk/copilot/narration.pyindex 6124f93ef..7fe1511a0 100644--- a/skyvern/forge/sdk/copilot/narration.py+++ b/skyvern/forge/sdk/copilot/narration.py@@ -48,6 +48,7 @@ _TOOL_ACTIVITY_DISPLAY_LABELS = {"get_block_schema": "Checking workflow block options","get_workflow_knowledge": "Looking up workflow guidance","list_integrations": "Checking connected integrations",+ "read_google_sheet": "Reading the Google Sheet","get_organization_usage_quota": "Checking account usage","inspect_current_workflow": "Inspecting workflow","discover_workflow_entrypoint": "Finding the entry page",diff --git a/skyvern/forge/sdk/copilot/output_utils.py b/skyvern/forge/sdk/copilot/output_utils.pyindex cd27d0e30..aae8c4e97 100644--- a/skyvern/forge/sdk/copilot/output_utils.py+++ b/skyvern/forge/sdk/copilot/output_utils.py@@ -2162,6 +2162,18 @@ def summarize_tool_result(tool_name: str, result: dict[str, Any], *, for_displayreturn f"Found {data.get('count', 0)} credential(s)"if tool_name == "list_integrations":return f"Found {data.get('count', 0)} connected integration(s)"+ if tool_name == "read_google_sheet":+ rows = data.get("connections")+ opened = (+ sum(1 for row in rows if isinstance(row, dict) and row.get("status") == "opened")+ if isinstance(rows, list)+ else 0+ )+ if not opened:+ return "No connection opened the Google Sheet"+ if data.get("values_error"):+ return f"Opened the Google Sheet through {opened} connection(s), but could not read its values"+ return f"Read the Google Sheet through {opened} connection(s)"if tool_name == "get_block_schema":if "block_types" in data:return f"Listed {data.get('count', '?')} block types"diff --git a/skyvern/forge/sdk/copilot/request_policy.py b/skyvern/forge/sdk/copilot/request_policy.pyindex 791de7637..ab2e7a653 100644--- a/skyvern/forge/sdk/copilot/request_policy.py+++ b/skyvern/forge/sdk/copilot/request_policy.py@@ -67,6 +67,7 @@ from skyvern.forge.sdk.schemas.workflow_copilot import ()from skyvern.forge.sdk.services import google_oauth_servicefrom skyvern.forge.sdk.workflow.models.parameter import ParameterType+from skyvern.schemas.google_sheets import extract_spreadsheet_idfrom skyvern.utils.strings import escape_code_fencesfrom skyvern.utils.yaml_loader import safe_load_no_dates@@ -965,6 +966,8 @@ class RequestPolicy:# The ordinary user message or accepted interactive response each URL came from, so a release# records truthful provenance without retaining or logging the response text.user_site_url_sources: dict[str, SiteURLSource] = field(default_factory=dict)+ # Spreadsheet ids from every URL the user wrote, not one per origin: two sheets share an origin.+ user_provided_spreadsheet_ids: list[str] = field(default_factory=list)existing_workflow_credential_ids: list[str] = field(default_factory=list)# Read from the saved workflow row, never from the submitted YAML. The submission is the live# canvas, which carries a copilot proposal the user has not accepted, so it cannot grant a run.@@ -4181,6 +4184,13 @@ def _persisted_question_response_url_texts(raw_interaction: dict[str, Any]) -> lreturn _accepted_question_response_url_texts(interaction)+def _spreadsheet_id_in_url(url: str) -> str | None:+ try:+ return extract_spreadsheet_id(url)+ except ValueError:+ return None++def _project_user_provided_sites(policy: RequestPolicy,url_texts: Sequence[_SiteURLText],@@ -4191,12 +4201,18 @@ def _project_user_provided_sites(if reset:policy.user_provided_site_urls = []policy.user_site_url_sources = {}+ policy.user_provided_spreadsheet_ids = []seen_origins = {parts[2] for url in policy.user_provided_site_urls if (parts := _url_parts(url)) is not None}for item in url_texts:for candidate in URL_CANDIDATE_RE.findall(item.text):cleaned = candidate.rstrip(".,;:!?")parts = _url_parts(cleaned)- if parts is None or parts[2] in seen_origins:+ if parts is None:+ continue+ spreadsheet_id = _spreadsheet_id_in_url(cleaned)+ if spreadsheet_id is not None and spreadsheet_id not in policy.user_provided_spreadsheet_ids:+ policy.user_provided_spreadsheet_ids.append(spreadsheet_id)+ if parts[2] in seen_origins:continueseen_origins.add(parts[2])policy.user_provided_site_urls.append(cleaned)diff --git a/skyvern/forge/sdk/copilot/tools/__init__.py b/skyvern/forge/sdk/copilot/tools/__init__.pyindex aa7f434ed..3be1aca51 100644--- a/skyvern/forge/sdk/copilot/tools/__init__.py+++ b/skyvern/forge/sdk/copilot/tools/__init__.py@@ -200,6 +200,7 @@ from .guardrails import ()from .integrations import (_list_integrations,+ _read_google_sheet,)from .mcp_hooks import _build_skyvern_mcp_overlays as _build_skyvern_mcp_overlaysfrom .mcp_hooks import _click_post_hook as _click_post_hook@@ -1135,6 +1136,44 @@ async def list_integrations_tool(ctx: RunContextWrapper) -> str:return json.dumps(sanitized)+@function_tool(failure_error_function=copilot_tool_failure, name_override="read_google_sheet")+async def read_google_sheet_tool(+ ctx: RunContextWrapper,+ spreadsheet_url: str,+ connection_id: str | None = None,+ range: str | None = None,+) -> str:+ """Read a Google spreadsheet through the organization's connected Google accounts, without a+ browser or a workflow run. Read-only; returns values, never tokens or formulas.++ `spreadsheet_url` must be a Google Sheets URL the user wrote in this chat; any other+ spreadsheet is not read. With `connection_id` omitted, every active Sheets-scoped connection+ is tried. `connections` reports one row per connection with `connection_id`, `name`,+ `email_address` and a `status`: `opened` (the connection reads this spreadsheet), `no_access`+ (the account cannot see this spreadsheet), `token_unavailable` (no access token could be+ minted for the connection), `error` (the attempt failed; see `reason`), or `not_eligible`+ (the given `connection_id` is not an active Sheets-scoped connection).++ When a connection opened the spreadsheet the result also has `title`, `tabs` (each with+ `title`, `gid`, `row_count`, `column_count`), `read_through` (the connection the values came+ from) and `values` for `range`. `range` is A1 notation; with it omitted, `values` holds the+ first rows of the tab named by the URL's `gid` (the first tab when the URL has none).+ `truncated` is true when rows, columns or cell text were cut to fit.+ """+ copilot_ctx = ctx.context+ arguments: dict[str, Any] = {"spreadsheet_url": spreadsheet_url, "connection_id": connection_id, "range": range}+ authority_error = _authority_tool_error(copilot_ctx, "read_google_sheet")+ if authority_error:+ result = {"ok": False, "error": authority_error}+ record_tool_step_result_for_ctx(copilot_ctx, "read_google_sheet", arguments, result)+ return json.dumps(result)++ result = await _read_google_sheet(arguments, copilot_ctx)+ record_tool_step_result_for_ctx(copilot_ctx, "read_google_sheet", arguments, result)+ sanitized = sanitize_tool_result_for_llm("read_google_sheet", result)+ return json.dumps(sanitized)++@function_tool(failure_error_function=copilot_tool_failure, name_override="get_organization_usage_quota")async def get_organization_usage_quota_tool(ctx: RunContextWrapper) -> str:"""Read this organization's account usage when the user asks about usage, credits, quota, plan@@ -2160,6 +2199,7 @@ NATIVE_TOOLS = [delete_block_tool,list_credentials_tool,list_integrations_tool,+ read_google_sheet_tool,get_organization_usage_quota_tool,run_blocks_tool,test_workflow_from_blank_browser_tool,diff --git a/skyvern/forge/sdk/copilot/tools/credentials.py b/skyvern/forge/sdk/copilot/tools/credentials.pyindex fe6cd836f..6a794161d 100644--- a/skyvern/forge/sdk/copilot/tools/credentials.py+++ b/skyvern/forge/sdk/copilot/tools/credentials.py@@ -648,12 +648,7 @@ async def _approve_server_verified_google_sheet_bindings(# Citation is judged against every visible row, the same set author time sees, so a longer# sibling name in the error state still shadows the shorter one; only active rows are eligible.- eligible = [- connection- for connection in visible_connections- if connection.state == google_oauth_service.STATE_ACTIVE- and google_oauth_service.GOOGLE_SHEETS_DATA_SCOPE in connection.scopes_granted- ]+ eligible = _eligible_sheets_connections(visible_connections)eligible_ids = {connection.id for connection in eligible}return [connection_id@@ -667,6 +662,18 @@ async def _approve_server_verified_google_sheet_bindings(def _same_turn_listed_google_sheet_ids(tool_activity: Sequence[dict[str, Any]]) -> set[str]:+ # A connection the server just used to open the sheet is one it would have listed, so it counts as listed.+ opened = {+ connection_id+ for activity in tool_activity+ if activity.get("tool") == "read_google_sheet" and isinstance(activity.get("opened_connection_ids"), list)+ for connection_id in activity["opened_connection_ids"]+ if isinstance(connection_id, str)+ }+ return _latest_listing_google_sheet_ids(tool_activity) | opened+++def _latest_listing_google_sheet_ids(tool_activity: Sequence[dict[str, Any]]) -> set[str]:for activity in reversed(tool_activity):if activity.get("tool") != "list_integrations":continuediff --git a/skyvern/forge/sdk/copilot/tools/integrations.py b/skyvern/forge/sdk/copilot/tools/integrations.pyindex cd7864524..9b4d69fe4 100644--- a/skyvern/forge/sdk/copilot/tools/integrations.py+++ b/skyvern/forge/sdk/copilot/tools/integrations.py@@ -1,11 +1,43 @@from __future__ import annotations-from typing import Any+import asyncio+import json+from dataclasses import dataclass, field+from typing import Any, Literal+import structlog++from skyvern.forge import app+from skyvern.forge.sdk.copilot.request_policy import RequestPolicyfrom skyvern.forge.sdk.copilot.runtime import AgentContext+from skyvern.forge.sdk.copilot.secret_scrub import scrub_secrets_from_structurefrom skyvern.forge.sdk.schemas.google_oauth import GoogleOAuthCredentialBasefrom skyvern.forge.sdk.schemas.microsoft_oauth import MicrosoftOAuthCredentialBase-from skyvern.forge.sdk.services import google_oauth_service, microsoft_oauth_service+from skyvern.forge.sdk.services import google_oauth_service, google_sheets_service, microsoft_oauth_service+from skyvern.schemas.google_sheets import (+ GoogleSheetsAPIError,+ build_a1,+ column_index_to_letter,+ extract_sheet_gid,+ extract_spreadsheet_id,+ is_plain_cell_range,+)++from .credentials import _eligible_sheets_connections++LOG = structlog.get_logger()++_SHEET_READ_TIMEOUT_SECONDS = 5.0+_SHEET_MAX_ROWS = 50+_SHEET_MAX_COLUMNS = 26+_SHEET_MAX_CELL_CHARS = 200+_SHEET_MAX_TABS = 50+_SHEET_MAX_VALUE_CHARS = 12_000+_SHEET_ERROR_MESSAGE_MAX_CHARS = 200+_SHEET_METADATA_FIELDS = "properties(title),sheets(properties(sheetId,title,gridProperties(rowCount,columnCount)))"+_SHEET_VALUES_FIELDS = "sheets(data(rowData(values(formattedValue))))"++SheetConnectionStatus = Literal["opened", "no_access", "token_unavailable", "error"]def _serialize(@@ -42,3 +74,233 @@ async def _list_integrations(params: dict[str, Any], ctx: AgentContext) -> dict["count": len(integrations),},}+++@dataclass(frozen=True)+class _SheetOpenAttempt:+ status: SheetConnectionStatus+ reason: str | None = None+ access_token: str | None = field(default=None, repr=False)+ metadata: dict[str, Any] | None = None+++@dataclass(frozen=True)+class _SheetTab:+ title: str+ gid: int+ row_count: int+ column_count: int+++def _sheet_error_reason(error: GoogleSheetsAPIError, access_token: str) -> str:+ code = f" {error.code}" if error.code else ""+ message = error.message.replace(access_token, "[token]")[:_SHEET_ERROR_MESSAGE_MAX_CHARS]+ return f"{error.status}{code}: {message}"+++async def _open_sheet_through_connection(+ organization_id: str, connection_id: str, spreadsheet_id: str+) -> _SheetOpenAttempt:+ access_token = await app.AGENT_FUNCTION.get_google_sheets_credentials(organization_id, connection_id)+ if access_token is None:+ return _SheetOpenAttempt("token_unavailable")+ try:+ metadata = await google_sheets_service.values_get(+ access_token=access_token,+ spreadsheet_id=spreadsheet_id,+ ranges="",+ fields=_SHEET_METADATA_FIELDS,+ )+ except GoogleSheetsAPIError as error:+ reason = _sheet_error_reason(error, access_token)+ # A 404 stays per connection: a sheet one account cannot find may still open through another.+ if error.status == 404 or (error.status == 403 and error.code != google_sheets_service._RECONNECT_SCOPE_CODE):+ return _SheetOpenAttempt("no_access", reason=reason)+ return _SheetOpenAttempt("error", reason=reason)+ return _SheetOpenAttempt("opened", access_token=access_token, metadata=metadata)+++async def _bounded_sheet_open(organization_id: str, connection_id: str, spreadsheet_id: str) -> _SheetOpenAttempt:+ try:+ return await asyncio.wait_for(+ _open_sheet_through_connection(organization_id, connection_id, spreadsheet_id),+ timeout=_SHEET_READ_TIMEOUT_SECONDS,+ )+ except TimeoutError:+ return _SheetOpenAttempt("error", reason="timeout")+ except Exception as error:+ LOG.warning(+ "copilot_read_google_sheet_open_failed",+ organization_id=organization_id,+ connection_id=connection_id,+ exc_info=True,+ )+ return _SheetOpenAttempt("error", reason=type(error).__name__)+++def _sheet_tabs(metadata: dict[str, Any]) -> list[_SheetTab]:+ tabs: list[_SheetTab] = []+ for sheet in metadata.get("sheets") or []:+ properties = sheet.get("properties") or {}+ if properties.get("sheetId") is None or properties.get("title") is None:+ continue+ grid = properties.get("gridProperties") or {}+ tabs.append(+ _SheetTab(+ title=str(properties["title"]),+ gid=int(properties["sheetId"]),+ row_count=int(grid.get("rowCount") or 0),+ column_count=int(grid.get("columnCount") or 0),+ )+ )+ return tabs+++def _first_rows_range(tab: _SheetTab) -> str | None:+ if not tab.row_count or not tab.column_count:+ return None+ last_column = column_index_to_letter(min(tab.column_count, _SHEET_MAX_COLUMNS) - 1)+ return build_a1(tab.title, f"A1:{last_column}{min(tab.row_count, _SHEET_MAX_ROWS)}")+++def _bounded_sheet_values(payload: dict[str, Any]) -> tuple[list[list[str]], bool]:+ # Picked by its data, so a response that also lists other tabs cannot read as an empty range.+ grids: list[dict[str, Any]] = next(+ (sheet["data"] for sheet in payload.get("sheets") or [] if sheet.get("data")), []+ )+ row_data = (grids[0].get("rowData") or []) if grids else []+ rows: list[list[str]] = []+ truncated = len(row_data) > _SHEET_MAX_ROWS+ used_chars = 0+ for row in row_data[:_SHEET_MAX_ROWS]:+ cells = row.get("values") or []+ truncated = truncated or len(cells) > _SHEET_MAX_COLUMNS+ values: list[str] = []+ for cell in cells[:_SHEET_MAX_COLUMNS]:+ text = str(cell.get("formattedValue") or "")+ truncated = truncated or len(text) > _SHEET_MAX_CELL_CHARS+ text = text[:_SHEET_MAX_CELL_CHARS]+ # Counted as serialized: non-ASCII text is escaped to several characters in the tool result.+ used_chars += len(json.dumps(text))+ if used_chars > _SHEET_MAX_VALUE_CHARS:+ return ([*rows, values] if values else rows), True+ values.append(text)+ rows.append(values)+ return rows, truncated+++async def _read_sheet_values(+ access_token: str, spreadsheet_id: str, tabs: list[_SheetTab], gid: int | None, requested_range: str | None+) -> dict[str, Any]:+ gid_tab = next((tab for tab in tabs if tab.gid == gid), None)+ plain_cells = requested_range is not None and is_plain_cell_range(requested_range.upper())+ if gid is not None and gid_tab is None and (plain_cells or not requested_range):+ return {"values_error": f"gid {gid} in the URL matches no tab of this spreadsheet."}+ first_rows_tab: _SheetTab | None = None+ if requested_range:+ # A plain cell range with no tab prefix reads the first tab, so the tab the URL names is made explicit.+ on_gid_tab = build_a1(gid_tab.title, requested_range) if gid_tab is not None and plain_cells else None+ values_range: str | None = on_gid_tab or requested_range+ else:+ first_rows_tab = gid_tab if gid_tab is not None else (tabs[0] if tabs else None)+ values_range = _first_rows_range(first_rows_tab) if first_rows_tab is not None else None+ if values_range is None:+ return {}+ try:+ payload = await asyncio.wait_for(+ google_sheets_service.values_get(+ access_token=access_token,+ spreadsheet_id=spreadsheet_id,+ ranges=values_range,+ fields=_SHEET_VALUES_FIELDS,+ ),+ timeout=_SHEET_READ_TIMEOUT_SECONDS,+ )+ except TimeoutError:+ return {"range": values_range, "values_error": "timeout"}+ except GoogleSheetsAPIError as error:+ return {"range": values_range, "values_error": _sheet_error_reason(error, access_token)}+ except ValueError as error:+ return {"range": values_range, "values_error": type(error).__name__}+ values, truncated = _bounded_sheet_values(payload)+ if first_rows_tab is not None:+ truncated = (+ truncated+ or (len(values) == _SHEET_MAX_ROWS and first_rows_tab.row_count > _SHEET_MAX_ROWS)+ or (+ first_rows_tab.column_count > _SHEET_MAX_COLUMNS+ and any(len(row) == _SHEET_MAX_COLUMNS for row in values)+ )+ )+ return {"range": values_range, "values": values, "truncated": truncated}+++async def _read_google_sheet(params: dict[str, Any], ctx: AgentContext) -> dict[str, Any]:+ spreadsheet_url = str(params.get("spreadsheet_url") or "")+ try:+ spreadsheet_id = extract_spreadsheet_id(spreadsheet_url)+ except ValueError:+ return {"ok": False, "error": "spreadsheet_url is not a Google Sheets URL."}+ policy = ctx.request_policy if isinstance(ctx.request_policy, RequestPolicy) else None+ if policy is None or spreadsheet_id not in policy.user_provided_spreadsheet_ids:+ return {+ "ok": False,+ "error": "This spreadsheet is not in a URL the user wrote in this chat, so it was not read.",+ }++ eligible = _eligible_sheets_connections(+ await google_oauth_service.get_visible_credentials_for_org(ctx.organization_id)+ )+ requested_connection_id = params.get("connection_id")+ connections: list[dict[str, Any]] = []+ if requested_connection_id:+ if all(connection.id != requested_connection_id for connection in eligible):+ connections.append({"connection_id": str(requested_connection_id), "status": "not_eligible"})+ eligible = [connection for connection in eligible if connection.id == requested_connection_id]++ attempts = await asyncio.gather(+ *(_bounded_sheet_open(ctx.organization_id, connection.id, spreadsheet_id) for connection in eligible)+ )+ for connection, attempt in zip(eligible, attempts):+ row: dict[str, Any] = {+ "connection_id": connection.id,+ "name": connection.credential_name,+ "status": attempt.status,+ }+ if connection.email_address:+ row["email_address"] = connection.email_address+ if attempt.reason:+ row["reason"] = attempt.reason+ connections.append(row)++ data: dict[str, Any] = {"spreadsheet_id": spreadsheet_id, "connections": connections}+ opened = next(+ ((connection, attempt) for connection, attempt in zip(eligible, attempts) if attempt.status == "opened"),+ None,+ )+ access_token = opened[1].access_token if opened is not None else None+ if opened is not None and access_token is not None:+ connection, attempt = opened+ metadata = attempt.metadata or {}+ tabs = _sheet_tabs(metadata)+ title = (metadata.get("properties") or {}).get("title")+ data["title"] = str(title)[:_SHEET_MAX_CELL_CHARS] if title is not None else None+ data["tabs"] = [+ {"title": tab.title, "gid": tab.gid, "row_count": tab.row_count, "column_count": tab.column_count}+ for tab in tabs[:_SHEET_MAX_TABS]+ ]+ if len(tabs) > _SHEET_MAX_TABS:+ data["tabs_total"] = len(tabs)+ data["read_through"] = connection.id+ requested_range = params.get("range")+ data.update(+ await _read_sheet_values(+ access_token,+ spreadsheet_id,+ tabs,+ extract_sheet_gid(spreadsheet_url),+ str(requested_range) if requested_range else None,+ )+ )+ scrubbed: dict[str, Any] = scrub_secrets_from_structure(ctx, data)+ return {"ok": True, "data": scrubbed}diff --git a/skyvern/forge/sdk/db/repositories/organizations.py b/skyvern/forge/sdk/db/repositories/organizations.pyindex 3ced13647..28a54381e 100644--- a/skyvern/forge/sdk/db/repositories/organizations.py+++ b/skyvern/forge/sdk/db/repositories/organizations.py@@ -268,6 +268,23 @@ class OrganizationsRepository(BaseRepository):remember_organization_created_at(organization.organization_id, organization.created_at)return Organization.model_validate(organization)+ @db_operation("has_valid_org_auth_token")+ async def has_valid_org_auth_token(+ self,+ organization_id: str,+ token_type: OrganizationAuthTokenType,+ ) -> bool:+ """Check token existence without decrypting its secret payload."""+ async with self.Session() as session:+ token_id = await session.scalar(+ select(OrganizationAuthTokenModel.id)+ .filter_by(organization_id=organization_id)+ .filter_by(token_type=token_type)+ .filter_by(valid=True)+ .limit(1)+ )+ return token_id is not None+@overloadasync def get_valid_org_auth_token(self,diff --git a/skyvern/forge/sdk/db/repositories/sms.py b/skyvern/forge/sdk/db/repositories/sms.pyindex 932ceb237..273a10469 100644--- a/skyvern/forge/sdk/db/repositories/sms.py+++ b/skyvern/forge/sdk/db/repositories/sms.py@@ -444,7 +444,7 @@ class SMSRepository(BaseRepository):return int(count or 0)@db_operation("delete_sms_config")- async def delete_sms_config(self, sms_config_id: str, organization_id: str) -> None:+ async def delete_sms_config(self, sms_config_id: str, organization_id: str) -> bool:async with self.Session() as session:row = await session.scalar(select(OrganizationSMSConfigModel)@@ -456,7 +456,7 @@ class SMSRepository(BaseRepository):.with_for_update())if row is None:- return+ return Falseactive_phone_id = await session.scalar(select(OrganizationPhoneNumberModel.phone_number_id).where(@@ -472,6 +472,7 @@ class SMSRepository(BaseRepository):row.deleted_at = naive_utc_now()row.modified_at = row.deleted_atawait session.commit()+ return True@db_operation("create_phone_number")async def create_phone_number(diff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.pyindex 3ada0d15a..a87b3d5f1 100644--- a/skyvern/forge/sdk/routes/agent_protocol.py+++ b/skyvern/forge/sdk/routes/agent_protocol.py@@ -232,6 +232,22 @@ from skyvern.webeye.real_browser_manager import runtime_supports_browser_type_seLOG = structlog.get_logger()+# Every OrganizationUpdate input has one corresponding persisted organization field.+ORGANIZATION_UPDATE_AUDIT_FIELD_MAP = {+ "slug": "slug",+ "max_steps_per_run": "max_steps_per_run",+ "max_steps_per_workflow_run": "max_steps_per_workflow_run",+ "clear_max_steps_per_workflow_run": "max_steps_per_workflow_run",+ "max_retries_per_step": "max_retries_per_step",+ "webhook_callback_url": "webhook_callback_url",+ "artifact_url_expiry_seconds": "artifact_url_expiry_seconds",+ "clear_artifact_url_expiry_seconds": "artifact_url_expiry_seconds",+ "default_llm_key": "default_llm_key",+ "clear_default_llm_key": "default_llm_key",+ "default_secondary_llm_key": "default_secondary_llm_key",+ "clear_default_secondary_llm_key": "default_secondary_llm_key",+}+FORCE_TASK_V1_MAX_STEPS = 25_create_from_prompt_adapter: TypeAdapter[CreateFromPromptRequest] = TypeAdapter(CreateFromPromptRequest)@@ -5752,6 +5768,13 @@ async def reset_workflow_browser_profile(message="Failed to clear the persisted browser profile. Please retry the reset operation.",status_code=http_status.HTTP_500_INTERNAL_SERVER_ERROR,) from exc+ await record_request_audit_event(+ current_org.organization_id,+ "workflow.update",+ "workflow",+ workflow_permanent_id,+ changed_fields=("saved_browser_profile",),+ )@legacy_base_router.post(@@ -5924,6 +5947,18 @@ async def update_organization(detail=f"{field_name} must reference a valid custom LLM for this organization",)+ stored_org = await app.DATABASE.organizations.get_organization(current_org.organization_id)+ comparison_org = stored_org or current_org+ changed_fields: set[str] = set()+ for request_field, organization_field in ORGANIZATION_UPDATE_AUDIT_FIELD_MAP.items():+ requested_value = getattr(org_update, request_field)+ if request_field.startswith("clear_"):+ changed = requested_value and getattr(comparison_org, organization_field) is not None+ else:+ changed = requested_value is not None and requested_value != getattr(comparison_org, organization_field)+ if changed:+ changed_fields.add(organization_field)+try:updated = await app.DATABASE.organizations.update_organization(current_org.organization_id,@@ -5950,6 +5985,14 @@ async def update_organization() from excorg_auth_service.invalidate_cached_org(current_org.organization_id)+ if changed_fields:+ await record_request_audit_event(+ current_org.organization_id,+ "organization.settings.update",+ "organization",+ current_org.organization_id,+ changed_fields=tuple(sorted(changed_fields)),+ )return updateddiff --git a/skyvern/forge/sdk/routes/credentials.py b/skyvern/forge/sdk/routes/credentials.pyindex f973b84cf..8c5069ce3 100644--- a/skyvern/forge/sdk/routes/credentials.py+++ b/skyvern/forge/sdk/routes/credentials.py@@ -2617,14 +2617,15 @@ async def update_credential_folder(if not folder:raise HTTPException(status_code=404, detail=f"Credential folder {folder_id} not found")+ changed_fields = tuple(+ name for name, value in (("title", data.title), ("description", data.description)) if value is not None+ )await record_request_audit_event(current_org.organization_id,"credential_folder.update","credential_folder",folder.folder_id,- changed_fields=tuple(- name for name, value in (("title", data.title), ("description", data.description)) if value is not None- ),+ changed_fields=changed_fields,)credential_count = await app.DATABASE.credential_folders.get_credential_folder_credential_count(folder_id=folder.folder_id,diff --git a/skyvern/forge/sdk/routes/custom_llms.py b/skyvern/forge/sdk/routes/custom_llms.pyindex 102ce0f56..bdc8f7b22 100644--- a/skyvern/forge/sdk/routes/custom_llms.py+++ b/skyvern/forge/sdk/routes/custom_llms.py@@ -5,6 +5,7 @@ import structlogfrom fastapi import Depends, HTTPException, Pathfrom skyvern.forge import app+from skyvern.forge.agent_functions import record_request_audit_eventfrom skyvern.forge.sdk.api.llm.custom_llm_registry import (deregister_custom_llm_config,register_custom_llm_config,@@ -118,6 +119,12 @@ async def create_custom_llm()custom_llm = custom_llm_from_org_auth_token(token)register_custom_llm_config(custom_llm.id, custom_llm.organization_id, custom_llm.config)+ await record_request_audit_event(+ current_org.organization_id,+ "custom_model.create",+ "custom_llm",+ token.id,+ )return CustomLLMResponse(custom_llm=custom_llm_response_from_org_auth_token(token))@@ -154,6 +161,21 @@ async def update_custom_llm(custom_llm = custom_llm_from_org_auth_token(token)register_custom_llm_config(custom_llm.id, custom_llm.organization_id, custom_llm.config)+ changed_fields = tuple(+ sorted(+ field_name+ for field_name in CustomLLMConfig.model_fields+ if getattr(config, field_name) != getattr(existing_custom_llm.config, field_name)+ )+ )+ if changed_fields:+ await record_request_audit_event(+ current_org.organization_id,+ "custom_model.update",+ "custom_llm",+ custom_llm_id,+ changed_fields=changed_fields,+ )return CustomLLMResponse(custom_llm=custom_llm_response_from_org_auth_token(token))@@ -184,4 +206,10 @@ async def delete_custom_llm(raise HTTPException(status_code=404, detail="Custom LLM not found") from ederegister_custom_llm_config(custom_llm_id)+ await record_request_audit_event(+ current_org.organization_id,+ "custom_model.delete",+ "custom_llm",+ custom_llm_id,+ )return ClearOrganizationAuthTokenResponse(success=True)diff --git a/skyvern/forge/sdk/routes/google_oauth.py b/skyvern/forge/sdk/routes/google_oauth.pyindex 1e5b11e6c..cc05a2ec5 100644--- a/skyvern/forge/sdk/routes/google_oauth.py+++ b/skyvern/forge/sdk/routes/google_oauth.py@@ -11,6 +11,7 @@ from google.auth.exceptions import GoogleAuthErrorfrom oauthlib.oauth2 import InvalidGrantError, OAuth2Errorfrom skyvern.forge import app+from skyvern.forge.agent_functions import record_request_audit_eventfrom skyvern.forge.sdk.schemas.google_oauth import (CreateGoogleOAuthAuthorizeRequest,CreateGoogleOAuthCallbackRequest,@@ -256,6 +257,21 @@ async def google_oauth_callback(except google_oauth_service.EncryptionNotConfiguredError as exc:raise HTTPException(status_code=503, detail=str(exc))+ if not prior_state_known or prior_state in {google_oauth_service.STATE_ACTIVE, google_oauth_service.STATE_ERROR}:+ await record_request_audit_event(+ current_org.organization_id,+ "google_oauth.update",+ "google_oauth_credential",+ credential.id,+ )+ else:+ await record_request_audit_event(+ current_org.organization_id,+ "google_oauth.create",+ "google_oauth_credential",+ credential.id,+ )+if not prior_state_known:LOG.warning("Skipping Google integration lifecycle analytics because prior credential state is unknown",@@ -362,6 +378,30 @@ async def update_google_oauth_client_config(raise HTTPException(status_code=404, detail=str(exc))except google_oauth_service.EncryptionNotConfiguredError as exc:raise HTTPException(status_code=503, detail=str(exc))+ existing_config = resolved.config if resolved and resolved.source == "organization" else None+ changed_fields = tuple(+ sorted(+ field_name+ for field_name in GoogleOAuthClientConfig.model_fields+ if existing_config is None or getattr(config, field_name) != getattr(existing_config, field_name)+ )+ )+ if existing_config is None:+ await record_request_audit_event(+ current_org.organization_id,+ "google_oauth.create",+ "google_oauth_client_config",+ current_org.organization_id,+ changed_fields=changed_fields,+ )+ elif changed_fields:+ await record_request_audit_event(+ current_org.organization_id,+ "google_oauth.update",+ "google_oauth_client_config",+ current_org.organization_id,+ changed_fields=changed_fields,+ )return GoogleOAuthClientConfigResponse(config=saved.safe())@@ -372,9 +412,16 @@ async def delete_google_oauth_client_config("""Clear the organization-level Google OAuth client config and fall back to environment config."""_require_organization_client_config_enabled()try:- await google_oauth_service.delete_client_config(current_org.organization_id)+ changed = await google_oauth_service.delete_client_config(current_org.organization_id)except google_oauth_service.OrganizationGoogleOAuthConfigDisabledError as exc:raise HTTPException(status_code=404, detail=str(exc))+ if changed:+ await record_request_audit_event(+ current_org.organization_id,+ "google_oauth.delete",+ "google_oauth_client_config",+ current_org.organization_id,+ )return {"success": True}@@ -415,6 +462,13 @@ async def rename_google_oauth_credential()if updated is None:raise HTTPException(status_code=404, detail="Credential not found")+ await record_request_audit_event(+ current_org.organization_id,+ "google_oauth.update",+ "google_oauth_credential",+ credential_id,+ changed_fields=("credential_name",),+ )return GoogleOAuthCredentialResponse(credential=updated)@@ -432,4 +486,10 @@ async def delete_google_oauth_credential()if not revoked:raise HTTPException(status_code=404, detail="Credential not found")+ await record_request_audit_event(+ current_org.organization_id,+ "google_oauth.delete",+ "google_oauth_credential",+ credential_id,+ )return {"success": True}diff --git a/skyvern/forge/sdk/routes/microsoft_oauth.py b/skyvern/forge/sdk/routes/microsoft_oauth.pyindex 141ca955d..48e92d0eb 100644--- a/skyvern/forge/sdk/routes/microsoft_oauth.py+++ b/skyvern/forge/sdk/routes/microsoft_oauth.py@@ -7,6 +7,7 @@ import structlogfrom fastapi import APIRouter, Depends, HTTPException, statusfrom skyvern.forge import app+from skyvern.forge.agent_functions import record_request_audit_eventfrom skyvern.forge.sdk.schemas.microsoft_oauth import (CreateMicrosoftOAuthAuthorizeRequest,CreateMicrosoftOAuthCallbackRequest,@@ -219,6 +220,24 @@ async def microsoft_oauth_callback(except microsoft_oauth_service.EncryptionNotConfiguredError as exc:raise HTTPException(status_code=503, detail=str(exc)) from exc+ if not prior_state_known or prior_state in {+ microsoft_oauth_service.STATE_ACTIVE,+ microsoft_oauth_service.STATE_ERROR,+ }:+ await record_request_audit_event(+ current_org.organization_id,+ "microsoft_oauth.update",+ "microsoft_oauth_credential",+ credential.id,+ )+ else:+ await record_request_audit_event(+ current_org.organization_id,+ "microsoft_oauth.create",+ "microsoft_oauth_credential",+ credential.id,+ )+if not prior_state_known:LOG.warning("Skipping Microsoft integration lifecycle analytics because prior credential state is unknown",@@ -322,6 +341,13 @@ async def rename_microsoft_oauth_credential()if updated is None:raise HTTPException(status_code=404, detail="Credential not found")+ await record_request_audit_event(+ current_org.organization_id,+ "microsoft_oauth.update",+ "microsoft_oauth_credential",+ credential_id,+ changed_fields=("credential_name",),+ )return MicrosoftOAuthCredentialResponse(credential=updated)@@ -339,3 +365,9 @@ async def delete_microsoft_oauth_credential()if not revoked:raise HTTPException(status_code=404, detail="Credential not found")+ await record_request_audit_event(+ current_org.organization_id,+ "microsoft_oauth.delete",+ "microsoft_oauth_credential",+ credential_id,+ )diff --git a/skyvern/forge/sdk/routes/twilio_integration.py b/skyvern/forge/sdk/routes/twilio_integration.pyindex 4cbe2a80d..87d1b56c5 100644--- a/skyvern/forge/sdk/routes/twilio_integration.py+++ b/skyvern/forge/sdk/routes/twilio_integration.py@@ -10,6 +10,7 @@ from pydantic import BaseModel, ConfigDict, model_validatorfrom skyvern.config import settingsfrom skyvern.forge import app+from skyvern.forge.agent_functions import record_request_audit_eventfrom skyvern.forge.sdk.db.enums import OrganizationAuthTokenTypefrom skyvern.forge.sdk.db.repositories.sms import SMSLifecycleLockTimeoutfrom skyvern.forge.sdk.encrypt.base import EncryptMethod@@ -449,6 +450,12 @@ async def _enable_twilio_phone_number_locked(connected_config = await app.DATABASE.sms.create_sms_config(organization_id=organization_id, mode="connected", webhook_secret=secrets.token_urlsafe(32))+ await record_request_audit_event(+ organization_id,+ "twilio.create",+ "twilio_sms_config",+ connected_config[0].sms_config_id,+ )config, webhook_secret = connected_configinbound_url = _inbound_url(config.sms_config_id, webhook_secret)current_sms_url = _current_sms_url(provider_number)@@ -536,6 +543,14 @@ async def _enable_twilio_phone_number_locked()raise+ await record_request_audit_event(+ organization_id,+ "twilio.create" if registered is None else "twilio.update",+ "twilio_phone_number",+ saved.phone_number_id,+ changed_fields=("status",),+ )+try:await _shielded(client.update_inbound_sms_config(request.phone_number_sid, inbound_url, "POST", ""))except BaseException as error:@@ -553,7 +568,15 @@ async def _enable_twilio_phone_number_locked(if isinstance(error, TwilioApiError):raise _twilio_api_http_exception(error) from Noneraise- return await _finalize_phone_number(saved.phone_number_id, organization_id, status="active")+ phone_number = await _finalize_phone_number(saved.phone_number_id, organization_id, status="active")+ await record_request_audit_event(+ organization_id,+ "twilio.update",+ "twilio_phone_number",+ phone_number.phone_number_id,+ changed_fields=("status",),+ )+ return phone_number@twilio_integration_router.post(@@ -571,6 +594,18 @@ async def create_twilio_credential(_require_twilio_sms_enabled()organization_id = current_org.organization_idasync with _organization_sms_lifecycle_lock(organization_id):+ try:+ credential_exists = await app.DATABASE.organizations.has_valid_org_auth_token(+ organization_id,+ OrganizationAuthTokenType.twilio_credential,+ )+ except Exception:+ credential_exists = None+ LOG.warning(+ "Failed to read Twilio credential state for audit classification",+ organization_id=organization_id,+ exc_info=True,+ )active_number_count = await _active_connected_phone_count(organization_id)if active_number_count:existing_credential = await _get_credential(organization_id)@@ -592,6 +627,13 @@ async def create_twilio_credential(token=request.credential,encrypted_method=EncryptMethod.AES,)+ await record_request_audit_event(+ organization_id,+ "twilio.create" if credential_exists is False else "twilio.update",+ "twilio_credential",+ organization_id,+ changed_fields=("account_sid", "auth_token", "api_key_sid"),+ )return _safe_credential(request.credential)@@ -634,10 +676,17 @@ async def delete_twilio_credential(status_code=409,detail="Disable all connected Twilio phone numbers before disconnecting Twilio",)- await app.DATABASE.organizations.invalidate_org_auth_tokens(+ invalidated = await app.DATABASE.organizations.invalidate_org_auth_tokens(organization_id=organization_id,token_type=OrganizationAuthTokenType.twilio_credential,)+ if invalidated:+ await record_request_audit_event(+ organization_id,+ "twilio.delete",+ "twilio_credential",+ organization_id,+ )return {"success": True}@@ -756,6 +805,13 @@ async def _disable_twilio_phone_number_locked()if staged_row is None:raise HTTPException(status_code=404, detail="Phone number not found")+ await record_request_audit_event(+ organization_id,+ "twilio.update",+ "twilio_phone_number",+ registered.phone_number_id,+ changed_fields=("status",),+ )if registered.provider_number_sid and client is not None:try:@@ -817,7 +873,15 @@ async def _disable_twilio_phone_number_locked(if isinstance(error, TwilioApiError):raise _twilio_api_http_exception(error) from Noneraise- return await _finalize_phone_number(registered.phone_number_id, organization_id, status="disabled")+ phone_number = await _finalize_phone_number(registered.phone_number_id, organization_id, status="disabled")+ await record_request_audit_event(+ organization_id,+ "twilio.update",+ "twilio_phone_number",+ phone_number.phone_number_id,+ changed_fields=("status",),+ )+ return phone_number@twilio_integration_router.post("/sms-configs", response_model=SMSConfigCreated)@@ -834,6 +898,12 @@ async def create_sms_config(mode=request.mode,webhook_secret=secrets.token_urlsafe(32),)+ await record_request_audit_event(+ organization_id,+ "twilio.create",+ "twilio_sms_config",+ config.sms_config_id,+ )return SMSConfigCreated(**config.model_dump(),inbound_url=_inbound_url(config.sms_config_id, webhook_secret),@@ -874,7 +944,14 @@ async def delete_sms_config()if active_phone_count > 0:raise HTTPException(status_code=409, detail="SMS configuration still has active phone numbers")- await app.DATABASE.sms.delete_sms_config(sms_config_id, organization_id)+ deleted = await app.DATABASE.sms.delete_sms_config(sms_config_id, organization_id)+ if deleted:+ await record_request_audit_event(+ organization_id,+ "twilio.delete",+ "twilio_sms_config",+ sms_config_id,+ )return {"success": True}@@ -906,12 +983,19 @@ async def register_manual_phone_number(registered = await _get_registered_phone_number(phone_number, organization_id)_require_twilio_provider(registered)if registered is None:- return await app.DATABASE.sms.create_phone_number(+ phone = await app.DATABASE.sms.create_phone_number(organization_id=organization_id,sms_config_id=sms_config_id,phone_number=phone_number,provider="twilio",)+ await record_request_audit_event(+ organization_id,+ "twilio.create",+ "twilio_phone_number",+ phone.phone_number_id,+ )+ return phoneif (registered.status != "disabled"or registered.provider_number_sid is not None@@ -926,4 +1010,11 @@ async def register_manual_phone_number()if updated is None:raise HTTPException(status_code=404, detail="Phone number not found")+ await record_request_audit_event(+ organization_id,+ "twilio.update",+ "twilio_phone_number",+ updated.phone_number_id,+ changed_fields=("sms_config_id", "status"),+ )return updateddiff --git a/skyvern/forge/sdk/services/google_oauth_service.py b/skyvern/forge/sdk/services/google_oauth_service.pyindex df1004ec7..dd8e59b90 100644--- a/skyvern/forge/sdk/services/google_oauth_service.py+++ b/skyvern/forge/sdk/services/google_oauth_service.py@@ -308,9 +308,9 @@ async def save_client_config(return GoogleOAuthClientConfigResolution(config=config, source="organization")-async def delete_client_config(organization_id: str) -> None:+async def delete_client_config(organization_id: str) -> bool:_require_organization_client_config_enabled()- await app.DATABASE.organizations.invalidate_org_auth_tokens(+ invalidated = await app.DATABASE.organizations.invalidate_org_auth_tokens(organization_id=organization_id,token_type=OrganizationAuthTokenType.google_oauth_client_config,)@@ -327,6 +327,7 @@ async def delete_client_config(organization_id: str) -> None:organization_id=organization_id,count=flipped,)+ return bool(invalidated or flipped)def _require_client_credentials(client_config: GoogleOAuthClientConfig | None = None) -> tuple[str, str]:diff --git a/tests/unit/forge/sdk/copilot/test_organization_usage_tool.py b/tests/unit/forge/sdk/copilot/test_organization_usage_tool.pyindex c2baf52ec..37888be41 100644--- a/tests/unit/forge/sdk/copilot/test_organization_usage_tool.py+++ b/tests/unit/forge/sdk/copilot/test_organization_usage_tool.py@@ -61,6 +61,7 @@ CATALOG_WITHOUT_THIS_TOOL = ["delete_block","list_credentials","list_integrations",+ "read_google_sheet","run_blocks_and_collect_debug","test_workflow_from_blank_browser","get_run_results",diff --git a/tests/unit/test_copilot_account_choices.py b/tests/unit/test_copilot_account_choices.pyindex 16c290bce..3f9a74996 100644--- a/tests/unit/test_copilot_account_choices.py+++ b/tests/unit/test_copilot_account_choices.py@@ -1,6 +1,7 @@from __future__ import annotationsimport asyncio+import jsonfrom collections.abc import Callablefrom datetime import datetimefrom types import SimpleNamespace@@ -8,6 +9,7 @@ from unittest.mock import AsyncMock, MagicMockimport httpximport pytest+import pytest_asynciofrom skyvern.forge import appfrom skyvern.forge.sdk.copilot import agent as agent_module@@ -20,6 +22,8 @@ from skyvern.forge.sdk.copilot.context import (adopt_model_authored_context,record_approved_credentials_in_global_llm_context,)+from skyvern.forge.sdk.copilot.hooks import CopilotRunHooks+from skyvern.forge.sdk.copilot.output_utils import sanitize_tool_result_for_llmfrom skyvern.forge.sdk.copilot.tools.credentials import (_approve_server_verified_google_sheet_bindings,_approved_run_credential_ids,@@ -32,6 +36,7 @@ from skyvern.forge.sdk.copilot.tools.credentials import (canonicalize_named_google_sheet_bindings,resolve_google_sheet_tabs_from_gid,)+from skyvern.forge.sdk.copilot.tools.integrations import _read_google_sheetfrom skyvern.forge.sdk.copilot.turn_outcome import (connected_account_choice_context,selected_connected_account_id,@@ -1779,3 +1784,111 @@ async def test_gid_resolution_bounds_a_hung_tab_lookup_once_per_spreadsheet(assert [fact["status"] for fact in facts] == ["lookup_failed", "lookup_failed"]assert lookups == [CITED_ACCOUNT_ID]+++OPENING_ACCOUNT_ID = "goac_opens_sheet"+DENIED_ACCOUNT_ID = "goac_cannot_open_sheet"+OPENING_ACCOUNT_NAME = "Ops Sheets"+READ_SHEET_URL = f"https://docs.google.com/spreadsheets/d/{SPREADSHEET_ID}/edit#gid={ENGINEERING_GID}"+READ_SHEET_METADATA = {+ "properties": {"title": "Fleet metrics"},+ "sheets": [+ {+ "properties": {+ "sheetId": ENGINEERING_GID,+ "title": "Engineering",+ "gridProperties": {"rowCount": 20, "columnCount": 4},+ }+ }+ ],+}+++@pytest_asyncio.fixture+async def ctx_after_read_google_sheet(+ monkeypatch: pytest.MonkeyPatch,+ mock_sheets_transport: Callable[[Callable[[httpx.Request], httpx.Response]], None],+) -> CopilotContext:+ def handler(request: httpx.Request) -> httpx.Response:+ if request.headers["Authorization"] != f"Bearer token-{OPENING_ACCOUNT_ID}":+ return httpx.Response(404, json={"error": {"code": 404, "message": "Requested entity was not found."}})+ if "ranges" in request.url.params:+ return httpx.Response(200, json={"sheets": [{"data": [{"rowData": []}]}]})+ return httpx.Response(200, json=READ_SHEET_METADATA)++ async def mint(organization_id: str, connection_id: str) -> str:+ return f"token-{connection_id}"++ mock_sheets_transport(handler)+ _patch_visible_credentials(+ monkeypatch,+ [_google(OPENING_ACCOUNT_ID, OPENING_ACCOUNT_NAME), _google(DENIED_ACCOUNT_ID, "Personal Sheets")],+ )+ monkeypatch.setattr(app.AGENT_FUNCTION, "get_google_sheets_credentials", mint)+ user_message = f"read Sessions Started from https://example.com/dashboard and update {READ_SHEET_URL}"+ policy = request_policy_module.RequestPolicy(canonical_user_message=user_message)+ request_policy_module._ground_user_provided_sites(policy, user_message, [])+ ctx = make_copilot_ctx(request_policy=policy)++ result = await _read_google_sheet({"spreadsheet_url": READ_SHEET_URL}, ctx)+ tool = SimpleNamespace(name="read_google_sheet")+ await CopilotRunHooks(ctx).on_tool_end(+ MagicMock(), MagicMock(), tool, json.dumps(sanitize_tool_result_for_llm("read_google_sheet", result))+ )+ return ctx+++async def _approved_after_tool_activity(ctx: CopilotContext, credential_id: str) -> list[str]:+ assert isinstance(ctx.request_policy, request_policy_module.RequestPolicy)+ return await _approve_server_verified_google_sheet_bindings(+ [(SHEETS_BLOCK_LABEL, credential_id)],+ tool_activity=ctx.tool_activity,+ organization_id="org-1",+ request_policy=ctx.request_policy,+ )+++async def test_connection_that_opened_the_sheet_is_run_approved_in_the_same_turn(+ ctx_after_read_google_sheet: CopilotContext,+) -> None:+ ctx = ctx_after_read_google_sheet++ approved = await _approved_after_tool_activity(ctx, OPENING_ACCOUNT_ID)++ assert approved == [OPENING_ACCOUNT_ID]+ assert (+ _credential_run_approval_blocker_signal(+ [OPENING_ACCOUNT_ID], ctx.request_policy, additional_approved_ids=approved+ )+ is None+ )++[email protected]("credential_id", [OPENING_ACCOUNT_NAME, DENIED_ACCOUNT_ID, "goac_never_reported"])+async def test_name_or_connection_the_sheet_read_did_not_open_stays_authority_denied(+ ctx_after_read_google_sheet: CopilotContext, credential_id: str+) -> None:+ ctx = ctx_after_read_google_sheet++ assert await _approved_after_tool_activity(ctx, credential_id) == []+ assert ctx.request_policy.run_approved_google_connection_ids == []+++ "later_listing",+ [+ [{"tool": "list_integrations", "integrations": "malformed"}],+ _listed_integrations(_google("goac_other", "Other Sheets")),+ ],+)+async def test_later_listing_neither_erases_an_opened_connection_nor_admits_one_that_did_not_open(+ ctx_after_read_google_sheet: CopilotContext, later_listing: list[dict[str, object]]+) -> None:+ ctx = ctx_after_read_google_sheet+ ctx.tool_activity.extend(later_listing)++ assert await _approved_after_tool_activity(ctx, OPENING_ACCOUNT_ID) == [OPENING_ACCOUNT_ID]+ assert await _approved_after_tool_activity(ctx, DENIED_ACCOUNT_ID) == []diff --git a/tests/unit/test_copilot_failure_publication.py b/tests/unit/test_copilot_failure_publication.pyindex 0cc9d6fca..178f30101 100644--- a/tests/unit/test_copilot_failure_publication.py+++ b/tests/unit/test_copilot_failure_publication.py@@ -7,6 +7,7 @@ from types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMockimport pytest+from structlog.testing import capture_logsfrom skyvern.forge.sdk.artifact.models import ArtifactTypefrom skyvern.forge.sdk.copilot import enforcement as enforcement_module@@ -1422,7 +1423,9 @@ async def test_capture_settlement_failure_uses_protected_block_failure_path(monkmonkeypatch.setattr(CodeBlock, "_invalidate_stale_output_on_failure", AsyncMock())monkeypatch.setattr(CodeBlock, "build_block_result", build_result)- result = await _block().execute_safe(workflow_run_id="wr_test", organization_id="o_test")+ # structlog's unconfigured default renderer cannot format the failure log's list-valued `stack`.+ with capture_logs():+ result = await _block().execute_safe(workflow_run_id="wr_test", organization_id="o_test")assert result.failure_reason == "CodeBlock execution failed."assert build_result.await_args.kwargs["workflow_run_block_id"] == "wrb_successor"diff --git a/tests/unit/test_copilot_tools_list_integrations.py b/tests/unit/test_copilot_tools_list_integrations.pyindex e94ab7ea3..c3a7a4ae2 100644--- a/tests/unit/test_copilot_tools_list_integrations.py+++ b/tests/unit/test_copilot_tools_list_integrations.py@@ -1,12 +1,20 @@+import asyncio+import json+from collections.abc import Callablefrom datetime import datetimefrom types import SimpleNamespace+import httpximport pytest-from skyvern.forge.sdk.copilot.tools import list_integrations_tool-from skyvern.forge.sdk.copilot.tools.integrations import _list_integrations, _serialize+from skyvern.forge import app+from skyvern.forge.sdk.copilot.context import USER_FACING_REASON_PARAM, CopilotContext+from skyvern.forge.sdk.copilot.request_policy import RequestPolicy, _ground_user_provided_sites+from skyvern.forge.sdk.copilot.tools import copilot_native_tools, list_integrations_tool+from skyvern.forge.sdk.copilot.tools.integrations import _list_integrations, _read_google_sheet, _serializefrom skyvern.forge.sdk.schemas.google_oauth import GoogleOAuthCredentialBasefrom skyvern.forge.sdk.schemas.microsoft_oauth import MicrosoftOAuthCredentialBase+from tests.unit.copilot_test_helpers import make_copilot_ctxORGANIZATION_ID = "o_test_org"@@ -160,3 +168,276 @@ def test_tool_description_states_facts_without_prescribing_dialogue() -> None:assert "state` is `error`" in descriptionassert "ask the user" not in description.lower()assert "reconnect" not in description.lower()+++SPREADSHEET_ID = "1AbCdEfGhIjKlMnOpQrStUvWxYz0123456789"+OTHER_SPREADSHEET_ID = "1ZyXwVuTsRqPoNmLkJiHgFeDcBa9876543210"+BUDGET_GID = 1226505961+SHEET_URL = f"https://docs.google.com/spreadsheets/d/{SPREADSHEET_ID}/edit?gid={BUDGET_GID}#gid={BUDGET_GID}"+OPENING_TOKEN = "ya29.a0AfB_byC-opening-account-access-token"+DENIED_TOKEN = "ya29.a0AfB_byC-denied-account-access-token"+SHEET_METADATA = {+ "properties": {"title": "Fleet metrics"},+ "sheets": [+ {"properties": {"sheetId": 0, "title": "Summary", "gridProperties": {"rowCount": 1000, "columnCount": 26}}},+ {+ "properties": {+ "sheetId": BUDGET_GID,+ "title": "Budget",+ "gridProperties": {"rowCount": 12, "columnCount": 3},+ }+ },+ ],+}++SheetRows = list[list[str]]+TransportInstaller = Callable[[Callable[[httpx.Request], httpx.Response]], None]+SheetsApiInstaller = Callable[..., list[httpx.Request]]+++def _grid_payload(rows: SheetRows) -> dict[str, object]:+ row_data = [{"values": [{"formattedValue": cell} for cell in row]} for row in rows]+ return {"sheets": [{"data": [{"rowData": row_data}]}]}+++def _sheet_ctx(user_message: str = f"read Sessions Started and update {SHEET_URL}") -> CopilotContext:+ policy = RequestPolicy()+ _ground_user_provided_sites(policy, user_message, [])+ return make_copilot_ctx(organization_id=ORGANIZATION_ID, request_policy=policy)+++def sheets_api(monkeypatch: pytest.MonkeyPatch, mock_sheets_transport: TransportInstaller) -> SheetsApiInstaller:+ def _apply(+ connections: list[GoogleOAuthCredentialBase],+ tokens: dict[str, str | None],+ rows: SheetRows | None = None,+ values_response: httpx.Response | None = None,+ ) -> list[httpx.Request]:+ requests: list[httpx.Request] = []++ def handler(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ if request.headers["Authorization"] != f"Bearer {OPENING_TOKEN}":+ denied = {"error": {"code": 403, "message": "The caller does not have permission"}}+ return httpx.Response(403, json=denied)+ if "ranges" in request.url.params:+ if values_response is not None:+ return values_response+ return httpx.Response(200, json=_grid_payload(rows or [["Metric", "Value"], ["Sessions", "72.51k"]]))+ return httpx.Response(200, json=SHEET_METADATA)++ async def mint(organization_id: str, connection_id: str) -> str | None:+ assert organization_id == ORGANIZATION_ID+ return tokens[connection_id]++ async def visible(organization_id: str) -> list[GoogleOAuthCredentialBase]:+ return connections++ mock_sheets_transport(handler)+ monkeypatch.setattr(app.AGENT_FUNCTION, "get_google_sheets_credentials", mint)+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.tools.integrations.google_oauth_service.get_visible_credentials_for_org",+ visible,+ )+ return requests++ return _apply+++async def test_read_google_sheet_reports_each_connection_and_reads_the_gid_tab_without_token_material(+ sheets_api: SheetsApiInstaller,+) -> None:+ requests = sheets_api(+ [+ _google(id="goac_denied", credential_name="Personal"),+ _google(id="goac_opens", credential_name="Ops", email_address="[email protected]"),+ _google(id="goac_expired_grant", credential_name="Old"),+ _google(id="goac_gmail_only", scopes_granted=["https://www.googleapis.com/auth/gmail.readonly"]),+ _google(id="goac_needs_reconnect", state="error"),+ ],+ {"goac_denied": DENIED_TOKEN, "goac_opens": OPENING_TOKEN, "goac_expired_grant": None},+ )++ result = await _read_google_sheet({"spreadsheet_url": SHEET_URL}, _sheet_ctx())++ assert result["ok"] is True+ data = result["data"]+ assert data["connections"] == [+ {+ "connection_id": "goac_denied",+ "name": "Personal",+ "status": "no_access",+ "reason": "403: The caller does not have permission",+ },+ {"connection_id": "goac_opens", "name": "Ops", "status": "opened", "email_address": "[email protected]"},+ {"connection_id": "goac_expired_grant", "name": "Old", "status": "token_unavailable"},+ ]+ assert data["title"] == "Fleet metrics"+ assert data["tabs"] == [+ {"title": "Summary", "gid": 0, "row_count": 1000, "column_count": 26},+ {"title": "Budget", "gid": BUDGET_GID, "row_count": 12, "column_count": 3},+ ]+ assert data["read_through"] == "goac_opens"+ assert data["range"] == "'Budget'!A1:C12"+ assert data["values"] == [["Metric", "Value"], ["Sessions", "72.51k"]]+ assert data["truncated"] is False+ assert requests[-1].url.params["ranges"] == "'Budget'!A1:C12"+ serialized = json.dumps(result)+ assert "ya29." not in serialized+ assert not any(name in serialized for name in ("access_token", "refresh_token", "client_secret", "id_token"))+++async def test_read_google_sheet_reads_a_requested_range_on_the_gid_tab(sheets_api: SheetsApiInstaller) -> None:+ requests = sheets_api([_google(id="goac_opens")], {"goac_opens": OPENING_TOKEN}, rows=[["72.51k"]])++ result = await _read_google_sheet(+ {"spreadsheet_url": SHEET_URL, "connection_id": "goac_opens", "range": "B2"}, _sheet_ctx()+ )++ assert result["data"]["range"] == "'Budget'!B2"+ assert result["data"]["values"] == [["72.51k"]]+ assert requests[-1].url.params["ranges"] == "'Budget'!B2"+++async def test_read_google_sheet_refuses_a_spreadsheet_the_user_did_not_give_before_any_call(+ sheets_api: SheetsApiInstaller,+) -> None:+ requests = sheets_api([_google(id="goac_opens")], {})+ ctx = _sheet_ctx()++ result = await _read_google_sheet(+ {"spreadsheet_url": f"https://docs.google.com/spreadsheets/d/{OTHER_SPREADSHEET_ID}/edit"}, ctx+ )++ assert result["ok"] is False+ assert "data" not in result+ assert requests == []+++def test_every_spreadsheet_url_the_user_wrote_is_readable_not_one_per_origin() -> None:+ policy = RequestPolicy()+ second_url = f"https://docs.google.com/spreadsheets/d/{OTHER_SPREADSHEET_ID}/edit"++ _ground_user_provided_sites(policy, f"move the totals from {SHEET_URL} to {second_url}.", [])++ assert policy.user_provided_spreadsheet_ids == [SPREADSHEET_ID, OTHER_SPREADSHEET_ID]+++async def test_read_google_sheet_reports_a_connection_id_outside_the_eligible_set_without_trying_it(+ sheets_api: SheetsApiInstaller,+) -> None:+ requests = sheets_api([_google(id="goac_opens"), _google(id="goac_needs_reconnect", state="error")], {})++ result = await _read_google_sheet(+ {"spreadsheet_url": SHEET_URL, "connection_id": "goac_needs_reconnect"}, _sheet_ctx()+ )++ assert result["ok"] is True+ assert result["data"]["connections"] == [{"connection_id": "goac_needs_reconnect", "status": "not_eligible"}]+ assert requests == []+++async def test_read_google_sheet_reports_a_hung_connection_as_a_timeout_row(+ monkeypatch: pytest.MonkeyPatch, sheets_api: SheetsApiInstaller+) -> None:+ sheets_api([_google(id="goac_hung"), _google(id="goac_opens")], {"goac_opens": OPENING_TOKEN})+ mint = app.AGENT_FUNCTION.get_google_sheets_credentials++ async def hung_mint(organization_id: str, connection_id: str) -> str | None:+ if connection_id == "goac_hung":+ await asyncio.Event().wait()+ return await mint(organization_id, connection_id)++ monkeypatch.setattr(app.AGENT_FUNCTION, "get_google_sheets_credentials", hung_mint)+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools.integrations._SHEET_READ_TIMEOUT_SECONDS", 0.05)++ result = await asyncio.wait_for(_read_google_sheet({"spreadsheet_url": SHEET_URL}, _sheet_ctx()), timeout=2)++ assert result["ok"] is True+ assert [(row["connection_id"], row["status"]) for row in result["data"]["connections"]] == [+ ("goac_hung", "error"),+ ("goac_opens", "opened"),+ ]+ assert result["data"]["connections"][0]["reason"] == "timeout"+ assert result["data"]["read_through"] == "goac_opens"+++async def test_read_google_sheet_reads_a_named_tab_as_given_and_reports_a_gid_no_tab_has(+ sheets_api: SheetsApiInstaller,+) -> None:+ requests = sheets_api([_google(id="goac_opens")], {"goac_opens": OPENING_TOKEN})+ stale_gid_url = SHEET_URL.replace(str(BUDGET_GID), "424242")++ named_tab = await _read_google_sheet({"spreadsheet_url": SHEET_URL, "range": "Summary"}, _sheet_ctx())+ stale_gid = await _read_google_sheet({"spreadsheet_url": stale_gid_url}, _sheet_ctx())++ assert named_tab["data"]["range"] == "Summary"+ assert "424242" in stale_gid["data"]["values_error"]+ assert "values" not in stale_gid["data"]+ assert [request.url.params.get("ranges") for request in requests] == [None, "Summary", None]+++ ("values_response", "values_error"),+ [+ (httpx.Response(200, text="<html>not json</html>"), "JSONDecodeError"),+ (+ httpx.Response(400, json={"error": {"message": f"Unable to parse range for {OPENING_TOKEN}"}}),+ "400: Unable to parse range for [token]",+ ),+ ],+)+async def test_read_google_sheet_keeps_the_opened_connection_and_no_token_when_the_values_read_fails(+ sheets_api: SheetsApiInstaller, values_response: httpx.Response, values_error: str+) -> None:+ sheets_api([_google(id="goac_opens")], {"goac_opens": OPENING_TOKEN}, values_response=values_response)++ result = await _read_google_sheet({"spreadsheet_url": SHEET_URL}, _sheet_ctx())++ assert result["ok"] is True+ assert result["data"]["connections"][0]["status"] == "opened"+ assert result["data"]["values_error"] == values_error+ assert "ya29." not in json.dumps(result)++[email protected]("cell_character", ["x", "表", "😀"])+async def test_read_google_sheet_bounds_an_oversized_sheet_and_says_so(+ sheets_api: SheetsApiInstaller, cell_character: str+) -> None:+ sheets_api([_google(id="goac_opens")], {"goac_opens": OPENING_TOKEN}, rows=[[cell_character * 5_000] * 60] * 400)++ result = await _read_google_sheet({"spreadsheet_url": SHEET_URL, "range": "A1:ZZ400"}, _sheet_ctx())++ values = result["data"]["values"]+ assert 0 < len(values) <= 50+ assert all(len(row) <= 26 and all(len(cell) <= 200 for cell in row) for row in values)+ assert result["data"]["truncated"] is True+ assert len(json.dumps(result)) < 20_000+++def test_read_google_sheet_description_states_facts_without_steering() -> None:+ registered = {+ tool.name: tool for tool in copilot_native_tools(supports_question_tool=True, browser_code_available=False)+ }+ tool = registered["read_google_sheet"]+ description = tool.description.lower()++ assert set(tool.params_json_schema["properties"]) == {+ "spreadsheet_url",+ "connection_id",+ "range",+ USER_FACING_REASON_PARAM,+ }+ for status in ("opened", "no_access", "token_unavailable", "not_eligible"):+ assert status in description+ for steering in ("ask the user", "reconnect", "instead of", "prefer", "do not", "must call", "browser ui"):+ assert steering not in descriptiondiff --git a/tests/unit/test_custom_llms.py b/tests/unit/test_custom_llms.pyindex 30faf1c48..02588b57e 100644--- a/tests/unit/test_custom_llms.py+++ b/tests/unit/test_custom_llms.py@@ -45,6 +45,9 @@ class FakeOrganizationsRepository:self.updated_encrypted_methods: list[EncryptMethod | None] = []self.update_organization = AsyncMock()+ async def get_organization(self, organization_id: str) -> Organization | None:+ return None+async def get_valid_org_auth_tokens(self,organization_id: str,diff --git a/tests/unit/test_llm_handler_parity_characterization.py b/tests/unit/test_llm_handler_parity_characterization.pyindex 95b130a80..337ed5aac 100644--- a/tests/unit/test_llm_handler_parity_characterization.py+++ b/tests/unit/test_llm_handler_parity_characterization.py@@ -16,6 +16,7 @@ from unittest.mock import AsyncMock, MagicMockimport litellm # type: ignore[import-not-found]import pytest # type: ignore[import-not-found]+import structlogfrom opentelemetry.sdk.trace import ReadableSpanfrom opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter@@ -196,6 +197,9 @@ def _stub_common(mp: pytest.MonkeyPatch, outcome: HandlerOutcome, context: Skyveif _event == "LLM API handler duration metrics":outcome.metrics_events.append(fields)+ # Patching `info` on the shared lazy proxy leaves a stale bound method behind on undo, which detaches the+ # module's logger from later `capture_logs()` calls; a throwaway proxy keeps the shared one untouched.+ mp.setattr(api_handler_factory, "LOG", structlog.get_logger())mp.setattr(api_handler_factory.LOG, "info", capture_info)artifact_manager = MagicMock()diff --git a/tests/unit/test_organization_slug.py b/tests/unit/test_organization_slug.pyindex afb38aa0b..07c750c71 100644--- a/tests/unit/test_organization_slug.py+++ b/tests/unit/test_organization_slug.py@@ -25,6 +25,19 @@ def _integrity_error(constraint_name: str) -> IntegrityError:)+def _organization_snapshot() -> SimpleNamespace:+ return SimpleNamespace(+ slug="before",+ webhook_callback_url=None,+ max_steps_per_run=None,+ max_steps_per_workflow_run=None,+ max_retries_per_step=None,+ artifact_url_expiry_seconds=None,+ default_llm_key=None,+ default_secondary_llm_key=None,+ )++@pytest.mark.parametrize(("organization_name", "organization_id", "expected"),[@@ -230,13 +243,18 @@ async def test_update_organization_returns_conflict_for_duplicate_slug(monkeypatch.setattr(agent_protocol.app,"DATABASE",- SimpleNamespace(organizations=SimpleNamespace(update_organization=update_organization)),+ SimpleNamespace(+ organizations=SimpleNamespace(+ get_organization=AsyncMock(return_value=_organization_snapshot()),+ update_organization=update_organization,+ )+ ),)with pytest.raises(HTTPException) as exc_info:await agent_protocol.update_organization(OrganizationUpdate(slug="taken"),- current_org=SimpleNamespace(organization_id="o_123", webhook_callback_url=None),+ current_org=SimpleNamespace(organization_id="o_123", slug="before", webhook_callback_url=None),)assert exc_info.value.status_code == 409@@ -252,13 +270,18 @@ async def test_update_organization_reraises_unrelated_integrity_error(monkeypatcmonkeypatch.setattr(agent_protocol.app,"DATABASE",- SimpleNamespace(organizations=SimpleNamespace(update_organization=update_organization)),+ SimpleNamespace(+ organizations=SimpleNamespace(+ get_organization=AsyncMock(return_value=_organization_snapshot()),+ update_organization=update_organization,+ )+ ),)with pytest.raises(IntegrityError) as exc_info:await agent_protocol.update_organization(OrganizationUpdate(slug="available"),- current_org=SimpleNamespace(organization_id="o_123", webhook_callback_url=None),+ current_org=SimpleNamespace(organization_id="o_123", slug="before", webhook_callback_url=None),)assert exc_info.value is error@@ -280,7 +303,7 @@ async def test_update_organization_rejects_explicit_slug_clear(monkeypatch: pytewith pytest.raises(HTTPException) as exc_info:await agent_protocol.update_organization(OrganizationUpdate(slug=None),- current_org=SimpleNamespace(organization_id="o_123", webhook_callback_url=None),+ current_org=SimpleNamespace(organization_id="o_123", slug="before", webhook_callback_url=None),)assert exc_info.value.status_code == 400diff --git a/tests/unit/test_twilio_integration_routes.py b/tests/unit/test_twilio_integration_routes.pyindex 98dbca1e1..bf18f2253 100644--- a/tests/unit/test_twilio_integration_routes.py+++ b/tests/unit/test_twilio_integration_routes.py@@ -169,6 +169,7 @@ def _registered_phone(config: SMSConfig, **overrides: object) -> OrganizationPhodef _database(*, token: SimpleNamespace | None = None) -> SimpleNamespace:organizations = SimpleNamespace(+ has_valid_org_auth_token=AsyncMock(return_value=token is not None),get_valid_org_auth_token=AsyncMock(return_value=token),replace_org_auth_token=AsyncMock(),invalidate_org_auth_tokens=AsyncMock(),