Skip to content

A desktop coding agent with free access to frontier models.

TypeScript
92.8 KB
Raw Blame
import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
import type { LookupAddress, LookupAllOptions } from "node:dns";
import { lookup } from "node:dns/promises";
import { createServer, type Server } from "node:http";
import { chmod, mkdir, readFile, realpath, rm, stat, writeFile } from "node:fs/promises";
import { isIP, type LookupFunction } from "node:net";
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
import { omnirushServerConfigPath } from "@omnirush/paths";
import { z } from "zod";
import {
  Agent,
  fetch as undiciFetch,
  type RequestInit as UndiciRequestInit,
} from "undici";

import { ApiError } from "../errors.js";
import { isLocalManagedMcpPrivateAddress } from "../local-managed-mcp-url-guard.js";
import { externalFetch } from "../server-fetch.js";
import type { ServerConfig } from "../types.js";

export const GOOGLE_WORKSPACE_EXTENSION_ID = "google-workspace";

const GMAIL_HARD_WRAP_MIN_LINE_LENGTH = 50;
const GMAIL_QUOTE_BODY_LIMIT = 10_000;
const GMAIL_REPLY_SUBJECT_RE = /^\s*(re|fwd?)\s*:/i;
const GMAIL_ATTACHMENT_MAX_BYTES = 20 * 1024 * 1024;
const GMAIL_RAW_MESSAGE_MAX_BYTES = 25 * 1024 * 1024;
const GMAIL_ATTACHMENT_REDIRECT_LIMIT = 5;
const GMAIL_HEADER_FOLD_LIMIT = 78;
const UTC_WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const UTC_MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const GOOGLE_WORKSPACE_DESKTOP_CLIENT_ID = "929071212606-pmkqimjhm2tnp68kbklnout0irllj99h.apps.googleusercontent.com";
const GOOGLE_WORKSPACE_CLIENT_ID_ENV = "OMNIRUSH_GOOGLE_WORKSPACE_OAUTH_CLIENT_ID";
const GOOGLE_WORKSPACE_CLIENT_SECRET_ENV = "GOOGLE_WORKSPACE_OAUTH_CLIENT_SECRET";
const LEGACY_GOOGLE_WORKSPACE_CLIENT_SECRET_ENV = "OMNIRUSH_GOOGLE_WORKSPACE_OAUTH_CLIENT_SECRET";
const GOOGLE_WORKSPACE_TOKEN_BROKER_URL_ENV = "OMNIRUSH_GOOGLE_WORKSPACE_TOKEN_BROKER_URL";
const GOOGLE_WORKSPACE_ALLOW_PLAINTEXT_VAULT_ENV = "OMNIRUSH_GOOGLE_WORKSPACE_ALLOW_PLAINTEXT_VAULT";
const GOOGLE_WORKSPACE_AUTH_TIMEOUT_MS = 5 * 60 * 1000;
const GOOGLE_WORKSPACE_API_TIMEOUT_MS = 30_000;
const GOOGLE_WORKSPACE_SCOPES = [
  "openid",
  "https://www.googleapis.com/auth/userinfo.email",
  "https://www.googleapis.com/auth/userinfo.profile",
  "https://www.googleapis.com/auth/calendar.readonly",
  "https://www.googleapis.com/auth/gmail.compose",
  "https://www.googleapis.com/auth/drive.file",
];
const GMAIL_READONLY_SCOPE = "https://www.googleapis.com/auth/gmail.readonly";
const DRIVE_FULL_SCOPE = "https://www.googleapis.com/auth/drive";
const CALENDAR_EVENTS_SCOPE = "https://www.googleapis.com/auth/calendar.events";
const CHAT_SPACES_SCOPE = "https://www.googleapis.com/auth/chat.spaces.readonly";
const CHAT_MESSAGES_READ_SCOPE = "https://www.googleapis.com/auth/chat.messages.readonly";
const CHAT_MESSAGES_CREATE_SCOPE = "https://www.googleapis.com/auth/chat.messages.create";

export const GOOGLE_WORKSPACE_OPTIONAL_FEATURES = {
  gmailRead: [GMAIL_READONLY_SCOPE],
  driveFull: [DRIVE_FULL_SCOPE],
  calendarWrite: [CALENDAR_EVENTS_SCOPE],
  chat: [CHAT_SPACES_SCOPE, CHAT_MESSAGES_READ_SCOPE, CHAT_MESSAGES_CREATE_SCOPE],
} satisfies Record<string, string[]>;

export type GoogleWorkspaceOptionalFeature = keyof typeof GOOGLE_WORKSPACE_OPTIONAL_FEATURES;

function isGoogleWorkspaceOptionalFeature(value: string): value is GoogleWorkspaceOptionalFeature {
  return Object.hasOwn(GOOGLE_WORKSPACE_OPTIONAL_FEATURES, value);
}

const GMAIL_DRAFT_ATTACHMENTS_SCHEMA = {
  type: "array",
  description: "Optional files to attach. Each item must provide exactly one of url or path.",
  items: {
    type: "object",
    properties: {
      url: { type: "string", description: "Public https URL to download and attach. Preferred over path; works from any surface." },
      path: { type: "string", description: "Deprecated; prefer url. Workspace-relative path or authorized absolute file path." },
      filename: { type: "string", description: "Optional attachment filename shown in Gmail." },
      mimeType: { type: "string", description: "Optional attachment MIME type. Defaults from the download response or file extension when possible." },
    },
    additionalProperties: false,
  },
};

export const GOOGLE_WORKSPACE_EXTENSION_ACTIONS = [
  {
    extensionId: GOOGLE_WORKSPACE_EXTENSION_ID,
    action: "status",
    title: "Google Workspace status",
    description: "Check whether Google Workspace is connected and ready for the app's extension actions.",
    inputSchema: { type: "object", properties: {}, additionalProperties: false },
  },
  {
    extensionId: GOOGLE_WORKSPACE_EXTENSION_ID,
    action: "calendar_list_events",
    title: "List calendar events",
    description: "List events from the connected Google Calendar account for a requested time range.",
    inputSchema: {
      type: "object",
      properties: {
        timeMin: { type: "string", format: "date-time", description: "Exclusive lower bound for event end times. RFC 3339 with Z or a UTC offset, e.g. 2026-09-01T09:00:00+02:00." },
        timeMax: { type: "string", format: "date-time", description: "Exclusive upper bound for event start times. RFC 3339 with Z or a UTC offset; must be later than timeMin." },
        maxResults: { type: "integer", description: "Maximum events to return. Defaults to 10; clamped to 1–50." },
      },
      required: ["timeMin", "timeMax"],
      additionalProperties: false,
    },
  },
  {
    extensionId: GOOGLE_WORKSPACE_EXTENSION_ID,
    action: "gmail_create_draft",
    title: "Create Gmail draft",
    description: "Create a brand-new Gmail draft for a new conversation only — never for replies. This does not send email. body must contain only the new message text; never paste quoted history from an earlier email. Subjects starting with Re: or Fwd: are rejected here — use gmail_create_reply_draft so the thread is preserved. Returns draftUrl; always share it with the user so they can review and send in Gmail.",
    inputSchema: {
      type: "object",
      properties: {
        to: { type: "array", items: { type: "string" }, description: "Recipient email addresses." },
        cc: { type: "array", items: { type: "string" }, description: "Optional CC recipients." },
        bcc: { type: "array", items: { type: "string" }, description: "Optional BCC recipients." },
        subject: { type: "string", description: "Draft subject. Do not use Re: or Fwd: here; use gmail_create_reply_draft for replies." },
        body: { type: "string", description: "Plain text draft body. Write plain prose with no markdown syntax, separate paragraphs with blank lines, and do not hard-wrap prose." },
        attachments: GMAIL_DRAFT_ATTACHMENTS_SCHEMA,
      },
      required: ["to", "subject", "body"],
      additionalProperties: false,
    },
  },
  {
    extensionId: GOOGLE_WORKSPACE_EXTENSION_ID,
    action: "gmail_create_reply_draft",
    title: "Create Gmail reply draft",
    description: "Create a Gmail draft reply in an existing thread. This does not send email. Requires Gmail read access (gmail.readonly scope). body must contain only the new reply text — the app automatically appends the quoted conversation below it in plain text and in Gmail's collapsible quote format; never include quoted history yourself. Returns draftUrl and threadUrl plus the resolved reply target; always share draftUrl with the user so they can review and send in Gmail.",
    inputSchema: {
      type: "object",
      properties: {
        messageId: { type: "string", description: "Gmail message id to reply to." },
        body: { type: "string", description: "Plain text reply body. Write plain prose with no markdown syntax; do not include quoted history because the app appends it automatically." },
        replyAll: { type: "boolean", description: "Reply to everyone on the original message. Defaults to true." },
        attachments: GMAIL_DRAFT_ATTACHMENTS_SCHEMA,
      },
      required: ["messageId", "body"],
      additionalProperties: false,
    },
  },
  {
    extensionId: GOOGLE_WORKSPACE_EXTENSION_ID,
    action: "gmail_list_messages",
    title: "List Gmail messages",
    description: "List recent Gmail messages for the connected account. Requires Gmail read access (gmail.readonly scope).",
    inputSchema: {
      type: "object",
      properties: {
        query: { type: "string", description: "Optional Gmail search query, e.g. 'is:unread' or 'from:[email protected]'." },
        maxResults: { type: "number", description: "Maximum messages to return." },
      },
      additionalProperties: false,
    },
  },
  {
    extensionId: GOOGLE_WORKSPACE_EXTENSION_ID,
    action: "gmail_get_message",
    title: "Read Gmail message",
    description: "Read a Gmail message by id, including its plain text body and attachment metadata. Requires Gmail read access (gmail.readonly scope).",
    inputSchema: {
      type: "object",
      properties: {
        messageId: { type: "string", description: "Gmail message id." },
      },
      required: ["messageId"],
      additionalProperties: false,
    },
  },
  {
    extensionId: GOOGLE_WORKSPACE_EXTENSION_ID,
    action: "gmail_download_attachment",
    title: "Download Gmail attachment",
    description: "Download a Gmail attachment by message id and attachment id. Returns base64-encoded attachment bytes. Requires Gmail read access (gmail.readonly scope).",
    inputSchema: {
      type: "object",
      properties: {
        messageId: { type: "string", description: "Gmail message id." },
        attachmentId: { type: "string", description: "Gmail attachment id from gmail_get_message attachment metadata." },
      },
      required: ["messageId", "attachmentId"],
      additionalProperties: false,
    },
  },
  {
    extensionId: GOOGLE_WORKSPACE_EXTENSION_ID,
    action: "drive_search_files",
    title: "Search Drive files",
    description: "Search files available to the app through the connected Google Drive scope. With full Drive access enabled, this searches the entire Drive.",
    inputSchema: {
      type: "object",
      properties: {
        query: { type: "string", description: "Search text." },
        maxResults: { type: "number", description: "Maximum files to return." },
      },
      required: ["query"],
      additionalProperties: false,
    },
  },
  {
    extensionId: GOOGLE_WORKSPACE_EXTENSION_ID,
    action: "drive_read_file",
    title: "Read Drive file",
    description: "Read a Drive file available to the app by file id.",
    inputSchema: {
      type: "object",
      properties: {
        fileId: { type: "string", description: "Google Drive file id." },
      },
      required: ["fileId"],
      additionalProperties: false,
    },
  },
  {
    extensionId: GOOGLE_WORKSPACE_EXTENSION_ID,
    action: "drive_update_file",
    title: "Update Drive file",
    description: "Replace the plain text content of a Drive file available to the app by file id.",
    inputSchema: {
      type: "object",
      properties: {
        fileId: { type: "string", description: "Google Drive file id." },
        content: { type: "string", description: "New plain text content for the file." },
      },
      required: ["fileId", "content"],
      additionalProperties: false,
    },
  },
  {
    extensionId: GOOGLE_WORKSPACE_EXTENSION_ID,
    action: "calendar_create_event",
    title: "Create calendar event",
    description: "Create an event on the connected Google Calendar. Requires calendar editing access (calendar.events scope).",
    inputSchema: {
      type: "object",
      properties: {
        summary: { type: "string", description: "Event title." },
        description: { type: "string", description: "Optional event description." },
        location: { type: "string", description: "Optional event location." },
        start: { type: "string", description: "Event start as ISO datetime." },
        end: { type: "string", description: "Event end as ISO datetime." },
        timeZone: { type: "string", description: "Optional IANA time zone, e.g. 'Europe/Paris'." },
        attendees: { type: "array", items: { type: "string" }, description: "Optional attendee email addresses." },
      },
      required: ["summary", "start", "end"],
      additionalProperties: false,
    },
  },
  {
    extensionId: GOOGLE_WORKSPACE_EXTENSION_ID,
    action: "chat_list_spaces",
    title: "List Google Chat spaces",
    description: "List Google Chat spaces for the connected account. Requires Google Chat access.",
    inputSchema: {
      type: "object",
      properties: {
        maxResults: { type: "number", description: "Maximum spaces to return." },
      },
      additionalProperties: false,
    },
  },
  {
    extensionId: GOOGLE_WORKSPACE_EXTENSION_ID,
    action: "chat_list_messages",
    title: "List Google Chat messages",
    description: "List recent messages in a Google Chat space. Requires Google Chat access.",
    inputSchema: {
      type: "object",
      properties: {
        spaceId: { type: "string", description: "Chat space id or resource name, e.g. 'spaces/AAAA1234'." },
        maxResults: { type: "number", description: "Maximum messages to return." },
      },
      required: ["spaceId"],
      additionalProperties: false,
    },
  },
  {
    extensionId: GOOGLE_WORKSPACE_EXTENSION_ID,
    action: "chat_send_message",
    title: "Send Google Chat message",
    description: "Send a text message to a Google Chat space. Requires Google Chat access.",
    inputSchema: {
      type: "object",
      properties: {
        spaceId: { type: "string", description: "Chat space id or resource name, e.g. 'spaces/AAAA1234'." },
        text: { type: "string", description: "Message text." },
      },
      required: ["spaceId", "text"],
      additionalProperties: false,
    },
  },
];

