# `valstorm-plugin-google-workspace` — Hybrid Google Workspace Plugin (`NF-489`) Hybrid (**Python + Go**) Google Workspace productivity integration for **Open Valstorm**, mounted at `platform.google_workspace` (`VALSTORM_PLUGINS=google-workspace` or `*`). Provides 100% per-user OAuth 2.0 authentication (zero Domain-Wide Delegation required), tenant Bring-Your-Own-App (BYO-App) OAuth client support, $O(1)$ Pub/Sub webhook routing, and high-throughput Go worker delta synchronization for: - **Gmail (`platform.google_workspace.gmail` & Go `GmailProcessor`)**: Send emails, create drafts, list/fetch threads, register `users.watch` push notifications, and run high-speed Go MIME parsing & history delta sync (`email:google_pubsub_webhook`). - **Google Calendar (`platform.google_workspace.calendar` & Go `CalendarProcessor`)**: List calendars/events, create events, query `freeBusy` availability (used by `valstorm-plugin-booking`), and run incremental `syncToken` delta sync (`calendar:google_sync`). - **Google Meet (`platform.google_workspace.meet`)**: Auto-provision Google Meet video conference links (`hangoutsMeet`) and calendar invites. - **Google Drive & Docs (`platform.google_workspace.docs`)**: Search Drive files, create Google Docs, and convert Google Docs JSON AST into clean styled HTML/CSS and plaintext. --- ## 🤖 Agent-Assisted Quick Setup (Let the Valstorm Agent Set It Up) Because Google OAuth 2.0 Web Clients require a Client ID & Secret from the Google Cloud Console, the fastest way to set up `valstorm-plugin-google-workspace` is to grab the downloaded `client_secret_*.json` file (or paste the Client ID & Secret) and let your **Valstorm AI Agent** handle enabling the APIs, encrypting the tenant BYO-App configuration, generating your one-click OAuth link, and wiring up Cloud Pub/Sub push notifications. ### 1. Quick Human Prerequisite 1. Ensure `gcloud` is authenticated (`brew install --cask google-cloud-sdk && gcloud auth login`). 2. In [Google Cloud Console -> Credentials](https://console.cloud.google.com/apis/credentials), click **Create Credentials -> OAuth client ID -> Web application**, add your callback URI (`http://localhost:8000/v1/google-workspace/auth/callback` or `https://api.yourdomain.com/v1/google-workspace/auth/callback`), and download the JSON file (or copy `client_id` and `client_secret`). ### 2. Copy-Paste Prompt for Your Valstorm Agent Drop this prompt into Valstorm Chat: > *"Set up `valstorm-plugin-google-workspace` using my GCP project `` and OAuth Client credentials ``. Follow `plugins/valstorm-plugin-google-workspace/README.md` to enable the Gmail/Calendar/Drive/Docs APIs via `gcloud`, store the encrypted BYO-App config via `platform.credentials.save_env_config('google_workspace', ...)`, provision the `gmail-watch-events` Pub/Sub topic, and give me the OAuth login URL to connect my account."* ### 3. Agent Execution Runbook (Instructions for the AI Agent) When a user asks you to set up `valstorm-plugin-google-workspace`, execute this sequence autonomously: 1. **Enable Workspace & Pub/Sub APIs via `gcloud`**: - Run `gcloud services enable gmail.googleapis.com calendar-json.googleapis.com drive.googleapis.com docs.googleapis.com pubsub.googleapis.com --project=`. 2. **Parse & Save Tenant OAuth Client Credentials**: - Accept either a raw GCP `{"web": {"client_id": "...", "client_secret": "..."}}` JSON file or flat `client_id` / `client_secret` values. - Persist encrypted in `environment_configuration` via `await platform.credentials.save_env_config("google_workspace", {"client_id": ..., "client_secret": ..., "project_id": ...})`. - If a local JSON file path was provided, remind or offer to remove the plaintext download once saved. 3. **Provision Gmail Push Pub/Sub Topic & Permissions**: - Run `gcloud pubsub topics create gmail-watch-events --project=` (ignore if already exists). - Grant Gmail push publisher permission: `gcloud pubsub topics add-iam-policy-binding gmail-watch-events --member="serviceAccount:gmail-api-push@system.gserviceaccount.com" --role="roles/pubsub.publisher" --project=`. 4. **Generate User OAuth Consent URL & Verify**: - Call `await platform.google_workspace.get_authorization_url(...)` (or `GET /v1/google-workspace/auth/login`) and present the clickable link to the user. - Once the user completes consent, call `google_workspace_verify_connection` to confirm live Gmail/Calendar/Drive access and $O(1)$ webhook routing registration. --- ## 🛠️ End-to-End DIY Setup Guide (Manual / CLI) ### Step 1: Enable Google Workspace APIs in GCP Console In the [Google Cloud Console](https://console.cloud.google.com/), enable the four Workspace APIs on your project: 1. **Gmail API** (`gmail.googleapis.com`) 2. **Google Calendar API** (`calendar-json.googleapis.com`) 3. **Google Drive API** (`drive.googleapis.com`) 4. **Google Docs API** (`docs.googleapis.com`) ```bash gcloud services enable \ gmail.googleapis.com \ calendar-json.googleapis.com \ drive.googleapis.com \ docs.googleapis.com \ --project=YOUR_GCP_PROJECT_ID ``` ### Step 2: Configure the OAuth Consent Screen 1. Go to **APIs & Services -> OAuth consent screen**. 2. Configure **User Type** (`Internal` for your Workspace organization, or `External` for multi-tenant production). 3. Add the required OAuth scopes (or use Open Valstorm's progressive consent presets): - `openid`, `https://www.googleapis.com/auth/userinfo.email`, `https://www.googleapis.com/auth/userinfo.profile` - `https://www.googleapis.com/auth/gmail.modify`, `https://www.googleapis.com/auth/gmail.compose`, `https://www.googleapis.com/auth/gmail.labels` - `https://www.googleapis.com/auth/calendar.events` - `https://www.googleapis.com/auth/drive`, `https://www.googleapis.com/auth/documents` ### Step 3: Create an OAuth 2.0 Web Application Client ID 1. Navigate to **APIs & Services -> Credentials -> Create Credentials -> OAuth client ID**. 2. Select **Application type: Web application**. 3. Under **Authorized redirect URIs**, add your Open Valstorm callback URLs: - Local development: - `http://localhost:8000/v1/google-workspace/auth/callback` - `http://localhost:8000/v1/google/auth/callback` - Production: - `https://api.yourdomain.com/v1/google-workspace/auth/callback` - `https://api.yourdomain.com/v1/google/auth/callback` 4. Copy the generated **Client ID** and **Client Secret**. --- ## 2. Configuring OAuth Client Credentials in Open Valstorm You can configure Google OAuth Client credentials either globally via environment variables or per-tenant (BYO-App) in `environment_configuration`. ### Option A: Environment Variables (Platform Default / Local Dev) Add to `apps/open-api/.env` and `apps/open-worker/.env`: ```env VALSTORM_PLUGINS=* GOOGLE_WORKSPACE_CLIENT_ID=1234567890-abcdefg.apps.googleusercontent.com GOOGLE_WORKSPACE_CLIENT_SECRET=GOCSPX-your-client-secret GOOGLE_PROJECT_ID=your-gcp-project-id ``` ### Option B: Tenant BYO-App (`environment_configuration`) Each tenant organization can bring its own Google OAuth Web Client: ```python await platform.credentials.save_env_config( "google_workspace", { "client_id": "1234567890-tenant.apps.googleusercontent.com", "client_secret": "GOCSPX-tenant-secret", "project_id": "tenant-gcp-project", }, ) ``` --- ## 3. Connecting a User Account & Setting Up Push Sync ### Step 1: Initiate OAuth 2.0 Login Call `GET /v1/google-workspace/auth/login` (optionally passing `scope_preset=standard|calendar|email_full|drive|draft_only`): ```bash curl -X GET "http://localhost:8000/v1/google-workspace/auth/login?scope_preset=standard" \ -H "Authorization: Bearer " ``` Open the returned `authorization_url` in a browser and grant consent. When Google redirects to `/v1/google-workspace/auth/callback`: 1. Open Valstorm exchanges the authorization `code` for an `access_token` and `refresh_token`. 2. Tokens are encrypted at rest in `auth_credential` scoped to `user_id`. 3. The user's connected `email` is automatically registered in `valstorm_directory.external_account_routing` (`provider="google_workspace"`) for **$O(1)$ webhook routing**. ### Step 2: Enable Real-Time Gmail Push Notifications (Cloud Pub/Sub) 1. In Google Cloud Pub/Sub, create a push subscription on your topic pointing to: ```text https://api.yourdomain.com/v1/google-workspace/webhooks/pubsub ``` 2. Start watching the user's mailbox: ```bash curl -X POST http://localhost:8000/v1/google-workspace/gmail/watch \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{"topic_name": "projects/your-gcp-project-id/topics/gmail-watch-events"}' ``` 3. Whenever a new email arrives, Google Pub/Sub posts to `/v1/google-workspace/webhooks/pubsub`, Open Valstorm resolves the tenant in $O(1)$ time, and dispatches `email:google_pubsub_webhook` to the Go worker (`plugins/valstorm-plugin-google-workspace/go`). --- ## 4. Registered Object Prefixes & Marketplace App Bundle When active, `valstorm-plugin-google-workspace` dynamically injects: - **Object ID Prefixes (`NF-490`)**: - `drfi` -> `drive_file` - `gmms` -> `gmail_message` - `gmth` -> `gmail_thread` - `gcev` -> `google_calendar_event` - **Marketplace App Bundle (`NF-499`)**: - `app_google_workspace` (**"Google Workspace"**) --- ## 5. Python & Go Usage Examples ### Python (`platform.google_workspace`) ```python # 1. Send an email via Gmail & automatically log the `email` record in CRM await platform.google_workspace.gmail.send_email( to="prospect@acme.com", subject="Valstorm Architecture Follow-Up", body_html="

