@open-mercato/channel-gmail 0.8.1-develop.7296.1.2111d779db → 0.8.1-develop.7441.1.b42958b98c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -29,6 +29,7 @@ Gmail email channel provider for the Communications Hub (`communication_channels
29
29
  - Tenant OAuth client config (`{ clientId, clientSecret, scopes? }`) lives on `IntegrationCredentials` for provider `gmail`; per-user tokens live on `CommunicationChannel.credentials`.
30
30
  - `fetchHistory` is cursor-driven via `channelState.historyId`. The terminal `historyId` MUST only advance over messages actually normalized; a transient (non-404/410) fetch failure pins the cursor and re-fetches next tick (see the L3 fix in `fetchAndNormalize`).
31
31
  - `importHistory` is the operator-triggered BACKLOG sweep and is independent of `fetchHistory`: it walks `users.messages.list?q=after:<epochSeconds>[ from:(… OR …)]` backwards and MUST NOT read or write `channelState.historyId`. Its cursor carries only Gmail's `nextPageToken`, the frozen query, the group index and the collected counter, so it stays compact for a multi-year mailbox. Senders are chunked into groups of 25 and walked sequentially across pages.
32
+ - `importHistory` lists with `labelIds: ['INBOX']` (same scope as `fetchHistory` and the IMAP adapter), so archived mail and other messages outside the inbox are NOT swept — expect a long backfill to miss old mail the user archived. Widening the scope is a behavior change: update this note and `.ai/qa/scenarios/TC-CHANNEL-EMAIL-032-gmail-import-history.md` with it.
32
33
  - The clients are swappable via `setGmailApiClient` / `setGoogleOAuthClient` (test-only hooks).
33
34
 
34
35
  ## Health Check
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/channel_gmail/__integration__/TC-CHANNEL-EMAIL-032.spec.ts"],
4
- "sourcesContent": ["import { expect, test } from '@playwright/test'\nimport { getAuthToken } from '@open-mercato/core/helpers/integration/authFixtures'\nimport { apiRequest } from '@open-mercato/core/helpers/integration/api'\n\n/**\n * TC-CHANNEL-EMAIL-032 \u2014 Gmail backlog import route wiring.\n *\n * The Gmail adapter now implements `importHistory`, so\n * `POST /api/communication_channels/channels/{id}/import-history` must no\n * longer short-circuit with the \"provider does not support history import\"\n * 400 for `gmail` channels. This spec covers the route surface reachable\n * without a live Google grant: auth, body validation (including the widened\n * 10-year / 50k ceilings), and the not-found branch.\n *\n * The Gmail query construction, sender chunking, cursor round-trip,\n * pagination, `maxMessages` cap and per-message error handling are covered by\n * `packages/channel-gmail/src/modules/channel_gmail/lib/__tests__/adapter.test.ts`\n * (`GmailChannelAdapter.importHistory`).\n *\n * The full end-to-end (connect a Gmail mailbox \u2192 POST /import-history \u2192\n * ProgressJob completes \u2192 imported messages on the Person timeline) needs a\n * real OAuth grant and stays manual, alongside\n * `.ai/qa/scenarios/TC-CHANNEL-EMAIL-029-import-history.md`.\n */\ntest.describe('TC-CHANNEL-EMAIL-032: gmail import-history route wiring', () => {\n const FAKE_CHANNEL_ID = '00000000-0000-0000-0000-000000000032'\n const path = `/api/communication_channels/channels/${FAKE_CHANNEL_ID}/import-history`\n\n test('rejects unauthenticated requests', async ({ request }) => {\n const response = await apiRequest(request, 'POST', path, {\n // Intentionally empty token \u2014 this test asserts the 401 unauth path.\n token: '',\n data: { sinceDays: 365 },\n })\n expect(response.status()).toBe(401)\n })\n\n test('rejects a sinceDays value beyond the ten-year ceiling', async ({ request }) => {\n const token = await getAuthToken(request)\n const response = await apiRequest(request, 'POST', path, {\n token,\n data: { sinceDays: 3651 },\n })\n expect(response.status()).toBe(400)\n })\n\n test('accepts a multi-year window without a schema rejection', async ({ request }) => {\n const token = await getAuthToken(request)\n const response = await apiRequest(request, 'POST', path, {\n token,\n data: { sinceDays: 1825, maxMessages: 50000 },\n })\n // The channel does not exist, so the request must fail on the lookup\n // branch (or the missing-org-scope branch) \u2014 never on body validation and\n // never with a 5xx.\n expect(response.status(), 'route should not 5xx').toBeLessThan(500)\n expect([400, 403, 404]).toContain(response.status())\n })\n})\n"],
4
+ "sourcesContent": ["import { expect, test } from '@playwright/test'\nimport { getAuthToken } from '@open-mercato/core/helpers/integration/authFixtures'\nimport { apiRequest } from '@open-mercato/core/helpers/integration/api'\n\n/**\n * TC-CHANNEL-EMAIL-032 \u2014 Gmail backlog import route wiring.\n *\n * The Gmail adapter now implements `importHistory`, so\n * `POST /api/communication_channels/channels/{id}/import-history` must no\n * longer short-circuit with the \"provider does not support history import\"\n * 400 for `gmail` channels. This spec covers the route surface reachable\n * without a live Google grant: auth, body validation (including the widened\n * 10-year / 50k ceilings), and the not-found branch.\n *\n * The Gmail query construction, sender chunking, cursor round-trip,\n * pagination, `maxMessages` cap and per-message error handling are covered by\n * `packages/channel-gmail/src/modules/channel_gmail/lib/__tests__/adapter.test.ts`\n * (`GmailChannelAdapter.importHistory`).\n *\n * The full end-to-end (connect a Gmail mailbox \u2192 POST /import-history \u2192\n * ProgressJob completes \u2192 imported messages on the Person timeline) needs a\n * real OAuth grant and stays manual \u2014 see\n * `.ai/qa/scenarios/TC-CHANNEL-EMAIL-032-gmail-import-history.md`.\n */\ntest.describe('TC-CHANNEL-EMAIL-032: gmail import-history route wiring', () => {\n const FAKE_CHANNEL_ID = '00000000-0000-0000-0000-000000000032'\n const path = `/api/communication_channels/channels/${FAKE_CHANNEL_ID}/import-history`\n\n test('rejects unauthenticated requests', async ({ request }) => {\n const response = await apiRequest(request, 'POST', path, {\n // Intentionally empty token \u2014 this test asserts the 401 unauth path.\n token: '',\n data: { sinceDays: 365 },\n })\n expect(response.status()).toBe(401)\n })\n\n test('rejects a sinceDays value beyond the ten-year ceiling', async ({ request }) => {\n const token = await getAuthToken(request)\n const response = await apiRequest(request, 'POST', path, {\n token,\n data: { sinceDays: 3651 },\n })\n expect(response.status()).toBe(400)\n })\n\n test('accepts a multi-year window without a schema rejection', async ({ request }) => {\n const token = await getAuthToken(request)\n const response = await apiRequest(request, 'POST', path, {\n token,\n data: { sinceDays: 1825, maxMessages: 50000 },\n })\n // The channel does not exist, so the request must fail on the lookup\n // branch (or the missing-org-scope branch) \u2014 never on body validation and\n // never with a 5xx.\n expect(response.status(), 'route should not 5xx').toBeLessThan(500)\n expect([400, 403, 404]).toContain(response.status())\n })\n})\n"],
5
5
  "mappings": "AAAA,SAAS,QAAQ,YAAY;AAC7B,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAsB3B,KAAK,SAAS,2DAA2D,MAAM;AAC7E,QAAM,kBAAkB;AACxB,QAAM,OAAO,wCAAwC,eAAe;AAEpE,OAAK,oCAAoC,OAAO,EAAE,QAAQ,MAAM;AAC9D,UAAM,WAAW,MAAM,WAAW,SAAS,QAAQ,MAAM;AAAA;AAAA,MAEvD,OAAO;AAAA,MACP,MAAM,EAAE,WAAW,IAAI;AAAA,IACzB,CAAC;AACD,WAAO,SAAS,OAAO,CAAC,EAAE,KAAK,GAAG;AAAA,EACpC,CAAC;AAED,OAAK,yDAAyD,OAAO,EAAE,QAAQ,MAAM;AACnF,UAAM,QAAQ,MAAM,aAAa,OAAO;AACxC,UAAM,WAAW,MAAM,WAAW,SAAS,QAAQ,MAAM;AAAA,MACvD;AAAA,MACA,MAAM,EAAE,WAAW,KAAK;AAAA,IAC1B,CAAC;AACD,WAAO,SAAS,OAAO,CAAC,EAAE,KAAK,GAAG;AAAA,EACpC,CAAC;AAED,OAAK,0DAA0D,OAAO,EAAE,QAAQ,MAAM;AACpF,UAAM,QAAQ,MAAM,aAAa,OAAO;AACxC,UAAM,WAAW,MAAM,WAAW,SAAS,QAAQ,MAAM;AAAA,MACvD;AAAA,MACA,MAAM,EAAE,WAAW,MAAM,aAAa,IAAM;AAAA,IAC9C,CAAC;AAID,WAAO,SAAS,OAAO,GAAG,sBAAsB,EAAE,aAAa,GAAG;AAClE,WAAO,CAAC,KAAK,KAAK,GAAG,CAAC,EAAE,UAAU,SAAS,OAAO,CAAC;AAAA,EACrD,CAAC;AACH,CAAC;",
6
6
  "names": []
7
7
  }
@@ -685,35 +685,26 @@ function parseClientCredentialsOrThrow(value) {
685
685
  }
686
686
  return parsed.data;
687
687
  }
688
- let warnedLegacyClientPath = false;
689
688
  function resolveGmailOAuthClient(input) {
690
- if (input.oauthClient) {
691
- const client = input.oauthClient;
692
- if (!client.clientId) {
693
- throw new Error("[internal] Invalid Gmail OAuth client credentials: OAuth Client ID required");
694
- }
695
- if (!client.clientSecret) {
696
- throw new Error("[internal] Invalid Gmail OAuth client credentials: clientSecret required");
697
- }
698
- return {
699
- clientId: client.clientId,
700
- clientSecret: client.clientSecret,
701
- // `GmailClientCredentials.scopes` is the wire format the legacy
702
- // `credentials._client` blob carried — comma/space-separated string.
703
- // Spec A's `OAuthClientConfig.scopes` is the canonical `string[]`.
704
- // `parseScopes` accepts either separator, so join with a single space.
705
- ...client.scopes !== void 0 ? { scopes: client.scopes.join(" ") } : {}
706
- };
707
- }
708
- if (!warnedLegacyClientPath) {
709
- warnedLegacyClientPath = true;
710
- logger.warn(
711
- "reading OAuth client config from credentials._client is deprecated; pass via RefreshCredentialsInput.oauthClient instead (Spec A)"
689
+ if (!input.oauthClient) {
690
+ throw new Error(
691
+ "[internal] Invalid Gmail OAuth client credentials: oauthClient is required on RefreshCredentialsInput"
712
692
  );
713
693
  }
714
- return parseClientCredentialsOrThrow(
715
- input.credentials._client ?? input.credentials
716
- );
694
+ const client = input.oauthClient;
695
+ if (!client.clientId) {
696
+ throw new Error("[internal] Invalid Gmail OAuth client credentials: OAuth Client ID required");
697
+ }
698
+ if (!client.clientSecret) {
699
+ throw new Error("[internal] Invalid Gmail OAuth client credentials: clientSecret required");
700
+ }
701
+ return {
702
+ clientId: client.clientId,
703
+ clientSecret: client.clientSecret,
704
+ // Spec A's `OAuthClientConfig.scopes` is `string[]`; `GmailClientCredentials.scopes`
705
+ // is a comma/space-separated string. `parseScopes` accepts either separator.
706
+ ...client.scopes !== void 0 ? { scopes: client.scopes.join(" ") } : {}
707
+ };
717
708
  }
718
709
  function pickRawMimeBuffer(payload) {
719
710
  if (typeof payload.rawBase64Url === "string") return decodeBase64Url(payload.rawBase64Url);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/channel_gmail/lib/adapter.ts"],
4
- "sourcesContent": ["import type {\n ApplyPushNotificationInput,\n ChannelAdapter,\n ChannelNativeContent,\n ConvertOutboundInput,\n BuildOAuthAuthorizeUrlInput,\n BuildOAuthAuthorizeUrlResult,\n DeleteChannelMessageInput,\n ExchangeOAuthCodeInput,\n ExchangeOAuthCodeResult,\n FetchHistoryInput,\n GetMessageStatusInput,\n HistoryPage,\n ImportHistoryInput,\n ImportHistoryPage,\n InboundMessage,\n MessageStatus,\n NormalizedInboundMessage,\n PushRegistration,\n RefreshCredentialsInput,\n RefreshedCredentials,\n RegisterPushInput,\n ResolveContactInput,\n ContactHint,\n SendMessageInput,\n SendMessageResult,\n UnregisterPushInput,\n VerifyWebhookInput,\n} from '@open-mercato/core/modules/communication_channels/lib/adapter'\nimport { gmailCapabilities } from './capabilities'\nimport {\n gmailChannelStateSchema,\n gmailClientCredentialsSchema,\n gmailUserCredentialsSchema,\n parseScopes,\n type GmailChannelState,\n type GmailClientCredentials,\n type GmailUserCredentials,\n} from './credentials'\nimport {\n decodeBase64Url,\n encodeBase64Url,\n getGmailApiClient,\n GmailApiError,\n type GmailGetMessageRawResponse,\n} from './gmail-client'\nimport {\n getGoogleOAuthClient,\n tokenResponseToExpiresAt,\n} from './oauth'\nimport {\n convertOutboundForGmail,\n type GmailEmailNativeMetadata,\n} from './convert-outbound'\nimport { normalizeInboundGmailMessage } from './normalize-inbound'\nimport { emailResolveContact } from '@open-mercato/core/modules/communication_channels/lib/email-contact'\nimport { decodeCursor, encodeCursor } from '@open-mercato/core/modules/communication_channels/lib/email-mime'\nimport {\n IMPORT_HISTORY_DEFAULT_SINCE_DAYS,\n IMPORT_HISTORY_DEFAULT_MAX_MESSAGES,\n getImportHistoryMaxSinceDays,\n getImportHistoryMaxMessages,\n} from '@open-mercato/core/modules/communication_channels/lib/import-history-limits'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('channel_gmail')\n\n/**\n * Gmail `ChannelAdapter`. OAuth2-based, polling-driven (`realtimePush: false`).\n *\n * Credential shape on `CommunicationChannel.credentials`:\n * - Per-user: `{ accessToken, refreshToken?, expiresAt?, scopes?, email? }`\n * - Tenant OAuth client config sits on `IntegrationCredentials.credentials`\n * for the `gmail` provider: `{ clientId, clientSecret, scopes? }`. The hub\n * looks it up by `(tenantId, providerKey='gmail')` and passes it to\n * `buildOAuthAuthorizeUrl` + `exchangeOAuthCode` + `refreshCredentials`.\n *\n * Sync model:\n * - First poll on a fresh channel reads `gmail.users.getProfile.historyId`\n * and persists it; no message fetch is done on the bootstrap call (the\n * existing inbox is intentionally not back-filled, matching the spec).\n * - Subsequent polls call `gmail.users.history.list?startHistoryId=\u2026` and\n * fetch each `messagesAdded` entry's RAW payload.\n * - If the server returns `404` for the history id (Gmail keeps ~7 days),\n * we fall back to `gmail.users.messages.list?labelIds=INBOX` and persist\n * the new historyId from the next `getProfile` call.\n */\nclass GmailChannelAdapter implements ChannelAdapter {\n readonly providerKey = 'gmail'\n readonly channelType = 'email'\n readonly capabilities = gmailCapabilities\n\n async sendMessage(input: SendMessageInput): Promise<SendMessageResult> {\n const userCredentials = parseUserCredentialsOrThrow(input.credentials)\n let native: ChannelNativeContent\n try {\n native = await convertOutboundForGmail({\n body: input.content.html ?? input.content.text ?? '',\n bodyFormat: input.content.bodyFormat ?? (input.content.html ? 'html' : 'text'),\n attachments: input.content.attachments,\n channelMetadata: input.metadata,\n fromAddress: userCredentials.email ?? 'me',\n })\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Outbound conversion failed'\n return { externalMessageId: '', status: 'failed', error: message }\n }\n\n const nativeMeta = native.metadata as unknown as GmailEmailNativeMetadata\n const rawBase64Url = encodeBase64Url(nativeMeta.rawMessage)\n\n try {\n const response = await getGmailApiClient().sendRawMessage(\n { accessToken: userCredentials.accessToken },\n { rawBase64Url, threadId: nativeMeta.threadId },\n )\n return {\n externalMessageId: nativeMeta.messageId ?? response.id,\n conversationId: response.threadId,\n status: 'sent',\n metadata: { gmailMessageId: response.id, gmailThreadId: response.threadId, labelIds: response.labelIds ?? [] },\n }\n } catch (error) {\n if (error instanceof GmailApiError && error.status === 401) {\n // `requires_reauth` is a protocol sentinel the hub keys on (see\n // communication_channels error-classification.isReauthError), not a\n // user/log message \u2014 do NOT prefix or translate it.\n return { externalMessageId: '', status: 'failed', error: 'requires_reauth' }\n }\n const message = error instanceof Error ? error.message : 'Gmail send failed'\n return { externalMessageId: '', status: 'failed', error: message }\n }\n }\n\n async verifyWebhook(_input: VerifyWebhookInput): Promise<InboundMessage> {\n // Gmail Pub/Sub push (Spec C) is handled by the dedicated `/webhooks/gmail`\n // route + `applyPushNotification`, not this generic hub-webhook hook, so this\n // returns an unhandled event for the generic route to ack 2xx.\n return { raw: {}, eventType: 'other', metadata: { reason: 'gmail-uses-polling-not-push' } }\n }\n\n async getStatus(_input: GetMessageStatusInput): Promise<MessageStatus> {\n // Gmail exposes no per-message delivery-status API, so we return a\n // best-effort `'sent'` placeholder (a later bounce is not reflected here).\n // Mirrors the IMAP adapter's documented behavior.\n return { status: 'sent' }\n }\n\n async convertOutbound(input: ConvertOutboundInput): Promise<ChannelNativeContent> {\n return convertOutboundForGmail({ ...input, fromAddress: 'me' })\n }\n\n async normalizeInbound(raw: InboundMessage): Promise<NormalizedInboundMessage> {\n const payload = raw.raw as {\n rawBase64Url?: unknown\n rawBody?: unknown\n gmailMessageId?: unknown\n gmailThreadId?: unknown\n labelIds?: unknown\n accountIdentifier?: unknown\n }\n const rawMessage = pickRawMimeBuffer(payload)\n const gmailMessageId = typeof payload.gmailMessageId === 'string' ? payload.gmailMessageId : 'unknown'\n const gmailThreadId = typeof payload.gmailThreadId === 'string' ? payload.gmailThreadId : gmailMessageId\n const labelIds = Array.isArray(payload.labelIds) ? (payload.labelIds.filter((v) => typeof v === 'string') as string[]) : []\n const accountIdentifier = typeof payload.accountIdentifier === 'string' ? payload.accountIdentifier : 'unknown@gmail'\n return normalizeInboundGmailMessage({\n rawMessage,\n gmailMessageId,\n gmailThreadId,\n gmailLabelIds: labelIds,\n accountIdentifier,\n })\n }\n\n async buildOAuthAuthorizeUrl(input: BuildOAuthAuthorizeUrlInput): Promise<BuildOAuthAuthorizeUrlResult> {\n const client = parseClientCredentialsOrThrow(input.credentials)\n const scopes = parseScopes(client.scopes)\n const url = getGoogleOAuthClient().buildAuthorizeUrl({\n clientId: client.clientId,\n redirectUri: input.redirectUri,\n state: input.state,\n scopes,\n loginHint: input.loginHint,\n })\n return { authorizeUrl: url, extra: { scopes } }\n }\n\n async exchangeOAuthCode(input: ExchangeOAuthCodeInput): Promise<ExchangeOAuthCodeResult> {\n const client = parseClientCredentialsOrThrow(input.credentials)\n const token = await getGoogleOAuthClient().exchangeCode({\n clientId: client.clientId,\n clientSecret: client.clientSecret,\n redirectUri: input.redirectUri,\n code: input.code,\n })\n let email: string | undefined\n let displayName: string | undefined\n try {\n const userInfo = await getGoogleOAuthClient().fetchUserInfo(token.access_token)\n email = userInfo.email\n displayName = userInfo.name ?? userInfo.email\n } catch {\n // Userinfo failure is non-fatal; fall back to the optional `id_token` parser later.\n }\n const expiresAt = tokenResponseToExpiresAt(token)\n const credentials: GmailUserCredentials = {\n accessToken: token.access_token,\n refreshToken: token.refresh_token,\n expiresAt: expiresAt?.toISOString(),\n scopes: token.scope ? token.scope.split(' ').filter(Boolean) : undefined,\n email,\n }\n return {\n credentials: credentials as unknown as Record<string, unknown>,\n externalIdentifier: email,\n displayName: displayName ?? email,\n expiresAt,\n }\n }\n\n async refreshCredentials(input: RefreshCredentialsInput): Promise<RefreshedCredentials> {\n const current = parseUserCredentialsOrThrow(input.credentials)\n if (!current.refreshToken) {\n throw new Error('requires_reauth')\n }\n // Spec A: prefer the new `input.oauthClient` slot (resolved by the hub from\n // the `channel_gmail` integration's tenant-scoped client credentials). Fall\n // back to the deprecated `credentials._client` path for one minor release so\n // existing test fixtures keep working.\n const clientFromState = resolveGmailOAuthClient(input)\n const token = await getGoogleOAuthClient().refreshToken({\n clientId: clientFromState.clientId,\n clientSecret: clientFromState.clientSecret,\n refreshToken: current.refreshToken,\n })\n const expiresAt = tokenResponseToExpiresAt(token)\n const refreshed: GmailUserCredentials = {\n accessToken: token.access_token,\n // Google does NOT always return a new refresh token \u2014 keep the existing one.\n refreshToken: token.refresh_token ?? current.refreshToken,\n expiresAt: expiresAt?.toISOString(),\n scopes: token.scope ? token.scope.split(' ').filter(Boolean) : current.scopes,\n email: current.email,\n }\n return {\n credentials: refreshed as unknown as Record<string, unknown>,\n expiresAt,\n }\n }\n\n async fetchHistory(input: FetchHistoryInput): Promise<HistoryPage> {\n const userCredentials = parseUserCredentialsOrThrow(input.credentials)\n const channelState = gmailChannelStateSchema.parse(input.channelState ?? {})\n const auth = { accessToken: userCredentials.accessToken }\n const api = getGmailApiClient()\n const limit = input.limit ?? 50\n\n // L3 first-page retry: a prior fallback scan hard-failed on its FIRST page and\n // pinned only the history snapshot (no page token). Re-enter the fallback scan\n // from the first INBOX page so unprocessed messages are retried, not skipped by\n // the bootstrap path below.\n if (channelState.pendingMessagesHistoryIdSnapshot && !channelState.pendingMessagesPageToken) {\n return await this.startMessagesListFallback(\n api,\n auth,\n userCredentials.email ?? 'me',\n channelState.pendingMessagesHistoryIdSnapshot,\n limit,\n )\n }\n\n // Bootstrap path: no historyId yet \u2192 just persist current historyId and skip fetch.\n if (!channelState.historyId && !channelState.pendingMessagesPageToken) {\n const profile = await api.getProfile(auth)\n const nextState: GmailChannelState = {\n historyId: profile.historyId,\n lastSyncedAt: new Date().toISOString(),\n }\n return {\n messages: [],\n nextCursor: encodeCursor(nextState),\n hasMore: false,\n }\n }\n\n // Mid-drain fallback (404 path): we previously fell back to messages.list\n // for an expired historyId and still have pages to drain. Resume from the\n // stored pageToken without re-issuing the history.list call.\n if (channelState.pendingMessagesPageToken) {\n return await this.continueMessagesListDrain(\n api,\n auth,\n userCredentials.email ?? 'me',\n channelState,\n limit,\n )\n }\n\n // Incremental path: history.list since stored historyId, walking\n // nextPageToken until either (a) all pages drained, or (b) we've collected\n // `limit` messages.\n // CRITICAL: terminal historyId is ONLY advanced after full drain. While a\n // pending pageToken exists in channelState, the original startHistoryId is\n // retained so the next tick re-enters the same history window.\n let messages: NormalizedInboundMessage[] = []\n try {\n return await this.continueHistoryListDrain(\n api,\n auth,\n userCredentials.email ?? 'me',\n channelState,\n String(channelState.historyId),\n limit,\n )\n } catch (error) {\n if (error instanceof GmailApiError && error.status === 404) {\n // Gmail history expired (~7-day retention). Fall back to a paged inbox\n // scan via messages.list. Snapshot the post-fallback historyId now so\n // we can advance it once the messages.list drain completes.\n const profile = await api.getProfile(auth)\n return await this.startMessagesListFallback(\n api,\n auth,\n userCredentials.email ?? 'me',\n profile.historyId,\n limit,\n )\n }\n throw error\n }\n }\n\n /**\n * Spec C \u00A7 Phase C2 \u2014 Register Gmail Pub/Sub watch.\n *\n * Calls `gmail.users.watch` with the operator-configured Pub/Sub topic.\n * Returns `historyId` (cursor for subsequent `history.list` calls) and\n * `expiration` (ms since epoch \u2014 Gmail caps at ~7 days). Persists both\n * onto `CommunicationChannel.channelState` via the hub's\n * `push.register` command.\n */\n async registerPush(input: RegisterPushInput): Promise<PushRegistration> {\n const userCredentials = parseUserCredentialsOrThrow(input.credentials)\n const auth = { accessToken: userCredentials.accessToken }\n const api = getGmailApiClient()\n const topicName = (input.providerConfig?.pubsubTopic as string | undefined) ?? ''\n if (!topicName) {\n return {\n providerKey: this.providerKey,\n status: 'failed',\n channelStatePatch: {\n pushStatus: 'failed',\n lastPushError: {\n code: 'missing_topic',\n message: 'Pub/Sub topic not configured',\n at: new Date().toISOString(),\n },\n },\n error: {\n code: 'missing_topic',\n message: 'OM_GMAIL_PUBSUB_TOPIC not configured for this tenant',\n },\n }\n }\n try {\n const result = await api.watchInbox(auth, { topicName, labelIds: ['INBOX'] })\n const expirationMs = Number(result.expiration)\n return {\n providerKey: this.providerKey,\n status: 'active',\n channelStatePatch: {\n historyId: result.historyId,\n watchExpirationMs: Number.isFinite(expirationMs) ? expirationMs : Date.now() + 6 * 24 * 3600 * 1000,\n pubsubTopic: topicName,\n pushStatus: 'active',\n lastPushError: null,\n },\n recommendedPollIntervalSeconds: 1800,\n }\n } catch (error) {\n const status = error instanceof GmailApiError ? error.status : 0\n const detail = error instanceof Error ? error.message : 'watch failed'\n return {\n providerKey: this.providerKey,\n status: 'failed',\n channelStatePatch: {\n pushStatus: 'failed',\n lastPushError: {\n code: `gmail_watch_${status || 'error'}`,\n message: detail.slice(0, 500),\n at: new Date().toISOString(),\n },\n },\n error: { code: `gmail_watch_${status || 'error'}`, message: detail },\n }\n }\n }\n\n /**\n * Spec C \u00A7 Phase C2 \u2014 Tear down Gmail watch via `gmail.users.stop`.\n * Idempotent: a 404 (no active watch) is swallowed.\n */\n async unregisterPush(input: UnregisterPushInput): Promise<void> {\n const userCredentials = parseUserCredentialsOrThrow(input.credentials)\n const auth = { accessToken: userCredentials.accessToken }\n const api = getGmailApiClient()\n try {\n await api.stopWatch(auth)\n } catch (error) {\n if (error instanceof GmailApiError && error.status === 404) return\n throw error\n }\n }\n\n /**\n * Spec C \u00A7 Phase C2 \u2014 Convert a verified Pub/Sub notification into a\n * `HistoryPage`. The notification body itself is just `{ emailAddress,\n * historyId }`; the actual messages come from `history.list` against\n * `channelState.historyId`. We delegate to `fetchHistory` so the\n * pagination / 404-fallback logic stays in one place.\n */\n async applyPushNotification(input: ApplyPushNotificationInput): Promise<HistoryPage> {\n // The notification's `historyId` is informational \u2014 Gmail guarantees\n // it is `>= channelState.historyId`, but a multi-event batch may\n // advance further than what `history.list` returns in a single page.\n // Treat the call as \"drain whatever is new since the stored cursor\".\n // If `channelState.historyId` is absent (a push arrived before the cursor\n // was seeded), `fetchHistory` bootstraps \u2014 persists the current historyId\n // and returns zero messages \u2014 so this notification's delta is picked up on\n // the next call. In practice `registerPush` seeds the cursor before any\n // push flows, so this edge is not hit in the normal lifecycle.\n return this.fetchHistory({\n conversationId: 'INBOX',\n credentials: input.credentials,\n channelState: input.channelState,\n scope: input.scope,\n // Push notifications are bursty (1/s max per Gmail user); use a\n // smaller per-call limit so the worker drains quickly between\n // notifications without holding the API quota.\n limit: 50,\n } as FetchHistoryInput)\n }\n\n private async continueHistoryListDrain(\n api: ReturnType<typeof getGmailApiClient>,\n auth: { accessToken: string },\n accountIdentifier: string,\n channelState: GmailChannelState,\n startHistoryId: string,\n limit: number,\n ): Promise<HistoryPage> {\n const collected: Array<{ id: string; threadId: string; labelIds?: string[] }> = []\n const seen = new Set<string>()\n let pageToken: string | undefined = channelState.pendingHistoryPageToken\n let lastResponseHistoryId: string | undefined\n let drained = false\n\n // Fully consume each page before deciding to stop: `pageToken` must only ever\n // advance past refs we have actually collected, otherwise a page carrying more\n // than `limit` new refs would silently drop the overflow. `collected` may\n // therefore exceed `limit` by up to one page \u2014 bounded and intentional.\n while (true) {\n const history = await api.listHistory(auth, {\n startHistoryId,\n pageToken,\n })\n lastResponseHistoryId = history.historyId ?? lastResponseHistoryId\n for (const ref of collectMessageRefs(history.history ?? [])) {\n if (seen.has(ref.id)) continue\n seen.add(ref.id)\n collected.push(ref)\n }\n if (!history.nextPageToken) {\n drained = true\n break\n }\n pageToken = history.nextPageToken\n if (collected.length >= limit) break\n }\n\n const { messages, hardFailed } = await this.fetchAndNormalize(api, auth, collected, accountIdentifier)\n const nextState: GmailChannelState = {\n lastSyncedAt: new Date().toISOString(),\n }\n if (hardFailed) {\n // L3: a message failed transiently. Restart the window from startHistoryId\n // on the next tick (drop any page token) so every page \u2014 including the one\n // carrying the failed message \u2014 is re-read; already-ingested messages dedup\n // at the hub. Do NOT advance the terminal historyId or pin a forward token,\n // which would skip the failed message's page.\n nextState.historyId = startHistoryId\n } else if (drained) {\n // All pages drained \u2014 advance the terminal historyId.\n nextState.historyId = lastResponseHistoryId ?? startHistoryId\n } else {\n // Mid-drain \u2014 keep the prior startHistoryId pinned + remember the next\n // unconsumed pageToken so the following tick resumes without re-walking.\n nextState.historyId = startHistoryId\n nextState.pendingHistoryPageToken = pageToken\n }\n return {\n messages,\n nextCursor: encodeCursor(nextState),\n // Re-enqueue immediately when a transient failure left work behind.\n hasMore: hardFailed || !drained,\n }\n }\n\n private async startMessagesListFallback(\n api: ReturnType<typeof getGmailApiClient>,\n auth: { accessToken: string },\n accountIdentifier: string,\n historyIdSnapshot: string,\n limit: number,\n ): Promise<HistoryPage> {\n const list = await api.listMessages(auth, {\n labelIds: ['INBOX'],\n maxResults: limit,\n })\n const refs = (list.messages ?? []).map((m) => ({\n id: m.id,\n threadId: m.threadId,\n labelIds: ['INBOX'],\n }))\n const { messages, hardFailed } = await this.fetchAndNormalize(api, auth, refs, accountIdentifier)\n const drained = !list.nextPageToken\n const nextState: GmailChannelState = {\n lastSyncedAt: new Date().toISOString(),\n }\n if (hardFailed) {\n // L3: this is the FIRST fallback page (no prior page token), so there is\n // nothing to pin. Deliberately leave `historyId` unset so the cursor does\n // NOT advance past the unprocessed messages \u2014 the next tick re-enters the\n // same fallback scan and retries them.\n nextState.pendingMessagesHistoryIdSnapshot = historyIdSnapshot\n } else if (drained) {\n nextState.historyId = historyIdSnapshot\n } else {\n nextState.pendingMessagesPageToken = list.nextPageToken\n nextState.pendingMessagesHistoryIdSnapshot = historyIdSnapshot\n }\n return {\n messages,\n nextCursor: encodeCursor(nextState),\n hasMore: hardFailed || !drained,\n }\n }\n\n private async continueMessagesListDrain(\n api: ReturnType<typeof getGmailApiClient>,\n auth: { accessToken: string },\n accountIdentifier: string,\n channelState: GmailChannelState,\n limit: number,\n ): Promise<HistoryPage> {\n const list = await api.listMessages(auth, {\n labelIds: ['INBOX'],\n maxResults: limit,\n pageToken: channelState.pendingMessagesPageToken,\n })\n const refs = (list.messages ?? []).map((m) => ({\n id: m.id,\n threadId: m.threadId,\n labelIds: ['INBOX'],\n }))\n const { messages, hardFailed } = await this.fetchAndNormalize(api, auth, refs, accountIdentifier)\n const drained = !list.nextPageToken\n const nextState: GmailChannelState = {\n lastSyncedAt: new Date().toISOString(),\n }\n if (hardFailed) {\n // L3: re-pin the SAME page token (not list.nextPageToken) so the next\n // tick re-fetches this page and retries the unprocessed messages.\n nextState.pendingMessagesPageToken = channelState.pendingMessagesPageToken\n nextState.pendingMessagesHistoryIdSnapshot = channelState.pendingMessagesHistoryIdSnapshot\n } else if (drained) {\n nextState.historyId = channelState.pendingMessagesHistoryIdSnapshot ?? channelState.historyId\n } else {\n nextState.pendingMessagesPageToken = list.nextPageToken\n nextState.pendingMessagesHistoryIdSnapshot = channelState.pendingMessagesHistoryIdSnapshot\n }\n return {\n messages,\n nextCursor: encodeCursor(nextState),\n hasMore: hardFailed || !drained,\n }\n }\n\n /**\n * Operator-triggered backlog import (Spec B \u00A7 Phase B6).\n *\n * Reaches BACKWARD in time over `gmail.users.messages.list?q=\u2026`, independent\n * of the forward-polling `historyId` cursor \u2014 nothing here reads or writes\n * `GmailChannelState`, so a multi-year backfill can never move the live poll\n * cursor.\n *\n * Scale contract: the cursor carries Gmail's own `nextPageToken` plus a\n * collected counter and the frozen query, so it stays a few hundred bytes for\n * a 50k-message mailbox. Message ids are never enumerated up front.\n */\n async importHistory(input: ImportHistoryInput): Promise<ImportHistoryPage> {\n const userCredentials = parseUserCredentialsOrThrow(input.credentials)\n const auth = { accessToken: userCredentials.accessToken }\n const api = getGmailApiClient()\n const accountIdentifier = userCredentials.email ?? 'me'\n\n const maxMessages = clampImportMaxMessages(input.maxMessages)\n const pageSize = resolveImportPageSize()\n const concurrency = resolveImportConcurrency()\n\n const cursor = decodeGmailImportCursor(input.cursor)\n const afterTerm = cursor?.after ?? buildAfterTerm(clampImportSinceDays(input.sinceDays))\n const queries = buildImportQueries(afterTerm, input.contactEmails)\n\n let queryIndex = cursor ? cursor.queryIndex : 0\n let pageToken = cursor?.pageToken\n const collectedSoFar = cursor?.collected ?? 0\n let activeQuery: string | undefined = cursor?.query ?? queries[queryIndex]\n\n const budget = Math.max(0, maxMessages - collectedSoFar)\n if (budget === 0 || queryIndex >= queries.length) {\n return { messages: [], hasMore: false }\n }\n\n const perPage = Math.min(pageSize, budget)\n const refs: Array<{ id: string; threadId: string }> = []\n let listCalls = 0\n while (refs.length < perPage && queryIndex < queries.length && listCalls < IMPORT_MAX_LIST_CALLS_PER_PAGE) {\n listCalls += 1\n const list = await api.listMessages(auth, {\n query: activeQuery,\n labelIds: ['INBOX'],\n pageToken,\n maxResults: perPage - refs.length,\n })\n for (const message of list.messages ?? []) {\n refs.push({ id: message.id, threadId: message.threadId })\n }\n if (list.nextPageToken) {\n pageToken = list.nextPageToken\n continue\n }\n queryIndex += 1\n pageToken = undefined\n activeQuery = queries[queryIndex]\n }\n\n const messages = await this.fetchAndNormalizeForImport(api, auth, refs, accountIdentifier, concurrency)\n\n const collected = collectedSoFar + messages.length\n const exhausted = pageToken === undefined && queryIndex >= queries.length\n const hasMore = !exhausted && collected < maxMessages\n const nextCursor = hasMore\n ? encodeCursor({\n v: GMAIL_IMPORT_CURSOR_VERSION,\n after: afterTerm,\n query: queries[queryIndex] ?? activeQuery ?? queries[queries.length - 1],\n queryIndex,\n pageToken,\n collected,\n } satisfies GmailImportCursor)\n : undefined\n\n return { messages, nextCursor, hasMore }\n }\n\n /**\n * Import-path fetch. Diverges from `fetchAndNormalize` deliberately: the\n * forward path stops at the first hard failure to protect the polling cursor,\n * whereas a backlog import has no cursor to protect and must not abandon a\n * multi-year sweep over one unreadable message \u2014 so a per-message failure is\n * skipped and logged. Only credential/permission failures (401/403), which\n * would fail every remaining message too, abort the page.\n */\n private async fetchAndNormalizeForImport(\n api: ReturnType<typeof getGmailApiClient>,\n auth: { accessToken: string },\n refs: Array<{ id: string; threadId: string }>,\n accountIdentifier: string,\n concurrency: number,\n ): Promise<NormalizedInboundMessage[]> {\n const results = new Array<NormalizedInboundMessage | null>(refs.length).fill(null)\n let nextIndex = 0\n const workerCount = Math.max(1, Math.min(concurrency, refs.length))\n\n const runWorker = async (): Promise<void> => {\n while (true) {\n const index = nextIndex\n nextIndex += 1\n if (index >= refs.length) return\n const ref = refs[index]\n try {\n const raw = await api.getMessageRaw(auth, ref.id)\n const fallbackDate = raw.internalDate ? new Date(Number(raw.internalDate)) : undefined\n results[index] = await normalizeInboundGmailMessage({\n rawMessage: decodeBase64Url(raw.raw),\n gmailMessageId: raw.id,\n gmailThreadId: raw.threadId,\n gmailLabelIds: raw.labelIds ?? [],\n accountIdentifier,\n fallbackDate,\n })\n } catch (error) {\n if (isFatalGmailImportError(error)) throw error\n logger.warn('skipping unreadable message during history import', {\n gmailMessageId: ref.id,\n reason: error instanceof Error ? error.message.slice(0, 200) : 'unknown error',\n })\n }\n }\n }\n\n await Promise.all(Array.from({ length: workerCount }, () => runWorker()))\n return results.filter((message): message is NormalizedInboundMessage => message !== null)\n }\n\n async deleteMessage(input: DeleteChannelMessageInput): Promise<void> {\n const userCredentials = parseUserCredentialsOrThrow(input.credentials)\n const api = getGmailApiClient()\n // Gmail's \"delete\" capability is delivered as Trash to match the user's\n // mental model and avoid permanent loss on accidental clicks. The user can\n // restore from Trash in the Gmail web UI within 30 days.\n await api.trashMessage({ accessToken: userCredentials.accessToken }, input.externalMessageId)\n }\n\n async resolveContact(input: ResolveContactInput): Promise<ContactHint | null> {\n return emailResolveContact(input)\n }\n\n /**\n * Fetch + normalize each collected message ref.\n *\n * L3 fix: a non-404/410 error on `getMessageRaw` (e.g. a transient 500/403)\n * used to re-throw and abort the whole tick, discarding messages that had\n * already normalized in the same page. Worse, because the cursor could be\n * advanced from a different source (a push notification carrying a higher\n * historyId), the transiently-failed messages could be skipped permanently.\n *\n * We now treat a hard failure as a stop point: keep the messages normalized\n * BEFORE the failure and signal `hardFailed: true` so the caller pins the\n * persisted `historyId` (does NOT advance past the failure) and re-fetches on\n * the next tick. 404/410 stay skipped (the message is genuinely gone).\n */\n private async fetchAndNormalize(\n api: ReturnType<typeof getGmailApiClient>,\n auth: { accessToken: string },\n refs: Array<{ id: string; threadId: string; labelIds?: string[] }>,\n accountIdentifier: string,\n ): Promise<{ messages: NormalizedInboundMessage[]; hardFailed: boolean }> {\n const out: NormalizedInboundMessage[] = []\n for (const ref of refs) {\n let raw: GmailGetMessageRawResponse\n try {\n raw = await api.getMessageRaw(auth, ref.id)\n } catch (error) {\n // 404/410: the message is gone \u2014 skip it and keep draining.\n if (error instanceof GmailApiError && (error.status === 404 || error.status === 410)) continue\n // Any other failure is potentially transient. Stop here without\n // advancing past the unprocessed messages so the next tick retries them.\n return { messages: out, hardFailed: true }\n }\n const rawBuffer = decodeBase64Url(raw.raw)\n // `internalDate` is when Gmail received the message; the MIME Date header\n // is the sender's and must not date the platform message (#6095).\n const receivedAt = raw.internalDate ? new Date(Number(raw.internalDate)) : undefined\n const normalized = await normalizeInboundGmailMessage({\n rawMessage: rawBuffer,\n gmailMessageId: raw.id,\n gmailThreadId: raw.threadId,\n gmailLabelIds: raw.labelIds ?? ref.labelIds ?? [],\n accountIdentifier,\n receivedAt,\n })\n out.push(normalized)\n }\n return { messages: out, hardFailed: false }\n }\n}\n\n// \u2500\u2500 Backlog import (importHistory) helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst GMAIL_IMPORT_CURSOR_VERSION = 1\nconst IMPORT_SINCE_DAYS_MIN = 1\nconst IMPORT_SINCE_DAYS_DEFAULT = IMPORT_HISTORY_DEFAULT_SINCE_DAYS\nconst IMPORT_MAX_MESSAGES_MIN = 1\nconst IMPORT_MAX_MESSAGES_DEFAULT = IMPORT_HISTORY_DEFAULT_MAX_MESSAGES\nconst IMPORT_PAGE_SIZE_DEFAULT = 100\n/** `users.messages.list` rejects `maxResults` above 500. */\nconst IMPORT_PAGE_SIZE_MAX = 500\nconst IMPORT_CONCURRENCY_DEFAULT = 5\nconst IMPORT_CONCURRENCY_MAX = 20\n/** Senders per `from:(\u2026 OR \u2026)` group \u2014 keeps each `q` well inside Gmail's URL budget. */\nconst IMPORT_SENDER_CHUNK_SIZE = 25\n/** Matches the hub's `contactEmails` ceiling; bounds the number of query groups. */\nconst IMPORT_SENDER_MAX = 200\n/** Bounds `messages.list` round-trips inside a single page when groups come back empty. */\nconst IMPORT_MAX_LIST_CALLS_PER_PAGE = 25\n\ninterface GmailImportCursor {\n v: number\n /** Frozen `after:<epochSeconds>` term so later pages cannot drift with wall-clock. */\n after: string\n /** Frozen full query for the group the next page resumes on. */\n query: string\n queryIndex: number\n pageToken?: string\n collected: number\n}\n\nfunction clampImportSinceDays(value: number): number {\n const raw = Number.isFinite(value) ? Math.trunc(value) : IMPORT_SINCE_DAYS_DEFAULT\n return Math.max(IMPORT_SINCE_DAYS_MIN, Math.min(getImportHistoryMaxSinceDays(), raw))\n}\n\nfunction clampImportMaxMessages(value: number | undefined): number {\n const raw = Number.isFinite(value) ? Math.trunc(value as number) : IMPORT_MAX_MESSAGES_DEFAULT\n return Math.max(IMPORT_MAX_MESSAGES_MIN, Math.min(getImportHistoryMaxMessages(), raw))\n}\n\nfunction resolveEnvInt(name: string, fallback: number, max: number): number {\n const parsed = Number.parseInt(process.env[name] ?? '', 10)\n if (!Number.isFinite(parsed) || parsed <= 0) return fallback\n return Math.min(parsed, max)\n}\n\nfunction resolveImportPageSize(): number {\n return resolveEnvInt('OM_CHANNEL_GMAIL_IMPORT_PAGE_SIZE', IMPORT_PAGE_SIZE_DEFAULT, IMPORT_PAGE_SIZE_MAX)\n}\n\nfunction resolveImportConcurrency(): number {\n return resolveEnvInt('OM_CHANNEL_GMAIL_IMPORT_CONCURRENCY', IMPORT_CONCURRENCY_DEFAULT, IMPORT_CONCURRENCY_MAX)\n}\n\n/**\n * Gmail accepts `after:` as either `YYYY/MM/DD` \u2014 resolved in the mailbox\n * owner's display timezone, so the boundary day is ambiguous \u2014 or as a Unix\n * timestamp in seconds, which is not. We emit the timestamp form.\n *\n * Either form filters on Gmail's INTERNAL date (when Gmail received the\n * message), not the `Date:` header, so a message with an old header that was\n * recently delivered or migrated into the mailbox counts as recent.\n */\nfunction buildAfterTerm(sinceDays: number): string {\n const epochSeconds = Math.floor((Date.now() - sinceDays * 24 * 60 * 60 * 1000) / 1000)\n return `after:${Math.max(0, epochSeconds)}`\n}\n\nfunction normalizeImportSenders(contactEmails: string[] | undefined): string[] {\n const seen = new Set<string>()\n for (const raw of contactEmails ?? []) {\n if (typeof raw !== 'string') continue\n const trimmed = raw.trim().toLowerCase()\n if (!trimmed.includes('@') || /[\\s\"()]/.test(trimmed)) continue\n seen.add(trimmed)\n if (seen.size >= IMPORT_SENDER_MAX) break\n }\n return Array.from(seen)\n}\n\n/**\n * Build the ordered list of Gmail queries this import walks.\n *\n * Gmail's `q` rides in the request URL, so a 200-address `from:(\u2026 OR \u2026)` chain\n * would blow past a practical URL budget. Senders are therefore split into\n * groups of `IMPORT_SENDER_CHUNK_SIZE` and the groups are walked SEQUENTIALLY\n * across pages (the cursor records which group is active). Groups are disjoint\n * by construction \u2014 a message has exactly one `From` \u2014 so no cross-group dedup\n * is needed. With no sender hint a single date-only query is returned.\n */\nfunction buildImportQueries(afterTerm: string, contactEmails: string[] | undefined): string[] {\n const senders = normalizeImportSenders(contactEmails)\n if (senders.length === 0) return [afterTerm]\n const queries: string[] = []\n for (let index = 0; index < senders.length; index += IMPORT_SENDER_CHUNK_SIZE) {\n const group = senders.slice(index, index + IMPORT_SENDER_CHUNK_SIZE)\n queries.push(`${afterTerm} from:(${group.join(' OR ')})`)\n }\n return queries\n}\n\nfunction decodeGmailImportCursor(value: string | undefined): GmailImportCursor | null {\n const parsed = decodeCursor(value)\n if (!parsed || typeof parsed !== 'object') return null\n const candidate = parsed as Partial<Record<keyof GmailImportCursor, unknown>>\n if (candidate.v !== GMAIL_IMPORT_CURSOR_VERSION) return null\n if (typeof candidate.after !== 'string' || typeof candidate.query !== 'string') return null\n const queryIndex = typeof candidate.queryIndex === 'number' && candidate.queryIndex >= 0 ? Math.trunc(candidate.queryIndex) : 0\n const collected = typeof candidate.collected === 'number' && candidate.collected >= 0 ? Math.trunc(candidate.collected) : 0\n const pageToken = typeof candidate.pageToken === 'string' && candidate.pageToken.length > 0 ? candidate.pageToken : undefined\n return {\n v: GMAIL_IMPORT_CURSOR_VERSION,\n after: candidate.after,\n query: candidate.query,\n queryIndex,\n pageToken,\n collected,\n }\n}\n\n/**\n * A 401 (expired/revoked grant) or a 403 that survived the client's bounded\n * retry (permission denied, or exhausted per-user quota) will fail every\n * remaining message in the sweep, so it aborts the page instead of being\n * skipped message by message.\n */\nfunction isFatalGmailImportError(error: unknown): boolean {\n return error instanceof GmailApiError && (error.status === 401 || error.status === 403)\n}\n\nfunction collectMessageRefs(\n history: Array<{\n messagesAdded?: Array<{ message: { id: string; threadId: string; labelIds?: string[] } }>\n }>,\n): Array<{ id: string; threadId: string; labelIds?: string[] }> {\n const seen = new Set<string>()\n const refs: Array<{ id: string; threadId: string; labelIds?: string[] }> = []\n for (const entry of history) {\n for (const added of entry.messagesAdded ?? []) {\n if (seen.has(added.message.id)) continue\n seen.add(added.message.id)\n refs.push({ id: added.message.id, threadId: added.message.threadId, labelIds: added.message.labelIds })\n }\n }\n return refs\n}\n\nfunction parseUserCredentialsOrThrow(value: unknown): GmailUserCredentials {\n const parsed = gmailUserCredentialsSchema.safeParse(value)\n if (!parsed.success) {\n const first = parsed.error.issues[0]\n throw new Error(`Invalid Gmail credentials: ${first?.message ?? 'unknown validation error'}`)\n }\n return parsed.data\n}\n\nfunction parseClientCredentialsOrThrow(value: unknown): GmailClientCredentials {\n const parsed = gmailClientCredentialsSchema.safeParse(value)\n if (!parsed.success) {\n const first = parsed.error.issues[0]\n throw new Error(`Invalid Gmail OAuth client credentials: ${first?.message ?? 'unknown validation error'}`)\n }\n return parsed.data\n}\n\nlet warnedLegacyClientPath = false\n\n/**\n * Resolve the OAuth client config for a Gmail refresh, preferring the new\n * `RefreshCredentialsInput.oauthClient` field (Spec A,\n * .ai/specs/implemented/2026-05-27-email-integration-inbound-reliability-and-threading.md).\n *\n * Falls back to the deprecated `credentials._client` read path for one\n * minor release so existing tests keep working. The legacy path emits a\n * one-time deprecation warning per process so production logs stay quiet.\n */\nfunction resolveGmailOAuthClient(input: RefreshCredentialsInput): GmailClientCredentials {\n if (input.oauthClient) {\n const client = input.oauthClient\n if (!client.clientId) {\n throw new Error('[internal] Invalid Gmail OAuth client credentials: OAuth Client ID required')\n }\n if (!client.clientSecret) {\n throw new Error('[internal] Invalid Gmail OAuth client credentials: clientSecret required')\n }\n return {\n clientId: client.clientId,\n clientSecret: client.clientSecret,\n // `GmailClientCredentials.scopes` is the wire format the legacy\n // `credentials._client` blob carried \u2014 comma/space-separated string.\n // Spec A's `OAuthClientConfig.scopes` is the canonical `string[]`.\n // `parseScopes` accepts either separator, so join with a single space.\n ...(client.scopes !== undefined ? { scopes: client.scopes.join(' ') } : {}),\n }\n }\n // Legacy path \u2014 DEPRECATED. Remove in the next minor release.\n if (!warnedLegacyClientPath) {\n warnedLegacyClientPath = true\n logger.warn(\n 'reading OAuth client config from credentials._client is deprecated;' +\n ' pass via RefreshCredentialsInput.oauthClient instead (Spec A)',\n )\n }\n return parseClientCredentialsOrThrow(\n (input.credentials as unknown as { _client?: unknown })._client ?? input.credentials,\n )\n}\n\nfunction pickRawMimeBuffer(payload: { rawBase64Url?: unknown; rawBody?: unknown }): Buffer {\n if (typeof payload.rawBase64Url === 'string') return decodeBase64Url(payload.rawBase64Url)\n const value = payload.rawBody\n if (Buffer.isBuffer(value)) return value\n if (value instanceof Uint8Array) return Buffer.from(value)\n if (typeof value === 'string') return Buffer.from(value, 'utf-8')\n throw new Error('[internal] Gmail normalizeInbound requires `raw.rawBase64Url` or `raw.rawBody`')\n}\n\nlet cachedAdapter: GmailChannelAdapter | null = null\n\nexport function getGmailChannelAdapter(): GmailChannelAdapter {\n if (!cachedAdapter) cachedAdapter = new GmailChannelAdapter()\n return cachedAdapter\n}\n\nexport { GmailChannelAdapter }\n"],
5
- "mappings": "AA6BA,SAAS,yBAAyB;AAClC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,E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NotificationInput,\n ChannelAdapter,\n ChannelNativeContent,\n ConvertOutboundInput,\n BuildOAuthAuthorizeUrlInput,\n BuildOAuthAuthorizeUrlResult,\n DeleteChannelMessageInput,\n ExchangeOAuthCodeInput,\n ExchangeOAuthCodeResult,\n FetchHistoryInput,\n GetMessageStatusInput,\n HistoryPage,\n ImportHistoryInput,\n ImportHistoryPage,\n InboundMessage,\n MessageStatus,\n NormalizedInboundMessage,\n PushRegistration,\n RefreshCredentialsInput,\n RefreshedCredentials,\n RegisterPushInput,\n ResolveContactInput,\n ContactHint,\n SendMessageInput,\n SendMessageResult,\n UnregisterPushInput,\n VerifyWebhookInput,\n} from '@open-mercato/core/modules/communication_channels/lib/adapter'\nimport { gmailCapabilities } from './capabilities'\nimport {\n gmailChannelStateSchema,\n gmailClientCredentialsSchema,\n gmailUserCredentialsSchema,\n parseScopes,\n type GmailChannelState,\n type GmailClientCredentials,\n type GmailUserCredentials,\n} from './credentials'\nimport {\n decodeBase64Url,\n encodeBase64Url,\n getGmailApiClient,\n GmailApiError,\n type GmailGetMessageRawResponse,\n} from './gmail-client'\nimport {\n getGoogleOAuthClient,\n tokenResponseToExpiresAt,\n} from './oauth'\nimport {\n convertOutboundForGmail,\n type GmailEmailNativeMetadata,\n} from './convert-outbound'\nimport { normalizeInboundGmailMessage } from './normalize-inbound'\nimport { emailResolveContact } from '@open-mercato/core/modules/communication_channels/lib/email-contact'\nimport { decodeCursor, encodeCursor } from '@open-mercato/core/modules/communication_channels/lib/email-mime'\nimport {\n IMPORT_HISTORY_DEFAULT_SINCE_DAYS,\n IMPORT_HISTORY_DEFAULT_MAX_MESSAGES,\n getImportHistoryMaxSinceDays,\n getImportHistoryMaxMessages,\n} from '@open-mercato/core/modules/communication_channels/lib/import-history-limits'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('channel_gmail')\n\n/**\n * Gmail `ChannelAdapter`. OAuth2-based, polling-driven (`realtimePush: false`).\n *\n * Credential shape on `CommunicationChannel.credentials`:\n * - Per-user: `{ accessToken, refreshToken?, expiresAt?, scopes?, email? }`\n * - Tenant OAuth client config sits on `IntegrationCredentials.credentials`\n * for the `gmail` provider: `{ clientId, clientSecret, scopes? }`. The hub\n * looks it up by `(tenantId, providerKey='gmail')` and passes it to\n * `buildOAuthAuthorizeUrl` + `exchangeOAuthCode` + `refreshCredentials`.\n *\n * Sync model:\n * - First poll on a fresh channel reads `gmail.users.getProfile.historyId`\n * and persists it; no message fetch is done on the bootstrap call (the\n * existing inbox is intentionally not back-filled, matching the spec).\n * - Subsequent polls call `gmail.users.history.list?startHistoryId=\u2026` and\n * fetch each `messagesAdded` entry's RAW payload.\n * - If the server returns `404` for the history id (Gmail keeps ~7 days),\n * we fall back to `gmail.users.messages.list?labelIds=INBOX` and persist\n * the new historyId from the next `getProfile` call.\n */\nclass GmailChannelAdapter implements ChannelAdapter {\n readonly providerKey = 'gmail'\n readonly channelType = 'email'\n readonly capabilities = gmailCapabilities\n\n async sendMessage(input: SendMessageInput): Promise<SendMessageResult> {\n const userCredentials = parseUserCredentialsOrThrow(input.credentials)\n let native: ChannelNativeContent\n try {\n native = await convertOutboundForGmail({\n body: input.content.html ?? input.content.text ?? '',\n bodyFormat: input.content.bodyFormat ?? (input.content.html ? 'html' : 'text'),\n attachments: input.content.attachments,\n channelMetadata: input.metadata,\n fromAddress: userCredentials.email ?? 'me',\n })\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Outbound conversion failed'\n return { externalMessageId: '', status: 'failed', error: message }\n }\n\n const nativeMeta = native.metadata as unknown as GmailEmailNativeMetadata\n const rawBase64Url = encodeBase64Url(nativeMeta.rawMessage)\n\n try {\n const response = await getGmailApiClient().sendRawMessage(\n { accessToken: userCredentials.accessToken },\n { rawBase64Url, threadId: nativeMeta.threadId },\n )\n return {\n externalMessageId: nativeMeta.messageId ?? response.id,\n conversationId: response.threadId,\n status: 'sent',\n metadata: { gmailMessageId: response.id, gmailThreadId: response.threadId, labelIds: response.labelIds ?? [] },\n }\n } catch (error) {\n if (error instanceof GmailApiError && error.status === 401) {\n // `requires_reauth` is a protocol sentinel the hub keys on (see\n // communication_channels error-classification.isReauthError), not a\n // user/log message \u2014 do NOT prefix or translate it.\n return { externalMessageId: '', status: 'failed', error: 'requires_reauth' }\n }\n const message = error instanceof Error ? error.message : 'Gmail send failed'\n return { externalMessageId: '', status: 'failed', error: message }\n }\n }\n\n async verifyWebhook(_input: VerifyWebhookInput): Promise<InboundMessage> {\n // Gmail Pub/Sub push (Spec C) is handled by the dedicated `/webhooks/gmail`\n // route + `applyPushNotification`, not this generic hub-webhook hook, so this\n // returns an unhandled event for the generic route to ack 2xx.\n return { raw: {}, eventType: 'other', metadata: { reason: 'gmail-uses-polling-not-push' } }\n }\n\n async getStatus(_input: GetMessageStatusInput): Promise<MessageStatus> {\n // Gmail exposes no per-message delivery-status API, so we return a\n // best-effort `'sent'` placeholder (a later bounce is not reflected here).\n // Mirrors the IMAP adapter's documented behavior.\n return { status: 'sent' }\n }\n\n async convertOutbound(input: ConvertOutboundInput): Promise<ChannelNativeContent> {\n return convertOutboundForGmail({ ...input, fromAddress: 'me' })\n }\n\n async normalizeInbound(raw: InboundMessage): Promise<NormalizedInboundMessage> {\n const payload = raw.raw as {\n rawBase64Url?: unknown\n rawBody?: unknown\n gmailMessageId?: unknown\n gmailThreadId?: unknown\n labelIds?: unknown\n accountIdentifier?: unknown\n }\n const rawMessage = pickRawMimeBuffer(payload)\n const gmailMessageId = typeof payload.gmailMessageId === 'string' ? payload.gmailMessageId : 'unknown'\n const gmailThreadId = typeof payload.gmailThreadId === 'string' ? payload.gmailThreadId : gmailMessageId\n const labelIds = Array.isArray(payload.labelIds) ? (payload.labelIds.filter((v) => typeof v === 'string') as string[]) : []\n const accountIdentifier = typeof payload.accountIdentifier === 'string' ? payload.accountIdentifier : 'unknown@gmail'\n return normalizeInboundGmailMessage({\n rawMessage,\n gmailMessageId,\n gmailThreadId,\n gmailLabelIds: labelIds,\n accountIdentifier,\n })\n }\n\n async buildOAuthAuthorizeUrl(input: BuildOAuthAuthorizeUrlInput): Promise<BuildOAuthAuthorizeUrlResult> {\n const client = parseClientCredentialsOrThrow(input.credentials)\n const scopes = parseScopes(client.scopes)\n const url = getGoogleOAuthClient().buildAuthorizeUrl({\n clientId: client.clientId,\n redirectUri: input.redirectUri,\n state: input.state,\n scopes,\n loginHint: input.loginHint,\n })\n return { authorizeUrl: url, extra: { scopes } }\n }\n\n async exchangeOAuthCode(input: ExchangeOAuthCodeInput): Promise<ExchangeOAuthCodeResult> {\n const client = parseClientCredentialsOrThrow(input.credentials)\n const token = await getGoogleOAuthClient().exchangeCode({\n clientId: client.clientId,\n clientSecret: client.clientSecret,\n redirectUri: input.redirectUri,\n code: input.code,\n })\n let email: string | undefined\n let displayName: string | undefined\n try {\n const userInfo = await getGoogleOAuthClient().fetchUserInfo(token.access_token)\n email = userInfo.email\n displayName = userInfo.name ?? userInfo.email\n } catch {\n // Userinfo failure is non-fatal; fall back to the optional `id_token` parser later.\n }\n const expiresAt = tokenResponseToExpiresAt(token)\n const credentials: GmailUserCredentials = {\n accessToken: token.access_token,\n refreshToken: token.refresh_token,\n expiresAt: expiresAt?.toISOString(),\n scopes: token.scope ? token.scope.split(' ').filter(Boolean) : undefined,\n email,\n }\n return {\n credentials: credentials as unknown as Record<string, unknown>,\n externalIdentifier: email,\n displayName: displayName ?? email,\n expiresAt,\n }\n }\n\n async refreshCredentials(input: RefreshCredentialsInput): Promise<RefreshedCredentials> {\n const current = parseUserCredentialsOrThrow(input.credentials)\n if (!current.refreshToken) {\n throw new Error('requires_reauth')\n }\n // Spec A: OAuth client config comes only from `input.oauthClient` (resolved\n // by the hub from the `channel_gmail` integration's tenant-scoped row).\n const clientFromState = resolveGmailOAuthClient(input)\n const token = await getGoogleOAuthClient().refreshToken({\n clientId: clientFromState.clientId,\n clientSecret: clientFromState.clientSecret,\n refreshToken: current.refreshToken,\n })\n const expiresAt = tokenResponseToExpiresAt(token)\n const refreshed: GmailUserCredentials = {\n accessToken: token.access_token,\n // Google does NOT always return a new refresh token \u2014 keep the existing one.\n refreshToken: token.refresh_token ?? current.refreshToken,\n expiresAt: expiresAt?.toISOString(),\n scopes: token.scope ? token.scope.split(' ').filter(Boolean) : current.scopes,\n email: current.email,\n }\n return {\n credentials: refreshed as unknown as Record<string, unknown>,\n expiresAt,\n }\n }\n\n async fetchHistory(input: FetchHistoryInput): Promise<HistoryPage> {\n const userCredentials = parseUserCredentialsOrThrow(input.credentials)\n const channelState = gmailChannelStateSchema.parse(input.channelState ?? {})\n const auth = { accessToken: userCredentials.accessToken }\n const api = getGmailApiClient()\n const limit = input.limit ?? 50\n\n // L3 first-page retry: a prior fallback scan hard-failed on its FIRST page and\n // pinned only the history snapshot (no page token). Re-enter the fallback scan\n // from the first INBOX page so unprocessed messages are retried, not skipped by\n // the bootstrap path below.\n if (channelState.pendingMessagesHistoryIdSnapshot && !channelState.pendingMessagesPageToken) {\n return await this.startMessagesListFallback(\n api,\n auth,\n userCredentials.email ?? 'me',\n channelState.pendingMessagesHistoryIdSnapshot,\n limit,\n )\n }\n\n // Bootstrap path: no historyId yet \u2192 just persist current historyId and skip fetch.\n if (!channelState.historyId && !channelState.pendingMessagesPageToken) {\n const profile = await api.getProfile(auth)\n const nextState: GmailChannelState = {\n historyId: profile.historyId,\n lastSyncedAt: new Date().toISOString(),\n }\n return {\n messages: [],\n nextCursor: encodeCursor(nextState),\n hasMore: false,\n }\n }\n\n // Mid-drain fallback (404 path): we previously fell back to messages.list\n // for an expired historyId and still have pages to drain. Resume from the\n // stored pageToken without re-issuing the history.list call.\n if (channelState.pendingMessagesPageToken) {\n return await this.continueMessagesListDrain(\n api,\n auth,\n userCredentials.email ?? 'me',\n channelState,\n limit,\n )\n }\n\n // Incremental path: history.list since stored historyId, walking\n // nextPageToken until either (a) all pages drained, or (b) we've collected\n // `limit` messages.\n // CRITICAL: terminal historyId is ONLY advanced after full drain. While a\n // pending pageToken exists in channelState, the original startHistoryId is\n // retained so the next tick re-enters the same history window.\n let messages: NormalizedInboundMessage[] = []\n try {\n return await this.continueHistoryListDrain(\n api,\n auth,\n userCredentials.email ?? 'me',\n channelState,\n String(channelState.historyId),\n limit,\n )\n } catch (error) {\n if (error instanceof GmailApiError && error.status === 404) {\n // Gmail history expired (~7-day retention). Fall back to a paged inbox\n // scan via messages.list. Snapshot the post-fallback historyId now so\n // we can advance it once the messages.list drain completes.\n const profile = await api.getProfile(auth)\n return await this.startMessagesListFallback(\n api,\n auth,\n userCredentials.email ?? 'me',\n profile.historyId,\n limit,\n )\n }\n throw error\n }\n }\n\n /**\n * Spec C \u00A7 Phase C2 \u2014 Register Gmail Pub/Sub watch.\n *\n * Calls `gmail.users.watch` with the operator-configured Pub/Sub topic.\n * Returns `historyId` (cursor for subsequent `history.list` calls) and\n * `expiration` (ms since epoch \u2014 Gmail caps at ~7 days). Persists both\n * onto `CommunicationChannel.channelState` via the hub's\n * `push.register` command.\n */\n async registerPush(input: RegisterPushInput): Promise<PushRegistration> {\n const userCredentials = parseUserCredentialsOrThrow(input.credentials)\n const auth = { accessToken: userCredentials.accessToken }\n const api = getGmailApiClient()\n const topicName = (input.providerConfig?.pubsubTopic as string | undefined) ?? ''\n if (!topicName) {\n return {\n providerKey: this.providerKey,\n status: 'failed',\n channelStatePatch: {\n pushStatus: 'failed',\n lastPushError: {\n code: 'missing_topic',\n message: 'Pub/Sub topic not configured',\n at: new Date().toISOString(),\n },\n },\n error: {\n code: 'missing_topic',\n message: 'OM_GMAIL_PUBSUB_TOPIC not configured for this tenant',\n },\n }\n }\n try {\n const result = await api.watchInbox(auth, { topicName, labelIds: ['INBOX'] })\n const expirationMs = Number(result.expiration)\n return {\n providerKey: this.providerKey,\n status: 'active',\n channelStatePatch: {\n historyId: result.historyId,\n watchExpirationMs: Number.isFinite(expirationMs) ? expirationMs : Date.now() + 6 * 24 * 3600 * 1000,\n pubsubTopic: topicName,\n pushStatus: 'active',\n lastPushError: null,\n },\n recommendedPollIntervalSeconds: 1800,\n }\n } catch (error) {\n const status = error instanceof GmailApiError ? error.status : 0\n const detail = error instanceof Error ? error.message : 'watch failed'\n return {\n providerKey: this.providerKey,\n status: 'failed',\n channelStatePatch: {\n pushStatus: 'failed',\n lastPushError: {\n code: `gmail_watch_${status || 'error'}`,\n message: detail.slice(0, 500),\n at: new Date().toISOString(),\n },\n },\n error: { code: `gmail_watch_${status || 'error'}`, message: detail },\n }\n }\n }\n\n /**\n * Spec C \u00A7 Phase C2 \u2014 Tear down Gmail watch via `gmail.users.stop`.\n * Idempotent: a 404 (no active watch) is swallowed.\n */\n async unregisterPush(input: UnregisterPushInput): Promise<void> {\n const userCredentials = parseUserCredentialsOrThrow(input.credentials)\n const auth = { accessToken: userCredentials.accessToken }\n const api = getGmailApiClient()\n try {\n await api.stopWatch(auth)\n } catch (error) {\n if (error instanceof GmailApiError && error.status === 404) return\n throw error\n }\n }\n\n /**\n * Spec C \u00A7 Phase C2 \u2014 Convert a verified Pub/Sub notification into a\n * `HistoryPage`. The notification body itself is just `{ emailAddress,\n * historyId }`; the actual messages come from `history.list` against\n * `channelState.historyId`. We delegate to `fetchHistory` so the\n * pagination / 404-fallback logic stays in one place.\n */\n async applyPushNotification(input: ApplyPushNotificationInput): Promise<HistoryPage> {\n // The notification's `historyId` is informational \u2014 Gmail guarantees\n // it is `>= channelState.historyId`, but a multi-event batch may\n // advance further than what `history.list` returns in a single page.\n // Treat the call as \"drain whatever is new since the stored cursor\".\n // If `channelState.historyId` is absent (a push arrived before the cursor\n // was seeded), `fetchHistory` bootstraps \u2014 persists the current historyId\n // and returns zero messages \u2014 so this notification's delta is picked up on\n // the next call. In practice `registerPush` seeds the cursor before any\n // push flows, so this edge is not hit in the normal lifecycle.\n return this.fetchHistory({\n conversationId: 'INBOX',\n credentials: input.credentials,\n channelState: input.channelState,\n scope: input.scope,\n // Push notifications are bursty (1/s max per Gmail user); use a\n // smaller per-call limit so the worker drains quickly between\n // notifications without holding the API quota.\n limit: 50,\n } as FetchHistoryInput)\n }\n\n private async continueHistoryListDrain(\n api: ReturnType<typeof getGmailApiClient>,\n auth: { accessToken: string },\n accountIdentifier: string,\n channelState: GmailChannelState,\n startHistoryId: string,\n limit: number,\n ): Promise<HistoryPage> {\n const collected: Array<{ id: string; threadId: string; labelIds?: string[] }> = []\n const seen = new Set<string>()\n let pageToken: string | undefined = channelState.pendingHistoryPageToken\n let lastResponseHistoryId: string | undefined\n let drained = false\n\n // Fully consume each page before deciding to stop: `pageToken` must only ever\n // advance past refs we have actually collected, otherwise a page carrying more\n // than `limit` new refs would silently drop the overflow. `collected` may\n // therefore exceed `limit` by up to one page \u2014 bounded and intentional.\n while (true) {\n const history = await api.listHistory(auth, {\n startHistoryId,\n pageToken,\n })\n lastResponseHistoryId = history.historyId ?? lastResponseHistoryId\n for (const ref of collectMessageRefs(history.history ?? [])) {\n if (seen.has(ref.id)) continue\n seen.add(ref.id)\n collected.push(ref)\n }\n if (!history.nextPageToken) {\n drained = true\n break\n }\n pageToken = history.nextPageToken\n if (collected.length >= limit) break\n }\n\n const { messages, hardFailed } = await this.fetchAndNormalize(api, auth, collected, accountIdentifier)\n const nextState: GmailChannelState = {\n lastSyncedAt: new Date().toISOString(),\n }\n if (hardFailed) {\n // L3: a message failed transiently. Restart the window from startHistoryId\n // on the next tick (drop any page token) so every page \u2014 including the one\n // carrying the failed message \u2014 is re-read; already-ingested messages dedup\n // at the hub. Do NOT advance the terminal historyId or pin a forward token,\n // which would skip the failed message's page.\n nextState.historyId = startHistoryId\n } else if (drained) {\n // All pages drained \u2014 advance the terminal historyId.\n nextState.historyId = lastResponseHistoryId ?? startHistoryId\n } else {\n // Mid-drain \u2014 keep the prior startHistoryId pinned + remember the next\n // unconsumed pageToken so the following tick resumes without re-walking.\n nextState.historyId = startHistoryId\n nextState.pendingHistoryPageToken = pageToken\n }\n return {\n messages,\n nextCursor: encodeCursor(nextState),\n // Re-enqueue immediately when a transient failure left work behind.\n hasMore: hardFailed || !drained,\n }\n }\n\n private async startMessagesListFallback(\n api: ReturnType<typeof getGmailApiClient>,\n auth: { accessToken: string },\n accountIdentifier: string,\n historyIdSnapshot: string,\n limit: number,\n ): Promise<HistoryPage> {\n const list = await api.listMessages(auth, {\n labelIds: ['INBOX'],\n maxResults: limit,\n })\n const refs = (list.messages ?? []).map((m) => ({\n id: m.id,\n threadId: m.threadId,\n labelIds: ['INBOX'],\n }))\n const { messages, hardFailed } = await this.fetchAndNormalize(api, auth, refs, accountIdentifier)\n const drained = !list.nextPageToken\n const nextState: GmailChannelState = {\n lastSyncedAt: new Date().toISOString(),\n }\n if (hardFailed) {\n // L3: this is the FIRST fallback page (no prior page token), so there is\n // nothing to pin. Deliberately leave `historyId` unset so the cursor does\n // NOT advance past the unprocessed messages \u2014 the next tick re-enters the\n // same fallback scan and retries them.\n nextState.pendingMessagesHistoryIdSnapshot = historyIdSnapshot\n } else if (drained) {\n nextState.historyId = historyIdSnapshot\n } else {\n nextState.pendingMessagesPageToken = list.nextPageToken\n nextState.pendingMessagesHistoryIdSnapshot = historyIdSnapshot\n }\n return {\n messages,\n nextCursor: encodeCursor(nextState),\n hasMore: hardFailed || !drained,\n }\n }\n\n private async continueMessagesListDrain(\n api: ReturnType<typeof getGmailApiClient>,\n auth: { accessToken: string },\n accountIdentifier: string,\n channelState: GmailChannelState,\n limit: number,\n ): Promise<HistoryPage> {\n const list = await api.listMessages(auth, {\n labelIds: ['INBOX'],\n maxResults: limit,\n pageToken: channelState.pendingMessagesPageToken,\n })\n const refs = (list.messages ?? []).map((m) => ({\n id: m.id,\n threadId: m.threadId,\n labelIds: ['INBOX'],\n }))\n const { messages, hardFailed } = await this.fetchAndNormalize(api, auth, refs, accountIdentifier)\n const drained = !list.nextPageToken\n const nextState: GmailChannelState = {\n lastSyncedAt: new Date().toISOString(),\n }\n if (hardFailed) {\n // L3: re-pin the SAME page token (not list.nextPageToken) so the next\n // tick re-fetches this page and retries the unprocessed messages.\n nextState.pendingMessagesPageToken = channelState.pendingMessagesPageToken\n nextState.pendingMessagesHistoryIdSnapshot = channelState.pendingMessagesHistoryIdSnapshot\n } else if (drained) {\n nextState.historyId = channelState.pendingMessagesHistoryIdSnapshot ?? channelState.historyId\n } else {\n nextState.pendingMessagesPageToken = list.nextPageToken\n nextState.pendingMessagesHistoryIdSnapshot = channelState.pendingMessagesHistoryIdSnapshot\n }\n return {\n messages,\n nextCursor: encodeCursor(nextState),\n hasMore: hardFailed || !drained,\n }\n }\n\n /**\n * Operator-triggered backlog import (Spec B \u00A7 Phase B6).\n *\n * Reaches BACKWARD in time over `gmail.users.messages.list?q=\u2026`, independent\n * of the forward-polling `historyId` cursor \u2014 nothing here reads or writes\n * `GmailChannelState`, so a multi-year backfill can never move the live poll\n * cursor.\n *\n * Scale contract: the cursor carries Gmail's own `nextPageToken` plus a\n * collected counter and the frozen query, so it stays a few hundred bytes for\n * a 50k-message mailbox. Message ids are never enumerated up front.\n */\n async importHistory(input: ImportHistoryInput): Promise<ImportHistoryPage> {\n const userCredentials = parseUserCredentialsOrThrow(input.credentials)\n const auth = { accessToken: userCredentials.accessToken }\n const api = getGmailApiClient()\n const accountIdentifier = userCredentials.email ?? 'me'\n\n const maxMessages = clampImportMaxMessages(input.maxMessages)\n const pageSize = resolveImportPageSize()\n const concurrency = resolveImportConcurrency()\n\n const cursor = decodeGmailImportCursor(input.cursor)\n const afterTerm = cursor?.after ?? buildAfterTerm(clampImportSinceDays(input.sinceDays))\n const queries = buildImportQueries(afterTerm, input.contactEmails)\n\n let queryIndex = cursor ? cursor.queryIndex : 0\n let pageToken = cursor?.pageToken\n const collectedSoFar = cursor?.collected ?? 0\n let activeQuery: string | undefined = cursor?.query ?? queries[queryIndex]\n\n const budget = Math.max(0, maxMessages - collectedSoFar)\n if (budget === 0 || queryIndex >= queries.length) {\n return { messages: [], hasMore: false }\n }\n\n const perPage = Math.min(pageSize, budget)\n const refs: Array<{ id: string; threadId: string }> = []\n let listCalls = 0\n while (refs.length < perPage && queryIndex < queries.length && listCalls < IMPORT_MAX_LIST_CALLS_PER_PAGE) {\n listCalls += 1\n const list = await api.listMessages(auth, {\n query: activeQuery,\n labelIds: ['INBOX'],\n pageToken,\n maxResults: perPage - refs.length,\n })\n for (const message of list.messages ?? []) {\n refs.push({ id: message.id, threadId: message.threadId })\n }\n if (list.nextPageToken) {\n pageToken = list.nextPageToken\n continue\n }\n queryIndex += 1\n pageToken = undefined\n activeQuery = queries[queryIndex]\n }\n\n const messages = await this.fetchAndNormalizeForImport(api, auth, refs, accountIdentifier, concurrency)\n\n const collected = collectedSoFar + messages.length\n const exhausted = pageToken === undefined && queryIndex >= queries.length\n const hasMore = !exhausted && collected < maxMessages\n const nextCursor = hasMore\n ? encodeCursor({\n v: GMAIL_IMPORT_CURSOR_VERSION,\n after: afterTerm,\n query: queries[queryIndex] ?? activeQuery ?? queries[queries.length - 1],\n queryIndex,\n pageToken,\n collected,\n } satisfies GmailImportCursor)\n : undefined\n\n return { messages, nextCursor, hasMore }\n }\n\n /**\n * Import-path fetch. Diverges from `fetchAndNormalize` deliberately: the\n * forward path stops at the first hard failure to protect the polling cursor,\n * whereas a backlog import has no cursor to protect and must not abandon a\n * multi-year sweep over one unreadable message \u2014 so a per-message failure is\n * skipped and logged. Only credential/permission failures (401/403), which\n * would fail every remaining message too, abort the page.\n */\n private async fetchAndNormalizeForImport(\n api: ReturnType<typeof getGmailApiClient>,\n auth: { accessToken: string },\n refs: Array<{ id: string; threadId: string }>,\n accountIdentifier: string,\n concurrency: number,\n ): Promise<NormalizedInboundMessage[]> {\n const results = new Array<NormalizedInboundMessage | null>(refs.length).fill(null)\n let nextIndex = 0\n const workerCount = Math.max(1, Math.min(concurrency, refs.length))\n\n const runWorker = async (): Promise<void> => {\n while (true) {\n const index = nextIndex\n nextIndex += 1\n if (index >= refs.length) return\n const ref = refs[index]\n try {\n const raw = await api.getMessageRaw(auth, ref.id)\n const fallbackDate = raw.internalDate ? new Date(Number(raw.internalDate)) : undefined\n results[index] = await normalizeInboundGmailMessage({\n rawMessage: decodeBase64Url(raw.raw),\n gmailMessageId: raw.id,\n gmailThreadId: raw.threadId,\n gmailLabelIds: raw.labelIds ?? [],\n accountIdentifier,\n fallbackDate,\n })\n } catch (error) {\n if (isFatalGmailImportError(error)) throw error\n logger.warn('skipping unreadable message during history import', {\n gmailMessageId: ref.id,\n reason: error instanceof Error ? error.message.slice(0, 200) : 'unknown error',\n })\n }\n }\n }\n\n await Promise.all(Array.from({ length: workerCount }, () => runWorker()))\n return results.filter((message): message is NormalizedInboundMessage => message !== null)\n }\n\n async deleteMessage(input: DeleteChannelMessageInput): Promise<void> {\n const userCredentials = parseUserCredentialsOrThrow(input.credentials)\n const api = getGmailApiClient()\n // Gmail's \"delete\" capability is delivered as Trash to match the user's\n // mental model and avoid permanent loss on accidental clicks. The user can\n // restore from Trash in the Gmail web UI within 30 days.\n await api.trashMessage({ accessToken: userCredentials.accessToken }, input.externalMessageId)\n }\n\n async resolveContact(input: ResolveContactInput): Promise<ContactHint | null> {\n return emailResolveContact(input)\n }\n\n /**\n * Fetch + normalize each collected message ref.\n *\n * L3 fix: a non-404/410 error on `getMessageRaw` (e.g. a transient 500/403)\n * used to re-throw and abort the whole tick, discarding messages that had\n * already normalized in the same page. Worse, because the cursor could be\n * advanced from a different source (a push notification carrying a higher\n * historyId), the transiently-failed messages could be skipped permanently.\n *\n * We now treat a hard failure as a stop point: keep the messages normalized\n * BEFORE the failure and signal `hardFailed: true` so the caller pins the\n * persisted `historyId` (does NOT advance past the failure) and re-fetches on\n * the next tick. 404/410 stay skipped (the message is genuinely gone).\n */\n private async fetchAndNormalize(\n api: ReturnType<typeof getGmailApiClient>,\n auth: { accessToken: string },\n refs: Array<{ id: string; threadId: string; labelIds?: string[] }>,\n accountIdentifier: string,\n ): Promise<{ messages: NormalizedInboundMessage[]; hardFailed: boolean }> {\n const out: NormalizedInboundMessage[] = []\n for (const ref of refs) {\n let raw: GmailGetMessageRawResponse\n try {\n raw = await api.getMessageRaw(auth, ref.id)\n } catch (error) {\n // 404/410: the message is gone \u2014 skip it and keep draining.\n if (error instanceof GmailApiError && (error.status === 404 || error.status === 410)) continue\n // Any other failure is potentially transient. Stop here without\n // advancing past the unprocessed messages so the next tick retries them.\n return { messages: out, hardFailed: true }\n }\n const rawBuffer = decodeBase64Url(raw.raw)\n // `internalDate` is when Gmail received the message; the MIME Date header\n // is the sender's and must not date the platform message (#6095).\n const receivedAt = raw.internalDate ? new Date(Number(raw.internalDate)) : undefined\n const normalized = await normalizeInboundGmailMessage({\n rawMessage: rawBuffer,\n gmailMessageId: raw.id,\n gmailThreadId: raw.threadId,\n gmailLabelIds: raw.labelIds ?? ref.labelIds ?? [],\n accountIdentifier,\n receivedAt,\n })\n out.push(normalized)\n }\n return { messages: out, hardFailed: false }\n }\n}\n\n// \u2500\u2500 Backlog import (importHistory) helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst GMAIL_IMPORT_CURSOR_VERSION = 1\nconst IMPORT_SINCE_DAYS_MIN = 1\nconst IMPORT_SINCE_DAYS_DEFAULT = IMPORT_HISTORY_DEFAULT_SINCE_DAYS\nconst IMPORT_MAX_MESSAGES_MIN = 1\nconst IMPORT_MAX_MESSAGES_DEFAULT = IMPORT_HISTORY_DEFAULT_MAX_MESSAGES\nconst IMPORT_PAGE_SIZE_DEFAULT = 100\n/** `users.messages.list` rejects `maxResults` above 500. */\nconst IMPORT_PAGE_SIZE_MAX = 500\nconst IMPORT_CONCURRENCY_DEFAULT = 5\nconst IMPORT_CONCURRENCY_MAX = 20\n/** Senders per `from:(\u2026 OR \u2026)` group \u2014 keeps each `q` well inside Gmail's URL budget. */\nconst IMPORT_SENDER_CHUNK_SIZE = 25\n/** Matches the hub's `contactEmails` ceiling; bounds the number of query groups. */\nconst IMPORT_SENDER_MAX = 200\n/** Bounds `messages.list` round-trips inside a single page when groups come back empty. */\nconst IMPORT_MAX_LIST_CALLS_PER_PAGE = 25\n\ninterface GmailImportCursor {\n v: number\n /** Frozen `after:<epochSeconds>` term so later pages cannot drift with wall-clock. */\n after: string\n /** Frozen full query for the group the next page resumes on. */\n query: string\n queryIndex: number\n pageToken?: string\n collected: number\n}\n\nfunction clampImportSinceDays(value: number): number {\n const raw = Number.isFinite(value) ? Math.trunc(value) : IMPORT_SINCE_DAYS_DEFAULT\n return Math.max(IMPORT_SINCE_DAYS_MIN, Math.min(getImportHistoryMaxSinceDays(), raw))\n}\n\nfunction clampImportMaxMessages(value: number | undefined): number {\n const raw = Number.isFinite(value) ? Math.trunc(value as number) : IMPORT_MAX_MESSAGES_DEFAULT\n return Math.max(IMPORT_MAX_MESSAGES_MIN, Math.min(getImportHistoryMaxMessages(), raw))\n}\n\nfunction resolveEnvInt(name: string, fallback: number, max: number): number {\n const parsed = Number.parseInt(process.env[name] ?? '', 10)\n if (!Number.isFinite(parsed) || parsed <= 0) return fallback\n return Math.min(parsed, max)\n}\n\nfunction resolveImportPageSize(): number {\n return resolveEnvInt('OM_CHANNEL_GMAIL_IMPORT_PAGE_SIZE', IMPORT_PAGE_SIZE_DEFAULT, IMPORT_PAGE_SIZE_MAX)\n}\n\nfunction resolveImportConcurrency(): number {\n return resolveEnvInt('OM_CHANNEL_GMAIL_IMPORT_CONCURRENCY', IMPORT_CONCURRENCY_DEFAULT, IMPORT_CONCURRENCY_MAX)\n}\n\n/**\n * Gmail accepts `after:` as either `YYYY/MM/DD` \u2014 resolved in the mailbox\n * owner's display timezone, so the boundary day is ambiguous \u2014 or as a Unix\n * timestamp in seconds, which is not. We emit the timestamp form.\n *\n * Either form filters on Gmail's INTERNAL date (when Gmail received the\n * message), not the `Date:` header, so a message with an old header that was\n * recently delivered or migrated into the mailbox counts as recent.\n */\nfunction buildAfterTerm(sinceDays: number): string {\n const epochSeconds = Math.floor((Date.now() - sinceDays * 24 * 60 * 60 * 1000) / 1000)\n return `after:${Math.max(0, epochSeconds)}`\n}\n\nfunction normalizeImportSenders(contactEmails: string[] | undefined): string[] {\n const seen = new Set<string>()\n for (const raw of contactEmails ?? []) {\n if (typeof raw !== 'string') continue\n const trimmed = raw.trim().toLowerCase()\n if (!trimmed.includes('@') || /[\\s\"()]/.test(trimmed)) continue\n seen.add(trimmed)\n if (seen.size >= IMPORT_SENDER_MAX) break\n }\n return Array.from(seen)\n}\n\n/**\n * Build the ordered list of Gmail queries this import walks.\n *\n * Gmail's `q` rides in the request URL, so a 200-address `from:(\u2026 OR \u2026)` chain\n * would blow past a practical URL budget. Senders are therefore split into\n * groups of `IMPORT_SENDER_CHUNK_SIZE` and the groups are walked SEQUENTIALLY\n * across pages (the cursor records which group is active). Groups are disjoint\n * by construction \u2014 a message has exactly one `From` \u2014 so no cross-group dedup\n * is needed. With no sender hint a single date-only query is returned.\n */\nfunction buildImportQueries(afterTerm: string, contactEmails: string[] | undefined): string[] {\n const senders = normalizeImportSenders(contactEmails)\n if (senders.length === 0) return [afterTerm]\n const queries: string[] = []\n for (let index = 0; index < senders.length; index += IMPORT_SENDER_CHUNK_SIZE) {\n const group = senders.slice(index, index + IMPORT_SENDER_CHUNK_SIZE)\n queries.push(`${afterTerm} from:(${group.join(' OR ')})`)\n }\n return queries\n}\n\nfunction decodeGmailImportCursor(value: string | undefined): GmailImportCursor | null {\n const parsed = decodeCursor(value)\n if (!parsed || typeof parsed !== 'object') return null\n const candidate = parsed as Partial<Record<keyof GmailImportCursor, unknown>>\n if (candidate.v !== GMAIL_IMPORT_CURSOR_VERSION) return null\n if (typeof candidate.after !== 'string' || typeof candidate.query !== 'string') return null\n const queryIndex = typeof candidate.queryIndex === 'number' && candidate.queryIndex >= 0 ? Math.trunc(candidate.queryIndex) : 0\n const collected = typeof candidate.collected === 'number' && candidate.collected >= 0 ? Math.trunc(candidate.collected) : 0\n const pageToken = typeof candidate.pageToken === 'string' && candidate.pageToken.length > 0 ? candidate.pageToken : undefined\n return {\n v: GMAIL_IMPORT_CURSOR_VERSION,\n after: candidate.after,\n query: candidate.query,\n queryIndex,\n pageToken,\n collected,\n }\n}\n\n/**\n * A 401 (expired/revoked grant) or a 403 that survived the client's bounded\n * retry (permission denied, or exhausted per-user quota) will fail every\n * remaining message in the sweep, so it aborts the page instead of being\n * skipped message by message.\n */\nfunction isFatalGmailImportError(error: unknown): boolean {\n return error instanceof GmailApiError && (error.status === 401 || error.status === 403)\n}\n\nfunction collectMessageRefs(\n history: Array<{\n messagesAdded?: Array<{ message: { id: string; threadId: string; labelIds?: string[] } }>\n }>,\n): Array<{ id: string; threadId: string; labelIds?: string[] }> {\n const seen = new Set<string>()\n const refs: Array<{ id: string; threadId: string; labelIds?: string[] }> = []\n for (const entry of history) {\n for (const added of entry.messagesAdded ?? []) {\n if (seen.has(added.message.id)) continue\n seen.add(added.message.id)\n refs.push({ id: added.message.id, threadId: added.message.threadId, labelIds: added.message.labelIds })\n }\n }\n return refs\n}\n\nfunction parseUserCredentialsOrThrow(value: unknown): GmailUserCredentials {\n const parsed = gmailUserCredentialsSchema.safeParse(value)\n if (!parsed.success) {\n const first = parsed.error.issues[0]\n throw new Error(`Invalid Gmail credentials: ${first?.message ?? 'unknown validation error'}`)\n }\n return parsed.data\n}\n\nfunction parseClientCredentialsOrThrow(value: unknown): GmailClientCredentials {\n const parsed = gmailClientCredentialsSchema.safeParse(value)\n if (!parsed.success) {\n const first = parsed.error.issues[0]\n throw new Error(`Invalid Gmail OAuth client credentials: ${first?.message ?? 'unknown validation error'}`)\n }\n return parsed.data\n}\n\n/**\n * Resolve the OAuth client config for a Gmail refresh from\n * `RefreshCredentialsInput.oauthClient` (Spec A,\n * .ai/specs/implemented/2026-05-27-email-integration-inbound-reliability-and-threading.md).\n *\n * Client-app config must come from this trusted hub-supplied slot only \u2014\n * never from a per-user credentials blob.\n */\nfunction resolveGmailOAuthClient(input: RefreshCredentialsInput): GmailClientCredentials {\n if (!input.oauthClient) {\n throw new Error(\n '[internal] Invalid Gmail OAuth client credentials: oauthClient is required on RefreshCredentialsInput',\n )\n }\n const client = input.oauthClient\n if (!client.clientId) {\n throw new Error('[internal] Invalid Gmail OAuth client credentials: OAuth Client ID required')\n }\n if (!client.clientSecret) {\n throw new Error('[internal] Invalid Gmail OAuth client credentials: clientSecret required')\n }\n return {\n clientId: client.clientId,\n clientSecret: client.clientSecret,\n // Spec A's `OAuthClientConfig.scopes` is `string[]`; `GmailClientCredentials.scopes`\n // is a comma/space-separated string. `parseScopes` accepts either separator.\n ...(client.scopes !== undefined ? { scopes: client.scopes.join(' ') } : {}),\n }\n}\n\nfunction pickRawMimeBuffer(payload: { rawBase64Url?: unknown; rawBody?: unknown }): Buffer {\n if (typeof payload.rawBase64Url === 'string') return decodeBase64Url(payload.rawBase64Url)\n const value = payload.rawBody\n if (Buffer.isBuffer(value)) return value\n if (value instanceof Uint8Array) return Buffer.from(value)\n if (typeof value === 'string') return Buffer.from(value, 'utf-8')\n throw new Error('[internal] Gmail normalizeInbound requires `raw.rawBase64Url` or `raw.rawBody`')\n}\n\nlet cachedAdapter: GmailChannelAdapter | null = null\n\nexport function getGmailChannelAdapter(): GmailChannelAdapter {\n if (!cachedAdapter) cachedAdapter = new GmailChannelAdapter()\n return cachedAdapter\n}\n\nexport { GmailChannelAdapter }\n"],
5
+ "mappings": "AA6BA,SAAS,yBAAyB;AAClC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,OAEK;AACP,SAAS,oCAAoC;AAC7C,SAAS,2BAA2B;AACpC,SAAS,cAAc,oBAAoB;AAC3C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,eAAe;AAsB3C,MAAM,oBAA8C;AAAA,EAApD;AACE,SAAS,cAAc;AACvB,SAAS,cAAc;AACvB,SAA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C,OAAO,cAAc;AACxB,UAAM,IAAI,MAAM,0EAA0E;AAAA,EAC5F;AACA,SAAO;AAAA,IACL,UAAU,OAAO;AAAA,IACjB,cAAc,OAAO;AAAA;AAAA;AAAA,IAGrB,GAAI,OAAO,WAAW,SAAY,EAAE,QAAQ,OAAO,OAAO,KAAK,GAAG,EAAE,IAAI,CAAC;AAAA,EAC3E;AACF;AAEA,SAAS,kBAAkB,SAAgE;AACzF,MAAI,OAAO,QAAQ,iBAAiB,SAAU,QAAO,gBAAgB,QAAQ,YAAY;AACzF,QAAM,QAAQ,QAAQ;AACtB,MAAI,OAAO,SAAS,KAAK,EAAG,QAAO;AACnC,MAAI,iBAAiB,WAAY,QAAO,OAAO,KAAK,KAAK;AACzD,MAAI,OAAO,UAAU,SAAU,QAAO,OAAO,KAAK,OAAO,OAAO;AAChE,QAAM,IAAI,MAAM,gFAAgF;AAClG;AAEA,IAAI,gBAA4C;AAEzC,SAAS,yBAA8C;AAC5D,MAAI,CAAC,cAAe,iBAAgB,IAAI,oBAAoB;AAC5D,SAAO;AACT;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/channel-gmail",
3
- "version": "0.8.1-develop.7296.1.2111d779db",
3
+ "version": "0.8.1-develop.7441.1.b42958b98c",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -62,19 +62,19 @@
62
62
  }
63
63
  },
64
64
  "dependencies": {
65
- "@open-mercato/core": "0.8.1-develop.7296.1.2111d779db",
66
- "@open-mercato/ui": "0.8.1-develop.7296.1.2111d779db",
65
+ "@open-mercato/core": "0.8.1-develop.7441.1.b42958b98c",
66
+ "@open-mercato/ui": "0.8.1-develop.7441.1.b42958b98c",
67
67
  "@types/mailparser": "^3.4.5",
68
68
  "mailparser": "^3.9.17"
69
69
  },
70
70
  "peerDependencies": {
71
71
  "@mikro-orm/postgresql": "^7.0.14",
72
- "@open-mercato/shared": "0.8.1-develop.7296.1.2111d779db",
72
+ "@open-mercato/shared": "0.8.1-develop.7441.1.b42958b98c",
73
73
  "react": "^19.0.0",
74
74
  "react-dom": "^19.0.0"
75
75
  },
76
76
  "devDependencies": {
77
- "@open-mercato/shared": "0.8.1-develop.7296.1.2111d779db",
77
+ "@open-mercato/shared": "0.8.1-develop.7441.1.b42958b98c",
78
78
  "@types/jest": "^30.0.0",
79
79
  "@types/react": "^19.2.18",
80
80
  "@types/react-dom": "^19.2.5",
@@ -19,8 +19,8 @@ import { apiRequest } from '@open-mercato/core/helpers/integration/api'
19
19
  *
20
20
  * The full end-to-end (connect a Gmail mailbox → POST /import-history →
21
21
  * ProgressJob completes → imported messages on the Person timeline) needs a
22
- * real OAuth grant and stays manual, alongside
23
- * `.ai/qa/scenarios/TC-CHANNEL-EMAIL-029-import-history.md`.
22
+ * real OAuth grant and stays manual — see
23
+ * `.ai/qa/scenarios/TC-CHANNEL-EMAIL-032-gmail-import-history.md`.
24
24
  */
25
25
  test.describe('TC-CHANNEL-EMAIL-032: gmail import-history route wiring', () => {
26
26
  const FAKE_CHANNEL_ID = '00000000-0000-0000-0000-000000000032'
@@ -9,24 +9,9 @@ import {
9
9
  setGoogleOAuthClient,
10
10
  type GoogleOAuthClient,
11
11
  } from '../oauth'
12
- import { createLogger } from '@open-mercato/shared/lib/logger'
13
12
  import { getGmailChannelAdapter } from '../adapter'
14
13
  import { gmailCapabilities } from '../capabilities'
15
14
 
16
- jest.mock('@open-mercato/shared/lib/logger', () => {
17
- const mocked = {
18
- debug: jest.fn(),
19
- info: jest.fn(),
20
- warn: jest.fn(),
21
- error: jest.fn(),
22
- child: jest.fn(),
23
- }
24
- mocked.child.mockImplementation(() => mocked)
25
- return { createLogger: jest.fn(() => mocked) }
26
- })
27
-
28
- const adapterLoggerWarn = createLogger('channel_gmail').warn as jest.Mock
29
-
30
15
  const userCredentials = {
31
16
  accessToken: 'access',
32
17
  refreshToken: 'refresh',
@@ -408,11 +393,9 @@ describe('GmailChannelAdapter OAuth flow', () => {
408
393
  ).rejects.toThrow(/requires_reauth/)
409
394
  })
410
395
 
411
- // Spec A regression coverage — the new oauthClient path is the canonical
412
- // production wiring; the legacy _client path remains for one minor
413
- // release for backward compatibility.
396
+ // Spec A — oauthClient is the only accepted client-app config source.
414
397
  describe('refreshCredentials — OAuth client wiring (Spec A)', () => {
415
- it('refreshes successfully when oauthClient is provided (no _client on credentials)', async () => {
398
+ it('refreshes successfully when oauthClient is provided', async () => {
416
399
  const refreshCalls: Array<{ clientId: string; clientSecret: string; refreshToken: string }> = []
417
400
  setGoogleOAuthClient(
418
401
  stubOAuth({
@@ -424,7 +407,7 @@ describe('GmailChannelAdapter OAuth flow', () => {
424
407
  )
425
408
  await getGmailChannelAdapter().refreshCredentials!({
426
409
  channelId: 'channel-1',
427
- credentials: userCredentials, // NO _client pre-packing
410
+ credentials: userCredentials,
428
411
  scope: { tenantId: 't', organizationId: 'o' },
429
412
  oauthClient: {
430
413
  clientId: 'oauth-cid',
@@ -440,33 +423,28 @@ describe('GmailChannelAdapter OAuth flow', () => {
440
423
  ])
441
424
  })
442
425
 
443
- it('falls back to legacy _client path with a deprecation warning when oauthClient is absent', async () => {
444
- adapterLoggerWarn.mockClear()
445
- setGoogleOAuthClient(
446
- stubOAuth({
447
- refreshToken: async () => ({ access_token: 'a', expires_in: 1800, token_type: 'Bearer' }),
426
+ it('ignores credentials._client and throws when oauthClient is absent', async () => {
427
+ const refreshToken = jest.fn()
428
+ setGoogleOAuthClient(stubOAuth({ refreshToken }))
429
+ await expect(
430
+ getGmailChannelAdapter().refreshCredentials!({
431
+ channelId: 'channel-1',
432
+ credentials: { ...userCredentials, _client: clientCredentials },
433
+ scope: { tenantId: 't', organizationId: 'o' },
448
434
  }),
449
- )
450
- await getGmailChannelAdapter().refreshCredentials!({
451
- channelId: 'channel-1',
452
- credentials: { ...userCredentials, _client: clientCredentials },
453
- scope: { tenantId: 't', organizationId: 'o' },
454
- })
455
- // Legacy path emits a one-time deprecation warning per process.
456
- expect(adapterLoggerWarn).toHaveBeenCalledWith(
457
- expect.stringContaining('reading OAuth client config from credentials._client is deprecated'),
458
- )
435
+ ).rejects.toThrow(/oauthClient is required on RefreshCredentialsInput/)
436
+ expect(refreshToken).not.toHaveBeenCalled()
459
437
  })
460
438
 
461
- it('throws a clear error when neither oauthClient nor _client carries client config', async () => {
439
+ it('throws a clear error when oauthClient is absent', async () => {
462
440
  setGoogleOAuthClient(stubOAuth({}))
463
441
  await expect(
464
442
  getGmailChannelAdapter().refreshCredentials!({
465
443
  channelId: 'channel-1',
466
- credentials: userCredentials, // NO _client, NO oauthClient
444
+ credentials: userCredentials,
467
445
  scope: { tenantId: 't', organizationId: 'o' },
468
446
  }),
469
- ).rejects.toThrow(/Invalid Gmail OAuth client credentials/)
447
+ ).rejects.toThrow(/oauthClient is required on RefreshCredentialsInput/)
470
448
  })
471
449
  })
472
450
  })
@@ -153,29 +153,63 @@ describe('FetchGmailApiClient.requestJson retry/backoff', () => {
153
153
  }
154
154
  })
155
155
 
156
- it('honors an HTTP-date Retry-After value, bounded by the 8s cap', async () => {
157
- let calls = 0
158
- // 3 seconds in the future → ~3000ms wait, still under the 8s ceiling.
159
- const retryAt = new Date(Date.now() + 3_000).toUTCString()
160
- globalThis.fetch = (() => {
161
- calls += 1
162
- if (calls === 1) {
156
+ describe('HTTP-date Retry-After on a pinned clock', () => {
157
+ // A whole-second epoch, so the HTTP-date round trip (which drops sub-second
158
+ // precision) is lossless and the computed delay does not depend on how much
159
+ // real time elapses on a contended CI runner (issue #6437).
160
+ const PINNED_NOW = Date.UTC(2026, 0, 15, 12, 0, 0)
161
+
162
+ beforeEach(() => {
163
+ jest.spyOn(Date, 'now').mockReturnValue(PINNED_NOW)
164
+ })
165
+
166
+ afterEach(() => {
167
+ jest.restoreAllMocks()
168
+ })
169
+
170
+ function mockRateLimitedOnce(retryAfter: string): () => number {
171
+ let calls = 0
172
+ globalThis.fetch = (() => {
173
+ calls += 1
174
+ if (calls === 1) {
175
+ return Promise.resolve(
176
+ fakeResponse({ status: 429, statusText: 'Too Many Requests', body: '', headers: { 'retry-after': retryAfter } }),
177
+ )
178
+ }
163
179
  return Promise.resolve(
164
- fakeResponse({ status: 429, statusText: 'Too Many Requests', body: '', headers: { 'retry-after': retryAt } }),
180
+ fakeResponse({ status: 200, statusText: 'OK', body: JSON.stringify({ emailAddress: 'a@gmail.com', historyId: '1' }) }),
165
181
  )
166
- }
167
- return Promise.resolve(
168
- fakeResponse({ status: 200, statusText: 'OK', body: JSON.stringify({ emailAddress: 'a@gmail.com', historyId: '1' }) }),
169
- )
170
- }) as unknown as typeof globalThis.fetch
182
+ }) as unknown as typeof globalThis.fetch
183
+ return () => calls
184
+ }
171
185
 
172
- await getGmailApiClient().getProfile({ accessToken: 'token' })
186
+ it('honors an HTTP-date Retry-After value, bounded by the 8s cap', async () => {
187
+ const callCount = mockRateLimitedOnce(new Date(PINNED_NOW + 3_000).toUTCString())
173
188
 
174
- expect(calls).toBe(2)
175
- expect(capturedDelays).toHaveLength(1)
176
- // Date.parse(retryAt) drops sub-second precision, so the delta is ~2000-3000ms.
177
- expect(capturedDelays[0]).toBeGreaterThan(1000)
178
- expect(capturedDelays[0]).toBeLessThanOrEqual(8000)
189
+ await getGmailApiClient().getProfile({ accessToken: 'token' })
190
+
191
+ expect(callCount()).toBe(2)
192
+ expect(capturedDelays).toEqual([3000])
193
+ })
194
+
195
+ it('clamps an HTTP-date Retry-After beyond the cap to 8s', async () => {
196
+ const callCount = mockRateLimitedOnce(new Date(PINNED_NOW + 60_000).toUTCString())
197
+
198
+ await getGmailApiClient().getProfile({ accessToken: 'token' })
199
+
200
+ expect(callCount()).toBe(2)
201
+ expect(capturedDelays).toEqual([8000])
202
+ })
203
+
204
+ it('falls back to computeBackoff when the HTTP-date Retry-After is already in the past', async () => {
205
+ Math.random = () => 0
206
+ const callCount = mockRateLimitedOnce(new Date(PINNED_NOW - 5_000).toUTCString())
207
+
208
+ await getGmailApiClient().getProfile({ accessToken: 'token' })
209
+
210
+ expect(callCount()).toBe(2)
211
+ expect(capturedDelays).toEqual([500])
212
+ })
179
213
  })
180
214
 
181
215
  it('throws GmailApiError carrying the upstream status after exhausting retries', async () => {
@@ -224,10 +224,8 @@ class GmailChannelAdapter implements ChannelAdapter {
224
224
  if (!current.refreshToken) {
225
225
  throw new Error('requires_reauth')
226
226
  }
227
- // Spec A: prefer the new `input.oauthClient` slot (resolved by the hub from
228
- // the `channel_gmail` integration's tenant-scoped client credentials). Fall
229
- // back to the deprecated `credentials._client` path for one minor release so
230
- // existing test fixtures keep working.
227
+ // Spec A: OAuth client config comes only from `input.oauthClient` (resolved
228
+ // by the hub from the `channel_gmail` integration's tenant-scoped row).
231
229
  const clientFromState = resolveGmailOAuthClient(input)
232
230
  const token = await getGoogleOAuthClient().refreshToken({
233
231
  clientId: clientFromState.clientId,
@@ -943,47 +941,34 @@ function parseClientCredentialsOrThrow(value: unknown): GmailClientCredentials {
943
941
  return parsed.data
944
942
  }
945
943
 
946
- let warnedLegacyClientPath = false
947
-
948
944
  /**
949
- * Resolve the OAuth client config for a Gmail refresh, preferring the new
950
- * `RefreshCredentialsInput.oauthClient` field (Spec A,
945
+ * Resolve the OAuth client config for a Gmail refresh from
946
+ * `RefreshCredentialsInput.oauthClient` (Spec A,
951
947
  * .ai/specs/implemented/2026-05-27-email-integration-inbound-reliability-and-threading.md).
952
948
  *
953
- * Falls back to the deprecated `credentials._client` read path for one
954
- * minor release so existing tests keep working. The legacy path emits a
955
- * one-time deprecation warning per process so production logs stay quiet.
949
+ * Client-app config must come from this trusted hub-supplied slot only —
950
+ * never from a per-user credentials blob.
956
951
  */
957
952
  function resolveGmailOAuthClient(input: RefreshCredentialsInput): GmailClientCredentials {
958
- if (input.oauthClient) {
959
- const client = input.oauthClient
960
- if (!client.clientId) {
961
- throw new Error('[internal] Invalid Gmail OAuth client credentials: OAuth Client ID required')
962
- }
963
- if (!client.clientSecret) {
964
- throw new Error('[internal] Invalid Gmail OAuth client credentials: clientSecret required')
965
- }
966
- return {
967
- clientId: client.clientId,
968
- clientSecret: client.clientSecret,
969
- // `GmailClientCredentials.scopes` is the wire format the legacy
970
- // `credentials._client` blob carried — comma/space-separated string.
971
- // Spec A's `OAuthClientConfig.scopes` is the canonical `string[]`.
972
- // `parseScopes` accepts either separator, so join with a single space.
973
- ...(client.scopes !== undefined ? { scopes: client.scopes.join(' ') } : {}),
974
- }
975
- }
976
- // Legacy path — DEPRECATED. Remove in the next minor release.
977
- if (!warnedLegacyClientPath) {
978
- warnedLegacyClientPath = true
979
- logger.warn(
980
- 'reading OAuth client config from credentials._client is deprecated;' +
981
- ' pass via RefreshCredentialsInput.oauthClient instead (Spec A)',
953
+ if (!input.oauthClient) {
954
+ throw new Error(
955
+ '[internal] Invalid Gmail OAuth client credentials: oauthClient is required on RefreshCredentialsInput',
982
956
  )
983
957
  }
984
- return parseClientCredentialsOrThrow(
985
- (input.credentials as unknown as { _client?: unknown })._client ?? input.credentials,
986
- )
958
+ const client = input.oauthClient
959
+ if (!client.clientId) {
960
+ throw new Error('[internal] Invalid Gmail OAuth client credentials: OAuth Client ID required')
961
+ }
962
+ if (!client.clientSecret) {
963
+ throw new Error('[internal] Invalid Gmail OAuth client credentials: clientSecret required')
964
+ }
965
+ return {
966
+ clientId: client.clientId,
967
+ clientSecret: client.clientSecret,
968
+ // Spec A's `OAuthClientConfig.scopes` is `string[]`; `GmailClientCredentials.scopes`
969
+ // is a comma/space-separated string. `parseScopes` accepts either separator.
970
+ ...(client.scopes !== undefined ? { scopes: client.scopes.join(' ') } : {}),
971
+ }
987
972
  }
988
973
 
989
974
  function pickRawMimeBuffer(payload: { rawBase64Url?: unknown; rawBody?: unknown }): Buffer {