OfficialVerifiedEmail

Pending Google approval. Google is still reviewing Houston's access to Gmail. Until Google approves it, you will see a Google hasn't verified this app screen while connecting with Google: select Advanced, then continue to Houston.

Gmail

Give agents the context they need from your Gmail inbox. You choose what they may do in three separate areas:

  • Messages
    • Read: search mail with Gmail's own search syntax, read whole conversations, download attachments and see your labels.
    • Organize: also archive, mark read or unread, apply labels, and create, rename and delete labels.
  • Drafts
    • Create: prepare new drafts and replies (with attachments) for you to review and send from Gmail.
    • Manage: also read, edit and delete your drafts.
  • Sending
    • Send: send new mail and replies (with attachments) from your address.

Each area can be set to None. Agents can never delete mail or move it to Trash or Spam. Deleted drafts are removed permanently. Gmail stores drafts as messages, so Messages at Read can also show your drafts. Replying in a conversation needs Messages at Read or above, so the agent can read the message it answers.

Setup instructions

Connect Gmail

  1. Choose a level for each row of Access:

    • Messages: Read lets agents search and read your mail, threads, attachments and labels. Organize also lets them archive, mark messages read or unread, apply labels, and create, rename and delete labels.
    • Drafts: Create lets agents write new drafts. You review and send them yourself in Gmail. Manage also lets them read, edit and delete your drafts. Google's permission for Manage also mentions sending drafts; Houston never sends a draft.
    • Sending: Send lets agents send new mail and replies from your address.

    Leave a row on None to turn it off. Gmail stores drafts as messages, so Messages at Read can also show your drafts.

  2. Choose an available sign-in option and select Connect Gmail.

  3. Choose your Google account and approve access. With Connect with Google, if Google shows a checkbox per permission, tick them all: Houston refuses a partial grant. You will return to Houston.

Houston calls Gmail only when your agent asks it to and never syncs your mailbox in the background. Connect with Google asks only for the permissions of the levels you choose, so Google itself refuses anything beyond them, and it does not grant access to your other Google services. Houston never deletes messages or moves them to Trash or Spam; deleted drafts are removed for good.

If you connect with Composio, it requires full Gmail access. Houston limits its use to the access level you select.

Advanced
  • To change Access, edit the connection and connect the same mailbox again. Add a separate connection for a different mailbox.
  • Agents send from your account's own address. To reply in a conversation, they need Messages at Read or above.
  • Removing a connection stops Houston from using it. To revoke access in Google too, remove Composio (or Houston for direct sign-in) from your Google Account's connections. This also affects other connections using that app.
  • If your Google Workspace blocks the connection, ask your administrator to allow the app shown on Google's consent screen.

