@openclaw/googlechat 2026.9.6 → 2026.9.7

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.
Files changed (35) hide show
  1. package/assets/icon.png +0 -0
  2. package/dist/.setup/actions-K6_7xusH.mjs +56 -0
  3. package/dist/.setup/{approval-auth-C6NmZR0i.mjs → approval-auth-DXvh9tfx.mjs} +2 -2
  4. package/dist/.setup/approval-card-text-BKg_4mXq.mjs +12 -0
  5. package/dist/.setup/{approval-handler.runtime-DPTrNUbd.mjs → approval-handler.runtime-CT2MVoa-.mjs} +42 -81
  6. package/dist/.setup/{channel-E2g6ySbf.mjs → channel-DAUmcC2J.mjs} +34 -82
  7. package/dist/.setup/{channel-base-B3EzcV7X.mjs → channel-base-inLf3HGV.mjs} +15 -36
  8. package/dist/.setup/{channel.adapters-CSAwKSvQ.mjs → channel.adapters-DIQot11j.mjs} +85 -172
  9. package/dist/.setup/{channel.runtime-BdzxoqvE.mjs → channel.runtime-C-B60lWL.mjs} +84 -161
  10. package/dist/.setup/doctor-contract-wLrnvLUn.mjs +294 -0
  11. package/dist/.setup/runtime-C5OOOlaP.mjs +8 -0
  12. package/dist/.setup/{secret-contract-DmWM0kwM.mjs → secret-contract-B7H-kkqq.mjs} +4 -11
  13. package/dist/.setup/{secret-contract-api-DHLd5XO3.mjs → secret-contract-api-GavLI-0W.mjs} +1 -1
  14. package/dist/.setup/{setup-plugin-api-C0zTOlHy.mjs → setup-plugin-api-CAzvWHwN.mjs} +1 -1
  15. package/dist/.setup/{setup-plugin-api-DWL3ZytB.mjs → setup-plugin-api-DPYc1usm.mjs} +1 -1
  16. package/dist/api.js +2 -2
  17. package/dist/channel-plugin-api.js +1 -1
  18. package/dist/directory-contract-api.js +1 -1
  19. package/dist/doctor-contract-api.js +1 -1
  20. package/dist/runtime-api.js +2 -3
  21. package/dist/secret-contract-api.js +1 -1
  22. package/dist/setup-entry.js +2 -2
  23. package/dist/setup-plugin-api.js +1 -1
  24. package/node_modules/google-auth-library/node_modules/gcp-metadata/build/src/gcp-residency.d.ts +13 -4
  25. package/node_modules/google-auth-library/node_modules/gcp-metadata/build/src/gcp-residency.js +24 -19
  26. package/node_modules/google-auth-library/node_modules/gcp-metadata/build/src/gcp-residency.js.map +1 -1
  27. package/node_modules/google-auth-library/node_modules/gcp-metadata/build/src/index.js +65 -37
  28. package/node_modules/google-auth-library/node_modules/gcp-metadata/build/src/index.js.map +1 -1
  29. package/node_modules/google-auth-library/node_modules/gcp-metadata/package.json +1 -1
  30. package/node_modules/google-auth-library/package.json +6 -6
  31. package/package.json +5 -5
  32. package/dist/.setup/actions-BM-Gd-H7.mjs +0 -72
  33. package/dist/.setup/approval-card-text-ChngxXdJ.mjs +0 -6
  34. package/dist/.setup/doctor-contract-BLvSmTXT.mjs +0 -115
  35. package/dist/.setup/runtime-api-Cc5ZuXih.mjs +0 -24
@@ -1,10 +1,9 @@
1
- import { l as resolveGoogleChatAccount, r as formatGoogleChatAllowFromEntry, u as MAX_GOOGLE_CHAT_SERVICE_ACCOUNT_FILE_BYTES } from "./channel-base-B3EzcV7X.mjs";
2
- import { d as fetchWithSsrFGuard$1, m as missingTargetError, r as PAIRING_APPROVED_MESSAGE } from "./runtime-api-Cc5ZuXih.mjs";
1
+ import { l as resolveGoogleChatAccount, r as formatGoogleChatAllowFromEntry, u as MAX_GOOGLE_CHAT_SERVICE_ACCOUNT_FILE_BYTES } from "./channel-base-inLf3HGV.mjs";
3
2
  import { buildChannelOutboundSessionRoute } from "openclaw/plugin-sdk/channel-core";
4
3
  import { createLazyRuntimeNamedExport } from "openclaw/plugin-sdk/lazy-runtime";