type GoogleWorkspaceFlow = {
  flowId: string;
  state: string;
  verifier: string;
  redirectUri: string;
  expiresAt: number;
  status: "pending" | "connected" | "failed" | "expired";
  authUrl: string;
  account: unknown;
  error: string | null;
  server: Server;
};

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

function readStringField(value: unknown, key: string): string {
  if (!isRecord(value)) return "";
  const field = value[key];
  return typeof field === "string" ? field.trim() : "";
}

function configDir(config: ServerConfig): string {
  return dirname(config.configPath?.trim() || omnirushServerConfigPath());
}

function googleWorkspaceCredentials() {
  const clientId = process.env[GOOGLE_WORKSPACE_CLIENT_ID_ENV]?.trim() || process.env.GOOGLE_WORKSPACE_OAUTH_CLIENT_ID?.trim() || GOOGLE_WORKSPACE_DESKTOP_CLIENT_ID;
  const clientSecret = process.env[GOOGLE_WORKSPACE_CLIENT_SECRET_ENV]?.trim() || process.env[LEGACY_GOOGLE_WORKSPACE_CLIENT_SECRET_ENV]?.trim() || "";
  const tokenBrokerUrl = process.env[GOOGLE_WORKSPACE_TOKEN_BROKER_URL_ENV]?.trim() || process.env.GOOGLE_WORKSPACE_TOKEN_BROKER_URL?.trim() || "";
  const missing: string[] = [];
  if (!clientId) missing.push(GOOGLE_WORKSPACE_CLIENT_ID_ENV);
  if (!clientSecret && !tokenBrokerUrl) missing.push(GOOGLE_WORKSPACE_CLIENT_SECRET_ENV);
  const customClient = clientId !== GOOGLE_WORKSPACE_DESKTOP_CLIENT_ID;
  return { clientId, clientSecret, tokenBrokerUrl, missing, customClient };
}

export function googleWorkspaceLegacyConfigured(): boolean {
  return googleWorkspaceCredentials().missing.length === 0;
}

function googleWorkspaceDir(config: ServerConfig): string {
  return join(configDir(config), "extensions", GOOGLE_WORKSPACE_EXTENSION_ID);
}

function googleWorkspaceVaultPath(config: ServerConfig): string {
  return join(googleWorkspaceDir(config), "oauth.vault");
}

function googleWorkspacePlainTextVaultPath(config: ServerConfig): string {
  return join(googleWorkspaceDir(config), "oauth.dev-plaintext.json");
}

function googleWorkspaceVaultKeyPath(config: ServerConfig): string {
  return join(configDir(config), "vault-key");
}

function googleWorkspacePlainTextVaultEnabled() {
  return process.env.OMNIRUSH_DEV_MODE === "1" && process.env[GOOGLE_WORKSPACE_ALLOW_PLAINTEXT_VAULT_ENV] === "1";
}

function googleWorkspaceVaultMode() {
  return googleWorkspacePlainTextVaultEnabled() ? "plaintext-dev" : "encrypted";
}

function base64Url(buffer: Buffer): string {
  return buffer.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
}

function base64UrlString(value: string): string {
  return Buffer.from(value, "utf8").toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
}

function createGoogleWorkspacePkce() {
  const verifier = base64Url(randomBytes(48));
  const challenge = base64Url(createHash("sha256").update(verifier).digest());
  return { verifier, challenge };
}

async function googleWorkspaceVaultKey(config: ServerConfig): Promise<Buffer> {
  const envKey = process.env.OMNIRUSH_ENCRYPTION_KEY?.trim();
  if (envKey) return createHash("sha256").update(envKey).digest();

  const keyPath = googleWorkspaceVaultKeyPath(config);
  try {
    const raw = await readFile(keyPath, "utf8");
    const key = Buffer.from(raw.trim(), "base64");
    if (key.byteLength === 32) return key;
  } catch (error) {
    if ((error as { code?: string })?.code !== "ENOENT") throw error;
  }

  const key = randomBytes(32);
  await mkdir(dirname(keyPath), { recursive: true });
  await writeFile(keyPath, `${key.toString("base64")}\n`, { encoding: "utf8", mode: 0o600 });
  await chmod(keyPath, 0o600).catch(() => undefined);
  return key;
}

async function readGoogleWorkspaceVault(config: ServerConfig): Promise<Record<string, unknown> | null> {
  const vaultMode = googleWorkspaceVaultMode();
  const target = vaultMode === "plaintext-dev" ? googleWorkspacePlainTextVaultPath(config) : googleWorkspaceVaultPath(config);
  try {
    const raw = await readFile(target, "utf8");
    if (!raw.trim()) return null;
    if (vaultMode === "plaintext-dev") {
      const parsed = JSON.parse(raw) as unknown;
      return isRecord(parsed) ? parsed : null;
    }
    const envelope = JSON.parse(raw) as unknown;
    if (!isRecord(envelope) || typeof envelope.iv !== "string" || typeof envelope.tag !== "string" || typeof envelope.data !== "string") return null;
    const key = await googleWorkspaceVaultKey(config);
    const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(envelope.iv, "base64"));
    decipher.setAuthTag(Buffer.from(envelope.tag, "base64"));
    const decrypted = Buffer.concat([decipher.update(Buffer.from(envelope.data, "base64")), decipher.final()]).toString("utf8");
    const parsed = JSON.parse(decrypted) as unknown;
    return isRecord(parsed) ? parsed : null;
  } catch (error) {
    if ((error as { code?: string })?.code === "ENOENT") return null;
    throw error;
  }
}

async function writeGoogleWorkspaceVault(config: ServerConfig, value: Record<string, unknown>): Promise<void> {
  const vaultMode = googleWorkspaceVaultMode();
  const target = vaultMode === "plaintext-dev" ? googleWorkspacePlainTextVaultPath(config) : googleWorkspaceVaultPath(config);
  await mkdir(dirname(target), { recursive: true });
  if (vaultMode === "plaintext-dev") {
    await writeFile(target, `${JSON.stringify(value, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
    await chmod(target, 0o600).catch(() => undefined);
    return;
  }
  const key = await googleWorkspaceVaultKey(config);
  const iv = randomBytes(12);
  const cipher = createCipheriv("aes-256-gcm", key, iv);
  const encrypted = Buffer.concat([cipher.update(JSON.stringify(value), "utf8"), cipher.final()]);
  const envelope = { schemaVersion: 1, algorithm: "aes-256-gcm", iv: iv.toString("base64"), tag: cipher.getAuthTag().toString("base64"), data: encrypted.toString("base64") };
  await writeFile(target, `${JSON.stringify(envelope, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
  await chmod(target, 0o600).catch(() => undefined);
}

async function removeGoogleWorkspaceVault(config: ServerConfig): Promise<void> {
  await Promise.all([
    rm(googleWorkspaceVaultPath(config), { force: true }),
    rm(googleWorkspacePlainTextVaultPath(config), { force: true }),
  ]);
}

function googleWorkspaceSafeAccount(account: unknown) {
  if (!isRecord(account)) return null;
  return {
    accountId: googleWorkspaceAccountId({ account }),
    email: typeof account.email === "string" ? account.email : null,
    name: typeof account.name === "string" ? account.name : null,
    picture: typeof account.picture === "string" ? account.picture : null,
    sub: typeof account.sub === "string" ? account.sub : null,
  };
}

function googleWorkspaceAccountId(record: unknown): string | null {
  if (!isRecord(record)) return null;
  const account = isRecord(record.account) ? record.account : null;
  const sub = typeof account?.sub === "string" && account.sub.trim() ? account.sub.trim() : null;
  const email = typeof account?.email === "string" && account.email.trim() ? account.email.trim().toLowerCase() : null;
  return sub ?? email;
}

function googleWorkspaceAccountRecords(record: Record<string, unknown> | null): Record<string, unknown>[] {
  if (!record) return [];
  if (Array.isArray(record.accounts)) return record.accounts.filter(isRecord);
  return isRecord(record.token) ? [record] : [];
}

function googleWorkspacePrimaryRecord(record: Record<string, unknown> | null): Record<string, unknown> | null {
  const accounts = googleWorkspaceAccountRecords(record);
  if (accounts.length === 0) return null;
  const activeAccountId = typeof record?.activeAccountId === "string" ? record.activeAccountId : "";
  return accounts.find((account) => googleWorkspaceAccountId(account) === activeAccountId) ?? accounts[0] ?? null;
}

function googleWorkspacePublicAccounts(record: Record<string, unknown> | null) {
  return googleWorkspaceAccountRecords(record).map((entry) => ({
    ...googleWorkspaceSafeAccount(entry.account),
    accountId: googleWorkspaceAccountId(entry),
    scopes: Array.isArray(entry.scopes) ? entry.scopes.filter((item): item is string => typeof item === "string") : [],
    connectedAt: typeof entry.connectedAt === "string" ? entry.connectedAt : null,
  })).filter((entry) => entry.accountId !== null);
}

async function writeGoogleWorkspaceAccountsVault(config: ServerConfig, accounts: Record<string, unknown>[], activeAccountId: string | null): Promise<void> {
  if (accounts.length === 0) {
    await removeGoogleWorkspaceVault(config);
    return;
  }
  await writeGoogleWorkspaceVault(config, {
    version: 2,
    accounts,
    activeAccountId,
    updatedAt: new Date().toISOString(),
  });
}

async function upsertGoogleWorkspaceAccount(config: ServerConfig, accountRecord: Record<string, unknown>): Promise<void> {
  const accountId = googleWorkspaceAccountId(accountRecord);
  if (!accountId) throw new Error("Google account identifier is unavailable.");
  const current = await readGoogleWorkspaceVault(config);
  const accounts = googleWorkspaceAccountRecords(current);
  const nextAccounts = [accountRecord, ...accounts.filter((entry) => googleWorkspaceAccountId(entry) !== accountId)];
  await writeGoogleWorkspaceAccountsVault(config, nextAccounts, accountId);
}

function googleWorkspaceStatusPayload(record: Record<string, unknown> | null = null, extra: Record<string, unknown> = {}) {
  const credentials = googleWorkspaceCredentials();
  const primary = googleWorkspacePrimaryRecord(record);
  return {
    configured: credentials.missing.length === 0,
    missing: credentials.missing,
    customClient: credentials.customClient,
    vault: googleWorkspaceVaultMode(),
    connected: googleWorkspaceAccountRecords(record).length > 0,
    account: googleWorkspaceSafeAccount(primary?.account),
    accounts: googleWorkspacePublicAccounts(record),
    activeAccountId: googleWorkspaceAccountId(primary),
    scopes: Array.isArray(primary?.scopes) ? primary.scopes.filter((item): item is string => typeof item === "string") : [],
    connectedAt: typeof primary?.connectedAt === "string" ? primary.connectedAt : null,
    error: null,
    testStatus: null,
    smokeTest: null,
    ...extra,
  };
}

async function fetchGoogleJson(url: string, init: RequestInit = {}) {
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), GOOGLE_WORKSPACE_API_TIMEOUT_MS);
  let response: Response;
  try {
    response = await externalFetch(url, { ...init, signal: controller.signal });
  } catch (error) {
    if (error instanceof Error && error.name === "AbortError") throw new Error("Google request timed out. Check your connection and try again.");
    throw error;
  } finally {
    clearTimeout(timeout);
  }
  const text = await response.text();
  let payload: unknown = null;
  if (text.trim()) {
    try { payload = JSON.parse(text); } catch { payload = { raw: text }; }
  }
  if (!response.ok) {
    const details = isRecord(payload)
      ? isRecord(payload.error) && typeof payload.error.message === "string"
        ? payload.error.message
        : typeof payload.error_description === "string"
          ? payload.error_description
          : typeof payload.error === "string"
            ? payload.error
            : response.statusText
      : response.statusText;
    throw new Error(`Google request failed (${response.status}): ${details}`);
  }
  return payload;
}

async function fetchGoogleUserInfo(accessToken: string) {
  return fetchGoogleJson("https://www.googleapis.com/oauth2/v3/userinfo", { headers: { Authorization: `Bearer ${accessToken}` } });
}

async function fetchGoogleWorkspaceTokenBrokerJson(tokenBrokerUrl: string, body: Record<string, unknown>) {
  return fetchGoogleJson(tokenBrokerUrl, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
}

async function exchangeGoogleWorkspaceCode(input: { code: string; redirectUri: string; verifier: string }) {
  const { clientId, clientSecret, tokenBrokerUrl, missing } = googleWorkspaceCredentials();
  if (missing.length > 0) throw new Error(`Missing Google OAuth configuration: ${missing.join(", ")}`);
  if (tokenBrokerUrl) {
    return fetchGoogleWorkspaceTokenBrokerJson(tokenBrokerUrl, {
      grantType: "authorization_code",
      provider: GOOGLE_WORKSPACE_EXTENSION_ID,
      clientId,
      code: input.code,
      codeVerifier: input.verifier,
      redirectUri: input.redirectUri,
    });
  }
  return fetchGoogleJson("https://oauth2.googleapis.com/token", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      client_id: clientId,
      client_secret: clientSecret,
      code: input.code,
      code_verifier: input.verifier,
      grant_type: "authorization_code",
      redirect_uri: input.redirectUri,
    }),
  });
}

