Level 10Lesson 87โฑ๏ธ 70 min

Connecting Real Google (OAuth)

Six lessons on five fake emails. Now a real inbox, and the two things that broke the first afternoon.

What you will be able to do

  • Walk through an OAuth sign-in step by step and say what each step protects against
  • Ask for the narrowest scopes that do the job, and make the tool surface follow what was granted
  • Swap fixture adapters for real ones without touching tools, prompts or the loop
  • Add a second write tool that creates a draft and never sends
  • Recognise the assumptions fixtures let you make, by watching two of them fail on real data
Companion repo: posixplus/learn2exel-dayflow, tag lesson-87. New: dayflow/oauth.py, dayflow/adapters/google.py, the draft_reply tool,dayflow auth login | status | logout, tests/test_google.py. Everything on this page marked "real run" was run by the course author against his own Google account, with addresses and subjects redacted.

Sign in with Google, by hand

Lesson 81 wrote the agent loop by hand so you would know what a framework does for you.dayflow/oauth.py is the same exercise for OAuth: about 150 lines of standard library. The flow is called authorization code with PKCE, using a loopback redirect, and it has five steps.

StepWhat happensWhat it protects against
1Make a random verifier. Send only its SHA-256 hash, the challenge, to Google.Someone who intercepts the code in step 3 cannot use it without the verifier.
2Open the browser at Google's consent page. Listen on 127.0.0.1, on a port the OS picks.Nothing off your machine can reach the listener.
3You approve. Google redirects the browser to that port with a one-time code and the state you sent.A wrong state means the response is not an answer to your request. Stop.
4POST the code and the verifier to the token endpoint.Google checks the verifier against the challenge from step 1.
5Store the tokens in a file only you can read.Other users on the machine.
def consent_url(client, *, redirect_uri, scopes, state, challenge) -> str:
    return AUTH_URL + "?" + urllib.parse.urlencode({
        "client_id": client.client_id,
        "redirect_uri": redirect_uri,
        "response_type": "code",
        "scope": " ".join(scopes),
        "state": state,
        "code_challenge": challenge,
        "code_challenge_method": "S256",
        "access_type": "offline",        # ask for a refresh token
        "prompt": "consent",             # ...and get one even on a repeat login
    })

Dayflow never sees your Google password. It gets an access token that lasts about an hour and a refresh token that fetches a new one without the browser. You can cut it off at any time from your Google account settings without telling Dayflow.

def save_token(token: Token, path: Path = DEFAULT_TOKEN_PATH) -> None:
    """Owner read/write only, set BEFORE the secret is written into the file."""
    path.parent.mkdir(parents=True, exist_ok=True)
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    ...

def load_token(path: Path = DEFAULT_TOKEN_PATH) -> Token | None:
    ...
    if os.name == "posix" and mode & 0o077:
        raise OAuthError(f"{path} is readable by other users (mode {mode:o}). Fix with: chmod 600 {path}")
โ„น๏ธ
In production you would use a library
Google publishes one, and it handles edge cases this file does not. The reason to read 150 lines once is the same as for the loop: when sign-in fails at step 3 in a real project, you will know there is a step 3.

Ask for less, and let the tools follow

CommandScopes requestedWhat the token can do
dayflow auth logingmail.readonly, calendar.readonlyRead mail and calendar. Nothing else.
dayflow auth login --draftsthe two above plus gmail.composeAlso create drafts. Google does not split this scope: it can send too.

The second row is the uncomfortable one. There is no "drafts only" permission. Dayflow has no send tool, so the code is the only thing standing between that token and an outgoing email. Lesson 88 comes back to this.

def _use_real_google(store: Store) -> None:
    client = oauth.Client.from_env()
    token = oauth.valid_token(client)                     # raises if not signed in; refreshes if expired
    tools.use_google(bearer_http(lambda: oauth.valid_token(client).access_token), drafts=store)
    if not token.allows(oauth.SCOPE_COMPOSE):
        tools.REGISTRY.pop("draft_reply", None)           # the surface follows the token

If the user did not grant the compose scope, draft_reply is removed before the model ever sees the tool list. A tool the token cannot back should not exist as far as the model is concerned. Offering it and letting it fail teaches the model to apologise; removing it means there is nothing to apologise for.

real run
$ dayflow auth login
signed in. granted: calendar.readonly, gmail.readonly
token stored at ~/.config/dayflow/google_token.json (mode 600)

$ dayflow auth status
signed in. access token valid. refresh token: yes
granted: calendar.readonly, gmail.readonly
draft_reply: not offered (run `dayflow auth login --drafts` to add it)

