@openclaw/googlechat 2026.5.2-beta.1

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 (58) hide show
  1. package/api.ts +3 -0
  2. package/channel-config-api.ts +1 -0
  3. package/channel-plugin-api.ts +1 -0
  4. package/contract-api.ts +5 -0
  5. package/doctor-contract-api.ts +1 -0
  6. package/index.ts +20 -0
  7. package/openclaw.plugin.json +884 -0
  8. package/package.json +88 -0
  9. package/runtime-api.ts +60 -0
  10. package/secret-contract-api.ts +5 -0
  11. package/setup-entry.ts +13 -0
  12. package/setup-plugin-api.ts +3 -0
  13. package/src/accounts.ts +169 -0
  14. package/src/actions.test.ts +265 -0
  15. package/src/actions.ts +227 -0
  16. package/src/api.ts +322 -0
  17. package/src/approval-auth.test.ts +24 -0
  18. package/src/approval-auth.ts +32 -0
  19. package/src/auth.ts +209 -0
  20. package/src/channel-config.test.ts +39 -0
  21. package/src/channel.adapters.ts +293 -0
  22. package/src/channel.deps.runtime.ts +28 -0
  23. package/src/channel.runtime.ts +17 -0
  24. package/src/channel.setup.ts +98 -0
  25. package/src/channel.test.ts +695 -0
  26. package/src/channel.ts +256 -0
  27. package/src/config-schema.test.ts +16 -0
  28. package/src/config-schema.ts +3 -0
  29. package/src/doctor-contract.test.ts +75 -0
  30. package/src/doctor-contract.ts +182 -0
  31. package/src/doctor.ts +57 -0
  32. package/src/gateway.ts +63 -0
  33. package/src/google-auth.runtime.test.ts +462 -0
  34. package/src/google-auth.runtime.ts +539 -0
  35. package/src/group-policy.ts +17 -0
  36. package/src/monitor-access.test.ts +443 -0
  37. package/src/monitor-access.ts +405 -0
  38. package/src/monitor-reply-delivery.ts +156 -0
  39. package/src/monitor-routing.ts +55 -0
  40. package/src/monitor-types.ts +33 -0
  41. package/src/monitor-webhook.test.ts +446 -0
  42. package/src/monitor-webhook.ts +285 -0
  43. package/src/monitor.reply-delivery.test.ts +139 -0
  44. package/src/monitor.ts +428 -0
  45. package/src/monitor.webhook-routing.test.ts +252 -0
  46. package/src/runtime.ts +9 -0
  47. package/src/secret-contract.test.ts +60 -0
  48. package/src/secret-contract.ts +161 -0
  49. package/src/sender-allow.ts +46 -0
  50. package/src/setup-core.ts +40 -0
  51. package/src/setup-surface.ts +236 -0
  52. package/src/setup.test.ts +560 -0
  53. package/src/targets.test.ts +421 -0
  54. package/src/targets.ts +66 -0
  55. package/src/types.config.ts +3 -0
  56. package/src/types.ts +73 -0
  57. package/test-api.ts +2 -0
  58. package/tsconfig.json +16 -0