async function refreshGoogleWorkspaceVault(record: Record<string, unknown>) {
  const token = isRecord(record.token) ? record.token : null;
  const expiresAt = Number(token?.expiresAt ?? 0);
  const accessToken = typeof token?.accessToken === "string" ? token.accessToken : "";
  const refreshToken = typeof token?.refreshToken === "string" ? token.refreshToken : "";
  if (accessToken && expiresAt > Date.now() + 60_000) return record;
  if (!refreshToken) throw new Error("Google Workspace refresh token is missing. Reconnect Google Workspace.");
  const { clientId, clientSecret, tokenBrokerUrl, missing } = googleWorkspaceCredentials();
  if (missing.length > 0) throw new Error(`Missing Google OAuth configuration: ${missing.join(", ")}`);
  const refreshed = tokenBrokerUrl
    ? await fetchGoogleWorkspaceTokenBrokerJson(tokenBrokerUrl, { grantType: "refresh_token", provider: GOOGLE_WORKSPACE_EXTENSION_ID, clientId, refreshToken })
    : await fetchGoogleJson("https://oauth2.googleapis.com/token", {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: new URLSearchParams({ client_id: clientId, client_secret: clientSecret, grant_type: "refresh_token", refresh_token: refreshToken }),
    });
  if (!isRecord(refreshed) || typeof refreshed.access_token !== "string") throw new Error("Google OAuth refresh did not return an access token.");
  const next = {
    ...record,
    scopes: typeof refreshed.scope === "string" ? refreshed.scope.split(/\s+/).filter(Boolean) : record.scopes,
    token: {
      accessToken: refreshed.access_token,
      refreshToken: typeof refreshed.refresh_token === "string" ? refreshed.refresh_token : refreshToken,
      expiresAt: Date.now() + Number(refreshed.expires_in ?? 3600) * 1000,
    },
    updatedAt: new Date().toISOString(),
  };
  return next;
}

async function googleWorkspaceAccessToken(config: ServerConfig): Promise<{ record: Record<string, unknown>; accessToken: string }> {
  const vault = await readGoogleWorkspaceVault(config);
  const record = googleWorkspacePrimaryRecord(vault);
  if (!record) throw new ApiError(400, "google_workspace_not_connected", "Connect Google Workspace in OmniRush.ai Settings to use this tool.");
  const refreshed = await refreshGoogleWorkspaceVault(record);
  const refreshedAccountId = googleWorkspaceAccountId(refreshed);
  if (refreshedAccountId) {
    const nextAccounts = googleWorkspaceAccountRecords(vault).map((entry) => googleWorkspaceAccountId(entry) === refreshedAccountId ? refreshed : entry);
    await writeGoogleWorkspaceAccountsVault(config, nextAccounts, refreshedAccountId);
  }
  const token = isRecord(refreshed.token) ? refreshed.token : null;
  const accessToken = typeof token?.accessToken === "string" ? token.accessToken : "";
  if (!accessToken) throw new Error("Google Workspace access token is unavailable. Reconnect Google Workspace.");
  return { record: refreshed, accessToken };
}

function multipartRelatedBody(metadata: Record<string, unknown>, content: string, boundary: string): string {
  return [
    `--${boundary}`,
    "Content-Type: application/json; charset=UTF-8",
    "",
    JSON.stringify(metadata),
    `--${boundary}`,
    "Content-Type: text/plain; charset=UTF-8",
    "",
    content,
    `--${boundary}--`,
    "",
  ].join("\r\n");
}

function stringArrayField(value: unknown): string[] {
  return Array.isArray(value) ? value.filter((item): item is string => typeof item === "string" && item.trim().length > 0) : [];
}

type GmailDraftAttachmentRequest = {
  path?: string;
  url?: string;
  filename?: string;
  mimeType?: string;
};

type GmailDraftAttachment = {
  filename: string;
  mimeType: string;
  content: Buffer;
};

type GmailAttachmentFetch = (input: string | URL, init?: RequestInit) => Promise<Response>;
type GmailAttachmentAddressResolver = (hostname: string, options: LookupAllOptions) => Promise<LookupAddress[]>;

function gmailHeaderValue(value: string): string {
  return value.replace(/[\r\n]+/g, " ").trim();
}

function gmailMimeParameter(value: string): string {
  return gmailHeaderValue(value).replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
}

function base64MimeContent(buffer: Buffer): string {
  const chunks = buffer.toString("base64").match(/.{1,76}/g);
  return chunks ? chunks.join("\r\n") : "";
}

function gmailAttachmentMimeType(path: string, override: string | undefined): string {
  const provided = typeof override === "string" ? override.trim() : "";
  if (provided && /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(provided)) return provided;
  const lowered = path.toLowerCase();
  if (lowered.endsWith(".pdf")) return "application/pdf";
  if (lowered.endsWith(".png")) return "image/png";
  if (lowered.endsWith(".jpg") || lowered.endsWith(".jpeg")) return "image/jpeg";
  if (lowered.endsWith(".gif")) return "image/gif";
  if (lowered.endsWith(".csv")) return "text/csv";
  if (lowered.endsWith(".txt")) return "text/plain";
  return "application/octet-stream";
}

function gmailDraftAttachmentRequests(value: unknown): GmailDraftAttachmentRequest[] {
  if (!Array.isArray(value)) return [];
  const attachments: GmailDraftAttachmentRequest[] = [];
  for (const item of value) {
    if (!isRecord(item)) continue;
    const path = typeof item.path === "string" ? item.path.trim() : "";
    const url = typeof item.url === "string" ? item.url.trim() : "";
    if ((path && url) || (!path && !url)) throw new ApiError(400, "invalid_payload", "Each attachment must provide exactly one of url or path");
    const filename = typeof item.filename === "string" && item.filename.trim() ? item.filename.trim() : undefined;
    const mimeType = typeof item.mimeType === "string" && item.mimeType.trim() ? item.mimeType.trim() : undefined;
    attachments.push({ ...(path ? { path } : {}), ...(url ? { url } : {}), filename, mimeType });
  }
  return attachments;
}

function pushUniqueResolvedPath(paths: string[], path: string) {
  const trimmed = path.trim();
  if (!trimmed) return;
  const resolved = resolve(trimmed);
  if (!paths.includes(resolved)) paths.push(resolved);
}

function isPathWithinRoot(path: string, root: string): boolean {
  const child = relative(root, path);
  return child === "" || (!!child && !child.startsWith("..") && !isAbsolute(child));
}

function gmailAttachmentAllowedRoots(config: ServerConfig): string[] {
  const roots: string[] = [];
  for (const workspace of config.workspaces) pushUniqueResolvedPath(roots, workspace.path);
  for (const root of config.authorizedRoots) pushUniqueResolvedPath(roots, root);
  return roots;
}

function gmailAttachmentSearchRoots(config: ServerConfig, context: Record<string, unknown>, allowedRoots: string[]): string[] {
  const roots: string[] = [];
  const directory = readStringField(context, "directory");
  const worktree = readStringField(context, "worktree");
  if (directory) pushUniqueResolvedPath(roots, directory);
  if (worktree) pushUniqueResolvedPath(roots, worktree);
  for (const workspace of config.workspaces) pushUniqueResolvedPath(roots, workspace.path);
  for (const root of allowedRoots) pushUniqueResolvedPath(roots, root);
  return roots.filter((root) => allowedRoots.some((allowedRoot) => isPathWithinRoot(root, allowedRoot)));
}

function isFileNotFoundError(error: unknown): boolean {
  return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
}

async function assertGmailAttachmentFile(path: string) {
  const info = await stat(path);
  if (!info.isFile()) throw new ApiError(400, "invalid_payload", "Attachment path must point to a file", { path });
  if (info.size > GMAIL_ATTACHMENT_MAX_BYTES) throw new ApiError(413, "file_too_large", `Gmail draft attachments support files up to ${GMAIL_ATTACHMENT_MAX_BYTES} bytes.`, { path, size: info.size, maxBytes: GMAIL_ATTACHMENT_MAX_BYTES });
}

async function gmailAttachmentRealRoots(allowedRoots: string[]): Promise<string[]> {
  const realRoots: string[] = [];
  for (const root of allowedRoots) {
    try {
      pushUniqueResolvedPath(realRoots, await realpath(root));
    } catch (error) {
      if (!isFileNotFoundError(error)) throw error;
    }
  }
  return realRoots;
}

