| summary | Gmail watch + Pub/Sub delivery in gog | ||
|---|---|---|---|
| read_when |
|
Goal: Gmail publishes mailbox notifications to Pub/Sub, then gog turns those
notifications into downstream webhook payloads.
Two delivery modes are supported:
- Pull:
gog gmail watch pullreads a Pub/Sub subscription from the local machine. This is the preferred local-agent shape because Google does not need an inbound HTTP route to the machine runninggog. - Push:
gog gmail watch serveexposes an HTTP handler for Pub/Sub push. Use it when you intentionally operate a reachable HTTPS endpoint. Push and pull share the same downstream hook delivery policy.
- Create a Pub/Sub topic (GCP project).
- Create a pull subscription for the topic.
- Start watch:
gog gmail watch start \
--topic projects/<project>/topics/<topic> \
--label INBOX
- Run pull consumer:
gog gmail watch pull \
--subscription projects/<project>/subscriptions/<subscription> \
--hook-url http://127.0.0.1:18789/hooks/agent
For push delivery instead:
- Create a push subscription targeting your
gog gmail watch serveendpoint. - Configure push auth:
- Preferred: OIDC JWT from a service account.
- Fallback/dev: shared token header
x-gog-tokenor?token=.
- Start watch:
gog gmail watch start \
--topic projects/<project>/topics/<topic> \
--label INBOX
- Run handler:
gog gmail watch serve \
--bind 127.0.0.1 \
--port 8788 \
--path /gmail-pubsub \
--token-env GOG_WATCH_PUSH_TOKEN \
--hook-url http://127.0.0.1:18789/hooks/agent \
--hook-token-env GOG_WATCH_HOOK_TOKEN
Have your service manager or secret store supply GOG_WATCH_PUSH_TOKEN and
GOG_WATCH_HOOK_TOKEN in the process environment. The flags name the variables,
so neither token value needs to appear in the command line. The hook token is
sent as a bearer token to the configured hook URL. Environment values remain
accessible to the process owner and privileged users.
gog gmail watch start --topic <gcp-topic> [--label <idOrName>...] [--ttl <sec|duration>]
gog gmail watch status
gog gmail watch renew [--ttl <sec|duration>]
gog gmail watch stop
gog gmail watch serve \
--bind 127.0.0.1 --port 8788 --path /gmail-pubsub \
[--verify-oidc] [--oidc-email <svc@...>] [--oidc-audience <aud>] \
[--token <shared> | --token-env <var>] \
[--hook-url <url>] [--hook-token <token> | --hook-token-env <var>] \
[--fetch-delay <sec|duration>] \
[--include-body] [--max-bytes <n>] [--exclude-labels <id,id,...>] \
[--history-types <type>...] [--save-hook]
gog gmail watch pull \
--subscription projects/<project>/subscriptions/<subscription> \
[--hook-url <url>] [--hook-token <token>] \
[--fetch-delay <sec|duration>] \
[--include-body] [--max-bytes <n>] [--exclude-labels <id,id,...>] \
[--history-types <type>...] [--save-hook]
gog gmail history --since <historyId> [--max <n>] [--page <token>]
Notes:
watch startstores{historyId, expirationMs, topic, labels}for account.watch statusreads atomic state without creating state directories or lock files.watch renewreuses stored topic/labels.- Push and pull inspect notifications whose history ID equals the saved cursor; lower IDs remain stale. Duplicate Pub/Sub message IDs are still ignored.
- Push and pull read every page of Gmail history after the saved cursor and advance the cursor only after the last page, so bursts of more than one page of changes are delivered instead of skipped.
watch stopcalls Gmail stop + clears state.watch serveandwatch pulluse stored hook config if--hook-urlis not provided.watch pullneeds Google credentials that can consume the Pub/Sub subscription.watch serveneeds an HTTP endpoint reachable by Pub/Sub.watch serve --token-envand--hook-token-envread named environment variables once at startup. Each conflicts with its corresponding literal flag, including an explicitly empty literal. An empty variable name or an unset, empty, or whitespace-only value is a usage error; accepted token values are preserved exactly. Without these flags there is no environment lookup.- With a stored hook URL,
watch serve --hook-token-envoverrides the stored token while keeping the other stored defaults.--save-hookexplicitly persists the resolved hook token in the existing private watch state file; otherwise the override is used only for that run. The push token is not saved. watch serve --dry-runvalidates flags and prints a secret-free listen/auth/ hook plan. It may read existing atomic watch state to resolve stored hook settings, but does not create/lock/update state, create clients, or open a socket.watch serveandwatch pulldefault--exclude-labelstoSPAM,TRASH; set to an empty string to disable.- Exclude label IDs are matched exactly (case-sensitive opaque IDs).
watch serve --fetch-delayandwatch pull --fetch-delaydelay Gmail history fetch after each notification (default3s) to avoid indexing races; accepts seconds (5) or Go durations (5s).watch serve --history-typesandwatch pull --history-typesacceptmessageAdded,messageDeleted,labelAdded,labelRemoved(repeatable or comma-separated). Default:messageAdded(for backward compatibility).watch serve --history-typesandwatch pull --history-typesmust include at least one non-empty type.
Path (per account):
~/.config/gogcli/state/gmail-watch/<account>.json
Schema (v1):
{
"account": "you@gmail.com",
"topic": "projects/…/topics/…",
"labels": ["INBOX"],
"historyId": "12345",
"expirationMs": 1730000000000,
"providerExpirationMs": 1730000000000,
"renewAfterMs": 1730000001000,
"updatedAtMs": 1730000001000,
"authRecoveryPending": true,
"authFailureAtMs": 1730000001000,
"authFailureReason": "reauthentication_required",
"hook": {
"url": "http://127.0.0.1:18789/hooks/agent",
"token": "...",
"includeBody": false,
"maxBytes": 20000
}
}{
"source": "gmail",
"account": "you@gmail.com",
"historyId": "...",
"deletedMessageIds": ["..."],
"messages": [
{
"id": "...",
"threadId": "...",
"from": "...",
"to": "...",
"subject": "...",
"date": "...",
"snippet": "...",
"body": "...",
"bodyTruncated": true,
"labels": ["INBOX"]
}
]
}- Default: headers + snippet only.
--include-body: include text/plain body (first matching part).--max-bytes: hard cap on body bytes (default20000).- If over cap: truncate + set
bodyTruncated=true.
gog gmail watch serve preserves the selected OAuth client and any direct
--access-token (or GOG_ACCESS_TOKEN) when handling incoming push requests.
Direct-token mode does not require stored OAuth client credentials or a refresh
token. The token remains static and expires normally; restart the server with a
fresh token when needed. This is separate from authenticating the push sender
below.
Preferred:
- Pub/Sub push with OIDC JWT.
- Verify JWT audience + email (service account).
Fallback (dev only):
- Shared token via
x-gog-tokenheader or?token=.
Pull delivery does not expose a public HTTP receiver. The local gog process
must have Google credentials for:
- Gmail history reads for the watched account. These use the normal stored
gogGmail OAuth account selected by--account/--client. - Pub/Sub subscriber access on the configured subscription. These use the
Google Cloud client library credential chain, for example Application Default
Credentials or
GOOGLE_APPLICATION_CREDENTIALS, not the stored Gmail OAuth token. The credential must be able to consume the subscription; grantingroles/pubsub.subscriberon the subscription is the usual least-privilege shape.
The downstream hook token is still local to the hook call from gog to the
configured --hook-url.
- Stale historyId: fall back to
messages.list(last N) + reset historyId. - Watch expired:
watch renewerror; rerunwatch start. - Pull mode treats invalid Pub/Sub messages as poison messages: log and acknowledge them rather than redelivering forever. Wrong-account notifications are also terminal in both modes.
- Expired or revoked Gmail OAuth credentials are terminal for the current
notification. Push and pull acknowledge
invalid_grantfailures only after durably marking auth recovery as pending, without advancing the stored Gmail history cursor. This prevents Pub/Sub redelivery storms without discarding the catch-up position. If the recovery marker cannot be saved, the notification remains retryable. - After re-authenticating, run
gog gmail watch renew(or rerunwatch start). A successful watch registration preserves the last processed history ID while recovery is pending. Gmail sends an immediate notification for the new watch, which catches up from that retained cursor without waiting for another mailbox change. Successful history processing clears the recovery marker. Usegog gmail watch statusto inspectauth_recovery_pending,auth_failure_at, andauth_failure_reason. - Hook failures are retryable.
gogrecords the hook failure status, preserves the pre-hook watch cursor, and returns a delivery failure to Pub/Sub. This lets Pub/Sub redeliver the notification after the downstream agent or gateway comes back. - This is an intentional reliability change for existing push deployments.
Older
watch servebehavior acknowledged hook failures to avoid replay storms, but that could silently lose Gmail wakeups when the downstream OpenClaw gateway or agent was temporarily down. The supported behavior is now delivery-before-cursor-advance for both push and pull: push returns non-2xx on hook failure and pull nacks the message. - Pub/Sub may retry the same notification until the hook succeeds or until the subscription's retry/dead-letter policy takes over. Hook receivers should be safe to call more than once for the same Gmail history notification.
- This retry policy is intended for normal Gmail notification volumes. If you are processing very high mail rates, for example 1000 messages per minute, run your own monitoring, alerting, backlog policy, and dead-letter/backpressure setup instead of treating the default watcher as a complete queueing platform.