import { i as createLazyRuntimeNamedExport } from "./lazy-runtime-B-Fc-m0I.js";
import { t as DEFAULT_ACCOUNT_ID } from "./account-id-C7N4Rwku.js";
import { i as buildChannelConfigSchema } from "./config-schema-C1QEePO7.js";
import { i as runPassiveAccountLifecycle, t as createAccountStatusSink } from "./channel-lifecycle.core-BwupdI87.js";
import { i as createDangerousNameMatchingMutableAllowlistWarningCollector, r as collectStandardAllowlistLists, t as buildMutableAllowEntryDetector } from "./channel-policy-PlwZT1KM.js";
import { i as createChatChannelPlugin } from "./core-Vq_PHglM.js";
import { t as CHANNEL_APPROVAL_NATIVE_RUNTIME_CONTEXT_CAPABILITY } from "./approval-handler-adapter-runtime-DjbKLbMW.js";
import { r as registerChannelRuntimeContext } from "./channel-runtime-context-gztTEkoq.js";
import "./channel-outbound-DB2gO0FM.js";
import { d as createDefaultChannelRuntimeState, u as createComputedAccountStatusAdapter } from "./status-helpers-qb1hhp-k.js";
import { n as buildPassiveProbedChannelStatusSummary } from "./extension-shared-CZrErYNM.js";
import { n as GoogleChatConfigSchema } from "./bundled-channel-config-schema-JS4NS9pM.js";
import "./channel-core-B4dqPmDe.js";
import { t as extractToolSend } from "./tool-send-DlIp2cBO.js";
import { i as resolveGoogleChatAccount, n as listGoogleChatAccountIds } from "./accounts-CI5PaZrM.js";
import { a as resolveGoogleChatOutboundSessionRoute, i as normalizeGoogleChatTarget, n as isGoogleChatSpaceTarget, r as isGoogleChatUserTarget } from "./targets-7eoMJLs6.js";
import { i as shouldSuppressLocalGoogleChatExecApprovalPrompt, n as isGoogleChatNativeApprovalClientEnabled, t as googleChatApprovalCapability } from "./approval-native-BYM9OKVZ.js";
import { n as createGoogleChatPluginBase, t as GOOGLECHAT_CHANNEL_ID } from "./channel-base-CF_1IBWk.js";
import { a as googlechatPairingTextAdapter, i as googlechatOutboundAdapter, n as googlechatGroupsAdapter, o as googlechatSecurityAdapter, r as googlechatMessageAdapter, s as googlechatThreadingAdapter, t as googlechatDirectoryAdapter } from "./channel.adapters-CS180X-Q.js";
import { n as normalizeCompatibilityConfig, t as legacyConfigRules } from "./doctor-contract-DgawHBHz.js";
import { n as collectRuntimeConfigAssignments, r as secretTargetRegistryEntries } from "./secret-contract-B-jNj96U.js";
const collectGoogleChatMutableAllowlistWarnings = createDangerousNameMatchingMutableAllowlistWarningCollector({
	channel: "googlechat",
	detector: buildMutableAllowEntryDetector({
		prefixes: [
			"googlechat:",
			"google-chat:",
			"gchat:",
			"users/"
		],
		stableIdPattern: /^[^@]+$/
	}),
	collectLists: (scope) => collectStandardAllowlistLists(scope, {
		includeAllowFrom: false,
		includeDm: true,
		includeGroups: true,
		groupField: "users"
	})
});
//#endregion
//#region extensions/googlechat/src/gateway.ts
const loadGoogleChatChannelRuntime$1 = createLazyRuntimeNamedExport(() => import("./channel.runtime-CzExp2xu.js"), "googleChatChannelRuntime");
async function startGoogleChatGatewayAccount(ctx) {
	const account = ctx.account;
	const statusSink = createAccountStatusSink({
		accountId: account.accountId,
		setStatus: ctx.setStatus
	});
	ctx.log?.info?.(`[${account.accountId}] starting Google Chat webhook`);
	const { resolveGoogleChatWebhookPath, startGoogleChatMonitor } = await loadGoogleChatChannelRuntime$1();
	statusSink({
		running: true,
		lastStartAt: Date.now(),
		webhookPath: resolveGoogleChatWebhookPath({ account }),
		audienceType: account.config.audienceType,
		audience: account.config.audience
	});
	let stopped = false;
	const markStopped = () => {
		if (stopped) return;
		stopped = true;
		statusSink({
			running: false,
			lastStopAt: Date.now()
		});
	};
	if (isGoogleChatNativeApprovalClientEnabled({
		cfg: ctx.cfg,
		accountId: account.accountId
	})) registerChannelRuntimeContext({
		channelRuntime: ctx.channelRuntime,
		channelId: "googlechat",
		accountId: account.accountId,
		capability: CHANNEL_APPROVAL_NATIVE_RUNTIME_CONTEXT_CAPABILITY,
		context: { account },
		abortSignal: ctx.abortSignal
	});
	try {
		await runPassiveAccountLifecycle({
			abortSignal: ctx.abortSignal,
			start: async () => await startGoogleChatMonitor({
				account,
				config: ctx.cfg,
				runtime: ctx.runtime,
				abortSignal: ctx.abortSignal,
				webhookPath: account.config.webhookPath,
				webhookUrl: account.config.webhookUrl,
				statusSink
			}),
			stop: async (unregister) => {
				unregister?.();
			},
			onStop: async () => {
				markStopped();
			}
		});
	} catch (error) {
		markStopped();
		throw error;
	}
}
//#endregion
//#region extensions/googlechat/src/channel.ts
const loadGoogleChatChannelRuntime = createLazyRuntimeNamedExport(() => import("./channel.runtime-CzExp2xu.js"), "googleChatChannelRuntime");
const googlechatActions = {
	describeMessageTool: ({ cfg, accountId }) => {
		if ((accountId ? [resolveGoogleChatAccount({
			cfg,
			accountId
		})].filter((account) => account.enabled && account.credentialSource !== "none" && account.tokenStatus !== "configured_unavailable") : listGoogleChatAccountIds(cfg).map((id) => resolveGoogleChatAccount({
			cfg,
			accountId: id
		})).filter((account) => account.enabled && account.credentialSource !== "none" && account.tokenStatus !== "configured_unavailable")).length === 0) return null;
		return { actions: ["send"] };
	},
	supportsAction: ({ action }) => action === "send",
	extractToolSend: ({ args }) => extractToolSend(args, "sendMessage"),
	handleAction: async (ctx) => {
		const { googlechatMessageActions } = await import("./actions-C17zIeVm.js");
		if (!googlechatMessageActions.handleAction) throw new Error("Google Chat actions are not available.");
		return await googlechatMessageActions.handleAction(ctx);
	}
};
const googlechatPlugin = createChatChannelPlugin({
	base: {
		...createGoogleChatPluginBase({ configSchema: buildChannelConfigSchema(GoogleChatConfigSchema) }),
		approvalCapability: googleChatApprovalCapability,
		secrets: {
			secretTargetRegistryEntries,
			collectRuntimeConfigAssignments
		},
		groups: googlechatGroupsAdapter,
		messaging: {
			targetPrefixes: [
				"googlechat",
				"google-chat",
				"gchat"
			],
			targetIdComparison: "case-sensitive",
			normalizeTarget: normalizeGoogleChatTarget,
			resolveOutboundSessionRoute: (params) => resolveGoogleChatOutboundSessionRoute(params),
			targetResolver: {
				looksLikeId: (raw, normalized) => {
					const value = normalized ?? raw.trim();
					return isGoogleChatSpaceTarget(value) || isGoogleChatUserTarget(value);
				},
				hint: "<spaces/{space}|users/{user}>"
			}
		},
		directory: googlechatDirectoryAdapter,
		message: googlechatMessageAdapter,
		resolver: { resolveTargets: async ({ inputs, kind }) => {
			return inputs.map((input) => {
				const normalized = normalizeGoogleChatTarget(input);
				if (!normalized) return {
					input,
					resolved: false,
					note: "empty target"
				};
				if (kind === "user" && isGoogleChatUserTarget(normalized)) return {
					input,
					resolved: true,
					id: normalized
				};
				if (kind === "group" && isGoogleChatSpaceTarget(normalized)) return {
					input,
					resolved: true,
					id: normalized
				};
				return {
					input,
					resolved: false,
					note: "use spaces/{space} or users/{user}"
				};
			});
		} },
		actions: googlechatActions,
		doctor: {
			dmAllowFromMode: "nestedOnly",
			groupModel: "route",
			groupAllowFromFallbackToAllowFrom: false,
			warnOnEmptyGroupSenderAllowlist: false,
			legacyConfigRules,
			normalizeCompatibilityConfig,
			collectMutableAllowlistWarnings: collectGoogleChatMutableAllowlistWarnings
		},
		status: createComputedAccountStatusAdapter({
			defaultRuntime: createDefaultChannelRuntimeState(DEFAULT_ACCOUNT_ID),
			collectStatusIssues: (accounts) => accounts.flatMap((entry) => {
				const accountId = entry.accountId ?? "default";
				const enabled = entry.enabled !== false;
				const configured = entry.configured === true;
				if (!enabled || !configured) return [];
				const issues = [];
				if (!entry.audience) issues.push({
					channel: GOOGLECHAT_CHANNEL_ID,
					accountId,
					kind: "config",
					message: "Google Chat audience is missing (set channels.googlechat.audience).",
					fix: "Set channels.googlechat.audienceType and channels.googlechat.audience."
				});
				if (!entry.audienceType) issues.push({
					channel: GOOGLECHAT_CHANNEL_ID,
					accountId,
					kind: "config",
					message: "Google Chat audienceType is missing (app-url or project-number).",
					fix: "Set channels.googlechat.audienceType and channels.googlechat.audience."
				});
				return issues;
			}),
			buildChannelSummary: ({ snapshot }) => buildPassiveProbedChannelStatusSummary(snapshot, {
				credentialSource: snapshot.credentialSource ?? "none",
				audienceType: snapshot.audienceType ?? null,
				audience: snapshot.audience ?? null,
				webhookPath: snapshot.webhookPath ?? null,
				webhookUrl: snapshot.webhookUrl ?? null
			}),
			probeAccount: async ({ account }) => (await loadGoogleChatChannelRuntime()).probeGoogleChat(account),
			resolveAccountSnapshot: ({ account }) => ({
				accountId: account.accountId,
				name: account.name,
				enabled: account.enabled,
				configured: account.credentialSource !== "none",
				extra: {
					credentialSource: account.credentialSource,
					tokenStatus: account.tokenStatus,
					audienceType: account.config.audienceType,
					audience: account.config.audience,
					webhookPath: account.config.webhookPath,
					webhookUrl: account.config.webhookUrl,
					dmPolicy: account.config.dm?.policy ?? "pairing"
				}
			})
		}),
		gateway: { startAccount: startGoogleChatGatewayAccount }
	},
	pairing: { text: googlechatPairingTextAdapter },
	security: googlechatSecurityAdapter,
	threading: googlechatThreadingAdapter,
	outbound: {
		...googlechatOutboundAdapter,
		base: {
			...googlechatOutboundAdapter.base,
			shouldSuppressLocalPayloadPrompt: ({ cfg, accountId, payload, hint }) => shouldSuppressLocalGoogleChatExecApprovalPrompt({
				cfg,
				accountId,
				payload,
				hint
			})
		}
	}
});
//#endregion
export { googlechatPlugin as t };