package/src/auth.ts ADDED
@@ -0,0 +1,209 @@
1
+ import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/text-runtime";
2
+ import { fetchWithSsrFGuard } from "../runtime-api.js";
3
+ import type { ResolvedGoogleChatAccount } from "./accounts.js";
4
+ import {
5
+ __testing as googleAuthRuntimeTesting,
6
+ getGoogleAuthTransport,
7
+ loadGoogleAuthRuntime,
8
+ resolveValidatedGoogleChatCredentials,
9
+ } from "./google-auth.runtime.js";
10
+
11
+ const CHAT_SCOPE = "https://www.googleapis.com/auth/chat.bot";
12
+ const CHAT_ISSUER = "chat@system.gserviceaccount.com";
13
+ // Google Workspace Add-ons use a different service account pattern
14
+ const ADDON_ISSUER_PATTERN = /^service-\d+@gcp-sa-gsuiteaddons\.iam\.gserviceaccount\.com$/;
15
+ const CHAT_CERTS_URL =
16
+ "https://www.googleapis.com/service_accounts/v1/metadata/x509/chat@system.gserviceaccount.com";
17
+
18
+ // Size-capped to prevent unbounded growth in long-running deployments (#4948)
19
+ const MAX_AUTH_CACHE_SIZE = 32;
20
+ type GoogleAuthModule = typeof import("google-auth-library");
21
+ type GoogleAuthRuntime = {
22
+ GoogleAuth: GoogleAuthModule["GoogleAuth"];
23
+ OAuth2Client: GoogleAuthModule["OAuth2Client"];
24
+ };
25
+ type GoogleAuthInstance = InstanceType<GoogleAuthRuntime["GoogleAuth"]>;
26
+ type GoogleAuthOptions = ConstructorParameters<GoogleAuthRuntime["GoogleAuth"]>[0];
27
+ type GoogleAuthTransport = NonNullable<GoogleAuthOptions>["clientOptions"] extends {
28
+ transporter?: infer T;
29
+ }
30
+ ? T
31
+ : never;
32
+ type OAuth2ClientInstance = InstanceType<GoogleAuthRuntime["OAuth2Client"]>;
33
+
34
+ const authCache = new Map<string, { key: string; auth: GoogleAuthInstance }>();
35
+
36
+ let cachedCerts: { fetchedAt: number; certs: Record<string, string> } | null = null;
37
+ let verifyClientPromise: Promise<OAuth2ClientInstance> | null = null;
38
+
39
+ async function getVerifyClient(): Promise<OAuth2ClientInstance> {
40
+ if (!verifyClientPromise) {
41
+ verifyClientPromise = (async () => {
42
+ try {
43
+ const { OAuth2Client } = await loadGoogleAuthRuntime();
44
+ // google-auth-library types its transporter through gaxios' CJS surface,
45
+ // while the plugin imports the ESM entrypoint directly.
46
+ const transporter = (await getGoogleAuthTransport()) as unknown as GoogleAuthTransport;
47
+ return new OAuth2Client({ transporter });
48
+ } catch (error) {
49
+ verifyClientPromise = null;
50
+ throw error;
51
+ }
52
+ })();
53
+ }
54
+ return await verifyClientPromise;
55
+ }
56
+
57
+ function buildAuthKey(account: ResolvedGoogleChatAccount): string {
58
+ if (account.credentialsFile) {
59
+ return `file:${account.credentialsFile}`;
60
+ }
61
+ if (account.credentials) {
62
+ return `inline:${JSON.stringify(account.credentials)}`;
63
+ }
64
+ return "none";
65
+ }
66
+
67
+ async function getAuthInstance(account: ResolvedGoogleChatAccount): Promise<GoogleAuthInstance> {
68
+ const key = buildAuthKey(account);
69
+ const cached = authCache.get(account.accountId);
70
+ if (cached && cached.key === key) {
71
+ return cached.auth;
72
+ }
73
+ const [{ GoogleAuth }, rawTransporter, credentials] = await Promise.all([
74
+ loadGoogleAuthRuntime(),
75
+ getGoogleAuthTransport(),
76
+ resolveValidatedGoogleChatCredentials(account),
77
+ ]);
78
+ const transporter = rawTransporter as unknown as GoogleAuthTransport;
79
+
80
+ const evictOldest = () => {
81
+ if (authCache.size > MAX_AUTH_CACHE_SIZE) {
82
+ const oldest = authCache.keys().next().value;
83
+ if (oldest !== undefined) {
84
+ authCache.delete(oldest);
85
+ }
86
+ }
87
+ };
88
+
89
+ const auth = new GoogleAuth({
90
+ ...(credentials ? { credentials } : {}),
91
+ clientOptions: { transporter },
92
+ scopes: [CHAT_SCOPE],
93
+ });
94
+ authCache.set(account.accountId, { key, auth });
95
+ evictOldest();
96
+ return auth;
97
+ }
98
+
99
+ export async function getGoogleChatAccessToken(
100
+ account: ResolvedGoogleChatAccount,
101
+ ): Promise<string> {
102
+ const auth = await getAuthInstance(account);
103
+ const client = await auth.getClient();
104
+ const access = await client.getAccessToken();
105
+ const token = typeof access === "string" ? access : access?.token;
106
+ if (!token) {
107
+ throw new Error("Missing Google Chat access token");
108
+ }
109
+ return token;
110
+ }
111
+
112
+ async function fetchChatCerts(): Promise<Record<string, string>> {
113
+ const now = Date.now();
114
+ if (cachedCerts && now - cachedCerts.fetchedAt < 10 * 60 * 1000) {
115
+ return cachedCerts.certs;
116
+ }
117
+ const { response, release } = await fetchWithSsrFGuard({
118
+ url: CHAT_CERTS_URL,
119
+ auditContext: "googlechat.auth.certs",
120
+ });
121
+ try {
122
+ if (!response.ok) {
123
+ throw new Error(`Failed to fetch Chat certs (${response.status})`);
124
+ }
125
+ const certs = (await response.json()) as Record<string, string>;
126
+ cachedCerts = { fetchedAt: now, certs };
127
+ return certs;
128
+ } finally {
129
+ await release();
130
+ }
131
+ }
132
+
133
+ export type GoogleChatAudienceType = "app-url" | "project-number";
134
+
135
+ export async function verifyGoogleChatRequest(params: {
136
+ bearer?: string | null;
137
+ audienceType?: GoogleChatAudienceType | null;
138
+ audience?: string | null;
139
+ expectedAddOnPrincipal?: string | null;
140
+ }): Promise<{ ok: boolean; reason?: string }> {
141
+ const bearer = params.bearer?.trim();
142
+ if (!bearer) {
143
+ return { ok: false, reason: "missing token" };
144
+ }
145
+ const audience = params.audience?.trim();
146
+ if (!audience) {
147
+ return { ok: false, reason: "missing audience" };
148
+ }
149
+ const audienceType = params.audienceType ?? null;
150
+
151
+ if (audienceType === "app-url") {
152
+ try {
153
+ const verifyClient = await getVerifyClient();
154
+ const ticket = await verifyClient.verifyIdToken({
155
+ idToken: bearer,
156
+ audience,
157
+ });
158
+ const payload = ticket.getPayload();
159
+ const email = normalizeLowercaseStringOrEmpty(payload?.email ?? "");
160
+ if (!payload?.email_verified) {
161
+ return { ok: false, reason: "email not verified" };
162
+ }
163
+ if (email === CHAT_ISSUER) {
164
+ return { ok: true };
165
+ }
166
+ if (!ADDON_ISSUER_PATTERN.test(email)) {
167
+ return { ok: false, reason: `invalid issuer: ${email}` };
168
+ }
169
+ const expectedAddOnPrincipal = normalizeLowercaseStringOrEmpty(
170
+ params.expectedAddOnPrincipal ?? "",
171
+ );
172
+ if (!expectedAddOnPrincipal) {
173
+ return { ok: false, reason: "missing add-on principal binding" };
174
+ }
175
+ const tokenPrincipal = normalizeLowercaseStringOrEmpty(payload?.sub ?? "");
176
+ if (!tokenPrincipal || tokenPrincipal !== expectedAddOnPrincipal) {
177
+ return {
178
+ ok: false,
179
+ reason: `unexpected add-on principal: ${tokenPrincipal || "<missing>"}`,
180
+ };
181
+ }
182
+ return { ok: true };
183
+ } catch (err) {
184
+ return { ok: false, reason: err instanceof Error ? err.message : "invalid token" };
185
+ }
186
+ }
187
+
188
+ if (audienceType === "project-number") {
189
+ try {
190
+ const verifyClient = await getVerifyClient();
191
+ const certs = await fetchChatCerts();
192
+ await verifyClient.verifySignedJwtWithCertsAsync(bearer, certs, audience, [CHAT_ISSUER]);
193
+ return { ok: true };
194
+ } catch (err) {
195
+ return { ok: false, reason: err instanceof Error ? err.message : "invalid token" };
196
+ }
197
+ }
198
+
199
+ return { ok: false, reason: "unsupported audience type" };
200
+ }
201
+
202
+ export const __testing = {
203
+ resetGoogleChatAuthForTests(): void {
204
+ authCache.clear();
205
+ cachedCerts = null;
206
+ verifyClientPromise = null;
207
+ googleAuthRuntimeTesting.resetGoogleAuthRuntimeForTests();
208
+ },
209
+ };
@@ -0,0 +1,39 @@
1
+ import type { OpenClawConfig } from "openclaw/plugin-sdk/config-types";
2
+ import { describe, expect, it } from "vitest";
3
+ import { googlechatPlugin } from "./channel.js";
4
+
5
+ describe("googlechatPlugin config adapter", () => {
6
+ it("keeps read-only accessors from resolving service account SecretRefs", () => {
7
+ const cfg = {
8
+ secrets: {
9
+ providers: {
10
+ google_chat_service_account: {
11
+ source: "file",
12
+ path: "/tmp/openclaw-missing-google-chat-service-account",
13
+ mode: "singleValue",
14
+ },
15
+ },
16
+ },
17
+ channels: {
18
+ googlechat: {
19
+ serviceAccount: {
20
+ source: "file",
21
+ provider: "google_chat_service_account",
22
+ id: "value",
23
+ },
24
+ dm: {
25
+ allowFrom: ["users/123"],
26
+ },
27
+ defaultTo: "spaces/AAA",
28
+ },
29
+ },
30
+ } as OpenClawConfig;
31
+
32
+ expect(googlechatPlugin.config.resolveAllowFrom?.({ cfg, accountId: "default" })).toEqual([
33
+ "users/123",
34
+ ]);
35
+ expect(googlechatPlugin.config.resolveDefaultTo?.({ cfg, accountId: "default" })).toBe(
36
+ "spaces/AAA",
37
+ );
38
+ });
39
+ });
@@ -0,0 +1,293 @@
1
+ import { adaptScopedAccountAccessor } from "openclaw/plugin-sdk/channel-config-helpers";
2
+ import {
3
+ composeAccountWarningCollectors,
4
+ createAllowlistProviderOpenWarningCollector,
5
+ } from "openclaw/plugin-sdk/channel-policy";
6
+ import {
7
+ createChannelDirectoryAdapter,
8
+ listResolvedDirectoryGroupEntriesFromMapKeys,
9
+ listResolvedDirectoryUserEntriesFromAllowFrom,
10
+ } from "openclaw/plugin-sdk/directory-runtime";
11
+ import { createLazyRuntimeNamedExport } from "openclaw/plugin-sdk/lazy-runtime";
12
+ import type { OutboundMediaLoadOptions } from "openclaw/plugin-sdk/outbound-media";
13
+ import { sanitizeForPlainText } from "openclaw/plugin-sdk/outbound-runtime";
14
+ import {
15
+ normalizeLowercaseStringOrEmpty,
16
+ normalizeOptionalString,
17
+ } from "openclaw/plugin-sdk/text-runtime";
18
+ import {
19
+ type ResolvedGoogleChatAccount,
20
+ chunkTextForOutbound,
21
+ fetchRemoteMedia,
22
+ isGoogleChatUserTarget,
23
+ loadOutboundMediaFromUrl,
24
+ missingTargetError,
25
+ normalizeGoogleChatTarget,
26
+ PAIRING_APPROVED_MESSAGE,
27
+ resolveChannelMediaMaxBytes,
28
+ resolveGoogleChatAccount,
29
+ resolveGoogleChatOutboundSpace,
30
+ type OpenClawConfig,
31
+ } from "./channel.deps.runtime.js";
32
+ import { resolveGoogleChatGroupRequireMention } from "./group-policy.js";
33
+
34
+ const loadGoogleChatChannelRuntime = createLazyRuntimeNamedExport(
35
+ () => import("./channel.runtime.js"),
36
+ "googleChatChannelRuntime",
37
+ );
38
+
39
+ export const formatAllowFromEntry = (entry: string) =>
40
+ normalizeLowercaseStringOrEmpty(
41
+ entry
42
+ .trim()
43
+ .replace(/^(googlechat|google-chat|gchat):/i, "")
44
+ .replace(/^user:/i, "")
45
+ .replace(/^users\//i, ""),
46
+ );
47
+
48
+ const collectGoogleChatGroupPolicyWarnings =
49
+ createAllowlistProviderOpenWarningCollector<ResolvedGoogleChatAccount>({
50
+ providerConfigPresent: (cfg) => cfg.channels?.googlechat !== undefined,
51
+ resolveGroupPolicy: (account) => account.config.groupPolicy,
52
+ buildOpenWarning: {
53
+ surface: "Google Chat spaces",
54
+ openBehavior: "allows any space to trigger (mention-gated)",
55
+ remediation:
56
+ 'Set channels.googlechat.groupPolicy="allowlist" and configure channels.googlechat.groups',
57
+ },
58
+ });
59
+
60
+ const collectGoogleChatSecurityWarnings = composeAccountWarningCollectors<
61
+ ResolvedGoogleChatAccount,
62
+ {
63
+ cfg: OpenClawConfig;
64
+ account: ResolvedGoogleChatAccount;
65
+ }
66
+ >(
67
+ collectGoogleChatGroupPolicyWarnings,
68
+ (account) =>
69
+ account.config.dm?.policy === "open" &&
70
+ '- Google Chat DMs are open to anyone. Set channels.googlechat.dm.policy="pairing" or "allowlist".',
71
+ );
72
+
73
+ export const googlechatGroupsAdapter = {
74
+ resolveRequireMention: resolveGoogleChatGroupRequireMention,
75
+ };
76
+
77
+ export const googlechatDirectoryAdapter = createChannelDirectoryAdapter({
78
+ listPeers: async (params) =>
79
+ listResolvedDirectoryUserEntriesFromAllowFrom<ResolvedGoogleChatAccount>({
80
+ ...params,
81
+ resolveAccount: adaptScopedAccountAccessor(resolveGoogleChatAccount),
82
+ resolveAllowFrom: (account) => account.config.dm?.allowFrom,
83
+ normalizeId: (entry) => normalizeGoogleChatTarget(entry) ?? entry,
84
+ }),
85
+ listGroups: async (params) =>
86
+ listResolvedDirectoryGroupEntriesFromMapKeys<ResolvedGoogleChatAccount>({
87
+ ...params,
88
+ resolveAccount: adaptScopedAccountAccessor(resolveGoogleChatAccount),
89
+ resolveGroups: (account) => account.config.groups,
90
+ }),
91
+ });
92
+
93
+ export const googlechatSecurityAdapter = {
94
+ dm: {
95
+ channelKey: "googlechat",
96
+ resolvePolicy: (account: ResolvedGoogleChatAccount) => account.config.dm?.policy,
97
+ resolveAllowFrom: (account: ResolvedGoogleChatAccount) => account.config.dm?.allowFrom,
98
+ allowFromPathSuffix: "dm.",
99
+ normalizeEntry: (raw: string) => formatAllowFromEntry(raw),
100
+ },
101
+ collectWarnings: collectGoogleChatSecurityWarnings,
102
+ };
103
+
104
+ export const googlechatThreadingAdapter = {
105
+ scopedAccountReplyToMode: {
106
+ resolveAccount: (cfg: OpenClawConfig, accountId?: string | null) =>
107
+ resolveGoogleChatAccount({ cfg, accountId }),
108
+ resolveReplyToMode: (account: ResolvedGoogleChatAccount, _chatType?: string | null) =>
109
+ account.config.replyToMode,
110
+ fallback: "off" as const,
111
+ },
112
+ };
113
+
114
+ export const googlechatPairingTextAdapter = {
115
+ idLabel: "googlechatUserId",
116
+ message: PAIRING_APPROVED_MESSAGE,
117
+ normalizeAllowEntry: (entry: string) => formatAllowFromEntry(entry),
118
+ notify: async ({
119
+ cfg,
120
+ id,
121
+ message,
122
+ accountId,
123
+ }: {
124
+ cfg: OpenClawConfig;
125
+ id: string;
126
+ message: string;
127
+ accountId?: string | null;
128
+ }) => {
129
+ const account = resolveGoogleChatAccount({ cfg: cfg, accountId });
130
+ if (account.credentialSource === "none") {
131
+ return;
132
+ }
133
+ const user = normalizeGoogleChatTarget(id) ?? id;
134
+ const target = isGoogleChatUserTarget(user) ? user : `users/${user}`;
135
+ const space = await resolveGoogleChatOutboundSpace({ account, target });
136
+ const { sendGoogleChatMessage } = await loadGoogleChatChannelRuntime();
137
+ await sendGoogleChatMessage({
138
+ account,
139
+ space,
140
+ text: message,
141
+ });
142
+ },
143
+ };
144
+
145
+ export const googlechatOutboundAdapter = {
146
+ base: {
147
+ deliveryMode: "direct" as const,
148
+ chunker: chunkTextForOutbound,
149
+ chunkerMode: "markdown" as const,
150
+ textChunkLimit: 4000,
151
+ sanitizeText: ({ text }: { text: string }) => sanitizeForPlainText(text),
152
+ resolveTarget: ({ to }: { to?: string }) => {
153
+ const trimmed = normalizeOptionalString(to) ?? "";
154
+
155
+ if (trimmed) {
156
+ const normalized = normalizeGoogleChatTarget(trimmed);
157
+ if (!normalized) {
158
+ return {
159
+ ok: false as const,
160
+ error: missingTargetError("Google Chat", "<spaces/{space}|users/{user}>"),
161
+ };
162
+ }
163
+ return { ok: true as const, to: normalized };
164
+ }
165
+
166
+ return {
167
+ ok: false as const,
168
+ error: missingTargetError("Google Chat", "<spaces/{space}|users/{user}>"),
169
+ };
170
+ },
171
+ },
172
+ attachedResults: {
173
+ channel: "googlechat" as const,
174
+ sendText: async ({
175
+ cfg,
176
+ to,
177
+ text,
178
+ accountId,
179
+ replyToId,
180
+ threadId,
181
+ }: {
182
+ cfg: OpenClawConfig;
183
+ to: string;
184
+ text: string;
185
+ accountId?: string | null;
186
+ replyToId?: string | null;
187
+ threadId?: string | number | null;
188
+ }) => {
189
+ const account = resolveGoogleChatAccount({
190
+ cfg: cfg,
191
+ accountId,
192
+ });
193
+ const space = await resolveGoogleChatOutboundSpace({ account, target: to });
194
+ const thread =
195
+ typeof threadId === "number" ? String(threadId) : (threadId ?? replyToId ?? undefined);
196
+ const { sendGoogleChatMessage } = await loadGoogleChatChannelRuntime();
197
+ const result = await sendGoogleChatMessage({
198
+ account,
199
+ space,
200
+ text,
201
+ thread,
202
+ });
203
+ return {
204
+ messageId: result?.messageName ?? "",
205
+ chatId: space,
206
+ };
207
+ },
208
+ sendMedia: async ({
209
+ cfg,
210
+ to,
211
+ text,
212
+ mediaUrl,
213
+ mediaAccess,
214
+ mediaLocalRoots,
215
+ mediaReadFile,
216
+ accountId,
217
+ replyToId,
218
+ threadId,
219
+ }: {
220
+ cfg: OpenClawConfig;
221
+ to: string;
222
+ text?: string;
223
+ mediaUrl?: string;
224
+ mediaAccess?: OutboundMediaLoadOptions["mediaAccess"];
225
+ mediaLocalRoots?: OutboundMediaLoadOptions["mediaLocalRoots"];
226
+ mediaReadFile?: OutboundMediaLoadOptions["mediaReadFile"];
227
+ accountId?: string | null;
228
+ replyToId?: string | null;
229
+ threadId?: string | number | null;
230
+ }) => {
231
+ if (!mediaUrl) {
232
+ throw new Error("Google Chat mediaUrl is required.");
233
+ }
234
+ const account = resolveGoogleChatAccount({
235
+ cfg: cfg,
236
+ accountId,
237
+ });
238
+ const space = await resolveGoogleChatOutboundSpace({ account, target: to });
239
+ const thread =
240
+ typeof threadId === "number" ? String(threadId) : (threadId ?? replyToId ?? undefined);
241
+ const maxBytes = resolveChannelMediaMaxBytes({
242
+ cfg: cfg,
243
+ resolveChannelLimitMb: ({ cfg, accountId }) =>
244
+ (
245
+ cfg.channels?.googlechat as
246
+ | { accounts?: Record<string, { mediaMaxMb?: number }>; mediaMaxMb?: number }
247
+ | undefined
248
+ )?.accounts?.[accountId]?.mediaMaxMb ??
249
+ (cfg.channels?.googlechat as { mediaMaxMb?: number } | undefined)?.mediaMaxMb,
250
+ accountId,
251
+ });
252
+ const effectiveMaxBytes = maxBytes ?? (account.config.mediaMaxMb ?? 20) * 1024 * 1024;
253
+ const loaded = /^https?:\/\//i.test(mediaUrl)
254
+ ? await fetchRemoteMedia({
255
+ url: mediaUrl,
256
+ maxBytes: effectiveMaxBytes,
257
+ })
258
+ : await loadOutboundMediaFromUrl(mediaUrl, {
259
+ maxBytes: effectiveMaxBytes,
260
+ mediaAccess,
261
+ mediaLocalRoots,
262
+ mediaReadFile,
263
+ });
264
+ const { sendGoogleChatMessage, uploadGoogleChatAttachment } =
265
+ await loadGoogleChatChannelRuntime();
266
+ const upload = await uploadGoogleChatAttachment({
267
+ account,
268
+ space,
269
+ filename: loaded.fileName ?? "attachment",
270
+ buffer: loaded.buffer,
271
+ contentType: loaded.contentType,
272
+ });
273
+ const result = await sendGoogleChatMessage({
274
+ account,
275
+ space,
276
+ text,
277
+ thread,
278
+ attachments: upload.attachmentUploadToken
279
+ ? [
280
+ {
281
+ attachmentUploadToken: upload.attachmentUploadToken,
282
+ contentName: loaded.fileName,
283
+ },
284
+ ]
285
+ : undefined,
286
+ });
287
+ return {
288
+ messageId: result?.messageName ?? "",
289
+ chatId: space,
290
+ };
291
+ },
292
+ },
293
+ };
@@ -0,0 +1,28 @@
1
+ export {
2
+ buildChannelConfigSchema,
3
+ chunkTextForOutbound,
4
+ DEFAULT_ACCOUNT_ID,
5
+ fetchRemoteMedia,
6
+ GoogleChatConfigSchema,
7
+ loadOutboundMediaFromUrl,
8
+ missingTargetError,
9
+ PAIRING_APPROVED_MESSAGE,
10
+ resolveChannelMediaMaxBytes,
11
+ type ChannelMessageActionAdapter,
12
+ type ChannelStatusIssue,
13
+ type OpenClawConfig,
14
+ } from "../runtime-api.js";
15
+ export {
16
+ type GoogleChatConfigAccessorAccount,
17
+ listGoogleChatAccountIds,
18
+ resolveGoogleChatConfigAccessorAccount,
19
+ resolveDefaultGoogleChatAccountId,
20
+ resolveGoogleChatAccount,
21
+ type ResolvedGoogleChatAccount,
22
+ } from "./accounts.js";
23
+ export {
24
+ isGoogleChatSpaceTarget,
25
+ isGoogleChatUserTarget,
26
+ normalizeGoogleChatTarget,
27
+ resolveGoogleChatOutboundSpace,
28
+ } from "./targets.js";
@@ -0,0 +1,17 @@
1
+ import {
2
+ probeGoogleChat as probeGoogleChatImpl,
3
+ sendGoogleChatMessage as sendGoogleChatMessageImpl,
4
+ uploadGoogleChatAttachment as uploadGoogleChatAttachmentImpl,
5
+ } from "./api.js";
6
+ import {
7
+ resolveGoogleChatWebhookPath as resolveGoogleChatWebhookPathImpl,
8
+ startGoogleChatMonitor as startGoogleChatMonitorImpl,
9
+ } from "./monitor.js";
10
+
11
+ export const googleChatChannelRuntime = {
12
+ probeGoogleChat: probeGoogleChatImpl,
13
+ sendGoogleChatMessage: sendGoogleChatMessageImpl,
14
+ uploadGoogleChatAttachment: uploadGoogleChatAttachmentImpl,
15
+ resolveGoogleChatWebhookPath: resolveGoogleChatWebhookPathImpl,
16
+ startGoogleChatMonitor: startGoogleChatMonitorImpl,
17
+ };
@@ -0,0 +1,98 @@
1
+ import { describeAccountSnapshot } from "openclaw/plugin-sdk/account-helpers";
2
+ import { formatNormalizedAllowFromEntries } from "openclaw/plugin-sdk/allow-from";
3
+ import {
4
+ adaptScopedAccountAccessor,
5
+ createScopedChannelConfigAdapter,
6
+ } from "openclaw/plugin-sdk/channel-config-helpers";
7
+ import type { ChannelPlugin } from "openclaw/plugin-sdk/channel-core";
8
+ import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/text-runtime";
9
+ import {
10
+ type GoogleChatConfigAccessorAccount,
11
+ listGoogleChatAccountIds,
12
+ resolveGoogleChatConfigAccessorAccount,
13
+ resolveDefaultGoogleChatAccountId,
14
+ resolveGoogleChatAccount,
15
+ type ResolvedGoogleChatAccount,
16
+ } from "./accounts.js";
17
+ import { googlechatSetupAdapter } from "./setup-core.js";
18
+ import { googlechatSetupWizard } from "./setup-surface.js";
19
+
20
+ const formatGoogleChatAllowFromEntry = (entry: string) =>
21
+ normalizeLowercaseStringOrEmpty(
22
+ entry
23
+ .trim()
24
+ .replace(/^(googlechat|google-chat|gchat):/i, "")
25
+ .replace(/^user:/i, "")
26
+ .replace(/^users\//i, ""),
27
+ );
28
+
29
+ const googleChatConfigAdapter = createScopedChannelConfigAdapter<
30
+ ResolvedGoogleChatAccount,
31
+ GoogleChatConfigAccessorAccount
32
+ >({
33
+ sectionKey: "googlechat",
34
+ listAccountIds: listGoogleChatAccountIds,
35
+ resolveAccount: adaptScopedAccountAccessor(resolveGoogleChatAccount),
36
+ resolveAccessorAccount: resolveGoogleChatConfigAccessorAccount,
37
+ defaultAccountId: resolveDefaultGoogleChatAccountId,
38
+ clearBaseFields: [
39
+ "serviceAccount",
40
+ "serviceAccountFile",
41
+ "audienceType",
42
+ "audience",
43
+ "webhookPath",
44
+ "webhookUrl",
45
+ "botUser",
46
+ "name",
47
+ ],
48
+ resolveAllowFrom: (account) => account.config.dm?.allowFrom,
49
+ formatAllowFrom: (allowFrom) =>
50
+ formatNormalizedAllowFromEntries({
51
+ allowFrom,
52
+ normalizeEntry: formatGoogleChatAllowFromEntry,
53
+ }),
54
+ resolveDefaultTo: (account) => account.config.defaultTo,
55
+ });
56
+
57
+ export const googlechatSetupPlugin: ChannelPlugin<ResolvedGoogleChatAccount> = {
58
+ id: "googlechat",
59
+ meta: {
60
+ id: "googlechat",
61
+ label: "Google Chat",
62
+ selectionLabel: "Google Chat (Chat API)",
63
+ docsPath: "/channels/googlechat",
64
+ docsLabel: "googlechat",
65
+ blurb: "Google Workspace Chat app with HTTP webhook.",
66
+ aliases: ["gchat", "google-chat"],
67
+ order: 55,
68
+ detailLabel: "Google Chat",
69
+ systemImage: "message.badge",
70
+ markdownCapable: true,
71
+ },
72
+ setup: googlechatSetupAdapter,
73
+ setupWizard: googlechatSetupWizard,
74
+ capabilities: {
75
+ chatTypes: ["direct", "group", "thread"],
76
+ reactions: true,
77
+ threads: true,
78
+ media: true,
79
+ nativeCommands: false,
80
+ blockStreaming: true,
81
+ },
82
+ streaming: {
83
+ blockStreamingCoalesceDefaults: { minChars: 1500, idleMs: 1000 },
84
+ },
85
+ reload: { configPrefixes: ["channels.googlechat"] },
86
+ config: {
87
+ ...googleChatConfigAdapter,
88
+ isConfigured: (account) => account.credentialSource !== "none",
89
+ describeAccount: (account) =>
90
+ describeAccountSnapshot({
91
+ account,
92
+ configured: account.credentialSource !== "none",
93
+ extra: {
94
+ credentialSource: account.credentialSource,
95
+ },
96
+ }),
97
+ },
98
+ };