async function assertGmailAttachmentRealPath(path: string, allowedRoots: string[]): Promise<string> {
  const realCandidate = await realpath(path);
  const realRoots = await gmailAttachmentRealRoots(allowedRoots);
  if (!realRoots.some((root) => isPathWithinRoot(realCandidate, root))) {
    throw new ApiError(400, "invalid_payload", "Attachment path must resolve inside an authorized workspace root", { path });
  }
  await assertGmailAttachmentFile(realCandidate);
  return realCandidate;
}

async function resolveGmailAttachmentPath(config: ServerConfig, context: Record<string, unknown>, path: string): Promise<string> {
  const allowedRoots = gmailAttachmentAllowedRoots(config);
  if (!allowedRoots.length) throw new ApiError(400, "invalid_payload", "No authorized workspace roots are available for Gmail attachments");
  if (isAbsolute(path)) {
    const resolved = resolve(path);
    if (!allowedRoots.some((root) => isPathWithinRoot(resolved, root))) throw new ApiError(400, "invalid_payload", "Attachment path must be inside an authorized workspace root", { path });
    await assertGmailAttachmentFile(resolved);
    return assertGmailAttachmentRealPath(resolved, allowedRoots);
  }

  for (const root of gmailAttachmentSearchRoots(config, context, allowedRoots)) {
    const resolved = resolve(root, path);
    if (!isPathWithinRoot(resolved, root) || !allowedRoots.some((allowedRoot) => isPathWithinRoot(resolved, allowedRoot))) continue;
    try {
      await assertGmailAttachmentFile(resolved);
      return await assertGmailAttachmentRealPath(resolved, allowedRoots);
    } catch (error) {
      if (isFileNotFoundError(error)) continue;
      throw error;
    }
  }

  throw new ApiError(400, "invalid_payload", "Attachment file was not found in an authorized workspace root", { path });
}

// Attachment url validation is unconditional: unlike the managed MCP url
// guard, it must hold even under OMNIRUSH_DEV_MODE.
function assertGmailAttachmentUrl(rawUrl: string): URL {
  let parsed: URL;
  try {
    parsed = new URL(rawUrl);
  } catch {
    throw new ApiError(400, "invalid_payload", "Attachment url must be a valid https URL", { url: rawUrl });
  }
  const hostname = parsed.hostname.replace(/^\[|\]$/g, "");
  const privateHost = hostname === "localhost" || hostname.endsWith(".localhost") || hostname.endsWith(".local") || (isIP(hostname) !== 0 && isLocalManagedMcpPrivateAddress(hostname));
  if (parsed.protocol !== "https:" || parsed.username || parsed.password || privateHost) {
    throw new ApiError(400, "invalid_payload", "Attachment url must be a public https URL", { url: rawUrl });
  }
  return parsed;
}

// Hostnames must resolve to public addresses, unconditionally, like the
// literal-address checks above. externalFetch re-resolves when it connects,
// so this validates every answer we can observe but cannot pin the socket to
// it the way the managed MCP undici dispatcher does.
async function assertGmailAttachmentHostPublic(url: URL): Promise<void> {
  const hostname = url.hostname.replace(/^\[|\]$/g, "");
  if (isIP(hostname) !== 0) return;
  let addresses: LookupAddress[];
  try {
    addresses = await lookup(hostname, { all: true, verbatim: true });
  } catch {
    throw new ApiError(502, "attachment_fetch_failed", "Attachment url hostname could not be resolved", { hostname });
  }
  if (!addresses.length || addresses.some((entry) => isLocalManagedMcpPrivateAddress(entry.address))) {
    throw new ApiError(400, "invalid_payload", "Attachment url must resolve to a public address", { hostname });
  }
}

const resolveGmailAttachmentAddresses: GmailAttachmentAddressResolver = (hostname, options) => lookup(hostname, options);

function validateGmailAttachmentAddresses(hostname: string, addresses: LookupAddress[]): void {
  if (!addresses.length) throw new Error(`Attachment hostname ${hostname} did not resolve.`);
  const privateAddress = addresses.find((entry) => isLocalManagedMcpPrivateAddress(entry.address));
  if (privateAddress) {
    throw new Error(`Attachment hostname ${hostname} resolved to a private or reserved address (${privateAddress.address}).`);
  }
}

/**
 * Resolves and validates the attachment host inside the socket connector. The
 * same answers are handed to net.connect, closing the DNS-rebinding window
 * between a preflight lookup and the actual connection.
 */
export function createGmailAttachmentPublicLookup(
  resolver: GmailAttachmentAddressResolver = resolveGmailAttachmentAddresses,
): LookupFunction {
  return (hostname, options, callback) => {
    const lookupOptions: LookupAllOptions = { ...options, all: true, verbatim: true };
    void resolver(hostname, lookupOptions).then((addresses) => {
      try {
        validateGmailAttachmentAddresses(hostname, addresses);
      } catch (error) {
        callback(error instanceof Error ? error : new Error("Attachment hostname lookup failed."), []);
        return;
      }
      if (options.all) {
        callback(null, addresses);
        return;
      }
      const first = addresses[0];
      callback(null, first.address, first.family);
    }, (error: unknown) => {
      callback(error instanceof Error ? error : new Error("Attachment hostname lookup failed."), []);
    });
  };
}

const gmailAttachmentDispatcher = new Agent({
  connect: {
    lookup: createGmailAttachmentPublicLookup(),
    autoSelectFamily: true,
    autoSelectFamilyAttemptTimeout: 1_000,
  },
});

async function defaultGmailAttachmentFetch(input: string | URL, init?: RequestInit): Promise<Response> {
  // DOM and Undici expose structurally equivalent fetch types from separate
  // declarations. Keep the conversion at this transport boundary.
  const requestInit = { ...init, dispatcher: gmailAttachmentDispatcher } as unknown as UndiciRequestInit;
  return await undiciFetch(input, requestInit) as unknown as Response;
}

let gmailAttachmentFetch: GmailAttachmentFetch = defaultGmailAttachmentFetch;

export function setGmailAttachmentFetchForTests(fetchImpl?: GmailAttachmentFetch): void {
  gmailAttachmentFetch = fetchImpl ?? defaultGmailAttachmentFetch;
}

function gmailAttachmentFilenameFromResponse(url: URL, contentDisposition: string | null): string {
  const disposition = contentDisposition ?? "";
  const quoted = /filename\s*=\s*"([^"]+)"/i.exec(disposition)?.[1];
  const bare = quoted ? undefined : /filename\s*=\s*([^;\s]+)/i.exec(disposition)?.[1];
  const fromDisposition = (quoted ?? bare ?? "").trim();
  if (fromDisposition) return basename(fromDisposition);
  try {
    const fromPath = basename(decodeURIComponent(url.pathname));
    if (fromPath && fromPath !== "/") return fromPath;
  } catch {
    // fall through to the generic name on malformed percent-encoding
  }
  return "attachment";
}

async function readGmailAttachmentResponse(response: Response, url: string): Promise<Buffer> {
  const oversize = () => new ApiError(413, "file_too_large", `Gmail draft attachments support files up to ${GMAIL_ATTACHMENT_MAX_BYTES} bytes.`, { url, maxBytes: GMAIL_ATTACHMENT_MAX_BYTES });
  const declaredLength = Number(response.headers.get("content-length") ?? "");
  if (Number.isFinite(declaredLength) && declaredLength > GMAIL_ATTACHMENT_MAX_BYTES) throw oversize();
  const reader = response.body?.getReader();
  if (!reader) {
    const buffer = Buffer.from(await response.arrayBuffer());
    if (buffer.byteLength > GMAIL_ATTACHMENT_MAX_BYTES) throw oversize();
    return buffer;
  }
  const chunks: Buffer[] = [];
  let total = 0;
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    if (!value) continue;
    total += value.byteLength;
    if (total > GMAIL_ATTACHMENT_MAX_BYTES) {
      await reader.cancel().catch(() => undefined);
      throw oversize();
    }
    chunks.push(Buffer.from(value));
  }
  return Buffer.concat(chunks);
}

async function fetchGmailUrlAttachment(request: GmailDraftAttachmentRequest, url: string): Promise<GmailDraftAttachment> {
  let currentUrl = assertGmailAttachmentUrl(url);
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), GOOGLE_WORKSPACE_API_TIMEOUT_MS);
  try {
    for (let redirects = 0; ; redirects += 1) {
      await assertGmailAttachmentHostPublic(currentUrl);
      let response: Response;
      try {
        response = await gmailAttachmentFetch(currentUrl, { redirect: "manual", signal: controller.signal });
      } catch (error) {
        if (error instanceof Error && error.name === "AbortError") throw new ApiError(502, "attachment_fetch_failed", "Attachment download timed out", { url });
        throw new ApiError(502, "attachment_fetch_failed", `Attachment download failed: ${error instanceof Error ? error.message : String(error)}`, { url });
      }
      if (response.status >= 300 && response.status < 400) {
        await response.body?.cancel().catch(() => undefined);
        const location = response.headers.get("location");
        if (!location) throw new ApiError(502, "attachment_fetch_failed", "Attachment redirect did not include a location", { url });
        if (redirects >= GMAIL_ATTACHMENT_REDIRECT_LIMIT) throw new ApiError(400, "invalid_payload", "Attachment url followed too many redirects", { url });
        currentUrl = assertGmailAttachmentUrl(new URL(location, currentUrl).toString());
        continue;
      }
      if (!response.ok) throw new ApiError(502, "attachment_fetch_failed", `Attachment download failed (${response.status})`, { url, status: response.status });
      const content = await readGmailAttachmentResponse(response, url);
      const filename = gmailHeaderValue(request.filename || gmailAttachmentFilenameFromResponse(currentUrl, response.headers.get("content-disposition")));
      if (!filename) throw new ApiError(400, "invalid_payload", "Attachment filename is required", { url });
      const responseMimeType = (response.headers.get("content-type") ?? "").split(";")[0]?.trim();
      const mimeType = gmailAttachmentMimeType(currentUrl.pathname, request.mimeType || responseMimeType || undefined);
      return { filename, mimeType, content };
    }
  } finally {
    clearTimeout(timeout);
  }
}

async function loadGmailDraftAttachments(config: ServerConfig, context: Record<string, unknown>, requests: GmailDraftAttachmentRequest[]): Promise<GmailDraftAttachment[]> {
  const attachments: GmailDraftAttachment[] = [];
  for (const request of requests) {
    if (request.url) {
      attachments.push(await fetchGmailUrlAttachment(request, request.url));
      continue;
    }
    const path = await resolveGmailAttachmentPath(config, context, request.path ?? "");
    const content = await readFile(path);
    const filename = gmailHeaderValue(request.filename || basename(path));
    if (!filename) throw new ApiError(400, "invalid_payload", "Attachment filename is required", { path: request.path });
    attachments.push({ filename, mimeType: gmailAttachmentMimeType(path, request.mimeType), content });
  }
  return attachments;
}

function toCrlf(value: string): string {
  return value.replace(/\r\n?|\n/g, "\r\n");
}

function encodeMimeWord(value: string): string {
  if (/^[\x20-\x7e]*$/.test(value)) return value;
  const words: string[] = [];
  let chunk = "";
  let chunkBytes = 0;
  for (const character of value) {
    const characterBytes = Buffer.byteLength(character, "utf8");
    if (chunk && chunkBytes + characterBytes > 45) {
      words.push(chunk);
      chunk = "";
      chunkBytes = 0;
    }
    chunk += character;
    chunkBytes += characterBytes;
  }
  if (chunk) words.push(chunk);
  return words.map((word) => `=?UTF-8?B?${Buffer.from(word, "utf8").toString("base64")}?=`).join(" ");
}

function foldHeaderLine(line: string): string {
  if (line.length <= GMAIL_HEADER_FOLD_LIMIT) return line;
  const words = line.split(" ");
  const lines: string[] = [];
  let current = "";
  for (const word of words) {
    if (!current) {
      current = word;
      continue;
    }
    if (current.length + 1 + word.length > GMAIL_HEADER_FOLD_LIMIT) {
      lines.push(current);
      current = ` ${word}`;
      continue;
    }
    current += ` ${word}`;
  }
  if (current) lines.push(current);
  return lines.join("\r\n");
}