One more detail in login(): Google's consent screen lets the user untick individual permissions. So the code compares what was granted in the token response with what wasrequested, and fails with you did not grant: gmail.compose rather than saving a token that looks more capable than it is.

The adapter swap

adapters/google.py has the same method names and return shapes asadapters/fixtures.py. Tools, prompts, the loop and the gate do not change;tools.use_google() is the only switch, and MOCK=0 is what flips it. That was the point of writing the fixtures first. Four places where the real API does not look like the fixture:

FixtureGmailWhat the adapter does
Pagingoffsetopaque page tokenLists message ids once per run and slices that list by offset
Bodiesa stringa MIME tree, base64url encodedFinds the text/plain part, collapses whitespace, cuts it, and says how much was cut
Idempotencya dictnone for draftsKeeps its own key-to-draft map in the store, so a retried approval cannot make two drafts
Volume5 messageshundredsSee below. This is the one that was wrong.

The second write tool, draft_reply, takes a message_id, a body and an idempotency key. It does not take an address. The reply goes to whoever sent the original, in the original thread, as a draft. It is a write, so the gate from lesson 86 holds it like any other.

What broke on the first real run

Sign-in worked first time. Then the brief was run against a real inbox, and it failed three times in a row.

1. A real inbox is not five messages

real run
$ MOCK=0 dayflow brief --approve queue
loop stopped: token budget exceeded at step 3: 149696 > 60000

$ MOCK=0 dayflow brief --approve queue --token-budget 400000
loop stopped: token budget exceeded at step 6: 424721 > 400000

The adapter had been written to list up to 200 messages from the last three days, with 1,500 characters of body each. Against fixtures that looked generous. Against a real inbox it meant the model paged through the lot, and every step re-read everything before it. A run that costs four cents on fixtures was on its way to costing dollars.

Two things are worth noticing. The token budget from lesson 81 is what stopped it: a guard written six lessons ago for a different reason turned an expensive surprise into an error message. And no unit test could have caught this, because every test used an inbox the author had sized.

# These three were 1500, "in:inbox newer_than:3d" and 200, sized against a five-message fixture.
MAX_BODY_CHARS = int(os.environ.get("DAYFLOW_BODY_CHARS", "400"))
INBOX_QUERY = os.environ.get("DAYFLOW_INBOX_QUERY", "in:inbox newer_than:3d -category:promotions -category:social")
MAX_LISTED = int(os.environ.get("DAYFLOW_INBOX_MAX", "30"))             # newest N messages a run can see

        if self._more:
            # Say so. A brief built on a capped listing must not read as "this is everything".
            out["note"] = (f"Only the newest {len(ids)} matching messages are listed; older ones were not read. "
                           "Tell the user the brief covers the newest mail only.")
real run, after the fix
Note: the inbox tool returned only the newest 30 messages, so older mail wasn't read.
I created no tasks and no drafts.

[2 steps ยท 4 tool calls ยท 14350 in / 1544 out ยท run 27f5dd279e70]

From over 424,000 tokens and no brief to 14,350 and a brief. The note matters as much as the cap: a summary of part of your mail that reads like a summary of all of it is worse than no summary.

2. An approval ran in the wrong world

With the compose scope granted, a reply draft was queued against a real message and then approved:

real run
$ dayflow approve ap_6259a7
approved, but draft_reply failed: unknown_message: no message with id '1a1d...'

$ MOCK=0 dayflow approve ap_6259a7
approved ap_6259a7: {'draft_id': 'r-66100...', 'to': 'you@example.com', 'subject': 'Re: dayflow test', 'created': True}

The first command was typed without MOCK=0. So a proposal made against Gmail was executed against the fixtures, which looked up a real Gmail message id in a five-message JSON file. It failed, but only by luck: the id did not exist there. Had it been a tool whose arguments meant something in both worlds, it would have quietly done the wrong thing.

    proposed_on = row["backend"]
    if proposed_on and proposed_on != _tools.BACKEND:
        how = "MOCK=0 dayflow approve" if proposed_on == "google" else "MOCK=1 dayflow approve"
        raise ApprovalError(f"approval {approval_id} was proposed against {proposed_on}, but this command is running "
                            f"against {_tools.BACKEND}. Nothing was done. Run: {how} {approval_id}")

Every proposal now records the backend it was made against, and approve refuses on a mismatch, leaves the proposal pending, and prints the command to run. Lesson 86 said approving replays the stored arguments exactly. That is only half of "exactly": the arguments also have to land in the same place.