Files

  • connector.luau
    -- Gmail API v1 for the connected mailbox. Arguments and results keep Google's native
    -- field names; reads add decoded bodies and writes build MIME so callers never handle base64.
    local API = "https://gmail.googleapis.com/gmail/v1/users/me"
    local UPLOAD = "https://gmail.googleapis.com/upload/gmail/v1/users/me"
    
    -- Request layer shared verbatim by the Google connectors (tools/validate checks they match).
    type Options = {[string]: any}
    type Endpoint = {method: string, path: string, access: string?, query: {string}?, body: boolean?, defaults: Options?, list: string?, required: {[string]: string}?, help: string}
    
    local function text(value: any, field: string): string
    	assert(type(value) == "string" and value ~= "", field .. " must be a nonempty string")
    	return value
    end
    
    local function options(value: any): Options
    	if value == nil then return {} end
    	assert(type(value) == "table", "opts must be an object")
    	for key in value do assert(type(key) == "string", "opts must have named fields") end
    	return table.clone(value)
    end
    
    -- Moves the named fields from args into a query string; arrays repeat the key.
    local function query(args: Options, names: {string}): string
    	local parts: {string} = {}
    	for _, name in names do
    		local value = args[name]
    		args[name] = nil
    		for key, item in (if type(value) == "table" then value else {value}) do
    			assert(type(key) == "number" and (type(item) == "string" or type(item) == "number" or type(item) == "boolean"), name .. " must be a string, number, boolean or an array of them")
    			table.insert(parts, url.encode(name) .. "=" .. url.encode(item))
    		end
    	end
    	return if #parts > 0 then "?" .. table.concat(parts, "&") else ""
    end
    
    -- Older APIs name the reason in errors[], newer ones in an ErrorInfo detail.
    local function reasonOf(problem: any): string?
    	for _, list in {problem.errors, problem.details} :: {any} do
    		if type(list) == "table" then
    			for _, item in list do
    				if type(item) == "table" and type(item.reason) == "string" then return item.reason end
    			end
    		end
    	end
    	return nil
    end
    
    local function fail(operation: string, response: HttpResponse): never
    	local ok, decoded = pcall(json.decode, await(response.body:readPrefix(4096)))
    	local problem = if ok and type(decoded) == "table" and type(decoded.error) == "table" then decoded.error else {}
    	local reason = reasonOf(problem)
    	local message = "Google HTTP " .. tostring(response.statusCode)
    	if type(problem.status) == "string" then message ..= " (" .. problem.status .. ")" end
    	if type(problem.message) == "string" then message ..= ": " .. string.sub(problem.message, 1, 600) end
    	if reason then message ..= " [" .. reason .. "]" end
    	local retry = response.headers["retry-after"]
    	if retry and retry[1] then message ..= "; Retry-After: " .. retry[1] end
    	local limited = reason ~= nil and string.find(string.lower(reason), "ratelimitexceeded", 1, true) ~= nil
    	return houston.fail({operation = operation, layer = "upstream", upstream_status = response.statusCode,
    		retryable = response.statusCode == 429 or response.statusCode >= 500 or limited, message = message})
    end
    
    local function decode(operation: string, response: HttpResponse): any
    	if response.statusCode < 200 or response.statusCode >= 300 then fail(operation, response) end
    	local raw = await(response.body:readAll())
    	if raw == "" then return {success = true} end
    	local ok, value = pcall(json.decode, raw)
    	if not ok or type(value) ~= "table" or not string.match(raw, "^%s*{") then
    		houston.fail({operation = operation, layer = "upstream", upstream_status = response.statusCode,
    			retryable = false, message = "Google returned an invalid JSON object"})
    	end
    	return value
    end
    
    local function call(operation: string, method: string, href: string, body: any?): any
    	return decode(operation, await(http.request({method = method, url = href,
    		headers = if body ~= nil then {["Content-Type"] = {"application/json"}} else nil,
    		body = if body ~= nil then json.encode(body) else nil})))
    end
    
    -- Accepts a docs.google.com editor URL in place of its file ID; published and responder links (/d/e/...) carry no ID.
    local function docsId(value: any, product: string, field: string): any
    	if type(value) ~= "string" then return value end
    	local rest = string.match(value, "^https://docs%.google%.com/" .. product .. "/d/(.*)$")
    		or string.match(value, "^https://docs%.google%.com/" .. product .. "/u/%d+/d/(.*)$")
    		or string.match(value, "^https://docs%.google%.com/a/[^/]+/" .. product .. "/d/(.*)$")
    	local id: string = if rest then string.match(rest, "^[^/?#]*") or "" else value
    	assert(string.match(id, "^[%w_%-]+$") and id ~= "e", field .. " must be an ID or its https://docs.google.com/" .. product .. "/d/<id> URL")
    	return id
    end
    
    -- Moves {placeholders} and declared query fields from args into the URL; remaining fields form the JSON body.
    local function target(name: string, endpoint: Endpoint, args: Options): string
    	local defaults: Options = endpoint.defaults or {}
    	for key, value in defaults do
    		if args[key] == nil then args[key] = value end
    	end
    	local required: {[string]: string} = endpoint.required or {}
    	for field, kind in required do
    		local value = args[field]
    		assert(if kind == "array" then type(value) == "table" and value[1] ~= nil elseif kind == "string" then type(value) == "string" and value ~= "" elseif kind == "object" then type(value) == "table" and next(value) ~= nil and value[1] == nil else false,
    			name .. " requires " .. field .. " as a nonempty " .. kind)
    	end
    	local path = string.gsub(endpoint.path, "{(%w+)}", function(field: string)
    		local value = url.segment(text(args[field], field), field)
    		args[field] = nil
    		return value
    	end)
    	path ..= query(args, endpoint.query or {})
    	if not endpoint.body then assert(next(args) == nil, name .. " received an unknown option") end
    	return API .. path
    end
    
    local function invoke(name: string, endpoint: Endpoint, input: any): any
    	local args = options(input)
    	local result = call(name, endpoint.method, target(name, endpoint, args), if endpoint.body then args else nil)
    	if endpoint.list and result[endpoint.list] == nil then result[endpoint.list] = json.decode("[]") end
    	return result
    end
    
    local exports: {[string]: any} = {}
    local help: {[string]: string} = {}
    
    -- Exposes an operation when the connection allows the access it needs, if any.
    local function export(name: string, access: string?, fn: (any) -> any, doc: string)
    	if access == nil or houston.allows(access) then
    		exports[name], help[name] = fn, doc
    	end
    end
    
    local function exportEndpoints(endpoints: {[string]: Endpoint})
    	for name, endpoint in endpoints do
    		export(name, endpoint.access, function(args: Options?): any return invoke(name, endpoint, args) end, endpoint.help)
    	end
    end
    
    -- help() introduces the API, then documents exactly the configured operations.
    local function helpWith(overview: {string}): () -> string
    	return function(): string
    		local names: {string} = {}
    		for name in help do table.insert(names, name) end
    		table.sort(names)
    		local lines = table.clone(overview)
    		for _, name in names do table.insert(lines, help[name]) end
    		return table.concat(lines, "\n")
    	end
    end
    -- End of the shared request layer.
    
    -- Keep Gmail documentation outside the shared Google transport contract.
    local reference = {
    	text = "Gmail API v1 for the connected mailbox. Call operations directly, without await, using Google's camelCase options. Access: messages " .. access.messages .. ", drafts " .. access.drafts .. ", sending " .. access.sending .. ". Only configured operations appear below. Nothing deletes or trashes mail. Use help({section='operationName'}) for a complete signature and example.",
    	functions = {} :: {[string]: any},
    	sections = {errors = "Errors report Google's HTTP status, message and reason. The connector does not retry or page automatically; Houston may retry short HTTP 429 responses."} :: {[string]: string},
    }
    if houston.allows("messages:read") or houston.allows("drafts:manage") then
    	reference.sections.pagination = "Lists return one page. Pass nextPageToken as pageToken until it is absent; resultSizeEstimate is approximate. Use small pages."
    		.. (if houston.allows("messages:read") then " Message lists carry IDs only: fetch details with getMessages or getThread; use metadata reads when scanning mail." else " Draft lists carry IDs only: fetch content with getDraft.")
    end
    if houston.allows("messages:organize") or houston.allows("drafts:create") or houston.allows("sending:send") then
    	reference.sections.errors ..= " A failed or timed-out write may already have succeeded. Inspect the outcome before repeating."
    end
    local STRING = {type = "string"}
    local ID = {type = "string", minLength = 1}
    local STRINGS = {type = "array", items = ID}
    local HISTORY_TYPE: Options = {type = "string", enum = {"messageAdded", "messageDeleted", "labelAdded", "labelRemoved"}}
    local INTEGER = {type = "integer"}
    local function object(properties: Options, required: {string}?, extra: boolean?): Options
    	return {type = "object", properties = properties, required = if required and #required > 0 then required else json.decode("[]"), additionalProperties = extra == true}
    end
    local function input(properties: Options, required: {string}, example: Options): Options
    	local schema = object(properties, required)
    	schema.examples = {example}
    	return schema
    end
    local messageRef = object({id = ID, threadId = ID, labelIds = STRINGS}, {"id"}, true)
    local label = object({id = ID, name = STRING, type = STRING, labelListVisibility = STRING, messageListVisibility = STRING,
    	messagesTotal = INTEGER, messagesUnread = INTEGER, threadsTotal = INTEGER, threadsUnread = INTEGER,
    	color = object({textColor = STRING, backgroundColor = STRING}, nil, true)}, {"id"}, true)
    local draftRef = object({id = ID, message = messageRef}, {"id"}, true)
    local SUCCESS = object({success = {const = true}}, {"success"})
    local PAGE = {type = "integer", minimum = 1, maximum = 500, default = 100}
    local searchProperties = {q = {type = "string", description = "Gmail search syntax, e.g. from:[email protected] has:attachment."},
    	labelIds = {oneOf = {STRING, STRINGS}}, maxResults = PAGE, pageToken = STRING, includeSpamTrash = {type = "boolean", default = false}}
    local function pageSchema(key: string, item: Options): Options
    	return object({[key] = {type = "array", items = item}, nextPageToken = STRING, resultSizeEstimate = INTEGER}, {key}, true)
    end
    local labelChanges = {id = ID, addLabelIds = {type = "array", items = {type = "string", minLength = 1, ["not"] = {enum = {"TRASH", "SPAM"}}}}, removeLabelIds = STRINGS}
    local labelFields = {name = ID, labelListVisibility = {type = "string", enum = {"labelShow", "labelShowIfUnread", "labelHide"}},
    	messageListVisibility = {type = "string", enum = {"show", "hide"}}, color = object({textColor = STRING, backgroundColor = STRING}, nil, true)}
    
    type DocumentedEndpoint = Endpoint & {inputSchema: Options, outputSchema: Options}
    local SEARCH = {"q", "labelIds", "maxResults", "pageToken", "includeSpamTrash"}
    local endpoints: {[string]: DocumentedEndpoint} = {
    	listLabels = {method = "GET", path = "/labels", access = "messages:read", list = "labels",
    		help = "Lists all mailbox labels. System labels include INBOX, SENT, DRAFT, SPAM, TRASH, UNREAD, STARRED and IMPORTANT.",
    		inputSchema = input({}, {}, {}), outputSchema = object({labels = {type = "array", items = label}}, {"labels"})},
    	getLabel = {method = "GET", path = "/labels/{id}", access = "messages:read",
    		help = "Reads one label, including message and thread counts.",
    		inputSchema = input({id = ID}, {"id"}, {id = "INBOX"}), outputSchema = label},
    	listMessages = {method = "GET", path = "/messages", access = "messages:read", list = "messages", query = SEARCH,
    		help = "Searches one page of message IDs and thread IDs. Fetch bodies with getMessages. Pass nextPageToken back as pageToken; resultSizeEstimate is approximate.",
    		inputSchema = input(searchProperties, {}, {q = "is:unread in:inbox", maxResults = 20}), outputSchema = pageSchema("messages", messageRef)},
    	listThreads = {method = "GET", path = "/threads", access = "messages:read", list = "threads", query = SEARCH,
    		help = "Searches one page of conversations, returning id, snippet and historyId, without messages. Read a conversation with getThread. Pass nextPageToken as pageToken.",
    		inputSchema = input(searchProperties, {}, {q = "from:[email protected]", maxResults = 20}), outputSchema = pageSchema("threads", object({id = ID, snippet = STRING, historyId = STRING}, {"id"}, true))},
    	listDrafts = {method = "GET", path = "/drafts", access = "drafts:manage", list = "drafts", query = {"q", "maxResults", "pageToken", "includeSpamTrash"},
    		help = "Lists one page of draft IDs and message IDs, without content. Read content with getDraft; pass nextPageToken as pageToken.",
    		inputSchema = input({q = STRING, maxResults = PAGE, pageToken = STRING, includeSpamTrash = {type = "boolean", default = false}}, {}, {maxResults = 20}), outputSchema = pageSchema("drafts", draftRef)},
    	listHistory = {method = "GET", path = "/history", access = "messages:read", list = "history", query = {"startHistoryId", "labelId", "historyTypes", "maxResults", "pageToken"},
    		help = "Lists changes after startHistoryId, in chronological order. Pass nextPageToken as pageToken. An expired history ID returns HTTP 404: resync with listMessages. Keep historyId as a string.",
    		inputSchema = input({startHistoryId = ID, labelId = ID, historyTypes = {oneOf = {HISTORY_TYPE, {type = "array", items = HISTORY_TYPE}}}, maxResults = PAGE, pageToken = STRING}, {"startHistoryId"}, {startHistoryId = "12345", maxResults = 20}),
    		outputSchema = object({history = {type = "array", items = object({id = STRING, messages = {type = "array", items = messageRef}, messagesAdded = {type = "array", items = object({message = messageRef})}, messagesDeleted = {type = "array", items = object({message = messageRef})}, labelsAdded = {type = "array", items = object({message = messageRef, labelIds = STRINGS})}, labelsRemoved = {type = "array", items = object({message = messageRef, labelIds = STRINGS})}}, nil, true)}, historyId = STRING, nextPageToken = STRING}, {"history"}, true)},
    	modifyMessage = {method = "POST", path = "/messages/{id}/modify", access = "messages:organize", body = true,
    		help = "Changes labels on one message, preserving other labels. Remove UNREAD to mark read, add UNREAD to mark unread, or remove INBOX to archive. Adding TRASH or SPAM is refused. At most 100 labels per add/remove list.",
    		inputSchema = input(labelChanges, {"id"}, {id = "m1", removeLabelIds = {"UNREAD"}}), outputSchema = messageRef},
    	batchModifyMessages = {method = "POST", path = "/messages/batchModify", access = "messages:organize", body = true,
    		help = "Changes labels on up to 1000 message IDs. Remove UNREAD to mark read or INBOX to archive. Adding TRASH or SPAM is refused. An interrupted batch may already have changed mail; inspect before replaying.",
    		inputSchema = input({ids = {type = "array", items = ID, minItems = 1, maxItems = 1000}, addLabelIds = labelChanges.addLabelIds, removeLabelIds = STRINGS}, {"ids"}, {ids = {"m1", "m2"}, removeLabelIds = {"UNREAD"}}), outputSchema = SUCCESS},
    	modifyThread = {method = "POST", path = "/threads/{id}/modify", access = "messages:organize", body = true,
    		help = "Changes labels on every message in a conversation. Remove INBOX to archive or UNREAD to mark read. Adding TRASH or SPAM is refused. At most 100 labels per add/remove list. Returns Gmail's raw thread with raw messages, not decoded bodies.",
    		inputSchema = input(labelChanges, {"id"}, {id = "t1", removeLabelIds = {"INBOX"}}), outputSchema = object({id = ID, historyId = STRING, messages = {type = "array", items = messageRef}}, {"id"}, true)},
    	createLabel = {method = "POST", path = "/labels", access = "messages:organize", body = true,
    		help = "Creates a mailbox label. Use Parent/Child names to nest labels. Colors must be from Gmail's supported palette.",
    		inputSchema = input(labelFields, {"name"}, {name = "Projects/Launch"}), outputSchema = label},
    	updateLabel = {method = "PATCH", path = "/labels/{id}", access = "messages:organize", body = true,
    		help = "Updates specified label properties, preserving the others. Colors must be from Gmail's supported palette.",
    		inputSchema = input({id = ID, name = ID, labelListVisibility = labelFields.labelListVisibility, messageListVisibility = labelFields.messageListVisibility, color = labelFields.color}, {"id"}, {id = "Label_1", name = "Projects/Launch"}), outputSchema = label},
    	deleteLabel = {method = "DELETE", path = "/labels/{id}", access = "messages:organize",
    		help = "Deletes a user label and removes it from messages. The messages remain.",
    		inputSchema = input({id = ID}, {"id"}, {id = "Label_1"}), outputSchema = SUCCESS},
    	deleteDraft = {method = "DELETE", path = "/drafts/{id}", access = "drafts:manage",
    		help = "Permanently deletes a draft without sending it.",
    		inputSchema = input({id = ID}, {"id"}, {id = "d1"}), outputSchema = SUCCESS},
    }
    
    local function header(headers: any, name: string): string?
    	for _, item in headers or {} do
    		if type(item) == "table" and type(item.name) == "string" and string.lower(item.name) == name then return item.value end
    	end
    	return nil
    end
    
    -- Gmail returns body bytes in their original charset; non-UTF-8 text is read as Latin-1.
    local function bodyText(data: string): string
    	local value = base64.decode(data)
    	if utf8.len(value) == nil then
    		value = string.gsub(value, "[\128-\255]", function(c: string) return utf8.char(string.byte(c)) end)
    	end
    	return value
    end
    
    local function limitBody(value: string, limit: number): (string, boolean)
    	if limit == 0 or #value <= limit then return value, false end
    	value = string.sub(value, 1, limit)
    	while utf8.len(value) == nil do value = string.sub(value, 1, -2) end
    	return value, true
    end
    
    local function collect(part: any, found: Options)
    	if type(part.parts) == "table" then
    		for _, child in part.parts do collect(child, found) end
    		return
    	end
    	local body = part.body or {}
    	local disposition = string.lower(header(part.headers, "content-disposition") or "")
    	local attached = string.sub(disposition, 1, 10) == "attachment"
    	local filename = if type(part.filename) == "string" and part.filename ~= "" then part.filename else nil
    	if not filename and not attached and (part.mimeType == "text/plain" or part.mimeType == "text/html") then
    		found[part.mimeType] = found[part.mimeType] or {}
    		table.insert(found[part.mimeType], body)
    	elseif type(body.attachmentId) == "string" then
    		local contentId = header(part.headers, "content-id")
    		table.insert(found.attachments, {id = body.attachmentId, filename = filename, mimeType = part.mimeType, size = body.size,
    			inline = not attached and (contentId ~= nil or string.sub(disposition, 1, 6) == "inline"),
    			contentId = if contentId then string.match(contentId, "^%s*<?(.-)>?%s*$") else nil})
    	end
    end
    
    -- Match Unicode White_Space, as the native IMAP reader does; preserve the original text.
    local function hasContent(value: string): boolean
    	for _, point in utf8.codes(value) do
    		if not ((point >= 9 and point <= 13) or point == 32 or point == 0x85 or point == 0xA0 or point == 0x1680
    			or (point >= 0x2000 and point <= 0x200A) or point == 0x2028 or point == 0x2029 or point == 0x202F or point == 0x205F or point == 0x3000) then
    			return true
    		end
    	end
    	return false
    end
    
    -- Replaces Gmail's MIME payload with envelope fields, one decoded body and attachment metadata.
    local function message(raw: Options, limit: number, bodyFormat: string): Options
    	local payload = raw.payload or {}
    	local headers = payload.headers or json.decode("[]")
    	local found: Options = {attachments = json.decode("[]")}
    	collect(payload, found)
    	local body, unread = "", false
    	local mimeTypes: {string} = if bodyFormat == "auto" then {"text/plain", "text/html"} else {if bodyFormat == "text" then "text/plain" else "text/html"}
    	for _, mimeType in mimeTypes do
    		local parts: {Options} = found[mimeType] or {}
    		for _, part in parts do
    			local data = part.data
    			if (data == nil or data == "") and type(part.attachmentId) == "string" then
    				if houston.allows("messages:read") then
    					data = call("getMessage", "GET", API .. "/messages/" .. url.segment(raw.id, "id") .. "/attachments/" .. url.segment(part.attachmentId, "attachmentId")).data
    				else
    					unread = true
    				end
    			end
    			if type(data) == "string" then body = bodyText(data) end
    			if bodyFormat ~= "auto" or hasContent(body) then break end
    		end
    		if bodyFormat ~= "auto" or hasContent(body) then break end
    		body = ""
    	end
    	if bodyFormat == "auto" and body == "" then body = raw.snippet or "" end
    	local truncated: boolean
    	body, truncated = limitBody(body, limit)
    	truncated = truncated or unread
    	return {
    		id = raw.id, threadId = raw.threadId, labelIds = raw.labelIds or json.decode("[]"), snippet = raw.snippet,
    		historyId = raw.historyId, internalDate = raw.internalDate, sizeEstimate = raw.sizeEstimate,
    		from = header(headers, "from"), to = header(headers, "to"), cc = header(headers, "cc"), bcc = header(headers, "bcc"),
    		replyTo = header(headers, "reply-to"), subject = header(headers, "subject"), date = header(headers, "date"),
    		messageId = header(headers, "message-id"), body = body, bodyTruncated = truncated, attachments = found.attachments, headers = headers,
    	}
    end
    
    -- Moves the read options from args into a query string; returns it with the body byte limit.
    local function readQuery(args: Options): (string, number, string)
    	local limit = args.maxBodyBytes or 65536
    	assert(type(limit) == "number" and limit >= 0 and limit % 1 == 0, "maxBodyBytes must be a nonnegative integer")
    	local format = args.format or "full"
    	assert(format == "full" or format == "metadata" or format == "minimal", "format must be full, metadata or minimal")
    	local bodyFormat = if args.bodyFormat == nil then "auto" else args.bodyFormat
    	assert(bodyFormat == "auto" or bodyFormat == "text" or bodyFormat == "html", "bodyFormat must be auto, text or html")
    	args.maxBodyBytes, args.format, args.bodyFormat = nil, format, nil
    	return query(args, {"format", "metadataHeaders"}), limit, bodyFormat
    end
    
    local function read(name: string, collection: string, input: any): (any, number, string)
    	local args = options(input)
    	local id = text(args.id, "id")
    	args.id = nil
    	local suffix, limit, bodyFormat = readQuery(args)
    	assert(next(args) == nil, name .. " received an unknown option")
    	return call(name, "GET", API .. "/" .. collection .. "/" .. url.segment(id, "id") .. suffix), limit, bodyFormat
    end
    
    local function getMessages(input: any): {Options}
    	local args = options(input)
    	local ids = args.ids
    	assert(type(ids) == "table" and #ids >= 1 and #ids <= 100, "ids must be an array of 1 to 100 message IDs")
    	local segments: {string} = {}
    	for i = 1, #ids do
    		local field = "ids[" .. tostring(i) .. "]"
    		segments[i] = url.segment(text(ids[i], field), field)
    	end
    	args.ids = nil
    	local suffix, limit, bodyFormat = readQuery(args)
    	assert(next(args) == nil, "getMessages received an unknown option")
    	local out: {Options} = json.decode("[]")
    	-- Bounded concurrency stays within Gmail's per-user rate limits.
    	for first = 1, #ids, 10 do
    		local pending = {}
    		for i = first, math.min(first + 9, #ids) do
    			table.insert(pending, http.request({method = "GET", url = API .. "/messages/" .. segments[i] .. suffix}))
    		end
    		local responses = awaitAll(pending)
    		for i = 1, responses.n do table.insert(out, message(decode("getMessages", responses[i]), limit, bodyFormat)) end
    	end
    	return out
    end
    
    -- Gmail returns {"size": n, "data": "<base64url>"}; decode the data string as it streams so
    -- large attachments never sit in memory.
    local function getAttachment(input: any): Options
    	local args = options(input)
    	local messageId, attachmentId, path = text(args.messageId, "messageId"), text(args.attachmentId, "attachmentId"), text(args.path, "path")
    	args.messageId, args.attachmentId, args.path = nil, nil, nil
    	assert(next(args) == nil, "getAttachment received an unknown option")
    	local response = await(http.request({method = "GET", url = API .. "/messages/" .. url.segment(messageId, "messageId") .. "/attachments/" .. url.segment(attachmentId, "attachmentId")}))
    	if response.statusCode < 200 or response.statusCode >= 300 then fail("getAttachment", response) end
    	local output = fs.open(path, "w")
    	local pending, started, finished = "", false, false
    	while not finished do
    		local chunk = await(response.body:read(1048576))
    		if chunk.done then break end
    		pending ..= chunk.data
    		if not started then
    			local _, last = string.find(pending, '"data"%s*:%s*"')
    			if last then started, pending = true, string.sub(pending, last + 1) end
    		end
    		if started then
    			local close = string.find(pending, '"', 1, true)
    			finished = close ~= nil
    			local usable = if close then close - 1 else #pending - #pending % 4
    			await(output:write(base64.decode(string.sub(pending, 1, usable))))
    			pending = string.sub(pending, usable + 1)
    		end
    	end
    	response.body:close()
    	if not finished then
    		output:cancel()
    		pcall(function() await(output:close()) end)
    		houston.fail({operation = "getAttachment", layer = "upstream", upstream_status = response.statusCode, retryable = false, message = "Google returned no attachment data"})
    	end
    	await(output:close())
    	return {path = path, url = await(fs.signedGetUrl(path)), size = await(fs.stat(path)).size}
    end
    
    local EMAIL = "[%w%.%_%%%+%-]+@[%w%.%-]+"
    
    local function line(name: string, value: string?): string
    	if value == nil then return "" end
    	assert(not string.find(value, "[\r\n]"), name .. " must not contain line breaks")
    	return name .. ": " .. value .. "\r\n"
    end
    
    local function addresses(value: any, field: string): string?
    	if value == nil then return nil end
    	local list = if type(value) == "string" then {value} else value
    	assert(type(list) == "table" and #list > 0, field .. " must be an address or an array of addresses")
    	for _, item in list do assert(type(item) == "string" and item ~= "", field .. " must contain address strings") end
    	return table.concat(list, ", ")
    end
    
    -- Appends one base64-encoded MIME part.
    local function part(out: {string}, contentType: string, data: string, disposition: string?)
    	table.insert(out, line("Content-Type", contentType) .. line("Content-Disposition", disposition) .. "Content-Transfer-Encoding: base64\r\n\r\n")
    	table.insert(out, base64.encode(data, {wrap = true}))
    end
    
    -- Returns the opening, separating and closing lines of a multipart body.
    -- Base64 parts never contain "=_", so these fixed boundaries cannot collide with content.
    local function multipart(subtype: string): (string, string, string)
    	local boundary = "=_houston_" .. subtype
    	return "Content-Type: multipart/" .. subtype .. "; boundary=\"" .. boundary .. "\"\r\n\r\n--" .. boundary .. "\r\n",
    		"\r\n--" .. boundary .. "\r\n", "\r\n--" .. boundary .. "--\r\n"
    end
    
    local function attachment(out: {string}, item: any)
    	local spec = if type(item) == "string" then {path = item} else item
    	assert(type(spec) == "table", "attachments must be paths or {path, filename?, mimeType?}")
    	local path = text(spec.path, "attachment path")
    	local filename = text(spec.filename or string.match(path, "[^/]+$"), "attachment filename")
    	local file = fs.open(path, "r")
    	local data = await(file:readAll())
    	await(file:close())
    	local name = if string.match(filename, "^[%w%.%-_ ()]+$") then "filename=\"" .. filename .. "\"" else "filename*=UTF-8''" .. url.encode(filename)
    	part(out, text(spec.mimeType or "application/octet-stream", "attachment mimeType"), data, "attachment; " .. name)
    end
    
    -- The mailbox's own address, which a reply to all leaves out. Google sign-in grants only narrow
    -- Gmail scopes, none of which reads the profile, so it asks the userinfo endpoint instead.
    local function ownAddress(name: string): string
    	if auth.method == "oauth" then return call(name, "GET", "https://www.googleapis.com/oauth2/v2/userinfo").email or "" end
    	return call(name, "GET", API .. "/profile").emailAddress or ""
    end
    
    -- Builds the MIME message as pieces and returns them with the thread to post into. inReplyTo
    -- threads a reply to that message: recipients, subject and references default from the original.
    local function compose(name: string, args: Options): ({string}, string?)
    	local known = {}
    	for _, field in {"to", "cc", "bcc", "replyTo", "from", "subject", "text", "html", "attachments", "inReplyTo", "replyAll"} do known[field] = true end
    	for key in args do assert(known[key], name .. " received an unknown option " .. key) end
    	local to, cc, subject, threadId, references, inReplyTo = addresses(args.to, "to"), addresses(args.cc, "cc"), args.subject, nil, nil, nil
    	if args.inReplyTo ~= nil then
    		assert(houston.allows("messages:read"), name .. " with inReplyTo needs Messages access set to Read, to read the message it answers")
    		local metadata = {format = "metadata", metadataHeaders = {"From", "Reply-To", "To", "Cc", "Subject", "Message-ID", "References"}}
    		local original = call(name, "GET", API .. "/messages/" .. url.segment(text(args.inReplyTo, "inReplyTo"), "inReplyTo") .. query(metadata, {"format", "metadataHeaders"}))
    		local headers = original.payload and original.payload.headers
    		threadId, inReplyTo = original.threadId, header(headers, "message-id")
    		references = if inReplyTo then table.concat({header(headers, "references") or "", inReplyTo}, " ") else nil
    		to = to or header(headers, "reply-to") or header(headers, "from")
    		if subject == nil then
    			local previous = header(headers, "subject") or ""
    			subject = if string.match(string.lower(previous), "^re:") then previous else "Re: " .. previous
    		end
    		if args.replyAll == true and cc == nil then
    			local seen = {[string.lower(ownAddress(name))] = true}
    			for email in string.gmatch(string.lower(to or ""), EMAIL) do seen[email] = true end
    			local copied: {string} = {}
    			for email in string.gmatch(string.lower((header(headers, "to") or "") .. "," .. (header(headers, "cc") or "")), EMAIL) do
    				if not seen[email] then seen[email], copied[#copied + 1] = true, email end
    			end
    			cc = if #copied > 0 then table.concat(copied, ", ") else nil
    		end
    	end
    	assert(to, name .. " requires to (or inReplyTo)")
    	assert(args.text ~= nil or args.html ~= nil, name .. " requires text or html")
    	local attachments = if args.attachments == nil then {} else args.attachments
    	assert(type(attachments) == "table", "attachments must be an array")
    	if subject ~= nil and string.find(subject, "[\128-\255]") then subject = "=?UTF-8?B?" .. base64.encode(subject) .. "?=" end
    	local out = {line("From", args.from) .. line("To", to) .. line("Cc", cc) .. line("Bcc", addresses(args.bcc, "bcc"))
    		.. line("Reply-To", addresses(args.replyTo, "replyTo")) .. line("Subject", subject) .. line("In-Reply-To", inReplyTo)
    		.. line("References", references) .. "MIME-Version: 1.0\r\n"}
    	local open, between, close = multipart("mixed")
    	if #attachments > 0 then table.insert(out, open) end
    	if args.text ~= nil and args.html ~= nil then
    		local first, second, last = multipart("alternative")
    		table.insert(out, first)
    		part(out, "text/plain; charset=UTF-8", text(args.text, "text"))
    		table.insert(out, second)
    		part(out, "text/html; charset=UTF-8", text(args.html, "html"))
    		table.insert(out, last)
    	elseif args.html ~= nil then
    		part(out, "text/html; charset=UTF-8", text(args.html, "html"))
    	else
    		part(out, "text/plain; charset=UTF-8", text(args.text, "text"))
    	end
    	if #attachments > 0 then
    		for _, item in attachments do
    			table.insert(out, between)
    			attachment(out, item)
    		end
    		table.insert(out, close)
    	end
    	return out, threadId
    end
    
    -- Uploads the message as message/rfc822 beside Gmail's JSON metadata, so attachments are
    -- base64-encoded only once. Drafts nest the thread under message.
    local function submit(name: string, method: string, path: string, args: Options, draft: boolean): any
    	local mime, threadId = compose(name, args)
    	local metadata = if draft then {message = {threadId = threadId}} else {threadId = threadId}
    	local body = {"--=_houston_upload\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n" .. json.encode(metadata)
    		.. "\r\n--=_houston_upload\r\nContent-Type: message/rfc822\r\n\r\n"}
    	table.move(mime, 1, #mime, 2, body)
    	table.insert(body, "\r\n--=_houston_upload--\r\n")
    	return decode(name, await(http.request({method = method, url = UPLOAD .. path .. "?uploadType=multipart",
    		headers = {["Content-Type"] = {"multipart/related; boundary=\"=_houston_upload\""}}, body = table.concat(body)})))
    end
    
    for name, endpoint in endpoints do
    	if endpoint.access == nil or houston.allows(endpoint.access) then
    		-- Body fields pass through to Gmail; query-only endpoints reject unknown options.
    		endpoint.inputSchema.additionalProperties = endpoint.body == true
    		reference.functions[name] = {description = endpoint.help, inputSchema = endpoint.inputSchema,
    			outputSchema = endpoint.outputSchema, annotations = {readOnlyHint = endpoint.method == "GET", openWorldHint = true}}
    		exports[name] = function(args: Options?): any return invoke(name, endpoint, args) end
    	end
    end
    
    -- Gmail moves a message that gains one of these labels to Trash or Spam, where it is deleted
    -- after 30 days. The proxy cannot read request bodies, so the modify operations refuse them here.
    for _, name in {"modifyMessage", "batchModifyMessages", "modifyThread"} do
    	local modify = exports[name]
    	if modify then
    		exports[name] = function(input: any): any
    			local added: {any} = if type(input) == "table" and type(input.addLabelIds) == "table" then input.addLabelIds else {}
    			for _, label in added do
    				assert(string.upper(tostring(label)) ~= "TRASH" and string.upper(tostring(label)) ~= "SPAM", name .. " cannot add " .. tostring(label) .. ": nothing moves mail to Trash or Spam")
    			end
    			return modify(input)
    		end
    	end
    end
    
    local READ_OPTIONS = "bodyFormat auto (default) chooses the first nonblank decoded plain text, HTML, then snippet; text or html selects only that format, preserving whitespace and returning an empty string if missing. format full (default) decodes the body, metadata returns headers, minimal returns identifiers/labels. metadataHeaders limits metadata headers. maxBodyBytes caps each selected body (default 65536, 0 for no cap), preserving UTF-8 and setting bodyTruncated. A body cap does not bound the whole result; use small batches."
    local readProperties = {id = ID, format = {type = "string", enum = {"full", "metadata", "minimal"}, default = "full"},
    	metadataHeaders = {oneOf = {STRING, STRINGS}}, maxBodyBytes = {type = "integer", minimum = 0, default = 65536},
    	bodyFormat = {type = "string", enum = {"auto", "text", "html"}, default = "auto"}}
    local messageSchema = object({id = ID, threadId = ID, labelIds = STRINGS, snippet = STRING, historyId = STRING,
    	internalDate = {type = "string", description = "Epoch milliseconds, preserved as Google's string."}, sizeEstimate = INTEGER,
    	from = STRING, to = STRING, cc = STRING, bcc = STRING, replyTo = STRING, subject = STRING, date = STRING, messageId = STRING,
    	body = STRING, bodyTruncated = {type = "boolean"},
    	attachments = {type = "array", items = object({id = ID, filename = STRING, mimeType = STRING, size = INTEGER, inline = {type = "boolean"}, contentId = STRING}, {"id", "inline"})},
    	headers = {oneOf = {{type = "array", items = object({name = STRING, value = STRING}, {"name", "value"})}, {type = "object", maxProperties = 0}} :: {Options}}}, {"labelIds", "body", "bodyTruncated", "attachments", "headers"})
    if houston.allows("messages:read") or houston.allows("drafts:manage") then reference.sections.reading = READ_OPTIONS end
    
    if houston.allows("messages:read") then
    	reference.functions.getMessage = {
    		description = "Reads one message with decoded body, envelope headers and attachment metadata; it does not return Gmail's MIME payload. " .. READ_OPTIONS,
    		inputSchema = input(readProperties, {"id"}, {id = "m1", maxBodyBytes = 4096}), outputSchema = messageSchema,
    		annotations = {readOnlyHint = true, openWorldHint = true},
    	}
    	function exports.getMessage(input: any): Options
    		local raw, limit, bodyFormat = read("getMessage", "messages", input)
    		return message(raw, limit, bodyFormat)
    	end
    
    	local batchReadProperties: Options = table.clone(readProperties)
    	batchReadProperties.id = nil
    	batchReadProperties.ids = {type = "array", items = ID, minItems = 1, maxItems = 100}
    	reference.functions.getMessages = {
    		description = "Reads 1 to 100 messages in input ID order. Returns an array of {id, threadId, labelIds, snippet?, historyId?, internalDate?, sizeEstimate?, from?, to?, cc?, bcc?, replyTo?, subject?, date?, messageId?, body, bodyTruncated, attachments={{id, filename?, mimeType?, size?, inline, contentId?}}, headers={{name,value}}}. Batches run with at most 10 requests in flight. Use metadata to scan cheaply. " .. READ_OPTIONS,
    		inputSchema = input(batchReadProperties, {"ids"}, {ids = {"m1", "m2"}, format = "metadata", metadataHeaders = {"From", "Subject"}}),
    		annotations = {readOnlyHint = true, openWorldHint = true},
    	}
    	exports.getMessages = getMessages
    
    	reference.functions.getThread = {
    		description = "Reads every message in a conversation, oldest first. Each message has the decoded shape described by getMessage. " .. READ_OPTIONS,
    		inputSchema = input(readProperties, {"id"}, {id = "t1", maxBodyBytes = 4096}),
    		outputSchema = object({id = ID, historyId = STRING, messages = {type = "array", items = messageSchema}}, {"messages"}, true),
    		annotations = {readOnlyHint = true, openWorldHint = true},
    	}
    	function exports.getThread(input: any): Options
    		local thread, limit, bodyFormat = read("getThread", "threads", input)
    		local messages: {Options} = json.decode("[]")
    		for _, raw in thread.messages or {} do table.insert(messages, message(raw, limit, bodyFormat)) end
    		thread.messages = messages
    		return thread
    	end
    
    	reference.functions.getAttachment = {
    		description = "Streams an attachment into a session file. attachmentId comes from a message's attachments[].id. Returns path, signed Houston download url and byte size; never inline attachment bytes.",
    		inputSchema = input({messageId = ID, attachmentId = ID, path = ID}, {"messageId", "attachmentId", "path"}, {messageId = "m1", attachmentId = "a1", path = "files/report.pdf"}),
    		outputSchema = object({path = STRING, url = STRING, size = INTEGER}, {"path", "url", "size"}),
    		annotations = {readOnlyHint = true, openWorldHint = true},
    	}
    	exports.getAttachment = getAttachment
    
    	reference.functions.listMailFolders = {
    		description = "Lists every mailbox label as an array of {id, name}, sorted by ID. Takes no arguments.",
    		args = {}, inputSchema = input({}, {}, {}), annotations = {readOnlyHint = true, openWorldHint = true},
    	}
    	function exports.listMailFolders(...: any): {{id: string, name: string}}
    		assert(select("#", ...) == 0, "listMailFolders takes no arguments")
    		local labels = call("listMailFolders", "GET", API .. "/labels").labels or {}
    		local folders: {{id: string, name: string}} = json.decode("[]")
    		local seen = {}
    		for _, label in labels do
    			if type(label) ~= "table" or type(label.id) ~= "string" or label.id == "" or type(label.name) ~= "string" or seen[label.id] then
    				houston.fail({operation = "listMailFolders", layer = "upstream", retryable = false, message = "Google returned invalid label metadata"})
    			end
    			seen[label.id] = true
    			table.insert(folders, {id = label.id, name = label.name})
    		end
    		table.sort(folders, function(a: any, b: any) return a.id < b.id end)
    		return folders
    	end
    end
    
    if houston.allows("drafts:manage") then
    	reference.functions.getDraft = {
    		description = "Reads a draft with its message decoded like getMessage. " .. READ_OPTIONS .. " Long bodies stored as attachments require Messages Read access. Without it, bodyTruncated is true; auto can fall back to the snippet. Never replace a draft with incomplete content.",
    		inputSchema = input(readProperties, {"id"}, {id = "d1", maxBodyBytes = 4096}),
    		outputSchema = object({id = ID, message = messageSchema}, {"message"}, true), annotations = {readOnlyHint = true, openWorldHint = true},
    	}
    	function exports.getDraft(input: any): Options
    		local draft, limit, bodyFormat = read("getDraft", "drafts", input)
    		draft.message = message(draft.message or {}, limit, bodyFormat)
    		return draft
    	end
    end
    
    local COMPOSE = "Builds MIME from plain fields; do not encode anything yourself. to, cc, bcc and replyTo accept an address or an array. from must be a Gmail send-as address; otherwise Gmail replaces it with the mailbox address, also the default. Supply to or inReplyTo, and nonempty text and/or html. Attachments read session files. Keep the encoded message under 8 MiB (about 5 MiB of attachments); share larger files from Drive. inReplyTo is a Gmail message ID and requires Messages Read: recipients, Re: subject and threading headers default from the original. replyAll=true also copies its To/Cc except yourself; explicit cc overrides that default."
    local addressSchema = {oneOf = {ID, {type = "array", items = ID, minItems = 1}} :: {Options}}
    local composeProperties = {to = addressSchema, cc = addressSchema, bcc = addressSchema, replyTo = addressSchema, from = STRING,
    	subject = STRING, text = ID, html = ID, inReplyTo = ID, replyAll = {type = "boolean", default = false},
    	attachments = {type = "array", items = {oneOf = {ID, object({path = ID, filename = ID, mimeType = ID}, {"path"}, true)}}}}
    local function composeInput(update: boolean): Options
    	local properties = table.clone(composeProperties)
    	local example: Options = {to = "[email protected]", subject = "Launch plan", text = "Please review the launch plan."}
    	if update then properties.id, example.id = ID, "d1" end
    	local schema = input(properties, if update then {"id"} else {}, example)
    	schema.allOf = {{anyOf = {{required = {"to"}}, {required = {"inReplyTo"}}}}, {anyOf = {{required = {"text"}}, {required = {"html"}}}}}
    	return schema
    end
    if houston.allows("drafts:create") or houston.allows("sending:send") then reference.sections.composing = COMPOSE end
    
    if houston.allows("sending:send") then
    	reference.functions.sendMessage = {
    		description = "Sends a new message or reply immediately. " .. COMPOSE .. " A timeout may still have sent mail: " .. (if houston.allows("messages:read") then "check SENT before retrying." else "this connection cannot read SENT; tell the person before retrying."),
    		inputSchema = composeInput(false), outputSchema = messageRef, annotations = {readOnlyHint = false, openWorldHint = true},
    	}
    	function exports.sendMessage(input: any): any
    		return submit("sendMessage", "POST", "/messages/send", options(input), false)
    	end
    end
    if houston.allows("drafts:create") then
    	reference.functions.createDraft = {
    		description = "Saves a draft without sending; the person reviews and sends it from Gmail. " .. COMPOSE,
    		inputSchema = composeInput(false), outputSchema = draftRef, annotations = {readOnlyHint = false, openWorldHint = true},
    	}
    	function exports.createDraft(input: any): any
    		return submit("createDraft", "POST", "/drafts", options(input), true)
    	end
    end
    if houston.allows("drafts:manage") then
    	reference.functions.updateDraft = {
    		description = "Replaces the draft's entire content without sending. Include every recipient, body and attachment you want to retain; never copy a truncated body. " .. COMPOSE,
    		inputSchema = composeInput(true), outputSchema = draftRef, annotations = {readOnlyHint = false, openWorldHint = true},
    	}
    	function exports.updateDraft(input: any): any
    		local args = options(input)
    		local id = text(args.id, "id")
    		args.id = nil
    		return submit("updateDraft", "PUT", "/drafts/" .. url.segment(id, "id"), args, true)
    	end
    end
    
    exports.help = reference
    return exports
    
  • houston.json
    {
      "schema_version": 2,
      "name": "Gmail",
      "verification_key": "f8f70b3e9c1ae4e9b94e4cabb680db1c7ac85847721986fa399925cfdc79b980",
      "warning": "**Pending Google approval.** Google is still reviewing Houston's access to Gmail. Until Google approves it, you will see a *Google hasn't verified this app* screen while connecting with Google: select **Advanced**, then continue to Houston.",
      "files": [
        "connector.luau"
      ],
      "icon": "icon.svg",
      "access": [
        {
          "name": "messages",
          "label": "Messages",
          "description": "Read lets agents search and read your mail, threads, attachments and labels. Organize also lets them archive, mark read or unread, apply labels, and create, rename and delete labels. Agents can never delete mail.",
          "levels": [
            {
              "value": "none",
              "label": "None"
            },
            {
              "value": "read",
              "label": "Read"
            },
            {
              "value": "organize",
              "label": "Organize"
            }
          ],
          "default": "read"
        },
        {
          "name": "drafts",
          "label": "Drafts",
          "description": "Create lets agents write new drafts for you to review and send in Gmail. Manage also lets them read, edit and delete your drafts. Houston never sends a draft, even though Google's permission for Manage mentions sending.",
          "levels": [
            {
              "value": "none",
              "label": "None"
            },
            {
              "value": "create",
              "label": "Create"
            },
            {
              "value": "manage",
              "label": "Manage"
            }
          ],
          "default": "none"
        },
        {
          "name": "sending",
          "label": "Sending",
          "description": "Send lets agents send new mail and replies from your address.",
          "levels": [
            {
              "value": "none",
              "label": "None"
            },
            {
              "value": "send",
              "label": "Send"
            }
          ],
          "default": "none"
        }
      ],
      "auth": {
        "composio": {
          "account": {
            "label": "/emailAddress",
            "method": "GET",
            "url": "https://gmail.googleapis.com/gmail/v1/users/me/profile"
          },
          "api_key": "{{publisher.composio_api_key}}",
          "app": "gmail",
          "auth_config_id": "{{publisher.composio_auth_config_id}}",
          "description": "Composio requires full Gmail access. Houston limits its use to the access level you select.",
          "label": "Connect with Composio",
          "order": 2,
          "type": "composio"
        },
        "oauth": {
          "account": {
            "headers": {
              "Authorization": {
                "value": "Bearer {{auth.oauth.access_token}}"
              }
            },
            "label": "/email",
            "method": "GET",
            "url": "https://www.googleapis.com/oauth2/v2/userinfo"
          },
          "authorize_params": {
            "access_type": "offline",
            "include_granted_scopes": "false",
            "prompt": "consent"
          },
          "authorize_url": "https://accounts.google.com/o/oauth2/v2/auth",
          "brand": "google",
          "client_auth": "body",
          "client_id": "{{publisher.client_id}}",
          "client_secret": "{{publisher.client_secret}}",
          "label": "Connect with Google",
          "order": 1,
          "pkce": "S256",
          "require_refresh": true,
          "scopes": [
            {
              "if": "{{ allows access.messages \"read\" }}",
              "values": [
                "https://www.googleapis.com/auth/userinfo.email",
                "https://www.googleapis.com/auth/gmail.messages.readonly"
              ]
            },
            {
              "if": "{{ is access.messages \"read\" }}",
              "values": [
                "https://www.googleapis.com/auth/gmail.labels.readonly"
              ]
            },
            {
              "if": "{{ allows access.messages \"organize\" }}",
              "values": [
                "https://www.googleapis.com/auth/gmail.messages.modify",
                "https://www.googleapis.com/auth/gmail.labels"
              ]
            },
            {
              "if": "{{ is access.drafts \"create\" }}",
              "values": [
                "https://www.googleapis.com/auth/userinfo.email",
                "https://www.googleapis.com/auth/gmail.drafts.create"
              ]
            },
            {
              "if": "{{ allows access.drafts \"manage\" }}",
              "values": [
                "https://www.googleapis.com/auth/userinfo.email",
                "https://www.googleapis.com/auth/gmail.drafts"
              ]
            },
            {
              "if": "{{ allows access.sending \"send\" }}",
              "values": [
                "https://www.googleapis.com/auth/userinfo.email",
                "https://www.googleapis.com/auth/gmail.send"
              ]
            }
          ],
          "token_url": "https://oauth2.googleapis.com/token",
          "type": "oauth2"
        }
      },
      "publisher": {
        "client_id": {
          "label": "Google OAuth client ID",
          "order": 1,
          "type": "string"
        },
        "client_secret": {
          "label": "Google OAuth client secret",
          "order": 2,
          "type": "secret"
        },
        "composio_api_key": {
          "description": "Use an API key from the project that owns the Gmail auth config, with Proxy execute enabled. Composio is offered only when both fields are filled in.",
          "label": "Composio project API key",
          "order": 4,
          "type": "secret"
        },
        "composio_auth_config_id": {
          "description": "Create a Gmail OAuth2 auth config using Composio-managed credentials and the https://mail.google.com/ scope. Copy its ac_ ID here. Leave blank to offer only direct Google sign-in.",
          "label": "Composio Gmail auth config ID",
          "order": 3,
          "type": "string"
        }
      },
      "proxy": [
        {
          "if": "{{ allows access.messages \"read\" }}",
          "action": {
            "headers": {
              "remove": [
                "Authorization"
              ],
              "set": {
                "Authorization": {
                  "if": "{{ isDefined auth.oauth }}",
                  "value": "Bearer {{auth.oauth.access_token}}"
                }
              }
            }
          },
          "match": {
            "host": [
              "gmail.googleapis.com"
            ],
            "method": [
              "GET"
            ],
            "path": [
              "/gmail/v1/users/me/labels",
              "/gmail/v1/users/me/labels/{id}",
              "/gmail/v1/users/me/messages",
              "/gmail/v1/users/me/messages/{id}",
              "/gmail/v1/users/me/messages/{id}/attachments/{attachmentId}",
              "/gmail/v1/users/me/threads",
              "/gmail/v1/users/me/threads/{id}",
              "/gmail/v1/users/me/history"
            ],
            "protocol": "http"
          }
        },
        {
          "if": "{{ and (isDefined auth.oauth) (allows access.messages \"read\") }}",
          "action": {
            "headers": {
              "remove": [
                "Authorization"
              ],
              "set": {
                "Authorization": {
                  "if": "{{ isDefined auth.oauth }}",
                  "value": "Bearer {{auth.oauth.access_token}}"
                }
              }
            }
          },
          "match": {
            "host": [
              "www.googleapis.com"
            ],
            "method": [
              "GET"
            ],
            "path": [
              "/oauth2/v2/userinfo"
            ],
            "protocol": "http"
          }
        },
        {
          "if": "{{ and (isDefined auth.composio) (allows access.messages \"read\") }}",
          "action": {
            "headers": {
              "remove": [
                "Authorization"
              ],
              "set": {
                "Authorization": {
                  "if": "{{ isDefined auth.oauth }}",
                  "value": "Bearer {{auth.oauth.access_token}}"
                }
              }
            }
          },
          "match": {
            "host": [
              "gmail.googleapis.com"
            ],
            "method": [
              "GET"
            ],
            "path": [
              "/gmail/v1/users/me/profile"
            ],
            "protocol": "http"
          }
        },
        {
          "if": "{{ allows access.drafts \"manage\" }}",
          "action": {
            "headers": {
              "remove": [
                "Authorization"
              ],
              "set": {
                "Authorization": {
                  "if": "{{ isDefined auth.oauth }}",
                  "value": "Bearer {{auth.oauth.access_token}}"
                }
              }
            }
          },
          "match": {
            "host": [
              "gmail.googleapis.com"
            ],
            "method": [
              "GET"
            ],
            "path": [
              "/gmail/v1/users/me/drafts",
              "/gmail/v1/users/me/drafts/{id}"
            ],
            "protocol": "http"
          }
        },
        {
          "if": "{{ allows access.drafts \"create\" }}",
          "action": {
            "headers": {
              "remove": [
                "Authorization"
              ],
              "set": {
                "Authorization": {
                  "if": "{{ isDefined auth.oauth }}",
                  "value": "Bearer {{auth.oauth.access_token}}"
                }
              }
            }
          },
          "match": {
            "host": [
              "gmail.googleapis.com"
            ],
            "method": [
              "POST"
            ],
            "path": [
              "/upload/gmail/v1/users/me/drafts"
            ],
            "protocol": "http"
          }
        },
        {
          "if": "{{ allows access.drafts \"manage\" }}",
          "action": {
            "headers": {
              "remove": [
                "Authorization"
              ],
              "set": {
                "Authorization": {
                  "if": "{{ isDefined auth.oauth }}",
                  "value": "Bearer {{auth.oauth.access_token}}"
                }
              }
            }
          },
          "match": {
            "host": [
              "gmail.googleapis.com"
            ],
            "method": [
              "PUT"
            ],
            "path": [
              "/upload/gmail/v1/users/me/drafts/{id}"
            ],
            "protocol": "http"
          }
        },
        {
          "if": "{{ allows access.drafts \"manage\" }}",
          "action": {
            "headers": {
              "remove": [
                "Authorization"
              ],
              "set": {
                "Authorization": {
                  "if": "{{ isDefined auth.oauth }}",
                  "value": "Bearer {{auth.oauth.access_token}}"
                }
              }
            }
          },
          "match": {
            "host": [
              "gmail.googleapis.com"
            ],
            "method": [
              "DELETE"
            ],
            "path": [
              "/gmail/v1/users/me/drafts/{id}"
            ],
            "protocol": "http"
          }
        },
        {
          "if": "{{ allows access.messages \"organize\" }}",
          "action": {
            "headers": {
              "remove": [
                "Authorization"
              ],
              "set": {
                "Authorization": {
                  "if": "{{ isDefined auth.oauth }}",
                  "value": "Bearer {{auth.oauth.access_token}}"
                }
              }
            }
          },
          "match": {
            "host": [
              "gmail.googleapis.com"
            ],
            "method": [
              "POST"
            ],
            "path": [
              "/gmail/v1/users/me/messages/batchModify",
              "/gmail/v1/users/me/messages/{id}/modify",
              "/gmail/v1/users/me/threads/{id}/modify",
              "/gmail/v1/users/me/labels"
            ],
            "protocol": "http"
          }
        },
        {
          "if": "{{ allows access.messages \"organize\" }}",
          "action": {
            "headers": {
              "remove": [
                "Authorization"
              ],
              "set": {
                "Authorization": {
                  "if": "{{ isDefined auth.oauth }}",
                  "value": "Bearer {{auth.oauth.access_token}}"
                }
              }
            }
          },
          "match": {
            "host": [
              "gmail.googleapis.com"
            ],
            "method": [
              "PATCH",
              "DELETE"
            ],
            "path": [
              "/gmail/v1/users/me/labels/{id}"
            ],
            "protocol": "http"
          }
        },
        {
          "if": "{{ allows access.sending \"send\" }}",
          "action": {
            "headers": {
              "remove": [
                "Authorization"
              ],
              "set": {
                "Authorization": {
                  "if": "{{ isDefined auth.oauth }}",
                  "value": "Bearer {{auth.oauth.access_token}}"
                }
              }
            }
          },
          "match": {
            "host": [
              "gmail.googleapis.com"
            ],
            "method": [
              "POST"
            ],
            "path": [
              "/upload/gmail/v1/users/me/messages/send"
            ],
            "protocol": "http"
          }
        }
      ]
    }
    
  • icon.svgicon.svg
  • README.md
    ---
    description: Search, read and answer Gmail, with attachments and drafts.
    ---
    # Gmail
    
    Give agents the context they need from your Gmail inbox. You choose what they
    may do in three separate areas:
    
    - **Messages**
      - **Read**: search mail with Gmail's own search syntax, read whole
        conversations, download attachments and see your labels.
      - **Organize**: also archive, mark read or unread, apply labels, and create,
        rename and delete labels.
    - **Drafts**
      - **Create**: prepare new drafts and replies (with attachments) for you to
        review and send from Gmail.
      - **Manage**: also read, edit and delete your drafts.
    - **Sending**
      - **Send**: send new mail and replies (with attachments) from your address.
    
    > Each area can be set to **None**. Agents can never delete mail or move it to
    > Trash or Spam. Deleted drafts are removed permanently. Gmail stores drafts as
    > messages, so Messages at Read can also show your drafts. Replying in a conversation
    > needs Messages at Read or above, so the agent can read the message it answers.
    
  • SETUP.md
    # Connect Gmail
    
    1. Choose a level for each row of **Access**:
       - **Messages**: **Read** lets agents search and read your mail, threads,
         attachments and labels. **Organize** also lets them archive, mark messages
         read or unread, apply labels, and create, rename and delete labels.
       - **Drafts**: **Create** lets agents write new drafts. You review and send
         them yourself in Gmail. **Manage** also lets them read, edit and delete
         your drafts. Google's permission for Manage also mentions sending drafts;
         Houston never sends a draft.
       - **Sending**: **Send** lets agents send new mail and replies from your
         address.
    
       Leave a row on **None** to turn it off. Gmail stores drafts as messages, so
       Messages at Read can also show your drafts.
    2. Choose an available sign-in option and select **Connect Gmail**.
    3. Choose your Google account and approve access. With Connect with Google, if
       Google shows a checkbox per permission, tick them all: Houston refuses a
       partial grant. You will return to Houston.
    
    Houston calls Gmail only when your agent asks it to and never syncs your mailbox
    in the background. Connect with Google asks only for the permissions of the
    levels you choose, so Google itself refuses anything beyond them, and it does
    not grant access to your other Google services. Houston never deletes messages
    or moves them to Trash or Spam; deleted drafts are removed for good.
    
    > If you connect with Composio, it requires full Gmail access. Houston limits its use to the access level
    > you select.
    
    ## Advanced
    
    - To change **Access**, edit the connection and connect the same mailbox again.
      Add a separate connection for a different mailbox.
    - Agents send from your account's own address. To reply in a conversation, they
      need Messages at Read or above.
    - Removing a connection stops Houston from using it. To revoke access in Google
      too, remove Composio (or Houston for direct sign-in) from
      [your Google Account's connections](https://myaccount.google.com/connections).
      This also affects other connections using that app.
    - If your Google Workspace blocks the connection, ask your administrator to
      allow the app shown on Google's consent screen.
    
  • tests
    • attachments.luau
      return {
      	scenario = {publisher = {client_id = "fixture-client", client_secret = "fixture-private-secret"}, config = {}, auth_method = "oauth", auth_config = {}},
      	access = {messages = "read", drafts = "none", sending = "none"},
      	configure = function()
      		requests, responses = {}, {}
      		fs = fixture.files()
      		-- Serves the body in fixed-size chunks to cross every parser boundary.
      		function chunked(bytes, size)
      			local position = 1
      			local reader = {closed = false}
      			function reader:read(_max)
      				if position > #bytes then return fixture.operation({done = true}) end
      				local data = string.sub(bytes, position, position + size - 1)
      				position += size
      				return fixture.operation({done = false, data = data})
      			end
      			function reader:readAll() error("attachments must stream, never readAll") end
      			function reader:close() self.closed = true end
      			return reader
      		end
      		http = {request = function(req)
      			table.insert(requests, req)
      			assert(#responses > 0, "unexpected request: " .. req.url)
      			return fixture.operation(table.remove(responses, 1))
      		end}
      	end,
      	run = function(c)
      		local bytes = {}
      		for i = 0, 255 do table.insert(bytes, string.char(i)) end
      		local binary = table.concat(bytes) .. "tail"
      		local payload = '{\n  "size": ' .. #binary .. ',\n  "data": "' .. base64.encode(binary, {url = true, pad = false}) .. '"\n}\n'
      		for _, size in {1, 3, 7, 64, 100000} do
      			local reader = chunked(payload, size)
      			responses = {{statusCode = 200, headers = {}, body = reader}}
      			local saved = c.getAttachment({messageId = "m:1", attachmentId = "att-1", path = "files/blob.bin"})
      			assert(requests[#requests].url == "https://gmail.googleapis.com/gmail/v1/users/me/messages/m%3A1/attachments/att-1", requests[#requests].url)
      			assert(saved.path == "files/blob.bin" and saved.url == "https://houston.test/files/blob.bin" and saved.size == #binary, "chunk size " .. size)
      			local file = fs.open("files/blob.bin", "r")
      			assert(await(file:readAll()) == binary, "decoded bytes differ for chunk size " .. size)
      			await(file:close())
      			assert(reader.closed)
      		end
      		responses = {{statusCode = 200, headers = {}, body = chunked('{"size":0}', 4)}}
      		assert(not pcall(c.getAttachment, {messageId = "m", attachmentId = "a", path = "x.bin"}), "missing data accepted")
      		responses = {{statusCode = 404, headers = {}, body = fixture.reader('{"error":{"code":404,"message":"Requested entity was not found.","status":"NOT_FOUND"}}')}}
      		local ok, err = pcall(c.getAttachment, {messageId = "m", attachmentId = "a", path = "x.bin"})
      		assert(not ok and string.find(tostring(err), "NOT_FOUND", 1, true), tostring(err))
      		local count = #requests
      		assert(not pcall(c.getAttachment, {messageId = "m", attachmentId = "a"}), "path is required")
      		assert(not pcall(c.getAttachment, {messageId = "m", attachmentId = "a", path = "x", extra = 1}))
      		for _, id in {"m/1", "..", ".", "m%2F1", "m\\1", "m\n"} do
      			local rejected, problem = pcall(c.getAttachment, {messageId = id, attachmentId = "a", path = "x.bin"})
      			assert(not rejected and problem.code == "invalid_argument" and string.find(problem.message, "messageId must be one", 1, true))
      		end
      		assert(not pcall(c.getAttachment, {messageId = "m", attachmentId = "a/b", path = "x.bin"}))
      		assert(#requests == count and #responses == 0)
      	end,
      }
      
    • authentication.luau
      return {
      	contract = function(m)
      		m.authentication({
      			{
      				auth = {},
      				config = {},
      				endpoint = { "GET", "https://gmail.googleapis.com/gmail/v1/users/me/labels" },
      				expected = "Bearer synthetic-oauth-token",
      				header = "Authorization",
      				method = "oauth",
      				oauth = true,
      				publisher = {
      					client_id = "synthetic-public-client",
      					client_secret = "synthetic-client-secret",
      				},
      				scopes = true,
      			},
      		})
      	end,
      }
      
    • body_formats.luau
      local function encoded(value)
      	return base64.encode(value, {url = true, pad = false}) -- Gmail bodies are unpadded base64url.
      end
      
      return {
      	scenario = {publisher = {client_id = "fixture-client", client_secret = "fixture-private-secret"}, config = {}, auth_method = "oauth", auth_config = {}},
      	access = {messages = "read", drafts = "manage", sending = "none"},
      	configure = function()
      		requests, responses = {}, {}
      		http = {request = function(req)
      			table.insert(requests, req)
      			assert(#responses > 0, "unexpected request: " .. req.url)
      			return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader(json.encode(table.remove(responses, 1)))})
      		end}
      	end,
      	run = function(c)
      		local function raw(plain, html)
      			local parts = {}
      			if plain ~= nil then table.insert(parts, {mimeType = "text/plain", body = {data = encoded(plain)}}) end
      			if html ~= nil then table.insert(parts, {mimeType = "text/html", body = {data = encoded(html)}}) end
      			return {id = "newsletter", snippet = "Preview", payload = {mimeType = "multipart/alternative", parts = parts}}
      		end
      		for _, case in {
      			{plain = "\r\n", html = "<p>Newsletter</p>", want = "<p>Newsletter</p>"},
      			{plain = " \t\r\n", html = "<p>Newsletter</p>", format = "auto", want = "<p>Newsletter</p>"},
      			{plain = "", html = "<p>Newsletter</p>", want = "<p>Newsletter</p>"},
      			{plain = utf8.char(0xA0, 0x2003), html = "<p>Newsletter</p>", want = "<p>Newsletter</p>"},
      			{plain = "  Text\n", html = "<p>Newsletter</p>", want = "  Text\n"},
      			{plain = "Text", html = "  <p>HTML</p>\n", format = "html", want = "  <p>HTML</p>\n"},
      			{plain = "\r\n", html = "<p>Newsletter</p>", format = "text", want = "\r\n"},
      			{html = "<p>Newsletter</p>", format = "text", want = ""},
      			{plain = "Text", format = "html", want = ""},
      			{plain = " \n", html = "\r\n", want = "Preview"},
      			{plain = "   Text", html = "<p>HTML</p>", limit = 2, want = "  ", truncated = true},
      			{plain = "\r\n", html = "<p>HTML</p>", limit = 4, want = "<p>H", truncated = true},
      		} do
      			responses = {raw(case.plain, case.html)}
      			local m = c.getMessage({id = "newsletter", bodyFormat = case.format, maxBodyBytes = case.limit})
      			assert(m.body == case.want, "body mismatch: " .. json.encode(m.body))
      			assert(m.bodyTruncated == (case.truncated == true), "selected body truncation")
      			assert(requests[#requests].url == "https://gmail.googleapis.com/gmail/v1/users/me/messages/newsletter?format=full")
      		end
      
      		local full = raw("Plain", "<p>HTML</p>")
      		responses = {full, {id = "thread", messages = {full}}, {id = "draft", message = full}}
      		assert(c.getMessages({ids = {"newsletter"}, bodyFormat = "html"})[1].body == "<p>HTML</p>")
      		assert(c.getThread({id = "thread", bodyFormat = "html"}).messages[1].body == "<p>HTML</p>")
      		assert(c.getDraft({id = "draft", bodyFormat = "html"}).message.body == "<p>HTML</p>")
      		responses = {{id = "newsletter", snippet = "Preview"}}
      		assert(c.getMessage({id = "newsletter", format = "metadata", bodyFormat = "html"}).body == "")
      
      		full = raw("\r\n", nil)
      		table.insert(full.payload.parts, {mimeType = "text/plain", body = {data = encoded("Later text")}})
      		responses = {full}
      		assert(c.getMessage({id = "newsletter"}).body == "Later text")
      		full = raw("\r\n", nil)
      		table.insert(full.payload.parts, {mimeType = "text/html", body = {attachmentId = "body1", size = 100}})
      		responses = {full, {data = encoded("<p>External HTML</p>")}}
      		local external = c.getMessage({id = "newsletter"})
      		assert(external.body == "<p>External HTML</p>" and #external.attachments == 0)
      		assert(requests[#requests].url == "https://gmail.googleapis.com/gmail/v1/users/me/messages/newsletter/attachments/body1")
      		full.payload.parts[2].body.data = ""
      		for _, format in {"auto", "html"} do
      			responses = {full, {data = encoded("<p>External HTML</p>")}}
      			assert(c.getMessage({id = "newsletter", bodyFormat = format}).body == "<p>External HTML</p>")
      		end
      		responses = {full}
      		assert(c.getMessage({id = "newsletter", bodyFormat = "text"}).body == "\r\n")
      		assert(#responses == 0)
      		for _, format in {"", "markdown", false, 3} do
      			local count = #requests
      			assert(not pcall(c.getMessage, {id = "newsletter", bodyFormat = format}))
      			assert(not pcall(c.getMessages, {ids = {"newsletter"}, bodyFormat = format}))
      			assert(not pcall(c.getThread, {id = "thread", bodyFormat = format}))
      			assert(not pcall(c.getDraft, {id = "draft", bodyFormat = format}))
      			assert(#requests == count, "invalid body format reached Google")
      		end
      	end,
      }
      
    • compose.luau
      -- Splits a MIME entity into its header block and body.
      local function entity(mime)
      	local head, body = string.match(mime, "^(.-)\r\n\r\n(.*)$")
      	return head, body
      end
      -- Returns the parts of a multipart body with the given boundary.
      local function parts(body, boundary)
      	local out = {}
      	local delimiter = "--" .. boundary
      	local rest = string.sub(body, string.find(body, delimiter, 1, true) + #delimiter + 2)
      	while true do
      		local stop = string.find(rest, "\r\n" .. delimiter, 1, true)
      		table.insert(out, string.sub(rest, 1, stop - 1))
      		rest = string.sub(rest, stop + 2 + #delimiter)
      		if string.sub(rest, 1, 2) == "--" then return out end
      		rest = string.sub(rest, 3)
      	end
      end
      -- Returns the JSON metadata and the MIME message of a Gmail multipart upload.
      local function uploaded(req)
      	assert(req.headers["Content-Type"][1] == 'multipart/related; boundary="=_houston_upload"')
      	local sections = parts(req.body, "=_houston_upload")
      	assert(#sections == 2 and select(1, entity(sections[1])) == "Content-Type: application/json; charset=UTF-8" and select(1, entity(sections[2])) == "Content-Type: message/rfc822")
      	return json.decode(select(2, entity(sections[1]))), select(2, entity(sections[2]))
      end
      return {
      	scenario = {publisher = {client_id = "fixture-client", client_secret = "fixture-private-secret"}, config = {}, auth_method = "oauth", auth_config = {}},
      	access = {messages = "read", drafts = "manage", sending = "send"},
      	configure = function()
      		requests, responses = {}, {}
      		fs = fixture.files()
      		http = {request = function(req)
      			table.insert(requests, req)
      			assert(#responses > 0, "unexpected request: " .. req.url)
      			local response = table.remove(responses, 1)
      			return fixture.operation({statusCode = response.status or 200, headers = {}, body = fixture.reader(response.body or "")})
      		end}
      	end,
      	run = function(c)
      		local API = "https://gmail.googleapis.com/gmail/v1/users/me"
      		local UPLOAD = "https://gmail.googleapis.com/upload/gmail/v1/users/me"
      		local binary = string.char(0, 255, 13, 10) .. string.rep("x", 100)
      		local file = fs.open("files/report.bin", "w")
      		file:write(binary)
      		await(file:close())
      
      		responses = {{body = '{"id":"s1","threadId":"t1","labelIds":["SENT"]}'}}
      		local sent = c.sendMessage({to = {"Ana <[email protected]>", "[email protected]"}, subject = "Résumé", text = "Hi Ana", html = "<p>Hi Ana</p>", bcc = "[email protected]",
      			attachments = {"files/report.bin", {path = "files/report.bin", filename = "naïve.bin", mimeType = "application/x-test"}}})
      		assert(sent.id == "s1")
      		local req = requests[#requests]
      		assert(req.method == "POST" and req.url == UPLOAD .. "/messages/send?uploadType=multipart", req.url)
      		local metadata, mime = uploaded(req)
      		assert(json.encode(metadata) == "{}", "a new message has no thread")
      		local head, content = entity(mime)
      		assert(string.find(head, "To: Ana <[email protected]>, [email protected]\r\n", 1, true) and string.find(head, "Bcc: [email protected]\r\n", 1, true))
      		assert(string.find(head, "Subject: =?UTF-8?B?UsOpc3Vtw6k=?=", 1, true) and string.find(head, "MIME-Version: 1.0", 1, true))
      		assert(string.find(head, 'Content-Type: multipart/mixed; boundary="=_houston_mixed"', 1, true) and not string.find(head, "In-Reply-To", 1, true))
      		local mixed = parts(content, "=_houston_mixed")
      		assert(#mixed == 3)
      		local altHead, altBody = entity(mixed[1])
      		assert(string.find(altHead, "multipart/alternative", 1, true))
      		local alternative = parts(altBody, "=_houston_alternative")
      		local textHead, textBody = entity(alternative[1])
      		assert(string.find(textHead, "text/plain; charset=UTF-8", 1, true) and base64.decode(textBody) == "Hi Ana")
      		assert(base64.decode(select(2, entity(alternative[2]))) == "<p>Hi Ana</p>")
      		local fileHead, fileBody = entity(mixed[2])
      		assert(string.find(fileHead, 'Content-Disposition: attachment; filename="report.bin"', 1, true) and string.find(fileHead, "application/octet-stream", 1, true))
      		assert(base64.decode(fileBody) == binary)
      		for encodedLine in string.gmatch(fileBody, "[^\r\n]+") do assert(#encodedLine <= 76, "base64 lines must wrap at 76") end
      		local namedHead = entity(mixed[3])
      		assert(string.find(namedHead, "filename*=UTF-8''na%C3%AFve.bin", 1, true) and string.find(namedHead, "application/x-test", 1, true))
      
      		local original = {id = "o1", threadId = "t9", payload = {headers = {
      			{name = "From", value = "Ana <[email protected]>"}, {name = "To", value = "[email protected], Bo <[email protected]>"}, {name = "Cc", value = "[email protected], [email protected]"},
      			{name = "Subject", value = "Plans"}, {name = "Message-ID", value = "<[email protected]>"}, {name = "References", value = "<[email protected]>"},
      		}}}
      		responses = {{body = json.encode(original)}, {body = '{"email":"[email protected]"}'}, {body = '{"id":"d1","message":{"id":"m","threadId":"t9"}}'}}
      		local draft = c.createDraft({inReplyTo = "o1", replyAll = true, text = "Sounds good", attachments = {}})
      		assert(draft.id == "d1")
      		assert(string.find(requests[#requests - 2].url, API .. "/messages/o1?format=metadata&metadataHeaders=From&metadataHeaders=Reply-To", 1, true), requests[#requests - 2].url)
      		assert(requests[#requests - 1].url == "https://www.googleapis.com/oauth2/v2/userinfo" and requests[#requests].url == UPLOAD .. "/drafts?uploadType=multipart")
      		metadata, mime = uploaded(requests[#requests])
      		assert(metadata.message.threadId == "t9")
      		head, content = entity(mime)
      		assert(string.find(head, "To: Ana <[email protected]>\r\n", 1, true) and string.find(head, "Cc: [email protected], [email protected]\r\n", 1, true), head)
      		assert(string.find(head, "Subject: Re: Plans\r\n", 1, true) and string.find(head, "In-Reply-To: <[email protected]>\r\n", 1, true))
      		assert(string.find(head, "References: <[email protected]> <[email protected]>\r\n", 1, true) and string.find(head, "Content-Type: text/plain; charset=UTF-8", 1, true))
      		assert(base64.decode(content) == "Sounds good")
      
      		original.payload.headers[4] = {name = "Subject", value = "RE: Plans"}
      		responses = {{body = json.encode(original)}, {body = '{"id":"d1"}'}}
      		c.updateDraft({id = "d1", inReplyTo = "o1", html = "<p>Updated</p>"})
      		assert(requests[#requests].method == "PUT" and requests[#requests].url == UPLOAD .. "/drafts/d1?uploadType=multipart")
      		head = entity(select(2, uploaded(requests[#requests])))
      		assert(string.find(head, "Subject: RE: Plans\r\n", 1, true) and not string.find(head, "Cc:", 1, true) and string.find(head, "text/html", 1, true))
      
      		local count = #requests
      		for _, args in {
      			{subject = "No recipient", text = "x"}, {to = "[email protected]"}, {to = "[email protected]", text = "x", unknown = true},
      			{to = "[email protected]", subject = "Injected\r\nBcc: [email protected]", text = "x"}, {to = {}, text = "x"},
      			{to = "[email protected]", text = "x", inReplyTo = ".."}, {to = "[email protected]", text = "x", inReplyTo = "o/1"},
      			{to = "[email protected]", text = "x", attachments = {"files/missing.bin"}}, {to = "[email protected]", text = "x", attachments = "files/report.bin"},
      		} do assert(not pcall(c.sendMessage, args)) end
      		for _, id in {"..", "d/1", "d%2F1"} do assert(not pcall(c.updateDraft, {id = id, to = "[email protected]", text = "x"})) end
      		assert(#requests == count and #responses == 0, "invalid messages reached Google")
      	end,
      }
      
    • composio.luau
      return {
      	scenario = {
      		publisher = {composio_auth_config_id = "ac_fixture", composio_api_key = "fixture-secret"},
      		config = {}, auth_method = "composio", auth_config = {},
      	},
      	access = {messages = "read", drafts = "create", sending = "none"},
      	configure = function()
      		requests, responses = {}, {}
      		http = {request = function(req)
      			table.insert(requests, req.url)
      			assert(#responses > 0, "unexpected request: " .. req.url)
      			return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader(table.remove(responses, 1))})
      		end}
      	end,
      	run = function(c)
      		local API = "https://gmail.googleapis.com/gmail/v1/users/me"
      		assert(type(c.listMessages) == "function" and c.sendMessage == nil and c.updateDraft == nil)
      		local original = {id = "o1", threadId = "t9", payload = {headers = {
      			{name = "From", value = "[email protected]"}, {name = "To", value = "[email protected], [email protected]"}, {name = "Message-ID", value = "<[email protected]>"},
      		}}}
      		responses = {json.encode(original), '{"emailAddress":"[email protected]"}', '{"id":"d1"}'}
      		c.createDraft({inReplyTo = "o1", replyAll = true, text = "Noted"})
      		assert(requests[2] == API .. "/profile", "Composio's full Gmail grant reads the mailbox address from the profile: " .. requests[2])
      		assert(#requests == 3 and #responses == 0)
      	end,
      }
      
    • composio_policy.luau
      return {
      	contract = function(m)
      		local publisher = {composio_auth_config_id = "ac_fixture", composio_api_key = "fixture-secret"}
      		for _, field in {"composio_api_key", "composio_auth_config_id"} do
      			local incomplete = table.clone(publisher)
      			incomplete[field] = nil
      			local _, err = m.resolve(incomplete, {}, nil, "composio")
      			assert(err, "Incomplete Composio settings must require " .. field)
      		end
      		local direct, directError = m.resolve({client_id = "google-client", client_secret = "google-secret"}, {}, nil, "oauth")
      		assert(direct and not directError, "Direct Google sign-in must work without Composio settings")
      		local google = {client_id = "google-client", client_secret = "google-secret"}
      		for _, settings in {{}, {composio_auth_config_id = "", composio_api_key = ""}, {composio_auth_config_id = "ac_fixture"}, {composio_api_key = "fixture-secret"}, publisher} do
      			local values = table.clone(google)
      			for key, value in settings do
      				values[key] = value
      			end
      			local form, err = m.draft(values, {}, nil, "oauth")
      			assert(form and not err, tostring(err))
      			for _, method in form.Methods do
      				local offered = method.key == "oauth" or settings == publisher
      				assert(method.eligible == offered and method.available == offered, "Sign-in choices must reflect complete publisher settings")
      			end
      			local resolved, resolveError = m.resolve(values, {}, nil, "oauth")
      			assert(resolved and not resolveError, "Optional Composio settings must not prevent Google sign-in")
      		end
      		local api = "https://gmail.googleapis.com/gmail/v1/users/me"
      		local upload = "https://gmail.googleapis.com/upload/gmail/v1/users/me"
      		for _, access in {
      			{messages = "read", drafts = "none", sending = "none"}, {messages = "none", drafts = "manage", sending = "none"},
      			{messages = "read", drafts = "create", sending = "none"}, {messages = "organize", drafts = "manage", sending = "send"},
      		} do
      			local r, err = m.resolve(publisher, {}, nil, "composio", access)
      			assert(r and not err, tostring(err))
      			m.routes(r, "", access.messages ~= "none", {"GET " .. api .. "/profile", "GET " .. api .. "/messages?q=is%3Aunread"})
      			m.routes(r, "", access.drafts ~= "none", {"POST " .. upload .. "/drafts?uploadType=multipart"})
      			m.routes(r, "", access.drafts == "manage", {"GET " .. api .. "/drafts", "GET " .. api .. "/drafts/d1", "PUT " .. upload .. "/drafts/d1?uploadType=multipart", "DELETE " .. api .. "/drafts/d1"})
      			m.routes(r, "", access.messages == "organize", {"POST " .. api .. "/messages/m1/modify", "POST " .. api .. "/labels"})
      			m.routes(r, "", access.sending == "send", {"POST " .. upload .. "/messages/send?uploadType=multipart"})
      			if access.messages ~= "none" then m.rejectOverrides(r, {"GET " .. api .. "/messages/m1"}) end
      			m.refused(r, "", {
      				"POST https://backend.composio.dev/api/v3.1/tools/execute/proxy", "GET https://gmail.googleapis.com/gmail/v1/users/[email protected]/profile",
      				"GET https://www.googleapis.com/oauth2/v2/userinfo", "POST " .. api .. "/drafts/send", "POST " .. api .. "/messages/m1/trash", "GET " .. api .. "/settings/sendAs",
      			})
      		end
      	end,
      }
      
    • drafts_create.luau
      return {
      	scenario = {publisher = {client_id = "fixture-client", client_secret = "fixture-private-secret"}, config = {}, auth_method = "oauth", auth_config = {}},
      	access = {messages = "none", drafts = "create", sending = "send"},
      	configure = function()
      		requests, responses = {}, {}
      		http = {request = function(req)
      			table.insert(requests, req)
      			assert(#responses > 0, "unexpected request: " .. req.url)
      			return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader(table.remove(responses, 1))})
      		end}
      	end,
      	run = function(c)
      		local UPLOAD = "https://gmail.googleapis.com/upload/gmail/v1/users/me"
      		local names = {}
      		for name in c do table.insert(names, name) end
      		table.sort(names)
      		assert(table.concat(names, ",") == "createDraft,sendMessage", "got " .. table.concat(names, ","))
      
      		responses = {'{"id":"d1","message":{"id":"m1"}}', '{"id":"s1"}'}
      		assert(c.createDraft({to = "[email protected]", subject = "Hello", text = "Hi Ana"}).id == "d1")
      		assert(requests[1].method == "POST" and requests[1].url == UPLOAD .. "/drafts?uploadType=multipart", requests[1].url)
      		assert(c.sendMessage({to = "[email protected]", subject = "Hello", text = "Hi Ana"}).id == "s1")
      		assert(requests[2].method == "POST" and requests[2].url == UPLOAD .. "/messages/send?uploadType=multipart", requests[2].url)
      
      		for _, operation in {c.createDraft, c.sendMessage} do
      			local ok, err = pcall(operation, {inReplyTo = "o1", text = "Sounds good"})
      			assert(not ok and string.find(tostring(err), "needs Messages access set to Read", 1, true), tostring(err))
      		end
      		assert(#requests == 2 and #responses == 0, "a reply without Messages access reached Google")
      	end,
      }
      
    • drafts_manage.luau
      return {
      	scenario = {publisher = {client_id = "fixture-client", client_secret = "fixture-private-secret"}, config = {}, auth_method = "oauth", auth_config = {}},
      	access = {messages = "none", drafts = "manage", sending = "none"},
      	configure = function()
      		requests, responses = {}, {}
      		http = {request = function(req)
      			table.insert(requests, req)
      			assert(#responses > 0, "unexpected request: " .. req.url)
      			return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader(table.remove(responses, 1))})
      		end}
      	end,
      	run = function(c)
      		local names = {}
      		for name in c do table.insert(names, name) end
      		table.sort(names)
      		assert(table.concat(names, ",") == "createDraft,deleteDraft,getDraft,listDrafts,updateDraft", "got " .. table.concat(names, ","))
      
      		responses = {'{"id":"d2","message":{"id":"m2","snippet":"Long draft","payload":{"mimeType":"text/plain","body":{"attachmentId":"body1","size":900000}}}}'}
      		local long = c.getDraft({id = "d2"})
      		assert(long.message.body == "Long draft" and long.message.bodyTruncated == true and #requests == 1, "a body stored as an attachment falls back to the snippet, marked truncated, without Messages access")
      	end,
      }
      
    • help_examples.luau
      -- Execute every documented call against the real connector; output schemas are checked by fixture.example.
      return {
      	scenario = {publisher = {client_id = "fixture-client", client_secret = "fixture-private-secret"}, config = {}, auth_method = "oauth", auth_config = {}},
      	access = {messages = "organize", drafts = "manage", sending = "send"},
      	configure = function()
      		fs = fixture.files()
      		requests, responses = {}, {}
      		http = {request = function(req)
      			assert(#responses > 0, "unexpected request: " .. req.url)
      			local expected = table.remove(responses, 1)
      			assert(req.method == expected.method, req.method)
      			assert(req.url == expected.url, req.url)
      			if expected.body then assert(req.body == expected.body, req.body) end
      			if expected.compose then
      				assert(string.find(req.body, "To: [email protected]\r\n", 1, true))
      				assert(string.find(req.body, "Subject: Launch plan\r\n", 1, true))
      				assert(string.find(req.body, base64.encode("Please review the launch plan."), 1, true))
      			end
      			table.insert(requests, req)
      			return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader(expected.response)})
      		end}
      	end,
      	run = function(c)
      		local API = "https://gmail.googleapis.com/gmail/v1/users/me"
      		local function expect(method, path, response, body)
      			table.insert(responses, {method = method, url = API .. path, response = response, body = body})
      		end
      		expect("GET", "/labels", '{"labels":[{"id":"INBOX","name":"INBOX","type":"system"}]}')
      		assert(fixture.example("listLabels").labels[1].id == "INBOX")
      		expect("GET", "/labels/INBOX", '{"id":"INBOX","name":"INBOX","messagesUnread":3}')
      		assert(fixture.example("getLabel").messagesUnread == 3)
      		expect("GET", "/messages?q=is%3Aunread%20in%3Ainbox&maxResults=20", '{"messages":[{"id":"m1","threadId":"t1"}],"nextPageToken":"next","resultSizeEstimate":2}')
      		assert(fixture.example("listMessages").nextPageToken == "next")
      		expect("GET", "/threads?q=from%3Aana%40example.com&maxResults=20", '{"threads":[{"id":"t1","snippet":"Plan","historyId":"12345"}]}')
      		assert(fixture.example("listThreads").threads[1].id == "t1")
      		expect("GET", "/drafts?maxResults=20", '{"drafts":[{"id":"d1","message":{"id":"m1","threadId":"t1"}}]}')
      		assert(fixture.example("listDrafts").drafts[1].id == "d1")
      		expect("GET", "/history?startHistoryId=12345&maxResults=20", '{"history":[{"id":"12346","messagesAdded":[{"message":{"id":"m1","threadId":"t1"}}]}],"historyId":"12346"}')
      		assert(fixture.example("listHistory").historyId == "12346")
      		expect("POST", "/messages/m1/modify", '{"id":"m1","threadId":"t1","labelIds":["INBOX"]}', '{"removeLabelIds":["UNREAD"]}')
      		assert(fixture.example("modifyMessage").labelIds[1] == "INBOX")
      		expect("POST", "/messages/batchModify", "")
      		assert(fixture.example("batchModifyMessages").success)
      		local batch = json.decode(requests[#requests].body)
      		assert(#batch.ids == 2 and batch.ids[2] == "m2" and batch.removeLabelIds[1] == "UNREAD")
      		expect("POST", "/threads/t1/modify", '{"id":"t1","messages":[{"id":"m1"}]}', '{"removeLabelIds":["INBOX"]}')
      		assert(fixture.example("modifyThread").id == "t1")
      		expect("POST", "/labels", '{"id":"Label_1","name":"Projects/Launch"}', '{"name":"Projects/Launch"}')
      		assert(fixture.example("createLabel").name == "Projects/Launch")
      		expect("PATCH", "/labels/Label_1", '{"id":"Label_1","name":"Projects/Launch"}', '{"name":"Projects/Launch"}')
      		assert(fixture.example("updateLabel").name == "Projects/Launch")
      		expect("DELETE", "/labels/Label_1", "")
      		assert(fixture.example("deleteLabel").success)
      		expect("DELETE", "/drafts/d1", "")
      		assert(fixture.example("deleteDraft").success)
      
      		local raw = {id = "m1", threadId = "t1", payload = {mimeType = "text/plain", headers = {{name = "Subject", value = "Plan"}}, body = {data = base64.encode("Please review.", {url = true, pad = false})}}}
      		expect("GET", "/messages/m1?format=full", json.encode(raw))
      		assert(fixture.example("getMessage").body == "Please review.")
      		for _, id in {"m1", "m2"} do
      			expect("GET", "/messages/" .. id .. "?format=metadata&metadataHeaders=From&metadataHeaders=Subject", json.encode({id = id, threadId = "t1", payload = {headers = {{name = "Subject", value = "Plan"}}}}))
      		end
      		local messages = fixture.example("getMessages")
      		assert(#messages == 2 and messages[1].id == "m1" and messages[2].id == "m2" and messages[2].subject == "Plan")
      		expect("GET", "/threads/t1?format=full", json.encode({id = "t1", historyId = "12345", messages = {raw}}))
      		assert(fixture.example("getThread").messages[1].body == "Please review.")
      		expect("GET", "/drafts/d1?format=full", json.encode({id = "d1", message = raw}))
      		assert(fixture.example("getDraft").message.body == "Please review.")
      		expect("GET", "/messages/m1/attachments/a1", json.encode({size = 6, data = base64.encode("report", {url = true, pad = false})}))
      		local saved = fixture.example("getAttachment")
      		assert(saved.path == "files/report.pdf" and saved.size == 6)
      		local file = fs.open(saved.path, "r")
      		assert(await(file:readAll()) == "report")
      		await(file:close())
      		expect("GET", "/labels", '{"labels":[{"id":"Label_1","name":"Projects"},{"id":"INBOX","name":"INBOX"}]}')
      		assert(fixture.example("listMailFolders")[1].id == "INBOX")
      
      		for _, spec in {{"sendMessage", "POST", "/messages/send", '{"id":"m2","threadId":"t2","labelIds":["SENT"]}'},
      			{"createDraft", "POST", "/drafts", '{"id":"d1","message":{"id":"m1","threadId":"t1"}}'},
      			{"updateDraft", "PUT", "/drafts/d1", '{"id":"d1","message":{"id":"m1","threadId":"t1"}}'}} do
      			table.insert(responses, {method = spec[2], url = "https://gmail.googleapis.com/upload/gmail/v1/users/me" .. spec[3] .. "?uploadType=multipart", response = spec[4], compose = true})
      			assert(fixture.example(spec[1]).id == (if spec[1] == "sendMessage" then "m2" else "d1"))
      		end
      		assert(#responses == 0 and #requests == 23)
      		local count = 0
      		for _ in c do count += 1 end
      		assert(count == 22, "execute an example for every configured operation")
      	end,
      }
      
    • manifest.luau
      return {
      	contract = function(m)
      		local api = "https://gmail.googleapis.com/gmail/v1/users/me"
      		local upload = "https://gmail.googleapis.com/upload/gmail/v1/users/me"
      		local function google(access, scopes)
      			local r, err = m.resolve({ client_id = "publisher-client", client_secret = "publisher-secret" }, {}, nil, "oauth", access)
      			assert(r and not err, tostring(err))
      			local want = { "https://www.googleapis.com/auth/userinfo.email" }
      			for _, scope in scopes do
      				table.insert(want, "https://www.googleapis.com/auth/" .. scope)
      			end
      			assert(m.equal(r.Scopes, want), "requested OAuth scopes: " .. table.concat(r.Scopes, " "))
      			r.Context.Auth.oauth.access_token = "fixture-token"
      			return r
      		end
      		-- Routes of a row's level, allowed only from that level up.
      		local function gated(r, allowed, routes)
      			m.routes(r, "Bearer fixture-token", allowed, routes)
      			if allowed then
      				m.rejectOverrides(r, routes)
      			end
      		end
      		do
      			local _, err = m.resolve({ client_id = "publisher-client", client_secret = "publisher-secret" }, {}, nil, "oauth", { messages = "none", drafts = "none", sending = "none" })
      			assert(string.find(tostring(err), "raise at least one access row", 1, true), "a connection with every row on None must be refused: " .. tostring(err))
      		end
      		for _, case in
      			{
      				{ access = { messages = "read", drafts = "none", sending = "none" }, scopes = { "gmail.messages.readonly", "gmail.labels.readonly" } },
      				{
      					access = { messages = "organize", drafts = "none", sending = "none" },
      					scopes = { "gmail.messages.readonly", "gmail.messages.modify", "gmail.labels" },
      				},
      				{ access = { messages = "none", drafts = "create", sending = "none" }, scopes = { "gmail.drafts.create" } },
      				{ access = { messages = "none", drafts = "manage", sending = "none" }, scopes = { "gmail.drafts" } },
      				{ access = { messages = "none", drafts = "none", sending = "send" }, scopes = { "gmail.send" } },
      				{
      					access = { messages = "read", drafts = "create", sending = "send" },
      					scopes = { "gmail.messages.readonly", "gmail.labels.readonly", "gmail.drafts.create", "gmail.send" },
      				},
      				{
      					access = { messages = "organize", drafts = "manage", sending = "send" },
      					scopes = { "gmail.messages.readonly", "gmail.messages.modify", "gmail.labels", "gmail.drafts", "gmail.send" },
      				},
      			}
      		do
      			local access = case.access
      			local r = google(access, case.scopes)
      			gated(r, access.messages ~= "none", {
      				"GET " .. api .. "/labels",
      				"GET " .. api .. "/labels/Label_1",
      				"GET " .. api .. "/messages?q=is%3Aunread",
      				"GET " .. api .. "/messages/m1?format=full",
      				"GET " .. api .. "/messages/m1/attachments/a1",
      				"GET " .. api .. "/threads",
      				"GET " .. api .. "/threads/t1",
      				"GET " .. api .. "/history?startHistoryId=1",
      				"GET https://www.googleapis.com/oauth2/v2/userinfo",
      			})
      			gated(r, access.messages == "organize", {
      				"POST " .. api .. "/messages/batchModify",
      				"POST " .. api .. "/messages/m1/modify",
      				"POST " .. api .. "/threads/t1/modify",
      				"POST " .. api .. "/labels",
      				"PATCH " .. api .. "/labels/Label_1",
      				"DELETE " .. api .. "/labels/Label_1",
      			})
      			gated(r, access.drafts ~= "none", { "POST " .. upload .. "/drafts?uploadType=multipart" })
      			gated(r, access.drafts == "manage", {
      				"GET " .. api .. "/drafts",
      				"GET " .. api .. "/drafts/d1",
      				"PUT " .. upload .. "/drafts/d1?uploadType=multipart",
      				"DELETE " .. api .. "/drafts/d1",
      			})
      			gated(r, access.sending == "send", { "POST " .. upload .. "/messages/send?uploadType=multipart" })
      			m.routes(r, "Bearer fixture-token", false, {
      				"POST https://oauth2.googleapis.com/token",
      				"GET https://www.googleapis.com/drive/v3/files",
      				"GET https://www.googleapis.com/oauth2/v2/tokeninfo",
      				"POST https://www.googleapis.com/oauth2/v2/userinfo",
      				"GET https://gmail.googleapis.com.evil.test/gmail/v1/users/me/labels",
      				"GET https://www.googleapis.com/gmail/v1/users/me/labels",
      				"GET https://gmail.googleapis.com/gmail/v1/users/[email protected]/labels",
      				"GET " .. api .. "/profile",
      				"POST https://gmail.googleapis.com/batch/gmail/v1",
      				"DELETE " .. api .. "/messages/m1",
      				"POST " .. api .. "/messages/batchDelete",
      				"POST " .. api .. "/messages/m1/trash",
      				"POST " .. api .. "/messages/m1/untrash",
      				"DELETE " .. api .. "/threads/t1",
      				"POST " .. api .. "/threads/t1/trash",
      				"POST " .. api .. "/threads/t1/untrash",
      				"POST " .. api .. "/messages/import",
      				"POST " .. api .. "/messages",
      				"POST " .. api .. "/messages/send",
      				"POST " .. api .. "/drafts/send",
      				"POST " .. upload .. "/drafts/send?uploadType=multipart",
      				"POST " .. upload .. "/drafts/d1?uploadType=multipart",
      				"POST " .. upload .. "/messages/import",
      				"POST " .. upload .. "/messages",
      				"PUT " .. api .. "/labels/Label_1",
      				"PUT " .. api .. "/drafts/d1",
      				"POST " .. api .. "/drafts",
      				"POST " .. api .. "/watch",
      				"POST " .. api .. "/stop",
      				"GET " .. api .. "/settings/sendAs",
      				"GET " .. api .. "/settings/forwardingAddresses",
      				"POST " .. api .. "/settings/filters",
      				"PUT " .. api .. "/settings/vacation",
      				"GET " .. api .. "/messages/%2e%2e/profile",
      				"GET " .. api .. "/messages/m1%2F..%2Fx",
      			})
      		end
      		do
      			local drafts = google({ messages = "read", drafts = "manage", sending = "none" }, { "gmail.messages.readonly", "gmail.labels.readonly", "gmail.drafts" })
      			for _, name in { "$httpMethod", "%24httpMethod" } do
      				m.refused(drafts, "method override", {
      					"GET " .. api .. "/drafts/send?" .. name .. "=POST",
      					"GET " .. api .. "/messages/send?" .. name .. "=POST",
      					"PUT " .. upload .. "/drafts/send?" .. name .. "=POST",
      				})
      			end
      		end
      	end,
      }
      
    • read_draft.luau
      return {
      	scenario = {publisher = {client_id = "fixture-client", client_secret = "fixture-private-secret"}, config = {}, auth_method = "oauth", auth_config = {}},
      	access = {messages = "read", drafts = "manage", sending = "none"},
      	configure = function()
      		requests, responses = {}, {}
      		http = {request = function(req)
      			table.insert(requests, req)
      			assert(#responses > 0, "unexpected request: " .. req.url)
      			return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader(table.remove(responses, 1))})
      		end}
      	end,
      	run = function(c)
      		local API = "https://gmail.googleapis.com/gmail/v1/users/me"
      		local UPLOAD = "https://gmail.googleapis.com/upload/gmail/v1/users/me"
      		local names = {}
      		for name in c do table.insert(names, name) end
      		table.sort(names)
      		assert(table.concat(names, ",") == "createDraft,deleteDraft,getAttachment,getDraft,getLabel,getMessage,getMessages,getThread,listDrafts,listHistory,listLabels,listMailFolders,listMessages,listThreads,updateDraft", "draft got " .. table.concat(names, ","))
      
      		responses = {'{"id":"d1","message":{"id":"m1","threadId":"t1"}}'}
      		assert(c.createDraft({to = "[email protected]", subject = "Monday follow-up", text = "Hi Ana"}).id == "d1")
      		local req = requests[#requests]
      		assert(req.method == "POST" and req.url == UPLOAD .. "/drafts?uploadType=multipart", req.url)
      		assert(string.find(req.body, "\r\nTo: [email protected]\r\n", 1, true) and string.find(req.body, "\r\nSubject: Monday follow-up\r\n", 1, true), req.body)
      
      		responses = {'{"id":"d1"}'}
      		c.updateDraft({id = "d1", to = "[email protected]", subject = "Monday follow-up", html = "<p>Hi Ana</p>"})
      		req = requests[#requests]
      		assert(req.method == "PUT" and req.url == UPLOAD .. "/drafts/d1?uploadType=multipart" and string.find(req.body, "text/html", 1, true), req.url)
      
      		responses = {""}
      		assert(c.deleteDraft({id = "d1"}).success == true)
      		req = requests[#requests]
      		assert(req.method == "DELETE" and req.url == API .. "/drafts/d1" and req.body == nil, req.url)
      		assert(#requests == 3 and #responses == 0)
      	end,
      }
      
    • read_only.luau
      return {
      	scenario = {publisher = {client_id = "fixture-client", client_secret = "fixture-private-secret"}, config = {}, auth_method = "oauth", auth_config = {}},
      	access = {messages = "read", drafts = "none", sending = "none"},
      	configure = function()
      		http = {request = function(req)
      			assert(req.url == "https://gmail.googleapis.com/gmail/v1/users/me/labels", req.url)
      			return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader('{"labels":[]}')})
      		end}
      	end,
      	run = function(c)
      		local names = {}
      		for name in c do table.insert(names, name) end
      		table.sort(names)
      		assert(table.concat(names, ",") == "getAttachment,getLabel,getMessage,getMessages,getThread,listHistory,listLabels,listMailFolders,listMessages,listThreads", "read got " .. table.concat(names, ","))
      		assert(not pcall(c.listMailFolders, "unexpected"))
      		local folders = c.listMailFolders()
      		assert(json.encode(folders) == "[]", "empty folders must remain a JSON array")
      	end,
      }
      
    • read_state.luau
      return {
      	scenario = {publisher = {client_id = "fixture-client", client_secret = "fixture-private-secret"}, config = {}, auth_method = "oauth", auth_config = {}},
      	access = {messages = "organize", drafts = "none", sending = "none"},
      	configure = function()
      		requests, responses = {}, {}
      		http = {request = function(req)
      			table.insert(requests, req)
      			assert(req.method == "POST" and req.headers.Authorization == nil)
      			assert(#responses > 0, "unexpected request: " .. req.url)
      			local response = table.remove(responses, 1)
      			return fixture.operation({statusCode = response.status or 200, headers = {}, body = fixture.reader(response.body or "")})
      		end}
      	end,
      	run = function(c)
      		local API = "https://gmail.googleapis.com/gmail/v1/users/me"
      		responses = {{body = '{"id":"m1","labelIds":["INBOX","STARRED"]}'}, {body = '{"id":"m1","labelIds":["INBOX","STARRED","UNREAD"]}'}, {status = 204}, {body = '{"id":"t1","messages":[{"id":"m1","labelIds":["INBOX"]}]}'} }
      		local read = c.modifyMessage({id = "m1", removeLabelIds = {"UNREAD"}})
      		assert(read.id == "m1" and read.labelIds[2] == "STARRED")
      		assert(requests[1].url == API .. "/messages/m1/modify" and requests[1].body == '{"removeLabelIds":["UNREAD"]}')
      		local unread = c.modifyMessage({id = "m1", addLabelIds = {"UNREAD"}})
      		assert(unread.labelIds[3] == "UNREAD")
      		assert(requests[2].url == API .. "/messages/m1/modify" and requests[2].body == '{"addLabelIds":["UNREAD"]}')
      		assert(c.batchModifyMessages({ids = {"m1", "m2"}, removeLabelIds = {"UNREAD"}}).success)
      		assert(requests[3].url == API .. "/messages/batchModify")
      		local batch = json.decode(requests[3].body)
      		assert(#batch.ids == 2 and batch.ids[1] == "m1" and batch.ids[2] == "m2" and #batch.removeLabelIds == 1 and batch.removeLabelIds[1] == "UNREAD" and batch.addLabelIds == nil)
      		local thread = c.modifyThread({id = "t1", removeLabelIds = {"UNREAD"}})
      		assert(thread.id == "t1" and thread.messages[1].id == "m1")
      		assert(requests[4].url == API .. "/threads/t1/modify" and requests[4].body == '{"removeLabelIds":["UNREAD"]}')
      		responses = {{status = 403, body = '{"error":{"message":"Insufficient permissions","status":"PERMISSION_DENIED"}}'}}
      		local ok, err = pcall(c.modifyMessage, {id = "m1", removeLabelIds = {"UNREAD"}})
      		assert(not ok and string.find(tostring(err), "PERMISSION_DENIED", 1, true))
      		assert(#requests == 5 and #responses == 0, "failed writes must not be replayed")
      		for _, call in {
      			function() return c.modifyMessage({id = "m1", addLabelIds = {"TRASH"}}) end, function() return c.modifyThread({id = "t1", addLabelIds = {"STARRED", "SPAM"}}) end,
      			function() return c.batchModifyMessages({ids = {"m1", "m2"}, addLabelIds = {"trash"}}) end,
      		} do
      			local refused, reason = pcall(call)
      			assert(not refused and string.find(tostring(reason), "nothing moves mail to Trash or Spam", 1, true), tostring(reason))
      		end
      		assert(#requests == 5, "a Trash or Spam label reached Google")
      	end,
      }
      
    • reads.luau
      -- Gmail bodies are unpadded base64url.
      local function b64(s)
      	return base64.encode(s, {url = true, pad = false})
      end
      return {
      	scenario = {publisher = {client_id = "fixture-client", client_secret = "fixture-private-secret"}, config = {}, auth_method = "oauth", auth_config = {}},
      	access = {messages = "read", drafts = "manage", sending = "none"},
      	configure = function()
      		requests, responses = {}, {}
      		http = {request = function(req)
      			table.insert(requests, req)
      			assert(#responses > 0, "unexpected request: " .. req.url)
      			local response = table.remove(responses, 1)
      			return fixture.operation({statusCode = response.status or 200, headers = response.headers or {}, body = fixture.reader(response.body or "")})
      		end}
      	end,
      	run = function(c)
      		local API = "https://gmail.googleapis.com/gmail/v1/users/me"
      		responses = {{body = '{"resultSizeEstimate":0}'}, {body = '{"messages":[{"id":"m1","threadId":"t1"}],"nextPageToken":"next+1"}'}}
      		local empty = c.listMessages({q = "from:[email protected] is:unread"})
      		assert(json.encode(empty.messages) == "[]", "absent lists must be empty arrays")
      		assert(requests[1].url == API .. "/messages?q=from%3Aana%40example.com%20is%3Aunread", requests[1].url)
      		local page = c.listMessages({labelIds = {"INBOX", "UNREAD"}, maxResults = 2, pageToken = "start+1"})
      		assert(page.nextPageToken == "next+1" and page.messages[1].id == "m1")
      		assert(requests[2].url == API .. "/messages?labelIds=INBOX&labelIds=UNREAD&maxResults=2&pageToken=start%2B1", requests[2].url)
      
      		local full = {
      			id = "m1", threadId = "t1", labelIds = {"INBOX"}, snippet = "Hello", internalDate = "1760000000000",
      			payload = {mimeType = "multipart/mixed", headers = {
      				{name = "From", value = "Ana <[email protected]>"}, {name = "To", value = "[email protected]"},
      				{name = "Subject", value = "Plans"}, {name = "Message-ID", value = "<[email protected]>"}, {name = "Received", value = "from mx"},
      			}, parts = {
      				{mimeType = "multipart/alternative", parts = {
      					{mimeType = "text/plain", body = {size = 12, data = b64("Héllo there!")}},
      					{mimeType = "text/html", body = {size = 20, data = b64("<p>Héllo there!</p>")}},
      				}},
      				{mimeType = "image/png", filename = "", headers = {{name = "Content-ID", value = "<logo@x>"}}, body = {attachmentId = "inline1", size = 10}},
      				{mimeType = "application/pdf", filename = "plan.pdf", headers = {{name = "Content-Disposition", value = "attachment; filename=\"plan.pdf\""}}, body = {attachmentId = "att1", size = 2048}},
      				{mimeType = "text/plain", filename = "notes.txt", body = {attachmentId = "att2", size = 5}},
      			}},
      		}
      		responses = {{body = json.encode(full)}}
      		local message = c.getMessage({id = "m1"})
      		assert(requests[3].url == API .. "/messages/m1?format=full", requests[3].url)
      		assert(message.from == "Ana <[email protected]>" and message.to == "[email protected]" and message.subject == "Plans" and message.messageId == "<[email protected]>")
      		assert(message.body == "Héllo there!" and message.bodyTruncated == false and message.payload == nil)
      		assert(#message.attachments == 3 and message.attachments[1].id == "inline1" and message.attachments[1].inline and message.attachments[1].contentId == "logo@x")
      		assert(message.attachments[2].filename == "plan.pdf" and not message.attachments[2].inline and message.attachments[2].size == 2048)
      		assert(message.attachments[3].filename == "notes.txt", "named text parts are attachments, not bodies")
      		assert(message.labelIds[1] == "INBOX" and #message.headers == 5)
      
      		local latin = {id = "m2", threadId = "t2", payload = {mimeType = "text/html", headers = {}, body = {data = b64("caf" .. string.char(233) .. " <b>ok</b>")}}}
      		responses = {{body = json.encode(latin)}}
      		message = c.getMessage({id = "m2", maxBodyBytes = 4})
      		assert(message.body == "caf" and message.bodyTruncated, "truncation keeps whole UTF-8 characters: " .. message.body)
      		assert(json.encode(message.attachments) == "[]" and message.from == nil)
      		responses = {{body = json.encode(latin)}}
      		assert(c.getMessage({id = "m2", maxBodyBytes = 0}).body == "café <b>ok</b>")
      		responses = {{body = '{"id":"m3","threadId":"t3","snippet":"Just a snippet"}'}}
      		message = c.getMessage({id = "m3", format = "minimal"})
      		assert(message.body == "Just a snippet" and string.find(requests[#requests].url, "format=minimal", 1, true))
      
      		local ids = {}
      		responses = {}
      		for i = 1, 12 do
      			table.insert(ids, "id" .. i)
      			table.insert(responses, {body = json.encode({id = "id" .. i, threadId = "t", payload = {headers = {{name = "Subject", value = "S" .. i}}}})})
      		end
      		local before = #requests
      		local batch = c.getMessages({ids = ids, format = "metadata", metadataHeaders = {"Subject"}})
      		assert(#batch == 12 and #requests == before + 12)
      		for i = 1, 12 do assert(batch[i].id == "id" .. i and batch[i].subject == "S" .. i) end
      		assert(requests[before + 1].url == API .. "/messages/id1?format=metadata&metadataHeaders=Subject", requests[before + 1].url)
      
      		responses = {{body = json.encode({id = "t1", historyId = "9", messages = {full, latin}})}, {body = json.encode({id = "d1", message = full})}}
      		local thread = c.getThread({id = "t1"})
      		assert(thread.id == "t1" and #thread.messages == 2 and thread.messages[1].body == "Héllo there!" and thread.messages[2].body == "café <b>ok</b>")
      		local draft = c.getDraft({id = "d1"})
      		assert(draft.id == "d1" and draft.message.subject == "Plans")
      
      		responses = {{body = '{"labels":[{"id":"Label_2","name":"Work","type":"user"},{"id":"INBOX","name":"INBOX","type":"system"}]}'}}
      		local folders = c.listMailFolders()
      		assert(#folders == 2 and folders[1].id == "INBOX" and folders[2].name == "Work" and folders[2].type == nil)
      		responses = {{body = '{"labels":[{"id":"A","name":"One"},{"id":"A","name":"Two"}]}'}}
      		assert(not pcall(c.listMailFolders), "duplicate label IDs accepted")
      
      		local count = #requests
      		for _, call in {
      			function() return c.getMessage({}) end, function() return c.getMessage("m1") end, function() return c.getMessage({id = "m1", format = "raw"}) end,
      			function() return c.getMessage({id = "m1", maxBodyBytes = -1}) end, function() return c.getMessage({id = "m1", extra = true}) end,
      			function() return c.getMessages({ids = {}}) end, function() return c.getMessages({ids = {"a", ""}}) end,
      			function() return c.getMessage({id = ".."}) end, function() return c.getMessage({id = "m/1"}) end, function() return c.getMessages({ids = {"a", "b%2Fc"}}) end, function() return c.getMessages({ids = {"a", nil, "c"}}) end,
      			function() return c.listMessages({unknown = 1}) end,
      		} do assert(not pcall(call)) end
      		assert(#requests == count, "invalid input reached Google")
      
      		responses = {{status = 403, body = '{"error":{"code":403,"message":"Request had insufficient authentication scopes.","status":"PERMISSION_DENIED","errors":[{"reason":"insufficientPermissions"}]}}'}}
      		local ok, err = pcall(c.listLabels)
      		assert(not ok and string.find(tostring(err), "insufficient authentication scopes", 1, true) and string.find(tostring(err), "PERMISSION_DENIED", 1, true), tostring(err))
      		assert(#responses == 0)
      	end,
      }