Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(plugins): native Google Drive REST tool + full Google scopes
Ruben Lütked74d9029a082
diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.pyindex df2e3e54df..dc5a2e0022 100644--- a/jarvis/brain/factory.py+++ b/jarvis/brain/factory.py@@ -156,6 +156,13 @@ ROUTER_TOOLS = frozenset({# MCP server block, so it must be router-visible directly; otherwise a# connected calendar is not callable by voice/chat. Never a spawn (AP-5/AP-14)."google_calendar",+ # Google Drive Marketplace plugin (2026-07-23): native REST tool. Replaces+ # Google's hosted Drive MCP (drivemcp.googleapis.com), which 403s every+ # data-plane call for consumer @gmail.com accounts (Workspace Developer+ # Preview). No MCP server block anymore, so it must be router-visible+ # directly; otherwise a connected Drive is not callable by voice/chat. Never+ # a spawn (AP-5/AP-14).+ "google_drive",# Computer-Use (Wave 1, 2026-05-29): first-class, clearly-described tool to# drive the user's LIVE desktop (open apps, click, type, scroll, operate# any GUI). The router previously had no honest desktop path — spawn-workerdiff --git a/jarvis/marketplace/seed_catalog.json b/jarvis/marketplace/seed_catalog.jsonindex 8022923d79..f1a3eb5ddf 100644--- a/jarvis/marketplace/seed_catalog.json+++ b/jarvis/marketplace/seed_catalog.json@@ -256,7 +256,7 @@{"id": "google_drive","display_name": "Google Drive",- "description": "Files Jarvis creates or you share with it (drive.file)",+ "description": "Search, read, create, share and delete your Drive files","category": "Productivity","logo_slug": "googledrive","featured": false,@@ -268,23 +268,19 @@"client_id": "REPLACE_WITH_JARVIS_GOOGLE_CLIENT_ID","callback_port": 3120,"callback_path": "",- "scopes": ["https://www.googleapis.com/auth/drive.file"],+ "scopes": ["https://www.googleapis.com/auth/drive"],"scope_separator": "space","user_scopes_only": false,"refresh_supported": true,"offline_access": true},- "mcp_server": {- "transport": "http",- "url": "https://drivemcp.googleapis.com/mcp/v1",- "auth_header_template": "Authorization: Bearer ${plugin_google_drive_access_token}"- },- "post_install_hint_md": "Setup: see docs/marketplace/google-oauth-setup.md. Uses the non-sensitive drive.file scope. Publish the Google consent app to 'In production' so offline access can refresh normally; a 'Testing' grant expires after 7 days. The Drive MCP server is Google's official endpoint (Developer Preview)."+ "native_tool": "google_drive",+ "post_install_hint_md": "Setup: see docs/marketplace/google-oauth-setup.md (shares the Google client with Gmail/Calendar). Talks to the Drive REST API v3 directly (Google's hosted Drive MCP is a Workspace-only Developer Preview that 403s consumer accounts). The full 'drive' scope grants read/write/delete over ALL your files and is a Google RESTRICTED scope: in 'Testing' status the refresh grant expires after 7 days, so publish the consent app to 'In production' and complete Google's restricted-scope (CASA) verification for uninterrupted offline access. A user, account, or administrator can still revoke the grant."},{"id": "gmail","display_name": "Gmail",- "description": "Read and send mail from your inbox",+ "description": "Read, send, organize and delete mail in your inbox","category": "Communication","logo_slug": "gmail","featured": false,@@ -297,8 +293,7 @@"callback_port": 3121,"callback_path": "","scopes": [- "https://www.googleapis.com/auth/gmail.readonly",- "https://www.googleapis.com/auth/gmail.send"+ "https://mail.google.com/"],"scope_separator": "space","user_scopes_only": false,diff --git a/jarvis/marketplace/usage_cards/google_drive.md b/jarvis/marketplace/usage_cards/google_drive.mdindex fcf2708412..49fb27d8f2 100644--- a/jarvis/marketplace/usage_cards/google_drive.md+++ b/jarvis/marketplace/usage_cards/google_drive.md@@ -2,8 +2,9 @@plugin_id: google_drivekeywords: drive, google drive, datei, dateien, file, files, ordner, folder, dokument, document, dokumente, documents, teilen, share, suche, search, hochladen, upload, erstellen, create, herunterladen, download----Use google_drive/* tools to list, search, read, create, and share files in Google Drive.-- The drive.file scope limits access to files Jarvis created or the user explicitly shared.+Use the google_drive tool to list, search, read, create, share and delete files in Google Drive.+- The full 'drive' scope grants access to ALL the user's files (read/write/delete), not just app-created ones.- Search by name or MIME type before creating; avoid duplicates.- Create and upload files directly (full autonomy); report file name and Drive URL afterwards.- Folders can be created and used as targets for new files.+- Sharing exposes data outward and deleting is destructive — both confirm before acting.diff --git a/jarvis/plugins/tool/drive_rest.py b/jarvis/plugins/tool/drive_rest.pynew file mode 100644index 0000000000..6a7743fbc5--- /dev/null+++ b/jarvis/plugins/tool/drive_rest.py@@ -0,0 +1,510 @@+"""google_drive tool — list, read, create, share and delete files via the+Google Drive REST API (v3).++Wired Node-free and MCP-free: the marketplace's PKCE-loopback flow stores the+user's Google OAuth token in the credential store (key ``plugin_google_drive_+tokens``); this tool reads that access token and calls the Drive REST API+directly, exactly like ``gmail_rest.py`` does for Gmail.++Why native instead of Google's hosted Drive MCP: the catalog used to point+Drive at ``https://drivemcp.googleapis.com/mcp/v1``. That endpoint is a Google+*Workspace* Developer-Preview server; for a consumer @gmail.com account it lets+``initialize`` through (200) but answers every data-plane call with 403+Forbidden (live forensic 2026-07-23: initialize 200 → notifications 202 →+tools/call 403, on every single Drive turn). Nothing client-side fixes that —+the raw Drive REST API v3 returns the same files with the same token, so we+talk to it directly.++Router-tier tool (like ``gmail``/``google_calendar``). Per-action risk tiers:+reads are ``safe``; create/folder are ``monitor`` (audited, no prompt — full+autonomy, matching the usage card); share and delete are ``ask`` (they expose+or destroy data — echo-confirm before acting).+"""+from __future__ import annotations++import json+import logging+from collections.abc import Awaitable, Callable+from typing import Any++from jarvis.core.protocols import ExecutionContext, ToolResult++log = logging.getLogger(__name__)++_DRIVE_BASE = "https://www.googleapis.com/drive/v3"+_DRIVE_UPLOAD = "https://www.googleapis.com/upload/drive/v3/files"++# User-facing error strings (English per CLAUDE.md; the brain rephrases to the+# user's language). Kept distinct so the brain can tell "never connected" from+# "was connected, token died — reconnect".+_NOT_CONNECTED = "Google Drive is not connected — connect it in the Plugins view."+_NEEDS_RECONNECT = (+ "Google Drive authorization expired and could not be renewed — "+ "please reconnect Google Drive in the Plugins view."+)++# Reading a file's content into the model context is bounded like Gmail's body:+# a large document would blow the context and slow the voice turn for no answer+# value. We cap the extracted text and mark the truncation.+_DRIVE_CONTENT_CHAR_CAP = 4000++# Field projection for list/get — only what actually answers a file question,+# incl. the webViewLink (the "Drive URL" the usage card asks us to report back).+_FILE_FIELDS = (+ "id,name,mimeType,modifiedTime,size,webViewLink,"+ "owners(displayName,emailAddress),parents"+)+_LIST_FIELDS = f"files({_FILE_FIELDS}),nextPageToken"++# Google-native types can't be downloaded raw — they must be EXPORTED to a+# concrete format. Map the common ones to a text export MIME.+_GOOGLE_EXPORT_MIME: dict[str, str] = {+ "application/vnd.google-apps.document": "text/plain",+ "application/vnd.google-apps.spreadsheet": "text/csv",+ "application/vnd.google-apps.presentation": "text/plain",+ "application/vnd.google-apps.script": "application/vnd.google-apps.script+json",+}+_FOLDER_MIME = "application/vnd.google-apps.folder"+++def _default_token_provider() -> str | None:+ from jarvis.marketplace.token_store import TokenStore++ tokens = TokenStore().load("google_drive")+ return tokens.access if tokens is not None else None+++async def _default_refresher(observed_access_token: str | None = None) -> bool:+ """Refresh the stored Google Drive token in place. Returns True on success.++ On an un-healable failure (revoked / invalid_client / placeholder client) it+ flags ``needs_reauth`` on the stored token so the Plugins view stops showing+ a green "connected" that lies and offers a Reconnect instead. Best-effort:+ any error returns False, never raises into the tool."""+ from jarvis.marketplace.connect_helpers import build_handler_from_catalog+ from jarvis.marketplace.refresh_scheduler import refresh_plugin_token+ from jarvis.marketplace.token_store import TokenStore++ store = TokenStore()+ attempt = await refresh_plugin_token(+ "google_drive",+ store,+ build_handler_from_catalog,+ force=True,+ observed_access_token=observed_access_token,+ )+ return attempt.usable+++def _slim_file(raw: dict[str, Any]) -> dict[str, Any]:+ """Project a raw Drive file resource to the fields that answer a file+ question — dropping the long ``owners`` list to a single display name."""+ owners = raw.get("owners") or []+ owner = ""+ if owners:+ o0 = owners[0]+ owner = o0.get("displayName") or o0.get("emailAddress") or ""+ return {+ "id": raw.get("id"),+ "name": raw.get("name"),+ "mimeType": raw.get("mimeType"),+ "modifiedTime": raw.get("modifiedTime"),+ "size": raw.get("size"),+ "url": raw.get("webViewLink"),+ "owner": owner,+ }+++def _escape_drive_q(value: str) -> str:+ """Escape a literal for a Drive ``q`` string clause (single-quote + backslash)."""+ return value.replace("\\", "\\\\").replace("'", "\\'")+++class DriveRestTool:+ name: str = "google_drive"+ risk_tier: str = "monitor"+ description: str = (+ "List, search, read, create, share and delete files in the user's "+ "connected Google Drive. Use for 'what's in my Drive', 'find the file "+ "named X', 'read that document', 'create a file', 'share it with X', "+ "'delete that file'. Actions: list_files (search/list — pass a plain "+ "search_text, or a raw Drive q query for power users; empty lists the "+ "most recently modified files), get_file (metadata by id), read_file "+ "(extract text content by id; Google Docs/Sheets are exported to text), "+ "create_file (name + text content, optional folder id), create_folder "+ "(name, optional parent folder id), share_file (id + either an "+ "emailAddress to share with one person, or public=true for a view link), "+ "delete_file (id). Requires the Google Drive plugin to be connected in "+ "the Plugins view. Always report the file name and its Drive URL back."+ )+ schema: dict[str, Any] = {+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "enum": [+ "list_files",+ "get_file",+ "read_file",+ "create_file",+ "create_folder",+ "share_file",+ "delete_file",+ ],+ "default": "list_files",+ },+ "search_text": {+ "type": "string",+ "description": "Plain text to match in file name or full text (list_files)",+ },+ "query": {+ "type": "string",+ "description": "Raw Drive 'q' query for power users; overrides search_text",+ },+ "max_results": {"type": "integer", "default": 15},+ "file_id": {"type": "string", "description": "target file id"},+ "name": {+ "type": "string",+ "description": "file/folder name (create_file/create_folder)",+ },+ "content": {"type": "string", "description": "text content (create_file)"},+ "mime_type": {+ "type": "string",+ "description": "MIME type for create_file (default text/plain)",+ },+ "parent_id": {+ "type": "string",+ "description": "target folder id for create_file/create_folder (optional)",+ },+ "email_address": {+ "type": "string",+ "description": "share with this Google account (share_file)",+ },+ "public": {+ "type": "boolean",+ "description": "share_file: make it viewable by anyone with the link",+ },+ "role": {+ "type": "string",+ "enum": ["reader", "writer", "commenter"],+ "default": "reader",+ "description": "permission role for share_file",+ },+ },+ "required": ["action"],+ }++ def __init__(+ self,+ access_token_provider: Callable[[], str | None] | None = None,+ transport: Any | None = None,+ token_refresher: Callable[[], Awaitable[bool]] | None = None,+ ) -> None:+ from ._http_pool import HttpClientPool++ self._token_provider = access_token_provider or _default_token_provider+ self._transport = transport+ self._refresher = token_refresher+ # Keep-alive pool: one warm TLS connection to googleapis.com reused+ # across list/get/read instead of a fresh handshake per request.+ self._pool = HttpClientPool(transport=transport)++ # -- internal helpers ---------------------------------------------------++ def _bearer(self) -> dict[str, str] | None:+ token = self._token_provider()+ if not token:+ return None+ return {"Authorization": f"Bearer {token}", "User-Agent": "Personal-Jarvis/1.0"}++ async def _with_auth_retry(+ self, do_call: Callable[[dict[str, str]], Awaitable[Any]]+ ) -> Any:+ """Run an authenticated Drive call; on a 401 refresh once and retry.++ Centralises the self-heal so every action recovers from an expired+ access token instead of returning a hard auth error. Returns the call's+ result on success, or a ``{"error": ...}`` dict the caller maps to a+ ToolResult."""+ import httpx++ headers = self._bearer()+ if headers is None:+ return {"error": _NOT_CONNECTED}+ try:+ return await do_call(headers)+ except httpx.HTTPStatusError as exc:+ if exc.response.status_code != 401:+ raise+ # 401 — token likely expired. Try exactly one refresh + retry.+ observed_token = headers["Authorization"].removeprefix("Bearer ")+ try:+ if self._refresher is None:+ refreshed = bool(await _default_refresher(observed_token))+ else:+ refreshed = bool(await self._refresher())+ except Exception: # noqa: BLE001 — refresher must never crash the tool+ refreshed = False+ if not refreshed:+ return {"error": _NEEDS_RECONNECT}+ headers = self._bearer()+ if headers is None:+ return {"error": _NEEDS_RECONNECT}+ return await do_call(headers)++ async def _get_json(self, path: str, params: dict[str, Any], headers: dict[str, str]):+ client = self._pool.client()+ resp = await client.get(f"{_DRIVE_BASE}{path}", params=params, headers=headers)+ resp.raise_for_status()+ return resp.json()++ async def _get_text(self, path: str, params: dict[str, Any], headers: dict[str, str]) -> str:+ client = self._pool.client()+ resp = await client.get(f"{_DRIVE_BASE}{path}", params=params, headers=headers)+ resp.raise_for_status()+ return resp.text++ # -- public actions (also directly unit-testable) -----------------------++ async def list_files(+ self, *, search_text: str = "", query: str = "", max_results: int = 15+ ) -> dict[str, Any]:+ q = query.strip()+ if not q and search_text.strip():+ esc = _escape_drive_q(search_text.strip())+ q = f"(name contains '{esc}' or fullText contains '{esc}')"+ # Never surface trashed files.+ q = f"({q}) and trashed = false" if q else "trashed = false"+ params = {+ "q": q,+ "pageSize": max(1, min(int(max_results), 100)),+ "fields": _LIST_FIELDS,+ "orderBy": "modifiedTime desc",+ "spaces": "drive",+ "corpora": "user",+ }+ out = await self._with_auth_retry(+ lambda headers: self._get_json("/files", params, headers)+ )+ if isinstance(out, dict) and out.get("error"):+ return out+ files = [_slim_file(f) for f in (out.get("files") or [])]+ return {"files": files, "count": len(files)}++ async def get_file(self, *, file_id: str) -> dict[str, Any]:+ out = await self._with_auth_retry(+ lambda headers: self._get_json(+ f"/files/{file_id}", {"fields": _FILE_FIELDS}, headers+ )+ )+ if isinstance(out, dict) and out.get("error"):+ return out+ return _slim_file(out)++ async def read_file(self, *, file_id: str) -> dict[str, Any]:+ meta = await self.get_file(file_id=file_id)+ if isinstance(meta, dict) and meta.get("error"):+ return meta+ mime = meta.get("mimeType") or ""+ text: str | None = None+ if mime in _GOOGLE_EXPORT_MIME:+ export_mime = _GOOGLE_EXPORT_MIME[mime]+ text = await self._with_auth_retry(+ lambda headers: self._get_text(+ f"/files/{file_id}/export", {"mimeType": export_mime}, headers+ )+ )+ elif mime.startswith("text/") or mime in (+ "application/json",+ "application/xml",+ "application/csv",+ ):+ text = await self._with_auth_retry(+ lambda headers: self._get_text(f"/files/{file_id}", {"alt": "media"}, headers)+ )+ if isinstance(text, dict) and text.get("error"):+ return text+ if text is None:+ return {**meta, "content": None, "note": "binary file — not read as text"}+ if len(text) > _DRIVE_CONTENT_CHAR_CAP:+ text = text[:_DRIVE_CONTENT_CHAR_CAP] + "… [truncated]"+ return {**meta, "content": text}++ async def create_file(+ self,+ *,+ name: str,+ content: str = "",+ mime_type: str = "text/plain",+ parent_id: str = "",+ ) -> dict[str, Any]:+ metadata: dict[str, Any] = {"name": name}+ if parent_id.strip():+ metadata["parents"] = [parent_id.strip()]+ boundary = "jarvis_drive_multipart_boundary"+ body = (+ f"--{boundary}\r\n"+ "Content-Type: application/json; charset=UTF-8\r\n\r\n"+ f"{json.dumps(metadata)}\r\n"+ f"--{boundary}\r\n"+ f"Content-Type: {mime_type}\r\n\r\n"+ f"{content}\r\n"+ f"--{boundary}--"+ )++ async def _do(headers: dict[str, str]):+ client = self._pool.client()+ h = {+ **headers,+ "Content-Type": f"multipart/related; boundary={boundary}",+ }+ resp = await client.post(+ _DRIVE_UPLOAD,+ params={"uploadType": "multipart", "fields": _FILE_FIELDS},+ content=body.encode("utf-8"),+ headers=h,+ )+ resp.raise_for_status()+ return resp.json()++ out = await self._with_auth_retry(_do)+ if isinstance(out, dict) and out.get("error"):+ return out+ return _slim_file(out)++ async def create_folder(self, *, name: str, parent_id: str = "") -> dict[str, Any]:+ metadata: dict[str, Any] = {"name": name, "mimeType": _FOLDER_MIME}+ if parent_id.strip():+ metadata["parents"] = [parent_id.strip()]++ async def _do(headers: dict[str, str]):+ client = self._pool.client()+ resp = await client.post(+ f"{_DRIVE_BASE}/files",+ params={"fields": _FILE_FIELDS},+ json=metadata,+ headers=headers,+ )+ resp.raise_for_status()+ return resp.json()++ out = await self._with_auth_retry(_do)+ if isinstance(out, dict) and out.get("error"):+ return out+ return _slim_file(out)++ async def share_file(+ self,+ *,+ file_id: str,+ email_address: str = "",+ public: bool = False,+ role: str = "reader",+ ) -> dict[str, Any]:+ if email_address.strip():+ perm = {"type": "user", "role": role, "emailAddress": email_address.strip()}+ elif public:+ perm = {"type": "anyone", "role": role}+ else:+ return {"error": "share_file needs either email_address or public=true"}++ async def _do(headers: dict[str, str]):+ client = self._pool.client()+ resp = await client.post(+ f"{_DRIVE_BASE}/files/{file_id}/permissions",+ json=perm,+ headers=headers,+ )+ resp.raise_for_status()+ return resp.json()++ out = await self._with_auth_retry(_do)+ if isinstance(out, dict) and out.get("error"):+ return out+ # Return the file's shareable link so the brain can read it back.+ meta = await self.get_file(file_id=file_id)+ return {"shared": True, "permission": out, "file": meta}++ async def delete_file(self, *, file_id: str) -> dict[str, Any]:+ async def _do(headers: dict[str, str]):+ client = self._pool.client()+ resp = await client.delete(f"{_DRIVE_BASE}/files/{file_id}", headers=headers)+ resp.raise_for_status()+ return {"deleted": True, "file_id": file_id}++ return await self._with_auth_retry(_do)++ # -- Tool protocol ------------------------------------------------------++ def risk_tier_for_args(self, args: dict[str, Any]) -> str:+ """Per-action risk tier (consulted by ``RiskTierEvaluator``).++ Reads are ``safe``; create/folder are ``monitor`` (audited, no prompt —+ full autonomy, matching the usage card). ``share_file`` and+ ``delete_file`` are consequential (they expose data outward or destroy+ it), so they keep the ``ask`` tier + the two-turn echo-confirm. An+ unrecognised action stays conservative (``ask``), never silently safe."""+ action = (args.get("action") or "list_files").strip()+ if action in ("list_files", "get_file", "read_file"):+ return "safe"+ if action in ("create_file", "create_folder"):+ return "monitor"+ return "ask" # share_file / delete_file / unknown++ async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:+ action = (args.get("action") or "list_files").strip()+ try:+ if action == "list_files":+ out = await self.list_files(+ search_text=args.get("search_text", ""),+ query=args.get("query", ""),+ max_results=int(args.get("max_results", 15)),+ )+ elif action == "get_file":+ fid = args.get("file_id")+ if not fid:+ return ToolResult(success=False, output=None, error="file_id missing")+ out = await self.get_file(file_id=fid)+ elif action == "read_file":+ fid = args.get("file_id")+ if not fid:+ return ToolResult(success=False, output=None, error="file_id missing")+ out = await self.read_file(file_id=fid)+ elif action == "create_file":+ nm = args.get("name")+ if not nm:+ return ToolResult(success=False, output=None, error="name missing")+ out = await self.create_file(+ name=nm,+ content=args.get("content", ""),+ mime_type=args.get("mime_type", "text/plain"),+ parent_id=args.get("parent_id", ""),+ )+ elif action == "create_folder":+ nm = args.get("name")+ if not nm:+ return ToolResult(success=False, output=None, error="name missing")+ out = await self.create_folder(name=nm, parent_id=args.get("parent_id", ""))+ elif action == "share_file":+ fid = args.get("file_id")+ if not fid:+ return ToolResult(success=False, output=None, error="file_id missing")+ out = await self.share_file(+ file_id=fid,+ email_address=args.get("email_address", ""),+ public=bool(args.get("public", False)),+ role=args.get("role", "reader"),+ )+ elif action == "delete_file":+ fid = args.get("file_id")+ if not fid:+ return ToolResult(success=False, output=None, error="file_id missing")+ out = await self.delete_file(file_id=fid)+ else:+ return ToolResult(success=False, output=None, error=f"unknown action {action!r}")+ except Exception as exc: # noqa: BLE001+ return ToolResult(success=False, output=None, error=str(exc))++ if isinstance(out, dict) and out.get("error"):+ return ToolResult(success=False, output=None, error=out["error"])+ return ToolResult(success=True, output=out)diff --git a/jarvis/plugins/tool/gmail_rest.py b/jarvis/plugins/tool/gmail_rest.pyindex bea280a189..2a9ae6073d 100644--- a/jarvis/plugins/tool/gmail_rest.py+++ b/jarvis/plugins/tool/gmail_rest.py@@ -130,10 +130,14 @@ class GmailRestTool:name: str = "gmail"risk_tier: str = "ask"description: str = (- "Read and send email from the user's connected Gmail inbox. "- "Use for 'check my mail', 'any new emails from X', 'read the last mail', "- "'send an email to X'. Actions: list_messages (search the inbox), "- "get_message (read one by id), send_message (compose + send). "+ "Read, send, organize and delete email in the user's connected Gmail "+ "inbox. Use for 'check my mail', 'any new emails from X', 'read the last "+ "mail', 'send an email to X', 'archive that', 'mark it read', 'move it to "+ "trash', 'delete it permanently'. Actions: list_messages (search the "+ "inbox), get_message (read one by id), send_message (compose + send), "+ "modify_message (add/remove labels by id — archive = remove 'INBOX', "+ "mark read = remove 'UNREAD', star = add 'STARRED'), trash_message (move "+ "to Trash, reversible), delete_message (permanent, irreversible). ""Requires the Gmail plugin to be connected in the Plugins view.")schema: dict[str, Any] = {@@ -141,15 +145,38 @@ class GmailRestTool:"properties": {"action": {"type": "string",- "enum": ["list_messages", "get_message", "send_message"],+ "enum": [+ "list_messages",+ "get_message",+ "send_message",+ "modify_message",+ "trash_message",+ "delete_message",+ ],"default": "list_messages",},"query": {"type": "string", "description": "Gmail search query (list_messages)"},"max_results": {"type": "integer", "default": 10},- "message_id": {"type": "string", "description": "message id (get_message)"},+ "message_id": {+ "type": "string",+ "description": "message id (get/modify/trash/delete_message)",+ },"to": {"type": "string", "description": "recipient (send_message)"},"subject": {"type": "string"},"body": {"type": "string"},+ "add_labels": {+ "type": "array",+ "items": {"type": "string"},+ "description": "label ids to add (modify_message), e.g. ['STARRED']",+ },+ "remove_labels": {+ "type": "array",+ "items": {"type": "string"},+ "description": (+ "label ids to remove (modify_message): ['INBOX'] archives, "+ "['UNREAD'] marks read"+ ),+ },},"required": ["action"],}@@ -224,8 +251,18 @@ class GmailRestTool:client = self._pool.client()resp = await client.post(f"{_GMAIL_BASE}{path}", json=json_body, headers=headers)resp.raise_for_status()+ # A 204 (e.g. trash returns a body; permanent delete returns 204 no body)+ # has no JSON — guard so the caller gets a stable ack either way.+ if resp.status_code == 204 or not resp.content:+ return {}return resp.json()+ async def _delete(self, path: str, headers: dict[str, str]):+ client = self._pool.client()+ resp = await client.delete(f"{_GMAIL_BASE}{path}", headers=headers)+ resp.raise_for_status()+ return {}+# -- public actions (also directly unit-testable) -----------------------async def list_messages(self, *, query: str = "", max_results: int = 10) -> dict[str, Any]:@@ -249,6 +286,32 @@ class GmailRestTool:lambda headers: self._post("/messages/send", {"raw": raw}, headers))+ async def modify_message(+ self,+ *,+ message_id: str,+ add_labels: list[str] | None = None,+ remove_labels: list[str] | None = None,+ ) -> dict[str, Any]:+ body = {+ "addLabelIds": list(add_labels or []),+ "removeLabelIds": list(remove_labels or []),+ }+ return await self._with_auth_retry(+ lambda headers: self._post(f"/messages/{message_id}/modify", body, headers)+ )++ async def trash_message(self, *, message_id: str) -> dict[str, Any]:+ return await self._with_auth_retry(+ lambda headers: self._post(f"/messages/{message_id}/trash", {}, headers)+ )++ async def delete_message(self, *, message_id: str) -> dict[str, Any]:+ """Permanent, irreversible delete (needs the full ``mail.google.com`` scope)."""+ return await self._with_auth_retry(+ lambda headers: self._delete(f"/messages/{message_id}", headers)+ )+# -- Tool protocol ------------------------------------------------------def risk_tier_for_args(self, args: dict[str, Any]) -> str:@@ -263,7 +326,13 @@ class GmailRestTool:action = (args.get("action") or "list_messages").strip()if action in ("list_messages", "get_message"):return "safe"- return "ask"+ # Reversible organization (archive / label / mark read, and Trash — which+ # Gmail keeps recoverable for 30 days) is audited but unprompted, so a+ # cleanup pass doesn't nag. Only send (outbound) and permanent delete+ # (irreversible) keep the two-turn echo-confirm. Unknown → conservative.+ if action in ("modify_message", "trash_message"):+ return "monitor"+ return "ask" # send_message / delete_message / unknownasync def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:action = (args.get("action") or "list_messages").strip()@@ -285,6 +354,25 @@ class GmailRestTool:out = await self.send_message(to=to, subject=args.get("subject", ""), body=args.get("body", ""))+ elif action == "modify_message":+ mid = args.get("message_id")+ if not mid:+ return ToolResult(success=False, output=None, error="message_id missing")+ out = await self.modify_message(+ message_id=mid,+ add_labels=args.get("add_labels") or [],+ remove_labels=args.get("remove_labels") or [],+ )+ elif action == "trash_message":+ mid = args.get("message_id")+ if not mid:+ return ToolResult(success=False, output=None, error="message_id missing")+ out = await self.trash_message(message_id=mid)+ elif action == "delete_message":+ mid = args.get("message_id")+ if not mid:+ return ToolResult(success=False, output=None, error="message_id missing")+ out = await self.delete_message(message_id=mid)else:return ToolResult(success=False, output=None, error=f"unknown action {action!r}")except Exception as exc: # noqa: BLE001diff --git a/pyproject.toml b/pyproject.tomlindex 09e77bb80f..a609ff9860 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -437,6 +437,15 @@ vercel = "jarvis.plugins.tool.vercel_rest:VercelRestTool"# spawn (AP-5/AP-14). Entry-point name matches the catalog native_tool +# token-store key "google_calendar".google_calendar = "jarvis.plugins.tool.google_calendar_rest:GoogleCalendarRestTool"+# Google Drive (marketplace plugin, 2026-07-23) — list/read/create/share/delete+# files via the Drive REST API v3 using the marketplace-stored OAuth token.+# Native tool because Google's hosted Drive MCP (drivemcp.googleapis.com) is a+# Workspace Developer-Preview server that answers every data-plane call with 403+# for consumer @gmail.com accounts (forensic 2026-07-23); the raw REST API works+# with the same token. Router-tier, per-action risk gating (reads safe, writes+# monitored, share/delete ask), never a spawn (AP-5/AP-14). Entry-point name+# matches the catalog native_tool + token-store key "google_drive".+google_drive = "jarvis.plugins.tool.drive_rest:DriveRestTool"screen-snapshot = "jarvis.plugins.tool.screen_snapshot:ScreenSnapshotTool"move-mouse = "jarvis.plugins.tool.move_mouse:MoveMouseTool"switch-window = "jarvis.plugins.tool.switch_window:SwitchWindowTool"diff --git a/tests/unit/brain/test_routing.py b/tests/unit/brain/test_routing.pyindex 21338ed2ae..2e50d0ce41 100644--- a/tests/unit/brain/test_routing.py+++ b/tests/unit/brain/test_routing.py@@ -1898,6 +1898,11 @@ def test_router_tools_is_pure_dispatcher_set() -> None:# as gmail — no MCP server block, so it must be router-visible# directly. Full autonomy (writes are monitor, never ask)."google_calendar",+ # Google Drive Marketplace plugin (2026-07-23): native REST tool+ # replacing Google's hosted Drive MCP (403s consumer accounts). No+ # MCP server block, so it must be router-visible directly; per-action+ # risk gating (reads safe, writes monitor, share/delete ask).+ "google_drive",# Computer-Use (Wave 1, 2026-05-29): first-class tool to drive the# live desktop. Router-tier only — a direct safe-gated action (the# loop gates each action via ToolExecutor, ADR-0008), never a spawn,diff --git a/tests/unit/marketplace/test_catalog_seed.py b/tests/unit/marketplace/test_catalog_seed.pyindex bf16133e81..708c4fb558 100644--- a/tests/unit/marketplace/test_catalog_seed.py+++ b/tests/unit/marketplace/test_catalog_seed.py@@ -174,24 +174,33 @@ def test_asana_is_pkce_loopback_with_resource_and_http_mcp() -> None:assert spec.mcp_server["url"] == "https://mcp.asana.com/v2/mcp"-def test_google_drive_uses_drive_file_scope() -> None:+def test_google_drive_uses_full_drive_scope_via_native_tool() -> None:+ # 2026-07-23: Drive moved off Google's hosted Drive MCP (a Workspace+ # Developer-Preview endpoint that 403s consumer @gmail.com accounts on every+ # data-plane call) onto a native REST tool. The catalog therefore carries a+ # native_tool + NO mcp_server, and the full 'drive' scope (all files, per the+ # "voller Zugriff" mandate) rather than the app-scoped drive.file.spec = _seed().by_id("google_drive")assert spec is not Noneassert spec.display_name == "Google Drive"assert spec.auth.mode == "oauth_pkce_loopback"- assert "https://www.googleapis.com/auth/drive.file" in spec.auth.scopes+ assert spec.auth.scopes == ["https://www.googleapis.com/auth/drive"]+ assert spec.native_tool == "google_drive"+ assert spec.mcp_server is Noneassert spec.auth.scope_separator == "space"assert spec.auth.callback_path == ""assert spec.auth.offline_access is True-def test_gmail_pkce_loopback_read_and_send_scopes() -> None:+def test_gmail_pkce_loopback_full_mail_scope() -> None:+ # 2026-07-23: Gmail widened to the full mail.google.com scope (read + send ++ # organize + delete) so the native tool's modify/trash/delete actions have+ # the grant they need ("voller Zugriff" mandate).spec = _seed().by_id("gmail")assert spec is not Noneassert spec.display_name == "Gmail"assert spec.auth.mode == "oauth_pkce_loopback"- assert "https://www.googleapis.com/auth/gmail.readonly" in spec.auth.scopes- assert "https://www.googleapis.com/auth/gmail.send" in spec.auth.scopes+ assert "https://mail.google.com/" in spec.auth.scopesassert spec.auth.scope_separator == "space"assert spec.auth.callback_path == ""assert spec.auth.offline_access is Truediff --git a/tests/unit/plugins/tool/test_drive_rest.py b/tests/unit/plugins/tool/test_drive_rest.pynew file mode 100644index 0000000000..284c37ab4d--- /dev/null+++ b/tests/unit/plugins/tool/test_drive_rest.py@@ -0,0 +1,246 @@+"""Google Drive REST tool: reads the marketplace keyring token and calls the+Drive REST API v3 directly (native, MCP-free — the hosted Drive MCP 403s+consumer @gmail.com accounts, forensic 2026-07-23)."""++import json++import httpx+import pytest++from jarvis.plugins.tool.drive_rest import DriveRestTool+++async def test_list_files_builds_query_and_uses_bearer():+ captured = {}++ def handler(req: httpx.Request) -> httpx.Response:+ assert req.headers["authorization"] == "Bearer at_123"+ captured["q"] = req.url.params.get("q")+ return httpx.Response(+ 200,+ json={+ "files": [+ {+ "id": "f1",+ "name": "budget.xlsx",+ "mimeType": "application/vnd.ms-excel",+ "modifiedTime": "2026-07-20T10:00:00Z",+ "webViewLink": "https://drive.google.com/file/d/f1/view",+ "owners": [{"displayName": "Ruben", "emailAddress": "[email protected]"}],+ }+ ]+ },+ )++ tool = DriveRestTool(+ access_token_provider=lambda: "at_123",+ transport=httpx.MockTransport(handler),+ )+ out = await tool.list_files(search_text="budget", max_results=5)+ # The plain search_text expands to a name/fullText clause AND excludes trash.+ assert "name contains 'budget'" in captured["q"]+ assert "fullText contains 'budget'" in captured["q"]+ assert "trashed = false" in captured["q"]+ # Slim projection: webViewLink -> url, single owner display name.+ assert out["files"][0] == {+ "id": "f1",+ "name": "budget.xlsx",+ "mimeType": "application/vnd.ms-excel",+ "modifiedTime": "2026-07-20T10:00:00Z",+ "size": None,+ "url": "https://drive.google.com/file/d/f1/view",+ "owner": "Ruben",+ }+ assert out["count"] == 1+++async def test_list_files_empty_search_lists_recent_untrashed():+ captured = {}++ def handler(req: httpx.Request) -> httpx.Response:+ captured["q"] = req.url.params.get("q")+ captured["orderBy"] = req.url.params.get("orderBy")+ return httpx.Response(200, json={"files": []})++ tool = DriveRestTool(+ access_token_provider=lambda: "at_123",+ transport=httpx.MockTransport(handler),+ )+ await tool.list_files()+ assert captured["q"] == "trashed = false"+ assert captured["orderBy"] == "modifiedTime desc"+++async def test_read_file_exports_google_doc_as_text():+ calls = {"n": 0}++ def handler(req: httpx.Request) -> httpx.Response:+ calls["n"] += 1+ url = str(req.url)+ if "/export" in url:+ assert req.url.params.get("mimeType") == "text/plain"+ return httpx.Response(200, text="This is the document body.")+ # metadata call+ return httpx.Response(+ 200,+ json={+ "id": "d1",+ "name": "Notes",+ "mimeType": "application/vnd.google-apps.document",+ "webViewLink": "https://docs.google.com/d1",+ },+ )++ tool = DriveRestTool(+ access_token_provider=lambda: "at_123",+ transport=httpx.MockTransport(handler),+ )+ out = await tool.read_file(file_id="d1")+ assert out["content"] == "This is the document body."+ assert out["name"] == "Notes"+ assert calls["n"] == 2 # metadata + export+++async def test_read_file_binary_is_not_downloaded_as_text():+ def handler(req: httpx.Request) -> httpx.Response:+ # Only the metadata call should ever fire for a binary file.+ assert "alt=media" not in str(req.url)+ return httpx.Response(+ 200,+ json={"id": "b1", "name": "photo.png", "mimeType": "image/png"},+ )++ tool = DriveRestTool(+ access_token_provider=lambda: "at_123",+ transport=httpx.MockTransport(handler),+ )+ out = await tool.read_file(file_id="b1")+ assert out["content"] is None+ assert "binary" in out["note"]+++async def test_create_file_sends_multipart_related():+ captured = {}++ def handler(req: httpx.Request) -> httpx.Response:+ captured["ctype"] = req.headers["content-type"]+ captured["body"] = req.content.decode("utf-8")+ captured["uploadType"] = req.url.params.get("uploadType")+ return httpx.Response(+ 200,+ json={+ "id": "n1",+ "name": "todo.txt",+ "mimeType": "text/plain",+ "webViewLink": "https://drive.google.com/n1",+ },+ )++ tool = DriveRestTool(+ access_token_provider=lambda: "at_123",+ transport=httpx.MockTransport(handler),+ )+ out = await tool.create_file(name="todo.txt", content="buy milk")+ assert captured["uploadType"] == "multipart"+ assert captured["ctype"].startswith("multipart/related; boundary=")+ assert '"name": "todo.txt"' in captured["body"]+ assert "buy milk" in captured["body"]+ assert out["url"] == "https://drive.google.com/n1"+++async def test_share_file_needs_email_or_public():+ tool = DriveRestTool(access_token_provider=lambda: "at_123")+ out = await tool.share_file(file_id="f1")+ assert "error" in out+ assert "email_address or public" in out["error"]+++async def test_share_file_with_email_posts_user_permission():+ captured = {}++ def handler(req: httpx.Request) -> httpx.Response:+ if "/permissions" in str(req.url):+ captured["perm"] = json.loads(req.content)+ return httpx.Response(200, json={"id": "p1"})+ return httpx.Response(200, json={"id": "f1", "name": "f", "webViewLink": "u"})++ tool = DriveRestTool(+ access_token_provider=lambda: "at_123",+ transport=httpx.MockTransport(handler),+ )+ out = await tool.share_file(file_id="f1", email_address="[email protected]", role="writer")+ assert captured["perm"] == {"type": "user", "role": "writer", "emailAddress": "[email protected]"}+ assert out["shared"] is True+++async def test_delete_file_issues_delete():+ def handler(req: httpx.Request) -> httpx.Response:+ assert req.method == "DELETE"+ assert str(req.url).endswith("/files/f1")+ return httpx.Response(204)++ tool = DriveRestTool(+ access_token_provider=lambda: "at_123",+ transport=httpx.MockTransport(handler),+ )+ out = await tool.delete_file(file_id="f1")+ assert out == {"deleted": True, "file_id": "f1"}+++async def test_execute_returns_error_when_not_connected():+ tool = DriveRestTool(access_token_provider=lambda: None)+ result = await tool.execute({"action": "list_files"}, ctx=None)+ assert result.success is False+ assert "connect" in (result.error or "").lower()+++async def test_list_files_refreshes_on_401_then_retries():+ calls = {"http": 0, "refresh": 0}++ def handler(req: httpx.Request) -> httpx.Response:+ calls["http"] += 1+ if calls["http"] == 1:+ return httpx.Response(401, json={"error": {"code": 401}})+ return httpx.Response(200, json={"files": [{"id": "m9", "name": "x"}]})++ async def refresher() -> bool:+ calls["refresh"] += 1+ return True++ tool = DriveRestTool(+ access_token_provider=lambda: "at_dead",+ transport=httpx.MockTransport(handler),+ token_refresher=refresher,+ )+ out = await tool.list_files()+ assert out["files"][0]["id"] == "m9"+ assert calls["refresh"] == 1+ assert calls["http"] == 2+++def test_risk_tiers_per_action():+ tool = DriveRestTool(access_token_provider=lambda: "x")+ assert tool.risk_tier_for_args({"action": "list_files"}) == "safe"+ assert tool.risk_tier_for_args({"action": "read_file"}) == "safe"+ assert tool.risk_tier_for_args({"action": "create_file"}) == "monitor"+ assert tool.risk_tier_for_args({"action": "create_folder"}) == "monitor"+ assert tool.risk_tier_for_args({"action": "share_file"}) == "ask"+ assert tool.risk_tier_for_args({"action": "delete_file"}) == "ask"+ assert tool.risk_tier_for_args({"action": "purge_everything"}) == "ask"+++def test_tool_contract_shape():+ tool = DriveRestTool()+ assert tool.name == "google_drive"+ assert "schema" in dir(tool)+ assert "list_files" in tool.schema["properties"]["action"]["enum"]