function gmailHtmlDivs(text: string): string {
  return text.replace(/\r\n?/g, "\n").split("\n").map((line) => line ? `<div>${escapeHtml(line)}</div>` : "<div><br></div>").join("");
}

const GMAIL_HTML_BREAK_TAGS = new Set(["p", "div", "tr", "li", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "table", "ul", "ol"]);

// Character scan instead of regex tag-stripping: nested or malformed markup
// can reassemble into tags after a single-pass replace, and an unterminated
// tag consumes the rest of the input the way browsers treat it.
function stripGmailHtmlMarkup(html: string): string {
  let text = "";
  let index = 0;
  while (index < html.length) {
    const character = html[index];
    if (character !== "<") {
      text += character;
      index += 1;
      continue;
    }
    const tagEnd = html.indexOf(">", index + 1);
    if (tagEnd === -1) break;
    const rawTag = html.slice(index + 1, tagEnd).trim();
    index = tagEnd + 1;
    const closing = rawTag.startsWith("/");
    const name = (closing ? rawTag.slice(1) : rawTag).split(/[\s/]/, 1)[0]?.toLowerCase() ?? "";
    if (!closing && (name === "script" || name === "style")) {
      const closeMatch = new RegExp(`</${name}\\b[^>]*>`, "i").exec(html.slice(index));
      if (!closeMatch) break;
      index += closeMatch.index + closeMatch[0].length;
      continue;
    }
    if (name === "br" || (closing && GMAIL_HTML_BREAK_TAGS.has(name))) text += "\n";
  }
  return text;
}

function gmailHtmlToText(html: string): string {
  const text = stripGmailHtmlMarkup(html)
    .replace(/&nbsp;/gi, " ")
    .replace(/&#x([0-9a-f]+);/gi, (match, hex: string) => {
      const code = Number.parseInt(hex, 16);
      return code >= 0 && code <= 0x10ffff ? String.fromCodePoint(code) : match;
    })
    .replace(/&#(\d+);/g, (match, decimal: string) => {
      const code = Number(decimal);
      return Number.isInteger(code) && code >= 0 && code <= 0x10ffff ? String.fromCodePoint(code) : match;
    })
    .replace(/&lt;/gi, "<")
    .replace(/&gt;/gi, ">")
    .replace(/&quot;/gi, "\"")
    .replace(/&apos;/gi, "'")
    .replace(/&amp;/gi, "&");
  return text.replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
}

function gmailRawMessage(input: { to: string[]; cc?: string[]; bcc?: string[]; subject: string; body: string; html?: string; headers?: { name: string; value: string }[]; attachments?: GmailDraftAttachment[] }): string {
  const headers = [
    `To: ${gmailHeaderValue(input.to.join(", "))}`,
    input.cc?.length ? `Cc: ${gmailHeaderValue(input.cc.join(", "))}` : null,
    input.bcc?.length ? `Bcc: ${gmailHeaderValue(input.bcc.join(", "))}` : null,
    `Subject: ${encodeMimeWord(gmailHeaderValue(input.subject))}`,
    ...(input.headers ?? []).map((header) => `${header.name}: ${gmailHeaderValue(header.value)}`),
    "MIME-Version: 1.0",
  ].filter((line): line is string => typeof line === "string").map(foldHeaderLine);
  const attachments = input.attachments ?? [];
  const body = toCrlf(normalizeGmailDraftBody(input.body));
  const html = typeof input.html === "string" ? toCrlf(input.html) : null;
  const textPartLines = [
    "Content-Type: text/plain; charset=UTF-8",
    "Content-Transfer-Encoding: 8bit",
    "",
    body,
  ];
  const alternativePartLines = () => {
    const boundary = `omnirush-alt-${randomBytes(16).toString("hex")}`;
    return [
      foldHeaderLine(`Content-Type: multipart/alternative; boundary="${boundary}"`),
      "",
      `--${boundary}`,
      ...textPartLines,
      `--${boundary}`,
      "Content-Type: text/html; charset=UTF-8",
      "Content-Transfer-Encoding: 8bit",
      "",
      html ?? "",
      `--${boundary}--`,
    ];
  };
  let raw: string;
  if (!attachments.length) {
    raw = [...headers, ...(html === null ? textPartLines : alternativePartLines())].join("\r\n");
  } else {
    const boundary = `omnirush-${randomBytes(16).toString("hex")}`;
    raw = [
      ...headers,
      foldHeaderLine(`Content-Type: multipart/mixed; boundary="${boundary}"`),
      "",
      `--${boundary}`,
      ...(html === null ? textPartLines : alternativePartLines()),
      ...attachments.flatMap((attachment) => [
        `--${boundary}`,
        foldHeaderLine(`Content-Type: ${attachment.mimeType}; name="${gmailMimeParameter(attachment.filename)}"`),
        foldHeaderLine(`Content-Disposition: attachment; filename="${gmailMimeParameter(attachment.filename)}"`),
        "Content-Transfer-Encoding: base64",
        "",
        base64MimeContent(attachment.content),
      ]),
      `--${boundary}--`,
      "",
    ].join("\r\n");
  }
  const sizeBytes = Buffer.byteLength(raw, "utf8");
  if (sizeBytes > GMAIL_RAW_MESSAGE_MAX_BYTES) {
    throw new ApiError(413, "gmail_draft_too_large", `Gmail drafts support messages up to ${GMAIL_RAW_MESSAGE_MAX_BYTES} bytes including encoded attachments.`, { sizeBytes, maxBytes: GMAIL_RAW_MESSAGE_MAX_BYTES });
  }
  return raw;
}