5
- import { asNullableObjectRecord, normalizeLowercaseStringOrEmpty, normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
4
+ import { asNullableObjectRecord, isRecord, normalizeLowercaseStringOrEmpty, normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
6
5
  import { resolveUserPath } from "openclaw/plugin-sdk/text-utility-runtime";
7
- import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
6
+ import { extractErrorCode, formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
8
7
  import { redactToolPayloadText } from "openclaw/plugin-sdk/logging-core";
9
8
  import { MediaFetchError, parseMediaContentLength, readResponseTextSnippet } from "openclaw/plugin-sdk/media-runtime";
10
9
  import { readProviderJsonResponse } from "openclaw/plugin-sdk/provider-http";
@@ -12,13 +11,16 @@ import { readResponseWithLimit } from "openclaw/plugin-sdk/response-limit-runtim
12
11
  import { buildHostnameAllowlistPolicyFromSuffixAllowlist, fetchWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime";
13
12
  import { createNativeApprovalControlRegistry } from "openclaw/plugin-sdk/approval-runtime";
14
13
  import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
15
- import { createMessageReceiptFromOutboundResults, defineChannelMessageAdapter, sanitizeForPlainText } from "openclaw/plugin-sdk/channel-outbound";
16
- import { FormatCapabilityProfile, markdownToIR, renderMarkdownIRChunksWithinLimit, renderMarkdownWithMarkers, sanitizeAssistantVisibleText } from "openclaw/plugin-sdk/text-chunking";
17
14
  import fs from "node:fs/promises";
15
+ import { readFileHandleBounded } from "openclaw/plugin-sdk/file-access-runtime";
18
16
  import { adaptScopedAccountAccessor } from "openclaw/plugin-sdk/channel-config-helpers";
17
+ import { missingTargetError } from "openclaw/plugin-sdk/channel-feedback";
19
18
  import { defineStableChannelIngressIdentity, identityEntryAuthenticationClassifier } from "openclaw/plugin-sdk/channel-ingress-runtime";
19
+ import { createMessageReceiptFromOutboundResults, defineChannelMessageAdapter, sanitizeForPlainText } from "openclaw/plugin-sdk/channel-outbound";
20
20
  import { buildChannelGroupsScopeTree, createAllowlistProviderOpenWarningCollector, createConditionalWarningCollector, resolveScopeRequireMention } from "openclaw/plugin-sdk/channel-policy";
21
+ import { PAIRING_APPROVED_MESSAGE } from "openclaw/plugin-sdk/channel-status";
21
22
  import { createChannelDirectoryAdapter, listResolvedDirectoryGroupEntriesFromMapKeys, listResolvedDirectoryUserEntriesFromAllowFrom } from "openclaw/plugin-sdk/directory-runtime";
23
+ import { FormatCapabilityProfile, markdownToIR, renderMarkdownIRChunksWithinLimit, renderMarkdownWithMarkers, sanitizeAssistantVisibleText } from "openclaw/plugin-sdk/text-chunking";
22
24
  //#region extensions/googlechat/src/approval-card-actions.ts
23
25
  const GOOGLECHAT_APPROVAL_ACTION = "openclaw.approval";
24
26
  const GOOGLECHAT_APPROVAL_ACTION_PARAM = "openclaw_action";
@@ -42,8 +44,7 @@ function buildGoogleChatApprovalActionParameters(token) {
42
44
  }
43
45
  function collectEventParameters(event) {
44
46
  const params = {};
45
- for (const [key, value] of Object.entries(event.common?.parameters ?? {})) if (typeof value === "string") params[key] = value;
46
- for (const [key, value] of Object.entries(event.commonEventObject?.parameters ?? {})) if (typeof value === "string") params[key] = value;
47
+ for (const source of [event.common?.parameters, event.commonEventObject?.parameters]) for (const [key, value] of Object.entries(source ?? {})) if (typeof value === "string") params[key] = value;
47
48
  for (const item of event.action?.parameters ?? []) if (typeof item.key === "string" && typeof item.value === "string") params[item.key] = item.value;
48
49
  return params;
49
50
  }
@@ -65,23 +66,19 @@ function registerGoogleChatApprovalCardBinding(binding) {
65
66
  return true;
66
67
  }
67
68
  function normalizeApprovalRef(value) {
68
- const normalized = value.trim().toLowerCase();
69
- return normalized ? normalized : null;
70
- }
71
- function manualApprovalFollowupSuppressionKey(approvalId) {
72
- return normalizeApprovalRef(approvalId);
69
+ return value.trim().toLowerCase() || null;
73
70
  }
74
71
  function registerGoogleChatManualApprovalFollowupSuppression(suppression) {
75
72
  if (suppression.expiresAtMs <= Date.now()) return false;
76
- const key = manualApprovalFollowupSuppressionKey(suppression.approvalId);
73
+ const key = normalizeApprovalRef(suppression.approvalId);
77
74
  if (!key) return false;
78
- if (manualApprovalFollowupSuppressions.has(key)) manualApprovalFollowupSuppressions.delete(key);
75
+ manualApprovalFollowupSuppressions.delete(key);
79
76
  manualApprovalFollowupSuppressions.set(key, suppression);
80
77
  pruneMapToMaxSize(manualApprovalFollowupSuppressions, GOOGLECHAT_MANUAL_APPROVAL_SUPPRESSION_MAX_ENTRIES);
81
78
  return true;
82
79
  }
83
80
  function unregisterGoogleChatManualApprovalFollowupSuppression(approvalId) {
84
- const key = manualApprovalFollowupSuppressionKey(approvalId);
81
+ const key = normalizeApprovalRef(approvalId);
85
82
  if (key) manualApprovalFollowupSuppressions.delete(key);
86
83
  }
87
84
  function approvalRefMatches(bindingApprovalId, approvalRef) {
@@ -96,8 +93,7 @@ function pruneExpiredGoogleChatApprovalCardBindings(nowMs) {
96
93
  }
97
94
  function hasActiveGoogleChatExecApprovalCardForManualCommand(params) {
98
95
  pruneExpiredGoogleChatApprovalCardBindings(params.nowMs);
99
- for (const binding of googleChatApprovalControls.values()) if (binding.approvalKind === "exec" && binding.allowedDecisions.includes(params.decision) && approvalRefMatches(binding.approvalId, params.approvalRef)) return true;
100
- for (const suppression of manualApprovalFollowupSuppressions.values()) if (suppression.approvalKind === "exec" && suppression.allowedDecisions.includes(params.decision) && approvalRefMatches(suppression.approvalId, params.approvalRef)) return true;
96
+ for (const entries of [googleChatApprovalControls.values(), manualApprovalFollowupSuppressions.values()]) for (const binding of entries) if (binding.approvalKind === "exec" && binding.allowedDecisions.includes(params.decision) && approvalRefMatches(binding.approvalId, params.approvalRef)) return true;
101
97
  return false;
102
98
  }
103
99
  function shouldSuppressGoogleChatManualExecApprovalFollowupText(text, nowMs = Date.now()) {
@@ -112,11 +108,8 @@ function shouldSuppressGoogleChatManualExecApprovalFollowupText(text, nowMs = Da
112
108
  }
113
109
  return false;
114
110
  }
115
- function hasSendableMedia(payload) {
116
- return Boolean(payload.mediaUrl?.trim() || payload.mediaUrls?.some((url) => url.trim()));
117
- }
118
111
  function hasStructuredPayloadPart(payload) {
119
- return Boolean(hasSendableMedia(payload) || payload.presentation || payload.interactive || payload.btw || payload.spokenText || payload.ttsSupplement);
112
+ return Boolean(payload.mediaUrl?.trim() || payload.mediaUrls?.some((url) => url.trim()) || payload.presentation || payload.interactive || payload.btw || payload.spokenText || payload.ttsSupplement);
120
113
  }
121
114
  function shouldSuppressGoogleChatManualExecApprovalFollowupPayload(payload, nowMs = Date.now()) {
122
115
  const text = payload.text?.trim();
@@ -134,17 +127,13 @@ const GOOGLE_AUTH_UNIVERSE_DOMAIN = "googleapis.com";
134
127
  const GOOGLE_CLIENT_CERTS_URL_PREFIX = "https://www.googleapis.com/robot/v1/metadata/x509/";
135
128
  const MAX_GOOGLE_AUTH_RESPONSE_BYTES = 1048576;
136
129
  let googleAuthRuntimePromise = null;
137
- function normalizeGoogleAuthPreparedRequestHeaders(config) {
138
- if (!(config.headers instanceof Headers)) config.headers = new Headers(config.headers);
139
- return config;
140
- }
141
- function normalizeGoogleAuthResponseHeaders(response) {
142
- if (!(response.headers instanceof Headers)) response.headers = new Headers(response.headers);
143
- return response;
130
+ function normalizeGoogleAuthHeaders(value) {
131
+ if (!(value.headers instanceof Headers)) value.headers = new Headers(value.headers);
132
+ return value;
144
133
  }
145
134
  function installGoogleAuthHeaderCompatibilityInterceptor(transport) {
146
- transport.interceptors.request.add({ resolved: async (config) => normalizeGoogleAuthPreparedRequestHeaders(config) });
147
- transport.interceptors.response.add({ resolved: async (response) => normalizeGoogleAuthResponseHeaders(response) });
135
+ transport.interceptors.request.add({ resolved: async (config) => normalizeGoogleAuthHeaders(config) });
136
+ transport.interceptors.response.add({ resolved: async (response) => normalizeGoogleAuthHeaders(response) });
148
137
  return transport;
149
138
  }
150
139
  function hasProxyAgentShape(value) {
@@ -178,14 +167,9 @@ function resolveGoogleAuthTlsOptions(init, url) {
178
167
  };
179
168
  return {};
180
169
  }
181
- function normalizeGoogleAuthProxyEnvValue(value) {
182
- if (typeof value !== "string") return;
183
- const trimmed = value.trim();
184
- return trimmed.length > 0 ? trimmed : null;
185
- }
186
170
  function resolveGoogleAuthEnvProxyUrl(protocol) {
187
- const httpProxy = normalizeGoogleAuthProxyEnvValue(process.env.HTTP_PROXY) ?? normalizeGoogleAuthProxyEnvValue(process.env.http_proxy);
188
- const httpsProxy = normalizeGoogleAuthProxyEnvValue(process.env.HTTPS_PROXY) ?? normalizeGoogleAuthProxyEnvValue(process.env.https_proxy);
171
+ const httpProxy = normalizeOptionalString(process.env.HTTP_PROXY) ?? normalizeOptionalString(process.env.http_proxy);
172
+ const httpsProxy = normalizeOptionalString(process.env.HTTPS_PROXY) ?? normalizeOptionalString(process.env.https_proxy);
189
173
  if (protocol === "https") return httpsProxy ?? httpProxy ?? void 0;
190
174
  return httpProxy ?? void 0;
191
175
  }
@@ -218,11 +202,7 @@ function shouldBypassGoogleAuthProxy(url, noProxy = []) {
218
202
  return false;
219
203
  }
220
204
  function readGoogleAuthProxyUrl(value) {
221
- if (typeof value === "string") {
222
- const trimmed = value.trim();
223
- return trimmed.length > 0 ? trimmed : void 0;
224
- }
225
- if (value instanceof URL) return value.toString();
205
+ return value instanceof URL ? value.toString() : normalizeOptionalString(value);
226
206
  }
227
207
  function readOptionalTrimmedString(record, fieldName) {
228
208
  const value = record[fieldName];
@@ -233,9 +213,9 @@ function readOptionalTrimmedString(record, fieldName) {
233
213
  return trimmed;
234
214
  }
235
215
  function readRequiredTrimmedString(record, fieldName) {
236
- return readOptionalTrimmedString(record, fieldName) ?? (() => {
237
- throw new Error(`Google Chat service account is missing "${fieldName}"`);
238
- })();
216
+ const value = readOptionalTrimmedString(record, fieldName);
217
+ if (value === void 0) throw new Error(`Google Chat service account is missing "${fieldName}"`);
218
+ return value;
239
219
  }
240
220
  function assertExactUrlField(record, fieldName, expectedUrl) {
241
221
  const value = readOptionalTrimmedString(record, fieldName);
@@ -264,33 +244,33 @@ function validateGoogleChatServiceAccountCredentials(credentials) {
264
244
  private_key: privateKey
265
245
  };
266
246
  }
247
+ function sanitizeCredentialFileReadError(error) {
248
+ return /* @__PURE__ */ new Error(extractErrorCode(error) === "too-large" ? `Google Chat service account file exceeds ${MAX_GOOGLE_CHAT_SERVICE_ACCOUNT_FILE_BYTES} bytes.` : "Failed to load Google Chat service account file.");
249
+ }
267
250
  async function readCredentialsFile(filePath) {
268
251
  const resolvedPath = resolveUserPath(filePath);
269
252
  if (!resolvedPath) throw new Error("Google Chat service account file path is empty");
270
253
  let handle;
271
254
  try {
272
255
  handle = await fs.open(resolvedPath, "r");
273
- } catch {
274
- throw new Error("Failed to load Google Chat service account file.");
256
+ } catch (error) {
257
+ throw sanitizeCredentialFileReadError(error);
275
258
  }
276
259
  try {
277
- const stat = await handle.stat();
278
- if (!stat.isFile()) throw new Error("Google Chat service account file must be a regular file.");
279
- if (stat.size > 65536) throw new Error(`Google Chat service account file exceeds ${MAX_GOOGLE_CHAT_SERVICE_ACCOUNT_FILE_BYTES} bytes.`);
260
+ if (!(await handle.stat()).isFile()) throw new Error("Google Chat service account file must be a regular file.");
280
261
  let raw;
281
262
  try {
282
- raw = await handle.readFile({ encoding: "utf8" });
283
- } catch {
284
- throw new Error("Failed to load Google Chat service account file.");
263
+ raw = (await readFileHandleBounded(handle, MAX_GOOGLE_CHAT_SERVICE_ACCOUNT_FILE_BYTES)).toString("utf8");
264
+ } catch (error) {
265
+ throw sanitizeCredentialFileReadError(error);
285
266
  }
286
- if (Buffer.byteLength(raw, "utf8") > 65536) throw new Error(`Google Chat service account file exceeds ${MAX_GOOGLE_CHAT_SERVICE_ACCOUNT_FILE_BYTES} bytes.`);
287
267
  let parsed;
288
268
  try {
289
269
  parsed = JSON.parse(raw);
290
270
  } catch {
291
271
  throw new Error("Invalid Google Chat service account JSON.");
292
272
  }
293
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("Google Chat service account file must contain a JSON object.");
273
+ if (!isRecord(parsed)) throw new Error("Google Chat service account file must contain a JSON object.");
294
274
  return parsed;
295
275
  } finally {
296
276
  await handle.close().catch(() => {});
@@ -363,7 +343,7 @@ function createGoogleAuthFetch() {
363
343
  statusText: response.statusText
364
344
  });
365
345
  } finally {
366
- if (!response.bodyUsed) response.body?.cancel().catch(() => void 0);
346
+ response.body?.cancel().catch(() => void 0);
367
347
  await release();
368
348
  }
369
349
  };
@@ -374,30 +354,8 @@ async function readGoogleAuthResponseBytes(response) {
374
354
  const contentLength = parseMediaContentLength(contentLengthHeader);
375
355
  if (contentLength !== null && contentLength > MAX_GOOGLE_AUTH_RESPONSE_BYTES) throw new Error(`Google auth response exceeds ${MAX_GOOGLE_AUTH_RESPONSE_BYTES} bytes.`);
376
356
  }
377
- const reader = response.body?.getReader();
378
- if (!reader) throw new Error("Google auth response body stream unavailable; refusing to buffer unbounded response.");
379
- const chunks = [];
380
- let total = 0;
381
- try {
382
- while (true) {
383
- const { done, value } = await reader.read();
384
- if (done) break;
385
- if (!value) continue;
386
- total += value.byteLength;
387
- if (total > MAX_GOOGLE_AUTH_RESPONSE_BYTES) throw new Error(`Google auth response exceeds ${MAX_GOOGLE_AUTH_RESPONSE_BYTES} bytes.`);
388
- chunks.push(value);
389
- }
390
- } finally {
391
- reader.cancel().catch(() => void 0);
392
- reader.releaseLock();
393
- }
394
- const bytes = new Uint8Array(total);
395
- let offset = 0;
396
- for (const chunk of chunks) {
397
- bytes.set(chunk, offset);
398
- offset += chunk.byteLength;
399
- }
400
- return bytes;
357
+ if (!response.body) throw new Error("Google auth response body stream unavailable; refusing to buffer unbounded response.");
358
+ return await readResponseWithLimit(response, MAX_GOOGLE_AUTH_RESPONSE_BYTES, { onOverflow: () => /* @__PURE__ */ new Error(`Google auth response exceeds ${MAX_GOOGLE_AUTH_RESPONSE_BYTES} bytes.`) });
401
359
  }
402
360
  async function loadGoogleAuthRuntime() {
403
361
  googleAuthRuntimePromise ??= import("google-auth-library").catch((error) => {
@@ -422,9 +380,6 @@ const CHAT_ISSUER = "chat@system.gserviceaccount.com";
422
380
  const ADDON_ISSUER_PATTERN = /^service-\d+@gcp-sa-gsuiteaddons\.iam\.gserviceaccount\.com$/;
423
381
  const CHAT_CERTS_URL = "https://www.googleapis.com/service_accounts/v1/metadata/x509/chat@system.gserviceaccount.com";
424
382
  const GOOGLECHAT_CERT_FETCH_TIMEOUT_MS = 3e4;
425
- async function readGoogleChatCertsResponse(response) {
426
- return readProviderJsonResponse(response, "Google Chat cert fetch failed");
427
- }
428
383
  const MAX_AUTH_CACHE_SIZE = 32;
429
384
  const authCache = /* @__PURE__ */ new Map();
430
385
  let cachedCerts = null;
@@ -455,12 +410,6 @@ async function getAuthInstance(account) {
455
410
  getGoogleAuthTransport(),
456
411
  resolveValidatedGoogleChatCredentials(account)
457
412
  ]);
458
- const evictOldest = () => {
459
- if (authCache.size > MAX_AUTH_CACHE_SIZE) {
460
- const oldest = authCache.keys().next().value;
461
- if (oldest !== void 0) authCache.delete(oldest);
462
- }
463
- };
464
413
  const auth = new GoogleAuth({
465
414
  ...credentials ? { credentials } : {},
466
415
  clientOptions: { transporter },
@@ -470,7 +419,7 @@ async function getAuthInstance(account) {
470
419
  key,
471
420
  auth
472
421
  });
473
- evictOldest();
422
+ pruneMapToMaxSize(authCache, MAX_AUTH_CACHE_SIZE);
474
423
  return auth;
475
424
  }
476
425
  async function getGoogleChatAccessToken(account) {
@@ -482,14 +431,14 @@ async function getGoogleChatAccessToken(account) {
482
431
  async function fetchChatCerts() {
483
432
  const now = Date.now();
484
433
  if (cachedCerts && now - cachedCerts.fetchedAt < 6e5) return cachedCerts.certs;
485
- const { response, release } = await fetchWithSsrFGuard$1({
434
+ const { response, release } = await fetchWithSsrFGuard({
486
435
  url: CHAT_CERTS_URL,
487
436
  auditContext: "googlechat.auth.certs",
488
437
  timeoutMs: GOOGLECHAT_CERT_FETCH_TIMEOUT_MS
489
438
  });
490
439
  try {
491
440
  if (!response.ok) throw new Error(`Failed to fetch Chat certs (${response.status})`);
492
- const certs = await readGoogleChatCertsResponse(response);
441
+ const certs = await readProviderJsonResponse(response, "Google Chat cert fetch failed");
493
442
  cachedCerts = {
494
443
  fetchedAt: now,
495
444
  certs
@@ -582,13 +531,6 @@ function resolveGoogleChatMediaTimeoutMs(maxBytes) {
582
531
  const transferMs = Math.ceil(maxBytes / GOOGLECHAT_MEDIA_MIN_BYTES_PER_SECOND * 1e3);
583
532
  return Math.min(GOOGLECHAT_MEDIA_TIMEOUT_GRACE_MS + transferMs, GOOGLECHAT_MEDIA_MAX_TIMEOUT_MS);
584
533
  }
585
- async function readGoogleChatJsonResponse(response, label) {
586
- return readProviderJsonResponse(response, label, {
587
- maxBytes: GOOGLECHAT_JSON_RESPONSE_MAX_BYTES,
588
- chunkTimeoutMs: GOOGLECHAT_RESPONSE_READ_IDLE_TIMEOUT_MS,
589
- onIdleTimeout: ({ chunkTimeoutMs }) => /* @__PURE__ */ new Error(`${label}: response body stalled after ${chunkTimeoutMs}ms`)
590
- });
591
- }
592
534
  async function readGoogleChatErrorResponse(response, label) {
593
535
  const text = await readResponseTextSnippet(response, {
594
536
  maxBytes: GOOGLECHAT_ERROR_BODY_MAX_BYTES,
@@ -598,7 +540,6 @@ async function readGoogleChatErrorResponse(response, label) {
598
540
  }) ?? "";
599
541
  return redactToolPayloadText(text);
600
542
  }
601
- const headersToObject = (headers) => headers instanceof Headers ? Object.fromEntries(headers.entries()) : Array.isArray(headers) ? Object.fromEntries(headers) : headers || {};
602
543
  async function withGoogleChatResponse(params) {
603
544
  const { account, url, init, auditContext, errorPrefix = "Google Chat API", timeoutMs = GOOGLECHAT_API_TIMEOUT_MS, handleResponse, assertDirectAdapterHandoff, onPlatformSendDispatch } = params;
604
545
  assertDirectAdapterHandoff?.();
@@ -612,7 +553,7 @@ async function withGoogleChatResponse(params) {
612
553
  init: {
613
554
  ...init,
614
555
  headers: {
615
- ...headersToObject(init?.headers),
556
+ ...init?.headers,
616
557
  Authorization: `Bearer ${token}`
617
558
  }
618
559
  },
@@ -638,33 +579,25 @@ async function fetchJson(account, url, init, hooks) {
638
579
  url,
639
580
  init: {
640
581
  ...init,
641
- headers: {
642
- ...headersToObject(init.headers),
643
- "Content-Type": "application/json"
644
- }
582
+ headers: { "Content-Type": "application/json" }
645
583
  },
646
584
  auditContext: "googlechat.api.json",
647
- handleResponse: async (response) => await readGoogleChatJsonResponse(response, "Google Chat API request failed")
648
- });
649
- }
650
- async function fetchOk(account, url, init) {
651
- await withGoogleChatResponse({
652
- account,
653
- url,
654
- init,
655
- auditContext: "googlechat.api.ok",
656
- handleResponse: async () => void 0
585
+ handleResponse: async (response) => await readProviderJsonResponse(response, "Google Chat API request failed", {
586
+ maxBytes: GOOGLECHAT_JSON_RESPONSE_MAX_BYTES,
587
+ chunkTimeoutMs: GOOGLECHAT_RESPONSE_READ_IDLE_TIMEOUT_MS,
588
+ onIdleTimeout: ({ chunkTimeoutMs }) => /* @__PURE__ */ new Error(`Google Chat API request failed: response body stalled after ${chunkTimeoutMs}ms`)
589
+ })
657
590
  });
658
591
  }
659
- async function fetchBuffer(account, url, init, options) {
592
+ async function downloadGoogleChatMedia(params) {
593
+ const { account, resourceName, maxBytes: requestedMaxBytes } = params;
660
594
  return await withGoogleChatResponse({
661
595
  account,
662
- url,
663
- init,
596
+ url: `${CHAT_API_BASE}/media/${resourceName}?alt=media`,
664
597
  auditContext: "googlechat.api.buffer",
665
- timeoutMs: resolveGoogleChatMediaTimeoutMs(options?.maxBytes),
598
+ timeoutMs: resolveGoogleChatMediaTimeoutMs(requestedMaxBytes),
666
599
  handleResponse: async (res) => {
667
- const maxBytes = options?.maxBytes ?? GOOGLE_CHAT_MEDIA_RESPONSE_MAX_BYTES;
600
+ const maxBytes = requestedMaxBytes ?? GOOGLE_CHAT_MEDIA_RESPONSE_MAX_BYTES;
668
601
  const lengthHeader = res.headers.get("content-length");
669
602
  if (lengthHeader) {
670
603
  const length = parseMediaContentLength(lengthHeader);
@@ -729,11 +662,13 @@ async function updateGoogleChatMessage(params) {
729
662
  }
730
663
  async function deleteGoogleChatMessage(params) {
731
664
  const { account, messageName } = params;
732
- await fetchOk(account, `${CHAT_API_BASE}/${messageName}`, { method: "DELETE" });
733
- }
734
- async function downloadGoogleChatMedia(params) {
735
- const { account, resourceName, maxBytes } = params;
736
- return await fetchBuffer(account, `${CHAT_API_BASE}/media/${resourceName}?alt=media`, void 0, { maxBytes });
665
+ await withGoogleChatResponse({
666
+ account,
667
+ url: `${CHAT_API_BASE}/${messageName}`,
668
+ init: { method: "DELETE" },
669
+ auditContext: "googlechat.api.ok",
670
+ handleResponse: async () => void 0
671
+ });
737
672
  }
738
673
  async function findGoogleChatDirectMessage(params) {
739
674
  const { account, userName } = params;
@@ -1154,18 +1089,15 @@ function normalizeGoogleChatUserId(raw) {
1154
1089
  return normalizeLowercaseStringOrEmpty(trimmed.replace(/^users\//i, ""));
1155
1090
  }
1156
1091
  const GOOGLECHAT_EMAIL_KIND = "plugin:googlechat-email";
1157
- function normalizeEntryValue(raw) {
1158
- return normalizeLowercaseStringOrEmpty(raw ?? "");
1159
- }
1160
1092
  function normalizeGoogleChatStableEntry(entry) {
1161
- const withoutProvider = normalizeEntryValue(entry).replace(/^(googlechat|google-chat|gchat):/i, "");
1093
+ const withoutProvider = normalizeLowercaseStringOrEmpty(entry).replace(/^(googlechat|google-chat|gchat):/i, "");
1162
1094
  if (!withoutProvider) return null;
1163
1095
  return withoutProvider.startsWith("users/") ? normalizeGoogleChatUserId(withoutProvider) : withoutProvider;
1164
1096
  }
1165
1097
  function normalizeGoogleChatEmailEntry(entry) {
1166
- if (normalizeEntryValue(entry).replace(/^(googlechat|google-chat|gchat):/i, "").startsWith("users/")) return null;
1167
- const stable = normalizeGoogleChatStableEntry(entry);
1168
- return stable?.includes("@") ? stable : null;
1098
+ const withoutProvider = normalizeLowercaseStringOrEmpty(entry).replace(/^(googlechat|google-chat|gchat):/i, "");
1099
+ if (withoutProvider.startsWith("users/")) return null;
1100
+ return withoutProvider.includes("@") ? withoutProvider : null;
1169
1101
  }
1170
1102
  const googleChatIngressIdentity = defineStableChannelIngressIdentity({
1171
1103
  key: "sender-id",
@@ -1176,28 +1108,15 @@ const googleChatIngressIdentity = defineStableChannelIngressIdentity({
1176
1108
  key: "email",
1177
1109
  kind: GOOGLECHAT_EMAIL_KIND,
1178
1110
  normalizeEntry: normalizeGoogleChatEmailEntry,
1179
- normalizeSubject: normalizeEntryValue,
1111
+ normalizeSubject: normalizeLowercaseStringOrEmpty,
1180
1112
  authentication: "mutable"
1181
1113
  }],
1182
- isWildcardEntry: (entry) => normalizeEntryValue(entry) === "*",
1114
+ isWildcardEntry: (entry) => normalizeLowercaseStringOrEmpty(entry) === "*",
1183
1115
  resolveEntryId: ({ entryIndex, fieldKey }) => fieldKey === "stableId" ? `entry-${entryIndex + 1}:user` : `entry-${entryIndex + 1}:${fieldKey}`
1184
1116
  });
1185
1117
  //#endregion
1186
1118
  //#region extensions/googlechat/src/channel.adapters.ts
1187
- const loadGoogleChatChannelRuntime = createLazyRuntimeNamedExport(() => import("./channel.runtime-BdzxoqvE.mjs"), "googleChatChannelRuntime");
1188
- function createGoogleChatSendReceipt(params) {
1189
- const messageId = params.messageId?.trim();
1190
- return createMessageReceiptFromOutboundResults({
1191
- results: messageId ? [{
1192
- channel: "googlechat",
1193
- messageId,
1194
- chatId: params.chatId,
1195
- conversationId: params.chatId
1196
- }] : [],
1197
- threadId: params.threadId,
1198
- kind: params.kind
1199
- });
1200
- }
1119
+ const loadGoogleChatChannelRuntime = createLazyRuntimeNamedExport(() => import("./channel.runtime-C-B60lWL.mjs"), "googleChatChannelRuntime");
1201
1120
  const collectGoogleChatGroupPolicyWarnings = createAllowlistProviderOpenWarningCollector({
1202
1121
  providerConfigPresent: (cfg) => cfg.channels?.googlechat !== void 0,
1203
1122
  resolveGroupPolicy: (account) => account.config.groupPolicy,
@@ -1235,16 +1154,13 @@ const googlechatSecurityAdapter = {
1235
1154
  resolveAllowFrom: (account) => account.config.allowFrom,
1236
1155
  allowFromPathSuffix: "",
1237
1156
  classifyEntryAuthentication: identityEntryAuthenticationClassifier(googleChatIngressIdentity),
1238
- normalizeEntry: (raw) => formatGoogleChatAllowFromEntry(raw)
1157
+ normalizeEntry: formatGoogleChatAllowFromEntry
1239
1158
  },
1240
1159
  collectWarnings: collectGoogleChatSecurityWarnings
1241
1160
  };
1242
1161
  const googlechatThreadingAdapter = {
1243
1162
  scopedAccountReplyToMode: {
1244
- resolveAccount: (cfg, accountId) => resolveGoogleChatAccount({
1245
- cfg,
1246
- accountId
1247
- }),
1163
+ resolveAccount: adaptScopedAccountAccessor(resolveGoogleChatAccount),
1248
1164
  resolveReplyToMode: (account, _chatType) => account.config.replyToMode,
1249
1165
  fallback: "off"
1250
1166
  },
@@ -1266,7 +1182,7 @@ const googlechatThreadingAdapter = {
1266
1182
  const googlechatPairingTextAdapter = {
1267
1183
  idLabel: "googlechatUserId",
1268
1184
  message: PAIRING_APPROVED_MESSAGE,
1269
- normalizeAllowEntry: (entry) => formatGoogleChatAllowFromEntry(entry),
1185
+ normalizeAllowEntry: formatGoogleChatAllowFromEntry,
1270
1186
  notify: async ({ cfg, id, message, accountId }) => {
1271
1187
  const account = resolveGoogleChatAccount({
1272
1188
  cfg,
@@ -1289,25 +1205,17 @@ const googlechatPairingTextAdapter = {
1289
1205
  const googlechatOutboundAdapter = {
1290
1206
  base: {
1291
1207
  deliveryMode: "direct",
1292
- chunker: (text, limit) => formatGoogleChatTextChunks(text, limit),
1208
+ chunker: formatGoogleChatTextChunks,
1293
1209
  chunkerMode: "markdown",
1294
1210
  textChunkLimit: GOOGLE_CHAT_FORMAT_PROFILE.chunk.limit,
1295
1211
  sanitizeText: ({ text }) => sanitizeGoogleChatText(text),
1296
1212
  normalizePayload: ({ payload }) => shouldSuppressGoogleChatManualExecApprovalFollowupPayload(payload) ? null : payload,
1297
1213
  resolveTarget: ({ to }) => {
1298
- const trimmed = normalizeOptionalString(to) ?? "";
1299
- if (trimmed) {
1300
- const normalized = normalizeGoogleChatTarget(trimmed);
1301
- if (!normalized) return {
1302
- ok: false,
1303
- error: missingTargetError("Google Chat", "<spaces/{space}|users/{user}>")
1304
- };
1305
- return {
1306
- ok: true,
1307
- to: normalized
1308
- };
1309
- }
1310
- return {
1214
+ const normalized = normalizeGoogleChatTarget(to);
1215
+ return normalized ? {
1216
+ ok: true,
1217
+ to: normalized
1218
+ } : {
1311
1219
  ok: false,
1312
1220
  error: missingTargetError("Google Chat", "<spaces/{space}|users/{user}>")
1313
1221
  };
@@ -1336,12 +1244,17 @@ const googlechatOutboundAdapter = {
1336
1244
  onPlatformSendDispatch
1337
1245
  });
1338
1246
  const messageId = result?.messageName ?? "";
1247
+ const receiptMessageId = messageId.trim();
1339
1248
  return {
1340
1249
  messageId,
1341
1250
  chatId: space,
1342
- receipt: createGoogleChatSendReceipt({
1343
- messageId,
1344
- chatId: space,
1251
+ receipt: createMessageReceiptFromOutboundResults({
1252
+ results: receiptMessageId ? [{
1253
+ channel: "googlechat",
1254
+ messageId: receiptMessageId,
1255
+ chatId: space,
1256
+ conversationId: space
1257
+ }] : [],
1345
1258
  threadId: result?.threadName ?? thread,
1346
1259
  kind: "text"
1347
1260
  })