Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions src/tools/create-tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -752,6 +752,92 @@ describe("createGmailTools", () => {
);
});

test("reply drafts address Reply-To, or the recipients of a sent message", async () => {
const original = (labelIds: string[]) => ({
id: "message-1",
threadId: "thread-1",
labelIds,
payload: {
mimeType: "text/plain",
headers: [
{ name: "From", value: "List <noreply@list.example>" },
{ name: "To", value: "Ada <ada@example.com>" },
{
name: "Reply-To",
value: "Real <real@example.com>, other@example.com",
},
{ name: "Subject", value: "Hello" },
{ name: "Message-ID", value: "<message-1@example.com>" },
],
body: { data: encodeBase64Url("Original") },
},
});
const headersFor = async (labelIds: string[], to?: string[]) => {
let raw = "";
const tools = createGmailTools({
capabilities: testCapabilities(async (input, init) => {
const url = new URL(String(input));
if (url.pathname.endsWith("/messages/message-1")) {
return new Response(JSON.stringify(original(labelIds)));
}
raw = draftRawFromRequest(init);
return new Response(JSON.stringify({ id: "draft-1" }));
}),
});
await tools.run(
{
id: "call-reply",
name: "gmail_create_draft",
arguments: {
replyToMessageId: "message-1",
body: "Thanks",
...(to === undefined ? {} : { to }),
},
},
new AbortController().signal,
);
await tools.dispose();
return Buffer.from(raw, "base64url").toString().split("\r\n\r\n")[0];
};

expect(await headersFor(["INBOX"])).toContain(
"To: real@example.com, other@example.com\r\nSubject: Re: Hello",
);
expect(await headersFor(["INBOX"], [])).toContain(
"To: real@example.com, other@example.com",
);
expect(await headersFor(["SENT"])).toContain("To: ada@example.com");
});

test("keeps an existing Re: prefix on reply subjects", () => {
const raw = createRawDraft(
{ body: "Reply" },
{ messageId: "<message-1@example.com>", subject: "RE: Original" },
);
expect(Buffer.from(raw, "base64url").toString()).toContain(
"Subject: RE: Original\r\n",
);
});

test("RFC 2047-encodes non-ASCII subjects", () => {
const subject = "Grüße – 日本 ".repeat(6);
const raw = Buffer.from(
createRawDraft({ to: ["ada@example.com"], subject, body: "x" }),
"base64url",
).toString();
const header = /^Subject: (.*?)\r\n(?! )/ms.exec(raw)?.[1] ?? "";
const words = header.split("\r\n ");
expect(words.length).toBeGreaterThan(1);
for (const word of words) {
expect(word).toMatch(/^=\?UTF-8\?B\?[A-Za-z0-9+/=]+\?=$/);
expect(word.length).toBeLessThanOrEqual(75);
}
const decoded = words
.map((word) => Buffer.from(word.slice(10, -2), "base64").toString())
.join("");
expect(decoded).toBe(subject);
});

test("applies and removes labels on messages and threads", async () => {
const fetchImpl = createFetchImpl(async (input, init) => {
const url = new URL(String(input));
Expand Down
23 changes: 15 additions & 8 deletions src/tools/create-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
import { GMAIL_CREDENTIAL_HANDLE, TOOL_DEFINITIONS } from "./definitions.js";
import {
metadataHeadersForView,
recipients,
toToolDraft,
toThreadListMessage,
toToolMessage,
Expand Down Expand Up @@ -127,7 +128,11 @@ async function replyContext(
const normalized = toToolMessage(original, "FULL_CONTENT");
const originalMessageId = headerValue(original, "Message-ID");
const originalReferences = headerValue(original, "References");
const recipient = inputRecipients(original, normalized);
const recipient = inputRecipients(
original,
normalized,
headerValue(original, "Reply-To"),
);
return {
...(original.threadId === undefined ? {} : { threadId: original.threadId }),
...(originalMessageId === undefined
Expand All @@ -152,14 +157,16 @@ async function replyContext(
function inputRecipients(
original: { labelIds?: readonly string[] },
normalized: ReturnType<typeof toToolMessage>,
replyTo: string | undefined,
): readonly string[] | undefined {
const replyAddress = original.labelIds?.includes("SENT")
? normalized.toRecipients?.[0]
: normalized.sender;
const recipient = plainEmailAddress(replyAddress);
return recipient === undefined || recipient.length === 0
? undefined
: [recipient];
const addresses = original.labelIds?.includes("SENT")
? normalized.toRecipients?.slice(0, 1)
: (recipients(replyTo) ?? [normalized.sender]);
const result = (addresses ?? []).flatMap((address) => {
const recipient = plainEmailAddress(address);
return recipient === undefined || recipient.length === 0 ? [] : [recipient];
});
return result.length === 0 ? undefined : result;
}

async function listDraftsForQuery(
Expand Down
44 changes: 41 additions & 3 deletions src/tools/drafts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,40 @@ function recipientHeader(
return [`${name}: ${addresses.join(", ")}`];
}

function replySubject(subject: string): string {
return /^re:/i.test(subject) ? subject : `Re: ${subject}`;
}

// RFC 2047 caps an encoded word at 75 characters; 45 bytes base64 to 60.
const MAX_ENCODED_WORD_BYTES = 45;

function encodeSubject(subject: string): string {
if (/^[\x20-\x7e]*$/.test(subject)) return subject;
const encoder = new TextEncoder();
const words: string[] = [];
let chunk = "";
for (const character of subject) {
if (
encoder.encode(chunk + character).length > MAX_ENCODED_WORD_BYTES &&
chunk.length > 0
) {
words.push(chunk);
chunk = "";
}
chunk += character;
}
words.push(chunk);
return words
.map((word) => {
let binary = "";
for (const byte of encoder.encode(word)) {
binary += String.fromCharCode(byte);
}
return `=?UTF-8?B?${btoa(binary)}?=`;
})
.join("\r\n ");
}

function escapeHtml(value: string): string {
return value
.replaceAll("&", "&amp;")
Expand Down Expand Up @@ -85,13 +119,17 @@ export function createRawDraft(
input: DraftInput,
reply?: ReplyContext,
): string {
const subject = input.subject ?? reply?.subject ?? "";
const subject =
input.subject ??
(reply?.subject === undefined ? "" : replySubject(reply.subject));
assertSafeHeader(subject, "subject");
const to =
input.to === undefined || input.to.length === 0 ? reply?.to : input.to;
const headers = [
...recipientHeader("To", input.to ?? reply?.to),
...recipientHeader("To", to),
...recipientHeader("Cc", input.cc),
...recipientHeader("Bcc", input.bcc),
`Subject: ${subject}`,
`Subject: ${encodeSubject(subject)}`,
"MIME-Version: 1.0",
];
if (reply?.messageId !== undefined) {
Expand Down
2 changes: 1 addition & 1 deletion src/tools/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ function bodyForMimeType(
return values.length === 0 ? undefined : values.join("\n\n");
}

function recipients(value: string | undefined): string[] | undefined {
export function recipients(value: string | undefined): string[] | undefined {
if (value === undefined || value.length === 0) return undefined;
const result: string[] = [];
let start = 0;
Expand Down
Loading