// Generated prose is sometimes hard-wrapped before it reaches Gmail. Those
// literal breaks become visible after send, especially on narrow screens.
function normalizeGmailDraftBody(body: string): string {
  return body.replace(/\r\n?/g, "\n").replace(/[^\n]+(?:\n[^\n]+)*/g, (block) => {
    const lines = block.split("\n");
    const hasStructure = lines.some((line) => {
      const trimmed = line.trimStart();
      return trimmed.length !== line.length || /^(?:[-*+•]\s|\d+[.)]\s|>|```|~~~)/.test(trimmed);
    });
    if (hasStructure) return block;

    const cleanedLines = lines.map((line) => line
      .replace(/^#{1,6}\s+/, "")
      .replace(/\*\*([^*\n]+)\*\*/g, "$1")
      .replace(/__([^_\n]+)__/g, "$1")
      .replace(/`([^`\n]+)`/g, "$1"));
    const looksHardWrapped = lines.slice(0, -1).every((line) => line.trimEnd().length >= GMAIL_HARD_WRAP_MIN_LINE_LENGTH);
    return lines.length > 1 && looksHardWrapped ? cleanedLines.map((line) => line.trim()).join(" ") : cleanedLines.join("\n");
  });
}

function splitEmailHeader(value: string): string[] {
  const entries: string[] = [];
  let current = "";
  let quoted = false;
  let escaped = false;
  let angleDepth = 0;
  for (const character of value) {
    if (escaped) {
      current += character;
      escaped = false;
      continue;
    }
    if (character === "\\" && quoted) {
      current += character;
      escaped = true;
      continue;
    }
    if (character === "\"") quoted = !quoted;
    if (!quoted && character === "<") angleDepth += 1;
    if (!quoted && character === ">" && angleDepth > 0) angleDepth -= 1;
    if (character === "," && !quoted && angleDepth === 0) {
      const entry = current.trim();
      if (entry) entries.push(entry);
      current = "";
      continue;
    }
    current += character;
  }
  const entry = current.trim();
  if (entry) entries.push(entry);
  return entries;
}

function emailHeaderKey(value: string): string {
  const match = /<([^<>]+)>/.exec(value);
  return (match?.[1] ?? value).trim().toLowerCase();
}

function uniqueEmailHeaders(values: string[], exclude: string[]): string[] {
  const seen = new Set(exclude.map((value) => value.trim().toLowerCase()).filter(Boolean));
  const recipients: string[] = [];
  for (const value of values.flatMap(splitEmailHeader)) {
    const key = emailHeaderKey(value);
    if (!key || !key.includes("@") || seen.has(key)) continue;
    seen.add(key);
    recipients.push(value);
  }
  return recipients;
}

function gmailReplySubject(subject: string): string {
  const trimmed = subject.trim();
  if (!trimmed) return "Re:";
  return /^re\s*:/i.test(trimmed) ? trimmed : `Re: ${trimmed}`;
}

function gmailReplyReferences(references: string, messageId: string): string {
  const entries = references.trim().split(/\s+/).filter(Boolean);
  return entries.includes(messageId) ? entries.join(" ") : [...entries, messageId].join(" ");
}

function formatGmailQuoteDate(value: string): string {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value;
  return `${UTC_WEEKDAYS[date.getUTCDay()]}, ${String(date.getUTCDate()).padStart(2, "0")} ${UTC_MONTHS[date.getUTCMonth()]} ${date.getUTCFullYear()} at ${String(date.getUTCHours()).padStart(2, "0")}:${String(date.getUTCMinutes()).padStart(2, "0")} UTC`;
}

function gmailBodyHasQuotedHistory(body: string): boolean {
  return /^>\s?/m.test(body) && /^.*wrote:\s*$/m.test(body);
}

function gmailQuoteAttribution(input: { from: string; date: string }): string {
  return input.date ? `On ${formatGmailQuoteDate(input.date)}, ${input.from} wrote:` : `${input.from} wrote:`;
}

function truncateGmailQuoteBody(body: string): { text: string; truncated: boolean } {
  const normalized = body.replace(/\r\n?/g, "\n");
  if (normalized.length <= GMAIL_QUOTE_BODY_LIMIT) return { text: normalized, truncated: false };
  return { text: normalized.slice(0, GMAIL_QUOTE_BODY_LIMIT), truncated: true };
}

function buildGmailQuoteBlock(input: { from: string; date: string; body: string }): string {
  const { text, truncated } = truncateGmailQuoteBody(input.body);
  const quotedLines = text.split("\n").map((line) => `> ${line}`);
  if (truncated) quotedLines.push("> [message trimmed]");
  return [gmailQuoteAttribution(input), ...quotedLines].join("\n");
}

// Gmail collapses quoted history behind its trimmed-content ellipsis only for
// the gmail_quote/gmail_attr blockquote structure; the quoted content is the
// escaped text rendition so the plain and HTML parts always agree.
function buildGmailQuoteHtml(input: { from: string; date: string; body: string }): string {
  const { text, truncated } = truncateGmailQuoteBody(input.body);
  const quoted = truncated ? `${text}\n[message trimmed]` : text;
  return `<div class="gmail_quote"><div dir="ltr" class="gmail_attr">${escapeHtml(gmailQuoteAttribution(input))}</div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px solid #ccc;padding-left:1ex">${gmailHtmlDivs(quoted)}</blockquote></div>`;
}

function gmailDraftMessageId(value: unknown): string | null {
  if (!isRecord(value)) return null;
  const message = isRecord(value.message) ? value.message : null;
  return typeof message?.id === "string" ? message.id : null;
}

function gmailDraftThreadId(value: unknown): string | null {
  if (!isRecord(value)) return null;
  const message = isRecord(value.message) ? value.message : null;
  return typeof message?.threadId === "string" ? message.threadId : null;
}

function gmailDraftUrl(messageId: string | null): string | null {
  return messageId ? `https://mail.google.com/mail/u/0/#drafts?compose=${encodeURIComponent(messageId)}` : null;
}

function gmailThreadUrl(threadId: string | null): string | null {
  return threadId ? `https://mail.google.com/mail/u/0/#all/${encodeURIComponent(threadId)}` : null;
}

function requireScope(record: Record<string, unknown>, scope: string, code: string, message: string) {
  const scopes = Array.isArray(record.scopes) ? record.scopes : [];
  if (!scopes.includes(scope)) throw new ApiError(403, code, message);
}

function requireGmailReadScope(record: Record<string, unknown>) {
  requireScope(record, GMAIL_READONLY_SCOPE, "google_gmail_read_not_granted", "Gmail read access is not granted for this account. Reconnect Google Workspace with Gmail read access enabled.");
}

function requireCalendarWriteScope(record: Record<string, unknown>) {
  requireScope(record, CALENDAR_EVENTS_SCOPE, "google_calendar_write_not_granted", "Calendar editing access is not granted for this account. Reconnect Google Workspace with calendar editing enabled.");
}

function requireChatScope(record: Record<string, unknown>, scope: string) {
  requireScope(record, scope, "google_chat_not_granted", "Google Chat access is not granted for this account. Reconnect Google Workspace with Google Chat enabled.");
}

function gmailHeader(payload: unknown, name: string): string {
  if (!isRecord(payload) || !Array.isArray(payload.headers)) return "";
  const header = payload.headers.filter(isRecord).find((entry) => typeof entry.name === "string" && entry.name.toLowerCase() === name.toLowerCase());
  return header && typeof header.value === "string" ? header.value : "";
}

function gmailMessageSummary(message: unknown) {
  if (!isRecord(message)) return null;
  return {
    id: typeof message.id === "string" ? message.id : null,
    threadId: typeof message.threadId === "string" ? message.threadId : null,
    snippet: typeof message.snippet === "string" ? message.snippet : null,
    labelIds: Array.isArray(message.labelIds) ? message.labelIds.filter((item): item is string => typeof item === "string") : [],
    subject: gmailHeader(message.payload, "Subject"),
    from: gmailHeader(message.payload, "From"),
    to: gmailHeader(message.payload, "To"),
    bcc: gmailHeader(message.payload, "Bcc"),
    date: gmailHeader(message.payload, "Date"),
  };
}

function decodeBase64Url(data: string): Buffer {
  return Buffer.from(data.replace(/-/g, "+").replace(/_/g, "/"), "base64");
}

function decodeGmailBody(data: string): string {
  return decodeBase64Url(data).toString("utf8");
}

function gmailMessageText(payload: unknown, mimePrefix = "text/plain"): string {
  if (!isRecord(payload)) return "";
  const mimeType = typeof payload.mimeType === "string" ? payload.mimeType : "";
  const data = isRecord(payload.body) && typeof payload.body.data === "string" ? payload.body.data : "";
  if (mimeType.startsWith(mimePrefix) && data) return decodeGmailBody(data);
  const parts = Array.isArray(payload.parts) ? payload.parts : [];
  for (const part of parts) {
    const text = gmailMessageText(part, mimePrefix);
    if (text) return text;
  }
  return "";
}

function gmailAttachmentMetadata(payload: unknown) {
  const attachments: { attachmentId: string; filename: string; mimeType: string; size: number | null }[] = [];
  const visit = (part: unknown) => {
    if (!isRecord(part)) return;
    const body = isRecord(part.body) ? part.body : null;
    const attachmentId = typeof body?.attachmentId === "string" ? body.attachmentId : "";
    if (attachmentId) {
      attachments.push({
        attachmentId,
        filename: typeof part.filename === "string" ? part.filename : "",
        mimeType: typeof part.mimeType === "string" ? part.mimeType : "",
        size: typeof body?.size === "number" ? body.size : null,
      });
    }
    const parts = Array.isArray(part.parts) ? part.parts : [];
    for (const child of parts) visit(child);
  };
  visit(payload);
  return attachments;
}

async function googleWorkspaceListMessages(config: ServerConfig, args: Record<string, unknown>) {
  const query = readStringField(args, "query");
  const maxResults = Math.min(Math.max(Number(args.maxResults ?? 10), 1), 50);
  const { record, accessToken } = await googleWorkspaceAccessToken(config);
  requireGmailReadScope(record);
  const url = new URL("https://gmail.googleapis.com/gmail/v1/users/me/messages");
  if (query) url.searchParams.set("q", query);
  url.searchParams.set("maxResults", String(maxResults));
  const list = await fetchGoogleJson(url.toString(), { headers: { Authorization: `Bearer ${accessToken}` } });
  const ids = isRecord(list) && Array.isArray(list.messages)
    ? list.messages.filter(isRecord).map((entry) => typeof entry.id === "string" ? entry.id : "").filter(Boolean)
    : [];
  const messages = await Promise.all(ids.map(async (id) => {
    const message = await fetchGoogleJson(
      `https://gmail.googleapis.com/gmail/v1/users/me/messages/${encodeURIComponent(id)}?format=metadata&metadataHeaders=Subject&metadataHeaders=From&metadataHeaders=To&metadataHeaders=Bcc&metadataHeaders=Date`,
      { headers: { Authorization: `Bearer ${accessToken}` } },
    );
    return gmailMessageSummary(message);
  }));
  return { messages, resultSizeEstimate: isRecord(list) && typeof list.resultSizeEstimate === "number" ? list.resultSizeEstimate : null };
}

async function googleWorkspaceGetMessage(config: ServerConfig, args: Record<string, unknown>) {
  const messageId = readStringField(args, "messageId");
  if (!messageId) throw new ApiError(400, "invalid_payload", "messageId is required");
  const { record, accessToken } = await googleWorkspaceAccessToken(config);
  requireGmailReadScope(record);
  const message = await fetchGoogleJson(
    `https://gmail.googleapis.com/gmail/v1/users/me/messages/${encodeURIComponent(messageId)}?format=full`,
    { headers: { Authorization: `Bearer ${accessToken}` } },
  );
  const payload = isRecord(message) ? message.payload : null;
  const body = gmailMessageText(payload) || gmailMessageText(payload, "text/html");
  return { ...gmailMessageSummary(message), body, attachments: gmailAttachmentMetadata(payload) };
}

async function googleWorkspaceDownloadAttachment(config: ServerConfig, args: Record<string, unknown>) {
  const messageId = readStringField(args, "messageId");
  const attachmentId = readStringField(args, "attachmentId");
  if (!messageId || !attachmentId) throw new ApiError(400, "invalid_payload", "messageId and attachmentId are required");
  const { record, accessToken } = await googleWorkspaceAccessToken(config);
  requireGmailReadScope(record);
  const attachment = await fetchGoogleJson(
    `https://gmail.googleapis.com/gmail/v1/users/me/messages/${encodeURIComponent(messageId)}/attachments/${encodeURIComponent(attachmentId)}`,
    { headers: { Authorization: `Bearer ${accessToken}` } },
  );
  if (!isRecord(attachment) || typeof attachment.data !== "string") throw new Error("Gmail attachment download did not return data.");
  const data = attachment.data;
  const content = decodeBase64Url(data);
  return {
    messageId,
    attachmentId,
    size: isRecord(attachment) && typeof attachment.size === "number" ? attachment.size : content.byteLength,
    dataBase64: content.toString("base64"),
  };
}

const calendarReadTimestamp = z.string().trim().datetime({ offset: true, message: "Use an RFC 3339 datetime with Z or a UTC offset." });
const calendarReadArgs = z.object({
  timeMin: calendarReadTimestamp,
  timeMax: calendarReadTimestamp,
  maxResults: z.number().int().default(10),
}).refine((args) => Date.parse(args.timeMax) > Date.parse(args.timeMin), {
  path: ["timeMax"], message: "timeMax must be later than timeMin.",
});

async function googleWorkspaceListEvents(config: ServerConfig, args: Record<string, unknown>) {
  const parsed = calendarReadArgs.safeParse(args);
  if (!parsed.success) throw new ApiError(400, "invalid_payload", parsed.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(" "));
  const { timeMin, timeMax } = parsed.data;
  const maxResults = Math.min(Math.max(parsed.data.maxResults, 1), 50);
  const { accessToken } = await googleWorkspaceAccessToken(config);
  const url = new URL("https://www.googleapis.com/calendar/v3/calendars/primary/events");
  url.searchParams.set("timeMin", timeMin);
  url.searchParams.set("timeMax", timeMax);
  url.searchParams.set("singleEvents", "true");
  url.searchParams.set("orderBy", "startTime");
  url.searchParams.set("maxResults", String(maxResults));
  return fetchGoogleJson(url.toString(), { headers: { Authorization: `Bearer ${accessToken}` } });
}

async function googleWorkspaceCreateDraft(config: ServerConfig, args: Record<string, unknown>, context: Record<string, unknown>) {
  const to = stringArrayField(args.to);
  const cc = stringArrayField(args.cc);
  const bcc = stringArrayField(args.bcc);
  const subject = readStringField(args, "subject");
  const body = typeof args.body === "string" ? args.body : "";
  if (!to.length || !subject || !body.trim()) throw new ApiError(400, "invalid_payload", "to, subject, and body are required");
  if (GMAIL_REPLY_SUBJECT_RE.test(subject)) throw new ApiError(400, "invalid_payload", "Subject looks like a reply. Use gmail_create_reply_draft instead so the Gmail thread is preserved.");
  const attachments = await loadGmailDraftAttachments(config, context, gmailDraftAttachmentRequests(args.attachments));
  const { accessToken } = await googleWorkspaceAccessToken(config);
  const draft = await fetchGoogleJson("https://gmail.googleapis.com/gmail/v1/users/me/drafts", {
    method: "POST",
    headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" },
    body: JSON.stringify({ message: { raw: base64UrlString(gmailRawMessage({ to, cc, bcc, subject, body, html: gmailHtmlDivs(normalizeGmailDraftBody(body)), attachments })) } }),
  });
  return {
    ...(isRecord(draft) ? draft : {}),
    draftUrl: gmailDraftUrl(gmailDraftMessageId(draft)),
    threadUrl: gmailThreadUrl(gmailDraftThreadId(draft)),
  };
}

async function googleWorkspaceCreateReplyDraft(config: ServerConfig, args: Record<string, unknown>, context: Record<string, unknown>) {
  const messageId = readStringField(args, "messageId");
  const body = typeof args.body === "string" ? args.body : "";
  const replyAll = args.replyAll !== false;
  if (!messageId || !body.trim()) throw new ApiError(400, "invalid_payload", "messageId and body are required");
  const { record, accessToken } = await googleWorkspaceAccessToken(config);
  requireGmailReadScope(record);
  const url = new URL(`https://gmail.googleapis.com/gmail/v1/users/me/messages/${encodeURIComponent(messageId)}`);
  url.searchParams.set("format", "full");
  const message = await fetchGoogleJson(url.toString(), { headers: { Authorization: `Bearer ${accessToken}` } });
  const payload = isRecord(message) ? message.payload : null;
  const threadId = isRecord(message) && typeof message.threadId === "string" ? message.threadId : "";
  const originalMessageId = gmailHeader(payload, "Message-ID");
  if (!threadId || !originalMessageId) throw new ApiError(400, "gmail_reply_target_invalid", "Gmail message is missing thread metadata required to create a reply draft.", { messageId });
  const account = googleWorkspaceSafeAccount(record.account);
  const ownEmail = typeof account?.email === "string" ? account.email : "";
  const replyTarget = gmailHeader(payload, "Reply-To") || gmailHeader(payload, "From");
  const to = uniqueEmailHeaders(replyAll ? [replyTarget, gmailHeader(payload, "To")] : [replyTarget], [ownEmail]);
  const cc = replyAll ? uniqueEmailHeaders([gmailHeader(payload, "Cc")], [ownEmail, ...to.map(emailHeaderKey)]) : [];
  if (!to.length) throw new ApiError(400, "invalid_payload", "Original message does not include reply recipients");
  const attachments = await loadGmailDraftAttachments(config, context, gmailDraftAttachmentRequests(args.attachments));
  const originalFrom = gmailHeader(payload, "From");
  const originalDate = gmailHeader(payload, "Date");
  const originalSubject = gmailHeader(payload, "Subject");
  const replySubject = gmailReplySubject(originalSubject);
  // HTML-only originals must still quote: fall back to the text/html part the
  // same way the read path does.
  const quoteSource = gmailMessageText(payload) || gmailHtmlToText(gmailMessageText(payload, "text/html"));
  const includeQuote = !!quoteSource && !gmailBodyHasQuotedHistory(body);
  const plainBody = includeQuote
    ? `${body}\n\n${buildGmailQuoteBlock({ from: originalFrom, date: originalDate, body: quoteSource })}`
    : body;
  const htmlBody = `${gmailHtmlDivs(normalizeGmailDraftBody(body))}${includeQuote ? `<div><br></div>${buildGmailQuoteHtml({ from: originalFrom, date: originalDate, body: quoteSource })}` : ""}`;
  const draft = await fetchGoogleJson("https://gmail.googleapis.com/gmail/v1/users/me/drafts", {
    method: "POST",
    headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" },
    body: JSON.stringify({
      message: {
        threadId,
        raw: base64UrlString(gmailRawMessage({
          to,
          cc,
          subject: replySubject,
          body: plainBody,
          html: htmlBody,
          headers: [
            { name: "In-Reply-To", value: originalMessageId },
            { name: "References", value: gmailReplyReferences(gmailHeader(payload, "References"), originalMessageId) },
          ],
          attachments,
        })),
      },
    }),
  });
  return {
    ...(isRecord(draft) ? draft : {}),
    draftUrl: gmailDraftUrl(gmailDraftMessageId(draft)),
    threadUrl: gmailThreadUrl(threadId),
    reply: {
      threadId,
      subject: replySubject,
      to,
      cc,
      inReplyTo: originalMessageId,
      original: { subject: originalSubject, from: originalFrom, date: originalDate },
    },
  };
}

async function googleWorkspaceSearchFiles(config: ServerConfig, args: Record<string, unknown>) {
  const query = readStringField(args, "query");
  if (!query) throw new ApiError(400, "invalid_payload", "query is required");
  const maxResults = Math.min(Math.max(Number(args.maxResults ?? 10), 1), 50);
  const { accessToken } = await googleWorkspaceAccessToken(config);
  const url = new URL("https://www.googleapis.com/drive/v3/files");
  const escapedQuery = query.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
  url.searchParams.set("q", `name contains '${escapedQuery}' and trashed = false`);
  url.searchParams.set("pageSize", String(maxResults));
  url.searchParams.set("fields", "files(id,name,mimeType,webViewLink,modifiedTime,size)");
  return fetchGoogleJson(url.toString(), { headers: { Authorization: `Bearer ${accessToken}` } });
}

async function googleWorkspaceReadFile(config: ServerConfig, args: Record<string, unknown>) {
  const fileId = readStringField(args, "fileId");
  if (!fileId) throw new ApiError(400, "invalid_payload", "fileId is required");
  const { accessToken } = await googleWorkspaceAccessToken(config);
  const metadata = await fetchGoogleJson(`https://www.googleapis.com/drive/v3/files/${encodeURIComponent(fileId)}?fields=id,name,mimeType,webViewLink`, {
    headers: { Authorization: `Bearer ${accessToken}` },
  });
  const mimeType = isRecord(metadata) && typeof metadata.mimeType === "string" ? metadata.mimeType : "";
  const exportMime = mimeType === "application/vnd.google-apps.document" ? "text/plain" : "";
  const url = exportMime
    ? `https://www.googleapis.com/drive/v3/files/${encodeURIComponent(fileId)}/export?mimeType=${encodeURIComponent(exportMime)}`
    : `https://www.googleapis.com/drive/v3/files/${encodeURIComponent(fileId)}?alt=media`;
  const response = await externalFetch(url, { headers: { Authorization: `Bearer ${accessToken}` } });
  const content = await response.text();
  if (!response.ok) throw new Error(`Google Drive read failed (${response.status}): ${content}`);
  return { metadata, content };
}

async function googleWorkspaceUpdateFile(config: ServerConfig, args: Record<string, unknown>) {
  const fileId = readStringField(args, "fileId");
  const content = typeof args.content === "string" ? args.content : "";
  if (!fileId || !content) throw new ApiError(400, "invalid_payload", "fileId and content are required");
  const { accessToken } = await googleWorkspaceAccessToken(config);
  return fetchGoogleJson(`https://www.googleapis.com/upload/drive/v3/files/${encodeURIComponent(fileId)}?uploadType=media&fields=id,name,mimeType,webViewLink,modifiedTime`, {
    method: "PATCH",
    headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "text/plain; charset=UTF-8" },
    body: content,
  });
}

async function googleWorkspaceCreateEvent(config: ServerConfig, args: Record<string, unknown>) {
  const summary = readStringField(args, "summary");
  const start = readStringField(args, "start");
  const end = readStringField(args, "end");
  if (!summary || !start || !end) throw new ApiError(400, "invalid_payload", "summary, start, and end are required");
  const description = readStringField(args, "description");
  const location = readStringField(args, "location");
  const timeZone = readStringField(args, "timeZone");
  const attendees = stringArrayField(args.attendees);
  const { record, accessToken } = await googleWorkspaceAccessToken(config);
  requireCalendarWriteScope(record);
  return fetchGoogleJson("https://www.googleapis.com/calendar/v3/calendars/primary/events", {
    method: "POST",
    headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" },
    body: JSON.stringify({
      summary,
      ...(description ? { description } : {}),
      ...(location ? { location } : {}),
      start: { dateTime: start, ...(timeZone ? { timeZone } : {}) },
      end: { dateTime: end, ...(timeZone ? { timeZone } : {}) },
      ...(attendees.length ? { attendees: attendees.map((email) => ({ email })) } : {}),
    }),
  });
}

function chatSpaceName(args: Record<string, unknown>): string {
  const spaceId = readStringField(args, "spaceId");
  if (!spaceId) throw new ApiError(400, "invalid_payload", "spaceId is required");
  return spaceId.startsWith("spaces/") ? spaceId : `spaces/${spaceId}`;
}

async function googleWorkspaceListChatSpaces(config: ServerConfig, args: Record<string, unknown>) {
  const maxResults = Math.min(Math.max(Number(args.maxResults ?? 25), 1), 100);
  const { record, accessToken } = await googleWorkspaceAccessToken(config);
  requireChatScope(record, CHAT_SPACES_SCOPE);
  const url = new URL("https://chat.googleapis.com/v1/spaces");
  url.searchParams.set("pageSize", String(maxResults));
  return fetchGoogleJson(url.toString(), { headers: { Authorization: `Bearer ${accessToken}` } });
}

async function googleWorkspaceListChatMessages(config: ServerConfig, args: Record<string, unknown>) {
  const space = chatSpaceName(args);
  const maxResults = Math.min(Math.max(Number(args.maxResults ?? 25), 1), 100);
  const { record, accessToken } = await googleWorkspaceAccessToken(config);
  requireChatScope(record, CHAT_MESSAGES_READ_SCOPE);
  const url = new URL(`https://chat.googleapis.com/v1/${space}/messages`);
  url.searchParams.set("pageSize", String(maxResults));
  url.searchParams.set("orderBy", "createTime desc");
  return fetchGoogleJson(url.toString(), { headers: { Authorization: `Bearer ${accessToken}` } });
}

async function googleWorkspaceSendChatMessage(config: ServerConfig, args: Record<string, unknown>) {
  const space = chatSpaceName(args);
  const text = typeof args.text === "string" ? args.text.trim() : "";
  if (!text) throw new ApiError(400, "invalid_payload", "text is required");
  const { record, accessToken } = await googleWorkspaceAccessToken(config);
  requireChatScope(record, CHAT_MESSAGES_CREATE_SCOPE);
  return fetchGoogleJson(`https://chat.googleapis.com/v1/${space}/messages`, {
    method: "POST",
    headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" },
    body: JSON.stringify({ text }),
  });
}

export async function callGoogleWorkspaceExtensionAction(config: ServerConfig, action: string, args: Record<string, unknown>, context: Record<string, unknown>, statusExtra: Record<string, unknown> = {}) {
  if (action === "status") {
    return {
      ok: true,
      extensionId: GOOGLE_WORKSPACE_EXTENSION_ID,
      action,
      result: await googleWorkspaceStatus(config, statusExtra),
      context,
    };
  }
  if (action === "calendar_list_events") return { ok: true, extensionId: GOOGLE_WORKSPACE_EXTENSION_ID, action, result: await googleWorkspaceListEvents(config, args), context };
  if (action === "gmail_create_draft") return { ok: true, extensionId: GOOGLE_WORKSPACE_EXTENSION_ID, action, result: await googleWorkspaceCreateDraft(config, args, context), context };
  if (action === "gmail_create_reply_draft") return { ok: true, extensionId: GOOGLE_WORKSPACE_EXTENSION_ID, action, result: await googleWorkspaceCreateReplyDraft(config, args, context), context };
  if (action === "gmail_list_messages") return { ok: true, extensionId: GOOGLE_WORKSPACE_EXTENSION_ID, action, result: await googleWorkspaceListMessages(config, args), context };
  if (action === "gmail_get_message") return { ok: true, extensionId: GOOGLE_WORKSPACE_EXTENSION_ID, action, result: await googleWorkspaceGetMessage(config, args), context };
  if (action === "gmail_download_attachment") return { ok: true, extensionId: GOOGLE_WORKSPACE_EXTENSION_ID, action, result: await googleWorkspaceDownloadAttachment(config, args), context };
  if (action === "drive_search_files") return { ok: true, extensionId: GOOGLE_WORKSPACE_EXTENSION_ID, action, result: await googleWorkspaceSearchFiles(config, args), context };
  if (action === "drive_read_file") return { ok: true, extensionId: GOOGLE_WORKSPACE_EXTENSION_ID, action, result: await googleWorkspaceReadFile(config, args), context };
  if (action === "drive_update_file") return { ok: true, extensionId: GOOGLE_WORKSPACE_EXTENSION_ID, action, result: await googleWorkspaceUpdateFile(config, args), context };
  if (action === "calendar_create_event") return { ok: true, extensionId: GOOGLE_WORKSPACE_EXTENSION_ID, action, result: await googleWorkspaceCreateEvent(config, args), context };
  if (action === "chat_list_spaces") return { ok: true, extensionId: GOOGLE_WORKSPACE_EXTENSION_ID, action, result: await googleWorkspaceListChatSpaces(config, args), context };
  if (action === "chat_list_messages") return { ok: true, extensionId: GOOGLE_WORKSPACE_EXTENSION_ID, action, result: await googleWorkspaceListChatMessages(config, args), context };
  if (action === "chat_send_message") return { ok: true, extensionId: GOOGLE_WORKSPACE_EXTENSION_ID, action, result: await googleWorkspaceSendChatMessage(config, args), context };
  return null;
}

export async function googleWorkspaceStatus(config: ServerConfig, extra: Record<string, unknown> = {}) {
  try {
    const record = await readGoogleWorkspaceVault(config);
    return googleWorkspaceStatusPayload(record, extra);
  } catch (error) {
    return googleWorkspaceStatusPayload(null, { ...extra, error: error instanceof Error ? error.message : String(error) });
  }
}

export async function googleWorkspaceTestConnection(config: ServerConfig) {
  const { record, accessToken } = await googleWorkspaceAccessToken(config);
  await fetchGoogleUserInfo(accessToken);
  await fetchGoogleJson("https://www.googleapis.com/calendar/v3/users/me/calendarList?maxResults=1", { headers: { Authorization: `Bearer ${accessToken}` } });
  return googleWorkspaceStatusPayload(record, { testStatus: "Google profile and Calendar read access verified." });
}

export async function googleWorkspaceRunScopeSmokeTest(config: ServerConfig) {
  const { record, accessToken } = await googleWorkspaceAccessToken(config);
  const account = await fetchGoogleUserInfo(accessToken);
  const email = isRecord(account) && typeof account.email === "string" ? account.email : googleWorkspaceSafeAccount(record.account)?.email;
  if (!email) throw new Error("Google account email is unavailable.");
  await fetchGoogleJson("https://www.googleapis.com/calendar/v3/users/me/calendarList?maxResults=1", { headers: { Authorization: `Bearer ${accessToken}` } });
  const createdAt = new Date().toISOString();
  const driveBoundary = `omnirush_${randomBytes(8).toString("hex")}`;
  const driveFile = await fetchGoogleJson("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id,name,webViewLink", {
    method: "POST",
    headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": `multipart/related; boundary=${driveBoundary}` },
    body: multipartRelatedBody({ name: "OmniRush.ai Google Workspace smoke test.txt", mimeType: "text/plain" }, `OmniRush.ai Google Workspace smoke test created at ${createdAt}.`, driveBoundary),
  });
  if (isRecord(driveFile) && typeof driveFile.id === "string") {
    const response = await externalFetch(`https://www.googleapis.com/drive/v3/files/${encodeURIComponent(driveFile.id)}?alt=media`, { headers: { Authorization: `Bearer ${accessToken}` } });
    if (!response.ok) throw new Error(`Google Drive smoke read failed (${response.status}): ${await response.text()}`);
  }
  const draft = await fetchGoogleJson("https://gmail.googleapis.com/gmail/v1/users/me/drafts", {
    method: "POST",
    headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" },
    body: JSON.stringify({ message: { raw: base64UrlString(gmailRawMessage({ to: [email], subject: "OmniRush.ai Google Workspace smoke test draft", body: `This draft was created by OmniRush.ai to verify Gmail draft access at ${createdAt}.\nOmniRush does not send this email automatically.` })) } }),
  });
  return googleWorkspaceStatusPayload(record, {
    testStatus: "Calendar read, Drive file create/read, and Gmail draft creation verified.",
    smokeTest: {
      driveFileId: isRecord(driveFile) && typeof driveFile.id === "string" ? driveFile.id : null,
      driveFileName: isRecord(driveFile) && typeof driveFile.name === "string" ? driveFile.name : null,
      gmailDraftId: isRecord(draft) && typeof draft.id === "string" ? draft.id : null,
    },
  });
}

export async function googleWorkspaceSetActiveAccount(config: ServerConfig, accountId: string) {
  const vault = await readGoogleWorkspaceVault(config);
  const accounts = googleWorkspaceAccountRecords(vault);
  const account = accounts.find((entry) => googleWorkspaceAccountId(entry) === accountId);
  if (!account) throw new ApiError(404, "google_workspace_account_not_found", "Google Workspace account is not connected.");
  await writeGoogleWorkspaceAccountsVault(config, accounts, accountId);
  const nextVault = await readGoogleWorkspaceVault(config);
  return googleWorkspaceStatusPayload(nextVault, { testStatus: "Default Google Workspace account updated." });
}

export async function googleWorkspaceDisconnect(config: ServerConfig, accountId: string | null = null) {
  const vault = await readGoogleWorkspaceVault(config);
  const accounts = googleWorkspaceAccountRecords(vault);
  const selectedAccounts = accountId
    ? accounts.filter((entry) => googleWorkspaceAccountId(entry) === accountId)
    : accounts;
  let revokeError: Error | null = null;
  for (const record of selectedAccounts) {
    const token = isRecord(record.token) ? record.token : null;
    const revokeToken = typeof token?.refreshToken === "string" ? token.refreshToken : typeof token?.accessToken === "string" ? token.accessToken : "";
    if (!revokeToken) continue;
    try {
      await fetchGoogleJson("https://oauth2.googleapis.com/revoke", {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: new URLSearchParams({ token: revokeToken }),
      });
    } catch (error) {
      revokeError = error instanceof Error ? error : new Error(String(error));
    }
  }
  const remainingAccounts = accountId
    ? accounts.filter((entry) => googleWorkspaceAccountId(entry) !== accountId)
    : [];
  const activeAccountId = remainingAccounts.length > 0 ? googleWorkspaceAccountId(remainingAccounts[0]) : null;
  await writeGoogleWorkspaceAccountsVault(config, remainingAccounts, activeAccountId);
  const nextVault = await readGoogleWorkspaceVault(config);
  return googleWorkspaceStatusPayload(nextVault, revokeError ? { error: `Local Google Workspace tokens were removed, but Google token revocation failed: ${revokeError.message}` } : { testStatus: "Google Workspace access revoked and local tokens removed." });
}

function escapeHtml(value: string): string {
  return String(value).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
}

function googleWorkspaceCallbackPage(status: number, title: string, body: string) {
  return new Response(`<!doctype html><html><head><title>${escapeHtml(title)}</title></head><body style="font-family: system-ui, sans-serif; padding: 32px;"><h1>${escapeHtml(title)}</h1><p>${escapeHtml(body)}</p><script>setTimeout(() => window.close(), 800);</script></body></html>`, {
    status,
    headers: { "Content-Type": "text/html; charset=utf-8", Connection: "close" },
  });
}

export function createGoogleWorkspaceConnectFlowManager(config: ServerConfig) {
  const flows = new Map<string, GoogleWorkspaceFlow>();

  const cleanup = (flowId: string) => {
    const flow = flows.get(flowId);
    if (!flow) return;
    flow.server.closeAllConnections?.();
    flow.server.close(() => undefined);
    flows.delete(flowId);
  };

  const start = async (options: { gmailRead?: boolean; features?: string[] } = {}) => {
    const credentials = googleWorkspaceCredentials();
    if (credentials.missing.length > 0) {
      throw new ApiError(400, "google_oauth_not_configured", `Missing Google OAuth configuration: ${credentials.missing.join(", ")}`);
    }
    const features = new Set((options.features ?? []).filter(isGoogleWorkspaceOptionalFeature));
    if (options.gmailRead) features.add("gmailRead");
    if (features.size > 0 && !credentials.customClient) {
      throw new ApiError(400, "google_extra_scopes_require_custom_client", "Extra Google permissions (Gmail read, full Drive, calendar editing, Google Chat) are only available when using your own Google OAuth client.");
    }
    const scopes = [...GOOGLE_WORKSPACE_SCOPES, ...[...features].flatMap((feature) => GOOGLE_WORKSPACE_OPTIONAL_FEATURES[feature])];
    const flowId = base64Url(randomBytes(18));
    const state = base64Url(randomBytes(24));
    const pkce = createGoogleWorkspacePkce();
    const expiresAt = Date.now() + GOOGLE_WORKSPACE_AUTH_TIMEOUT_MS;
    let callbackServer: Server | null = null;

    const port = await new Promise<number>((resolvePort, reject) => {
      callbackServer = createServer(async (request, response) => {
        const finish = async (page: Response) => {
          response.writeHead(page.status, Object.fromEntries(page.headers.entries()));
          response.end(await page.text());
        };
        try {
          const flow = flows.get(flowId);
          if (!flow) {
            await finish(googleWorkspaceCallbackPage(410, "Google Workspace connection expired", "Return to OmniRush.ai and start connection again."));
            return;
          }
          const url = new URL(request.url ?? "/", "http://127.0.0.1");
          if (url.pathname !== "/" && url.pathname !== "/oauth/google-workspace/callback") {
            response.writeHead(404);
            response.end("Not found");
            return;
          }
          const error = url.searchParams.get("error");
          if (error) {
            flow.status = "failed";
            flow.error = `Google OAuth returned error: ${error}`;
            await finish(googleWorkspaceCallbackPage(400, "Google Workspace connection failed", error));
            return;
          }
          const returnedState = url.searchParams.get("state") ?? "";
          const code = url.searchParams.get("code") ?? "";
          if (returnedState !== flow.state || !code) {
            flow.status = "failed";
            flow.error = "Invalid Google OAuth callback.";
            await finish(googleWorkspaceCallbackPage(400, "Google Workspace connection failed", "Invalid OAuth callback."));
            return;
          }
          await finish(googleWorkspaceCallbackPage(200, "Google Workspace authorization received", "You can return to OmniRush.ai while it finishes connecting."));
          try {
            const token = await exchangeGoogleWorkspaceCode({ code, redirectUri: flow.redirectUri, verifier: flow.verifier });
            if (!isRecord(token) || typeof token.access_token !== "string") throw new Error("Google OAuth response did not include an access token.");
            const account = await fetchGoogleUserInfo(token.access_token);
            const record = {
              version: 1,
              account,
              scopes: typeof token.scope === "string" ? token.scope.split(/\s+/).filter(Boolean) : scopes,
              token: {
                accessToken: token.access_token,
                refreshToken: typeof token.refresh_token === "string" ? token.refresh_token : null,
                expiresAt: Date.now() + Number(token.expires_in ?? 3600) * 1000,
              },
              connectedAt: new Date().toISOString(),
              updatedAt: new Date().toISOString(),
            };
            await upsertGoogleWorkspaceAccount(config, record);
            flow.status = "connected";
            flow.account = account;
          } catch (exchangeError) {
            flow.status = "failed";
            flow.error = `Google authorized OmniRush.ai, but token exchange failed: ${exchangeError instanceof Error ? exchangeError.message : String(exchangeError)}`;
          }
        } catch (callbackError) {
          const flow = flows.get(flowId);
          if (flow) {
            flow.status = "failed";
            flow.error = callbackError instanceof Error ? callbackError.message : String(callbackError);
          }
          if (!response.headersSent) {
            await finish(googleWorkspaceCallbackPage(500, "Google Workspace connection failed", callbackError instanceof Error ? callbackError.message : String(callbackError)));
          }
        }
      });
      callbackServer.once("error", reject);
      callbackServer.listen(0, "127.0.0.1", () => {
        const address = callbackServer?.address();
        const resolvedPort = typeof address === "object" && address ? address.port : null;
        if (!resolvedPort) reject(new Error("Could not start Google Workspace OAuth callback server."));
        else resolvePort(resolvedPort);
      });
    });
    if (!callbackServer) throw new Error("Could not start Google Workspace OAuth callback server.");
    const redirectUri = `http://127.0.0.1:${port}/`;
    const authorizationUrl = new URL("https://accounts.google.com/o/oauth2/v2/auth");
    authorizationUrl.searchParams.set("client_id", credentials.clientId);
    authorizationUrl.searchParams.set("redirect_uri", redirectUri);
    authorizationUrl.searchParams.set("response_type", "code");
    authorizationUrl.searchParams.set("scope", scopes.join(" "));
    authorizationUrl.searchParams.set("access_type", "offline");
    authorizationUrl.searchParams.set("prompt", "consent");
    authorizationUrl.searchParams.set("state", state);
    authorizationUrl.searchParams.set("code_challenge", pkce.challenge);
    authorizationUrl.searchParams.set("code_challenge_method", "S256");
    flows.set(flowId, {
      flowId,
      state,
      verifier: pkce.verifier,
      redirectUri,
      expiresAt,
      status: "pending",
      authUrl: authorizationUrl.toString(),
      account: null,
      error: null,
      server: callbackServer,
    });
    setTimeout(() => {
      const flow = flows.get(flowId);
      if (!flow || flow.status !== "pending") return;
      flow.status = "expired";
      flow.error = "Google Workspace OAuth timed out.";
      flow.server.closeAllConnections?.();
      flow.server.close(() => undefined);
    }, GOOGLE_WORKSPACE_AUTH_TIMEOUT_MS + 1000).unref?.();
    return { flowId, authUrl: authorizationUrl.toString(), expiresAt };
  };

  const status = async (flowId: string) => {
    const flow = flows.get(flowId);
    if (!flow) throw new ApiError(404, "google_oauth_flow_not_found", "Google Workspace connection flow not found");
    if (flow.status === "pending" && flow.expiresAt <= Date.now()) {
      flow.status = "expired";
      flow.error = "Google Workspace OAuth timed out.";
    }
    const googleWorkspace = flow.status === "connected" ? await googleWorkspaceStatus(config) : null;
    const payload = {
      flowId: flow.flowId,
      status: flow.status,
      expiresAt: flow.expiresAt,
      error: flow.error,
      googleWorkspace,
    };
    if (flow.status !== "pending") setTimeout(() => cleanup(flow.flowId), 1000).unref?.();
    return payload;
  };

  return { start, status };
}