Worked Example and Glossary
Extend the digest from Automation and Troubleshooting into a morning brief that reads your calendar and mail and prepares reply drafts with sending blocked, followed by a glossary of the book’s key terms.
As in the rest of the book, every command shown was checked against the --help output of gog v0.48.1, and every output was captured from a real run in a throwaway home without a Google account. Commands that need a signed-in account appear without output.
Morning brief script
Requirements
Write a script named morning-brief.sh that prints a Markdown document with 3 sections and meets the following requirements.
- Events today: list today’s events from your primary calendar with start and end times, and mark all-day events as such.
- Unread threads: list unread threads from the last day, as in
inbox-digest.sh, and report when the list is incomplete. - Reply drafts: for every thread that matches a reply query (by default
is:unread newer_than:1d label:needs-reply), create a reply draft from a plain-text template file, unless the thread already has a draft. Print one line per new draft. - Sending is impossible: all reads run under a read-only token. The draft step runs under flags and configuration that refuse every send command, so that a bug in the script, or a person who edits it carelessly, cannot deliver mail.
- Dry runs: with
BRIEF_DRY_RUN=1, the script performs all reads but only previews the drafts. - Failure handling: stop with gog’s exit code if a call fails. The script must also pass
shellcheckwithout warnings.
Preparing the tokens and guards
The project uses the split from the recommended agent setup in Safety Controls for Scripts and Agents: a read-only token under the client name reader and the default token for drafts. Run these steps once, interactively:
gog auth credentials ~/Downloads/client_secret.json
gog --client reader auth credentials ~/Downloads/client_secret.json
gog --client reader --readonly auth add you@example.com --services gmail,calendar
gog auth add you@example.com --services gmail,calendar
gog auth alias set me you@example.com
gog config no-send set you@example.com
Before opening a browser, you can preview the read-only grant with gog --client reader --dry-run --json --readonly auth add you@example.com --services gmail,calendar --no-input; it reports the client reader and the scopes calendar.readonly and gmail.readonly, besides email, openid and userinfo.email. Note that the per-account guard uses the email address: a guard registered under the alias me would not take effect, as the safety chapter shows.
Hints
- Keep 2 flag arrays, one for reads and one for the draft step, and pass them with
"${read_flags[@]}". Quoted array expansion preserves every flag and value as a separate argument. gog calendar events primary --today --jsonreturns aneventsarray. Each event carriesstartLocalandendLocal: an RFC 3339 timestamp for timed events and a plain date for all-day events, asinternal/cmd/calendar_print.goformats them. The other fields, such assummaryandlocation, come from the Calendar API event.gog gmail drafts list --all --jsonreturns adraftsarray whose items carryid,messageIdandthreadId(internal/cmd/gmail_drafts.go). Compare its thread IDs with the search results to skip threads that already have a draft.gog gmail drafts create --thread-id <threadId> --reply-all --body-file <file>saves a reply draft in the thread:--thread-idtakes the reply headers from the latest message in the thread, and--reply-allfills the recipients from that message. The subject may be omitted when--thread-idis given.--enable-commands-exactrefuses every command it does not name, so give the read array only the 3 read commands and the write array onlygmail.drafts.create.- A real draft result carries
draftId; a dry run prints an object with"dry_run": trueinstead.
Worked solution
#!/usr/bin/env bash
set -euo pipefail
gog_bin="${GOG:-gog}"
account="${BRIEF_ACCOUNT:-me}"
read_client="${BRIEF_READ_CLIENT:-reader}"
unread_query="${BRIEF_UNREAD_QUERY:-is:unread newer_than:1d}"
reply_query="${BRIEF_REPLY_QUERY:-is:unread newer_than:1d label:needs-reply}"
reply_body="${BRIEF_REPLY_BODY_FILE:?set BRIEF_REPLY_BODY_FILE to a plain-text reply template}"
max="${BRIEF_MAX:-100}"
read_flags=(
--account "$account" --client "$read_client"
--readonly --gmail-no-send --no-input --json
--enable-commands-exact "gmail.search,gmail.drafts.list,calendar.events"
)
write_flags=(
--account "$account"
--gmail-no-send --no-input --json
--enable-commands-exact gmail.drafts.create
)
if [[ "${BRIEF_DRY_RUN:-0}" == 1 ]]; then
write_flags+=(--dry-run)
fi
events_filter='
def md: gsub("(?<c>[\\\\`*_\\[\\]<>#])"; "\\\(.c)");
def hhmm: if test("T") then .[11:16] else "(all day)" end;
"## Events today (\(.events | length))",
"",
(if (.events | length) == 0 then "No events today." else
(.events[]
| "- \((.startLocal // "") | hhmm)"
+ (if (.startLocal // "") | test("T") then "-\((.endLocal // "") | hhmm)" else "" end)
+ " \((.summary // "(no title)") | md)"
+ (if .location then " (\(.location | md))" else "" end))
end)
'
threads_filter='
def md: gsub("(?<c>[\\\\`*_\\[\\]<>#])"; "\\\(.c)");
"## Unread threads (\(.threads | length))",
"",
(if (.threads | length) == 0 then "No unread threads." else
(.threads[]
| "- **\((.subject // "") | if . == "" then "(no subject)" else md end)**"
+ " from \((.from // "unknown sender") | md)"
+ (if .date then ", \(.date)" else "" end))
end),
(if .has_more then "", "_More threads match; raise BRIEF_MAX._" else empty end)
'
printf '# Morning brief for %s\n\n' "$(date +%F)"
"$gog_bin" "${read_flags[@]}" calendar events primary --today --max "$max" |
jq -r "$events_filter"
printf '\n'
"$gog_bin" "${read_flags[@]}" gmail search --max "$max" -- "$unread_query" |
jq -r "$threads_filter"
printf '\n'
candidates="$("$gog_bin" "${read_flags[@]}" gmail search --max "$max" -- "$reply_query")"
drafts="$("$gog_bin" "${read_flags[@]}" gmail drafts list --all)"
mapfile -t thread_ids < <(
jq -rn --argjson c "$candidates" --argjson d "$drafts" '
([$d.drafts[]?.threadId] | map(select(. != null))) as $drafted
| $c.threads[].id
| select(. as $id | $drafted | any(. == $id) | not)
'
)
printf '## Reply drafts (%d new)\n\n' "${#thread_ids[@]}"
if ((${#thread_ids[@]} == 0)); then
printf 'No threads need a new draft.\n'
fi
for id in "${thread_ids[@]}"; do
result="$("$gog_bin" "${write_flags[@]}" gmail drafts create \
--thread-id "$id" --reply-all --body-file "$reply_body")"
printf -- '- thread %s: %s\n' "$id" \
"$(jq -r 'if .dry_run then "dry run, nothing created" else "draft \(.draftId)" end' <<<"$result")"
done
Run it with a template, first as a dry run:
printf 'Thanks for your message. I will reply in detail later today.\n' > ~/reply.txt
BRIEF_REPLY_BODY_FILE=~/reply.txt BRIEF_DRY_RUN=1 ./morning-brief.sh
How the solution meets each requirement:
- Read-only access: every read passes
--client reader --readonly, so the token is limited by Google to reading, and gog also refuses any mutating request. - Sending restrictions: the draft step allows exactly 1 command,
gmail drafts create, adds--gmail-no-send, and runs for an account that carries a config guard. Each of the 3 would refuse a send on its own. For a stricter setup, setGOGto a binary baked from theagent-safeprofile, which blocks every send command at build time. - No duplicate drafts: threads that already appear in the draft list are skipped, so running the script twice in one morning creates no second draft.
- Failure handling:
set -euo pipefailstops the script at the first failing gog call, including calls inside a pipeline, and the script exits with that call’s code.
The jq filters were checked against handwritten samples built from the definitions in the source, in the way the automation chapter tests inbox-digest.sh.
Verifying the write path with --dry-run
A dry run proves that the draft command is well formed and that the guards let it through. It also proves that the same flags refuse sending, because the command lists and the send guard run before the handler, where a dry run stops. The captures below use the script’s write_flags, in a home where me is an alias of you@example.com and gog config no-send set you@example.com has been run.
$ write_flags=(--account me --gmail-no-send --no-input --json --enable-commands-exact gmail.drafts.create)
$ gog "${write_flags[@]}" --dry-run gmail drafts create --thread-id thread-a --reply-all --body-file reply.txt | jq -c '{dry_run, op, thread_id: .request.thread_id, reply_all: .request.reply_all, body_len: .request.body_len}'
{"dry_run":true,"op":"gmail.drafts.create","thread_id":"thread-a","reply_all":true,"body_len":61}
Every send path is refused with exit code 2, even with --dry-run. With --json, each refusal also prints an error object on stdout; only the stderr line is shown for the last 3:
$ gog "${write_flags[@]}" --dry-run gmail send --to friend@example.com --subject t --body b
command "gmail send" is not enabled (set --enable-commands or --enable-commands-exact to allow it)
{"error":{"class":"usage","code":2,"message":"command \"gmail send\" is not enabled (set --enable-commands or --enable-commands-exact to allow it)"}}
$ gog "${write_flags[@]}" --dry-run send --to friend@example.com --subject t --body b
command "send" is not enabled (set --enable-commands or --enable-commands-exact to allow it)
$ gog "${write_flags[@]}" --dry-run gmail reply m1 --body b
command "gmail reply" is not enabled (set --enable-commands or --enable-commands-exact to allow it)
$ gog "${write_flags[@]}" --dry-run gmail drafts send r1
command "gmail drafts send" is not enabled (set --enable-commands or --enable-commands-exact to allow it)
gog reports the allowlist refusal first because it checks the allowlist before the send guard. Remove it, and the account’s config guard refuses the same commands:
$ gog --account me --no-input --dry-run gmail drafts send r1
Gmail sending is blocked for you@example.com (config no-send)
$ echo $?
2
Glossary
- Access token
- A short-lived credential that gog obtains from a refresh token and sends with each Google API request. A token passed directly with
--access-tokenexpires after about 1 hour and is not refreshed. - Account alias
- A short name for an account address, set with
gog auth alias set, such asmeforyou@example.com.defaultandautoare reserved and cannot be aliases. - Agent skill
- A short instruction file that teaches a coding agent which gog commands exist and how to use them. gog publishes a core skill, one skill per service and several workflow skills.
- Baked binary
- A gog executable built by
build-safe.shwith a safety profile compiled in. Its version carries a-safesuffix. - Client name
- The label that selects one OAuth client’s credentials file and its separate token bucket, chosen with
--clientorGOG_CLIENT. The default name isdefault. - Command allowlist
- The list of commands that may run, set with
--enable-commands(prefix match) or--enable-commands-exact(exact match). Commands are written as dot paths such asgmail.drafts.create. - Command denylist
- The list of commands that may not run, set with
--disable-commands. It matches command paths, so each send path must be listed separately. - Default account
- The account gog uses when neither
--accountnorGOG_ACCOUNTis set. - Dry run
- A run with
--dry-run(also-n), in which a command validates its input, prints the action it would take and exits 0 without contacting Google. - Envelope
- The JSON object that wraps a list result, for example
threadstogether withnextPageToken,countandhas_more.--results-onlyremoves it. - Exit code class
- The stable name gog gives each exit code, such as
usagefor 2 orauth_requiredfor 4. It appears asclassin JSON error objects and ingog schema. - Gmail send guard
- gog’s block on every command that delivers mail, enabled with
--gmail-no-send,GOG_GMAIL_NO_SEND, the config keygmail_no_sendor a per-account entry fromgog config no-send set. - History ID
- A Gmail counter that increases with every mailbox change.
gog gmail history --since <historyId>lists messages added after it. - Keyring
- The secure store in which gog keeps refresh tokens and OAuth client secrets: the operating system’s keyring, or an encrypted file backend selected with
GOG_KEYRING_BACKEND=fileand opened withGOG_KEYRING_PASSWORD. - MCP server
- The server started by
gog mcp, which offers typed tools such asgmail_searchto agent clients over the Model Context Protocol. Write tools need--allow-write, and sending needs--allow-gmail-sendin addition. - OAuth client
- The client ID and secret, downloaded from the Google Cloud console as a JSON file for a desktop app, that identify gog to Google during sign-in. You install it with
gog auth credentials. - OAuth scope
- A named permission, written as a URL such as
https://www.googleapis.com/auth/gmail.readonly, that you approve on Google’s consent screen. Google rejects any call that the token’s scopes do not cover. - Refresh token
- The long-lived credential that
gog auth addstores in the keyring for one account and one client name. gog exchanges it for access tokens as needed. - Runtime read-only guard
- The check enabled by
--readonlyorGOG_READONLY=1that rejects mutating HTTP requests just before gog sends them. Withgog auth add, the same flag requests read-only scopes. - Safety profile
- A YAML policy that allows or blocks command paths and can lock boolean flags. The presets are
agent-safe,readonlyandfull. - Schema
- The machine-readable description that
gog schemaprints: the command tree with arguments and flags, the exit codes, the output formats and the safety state of the current invocation. - Untrusted-content wrapping
- The
--wrap-untrustedoption, which marks text fetched from Google in JSON output as external content, so that a language model can tell it apart from instructions.