by adom
Drive your whole Google Workspace from the terminal, run by your AI. Read Gmail, write Google Docs, build Google Sheets and Google Slides, search Google Drive, manage Google Calendar and Google Tasks, and post to Google Chat, plus any Google API and a zero-setup personal Gmail.
← Commit history
v0.8.28: people find/list (Workspace domain directory, directory.readonly) + chat dm <name>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
7 files changed
+642−17
README.md+10−2@@ -190,6 +190,7 @@ default (no setup quiz), so all of this works out of the box: |---|---| | **Gmail** | read messages, attachments & `.ics` invites, labels, trash, organize | | **Contacts** (People) | create / list / search contacts, store service identities |+| **Directory** (People) | who is `<name>`: email, title, Chat DM space, from your own Workspace domain only | | **Calendar** | create / move / delete events, invite guests, manage calendars | | **Tasks** | create / list / complete task lists & tasks | | **Google Chat** | post to spaces, list spaces, read space messages |@@ -200,7 +201,9 @@ default (no setup quiz), so all of this works out of the box: | **Any other Google API** | YouTube, Forms, Apps Script, Admin SDK, Photos… via `api` passthrough | Full mode uses the broad scopes (`gmail.modify`, `contacts`, `drive`, `spreadsheets`,-`documents`, `presentations`, `calendar`, `tasks`, `chat.messages`, `chat.spaces.readonly`).+`documents`, `presentations`, `calendar`, `tasks`, `chat.*`, `directory.readonly`).+`directory.readonly` is the People API's read-only "see your organization's directory" scope that+any Workspace member can grant; it is not an Admin SDK scope (those stay behind `auth --admin`). `api` reaches **any** Google endpoint, your real ceiling is just your own Google permissions (admin APIs only work for admins). @@ -321,8 +324,13 @@ adom-google contacts list | search <query> # Gmail (read), attachment bytes + .ics invites the connectors can't reach adom-google gmail attachments <messageId> | read <messageId> <attId> | ics <messageId> +# Directory, who is <name>? Your own Workspace domain only (directory.readonly; older tokens:+# adom-google scopes --require directory.readonly --auto-widen)+adom-google people find Kale [--dm] [--json] # email, title, DM space; all matches listed, exact first+adom-google people list [--json] # everyone in the domain directory+ # Google Chat, post/read as YOURSELF (no webhook "(on behalf of)" prefix)-adom-google chat spaces | dm <email> | read --from <space|email>+adom-google chat spaces | dm <email|name> | read --from <space|email> adom-google chat send --to <space-id|email> "<text>|-|@file" [--thread <key>] adom-google status [--json] # what's authorized (never prints secrets); exit 1 until authorized
SKILL.md+48−3@@ -1,6 +1,6 @@ --- name: adom-google-description: "Programmatic read+write access to a user's WHOLE Google Workspace, Gmail, Contacts, Drive, Sheets, Docs, Slides, Calendar, Tasks, Google Chat, plus a generic `api` passthrough to hit ANY Google API. CLI + OAuth only (no browser automation). Public/open-source; used daily by the Adom team. Auth is the account-specific part, Adom employees use it out of the box; other orgs either self-host their own OAuth gateway or email [email protected] for a managed OAuth container (~$5/mo). First run just authorizes with FULL Workspace access (no mode question to ask the user). Use when setting up/installing adom-google, authorizing Google, reading Gmail attachments/.ics, creating/listing/searching Contacts, editing Sheets/Docs/Slides, Drive files, Calendar events, posting to Google Chat, or any Google Workspace automation. For a brand-new ORG that needs its own Google OAuth client (non-Adom team getting started), use the companion `adom-google-onboarding` skill, it drives the user's real browser through Google Cloud Console and auto-configures everything. Trigger words, adom-google, install adom-google, set up adom-google, configure adom-google, google workspace cli, edit google sheet/doc/slides, drive upload, calendar event, post to google chat, post to chat as me, message colby, send a chat, dm <person>, gmail attachment, google contacts, people api, full workspace access, google oauth gateway broker, google api passthrough, self-host oauth, managed oauth container, onboard my org to google, set up google workspace for my company/team, configure google oauth for <org>, get my company on adom-google, create our google cloud oauth client."+description: "Programmatic read+write access to a user's WHOLE Google Workspace, Gmail, Contacts, Drive, Sheets, Docs, Slides, Calendar, Tasks, Google Chat, plus a generic `api` passthrough to hit ANY Google API. CLI + OAuth only (no browser automation). Public/open-source; used daily by the Adom team. Auth is the account-specific part, Adom employees use it out of the box; other orgs either self-host their own OAuth gateway or email [email protected] for a managed OAuth container (~$5/mo). First run just authorizes with FULL Workspace access (no mode question to ask the user). Use when setting up/installing adom-google, authorizing Google, reading Gmail attachments/.ics, creating/listing/searching Contacts, looking a teammate up in the Workspace directory (name to email, title, Chat DM space), editing Sheets/Docs/Slides, Drive files, Calendar events, posting to Google Chat, or any Google Workspace automation. For a brand-new ORG that needs its own Google OAuth client (non-Adom team getting started), use the companion `adom-google-onboarding` skill, it drives the user's real browser through Google Cloud Console and auto-configures everything. Trigger words, adom-google, install adom-google, set up adom-google, configure adom-google, google workspace cli, edit google sheet/doc/slides, drive upload, calendar event, post to google chat, post to chat as me, message colby, send a chat, dm <person>, dm <name>, who is <name>, find email for <name>, what is <name>'s email, look up a coworker, company directory, org directory, workspace directory, gmail attachment, google contacts, people api, full workspace access, google oauth gateway broker, google api passthrough, self-host oauth, managed oauth container, onboard my org to google, set up google workspace for my company/team, configure google oauth for <org>, get my company on adom-google, create our google cloud oauth client." --- # adom-google@@ -70,7 +70,8 @@ adom-google auth This grants full Workspace scopes (`gmail.modify, contacts, drive, spreadsheets, documents, presentations, calendar, tasks`, plus Chat: `chat.messages, chat.spaces, chat.memberships,-chat.delete, chat.customemojis, chat.users.*`) plus the generic+chat.delete, chat.customemojis, chat.users.*`, plus `directory.readonly` for read-only+Workspace directory lookups, which is not an admin scope) plus the generic `adom-google api <url>` passthrough for **any** Google API. It prints a Google consent URL; the user clicks **Allow** once. @@ -295,7 +296,9 @@ adom-google contacts search <query> [-v] [--json] # Google Chat, posts as the SIGNED-IN USER (their own identity, NO attribution prefix). # This is distinct from `adom-gchat`, which posts via an org webhook with "(on behalf of …)". adom-google chat spaces [--json] # list your spaces (id · type · name)-adom-google chat dm <email> [--json] # resolve the 1:1 DM space with a person+adom-google chat dm <email|name> [--json] # resolve the 1:1 DM space with a person+# A NAME (no "@") resolves ONLY through your Workspace domain directory (see "People" below):+# one unique exact match, or an ERROR listing the candidates. An email works exactly as before. adom-google chat send --to <space-id|email> "<text>" # post; email auto-resolves the DM # "<text>" may be '-' (stdin) or '@file'; add --thread <key> to reply in a thread adom-google chat send --to <space-id|email> "here's the clip" --attach demo.webm@@ -349,6 +352,48 @@ to probe real capability **without creating anything**, send a deliberately inva target method, a missing scope fails 403 `ACCESS_TOKEN_SCOPE_INSUFFICIENT` *before* body validation, while a granted scope fails 400 `INVALID_ARGUMENT` (proof the call would work). +## People: who is <name>? (Workspace domain directory, v0.8.28+)++Resolve a teammate's name to their email, title and Chat DM space straight from the Google+Workspace directory. No hand-maintained people tables: the directory already is the org-wide table.++```bash+adom-google people find Kale # name, email, title/department; exact matches first+adom-google people find Kale --dm # + each match's existing 1:1 Chat DM space+adom-google people find kale --json # {status, data:{query, domain, count, exact, people[]}, hints[]}+adom-google people list [--json] # everyone in the domain directory+adom-google chat dm Kale # name -> DM space (one unique exact match, else ERROR)+```++**Domain-only guarantee.** Lookups and name-based DMs resolve ONLY to accounts in the signed-in+user's own Workspace domain (derived from the token at run time, never hard-coded). The single+source is the domain's user profiles (`DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE`); personal Contacts,+"other contacts", Gmail headers and admin-shared external contacts are never consulted, and any+result outside the domain is dropped. If the domain cannot be determined, or nothing matches, you+get an `ERROR:` line, never a guess. So `chat dm <name>` cannot land on someone outside the team.++Rules for the AI:+- **Several matches are all listed; nothing is picked for you.** "Kale" never silently becomes+ "Caleb". Show the user the list and use the exact email of the one they mean.+- `--dm` finds only an EXISTING 1:1 conversation (findDirectMessage). "none yet" means the user+ has to start it in Google Chat once; this CLI never creates it.+- `chat send --to` and `chat read --from` still take an email or space id only (no names), so a+ post can never go to a fuzzy-matched person. Resolve with `people find` first.+- Still ask the user before sending anything, as always.++**Scope.** Needs `directory.readonly`, the People API end-user "see your organization's+directory" scope. It is read-only and NOT an Admin SDK scope (no admin rights involved; the+`admin.directory.*` scopes stay out of every tier). New `auth` runs include it (safe and full).+Tokens minted before v0.8.28 get an `ERROR:` + `Hint:` with the one-time fix (exit 2):++```bash+adom-google scopes --require directory.readonly --auto-widen # one Allow click, keeps everything+```++If results come back empty for a whole domain, the Workspace admin has turned off directory+sharing (Admin console > Directory > Directory settings > Sharing settings > Contact sharing).+A personal @gmail account has no domain directory and gets an ERROR.+ ## Multiple accounts (v0.8.0+), e.g. work + personal, fully isolated `adom-google --account <name> <cmd>` (or `ADOM_GOOGLE_ACCOUNT=<name>`) runs ANY command against a
VERSION+1−1@@ -1 +1 @@-0.8.27+0.8.28
bin/adom-google+357−7@@ -23,7 +23,7 @@ See `adom-google help`. """ import sys, os, json, base64, argparse, urllib.parse, ssl, socket, hashlib, secrets, struct, time, subprocess, shutil -ADOM_GOOGLE_VERSION = "0.8.27"+ADOM_GOOGLE_VERSION = "0.8.28" if sys.argv[1:2] == ["--version"]: print(f"adom-google {ADOM_GOOGLE_VERSION}") sys.exit(0)@@ -92,6 +92,8 @@ SCOPES_SAFE = [ "https://www.googleapis.com/auth/chat.messages", # Google Chat — read + post (not a "delete all" risk) "https://www.googleapis.com/auth/chat.spaces.readonly", # Google Chat — list your spaces "https://www.googleapis.com/auth/chat.spaces.create", # Google Chat — CREATE spaces (create-only, fits SAFE)+ "https://www.googleapis.com/auth/directory.readonly", # People API — READ the Workspace user directory+ # (`people find/list`, `chat dm <name>`). Read-only and NOT an Admin SDK scope; see SCOPES_FULL. ] SCOPES_FULL = [ "https://www.googleapis.com/auth/gmail.modify", # Gmail read/compose/send/labels@@ -113,11 +115,18 @@ SCOPES_FULL = [ "https://www.googleapis.com/auth/chat.users.spacesettings", # per-user space settings "https://www.googleapis.com/auth/chat.users.availability", # presence "https://www.googleapis.com/auth/chat.users.sections", # sections+ "https://www.googleapis.com/auth/directory.readonly", # People API — READ the Workspace user+ # directory (people:searchDirectoryPeople / listDirectoryPeople) for `people find/list` and+ # `chat dm <name>`. This is NOT an Admin SDK scope: it is the end-user "see your organization's+ # directory" permission any Workspace member can grant (the data Gmail autocomplete already+ # shows), read-only, no admin rights involved. Validated against the authorize endpoint+ # 2026-10-30 (accepted; a typo'd variant returns invalid_scope). # (Chat works because the shared rock-verbena project has a configured Chat app.) # Every string above was validated against Google's authorize endpoint before shipping (issue # #233): an invalid scope makes Google reject the WHOLE request with invalid_scope, which # breaks sign-in entirely rather than just the new capability. Re-validate before adding more.- # Admin/Directory scopes stay OUT — separate admin-only opt-in. chat.admin.* stays OUT+ # Admin SDK scopes (admin.directory.*) stay OUT — separate admin-only opt-in (SCOPES_ADMIN).+ # directory.readonly above is the People API end-user scope, not the Admin SDK. chat.admin.* stays OUT # PERMANENTLY: it is an org-wide admin surface, not a "drive my own Chat" capability. ] @@ -765,6 +774,314 @@ def cmd_contacts_search(a): print(f" resourceName: {p.get('resourceName','')}") +# ---------------------------------------------------------------- people (Workspace domain directory)+# "Who is Kale?" -> name, email, title, Chat DM space, straight from the Google Workspace directory,+# so nobody has to hand-maintain a people table. Uses the People API DIRECTORY endpoints+# (people:searchDirectoryPeople / people:listDirectoryPeople) under the+# `directory.readonly` scope. That scope is NOT an Admin SDK scope: it is the ordinary+# end-user "see your organization's directory" permission (the same data Gmail autocomplete+# shows), any Workspace member can grant it, and it is read-only. The Admin SDK+# (admin.directory.*) stays out of every tier; see SCOPES_ADMIN.+#+# DOMAIN-ONLY GUARANTEE (Drew, 2026-10-30): every lookup here, and every NAME passed to+# `chat dm`, resolves only to accounts in the signed-in user's OWN Workspace domain, so nobody+# DMs someone outside the team by accident:+# * the only source is DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE (the domain's user accounts).+# Never DOMAIN_CONTACT (admin-shared EXTERNAL contacts), never personal Contacts, "other+# contacts" or Gmail headers;+# * every result is then filtered to emails ending in @<the signed-in account's domain>, derived+# from the token at run time (never hard-coded, since other orgs use this public CLI);+# * when the domain cannot be determined, nothing is returned: an ERROR, never a guess.+SCOPE_DIRECTORY = "https://www.googleapis.com/auth/directory.readonly"+DIRECTORY_SOURCE = "DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE"+DIRECTORY_READMASK = "names,emailAddresses,organizations,photos"+_CONSUMER_DOMAINS = {"gmail.com", "googlemail.com"}+++def _acct_flag():+ return "" if ACCOUNT == "default" else f" --account {ACCOUNT}"+++def _people_fail(as_json, msg, hints, code=1, data=None):+ """Print ERROR + Hint lines (or the JSON envelope) and exit with `code`. Never a traceback."""+ if as_json:+ print(json.dumps({"status": "error", "error": msg, "data": data, "hints": hints}, indent=2))+ else:+ sys.stderr.write(f"ERROR: {msg}\n" + "".join(f"Hint: {h}\n" for h in hints))+ sys.exit(code)+++def _account_email(cfg):+ """The signed-in account's email, used ONLY to derive the domain filter. Cached in the config+ (keyed to the refresh token, so a re-auth as someone else invalidates it). Tries tokeninfo+ (has `email` when an email/openid scope is held), then Gmail users/me/profile (gmail.modify /+ gmail.compose, which every tier holds), then People people/me. Returns '' when none works."""+ rt_tag = hashlib.sha256((cfg.get("refresh_token") or "").encode()).hexdigest()[:16]+ if cfg.get("account_email") and cfg.get("account_email_for") == rt_tag:+ return cfg["account_email"]+ email = ""+ probes = [+ ("https://oauth2.googleapis.com/tokeninfo", lambda j: j.get("email")),+ (f"{GMAIL_API}/profile", lambda j: j.get("emailAddress")),+ (f"{PEOPLE_API}/people/me?personFields=emailAddresses",+ lambda j: next((e.get("value") for e in j.get("emailAddresses") or []+ if (e.get("metadata") or {}).get("primary")), None)),+ ]+ for url, pick in probes:+ try:+ if "tokeninfo" in url:+ r = requests.get(url, params={"access_token": _access_token(cfg)}, timeout=20)+ else:+ r = _request_raw(cfg, "GET", url, timeout=20)+ if r.status_code == 200:+ email = (pick(r.json()) or "").strip().lower()+ except (requests.RequestException, ValueError):+ email = ""+ if "@" in email:+ break+ if "@" in email:+ cfg["account_email"], cfg["account_email_for"] = email, rt_tag+ _save(cfg)+ return email+ return ""+++def _own_domain(cfg, as_json):+ email = _account_email(cfg)+ if not email:+ _people_fail(as_json, "could not determine which Google account this token belongs to, so the "+ "domain-only filter cannot be applied; refusing to return anyone.",+ [f"check the token works: adom-google{_acct_flag()} scopes",+ f"re-authorize if it is stale: adom-google{_acct_flag()} auth"])+ domain = email.rsplit("@", 1)[1]+ if domain in _CONSUMER_DOMAINS:+ _people_fail(as_json, f"{email} is a personal Google account; it has no Workspace domain "+ "directory to look people up in.",+ ["use a Workspace account: adom-google --account <work-account> people find <name>",+ "or pass an explicit email to the command you were running"])+ return domain+++def _primary_email(p):+ ems = p.get("emailAddresses") or []+ for e in ems:+ if (e.get("metadata") or {}).get("primary"):+ return (e.get("value") or "").strip()+ return (ems[0].get("value") or "").strip() if ems else ""+++def _person_row(p):+ """Flatten a People API Person into the fields we print / return."""+ n = (p.get("names") or [{}])[0]+ org = (p.get("organizations") or [{}])[0]+ photo = (p.get("photos") or [{}])[0]+ email = _primary_email(p)+ return {+ "name": n.get("displayName") or email or "(no name)",+ "givenName": n.get("givenName", ""),+ "familyName": n.get("familyName", ""),+ "email": email,+ "otherEmails": [e.get("value") for e in (p.get("emailAddresses") or [])+ if e.get("value") and e.get("value") != email],+ "title": org.get("title", ""),+ "department": org.get("department", ""),+ "photo": photo.get("url", "") if not photo.get("default") else "",+ "resourceName": p.get("resourceName", ""),+ }+++def _in_domain(row, domain):+ return row["email"].lower().endswith("@" + domain.lower())+++def _match_rank(row, q):+ """Lower is better. Exact identity first so 'Kale' never silently becomes 'Caleb':+ 0 exact email / full name; 1 exact first name or email local part; 2 prefix of+ first/last name or local part; 3 anything else the directory returned."""+ q = q.strip().lower()+ email = row["email"].lower()+ local = email.split("@", 1)[0]+ name, given, family = row["name"].lower(), row["givenName"].lower(), row["familyName"].lower()+ if q == email or q == name:+ return 0+ if q == given or q == local:+ return 1+ if any(x.startswith(q) for x in (given, family, local) if x):+ return 2+ return 3+++def _directory_get(cfg, endpoint, params, as_json):+ """GET a People API directory endpoint, all pages. Turns every failure into ERROR + Hint."""+ out, page = [], None+ while True:+ q = dict(params)+ if page:+ q["pageToken"] = page+ try:+ r = _request_raw(cfg, "GET", f"{PEOPLE_API}/people:{endpoint}", params=q, timeout=30)+ except requests.RequestException as e:+ _people_fail(as_json, f"could not reach the People API: {e}",+ ["check network access to people.googleapis.com, then retry"])+ if r.status_code == 403:+ text = r.text or ""+ if "ACCESS_TOKEN_SCOPE_INSUFFICIENT" in text or "insufficientPermissions" in text:+ _people_fail(as_json,+ "this token cannot read the Workspace directory yet (missing the "+ "directory.readonly scope; it is a read-only, non-admin scope).",+ [f"widen it, ONE browser Allow click, everything you already hold is kept: "+ f"adom-google{_acct_flag()} scopes --require directory.readonly --auto-widen",+ "then re-run the same command"],+ code=2, data={"missing_scope": SCOPE_DIRECTORY})+ if "SERVICE_DISABLED" in text or "accessNotConfigured" in text:+ _scope_wall_hint(r.url, r)+ _people_fail(as_json, "the People API is not enabled in this OAuth client's Google Cloud project.",+ ["see the block above for the console link and who can enable it"])+ _people_fail(as_json, f"People API refused the directory read (403): {text[:300]}",+ ["the Workspace admin may have turned off directory sharing "+ "(Admin console > Directory > Directory settings > Sharing settings > Contact sharing)",+ "or this is not a Workspace account; personal Google accounts have no domain directory"])+ if r.status_code >= 400:+ _people_fail(as_json, f"People API error {r.status_code} on {endpoint}: {(r.text or '')[:300]}",+ ["retry; if it persists check `adom-google scopes` and the People API status"])+ j = r.json() if r.content else {}+ out += j.get("people") or []+ page = j.get("nextPageToken")+ if not page:+ return out+++def _people_search(cfg, query, domain, as_json, limit=200):+ """Domain-profile search -> ranked, de-duplicated, own-domain-only rows."""+ people = _directory_get(cfg, "searchDirectoryPeople",+ {"query": query, "readMask": DIRECTORY_READMASK,+ "sources": DIRECTORY_SOURCE, "pageSize": 100}, as_json)+ rows, seen = [], set()+ for p in people:+ row = _person_row(p)+ if not row["email"] or not _in_domain(row, domain):+ continue # domain-only guarantee+ key = row["email"].lower()+ if key in seen:+ continue+ seen.add(key)+ row["rank"] = _match_rank(row, query)+ rows.append(row)+ rows.sort(key=lambda r: (r["rank"], r["name"].lower()))+ return rows[:limit]+++def _dm_for(cfg, email):+ """(space_name, spaceUri, error) for the 1:1 DM with `email`; never exits."""+ try:+ sp = _find_dm(cfg, email)+ except SystemExit as e: # _chat exits on non-404 errors+ return None, None, str(e.code if e.code is not None else "Chat API error")[:300]+ return sp.get("name"), sp.get("spaceUri"), None+++def _fmt_person(r):+ extra = " · ".join(x for x in (r["title"], r["department"]) if x)+ return f" {r['name']:28} {r['email']:32}" + (f" {extra}" if extra else "")+++_RANK_LABEL = {0: "exact", 1: "exact first name / email", 2: "prefix", 3: "partial"}+++def cmd_people_find(a):+ cfg = _load()+ q = a.query.strip()+ if not q:+ _people_fail(a.json, "empty query", ["pass a name or email, e.g. adom-google people find Kale"])+ domain = _own_domain(cfg, a.json)+ rows = _people_search(cfg, q, domain, a.json, limit=a.limit)+ if not rows:+ _people_fail(a.json, f'no one in the {domain} directory matches "{q}".',+ ["try a first name, a last name, or the email local part",+ f"see everyone: adom-google{_acct_flag()} people list"],+ data={"query": q, "domain": domain, "people": []})+ if a.dm:+ for r in rows[:10]: # cap Chat lookups on very broad queries+ r["dm_space"], r["dm_uri"], r["dm_error"] = _dm_for(cfg, r["email"])+ hints = []+ best = [r for r in rows if r["rank"] == rows[0]["rank"]]+ if len(rows) > 1:+ hints.append(f'{len(rows)} people match "{q}"; nothing was picked for you. '+ "Use the exact email of the one you mean, e.g. "+ f"adom-google{_acct_flag()} chat dm {rows[0]['email']}")+ if a.dm and any(r.get("dm_space") is None and not r.get("dm_error") for r in rows[:10]):+ hints.append("no DM space exists yet with some of these people; findDirectMessage only finds an "+ "existing 1:1 conversation. Start one in Google Chat first (this CLI never creates it).")+ if a.dm and len(rows) > 10:+ hints.append("DM spaces resolved for the first 10 matches only; narrow the query for the rest")+ if a.json:+ print(json.dumps({"status": "ok", "data": {"query": q, "domain": domain, "count": len(rows),+ "exact": len(best) == 1 and best[0]["rank"] <= 1,+ "people": rows},+ "hints": hints}, indent=2, ensure_ascii=False))+ return+ print(f'OK: {len(rows)} match{"es" if len(rows) != 1 else ""} for "{q}" in the {domain} directory')+ for r in rows:+ print(_fmt_person(r) + f" [{_RANK_LABEL[r['rank']]}]")+ if a.dm and "dm_space" in r:+ if r["dm_space"]:+ print(f" DM: {r['dm_space']}" + (f" · {r['dm_uri']}" if r.get("dm_uri") else ""))+ elif r.get("dm_error"):+ print(f" DM: lookup failed ({r['dm_error'].splitlines()[0]})")+ else:+ print(" DM: none yet (no existing 1:1 conversation)")+ for h in hints:+ print(f"Hint: {h}")+++def cmd_people_list(a):+ cfg = _load()+ domain = _own_domain(cfg, a.json)+ people = _directory_get(cfg, "listDirectoryPeople",+ {"readMask": DIRECTORY_READMASK, "sources": DIRECTORY_SOURCE,+ "pageSize": 1000}, a.json)+ rows, seen = [], set()+ for p in people:+ row = _person_row(p)+ if not row["email"] or not _in_domain(row, domain) or row["email"].lower() in seen:+ continue # domain-only guarantee+ seen.add(row["email"].lower())+ rows.append(row)+ rows.sort(key=lambda r: r["name"].lower())+ if a.limit:+ rows = rows[:a.limit]+ if a.json:+ print(json.dumps({"status": "ok", "data": {"domain": domain, "count": len(rows), "people": rows},+ "hints": []}, indent=2, ensure_ascii=False))+ return+ print(f"OK: {len(rows)} people in the {domain} directory")+ for r in rows:+ print(_fmt_person(r))+ if not rows:+ print("Hint: an empty directory usually means the Workspace admin turned off directory sharing "+ "(Admin console > Directory > Directory settings > Sharing settings > Contact sharing)")+++def _resolve_name_to_email(cfg, name, as_json):+ """`chat dm <name>`: resolve through the DOMAIN directory only. Exactly one best match or ERROR.+ A unique exact hit (full name / first name / local part) wins even if prefix hits exist;+ otherwise there must be exactly one result overall. Never guesses."""+ domain = _own_domain(cfg, as_json)+ rows = _people_search(cfg, name, domain, as_json)+ if not rows:+ _people_fail(as_json, f'no one in the {domain} directory matches "{name}"; not guessing.',+ [f"search more broadly: adom-google{_acct_flag()} people find <part-of-name>",+ "or pass the exact email: adom-google chat dm <email>"])+ # A unique hit in the best exact tier wins; otherwise the whole result set must be one person.+ pick = [r for r in rows if r["rank"] == rows[0]["rank"]] if rows[0]["rank"] <= 1 else rows+ if len(pick) != 1:+ listing = "; ".join(f"{r['name']} <{r['email']}>" for r in pick[:15])+ _people_fail(as_json, f'"{name}" matches {len(pick)} people in the {domain} directory: {listing}',+ ["re-run with the exact email of the one you mean: adom-google chat dm <email>"],+ data={"query": name, "domain": domain, "people": pick})+ return pick[0]++ # ---------------------------------------------------------------- Google Chat (as the user) # Posts as the SIGNED-IN user (their own Google identity) — no attribution prefix. This is # distinct from adom-gchat, which posts via an org webhook and prefixes "(on behalf of …)".@@ -870,14 +1187,29 @@ def cmd_chat_spaces(a): def cmd_chat_dm(a): cfg = _load()- sp = _find_dm(cfg, a.email)+ target, person = a.email.strip(), None+ if "@" not in target:+ # A NAME: resolve through the Workspace DOMAIN directory only (exactly one match, or ERROR).+ # An explicit email keeps its original behaviour below, unchanged.+ person = _resolve_name_to_email(cfg, target, a.json)+ target = person["email"]+ sys.stderr.write(f"(resolved \"{a.email}\" -> {person['name']} <{target}> via the domain directory)\n")+ sp = _find_dm(cfg, target) name = sp.get("name") if not name:+ if person:+ _people_fail(a.json, f"{person['name']} <{target}> is in the directory but you have no 1:1 DM "+ "with them yet; findDirectMessage only finds an existing conversation.",+ ["start the conversation in Google Chat once, then re-run this command"],+ data={"person": person}) sys.exit(f"no DM/space found for {a.email} — run 'adom-google chat spaces', or check the email") if a.json:+ if person:+ sp = dict(sp, resolvedPerson={"name": person["name"], "email": target}) print(json.dumps(sp, indent=2, ensure_ascii=False)) return- print(name + (f" · {sp.get('spaceUri')}" if sp.get("spaceUri") else ""))+ print(name + (f" · {sp.get('spaceUri')}" if sp.get("spaceUri") else "")+ + (f" · {person['name']} <{target}>" if person else "")) def cmd_chat_send(a):@@ -1029,6 +1361,8 @@ def _scope_wall_hint(url, resp): "without which a new group silently rejects external mail.\n") else: guess = _HOST_SCOPE.get(host)+ if host == "people.googleapis.com" and "Directory" in urllib.parse.urlparse(url).path:+ guess = "directory.readonly" # searchDirectoryPeople / listDirectoryPeople e.write("The token is missing a scope for this API. Check what you actually hold:\n" " adom-google scopes\n") if guess:@@ -2128,10 +2462,22 @@ CONTACTS (Google People API; read + write): adom-google contacts list [--limit N] [--json] adom-google contacts search <query> [-v] [--json] +PEOPLE (your Workspace DOMAIN directory; read-only `directory.readonly`, NOT an admin scope):+ adom-google people find <name|email> [--dm] [--limit N] [--json]+ who is <name>: email, title, department; exact first-name /+ email matches first; several matches are ALL listed, never+ picked for you. --dm also shows each existing 1:1 Chat DM space.+ adom-google people list [--limit N] [--json] everyone in the domain directory+ Domain-only: results are only accounts in YOUR OWN Workspace domain (no personal contacts,+ no shared external contacts). Older tokens lack the scope; widen once (one Allow click):+ adom-google scopes --require directory.readonly --auto-widen+ CHAT (Google Chat — posts as YOU, your own identity, no attribution prefix; adom-gchat is the other one — it posts via an org webhook with "(on behalf of)"): adom-google chat spaces [--json] list your spaces (id · type · name)- adom-google chat dm <email> [--json] resolve the 1:1 DM space with a person+ adom-google chat dm <email|name> [--json] resolve the 1:1 DM space with a person;+ a name resolves via the domain directory+ (one unique exact match, else ERROR listing them) adom-google chat send --to <space-id|email> "<text>" post a message (email auto-resolves DM) "<text>" may be '-' (stdin) or '@file'; --thread <key> replies in a thread adom-google chat read --from <space-id|email> [--limit N] [--json] recent messages@@ -2529,7 +2875,7 @@ def main(): s = sub.add_parser("auth", description=( "Authorize this container against Google. Default = FULL Workspace access (Gmail, Drive, " "Sheets, Docs, Slides, Calendar, Tasks, Chat incl. spaces/memberships/delete). "- "Admin/Directory scopes are NOT in any tier by default; add them with --admin (one "+ "Admin SDK scopes (admin.directory.*) are NOT in any tier by default; add them with --admin (one " "consent, no second browser trip) to manage Google Groups / distribution lists. " "Already authorized and just missing one capability? Do NOT re-run a bare `auth` -- use " "`adom-google scopes --require <scope> --auto-widen`, which preserves what you already "@@ -2603,11 +2949,15 @@ def main(): ch = sub.add_parser("chat"); chx = ch.add_subparsers(dest="sub") x = chx.add_parser("spaces"); x.add_argument("--json", action="store_true"); x.set_defaults(fn=cmd_chat_spaces)- x = chx.add_parser("dm"); x.add_argument("email"); x.add_argument("--json", action="store_true"); x.set_defaults(fn=cmd_chat_dm)+ x = chx.add_parser("dm", help="resolve the 1:1 DM space with a person (email, or a name looked up in your Workspace domain directory)"); x.add_argument("email", metavar="email|name", help="an email, or a name resolved ONLY through your own Workspace domain directory: a unique exact first-name / full-name / email-local-part match, or a single result; anything else is an ERROR listing the candidates"); x.add_argument("--json", action="store_true"); x.set_defaults(fn=cmd_chat_dm) x = chx.add_parser("send"); x.add_argument("--to", required=True, help="spaces/XXX id OR an email (auto-resolves the DM)"); x.add_argument("text", nargs="?", default="", help="message text, or '-' for stdin, or '@file' (optional when --attach is used)"); x.add_argument("--thread", help="threadKey for a threaded reply"); x.add_argument("--attach", action="append", metavar="PATH", help="attach a local file (image/video/PDF/any); repeatable"); x.add_argument("--no-agent-marker", action="store_true", help="don't stamp clientAssignedMessageId=client-agent-*"); x.set_defaults(fn=cmd_chat_send) x = chx.add_parser("read"); x.add_argument("--from", dest="frm", required=True, help="spaces/XXX id OR an email"); x.add_argument("--limit", type=int, default=20); x.add_argument("--json", action="store_true"); x.set_defaults(fn=cmd_chat_read) # Calendar (issue #662)+ pp = sub.add_parser("people", help="Workspace domain directory: who is <name>, their email, title, Chat DM space"); ppx = pp.add_subparsers(dest="sub")+ x = ppx.add_parser("find", help="search YOUR Workspace domain directory by name or email (domain accounts only)"); x.add_argument("query", help="a first/last/full name, email local part, or email"); x.add_argument("--dm", action="store_true", help="also resolve each match's existing 1:1 Chat DM space (first 10 matches)"); x.add_argument("--limit", type=int, default=50, help="max matches to show (default 50)"); x.add_argument("--json", action="store_true", help="{status, data:{query, domain, count, exact, people[]}, hints[]} envelope"); x.set_defaults(fn=cmd_people_find)+ x = ppx.add_parser("list", help="every account in YOUR Workspace domain directory (paginated)"); x.add_argument("--limit", type=int, default=0, help="max people to show (default 0 = all)"); x.add_argument("--json", action="store_true", help="{status, data:{domain, count, people[]}, hints[]} envelope"); x.set_defaults(fn=cmd_people_list)+ cal = sub.add_parser("calendar", help="Google Calendar: list/create events, list calendars"); cax = cal.add_subparsers(dest="sub") x = cax.add_parser("list", help="upcoming events"); x.add_argument("--cal", default="primary"); x.add_argument("--max", type=int, default=10); x.add_argument("--json", action="store_true"); x.set_defaults(fn=cmd_calendar_list) x = cax.add_parser("create", help="create an event"); x.add_argument("--summary", required=True); x.add_argument("--start", help="RFC3339, e.g. 2026-08-20T14:00:00-05:00"); x.add_argument("--end", help="RFC3339"); x.add_argument("--location"); x.add_argument("--description"); x.add_argument("--attendees", help="comma-separated emails"); x.add_argument("--cal", default="primary"); x.add_argument("--send", action="store_true", help="email invites to attendees"); x.add_argument("--json", action="store_true"); x.set_defaults(fn=cmd_calendar_create)
package.json+8−3@@ -1,6 +1,6 @@ { "slug": "adom-google",- "version": "0.8.27",+ "version": "0.8.28", "type": "app", "license": "MIT", "description": "Drive your whole Google Workspace from the terminal: Gmail, Contacts, Drive, Sheets, Docs, Slides, Calendar, Tasks, Google Chat, plus a generic `api` passthrough to hit ANY Google API. Connect a personal @gmail (or another org's Google account) with ZERO setup via Adom's hosted Connector (`adom-google connect-personal`), or bring your own token-broker gateway (`provider set`): Adom staff use the private adom-google-adom provider. One-click OAuth, no client secret on your machine.",@@ -19,7 +19,8 @@ "google-chat", "google-api", "cli",- "ai-agent"+ "ai-agent",+ "google-directory" ], "tags": [ "google-workspace",@@ -66,7 +67,11 @@ "connect my personal gmail", "use adom-google with my personal gmail", "connect my gmail account",- "adom-google"+ "adom-google",+ "who is on my team",+ "find the email for a coworker",+ "look up a teammate in the company directory",+ "dm a teammate by name" ], "dependencies": {}, "scripts": {
page.json+1−1@@ -4,7 +4,7 @@ "slug": "adom-google", "title": "Adom Google", "brief": "Drive your whole Google Workspace from the terminal, run by your AI. Read Gmail, write Google Docs, build Google Sheets and Google Slides, search Google Drive, manage Google Calendar and Google Tasks, and post to Google Chat, plus any Google API and a zero-setup personal Gmail.",- "version": "0.8.27",+ "version": "0.8.28", "visibility": "public", "install": { "binary_name": "adom-google"
tests/test_people.pyadded+217@@ -0,0 +1,217 @@+#!/usr/bin/env python3+"""Offline tests for `people find/list` and `chat dm <name>` (no network, no real token).++Loads bin/adom-google as a module under a throwaway HOME with a fake, already-valid access token,+then replaces requests.request / requests.get with canned People API + Chat responses.++ python3 tests/test_people.py # exits non-zero on any failure+"""+import contextlib, importlib.machinery, importlib.util, io, json, os, sys, tempfile, time, types, unittest++HERE = os.path.dirname(os.path.abspath(__file__))+BIN = os.path.join(HERE, "..", "bin", "adom-google")+++def P(given, family, email, title="", dept="", primary=True):+ return {"resourceName": f"people/{email.split('@')[0]}",+ "names": [{"displayName": f"{given} {family}".strip(), "givenName": given, "familyName": family}],+ "emailAddresses": [{"value": email, "metadata": {"primary": primary}}],+ "organizations": [{"title": title, "department": dept}] if title or dept else []}+++DIRECTORY = [+ P("Kale", "Weimer", "[email protected]", "Mechanical Engineer", "Engineering"),+ P("Caleb", "Stone", "[email protected]", "Technician"),+ P("Kalen", "Ross", "[email protected]"),+ P("Dan", "Park", "[email protected]"),+ P("Dan", "Wu", "[email protected]"),+ P("Outside", "Vendor", "[email protected]"), # NOT our domain: must never appear+]+++class Resp:+ def __init__(self, status, body, url=""):+ self.status_code, self._body, self.url = status, body, url+ self.text = json.dumps(body)+ self.content = self.text.encode()++ def json(self):+ return self._body+++class Fake:+ """Routes requests by URL. `scope_ok=False` makes directory calls return the real 403 shape."""+ def __init__(self, scope_ok=True, me="[email protected]", dms=None):+ self.scope_ok, self.me, self.dms, self.calls = scope_ok, me, dms or {}, []++ def request(self, method, url, headers=None, params=None, **kw):+ self.calls.append((method, url, dict(params or {})))+ params = params or {}+ if "people:searchDirectoryPeople" in url or "people:listDirectoryPeople" in url:+ assert params.get("sources") == "DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE", params+ if not self.scope_ok:+ return Resp(403, {"error": {"code": 403, "status": "PERMISSION_DENIED", "details": [+ {"reason": "ACCESS_TOKEN_SCOPE_INSUFFICIENT"}]}}, url)+ if "search" in url:+ q = params["query"].lower()+ hits = [p for p in DIRECTORY if any(+ x.lower().startswith(q) for x in (p["names"][0]["givenName"], p["names"][0]["familyName"],+ p["emailAddresses"][0]["value"]))]+ else:+ hits = DIRECTORY+ # two pages, to exercise pagination+ if not params.get("pageToken") and len(hits) > 1:+ return Resp(200, {"people": hits[:1], "nextPageToken": "p2"}, url)+ return Resp(200, {"people": hits[1:] if params.get("pageToken") else hits}, url)+ if url.endswith("/gmail/v1/users/me/profile"):+ return Resp(200, {"emailAddress": self.me}, url)+ if "spaces:findDirectMessage" in url:+ email = params["name"].split("/", 1)[1]+ if email in self.dms:+ return Resp(200, {"name": self.dms[email], "spaceUri": "https://chat.google.com/dm/x"}, url)+ return Resp(404, {"error": {"code": 404}}, url)+ raise AssertionError(f"unexpected request {method} {url}")++ def get(self, url, params=None, **kw):+ if "tokeninfo" in url: # no email scope -> no `email` field+ return Resp(200, {"scope": "x"}, url)+ return self.request("GET", url, params=params, **kw)+++def load(fake):+ home = tempfile.mkdtemp()+ os.makedirs(os.path.join(home, ".config", "adom-google"))+ with open(os.path.join(home, ".config", "adom-google", "config.json"), "w") as f:+ json.dump({"refresh_token": "fake", "access_token": "fake", "access_expires": time.time() + 3600,+ "broker": True, "mode": "full", "scopes": []}, f)+ os.environ["HOME"] = home+ os.environ.pop("ADOM_GOOGLE_ACCOUNT", None)+ sys.argv = ["adom-google"]+ loader = importlib.machinery.SourceFileLoader("adom_google_under_test", BIN)+ mod = importlib.util.module_from_spec(importlib.util.spec_from_loader(loader.name, loader))+ loader.exec_module(mod)+ mod.requests.request = fake.request+ mod.requests.get = fake.get+ return mod+++def run(mod, argv):+ """Run main() with argv; return (exit_code, stdout, stderr)."""+ out, err, code = io.StringIO(), io.StringIO(), 0+ sys.argv = ["adom-google"] + argv+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):+ try:+ mod.main()+ except SystemExit as e:+ code = e.code if isinstance(e.code, int) else 1+ if e.code and not isinstance(e.code, int):+ err.write(str(e.code))+ return code, out.getvalue(), err.getvalue()+++class PeopleTests(unittest.TestCase):+ def test_find_exact_first_name_ranks_first_and_lists_all(self):+ mod = load(Fake())+ code, out, err = run(mod, ["people", "find", "Kale"])+ self.assertEqual(code, 0, err)+ lines = [l for l in out.splitlines() if "@" in l and not l.startswith("Hint")]+ self.assertIn("[email protected]", lines[0]) # exact first name first+ self.assertTrue(any("[email protected]" in l for l in lines)) # prefix match still listed+ self.assertNotIn("[email protected]", out) # Kale is never Caleb+ self.assertNotIn("vendor.io", out) # domain-only+ self.assertIn("nothing was picked for you", out)++ def test_find_json_envelope_and_pagination(self):+ fake = Fake()+ mod = load(fake)+ code, out, _ = run(mod, ["people", "find", "Kale", "--json"])+ env = json.loads(out)+ self.assertEqual(env["status"], "ok")+ self.assertEqual(env["data"]["domain"], "example.com")+ self.assertEqual([p["email"] for p in env["data"]["people"]], ["[email protected]", "[email protected]"])+ self.assertEqual(env["data"]["people"][0]["title"], "Mechanical Engineer")+ self.assertTrue(any(c[2].get("pageToken") == "p2" for c in fake.calls))++ def test_find_dm_resolves_existing_space_and_flags_missing(self):+ mod = load(Fake(dms={"[email protected]": "spaces/KALE"}))+ code, out, _ = run(mod, ["people", "find", "Kale", "--dm"])+ self.assertEqual(code, 0)+ self.assertIn("DM: spaces/KALE", out)+ self.assertIn("DM: none yet", out) # Kalen has no DM+ self.assertIn("never creates it", out)++ def test_find_no_match_is_error_with_hint(self):+ mod = load(Fake())+ code, _, err = run(mod, ["people", "find", "Zed"])+ self.assertEqual(code, 1)+ self.assertIn("ERROR: no one in the example.com directory", err)+ self.assertIn("Hint:", err)++ def test_list_domain_only_sorted(self):+ mod = load(Fake())+ code, out, _ = run(mod, ["people", "list", "--json"])+ env = json.loads(out)+ emails = [p["email"] for p in env["data"]["people"]]+ self.assertEqual(len(emails), 5)+ self.assertNotIn("[email protected]", emails)++ def test_missing_scope_is_graceful(self):+ mod = load(Fake(scope_ok=False))+ code, out, err = run(mod, ["people", "find", "Kale"])+ self.assertEqual(code, 2)+ self.assertIn("ERROR:", err)+ self.assertIn("scopes --require directory.readonly --auto-widen", err)+ self.assertNotIn("Traceback", err)++ def test_personal_account_refused(self):+ mod = load(Fake(me="[email protected]"))+ code, _, err = run(mod, ["people", "find", "Kale"])+ self.assertEqual(code, 1)+ self.assertIn("personal Google account", err)++ def test_chat_dm_name_unique(self):+ mod = load(Fake(dms={"[email protected]": "spaces/KALE"}))+ code, out, err = run(mod, ["chat", "dm", "Kale"])+ self.assertEqual(code, 0, err)+ self.assertTrue(out.startswith("spaces/KALE"))+ self.assertIn("[email protected]", err) # says how it resolved++ def test_chat_dm_name_ambiguous_errors(self):+ mod = load(Fake())+ code, _, err = run(mod, ["chat", "dm", "Dan"])+ self.assertEqual(code, 1)+ self.assertIn('"Dan" matches 2 people', err)+ self.assertIn("[email protected]", err)+ self.assertIn("[email protected]", err)++ def test_chat_dm_name_not_found_never_guesses(self):+ mod = load(Fake())+ code, _, err = run(mod, ["chat", "dm", "Zed"])+ self.assertEqual(code, 1)+ self.assertIn("not guessing", err)++ def test_chat_dm_name_in_directory_but_no_dm(self):+ mod = load(Fake())+ code, _, err = run(mod, ["chat", "dm", "Caleb"])+ self.assertEqual(code, 1)+ self.assertIn("no 1:1 DM", err)++ def test_chat_dm_email_path_unchanged(self):+ fake = Fake(dms={"[email protected]": "spaces/EXT"})+ mod = load(fake)+ code, out, _ = run(mod, ["chat", "dm", "[email protected]"])+ self.assertEqual(code, 0)+ self.assertTrue(out.startswith("spaces/EXT"))+ self.assertFalse(any("Directory" in c[1] for c in fake.calls)) # no directory lookup for emails++ def test_scope_in_safe_and_full_not_personal(self):+ mod = load(Fake())+ s = "https://www.googleapis.com/auth/directory.readonly"+ self.assertIn(s, mod.SCOPES_FULL)+ self.assertIn(s, mod.SCOPES_SAFE)+ self.assertNotIn(s, mod.SCOPES_PERSONAL)+ self.assertFalse(any("admin.directory" in x for x in mod.SCOPES_FULL + mod.SCOPES_SAFE))+++if __name__ == "__main__":+ unittest.main(verbosity=2)