Here is the proposal we discussed.

", ) # 2. Provision a Google Meet link & Calendar invite meeting = await platform.google_workspace.meet.create_meeting( summary="Technical Deep Dive", start_time="2026-11-05T15:00:00Z", end_time="2026-11-05T15:30:00Z", attendees=["prospect@acme.com"], ) print(meeting["meet_link"]) # https://meet.google.com/... # 3. Check Free/Busy availability (used by `valstorm-plugin-booking`) free_busy = await platform.google_workspace.calendar.get_free_busy( time_min="2026-11-05T00:00:00Z", time_max="2026-11-05T23:59:59Z", ) # 4. Read a Google Doc as clean HTML & plaintext doc = await platform.google_workspace.docs.get_document("1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms") print(doc["title"], doc["html"]) ``` --- ## 6. REST API Endpoints (`/v1/google-workspace/*` & `/v1/google/*`) | Method | Endpoint | Description | | :--- | :--- | :--- | | `GET` | `/v1/google-workspace/setup-guide` | Step-by-step OAuth 2.0 & Pub/Sub setup guide | | `GET` | `/v1/google-workspace/auth/status` | Check user's OAuth connection status & granted scopes | | `GET` | `/v1/google-workspace/auth/login` | Generate Google OAuth 2.0 authorization URL | | `GET` | `/v1/google-workspace/auth/callback` | OAuth 2.0 callback — saves encrypted tokens & registers $O(1)$ routing | | `POST` | `/v1/google-workspace/verify` | Verify live OAuth token against Gmail API | | `POST` | `/v1/google-workspace/gmail/send` | Send email via Gmail API & persist CRM `email` record | | `POST` | `/v1/google-workspace/gmail/watch` | Register Gmail push notification watch on a Pub/Sub topic | | `POST` | `/v1/google-workspace/gmail/sync` | Enqueue Go worker `email:google_pubsub_webhook` delta sync | | `POST` | `/v1/google-workspace/webhooks/pubsub` | Unauthenticated Google Cloud Pub/Sub push webhook | | `GET` | `/v1/google-workspace/calendar/events` | List events from Google Calendar | | `POST` | `/v1/google-workspace/calendar/events` | Create Google Calendar event (optional Google Meet link) | | `POST` | `/v1/google-workspace/calendar/free-busy` | Query calendar free/busy intervals | | `POST` | `/v1/google-workspace/meet/create` | Create a Google Meet conference & calendar invite | | `GET` | `/v1/google-workspace/drive/files` | Search/list files in Google Drive | | `GET` | `/v1/google-workspace/docs/{document_id}` | Fetch Google Doc & render clean HTML and text | --- ## 7. Running Tests (Python & Go) ```bash # Run Python unit & webhook integration tests cd apps/open-api .venv/bin/pytest tests/test_plugin_google_workspace.py -v # Run Go worker processor & parser race tests cd ../../plugins/valstorm-plugin-google-workspace/go go test -race -v ./... ```