โš ๏ธ
Fixtures are a list of your assumptions
Both failures have the same shape. The fixture inbox was small, so nothing forced a decision about volume. There was only one backend in every test, so nothing forced a decision about which one an approval belongs to. Fixtures let you build fast, and they cannot tell you what you forgot to put in them. Budget an afternoon with real data before you call an integration finished, and keep the guards that turn a surprise into an error.

What was verified, and what was not

Checked on a real accountResult
Sign-in, token file at mode 600, refresh token presentWorked first time
Read-only brief on real Gmail and CalendarWorks after the volume fix: 14,350 input tokens
draft_reply withheld without the compose scopeConfirmed by auth status and by the brief
A task proposed from a real email, queued, approvedWritten as a new task
A reply draft queued, approved, created in GmailDraft created with the expected body

Not verified, so not claimed:

  • That the draft sits inside the original thread in every mail client. Gmail accepted the thread id; nobody checked how it renders.
  • How accurate the brief was on real mail. The author ran it; nobody graded it. Lesson 89 is about not skipping that step.
  • Token refresh after the hour is up, and the seven-day expiry Google applies to apps in Testing mode. Both are unit-tested against fake responses only.
  • The Agent SDK and orchestrated engines against real Google. The real runs used the raw loop.
๐Ÿ–ฅ๏ธHANDS-ON EXERCISEโฑ 45 min

Connect your own account

About ten minutes of Google Cloud Console, then a few cents of API calls. Use an account you are comfortable testing with.

  1. Run `pytest tests/test_google.py -v` first. Everything passes with no network: the OAuth flow, the adapters and the draft tool are all tested against fakes. Read test_login_believes_the_granted_scopes_not_the_requested_ones.
  2. In Google Cloud Console: create a project, enable the Gmail API and the Google Calendar API, set the OAuth consent screen to External and Testing, add your own address as a test user, then create an OAuth client ID of type Desktop app.
  3. Put GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET in .env. Never in code, never in a screenshot. Run `dayflow auth login`, then `dayflow auth status`. Check the file mode of the token: `ls -l ~/.config/dayflow/google_token.json`.
  4. Run `MOCK=0 dayflow brief --approve queue`. Read the footer. How many input tokens did your real inbox cost, compared with about 10,000 on the fixtures? Did the brief carry the "newest 30" note?
  5. See the original failure safely: `DAYFLOW_INBOX_MAX=200 DAYFLOW_BODY_CHARS=1500 MOCK=0 dayflow brief --approve queue --token-budget 30000`. The low budget stops it early. Which step did it reach?
  6. Run `dayflow auth login --drafts` and tick the compose permission. `dayflow auth status` should now say draft_reply: available. Run the brief again and look at `dayflow approvals`.
  7. Approve one proposal WITHOUT MOCK=0 and read the refusal. Then approve it with MOCK=0. If it was a draft, find it in Gmail and confirm it was not sent.
  8. Run `dayflow auth logout`. It revokes the token at Google and deletes the file. Run `dayflow auth status` to confirm, then check your Google account permissions page.

What this lesson deliberately does not do

  • Send email. There is no send tool and there will not be one in this course. A draft needs a person to press Send.
  • Read whole emails. 400 characters is enough to triage and thin for drafting a good reply to a long message. The better design lists subjects first and fetches one body on demand; it adds a tool and is left as an extension.
  • Store the token in the OS keychain. A file at mode 600 is the minimum, not the best. The capstone comes back to it.
  • Publish the app. In Testing mode only listed test users can sign in and tokens expire after seven days. Google's verification process for the Gmail scopes is a project of its own.
  • Mirror OAuth in TypeScript. The TypeScript version runs draft_reply against fixtures only.
Lesson 87 Quick Reference
Authorization code + PKCE

Browser sign-in for an installed app. A random verifier, hashed into a challenge, makes a stolen code useless.

Loopback redirect

Google sends the browser back to 127.0.0.1 on a port the app is listening on. Only this machine can reach it.

state

A random value sent with the request and checked on the response. A mismatch means stop.

Scopes

What the token may do. Default: gmail.readonly and calendar.readonly. --drafts adds gmail.compose, which can also send.

Granted, not requested

The user can untick permissions. Trust the scopes in the token response.

Surface follows the token

Without the compose scope, draft_reply is removed from the registry before the model sees it.

Adapter swap

MOCK=0 points the same tools at Gmail and Calendar. Tools, prompts, loop and gate are unchanged.

draft_reply

A write tool. Takes a message id, never an address. Creates a draft in the original thread; nothing is sent.

Volume caps

Newest 30 messages, 400 characters each, Promotions and Social skipped. The result says when it was cut.

Approve where you proposed

Each proposal records its backend. approve refuses on a mismatch and prints the command to run.

Unlocks in ~18 min of reading