UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

6,539 lines • 211 kB
import { c as normalizeOptionalLowercaseString, h as readNonEmptyStringPreservingWhitespace, l as normalizeOptionalString, m as readNonBlankString } from "../string-coerce-CCIiB4H7.mjs";
import { a as addTimerTimeoutGraceMs, d as asPositiveFiniteNumber, m as asSafeIntegerInRange } from "../number-coercion-D6u-4YD8.mjs";
import { a as asOptionalRecord, o as asRecord } from "../record-coerce-CVPuDqcc.mjs";
import { n as coerceErrorMessage } from "../error-coercion-hDrHOSGy.mjs";
import { b as uniqueStrings } from "../string-normalization-DLmfYZXI.mjs";
import { r as truncateUtf16Safe } from "../utf16-slice-CuDyEXgS.mjs";
import "../utils-C8YECn2Q.mjs";
import { s as raceWithTimeout } from "../src-BPmQBLJp.mjs";
import { t as sleep } from "../sleep-CkI3nkiJ.mjs";
import { t as formatErrorMessage } from "../errors-BKzCeTYb.mjs";
import { a as throwIfSettledRejected } from "../error-graph-internal-DdjdM90N.mjs";
import { t as createDeferredCore } from "../deferred-D0La5CRk.mjs";
import { n as captureCurrentPluginBackgroundRunner } from "../plugin-instance-invocation-Bq_toGDw.mjs";
import { n as normalizeAgentId } from "../agent-id-CQjtp2ft.mjs";
import { j as parseAgentSessionKey } from "../session-key-CqAyZeVk.mjs";
import { _ as resolveDefaultAgentId } from "../agent-scope-config-DmXgFGKP.mjs";
import { Et as _enum, Fn as object, Jn as string, Lt as boolean, Nt as array, Pn as number, Sn as looseObject, sr as unknown } from "../schemas-Cy6abvsu.mjs";
import { t as datetime } from "../iso-DaJ-ni95.mjs";
import { n as sha256Hex } from "../node-crypto-B6yuTjmm.mjs";
import { n as truncateUtf8Suffix } from "../utf8-truncate-BH7Ecfuh.mjs";
import { t as PluginStateStoreError } from "../plugin-state-error-C70ryyL-.mjs";
import { r as createLazyRuntimeModule } from "../lazy-runtime-zGjszCtt.mjs";
import { t as canonicalizeBase64 } from "../base64-CnKpkbff.mjs";
import { n as rememberBoundedKey } from "../dedupe-DxT0h2gR.mjs";
import { t as KeyedAsyncQueue } from "../keyed-async-queue-DewLnYvW.mjs";
import { t as copyOwnedBuffer } from "../owned-buffer-C1_N0F1K.mjs";
import { t as ErrorCodes } from "../gateway-error-details-B69XiHdh.mjs";
import { p as errorShape } from "../error-codes-BzF7aRQ0.mjs";
import { n as jsonResult } from "../tool-results-CcV0sxnb.mjs";
import { c as readNonNegativeIntegerParam, u as readPositiveIntegerParam } from "../common-njQNtpnW.mjs";
import { n as monotonicNow } from "../monotonic-time-Cc4T2fkU.mjs";
import "../plugin-state-store.types-BLIt6F-q.mjs";
import { n as callGatewayFromCli } from "../gateway-rpc-CxUN2f1a.mjs";
import { r as onDecodedOutput } from "../decoded-output-hLdmeeCp.mjs";
import { m as REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ, p as REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ } from "../agent-run-control-shared-BSSIeKkd.mjs";
import { i as mulawToPcm, n as convertPcmToMulaw8k, s as resamplePcm } from "../output-activity-tracker-B0aXImJ4.mjs";
import { m as resolveRealtimeVoiceAgentConsultToolsAllow, n as REALTIME_VOICE_AGENT_CONSULT_TOOL_NAME, p as resolveRealtimeVoiceAgentConsultTools, s as buildRealtimeVoiceAgentConsultWorkingResponse } from "../agent-consult-tool-DTRzLYLc.mjs";
import { i as readPcm16AudioStats, n as createSpeechThresholdGate, r as isRealtimeVoiceAudioAudible } from "../audio-energy-EzCntkPJ.mjs";
import { t as resolveTranscriptsConfig } from "../config-htoIOq74.mjs";
import { n as getRealtimeTranscriptionProvider, r as listRealtimeTranscriptionProviders } from "../provider-registry-KpxCAUuA.mjs";
import { S as consultRealtimeVoiceAgent, f as resolveConfiguredRealtimeVoiceProviderAsync, t as createRealtimeVoiceSessionHarness, w as resolveRealtimeVoiceBargeIn } from "../realtime-session-harness-DxmMQ7E9.mjs";
import { a as createMeetingStatusCallSource, i as createMeetingStatusPreludeSource, n as createMeetingPageScripts } from "../page-script-source-DGycjasY.mjs";
import { a as resolveMeetingAudioRuntimeForFormat, i as ensureMeetingAudioBackend, n as resolveMeetingChromeConfig, o as buildMeetingSoxAudioCommands, r as resolveMeetingRealtimeConfig, t as buildMeetingConfigAudioCommands } from "../meeting-config-JSurllHg.mjs";
import { t as MeetingSessionTranscriptStore } from "../session-transcript-store-9XVAazwO.mjs";
import { t as registerMeetingPluginCli } from "../plugin-cli-CT2YsMbz.mjs";
import { randomUUID } from "node:crypto";
import { spawn, spawnSync } from "node:child_process";
import { Type } from "typebox";
import { Readable } from "node:stream";
//#region src/meeting-bot/realtime-audio-format.ts
function resolveMeetingRealtimeAudioFormat(e) {
	return e === "g711-ulaw-8khz" ? REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ : REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ;
}
function convertMeetingBridgeAudioForStt(e, t) {
	if (t === "g711-ulaw-8khz") return e;
	return convertPcmToMulaw8k(e, 24e3);
}
function convertMeetingTtsAudioForBridge(e, t, n, r, i = "meeting platform") {
	const a = sourceTelephonyTtsFormat(r, i);
	if (n === "g711-ulaw-8khz" && a === "mulaw" && t === 8e3) return e;
	const o = decodeMeetingTelephonyTtsAudio(e, a);
	return n === "g711-ulaw-8khz" ? convertPcmToMulaw8k(o, t) : resamplePcm(o, t, 24e3);
}
function sourceTelephonyTtsFormat(e, t) {
	const n = e?.trim().toLowerCase().replaceAll("_", "-") ?? "";
	if (!n || n === "pcm" || n.startsWith("pcm-") || n.includes("pcm16") || n.includes("16bit-mono-pcm")) return "pcm";
	if (n.includes("mu-law") || n.includes("mulaw") || n.includes("ulaw")) return "mulaw";
	if (n.includes("a-law") || n.includes("alaw")) return "alaw";
	throw new Error(`Unsupported telephony TTS output format for ${t}: ${e}`);
}
function decodeMeetingTelephonyTtsAudio(e, t) {
	switch (t) {
		case "pcm": return e;
		case "mulaw": return mulawToPcm(e);
		case "alaw": return alawToPcm(e);
	}
	throw new Error("Unsupported telephony TTS output format for meeting platform");
}
function alawToPcm(e) {
	const t = Buffer.alloc(e.length * 2);
	for (let n = 0; n < e.length; n += 1) t.writeInt16LE(alawByteToLinear(e[n] ?? 0), n * 2);
	return t;
}
function alawByteToLinear(e) {
	const t = e ^ 85;
	const n = t & 128;
	const r = (t & 112) >> 4;
	const i = t & 15;
	const a = r === 0 ? (i << 4) + 8 : (i << 4) + 264 << r - 1;
	return n ? a : -a;
}
//#endregion
//#region src/meeting-bot/realtime-engine-support.ts
const MEETING_AGENT_TRANSCRIPT_DEBOUNCE_MS = 900;
const MEETING_OUTPUT_ECHO_SUPPRESSION_TAIL_MS = 3e3;
const MEETING_TRANSCRIPT_ECHO_LOOKBACK_MS = 45e3;
function createMeetingRealtimeHarness(e, t) {
	const n = createRealtimeVoiceSessionHarness({
		talk: t.talk,
		talkPayloads: t.talkPayloads,
		echoSuppression: e.transport.inputAudioIsolated ? void 0 : {
			bytesPerMs: meetingOutputBytesPerMs(e.config.chrome.audioFormat),
			tailMs: MEETING_OUTPUT_ECHO_SUPPRESSION_TAIL_MS,
			transcriptLookbackMs: MEETING_TRANSCRIPT_ECHO_LOOKBACK_MS
		},
		talkback: {
			debounceMs: MEETING_AGENT_TRANSCRIPT_DEBOUNCE_MS,
			logger: e.logger,
			logPrefix: t.logPrefix,
			responseStyle: "Brief, natural spoken answer for a live meeting.",
			fallbackText: "I hit an error while checking that. Please try again.",
			consult: ({ question: t, responseStyle: r, signal: i }) => e.consultAgent({
				meetingSessionId: e.meetingSessionId,
				requesterSessionKey: e.requesterSessionKey,
				args: {
					question: t,
					responseStyle: r
				},
				transcript: n.transcript,
				abortSignal: i
			}),
			deliver: t.deliver
		}
	});
	return n;
}
function meetingOutputBytesPerMs(e) {
	return e === "g711-ulaw-8khz" ? 8 : 48;
}
async function resolveMeetingRealtimeProvider(e) {
	const t = e.config.realtime.voiceProvider ?? e.config.realtime.provider;
	return resolveConfiguredRealtimeVoiceProviderAsync({
		configuredProviderId: t,
		providerConfigs: e.config.realtime.providers,
		cfg: e.fullConfig,
		agentId: e.config.realtime.agentId,
		surface: "gateway-relay",
		useProviderDefaultModel: true,
		providers: e.providers,
		defaultModel: e.config.realtime.model,
		noRegisteredProviderMessage: "No configured realtime voice provider registered"
	});
}
async function resolveMeetingRealtimeTranscriptionProvider(e) {
	const t = e.providers ?? listRealtimeTranscriptionProviders(e.fullConfig);
	if (t.length === 0) throw new Error("No configured realtime transcription provider registered");
	const n = e.config.realtime.transcriptionProvider ?? e.config.realtime.provider;
	const r = n ? e.providers?.find((e) => e.id === n || e.aliases?.includes(n)) ?? getRealtimeTranscriptionProvider(n, e.fullConfig) : void 0;
	const i = r ?? t[0];
	if (!i) throw new Error("No configured realtime transcription provider registered");
	const a = n ? e.config.realtime.providers[n] ?? e.config.realtime.providers[i.id] ?? {} : e.config.realtime.providers[i.id] ?? {};
	const o = i.resolveConfig ? i.resolveConfig({
		cfg: e.fullConfig,
		rawConfig: a
	}) : a;
	if (!(i.isConfiguredAsync ? await i.isConfiguredAsync({
		cfg: e.fullConfig,
		providerConfig: o,
		selectedExplicitly: r !== void 0
	}) : i.isConfigured?.({
		cfg: e.fullConfig,
		providerConfig: o
	}) ?? false)) throw new Error(`Realtime transcription provider "${i.id}" is not configured`);
	return {
		provider: i,
		providerConfig: o
	};
}
function buildMeetingSpeakExactUserMessage(e) {
	return ["Speak this exact OpenClaw answer to the meeting, without adding, removing, or rephrasing words.", `Answer: ${JSON.stringify(e)}`].join("\n");
}
function formatLogValue(e) {
	return (e ? truncateUtf16Safe(e.replace(/\s+/g, "_"), 180) : void 0) || "unknown";
}
function resolveProviderModelForLog(e) {
	return normalizeOptionalString(e.providerConfig.model) ?? normalizeOptionalString(e.providerConfig.modelId) ?? normalizeOptionalString(e.fallbackModel) ?? normalizeOptionalString(e.provider.defaultModel) ?? "provider-default";
}
function formatMeetingRealtimeVoiceModelLog(e) {
	return [
		`${e.logScope} realtime voice bridge starting: strategy=${formatLogValue(e.strategy)}`,
		`provider=${formatLogValue(e.provider.id)}`,
		`model=${formatLogValue(resolveProviderModelForLog(e))}`,
		`audioFormat=${formatLogValue(e.audioFormat)}`
	].join(" ");
}
function formatMeetingAgentAudioModelLog(e) {
	return [
		`${e.logScope} agent audio bridge starting: transcriptionProvider=${formatLogValue(e.provider.id)}`,
		`transcriptionModel=${formatLogValue(resolveProviderModelForLog(e))}`,
		"tts=telephony",
		`audioFormat=${formatLogValue(e.audioFormat)}`
	].join(" ");
}
function normalizeMeetingTtsPromptText(e) {
	const t = e?.trim();
	if (!t) return;
	const n = t.match(/^say exactly:\s*(?<text>.+)$/is)?.groups?.text?.trim();
	if (n) return n.replace(/^["']|["']$/g, "").trim() || t;
	return t;
}
//#endregion
//#region src/meeting-bot/realtime-output-owner.ts
const STALE_RESPONSE_LIMIT = 16;
const AUDIO_DELTA_EVENTS = /* @__PURE__ */ new Set([
	"conversation.output_audio.delta",
	"response.audio.delta",
	"response.output_audio.delta"
]);
const OUTPUT_MAX_PENDING_MS = 12e4;
const OUTPUT_MAX_PENDING_FRAMES = 6e3;
const OUTPUT_MAX_WRITE_MS = 500;
const OUTPUT_STALL_MS = 5e3;
const OUTPUT_STALL_PENDING_MS = 2e3;
/** Serializes native playback writes and fences queued audio across interruption. */
function createMeetingRealtimeOutputQueue(e) {
	let t = false;
	let n = 0;
	let r = "idle";
	let i = 0;
	let a;
	let o = 0;
	let s = false;
	let c = 0;
	let l = 0;
	let u = 0;
	let d = 0;
	let f = 0;
	let p = 0;
	let m;
	let h = Promise.resolve();
	const g = [];
	const _ = e.bytesPerMs * OUTPUT_MAX_PENDING_MS;
	const v = e.bytesPerMs * OUTPUT_STALL_PENDING_MS;
	const y = e.bytesPerMs * OUTPUT_MAX_WRITE_MS;
	const isStalled = (e = 0) => r === "writing" && Date.now() - i >= OUTPUT_STALL_MS && c + e > v;
	const reset = () => {
		clearTimeout(a);
		a = void 0;
		n += 1;
		g.length = 0;
		c = 0;
		l = 0;
		u = 0;
		d = 0;
		f = 0;
	};
	const clear = () => {
		if (t) return;
		p += 1;
		m = (/* @__PURE__ */ new Date()).toISOString();
		o += 1;
		h = h.then(async () => {
			if (!t) await e.transport.clearOutput();
		}).catch((t) => e.onFailure("audio output clear", t)).finally(() => {
			o -= 1;
			pump();
		});
	};
	const pump = () => {
		if (t || r !== "idle" || o > 0) return;
		const p = g.shift();
		if (!p) return;
		const m = [p];
		let h = p.audio.byteLength;
		let _ = 1;
		let v = Number(p.audible);
		while (h < y) {
			const e = g[0];
			if (!e || e.beginsOutput || e.audio.byteLength > y - h) break;
			g.shift();
			m.push(e);
			h += e.audio.byteLength;
			_ += 1;
			v += Number(e.audible);
		}
		const b = m.length === 1 ? p.audio : Buffer.concat(m.map((e) => e.audio), h);
		r = "scheduled";
		Promise.resolve().then(async () => {
			if (t || p.generation !== n) return;
			if (p.beginsOutput) e.transport.beginOutput?.();
			r = "writing";
			i = Date.now();
			a = setTimeout(() => {
				if (isStalled()) e.onStall();
			}, OUTPUT_STALL_MS);
			await e.transport.writeOutput(b);
			if (!t && p.generation === n) {
				d = Math.max(Date.now(), d);
				for (const t of m) {
					d += t.audio.byteLength / e.bytesPerMs;
					if (t.audible) f = d;
				}
			}
		}).catch((r) => {
			if (!t && p.generation === n) e.onFailure("audio output", r);
		}).finally(() => {
			clearTimeout(a);
			a = void 0;
			r = "idle";
			if (p.generation === n) {
				c -= h;
				l -= _;
				u -= v;
			}
			if (s && !t) {
				s = false;
				clear();
				return;
			}
			pump();
		});
	};
	return {
		enqueue(e, r, i) {
			if (t || isStalled(e.byteLength) || e.byteLength > _ - c || l >= OUTPUT_MAX_PENDING_FRAMES) return false;
			c += e.byteLength;
			l += 1;
			u += Number(r);
			g.push({
				audio: e,
				audible: r,
				beginsOutput: i,
				generation: n
			});
			pump();
			return true;
		},
		invalidate() {
			s ||= r === "writing";
			reset();
		},
		clear,
		stop() {
			t = true;
			s = false;
			reset();
		},
		pending: () => ({
			pendingBytes: c,
			pendingFrames: l
		}),
		hasUnplayedAudibleAudio: () => u > 0 || Date.now() < f,
		getHealth: () => ({
			clearCount: p,
			lastClearAt: m
		})
	};
}
function createMeetingRealtimeOutputOwner() {
	let e;
	let t;
	let n;
	let r;
	const i = /* @__PURE__ */ new Set();
	const rememberStale = (e) => {
		i.delete(e);
		rememberBoundedKey(i, e, STALE_RESPONSE_LIMIT);
	};
	return {
		accept(e) {
			if (e && i.has(e)) return false;
			if (r) {
				if (!r.responseId || !e || e === r.responseId) return false;
				r = void 0;
			}
			if (e) n = e;
			return true;
		},
		block() {
			if (r) return {
				blocked: false,
				token: r.token
			};
			const i = Symbol("meeting-realtime-output-blocked");
			const a = n ?? t;
			r = {
				...a ? { responseId: a } : {},
				token: i
			};
			if (a) rememberStale(a);
			e = void 0;
			return {
				blocked: true,
				token: i
			};
		},
		clearBlocked() {
			if (!r) return false;
			r = void 0;
			return true;
		},
		isBlockedBy(e) {
			return r?.token === e;
		},
		noteEvent(n) {
			if (n.direction === "server" && n.type === "response.created" && n.responseId) {
				t = n.responseId;
				e = void 0;
				return;
			}
			e = n.direction === "server" && AUDIO_DELTA_EVENTS.has(n.type) ? n.responseId ?? t : void 0;
		},
		providerClear() {
			if (r) {
				if (!r.responseId) r = void 0;
				return false;
			}
			const i = n ?? t;
			if (i) {
				r = {
					responseId: i,
					token: Symbol("meeting-realtime-output-blocked")
				};
				rememberStale(i);
			}
			e = void 0;
			return true;
		},
		reset() {
			e = void 0;
			t = void 0;
			n = void 0;
			r = void 0;
			i.clear();
		},
		takeNextResponseId() {
			const n = e ?? t;
			e = void 0;
			return n;
		},
		terminal(e) {
			if (!e || !r?.responseId || r.responseId === e) r = void 0;
			if (!e || t === e) t = void 0;
			if (e && n && n !== e) return false;
			n = void 0;
			return true;
		}
	};
}
//#endregion
//#region src/meeting-bot/realtime-tool-continuity.ts
const meetingRealtimeToolAbortSignals = /* @__PURE__ */ new WeakMap();
function readMeetingRealtimeToolAbortSignal(e) {
	return meetingRealtimeToolAbortSignals.get(e);
}
function createMeetingRealtimeToolContinuity(e) {
	const t = /* @__PURE__ */ new Set();
	const reset = (e) => {
		for (const n of t) n.abort(e);
		t.clear();
	};
	const runConsult = async (e, n) => {
		const r = new AbortController();
		t.add(r);
		const i = e.signal ? AbortSignal.any([r.signal, e.signal]) : r.signal;
		try {
			i.throwIfAborted();
			const t = await n({
				...e,
				signal: i
			});
			i.throwIfAborted();
			return t;
		} finally {
			t.delete(r);
		}
	};
	const run = (n) => {
		const r = new AbortController();
		t.add(r);
		const isActive = () => !r.signal.aborted;
		const i = n.harness.ensureTurn();
		n.harness.emit({
			type: "tool.call",
			turnId: i,
			itemId: n.call.event.itemId,
			callId: n.call.event.callId,
			payload: {
				name: n.call.event.name,
				args: n.call.event.args
			}
		});
		const a = Object.create(n.session);
		meetingRealtimeToolAbortSignals.set(a, r.signal);
		a.submitToolResult = (e, t, r) => {
			if (!isActive()) return;
			return n.session.submitToolResult(e, t, r);
		};
		return e({
			...n.call,
			session: a,
			onTalkEvent: (e) => {
				if (isActive()) n.harness.emit({
					...e,
					turnId: e.turnId ?? i
				});
			}
		}).catch((e) => {
			if (isActive()) throw e;
		}).finally(() => {
			meetingRealtimeToolAbortSignals.delete(a);
			t.delete(r);
		});
	};
	return {
		reset,
		run,
		runConsult
	};
}
//#endregion
//#region src/meeting-bot/realtime-engine.ts
async function startMeetingRealtimeEngine(e) {
	let t = false;
	let n;
	let r = false;
	let i = false;
	let a = false;
	let o;
	let s = false;
	let c = false;
	let l = false;
	const u = createMeetingRealtimeOutputOwner();
	const d = createMeetingRealtimeToolContinuity(e.handleToolCall);
	const f = e.logPrefix ? `${e.logPrefix} realtime` : "realtime";
	const p = resolveMeetingRealtimeAudioFormat(e.config.chrome.audioFormat);
	const m = createMeetingRealtimeOutputQueue({
		transport: e.transport,
		bytesPerMs: meetingOutputBytesPerMs(e.config.chrome.audioFormat),
		onFailure: (t, n) => {
			e.logger.warn(`${e.platform.logScope} ${f} ${t} failed: ${formatErrorMessage(n)}`);
			stopAfterFailure(t);
		},
		onStall: () => handleOutputBackpressure()
	});
	const stop = async () => {
		if (!t) {
			t = true;
			u.reset();
			m.stop();
			c = false;
			d.reset("meeting realtime stopped");
			y.talkback?.close();
			y.forcedConsults.clear();
		}
		if (n) {
			await n;
			return;
		}
		const s = Promise.resolve().then(async () => {
			if (!r) try {
				await o?.close();
			} catch (t) {
				e.logger.debug?.(`${e.platform.logScope} ${f}${e.logPrefix ? "" : " voice"} bridge close ignored: ${formatErrorMessage(t)}`);
			} finally {
				r = true;
				y.close();
			}
			let t;
			if (!i) try {
				await e.transport.stop();
				i = true;
			} catch (e) {
				t = e;
			}
			if (!a) try {
				await e.transport.dispose();
				a = true;
			} catch (e) {
				t ??= e;
			}
			if (t) throw t instanceof Error ? t : new Error("Meeting realtime transport cleanup failed", { cause: t });
		});
		n = s;
		try {
			await s;
		} finally {
			if (n === s) n = void 0;
		}
	};
	const stopAfterFailure = (t) => {
		stop().catch((n) => {
			e.logger.warn(`${e.platform.logScope} ${f} ${t} cleanup failed: ${formatErrorMessage(n)}`);
		});
	};
	const invalidateOutputPlayback = () => {
		m.invalidate();
		c = false;
	};
	const invalidateAndClearOutputPlayback = () => {
		blockOutput();
		m.clear();
	};
	const blockOutput = () => {
		const e = u.block();
		invalidateOutputPlayback();
		return e;
	};
	const handleOutputBackpressure = () => {
		const { pendingBytes: n, pendingFrames: r } = m.pending();
		const i = o?.bridge.outputAudioMode === "continuous" ? void 0 : blockOutput();
		if (i && !i.blocked) return;
		e.logger.warn(`${e.platform.logScope} ${f} audio output backpressured: pendingBytes=${n} pendingFrames=${r}`);
		if (!i) invalidateOutputPlayback();
		y.flushOutput(m.clear);
		y.finishOutputAudio("output-backpressure");
		if (!i) return;
		queueMicrotask(() => {
			if (t || !u.isBlockedBy(i.token)) return;
			y.handleBargeIn({
				audioPlaybackActive: true,
				force: true
			}, () => {});
		});
	};
	const startHumanBargeInMonitor = () => {
		if (!e.transport.startBargeInMonitor || !resolveRealtimeVoiceBargeIn({
			configuredBargeIn: void 0,
			interruptResponseOnInputAudio: void 0,
			capabilities: h.capabilities,
			outputAudioMode: o?.bridge.outputAudioMode
		})) return;
		e.transport.startBargeInMonitor(() => {
			if (t || !y.outputActivity.isInterruptible()) return false;
			const e = Date.now();
			const n = y.isOutputPlaybackWindowActive();
			const r = y.outputActivity.snapshot().lastAudioAt;
			if (!n && (r === void 0 || e - r > 1e3)) return false;
			y.handleBargeIn({ audioPlaybackActive: true }, invalidateAndClearOutputPlayback);
			return true;
		});
	};
	const h = await resolveMeetingRealtimeProvider({
		config: e.config,
		fullConfig: e.fullConfig,
		providers: e.providers
	});
	const g = e.config.realtime.strategy;
	e.logger.info(formatMeetingRealtimeVoiceModelLog({
		logScope: e.platform.logScope,
		strategy: g,
		provider: h.provider,
		providerConfig: h.providerConfig,
		fallbackModel: e.config.realtime.model,
		audioFormat: e.config.chrome.audioFormat
	}));
	const _ = e.talkContext ? {
		bridgeId: e.talkContext.bridgeId,
		meetingSessionId: e.meetingSessionId
	} : { meetingSessionId: e.meetingSessionId };
	const v = e.talkContext ? { bridgeId: e.talkContext.bridgeId } : { meetingSessionId: e.meetingSessionId };
	const reasonTalkPayload = (t) => e.talkContext ? {
		bridgeId: e.talkContext.bridgeId,
		reason: t
	} : { reason: t };
	const y = createMeetingRealtimeHarness(e, {
		talk: {
			sessionId: e.talkSessionId ?? `${e.platform.sessionIdPrefix}:${e.meetingSessionId}:command-realtime`,
			mode: "realtime",
			transport: "gateway-relay",
			brain: g === "bidi" && !h.capabilities?.handlesAgentConsult ? "direct-tools" : "agent-consult",
			provider: h.provider.id
		},
		talkPayloads: {
			turnStarted: () => _,
			turnEnded: reasonTalkPayload,
			inputAudioDelta: (e) => ({ byteLength: e.byteLength }),
			outputAudioStarted: () => v,
			outputAudioDelta: (e) => ({ byteLength: e.byteLength }),
			outputAudioDone: reasonTalkPayload
		},
		logPrefix: `${e.platform.logScope} ${f} agent`,
		deliver: (e) => {
			o?.sendUserMessage(buildMeetingSpeakExactUserMessage(e));
		}
	});
	y.emit({
		type: "session.started",
		payload: e.talkContext ? {
			..._,
			nodeId: e.talkContext.nodeId
		} : _
	});
	e.transport.onFatal(() => {
		stopAfterFailure("audio transport");
	});
	if (t) throw new Error(`${e.platform.displayName} audio transport failed before realtime provider setup`);
	try {
		const requireIsolatedInput = () => {
			if (!e.transport.inputAudioIsolated) throw new Error(`${e.platform.displayName} native live voice requires isolated meeting audio input. Remove chrome.audioInputCommand to use managed browser capture, which must be available before connecting.`);
		};
		if (h.capabilities?.handlesInputAudioBargeIn === true && h.capabilities.supportsBargeIn === false) requireIsolatedInput();
		o = y.createBridge({
			provider: h.provider,
			capabilities: h.capabilities,
			cfg: e.fullConfig,
			agentId: e.config.realtime.agentId,
			providerConfig: h.providerConfig,
			audioFormat: p,
			instructions: e.config.realtime.instructions,
			initialGreetingInstructions: e.config.realtime.introMessage,
			autoRespondToAudio: g === "bidi",
			triggerGreetingOnReady: false,
			markStrategy: "ack-immediately",
			tools: g === "bidi" && !h.capabilities?.handlesAgentConsult ? e.tools : [],
			...h.capabilities?.handlesAgentConsult ? { runAgentConsult: (n) => {
				if (t) throw new Error("Meeting realtime session is closed");
				return d.runConsult(n, ({ prompt: t, signal: n }) => {
					if (e.config.realtime.toolPolicy === "none") throw new Error("Agent delegation is disabled by the meeting tool policy");
					return e.consultAgent({
						meetingSessionId: e.meetingSessionId,
						requesterSessionKey: e.requesterSessionKey,
						args: { question: t },
						transcript: y.transcript,
						abortSignal: n
					});
				});
			} } : {},
			audioSink: {
				isOpen: () => !t,
				sendAudio: (e) => {
					const n = u.takeNextResponseId();
					const r = o?.bridge.outputAudioMode === "continuous";
					const i = !r || isRealtimeVoiceAudioAudible(e, p);
					if (!i && !m.hasUnplayedAudibleAudio()) {
						if (c) {
							c = false;
							y.finishOutputAudio("silence");
						}
						return;
					}
					if (t || !r && !u.accept(n)) return;
					if (!m.enqueue(e, i, !c)) {
						handleOutputBackpressure();
						return;
					}
					c = true;
					y.outputActivity.markPlaybackStarted();
					y.recordOutputAudio(e);
				},
				clearAudio: () => {
					const e = o?.bridge.outputAudioMode === "continuous";
					if (!e && !u.providerClear()) return;
					if (e) u.reset();
					invalidateOutputPlayback();
					y.flushOutput(m.clear);
					y.finishOutputAudio("clear");
				}
			},
			onTranscript: (e, n, r) => {
				const i = y.ensureTurn();
				const a = e === "assistant" ? r ? "output.text.done" : "output.text.delta" : r ? "transcript.done" : "transcript.delta";
				const o = e === "assistant" ? { text: n } : {
					role: e,
					text: n
				};
				y.emit({
					type: a,
					turnId: i,
					payload: o,
					final: r
				});
				if (e === "user" && r) y.emit({
					type: "input.audio.committed",
					turnId: i,
					payload: v,
					final: true
				});
				if (!r) return;
				if (e !== "user" || g !== "agent") return;
				if (y.isLikelyAssistantEchoTranscript(n)) return;
				if (!t) y.talkback?.enqueue(n);
			},
			onEvent: (t) => {
				if (t.direction === "server" && t.type === "session.created") l = false;
				if (t.direction === "client" && t.type === "session.continuity.reset") {
					if (l) return;
					l = true;
					s = false;
					u.reset();
					c = false;
					d.reset(t.type);
					const e = y.talk.activeTurnId;
					invalidateOutputPlayback();
					y.flushOutput(m.clear);
					y.finishOutputAudio(t.type);
					if (e) y.talk.cancelTurn({
						turnId: e,
						payload: {
							...v,
							reason: t.type
						}
					});
					return;
				}
				u.noteEvent(t);
				if (t.type === "input_audio_buffer.speech_started") y.ensureTurn();
				else if (t.type === "input_audio_buffer.speech_stopped") {
					const e = y.talk.activeTurnId;
					if (!e) return;
					y.emit({
						type: "input.audio.committed",
						turnId: e,
						payload: {
							...v,
							source: t.type
						},
						final: true
					});
				} else if (t.type === "error" && t.detail === "Cancellation failed: no active response found") {
					if (u.clearBlocked()) {
						c = false;
						y.finishOutputAudio(t.type);
					}
				} else if (t.type === "error") y.emit({
					type: "session.error",
					payload: { message: t.detail ?? "Realtime provider error" },
					final: true
				});
				if (t.type === "error" || t.type === "conversation.item.input_audio_transcription.failed") {
					const n = t.detail ? ` ${t.detail}` : "";
					e.logger.info(`${e.platform.logScope} ${f} ${t.direction}:${t.type}${n}`);
				}
			},
			onResponseDone: (t) => {
				if (!u.terminal(t.responseId)) return;
				c = false;
				if (t.status === "failed" || t.status === "incomplete") e.logger.warn(`${e.platform.logScope} ${f} response ${t.status}: ${t.message}`);
			},
			onToolCall: (n, r) => {
				if (t) return Promise.resolve();
				return d.run({
					session: r,
					call: {
						strategy: g,
						event: n,
						meetingSessionId: e.meetingSessionId,
						requesterSessionKey: e.requesterSessionKey,
						transcript: y.transcript
					},
					harness: y
				});
			},
			onError: (t) => {
				y.emit({
					type: "session.error",
					payload: { message: formatErrorMessage(t) },
					final: true
				});
				e.logger.warn(`${e.platform.logScope} ${f} voice bridge failed: ${formatErrorMessage(t)}`);
			},
			onClose: (e) => {
				c = false;
				s = false;
				y.finishOutputAudio(e);
				y.emit({
					type: "session.closed",
					payload: { reason: e },
					final: true
				});
				stopAfterFailure("voice bridge close");
			},
			onReady: () => {
				s = true;
				l = false;
				y.emit({
					type: "session.ready",
					payload: v
				});
			}
		});
		if (o.bridge.outputAudioMode === "continuous") requireIsolatedInput();
		startHumanBargeInMonitor();
		e.transport.startInput((e) => {
			if (t || e.byteLength === 0) return;
			if (!y.recordInputAudio(e)) return;
			o?.sendAudio(e);
		});
		await o.connect();
		if (t) throw new Error(`${e.platform.displayName} audio transport stopped during realtime provider setup`);
	} catch (t) {
		try {
			await stop();
		} catch (t) {
			e.logger.debug?.(`${e.platform.logScope} ${f} failed-start cleanup ignored: ${formatErrorMessage(t)}`);
			try {
				await stop();
			} catch (t) {
				e.logger.debug?.(`${e.platform.logScope} ${f} failed-start cleanup retry ignored: ${formatErrorMessage(t)}`);
			}
		}
		throw t;
	}
	return {
		providerId: h.provider.id,
		speak: (e) => {
			o?.triggerGreeting(e);
		},
		getHealth: () => ({
			...y.getHealth({
				providerConnected: o?.bridge.isConnected() ?? false,
				realtimeReady: s
			}),
			...o?.bridge.outputAudioMode === "continuous" ? { audioOutputActive: m.hasUnplayedAudibleAudio() } : {},
			...e.transport.getHealth?.(),
			...m.getHealth(),
			bridgeClosed: r
		}),
		stop
	};
}
//#endregion
//#region src/meeting-bot/realtime-agent-engine.ts
async function startMeetingAgentRealtimeEngine(e) {
	let t = false;
	let n;
	let r = null;
	let i = false;
	let a = Promise.resolve();
	const o = e.logPrefix ? `${e.logPrefix} agent` : "agent";
	const s = await resolveMeetingRealtimeTranscriptionProvider({
		config: e.config,
		fullConfig: e.fullConfig,
		providers: e.providers
	});
	e.logger.info(formatMeetingAgentAudioModelLog({
		logScope: e.platform.logScope,
		provider: s.provider,
		providerConfig: s.providerConfig,
		audioFormat: e.config.chrome.audioFormat
	}));
	const stop = async () => {
		if (t) {
			await n;
			return;
		}
		t = true;
		n = (async () => {
			c.close();
			try {
				r?.close();
			} catch (t) {
				e.logger.debug?.(`${e.platform.logScope} ${o} transcription bridge close ignored: ${formatErrorMessage(t)}`);
			}
			c.finishOutputAudio("stopped");
			c.endTurn("stopped");
			c.emit({
				type: "session.closed",
				final: true,
				payload: { meetingSessionId: e.meetingSessionId }
			});
			try {
				await e.transport.stop();
			} finally {
				await e.transport.dispose();
			}
		})();
		await n;
	};
	const stopAfterFailure = (t) => {
		stop().catch((n) => {
			e.logger.warn(`${e.platform.logScope} ${o} ${t} cleanup failed: ${formatErrorMessage(n)}`);
		});
	};
	const writeOutputAudio = async (t) => {
		e.transport.beginOutput?.();
		c.outputActivity.markPlaybackStarted();
		c.recordOutputAudio(t);
		await e.transport.writeOutput(t);
	};
	const enqueueSpeakText = (n) => {
		const r = normalizeMeetingTtsPromptText(n);
		if (!r || t) return;
		a = a.then(async () => {
			if (t) return;
			c.recordTranscript("assistant", r);
			const n = c.ensureTurn();
			c.emit({
				type: "output.text.done",
				turnId: n,
				final: true,
				payload: {
					meetingSessionId: e.meetingSessionId,
					text: r
				}
			});
			const i = await e.runtime.tts.textToSpeechTelephony({
				text: r,
				cfg: e.fullConfig
			});
			if (t) return;
			if (!i.success || !i.audioBuffer || !i.sampleRate) throw new Error(i.error ?? "TTS conversion failed");
			await writeOutputAudio(convertMeetingTtsAudioForBridge(i.audioBuffer, i.sampleRate, e.config.chrome.audioFormat, i.outputFormat, e.platform.displayName));
			if (t) return;
			c.finishOutputAudio("completed");
			c.endTurn();
		}).catch((n) => {
			if (t) return;
			c.finishOutputAudio("failed");
			c.endTurn("failed");
			e.logger.warn(`${e.platform.logScope} ${o} TTS failed: ${formatErrorMessage(n)}`);
		});
	};
	const c = createMeetingRealtimeHarness(e, {
		talk: {
			sessionId: `${e.platform.sessionIdPrefix}:${e.meetingSessionId}:agent`,
			mode: "stt-tts",
			transport: "gateway-relay",
			brain: "agent-consult",
			provider: s.provider.id,
			turnIdPrefix: `${e.platform.sessionIdPrefix}:${e.meetingSessionId}:turn`
		},
		talkPayloads: {
			turnStarted: () => ({ meetingSessionId: e.meetingSessionId }),
			turnEnded: () => ({ meetingSessionId: e.meetingSessionId }),
			inputAudioDelta: (t) => ({
				meetingSessionId: e.meetingSessionId,
				bytes: t.byteLength
			}),
			outputAudioStarted: () => ({ meetingSessionId: e.meetingSessionId }),
			outputAudioDelta: (t) => ({
				meetingSessionId: e.meetingSessionId,
				bytes: t.byteLength
			}),
			outputAudioDone: () => ({ meetingSessionId: e.meetingSessionId })
		},
		logPrefix: `${e.platform.logScope} ${o}`,
		deliver: enqueueSpeakText
	});
	e.transport.onFatal(() => {
		stopAfterFailure("audio transport");
	});
	if (t) throw new Error(`${e.platform.displayName} audio transport failed before transcription provider setup`);
	try {
		r = s.provider.createSession({
			cfg: e.fullConfig,
			providerConfig: s.providerConfig,
			onTranscript: (n) => {
				const r = n.trim();
				if (!r || t) return;
				const i = c.ensureTurn();
				c.emit({
					type: "input.audio.committed",
					turnId: i,
					final: true,
					payload: { meetingSessionId: e.meetingSessionId }
				});
				c.emit({
					type: "transcript.done",
					turnId: i,
					final: true,
					payload: {
						meetingSessionId: e.meetingSessionId,
						text: r,
						role: "user"
					}
				});
				c.recordTranscript("user", r);
				if (c.isLikelyAssistantEchoTranscript(r)) return;
				c.talkback?.enqueue(r);
			},
			onError: (t) => {
				e.logger.warn(`${e.platform.logScope} ${o} transcription bridge failed: ${formatErrorMessage(t)}`);
				c.emit({
					type: "session.error",
					final: true,
					payload: {
						meetingSessionId: e.meetingSessionId,
						error: formatErrorMessage(t)
					}
				});
				stopAfterFailure("transcription bridge");
			}
		});
		c.emit({
			type: "session.started",
			payload: {
				meetingSessionId: e.meetingSessionId,
				provider: s.provider.id
			}
		});
		e.transport.startInput((n) => {
			if (t || !i || n.byteLength === 0) return;
			if (!c.recordInputAudio(n)) return;
			r?.sendAudio(convertMeetingBridgeAudioForStt(n, e.config.chrome.audioFormat));
		});
		await r.connect();
	} catch (t) {
		try {
			await stop();
		} catch (t) {
			e.logger.debug?.(`${e.platform.logScope} ${o} failed-start cleanup ignored: ${formatErrorMessage(t)}`);
		}
		throw t;
	}
	if (t) throw new Error(`${e.platform.displayName} audio transport stopped during transcription provider setup`);
	i = true;
	c.emit({
		type: "session.ready",
		payload: { meetingSessionId: e.meetingSessionId }
	});
	return {
		providerId: s.provider.id,
		speak: enqueueSpeakText,
		getHealth: () => ({
			...c.getHealth({
				providerConnected: r?.isConnected() ?? false,
				realtimeReady: i
			}),
			...e.transport.getHealth?.(),
			bridgeClosed: t
		}),
		stop
	};
}
//#endregion
//#region src/meeting-bot/bridge-process.ts
var MeetingOutputProcessOwner = class {
	#e = /* @__PURE__ */ new Set();
	#t = /* @__PURE__ */ new Set();
	constructor(e) {
		this.graceMs = e;
	}
	write(e, t, n) {
		return new Promise((r, i) => {
			let a = false;
			const finish = (e) => {
				if (a) return;
				a = true;
				this.#e.delete(o);
				if (e) i(e);
				else r();
			};
			const o = {
				process: e,
				release: () => finish()
			};
			this.#e.add(o);
			try {
				t.write(n, (e) => finish(e ?? void 0));
			} catch (e) {
				finish(e instanceof Error ? e : new Error(formatErrorMessage(e)));
				return;
			}
			if (t.destroyed || t.writableEnded) finish(/* @__PURE__ */ new Error("audio output stream is closed"));
		});
	}
	release(e) {
		for (const t of this.#e) if (!e || t.process === e) t.release();
	}
	retire(e, t) {
		const n = terminateMeetingBridgeProcess(e, {
			graceMs: this.graceMs,
			initialSignal: t
		});
		this.#t.add(n);
		n.finally(() => this.#t.delete(n));
	}
	async stop(...e) {
		await Promise.all([...e.map((e) => terminateMeetingBridgeProcess(e, { graceMs: this.graceMs })), ...this.#t]);
	}
};
function hasExited(e) {
	return e.exitCode !== null || e.signalCode !== null;
}
function waitForExit(e, t) {
	if (hasExited(e)) return Promise.resolve(true);
	return new Promise((n) => {
		let r = false;
		const finish = (t) => {
			if (r) return;
			r = true;
			clearTimeout(i);
			e.off("exit", onExit);
			n(t);
		};
		const onExit = () => finish(true);
		const i = setTimeout(() => finish(hasExited(e)), t);
		i.unref?.();
		e.once("exit", onExit);
		if (hasExited(e)) finish(true);
	});
}
/** Settles after the bridge exits or the bounded force-kill sequence finishes. */
async function terminateMeetingBridgeProcess(e, t) {
	if (!e || hasExited(e)) return;
	const n = t.initialSignal ?? "SIGTERM";
	try {
		if (!e.kill(n)) return;
	} catch {
		return;
	}
	if (n === "SIGKILL") {
		await waitForExit(e, 1e3);
		return;
	}
	if (await waitForExit(e, t.graceMs)) return;
	try {
		if (!e.kill("SIGKILL")) return;
	} catch {
		return;
	}
	await waitForExit(e, 1e3);
}
//#endregion
//#region src/meeting-bot/command-argv.ts
function splitCommandArgv(e, t) {
	const [n, ...r] = e;
	if (!n) throw new Error(`${t} must not be empty`);
	return {
		command: n,
		args: r
	};
}
//#endregion
//#region src/meeting-bot/output-loopback-verifier.ts
const OUTPUT_LOOPBACK_OBSERVATION_WINDOW_MS = 5e3;
const OUTPUT_LOOPBACK_REFERENCE_MS = 500;
const OUTPUT_LOOPBACK_INPUT_HISTORY_MS = 1e4;
const OUTPUT_LOOPBACK_FINGERPRINT_POINTS = 64;
const OUTPUT_LOOPBACK_MIN_FINGERPRINT_POINTS = 16;
const OUTPUT_LOOPBACK_FULL_CORRELATION_THRESHOLD = .9;
const OUTPUT_LOOPBACK_SHORT_CORRELATION_THRESHOLD = .98;
const OUTPUT_LOOPBACK_RMS_THRESHOLD = 8;
const OUTPUT_LOOPBACK_PEAK_THRESHOLD = 32;
function decodeMeetingAudio(e, t) {
	return t === "g711-ulaw-8khz" ? mulawToPcm(e) : e;
}
function hasSignal(e) {
	return e.rms >= OUTPUT_LOOPBACK_RMS_THRESHOLD || e.peak >= OUTPUT_LOOPBACK_PEAK_THRESHOLD;
}
function createOutputFingerprint(e, t) {
	const n = Math.floor(e.byteLength * .5);
	let r = 0;
	while (r < n && Math.abs(e.readInt16LE(r * 2)) < OUTPUT_LOOPBACK_PEAK_THRESHOLD) r += 1;
	let i = n - 1;
	while (i >= r && Math.abs(e.readInt16LE(i * 2)) < OUTPUT_LOOPBACK_PEAK_THRESHOLD) i -= 1;
	const a = e.subarray(r * 2, (i + 1) * 2);
	const o = Math.floor(a.byteLength * .5);
	const s = Math.min(OUTPUT_LOOPBACK_FINGERPRINT_POINTS, Math.floor(o * .25));
	if (s < OUTPUT_LOOPBACK_MIN_FINGERPRINT_POINTS) return;
	const c = s ** -1;
	const l = [];
	for (let e = 0; e < s; e += 1) {
		const t = Math.floor(e * o * c);
		const n = Math.max(t + 1, Math.floor((e + 1) * o * c));
		let r = t;
		let i = a.readInt16LE(t * 2);
		for (let e = t + 1; e < n; e += 1) {
			const t = a.readInt16LE(e * 2);
			if (Math.abs(t) > Math.abs(i)) {
				r = e;
				i = t;
			}
		}
		l.push({
			index: r,
			sample: i
		});
	}
	const u = l[0]?.index ?? 0;
	const d = l.map((e) => e.sample);
	const f = d.length ** -1;
	const p = d.reduce((e, t) => e + t, 0) * f;
	const m = d.reduce((e, t) => {
		const n = t - p;
		return e + n * n;
	}, 0);
	if (m === 0) return;
	const h = l.map((e) => e.index - u);
	return {
		offsets: h,
		referenceMean: p,
		referenceVariance: m,
		samples: d,
		spanSamples: (h.at(-1) ?? 0) + 1,
		threshold: a.byteLength < t ? OUTPUT_LOOPBACK_SHORT_CORRELATION_THRESHOLD : OUTPUT_LOOPBACK_FULL_CORRELATION_THRESHOLD
	};
}
function fingerprintCorrelation(e, t, n) {
	let r = 0;
	for (const i of n.offsets) r += e.readInt16LE((t + i) * 2);
	const i = r * n.offsets.length ** -1;
	let a = 0;
	let o = 0;
	for (let r = 0; r < n.offsets.length; r += 1) {
		const s = (n.samples[r] ?? 0) - n.referenceMean;
		const c = e.readInt16LE((t + (n.offsets[r] ?? 0)) * 2) - i;
		a += s * c;
		o += c * c;
	}
	if (o === 0) return 0;
	return Math.abs(a * (n.referenceVariance * o) ** -.5);
}
/** Correlates sink audio with the same waveform returning on the microphone capture path. */
function createMeetingOutputLoopbackVerifier(e) {
	const t = e.audioFormat === "g711-ulaw-8khz" ? 8e3 : 24e3;
	const n = t * OUTPUT_LOOPBACK_REFERENCE_MS * .001 * 2;
	const r = t * OUTPUT_LOOPBACK_INPUT_HISTORY_MS * .001 * 2;
	let i = false;
	let a = false;
	let o = 0;
	let s;
	let c = Buffer.alloc(0);
	let l = 0;
	let u;
	let d = Buffer.alloc(0);
	let f = Number.NEGATIVE_INFINITY;
	let p = Number.NEGATIVE_INFINITY;
	let m = 0;
	let h;
	let g;
	let _;
	let v;
	const clearCorrelationScratch = () => {
		c = Buffer.alloc(0);
		l = 0;
		u = void 0;
		d = Buffer.alloc(0);
	};
	const resetGeneration = (e) => {
		i = e;
		a = false;
		if (e) o += 1;
		clearCorrelationScratch();
		f = Number.NEGATIVE_INFINITY;
		p = Number.NEGATIVE_INFINITY;
	};
	const refreshFingerprint = (e) => {
		u = e;
		const n = Math.floor(c.byteLength * .5);
		const r = t * OUTPUT_LOOPBACK_REFERENCE_MS * .001;
		l = Math.max(0, n - r);
	};
	const consumePendingOutput = () => {
		const e = d.byteLength;
		for (let t = e; t > 0; t -= n) {
			const e = createOutputFingerprint(d.subarray(Math.max(0, t - n), t), n);
			if (e) {
				d = Buffer.alloc(0);
				refreshFingerprint(e);
				return;
			}
		}
		d = e > n ? d.subarray(e - n) : d;
	};
	return {
		beginOutput() {
			resetGeneration(true);
		},
		cancelOutput() {
			resetGeneration(false);
		},
		recordInput(t) {
			const n = Date.now();
			if (!i || a || t.byteLength === 0 || n > f) return;
			const d = decodeMeetingAudio(t, e.audioFormat);
			const p = readPcm16AudioStats(d);
			const y = c.byteLength > 0 ? Buffer.concat([c, d]) : d;
			const b = Math.max(0, y.byteLength - r);
			c = b > 0 ? y.subarray(b) : y;
			if (b > 0) l = Math.max(0, l - Math.floor(b * .5));
			const x = u;
			if (!x || !hasSignal(p)) return;
			const S = Math.floor(c.byteLength * .5) - x.spanSamples;
			for (let e = l; e <= S; e += 1) {
				const r = fingerprintCorrelation(c, e, x);
				if (r < x.threshold) continue;
				const i = c.subarray(e * 2, (e + x.spanSamples) * 2);
				const l = readPcm16AudioStats(i);
				if (!hasSignal(l)) continue;
				a = true;
				s = o;
				m += t.byteLength;
				h = new Date(n).toISOString();
				g = r;
				_ = l.peak;
				v = l.rms;
				clearCorrelationScratch();
				return;
			}
			l = Math.max(0, S + 1);
		},
		recordOutput(r) {
			const o = Date.now();
			if (!i || f !== Number.NEGATIVE_INFINITY && o > f) resetGeneration(true);
			if (r.byteLength === 0) return;
			const s = (e.audioFormat === "g711-ulaw-8khz" ? r.byteLength : r.byteLength * .5) * t ** -1 * 1e3;
			p = Math.max(o, p) + s;
			f = Math.max(f, p + OUTPUT_LOOPBACK_OBSERVATION_WINDOW_MS);
			if (a) return;
			const c = decodeMeetingAudio(r, e.audioFormat);
			d = Buffer.concat([d, c]);
			if (!u || d.byteLength >= n) consumePendingOutput();
		},
		getHealth() {
			return {
				lastOutputLoopbackAt: h,
				lastOutputLoopbackCorrelation: g,
				lastOutputLoopbackPeak: _,
				lastOutputLoopbackRms: v,
				outputLoopbackSignalBytes: m,
				outputGeneration: o,
				verifiedOutputGeneration: s
			};
		}
	};
}
//#endregion
//#region src/meeting-bot/realtime-local-audio-transport.ts
const LOCAL_BRIDGE_TERMINATION_GRACE_MS = 1e3;
const STDERR_LINE_TRUNCATED_PREFIX = "[stderr line truncated] ";
const MAX_STDERR_CHUNK_BYTES = 8192;
function attachStderrLineLogger(e) {
	if (!e.stderr) return;
	if (!e.logger.debug) {
		e.stderr.on("data", () => {});
		return;
	}
	const debug = (t) => e.logger.debug?.(t);
	if (!(e.stderr instanceof Readable)) {
		e.stderr.on("data", (t) => {
			debug(`${e.prefix}: ${String(t).trim()}`);
		});
		return;
	}
	onDecodedOutput(e.stderr, (t) => {
		const n = t.trim();
		if (!n) return;
		const r = Buffer.byteLength(n, "utf8") > MAX_STDERR_CHUNK_BYTES;
		const i = r ? truncateUtf8Suffix(n, MAX_STDERR_CHUNK_BYTES) : n;
		debug(`${e.prefix}: ${r ? STDERR_LINE_TRUNCATED_PREFIX : ""}${i}`);
	});
}
function createLocalMeetingRealtimeAudioTransport(e) {
	const t = splitCommandArgv(e.inputCommand, "audio bridge command");
	const n = splitCommandArgv(e.outputCommand, "audio bridge command");
	const r = e.spawn ?? ((e, t, n) => spawn(e, t, n));
	const spawnOutputProcess = () => r(n.command, n.args, { stdio: [
		"pipe",
		"ignore",
		"pipe"
	] });
	let i = spawnOutputProcess();
	let a;
	try {
		a = r(t.command, t.args, { stdio: [
			"ignore",
			"pipe",
			"pipe"
		] });
	} catch (e) {
		i.on("error", () => {});
		terminateMeetingBridgeProcess(i, { graceMs: LOCAL_BRIDGE_TERMINATION_GRACE_MS });
		throw e;
	}
	let o;
	let s = false;
	let c = false;
	let l = false;
	let u;
	let d;
	const f = new MeetingOutputProcessOwner(LOCAL_BRIDGE_TERMINATION_GRACE_MS);
	const p = createMeetingOutputLoopbackVerifier({ audioFormat: e.audioFormat ?? "pcm16-24khz" });
	const signalFatal = () => {
		if (!l) {
			l = true;
			stop().catch((t) => {
				e.logger.warn(`${e.logScope} failed audio transport cleanup: ${formatErrorMessage(t)}`);
			});
			u?.();
		}
	};
	const fail = (t) => (n) => {
		e.logger.warn(`${e.logScope} ${t} failed: ${formatErrorMessage(n)}`);
		signalFatal();
	};
	const attachAudioProcessHandlers = (t, n) => {
		const isCurrent = () => n === "input" || t === i;
		const onError = (e = "") => (t) => {
			if (isCurrent()) fail(`audio ${n} command${e}`)(t);
		};
		t.on("error", onError());
		if (n === "output") t.stdin?.on?.("error", onError());
		else t.stdout?.on("error", onError(" stdout"));
		t.stderr?.on("error", onError(" stderr"));
		t.on("exit", (t, r) => {
			if (isCurrent() && !s) {
				e.logger.warn(`${e.logScope} audio ${n} command exited (${t ?? r ?? "done"})`);
				signalFatal();
			}
		});
		attachStderrLineLogger({
			stderr: t.stderr,
			logger: e.logger,
			prefix: `${e.logScope} audio ${n}`
		});
	};
	const stop = () => {
		d ??= (async () => {
			s = true;
			p.cancelOutput();
			f.release();
			await f.stop(a, i, o);
		})();
		return d;
	};
	attachAudioProcessHandlers(i, "output");
	attachAudioProcessHandlers(a, "input");
	const m = {
		onFatal: (e) => {
			u = e;
			if (l) e();
		},
		startInput: (e) => {
			if (c) throw new Error("audio input transport already started");
			c = true;
			a.stdout?.on("data", (t) => {
				if (!s) {
					const n = Buffer.isBuffer(t) ? t : Buffer.from(t);
					p.recordInput(n);
					e(n);
				}
			});
		},
		beginOutput: () => p.beginOutput(),
		stop,
		writeOutput: async (e) => {
			if (s) return;
			const t = i;
			const n = t.stdin;
			if (!n) return;
			p.recordOutput(e);
			try {
				await f.write(t, n, e);
			} catch (e) {
				if (s || t !== i || l) return;
				fail("audio output command")(e instanceof Error ? e : new Error(formatErrorMessage(e)));
			}
		},
		clearOutput: async () => {
			if (s) return;
			p.cancelOutput();
			const t = i;
			i = spawnOutputProcess();
			attachAudioProcessHandlers(i, "output");
			f.release(t);
			e.logger.debug?.(`${e.logScope} cleared realtime audio output buffer by restarting playback command`);
			f.retire(t, "SIGKILL");
		},
		dispose: async () => {
			await m.stop();
		},
		getHealth: () => p.getHealth()
	};
	if (!e.bargeInInputCommand) return m;
	return {
		...m,
		startBargeInMonitor: (t) => {
			if (o || s) return;
			const n = splitCommandArgv(e.bargeInInputCommand ?? [], "audio bridge command");
			const i = createSpeechThresholdGate({
				rmsThreshold: e.bargeInRmsThreshold,
				peakThreshold: e.bargeInPeakThreshold,
				cooldownMs: e.bargeInCooldownMs
			});
			o = r(n.command, n.args, { stdio: [
				"ignore",
				"pipe",
				"pipe"
			] });
			o.stdout?.on("data", (n) => {
				const r = Buffer.isBuffer(n) ? n : Buffer.from(n);
				if (s) return;
				const a = readPcm16AudioStats(r);
				if (!i.accept(a, {
					nowMs: Date.now(),
					onTrigger: () => t(r)
				})) return;
				e.logger.debug?.(`${e.logScope} human barge-in detected by local input (rms=${Math.round(a.rms)}, peak=${a.peak})`);
			});
			o.stdout?.on("error", (t) => {
				e.logger.warn(`${e.logScope} human barge-in input stdout failed: ${formatErrorMessage(t)}`);
			});
			attachStderrLineLogger({
				stderr: o.stderr,
				logger: e.logger,
				prefix: `${e.logScope} barge-in input`
			});
			o.stderr?.on("error", (t) => {
				e.logger.warn(`${e.logScope} human barge-in input stderr failed: ${formatErrorMessage(t)}`);
			});
			o.on("error", (t) => {
				e.logger.warn(`${e.logScope} human barge-in input failed: ${formatErrorMessage(t)}`);
			});
			o.on("exit", (t, n) => {
				if (!s) e.logger.debug?.(`${e.logScope} human barge-in input exited (${t ?? n ?? "done"})`);
			});
		}
	};
}
//#endregion
//#region src/meeting-bot/audio-base64.ts
function decodeMeetingAudioBase64(e, t) {
	const n = canonicalizeBase64(e);
	if (!n) throw new Error(`${t} base64 must be a valid audio payload`);
	return Buffer.from(n, "base64");
}
function isMeetingAudioBase64(e) {
	return canonicalizeBase64(e) !== void 0;
}
//#endregion
//#region src/meeting-bot/realtime-node-audio-transport.ts
const NODE_OUTPUT_GENERATION_CAPABILITY = Symbol.for("openclaw.internal.meeting-node-output-generation.v1");
function createNodeMeetingRealtimeAudioTransport(e) {
	let t = false;
	let n = false;
	let r = 0;
	let i;
	let a = false;
	let o;
	let s = 0;
	let c = false;
	let l = Promise.resolve();
	const u = createMeetingOutputLoopbackVerifier({ audioFormat: e.audioFormat ?? "pcm16-24khz" });
	const d = captureCurrentPluginBackgroundRunner();
	const invoke = (t, n = {}, r = 5e3) => d(() => e.runtime.nodes.invoke({
		nodeId: e.nodeId,
		command: e.commandName,
		params: {
			action: t,
			bridgeId: e.bridgeId,
			...n
		},
		timeoutMs: r
	}));
	const runOutputCommand = (e) => {
		if (c) return e();
		const t = l.then(e, e);
		l = t.then(() => void 0, () => void 0);
		return t;
	};
	const signalFatal = () => {
		if (!a) {
			a = true;
			o?.();
		}
	};
	const f = {
		onFatal: (e) => {
			o = e;
			if (a) e();
		},
		startInput: (a) => {
			if (n) throw new Error("audio input transport already started");
			n = true;
			(async () => {
				for (;;) {
					if (t) break;
					try {
						const e = await invoke("pullAudio", { timeoutMs: 250 }, 2e3);
						if (t) break;
						const n = asOptionalRecord(e);
						const o = asOptionalRecord(n?.payload ?? e) ?? {};
						const s = readNonBlankString(o.base64);
						if (s) {
							const e = decodeMeetingAudioBase64(s, "pullAudio");
							u.recordInput(e);
							a(e);
						}
						r = 0;
						i = void 0;
						if (o.closed === true) {
							signalFatal();
							break;
						}
					} catch (n) {
						if (t) break;
						const a = formatErrorMessage(n);
						r += 1;
						i = a;
						e.logger.warn(`${e.logScope} ${e.logPrefix} audio input failed (${r}/5): ${a}`);
						if (r >= 5 || /unknown bridgeId|bridge is not open/i.test(a)) {
							signalFatal();
							break;
						}
						await sleep(250);
					}
				}
			})();
		},
		beginOutput: () => u.beginOutput(),
		stop: async () => {
			if (t) return;
			t = true;
			u.cancelOutput();
			try {
				await invoke("stop");
			} catch (t) {
				e.logger.warn(`${e.logScope} node audio bridge stop did not complete: ${formatErrorMessage(t)}`);
			}
		},
		writeOutput: async (e) => {
			if (t) return;
			const n = s;
			u.recordOutput(e);
			try {
				await runOutputCommand(async () => {
					if (t) return;
					await invoke("pushAudio", {
						base64: e.toString("base64"),
						...c ? { outputGeneration: n } : {}
					});
				});
			} catch (e) {
				if (!t && n === s) u.cancelOutput();
				throw e;
			}
		},
		clearOutput: async () => {
			if (t) return;
			s += 1;
			u.cancelOutput();
			await runOutputCommand(async () => {
				if (t) return;
				await invoke("clearAudio", c ? { outputGeneration: s } : {});
			});
		},
		dispose: async () => {
			await f.stop();
		},
		getHealth: () => ({
			consecutiveInputErrors: r,
			lastInputError: i,
			...u.getHealth()
		})
	};
	Object.defineProperty(f, NODE_OUTPUT_GENERATION_CAPABILITY, {
		get() {
			return c;
		},
		set(e) {
			c = e === true;
		}
	});
	return f;
}
//#endregion
//#region src/meeting-bot/session-types.ts
const boundedText = (e) => string().min(1).max(e).refine((e) => e.trim().length > 0);
const observerSchema = boundedText(128);
const identitySchema = boundedText(512);
const speakerSchema = boundedText(512);
const observedAtSchema = datetime({ offset: true }).max(64);
const meetingObservationProvenanceSchema = object({
	observer: observerSchema,
	observationId: boundedText(1024).optional(),
	sessionId: identitySchema.optional(),
	epoch: identitySchema.optional(),
	observedAt: observedAtSchema.optional(),
	speaker: speakerSchema.optional(),
	self: _enum([
		"self",
		"other",
		"unknown"
	])
});
const meetingCaptionSourceSchema = object({
	id: string().min(1).max(512),
	epoch: string().min(1).max(512),
	revision: string().min(1).max(128),
	finalized: boolean(),
	/** Undefined means the provider could not establish whether this is our own speech. */
	ownEcho: boolean().optional()
});
//#endregion
//#region src/meeting-bot/observation-provenance.ts
/** Decode only bounded scalar facts. Invalid envelopes cannot donate identity or self claims. */
function normalizeMeetingObservationProvenance(e, t) {
	const n = meetingObservationProvenanceSchema.safeParse(e);
	if (n.success) return n.data;
	const r = meetingObservationProvenanceSchema.shape;
	const i = r.observer.safeParse(t.observer);
	const a = r.epoch.unwrap().safeParse(t.epoch);
	const o = r.observedAt.unwrap().safeParse(t.observedAt);
	const s = r.speaker.unwrap().safeParse(t.speaker);
	return {
		observer: i.success ? i.data : "unknown",
		...a.success ? { epoch: a.data } : {},
		...o.success ? { observedAt: o.data } : {},
		...s.success ? { speaker: s.data } : {},
		self: "unknown"
	};
}
/** Keep optional legacy shapes, but never share a mutable envelope with its caller. */
function snapshotMeetingObservation(e) {
	return {
		...e,
		...e.provenance !== void 0 ? { provenance: { ...e.provenance } } : {}
	};
}
function snapshotMeetingTranscript(e) {
	return {
		...e,
		...e.lines ? { lines: e.lines.map(snapshotMeetingObservation) } : {},
		...e.pendingLines ? { pendingLines: e.pendingLines.map(snapshotMeetingObservation) } : {}
	};
}
/** Carry row facts only where an independently validated action-source identity exists. */
function meetingCaptionParticipationSources(e) {
	return [...e.lines, ...e.pendingLines ?? []].flatMap((e) => e.source ? [{
		...e.source,
		kind: "caption",
		text: e.text,
		...e.provenance ? { provenance: e.provenance } : {}
	}] : []);
}
//#endregion
//#region src/meeting-bot/participation.ts
const SOURCE_LIFETIME_MS = 12e4;
const MAX_SOURCES = 1024;
function fingerprint(e) {
	const canonical = (e) => {
		if (Array.isArray(e)) return e.map(canonical);
		if (e && typeof e === "object") return Object.fromEntries(Object.entries(e).toSorted(([e], [t]) => e.localeCompare(t)).map(([e, t]) => [e, canonical(t)]));
		return e;
	};
	return sha256Hex(JSON.stringify(canonical(e)));
}
/** The live session owns authority; persisted claims only prevent replay of that authority. */
var MeetingParticipation = class {
	#e = /* @__PURE__ */ new Set();
	#t = /* @__PURE__ */ new Map();
	#n = /* @__PURE__ */ new Map();
	#r = /* @__PURE__ */ new Map();
	#i = /* @__PURE__ */ new Map();
	constructor(e) {
		this.options = e;
	}
	close(e) {
		this.#e.add(e);
		this.#r.delete(e);
		this.#n.delete(e);
		this.#i.delete(e);
	}
	observeEpoch(e, t, n) {
		if (this.#e.has(e) || !this.options.current(e) || !n) return false;
		let r = this.#i.get(e);
		if (!r) this.#i.set(e, r = /* @__PURE__ */ new Map());
		const i = r.get(t);
		if (i?.seen.has(n) && i.current !== n) return false;
		if (i) {
			i.current = n;
			i.seen.add(n);
		} else r.set(t, {
			current: n,
			seen: /* @__PURE__ */ new Set([n])
		});
		const a = this.#r.get(e);
		for (const [e, r] of a ?? []) if (r.kind === t && r.epoch !== n) a?.delete(e);
		return true;
	}
	observe(e, t) {
		const n = this.#e.has(e) ? void 0 : this.options.current(e);
		if (!n) return;
		if (!t.id || !this.observeEpoch(e, t.kind, t.epoch)) return;
		let r = this.#r.get(e);
		if (!r) this.#r.set(e, r = /* @__PURE__ */ new Map());
		for (const [e, t] of r) if (Date.now() - t.observedAt > SOURCE_LIFETIME_MS) r.delete(e);
		const i = fingerprint([
			t.kind,
			t.epoch,
			t.id
		]);
		const a = r.get(i);
		let o = this.#n.get(e);
		if (!o) this.#n.set(e, o = /* @__PURE__ */ new Map());
		let s = o.get(i);
		if (!s) {
			if (o.size >= 1e4) return;
			const t = (this.#t.get(e) ?? 0) + 1;
			this.#t.set(e, t);
			o.set(i, s = {
				order: t,
				observedAt: Date.now(),
				assertOwnerCurrent: n.assertCurrent.bind(n),
				seenRevisions: /* @__PURE__ */ new Set()
			});
		}
		s.ownEcho ||= t.ownEcho;
		if (s.ownEcho) {
			r.delete(i);
			return;
		}
		if (s.seenRevisions.has(t.revision) && s.revision !== t.revision) return;
		s.revision = t.revision;
		s.seenRevisions.add(t.revision);
		if (s.seenRevisions.size > 128) {
			r.delete(i);
			return;
		}
		try {
			s.assertOwnerCurrent();
		} catch {
			r.delete(i);
			return;
		}
		if (Date.now() - s.observedAt > SOURCE_LIFETIME_MS) return;
		if (!t.finalized || !t.revision || !t.text?.trim() || t.text.length > 16384) {
			r.delete(i);
			return;
		}
		if (a?.revision === t.revision && a.text === t.text) return a.sourceId;
		let c;
		if (!a && r.size >= MAX_SOURCES) {
			let e = s.order;
			for (const [t, n] of r) if (n.order < e) {
				c = t;
				e = n.order;
			}
			if (c === void 0) return;
		}
		const l = {
			...t,
			sourceId: randomUUID(),
			order: s.order,
			...s.sourceId ? { replacesSourceId: s.sourceId } : {},
			observedAt: s.observedAt,
			assertOwnerCurrent: s.assertOwnerCurrent
		};
		s.sourceId = l.sourceId;
		r.set(i, l);
		if (c !== void 0) r.delete(c);
		return l.sourceId;
	}
	context(e) {
		const t = this.#e.has(e) ? void 0 : this.options.current(e);
		return {
			sessionId: e,
			active: Boolean(t),
			sourceOrder: t ? this.#t.get(e) ?? 0 : 0,
			capabilities: t ? [...this.options.capabilities(t.session)] : [],
			sources: t ? [...this.#r.get(e)?.values() ?? []].filter((e) => this.#s(e)).map(({ observedAt: e, assertOwnerCurrent: t, ...n }) => n) : []
		};
	}
	inspect(e, t) {
		const n = this.#e.has(e) ? void 0 : this.options.current(e);
		const r = this.#o(e, t);
		if (!n || !r) return;
		const { observedAt: i, assertOwnerCurrent: a, ...o } = r;
		return {
			source: o,
			assertCurrent: () => {
				if (this.#e.has(e) || this.#o(e, t) !== r) throw new Error("The participation source is no longer current.");
				n.assertCurrent();
			}
		};
	}
	async execute(e, t) {
		const n = structuredClone(t);
		const result = (e, t) => ({
			requestId: n.requestId,
			status: e,
			message: t
		});
		const validToken = (e) => typeof e === "string" && e.trim().length > 0 && Buffer.byteLength(e, "utf8") <= 128;
		if (!validToken(e) || !validToken(n.requestId) || !n.action || !validToken(n.action.type) || n.sourceId !== void 0 && !validToken(n.sourceId) || n.correctionOf !== void 0 && !validToken(n.correctionOf)) return result("rejected", "Session, request, action, and source identifiers must be non-empty strings of at most 128 UTF-8 bytes.");
		const r = this.options.store;
		const i = `${e}:request:${n.requestId}`;
		const a = fingerprint(n);
		const replay = (e) => {
			if (e?.fingerprint !== a) return result("rejected", "This requestId already identifies a different action.");
			return {
				...e.result ?? result("uncertain", "This action was already claimed; its result is unknown. Do not retry it."),
				replayed: true
			};
		};
		const o = await r.lookup(i);
		if (o) return replay(o);
		const s = this.#e.has(e) ? void 0 : this.options.current(e);
		if (!s) return result("rejected", "The meeting session is no longer active.");
		const c = n.sourceId ? this.#o(e, n.sourceId) : void 0;
		let l = false;
		const assertCurrent = () => {
			if (this.#e.has(e)) throw new Error("The meeting session is closing.");
			s.assertCurrent();
			if (l && !this.options.capabilities(s.session).includes(n.action.type)) throw new Error("The participation capability is no longer available.");
			if (n.sourceId && (!c || this.#o(e, n.sourceId) !== c)) throw new Error("The participation source is stale, corrected, expired, or an own echo.");
		};
		const u = {
			kind: "meeting-participation-attempt",
			sessionId: e,
			requestId: n.requestId,
			fingerprint: a,
			...n.sourceId === void 0 ? {} : { sourceId: n.sourceId },
			actionType: n.action.type,
			...n.correctionOf === void 0 ? {} : { correctionOf: n.correctionOf }
		};
		if (!await this.#a(i, u)) return replay(await r.lookup(i));
		const finish = async (e) => {
			try {
				await r.register(i, {
					...u,
					result: e
				});
			} catch {
				return result("uncertain", "The action result could not be recorded. Its claim remains; do not retry it.");
			}
			return e;
		};
		try {
			assertCurrent();
			if (n.correctionOf) {
				const t = await r.lookup(`${e}:request:${n.correctionOf}`);
				assertCurrent();
				if (!t || t.correctionOf || t.result?.correctionOf !== n.correctionOf || t.sourceId !== n.sourceId || t.actionType !== n.action.type) return await finish(result("rejected", "The correction must retain a correctable request's source and action type."));
				const i = await this.#a(`${e}:correction:${n.correctionOf}`, u);
				assertCurrent();
				if (!i) return await finish(result("rejected", "This request already used its one correction opportunity."));
			}
			if (!this.options.capabilities(s.session).includes(n.action.type)) return await finish(result("unsupported", "This meeting does not support that participation action."));
			l = true;
			if (c) {
				const t = `${e}:source:${fingerprint([
					c.kind,
					c.epoch,
					c.id,
					n.action.type
				])}`;
				const i = await this.#a(t, u);
				assertCurrent();
				if (!i) {
					const e = await r.lookup(t);
					assertCurrent();
					if (!n.correctionOf || e?.requestId !== n.correctionOf || e.sourceId !== n.sourceId) return await finish(result("rejected", "This source already authorized this action type; it cannot authorize another attempt."));
				}
			}
			const t = this.options.validateAction(n.action);
			if (t) return await finish({
				...result("rejected", t),
				...!n.correctionOf ? { correctionOf: n.requestId } : {}
			});
			assertCurrent();
		} catch (e) {
			return await finish(result("rejected", coerceErrorMessage(e)));
		}
		let d;
		try {
			assertCurrent();
			const { correctable: e, ...t } = await this.options.execute(s.session, n, assertCurrent);
			assertCurrent();
			d = {
				status: t.status,
				...t.message === void 0 ? {} : { message: t.message },
				...t.observed === void 0 ? {} : { observed: t.observed },
				requestId: n.requestId,
				...t.status === "rejected" && e === true && !n.correctionOf ? { correctionOf: n.requestId } : {}
			};
		} catch (e) {
			d = result("uncertain", `The action outcome is unknown: ${coerceErrorMessage(e)}. Do not retry it.`);
		}
		return await finish(d);
	}
	async #a(e, t) {
		try {
			return await this.options.store.registerIfAbsent(e, t);
		} catch (n) {
			if (!(n instanceof PluginStateStoreError) || n.code !== "PLUGIN_STATE_LIMIT_EXCEEDED") throw n;
			const r = await this.options.store.entries();
			let i = 0;
			for (const e of r.toSorted((e, t) => e.createdAt - t.createdAt)) {
				const t = e.value;
				if (!t || t.kind !== "meeting-participation-attempt" || typeof t.sessionId !== "string" || !t.sessionId || typeof t.requestId !== "string") continue;
				if (!(e.key === `${t.sessionId}:request:${t.requestId}` || t.correctionOf && e.key === `${t.sessionId}:correction:${t.correctionOf}` || e.key.startsWith(`${t.sessionId}:source:`) && /^[a-f0-9]{64}$/.test(e.key.slice(`${t.sessionId}:source:`.length)))) continue;
				if (!this.#e.has(t.sessionId) && this.options.current(t.sessionId)) continue;
				if (await this.options.store.delete(e.key)) i++;
				if (i >= 1e3) break;
			}
			return await this.options.store.registerIfAbsent(e, t);
		}
	}
	#o(e, t) {
		for (const n of this.#r.get(e)?.values() ?? []) if (n.sourceId === t && this.#s(n)) return n;
	}
	#s(e) {
		if (Date.now() - e.observedAt > SOURCE_LIFETIME_MS) return false;
		try {
			e.assertOwnerCurrent();
			return true;
		} catch {
			return false;
		}
	}
};
//#endregion
//#region src/meeting-bot/session-cleanup-tracker.ts
var MeetingSessionCleanupTracker = class {
	#e = /* @__PURE__ */ new Map();
	#t(e) {
		let t = this.#e.get(e);
		if (!t) {
			t = { stops: /* @__PURE__ */ new Set() };
			this.#e.set(e, t);
		}
		return t;
	}
	prepareRuntime(e, t) {
		const n = this.#t(e);
		if (n.setup) return n.setup;
		const r = Promise.resolve().then(t).finally(() => {
			n.setup = void 0;
		});
		n.setup = r;
		return r;
	}
	addStop(e, t) {
		this.#t(e).stops.add(t);
	}
	hasRuntime(e) {
		const t = this.#e.get(e);
		return Boolean(t?.setup || t?.stops.size);
	}
	retainFailedJoin(e) {
		this.#t(e).unpublished = true;
	}
	stopRuntime(e) {
		const t = this.#e.get(e);
		if (!t) return Promise.resolve();
		if (t.stopping) return t.stopping;
		const n = Promise.resolve().then(async () => {
			await t.setup?.catch(() => void 0);
			const e = await Promise.allSettled([...t.stops].map(async (e) => {
				await e();
				t.stops.delete(e);
			}));
			throwIfSettledRejected(e, "Meeting runtime cleanup failed");
		}).finally(() => {
			t.stopping = void 0;
		});
		t.stopping = n;
		return n;
	}
	begin(e, t) {
		const n = this.#t(e);
		if (n.cleanup) return false;
		n.cleanup = {
			browserLeft: t,
			browserSettled: false,
			stopSettled: false
		};
		return true;
	}
	isPending(e) {
		return this.#e.get(e)?.cleanup !== void 0;
	}
	async cleanup(e) {
		const t = this.#e.get(e.sessionId)?.cleanup;
		if (!t) throw new Error("Missing cleanup state for meeting session " + e.sessionId);
		let n;
		if (!t.stopSettled) try {
			await this.stopRuntime(e.sessionId);
			t.stopSettled = true;
		} catch (e) {
			n = e;
		}
		if (!t.browserSettled) try {
			if (e.keepBrowserTab) t.browserSettled = true;
			else {
				t.browserLeft = await e.releaseBrowser();
				t.browserSettled = t.browserLeft !== false || !e.hasBrowserTab();
			}
		} catch (e) {
			n ??= e;
		}
		const r = this.#e.get(e.sessionId)?.unpublished === true;
		const i = e.sessionId;
		const a = t.stopSettled && t.browserSettled && !this.hasRuntime(i);
		if (a) this.#e.delete(i);
		if (n) throw n instanceof Error ? n : new Error("Meeting session cleanup failed", { cause: n });
		return {
			browserLeft: t.browserLeft,
			complete: a,
			unpublished: r
		};
	}
};
//#endregion
//#region src/meeting-bot/session-durable-transcripts.ts
const STOP_RETRY_DELAY_MS = 1e3;
const STOP_RETRY_MAX_DELAY_MS = 6e4;
var MeetingSessionDurableTranscripts = class {
	#e;
	#t;
	#n = Promise.resolve();
	#r = /* @__PURE__ */ new Map();
	constructor(e) {
		this.options = e;
		this.#t = resolveTranscriptsConfig(e.config?.config).enabled;
	}
	reconcilePolicy(e) {
		this.#t = e;
		const reconcile = async () => {
			const t = await this.#a();
			if (!t) return;
			await Promise.all(this.options.listSessions().map(async (n) => {
				if (n.state !== "active" || !this.options.isBrowserSession(n)) return;
				if (!e) await t.stop(n, async () => this.options.transcriptStore.captureNotes(n));
				else if (this.#t) {
					await t.stop(n, async () => this.options.transcriptStore.flushPending(n));
					this.#r.delete(n.id);
					await this.options.transcriptStore.captureNotes(n);
					if (this.#t && n.state === "active") await t.start(n, async () => this.options.transcriptStore.captureNotes(n));
				}
			}));
		};
		const t = this.#n.then(reconcile);
		this.#n = t.catch(() => {});
		return t;
	}
	async ingest(e, t) {
		await (await this.#a())?.ingest(e, t);
	}
	async start(e) {
		await this.#n;
		if (!this.#t || !this.options.isBrowserSession(e)) return;
		await (await this.#a())?.start(e, async () => await this.options.transcriptStore.captureNotes(e));
	}
	async stop(e, t) {
		const finalCapture = async () => await this.options.transcriptStore.captureNotes(e, { finalize: true });
		const n = await this.#a();
		if (n) try {
			if (await n.stop(e, finalCapture)) {
				this.#r.delete(e.id);
				return true;
			}
		} catch (t) {
			this.options.logger.warn(`${this.options.logScope} durable transcript finalization queued for retry: ${this.options.formatError(t)}`);
			this.#o(e, n);
			return false;
		}
		if (t.allowFallback && this.options.isTranscribeSession(e)) await finalCapture().catch((e) => {
			this.options.logger.debug?.(`${this.options.logScope} final transcript snapshot ignored: ${this.options.formatError(e)}`);
		});
		return true;
	}
	async startSource(e) {
		const t = await this.#a();
		if (!t?.enabled) return {
			ok: false,
			error: "meeting transcripts are disabled"
		};
		const n = this.#i(e.session.source);
		if (!n) return {
			ok: false,
			error: "No active meeting session matches the transcript source."
		};
		if (e.session.source.agentId !== n.agentId) return {
			ok: false,
			error: "meeting transcript source belongs to another agent"
		};
		return await t.attach(n, e);
	}
	async stopSource(e) {
		const t = await this.#a();
		return t ? await t.detach(e) : {
			ok: true,
			sessionId: e.sessionId,
			stoppedAt: (/* @__PURE__ */ new Date()).toISOString()
		};
	}
	#i(e) {
		const t = e.agentId?.trim();
		const n = e.meetingUrl?.trim();
		const r = e.channelId?.trim();
		if (!t || !n && !r) return;
		return this.options.listSessions().filter((e) => e.state === "active").toSorted((e, t) => e.createdAt.localeCompare(t.createdAt)).find((e) => e.agentId === t && (!r || e.id === r) && (!n || this.options.sameMeetingUrl(e.url, n)));
	}
	async #a() {
		if (!this.options.config) return;
		this.#e ??= import("../transcripts-bridge.runtime-Da1IGejj.mjs").then(({ createMeetingDurableTranscriptBridge: e }) => e({
			isEnabled: () => this.#t,
			logger: this.options.logger,
			options: this.options.config
		})).catch((e) => {
			this.options.logger.warn(`${this.options.logScope} durable transcripts unavailable: ${this.options.formatError(e)}`);
		});
		return await this.#e;
	}
	#o(e, t) {
		if (this.#r.has(e.id)) return;
		const n = Symbol(e.id);
		this.#r.set(e.id, {
			attempt: 1,
			token: n
		});
		const retry = () => {
			const t = this.#r.get(e.id)?.attempt ?? 1;
			const n = Math.min(STOP_RETRY_DELAY_MS * 2 ** Math.min(t - 1, 16), STOP_RETRY_MAX_DELAY_MS);
			setTimeout(() => void run(), n).unref?.();
		};
		const run = async () => {
			await this.#n;
			const r = this.#r.get(e.id);
			if (!r || r.token !== n) return;
			try {
				if (!await t.stop(e, async () => await this.options.transcriptStore.flushPending(e))) throw new Error("durable transcript capture is no longer active");
				if (this.#r.get(e.id)?.token !== n) return;
				this.options.transcriptStore.retire(e.id);
				this.#r.delete(e.id);
			} catch {
				if (this.#r.get(e.id)?.token !== n) return;
				this.#r.set(e.id, {
					attempt: r.attempt + 1,
					token: n
				});
				retry();
			}
		};
		retry();
	}
};
//#endregion
//#region src/meeting-bot/session-runtime-browser-tabs.ts
function inheritMeetingBrowserTabOwnership(e, t, n) {
	if (!n.tab) return;
	return [...e].some((e) => {
		const r = t.getBrowser(e);
		const i = r?.tab;
		return e.transport === n.transport && t.sameMeetingUrl(e.url, n.meetingUrl) && r?.nodeId === n.nodeId && i?.targetId === n.tab?.targetId && i?.openedByPlugin === true;
	}) ? {
		...n.tab,
		openedByPlugin: true
	} : n.tab;
}
async function settleMeetingRetainedBrowserTabs(e, t, n) {
	let r = true;
	for (let i = 0; i < t.length;) {
		const a = t[i];
		if (!a) break;
		const { session: o, tab: s } = a;
		const c = e.getBrowser(o);
		if (n?.transport === o.transport && n.nodeId === c?.nodeId && n.tab.targetId === s.targetId) {
			e.setBrowserTab(o, void 0);
			t.splice(i, 1);
			continue;
		}
		if (await e.releaseBrowserTab(o) === false) {
			r = false;
			i += 1;
			continue;
		}
		t.splice(i, 1);
	}
	return r;
}
async function settleMeetingRetainedBrowserTabsAfterFailure(e, t) {
	for (let n = 0; n < 2 && t.length > 0; n += 1) try {
		if (await settleMeetingRetainedBrowserTabs(e, t)) return;
	} catch (t) {
		e.logger.warn(`${e.logScope} retained browser cleanup failed: ${e.formatError(t)}`);
	}
	if (t.length > 0) e.logger.warn(`${e.logScope} retained browser cleanup incomplete after failed join`);
}
//#endregion
//#region src/meeting-bot/session-speech-readiness.ts
function evaluateMeetingSpeechReadiness(e) {
	const { browser: t, speech: n } = e;
	if (!e.talkBack || !t) return { ready: true };
	const r = e.managedBrowser ? t.health : void 0;
	if (r?.manualAction) return {
		ready: false,
		reason: r.manualAction.reason,
		message: r.manualAction.message
	};
	if (r?.inCall === true) {
		if (r.micMuted !== false) {
			const e = r.micMuted === true;
			return {
				ready: false,
				reason: e ? n.microphoneMutedReason : n.browserUnverifiedReason,
				message: e ? n.microphoneMuted : n.browserUnverified
			};
		}
	} else if (r?.inCall === false) return {
		ready: false,
		reason: n.notInCallReason,
		message: n.notInCall
	};
	else if (e.managedBrowser) return {
		ready: false,
		reason: n.browserUnverifiedReason,
		message: n.browserUnverified
	};
	return t.hasAudioBridge ? { ready: true } : {
		ready: false,
		reason: n.audioBridgeUnavailableReason,
		message: n.audioBridgeUnavailable
	};
}
//#endregion
//#region src/meeting-bot/session-runtime.ts
const nowIso$1 = () => (/* @__PURE__ */ new Date()).toISOString();
/** Shared lifecycle owner; platform strategies perform transport-specific I/O only. */
var MeetingSessionRuntime = class {
	#e = /* @__PURE__ */ new Map();
	#t;
	#n = new MeetingSessionCleanupTracker();
	#r = new KeyedAsyncQueue();
	#i = /* @__PURE__ */ new Map();
	#a = /* @__PURE__ */ new Map();
	#o;
	#s;
	constructor(e) {
		this.options = e;
		if (e.participation) this.#t = new MeetingParticipation({
			...e.participation,
			current: (e) => {
				const t = this.#e.get(e);
				if (!t) return;
				const n = this.#c(t);
				if (t.state !== "active") return;
				return {
					session: t,
					assertCurrent: () => {
						if (!n(e)) throw new Error("The meeting session no longer owns this browser tab and route.");
					}
				};
			}
		});
		this.#s = new MeetingSessionTranscriptStore({
			getSession: (e) => this.#e.get(e),
			isBrowserSession: (e) => this.options.isBrowserTransport(e.transport),
			isTranscribeSession: (e) => this.options.isTranscribeMode(e.mode),
			hasBrowserTab: (e) => Boolean(this.options.getBrowser(e)?.tab),
			capture: async (e, t) => {
				const n = this.#c(e, { requireSameTab: this.#t !== void 0 });
				const r = await this.options.captureTranscript(e, t);
				if (!n(e.id)) throw new Error("The meeting session no longer owns the captured browser tab and route.");
				return r && snapshotMeetingTranscript(r);
			},
			onSnapshot: (e, t) => {
				if (t.epoch && this.#t?.observeEpoch(e.id, "caption", t.epoch) === false) return;
				for (const n of meetingCaptionParticipationSources(t)) this.observeParticipationSource(e.id, n);
			},
			onLines: async (e, t) => await this.#o.ingest(e, t)
		});
		this.#o = new MeetingSessionDurableTranscripts({
			config: e.durableTranscripts,
			formatError: (t) => e.formatError(t),
			isBrowserSession: (t) => e.isBrowserTransport(t.transport),
			isTranscribeSession: (t) => e.isTranscribeMode(t.mode),
			listSessions: () => [...this.#e.values()],
			logger: e.logger,
			logScope: e.logScope,
			sameMeetingUrl: (t, n) => e.sameMeetingUrl(t, n),
			transcriptStore: this.#s
		});
	}
	list() {
		this.refreshHealth();
		return [...this.#e.values()].toSorted((e, t) => e.createdAt.localeCompare(t.createdAt));
	}
	getSession(e) {
		return this.#e.get(e);
	}
	async status(e) {
		this.refreshHealth(e);
		if (!e) {
			const e = [...this.#e.values()].toSorted((e, t) => e.createdAt.localeCompare(t.createdAt));
			await Promise.all(e.map((e) => this.options.refreshStatus(e)));
			return {
				found: true,
				sessions: e
			};
		}
		const t = this.#e.get(e);
		if (t) await this.options.refreshStatus(t);
		return t ? {
			found: true,
			session: t
		} : { found: false };
	}
	participationContext(e) {
		const t = this.#t?.context(e) ?? {
			sessionId: e,
			active: false,
			sourceOrder: 0,
			capabilities: [],
			sources: []
		};
		return {
			...t,
			sources: t.sources.map(snapshotMeetingObservation)
		};
	}
	observeParticipationEpoch(e, t, n) {
		return this.#t?.observeEpoch(e, t, n) ?? false;
	}
	observeParticipationSource(e, t) {
		return this.#t?.observe(e, snapshotMeetingObservation(t));
	}
	inspectParticipationSource(e, t) {
		const n = this.#t?.inspect(e, t);
		return n && {
			...n,
			source: snapshotMeetingObservation(n.source)
		};
	}
	async participate(e, t) {
		return this.#t ? await this.#t.execute(e, t) : {
			requestId: t.requestId,
			status: "unsupported",
			message: "This meeting platform does not support participation actions."
		};
	}
	async transcript(e, t = {}) {
		return snapshotMeetingTranscript(await this.#s.read(e, t));
	}
	async startTranscriptSource(e) {
		return await this.#o.startSource(e);
	}
	reconcileTranscriptPolicy(e) {
		return this.#o.reconcilePolicy(e);
	}
	async stopTranscriptSource(e) {
		return await this.#o.stopSource(e);
	}
	isReusableSession(e, t) {
		return e.state === "active" && this.options.sameMeetingUrl(e.url, t.url) && e.transport === t.transport && e.mode === t.mode && e.agentId === t.agentId;
	}
	async join(e) {
		const t = this.options.resolveJoin(e);
		return await this.#r.enqueue(this.#f(t.transport, t.url), async () => await this.#l(e, t));
	}
	async leave(e, t) {
		const n = this.#e.get(e);
		if (!n) return { found: false };
		this.#t?.close(e);
		return await this.#r.enqueue(this.#f(n.transport, n.url), async () => await this.#u(e, t));
	}
	async speak(e, t) {
		const n = this.#e.get(e);
		if (!n) return {
			found: false,
			spoken: false
		};
		if (n.state !== "active") return {
			found: true,
			spoken: false,
			session: n
		};
		const r = await this.options.speakViaTransport(n, t);
		if (n.state !== "active") return {
			found: true,
			spoken: false,
			session: n
		};
		if (r?.handled) return {
			found: true,
			spoken: r.spoken,
			session: n
		};
		await this.refreshBrowserHealth(n);
		if (n.state !== "active") return {
			found: true,
			spoken: false,
			session: n
		};
		await this.#n.prepareRuntime(n.id, async () => {
			if (n.state !== "active") return;
			const e = await this.options.ensureRealtimeBridge(n);
			if (e) this.#p(n, e);
		});
		if (n.state !== "active") {
			await this.#n.stopRuntime(n.id);
			return {
				found: true,
				spoken: false,
				session: n
			};
		}
		const i = this.#i.get(e);
		if (!i || n.state !== "active") return {
			found: true,
			spoken: false,
			session: n
		};
		const a = this.refreshSpeechReadiness(n);
		if (!a.ready) {
			const e = a.message ? `Realtime speech blocked: ${a.message}` : this.options.messages.speechBlockedFallback;
			this.#_(n, e);
			n.updatedAt = nowIso$1();
			return {
				found: true,
				spoken: false,
				session: n
			};
		}
		i(t || this.options.defaultSpeechInstructions);
		n.updatedAt = nowIso$1();
		this.refreshHealth(e);
		return {
			found: true,
			spoken: true,
			session: n
		};
	}
	async speakWhenReady(e, t) {
		let n = await this.speak(e.id, t);
		if (n.spoken || !this.options.isBrowserTransport(e.transport)) return n.spoken;
		const r = Math.min(Math.max(0, this.options.waitForInCallMs), Math.max(0, this.options.joinTimeoutMs));
		const i = monotonicNow() + r;
		while (monotonicNow() < i) {
			await sleep(Math.min(250, Math.max(0, i - monotonicNow())));
			n = await this.speak(e.id, t);
			if (n.spoken) return true;
			const r = this.options.getBrowser(n.session)?.health;
			if (r?.manualAction || n.session?.state !== "active") return false;
			const a = r?.speechBlockedReason;
			if (a && !this.options.transientSpeechBlockedReasons.has(a)) return false;
		}
		return false;
	}
	hasHealthHandle(e) {
		return this.#a.has(e);
	}
	refreshHealth(e) {
		const t = e ? [e] : [...this.#a.keys()];
		for (const e of t) {
			const t = this.#e.get(e);
			const n = this.#a.get(e);
			const r = t ? this.options.getBrowser(t) : void 0;
			if (!t || !r || !n) continue;
			this.options.setBrowserHealth(t, {
				...r.health,
				...n()
			});
			this.refreshSpeechReadiness(t);
		}
	}
	async refreshBrowserHealth(e, t = {}) {
		if (!this.#h(e)) {
			this.refreshSpeechReadiness(e);
			return;
		}
		if (!t.force && this.options.isTalkBackMode(e.mode) && this.#g(e).ready) {
			this.refreshSpeechReadiness(e);
			return;
		}
		await this.options.refreshBrowserHealth(e, t);
		this.refreshSpeechReadiness(e);
	}
	async refreshCaptionHealth(e) {
		if (!this.options.isTranscribeMode(e.mode)) {
			this.refreshSpeechReadiness(e);
			return;
		}
		await this.refreshBrowserHealth(e);
	}
	refreshSpeechReadiness(e) {
		const t = this.#g(e);
		if (t.ready) e.notes = e.notes.filter((e) => !e.startsWith("Realtime speech blocked:"));
		const n = this.options.getBrowser(e);
		if (n) this.options.setBrowserHealth(e, {
			...n.health,
			speechReady: t.ready,
			speechBlockedReason: t.reason,
			speechBlockedMessage: t.message
		});
		return t;
	}
	markSessionEnded(e, t) {
		this.#t?.close(e.id);
		e.state = "ended";
		e.updatedAt = nowIso$1();
		this.#m(e.id);
		this.#_(e, t);
	}
	#c(e, { requireSameTab: t = true } = {}) {
		const n = this.options.getBrowser(e);
		const r = n?.tab?.targetId;
		const i = n?.nodeId;
		const { url: a, transport: o, state: s } = e;
		return (n) => {
			const c = this.options.getBrowser(e);
			return this.#e.get(n) === e && e.state === s && e.url === a && e.transport === o && c?.nodeId === i && (!t || c?.tab?.targetId === r);
		};
	}
	async #l(e, t) {
		for (const e of this.list()) if (e.state === "ended" && e.transport === t.transport && this.options.sameMeetingUrl(e.url, t.url) && this.#n.hasRuntime(e.id)) await this.#u(e.id);
		const n = this.list().filter((e) => e.state === "active" && this.options.sameMeetingUrl(e.url, t.url) && e.transport === t.transport);
		const r = [];
		if (this.options.isBrowserTransport(t.transport)) for (const e of n) {
			if (this.isReusableSession(e, t)) continue;
			const n = this.options.getBrowser(e);
			const i = this.options.reuseExistingBrowserTab ? n?.tab : void 0;
			const a = Boolean(i) || n?.launched === false;
			if (i) r.push({
				session: e,
				tab: i
			});
			try {
				if ((await this.#u(e.id, a ? { keepBrowserTab: true } : void 0)).browserLeft === false) throw new Error(this.options.messages.previousBrowserLeaveFailed);
			} catch (e) {
				await settleMeetingRetainedBrowserTabsAfterFailure(this.options, r);
				throw e;
			}
			this.#_(e, this.options.messages.reassignedSessionNote);
		}
		let i = n.find((e) => this.isReusableSession(e, t));
		if (i) {
			const n = await this.options.refreshReusableSession(i, e, t);
			if (i.state !== "active") {
				await this.#d(i, { keepBrowserTab: n?.keepBrowserTab ?? true });
				i = void 0;
			}
		}
		const a = this.options.resolveSpeechInstructions(e);
		if (i) {
			await this.#o.start(i);
			await this.refreshBrowserHealth(i);
			this.#_(i, this.options.messages.reusedSessionNote);
			i.updatedAt = nowIso$1();
			const e = this.options.isTalkBackMode(t.mode) && a ? await this.speakWhenReady(i, a) : false;
			return {
				session: i,
				spoken: e
			};
		}
		const o = this.options.createSession({
			request: e,
			resolved: t,
			createdAt: nowIso$1()
		});
		let s;
		try {
			s = (await this.options.joinTransport({
				request: e,
				session: o,
				context: {
					attachRuntimeHandles: (e, t) => this.#p(e, t),
					inheritedBrowserTab: (e) => inheritMeetingBrowserTabOwnership(this.#e.values(), this.options, e)
				}
			})).delegatedSpoken === true;
			const t = this.options.getBrowser(o);
			if (!await settleMeetingRetainedBrowserTabs(this.options, r, t?.tab ? {
				transport: o.transport,
				nodeId: t.nodeId,
				tab: t.tab
			} : void 0)) throw new Error(this.options.messages.replacementBrowserLeaveFailed);
		} catch (e) {
			try {
				await this.#d(o);
			} catch (e) {
				this.options.logger.warn(`${this.options.logScope} replacement cleanup failed: ${this.options.formatError(e)}`);
			}
			if (this.#n.isPending(o.id)) {
				this.#n.retainFailedJoin(o.id);
				this.#e.set(o.id, o);
				this.#_(o, "Meeting cleanup is pending; use leave to retry.");
			}
			await settleMeetingRetainedBrowserTabsAfterFailure(this.options, r);
			this.options.logger.warn(`${this.options.logScope} join failed: ${this.options.formatError(e)}`);
			throw e;
		}
		this.#e.set(o.id, o);
		await this.#o.start(o);
		return {
			session: o,
			spoken: s ? true : this.options.isTalkBackMode(t.mode) && a ? await this.speakWhenReady(o, a) : false
		};
	}
	async #u(e, t) {
		const n = this.#e.get(e);
		if (!n) return { found: false };
		if (n.state === "ended" && !this.#n.isPending(e) && !this.#n.hasRuntime(e)) return {
			found: true,
			session: n,
			...n.browserLeft === void 0 ? {} : { browserLeft: n.browserLeft }
		};
		return await this.#d(n, t);
	}
	async #d(e, t) {
		this.#t?.close(e.id);
		const n = this.#n.begin(e.id, e.browserLeft);
		e.state = "ended";
		e.updatedAt = nowIso$1();
		this.#m(e.id);
		let r = false;
		try {
			r = await this.#o.stop(e, { allowFallback: n });
			const i = await this.#n.cleanup({
				sessionId: e.id,
				keepBrowserTab: t?.keepBrowserTab === true,
				hasBrowserTab: () => Boolean(this.options.getBrowser(e)?.tab),
				releaseBrowser: async () => await this.options.releaseBrowserTab(e)
			});
			e.browserLeft = i.browserLeft;
			const a = this.options.getBrowser(e);
			if (i.browserLeft === true && a?.health) this.options.setBrowserHealth(e, {
				...a.health,
				inCall: false,
				micMuted: void 0,
				manualAction: void 0,
				speechReady: false,
				speechBlockedReason: void 0,
				speechBlockedMessage: void 0
			});
			if (i.complete) {
				this.#m(e.id);
				if (i.unpublished) this.#e.delete(e.id);
			}
			return {
				found: true,
				session: e,
				...i.browserLeft === void 0 ? {} : { browserLeft: i.browserLeft }
			};
		} finally {
			if (r) this.#s.retire(e.id);
		}
	}
	#f(e, t) {
		return `${e}:${this.options.normalizeMeetingUrlForReuse(t) ?? t}`;
	}
	#p(e, t) {
		if (t.stop) this.#n.addStop(e.id, t.stop);
		if (e.state !== "active") return;
		if (t.speak) this.#i.set(e.id, t.speak);
		if (t.getHealth) this.#a.set(e.id, t.getHealth);
	}
	#m(e) {
		this.#i.delete(e);
		this.#a.delete(e);
	}
	#h(e) {
		const t = this.options.getBrowser(e);
		return Boolean(this.options.isBrowserTransport(e.transport) && t?.launched);
	}
	#g(e) {
		return evaluateMeetingSpeechReadiness({
			browser: this.options.getBrowser(e),
			managedBrowser: this.#h(e),
			speech: this.options.messages.speech,
			talkBack: this.options.isTalkBackMode(e.mode)
		});
	}
	#_(e, t) {
		e.notes = [...e.notes.filter((e) => e !== t), t];
	}
};
//#endregion
//#region src/meeting-bot/session-factory.ts
function createMeetingSession(e) {
	const { config: t, createdAt: n, platform: r, resolved: i } = e;
	return {
		id: `${r.session.idPrefix}_${randomUUID()}`,
		...i,
		state: "active",
		createdAt: n,
		updatedAt: n,
		participantIdentity: r.session.participantIdentity(i.transport),
		realtime: {
			enabled: i.mode === "agent" || i.mode === "bidi",
			strategy: i.mode === "bidi" ? "bidi" : "agent",
			provider: i.mode === "bidi" ? t.realtime.voiceProvider ?? t.realtime.provider : void 0,
			model: i.mode === "bidi" ? t.realtime.model : void 0,
			transcriptionProvider: i.mode === "agent" ? t.realtime.transcriptionProvider ?? t.realtime.provider : void 0,
			toolPolicy: t.realtime.toolPolicy
		},
		notes: []
	};
}
//#endregion
//#region src/meeting-bot/browser-act-lock.ts
const browserActLock = new KeyedAsyncQueue();
const BROWSER_ACT_TIMEOUT_MESSAGE = "Meeting browser operation timed out waiting for browser tab control.";
async function runMeetingBrowserAct(e) {
	const t = Math.floor(e.deadline - performance.now());
	if (t <= 0) throw new Error(BROWSER_ACT_TIMEOUT_MESSAGE);
	const { promise: n, resolve: r } = createDeferredCore();
	const i = browserActLock.enqueue(e.targetId, async () => {
		const t = Math.floor(e.deadline - performance.now());
		if (t <= 0) throw new Error(BROWSER_ACT_TIMEOUT_MESSAGE);
		r();
		return await e.operation(t);
	});
	i.catch(() => void 0);
	await raceWithTimeout(n, t, () => {
		throw new Error(BROWSER_ACT_TIMEOUT_MESSAGE);
	});
	return await i;
}
function evaluateMeetingBrowser(e) {
	return runMeetingBrowserAct({
		deadline: e.deadline,
		targetId: e.targetId,
		operation: (t) => e.callBrowser({
			method: "POST",
			path: "/act",
			body: {
				kind: "evaluate",
				targetId: e.targetId,
				fn: e.script()
			},
			timeoutMs: t
		})
	});
}
//#endregion
//#region src/meeting-bot/browser-navigation-errors.ts
function isMeetingBrowserTransientNavigationError(e) {
	return /execution context was destroyed.*navigation|cannot find context with specified id/i.test(coerceErrorMessage(e));
}
//#endregion
//#region src/meeting-bot/browser-request.ts
function asMeetingBrowserTabs(e) {
	const t = e && typeof e === "object" ? e : {};
	return Array.isArray(t.tabs) ? t.tabs : [];
}
function readMeetingBrowserTab(e) {
	return e && typeof e === "object" ? e : void 0;
}
function resolveBrowserGatewayTimeoutMs(e) {
	return addTimerTimeoutGraceMs(e) ?? 1;
}
async function callLocalBrowserRequest(e) {
	return await callGatewayFromCli("browser.request", {
		json: true,
		timeout: String(resolveBrowserGatewayTimeoutMs(e.timeoutMs))
	}, {
		method: e.method,
		path: e.path,
		body: e.body,
		timeoutMs: e.timeoutMs
	}, { progress: false });
}
async function resolveLocalMeetingBrowserRequest(e) {
	if (!await e.gateway.isAvailable()) return callLocalBrowserRequest;
	return async (t) => await e.gateway.request("browser.request", {
		method: t.method,
		path: t.path,
		body: t.body,
		timeoutMs: t.timeoutMs
	}, {
		timeoutMs: resolveBrowserGatewayTimeoutMs(t.timeoutMs),
		scopes: ["operator.admin"]
	});
}
//#endregion
//#region src/meeting-bot/browser-controller.ts
function mergeBrowserNotes(e, t) {
	if (!e || t.length === 0) return e;
	return {
		...e,
		notes: uniqueStrings([...e.notes ?? [], ...t])
	};
}
function applyMeetingManualAction(e, t) {
	return e && t ? {
		...e,
		manualAction: {
			reason: t.reason,
			message: t.message
		}
	} : e;
}
async function prepareMeetingBrowserTab(e) {
	const t = e.adapter.browser.permissions({
		allowMicrophone: e.allowMicrophone,
		meetingUrl: e.meetingUrl
	});
	if (!t) return e.adapter.browser.permissionNotes({ allowMicrophone: e.allowMicrophone });
	try {
		const n = await e.callBrowser({
			method: "POST",
			path: "/permissions/grant",
			body: {
				origin: t.origin,
				permissions: t.permissions,
				optionalPermissions: t.optionalPermissions,
				targetId: e.targetId,
				timeoutMs: Math.min(e.timeoutMs, 5e3)
			},
			timeoutMs: Math.min(e.timeoutMs, 5e3)
		});
		return e.adapter.browser.permissionNotes({
			allowMicrophone: e.allowMicrophone,
			result: n
		});
	} catch (t) {
		return e.adapter.browser.permissionNotes({
			allowMicrophone: e.allowMicrophone,
			error: t
		});
	}
}
async function openMeetingWithBrowser(e) {
	if (!e.config.launch) return { launched: false };
	const t = Math.max(1e3, e.config.joinTimeoutMs);
	let n;
	let r;
	let i = e.session;
	let a = false;
	if (e.config.reuseExistingTab) {
		const a = asMeetingBrowserTabs(await e.callBrowser({
			method: "GET",
			path: "/tabs",
			timeoutMs: Math.min(t, 5e3)
		})).filter((t) => e.adapter.urls.isRecoverableTab(t, e.session.url));
		const o = e.adapter.urls.accountHint(e.session.url);
		r = a.find((t) => e.adapter.urls.isPreferredJoinUrl(t.url) && (!o || e.adapter.urls.accountHint(t.url) === o));
		if (!r && !e.adapter.urls.accountHint(e.session.url)) {
			const t = a.find((e) => e.url)?.url;
			if (t) i = {
				...e.session,
				url: t
			};
		}
		n = r?.targetId;
		if (r && n) await e.callBrowser({
			method: "POST",
			path: "/tabs/focus",
			body: { targetId: n },
			timeoutMs: Math.min(t, 5e3)
		});
	}
	if (!n) {
		r = readMeetingBrowserTab(await e.callBrowser({
			method: "POST",
			path: "/tabs/open",
			body: { url: e.adapter.urls.buildJoinUrl(i) },
			timeoutMs: t
		}));
		n = r?.targetId;
		a = Boolean(n);
	}
	if (!n) return {
		launched: true,
		browser: {
			status: "browser-control",
			notes: [`Browser proxy opened ${e.adapter.browserLabel} but did not return a targetId.`],
			browserUrl: r?.url,
			browserTitle: r?.title
		}
	};
	const o = {
		targetId: n,
		openedByPlugin: a
	};
	const s = e.adapter.browser.allowsMicrophone(e.session.mode);
	const c = await prepareMeetingBrowserTab({
		adapter: e.adapter,
		allowMicrophone: s,
		callBrowser: e.callBrowser,
		meetingUrl: e.session.url,
		targetId: n,
		timeoutMs: t
	});
	const l = performance.now() + Math.max(0, e.config.waitForInCallMs);
	let u = {
		status: "browser-control",
		browserUrl: r?.url,
		browserTitle: r?.title,
		notes: c
	};
	let d = true;
	do {
		try {
			const r = d;
			d = false;
			const i = Math.min(t, 1e4);
			const a = await evaluateMeetingBrowser({
				callBrowser: e.callBrowser,
				deadline: performance.now() + i,
				targetId: n,
				script: () => e.adapter.browser.buildStatusJoinScript({
					...e.session,
					allowSessionAdoption: r,
					autoJoin: e.config.autoJoin,
					captureCaptions: e.session.captureCaptions ?? e.adapter.browser.captions.enabled(e.session.mode),
					guestName: e.config.guestName,
					waitForInCallMs: e.config.waitForInCallMs
				})
			});
			u = mergeBrowserNotes(e.adapter.browser.parseStatus(a) ?? u, c);
			const l = u ? e.adapter.browser.classifyManualAction(u) : void 0;
			u = applyMeetingManualAction(u, l);
			const f = u ? e.adapter.browser.shouldRetryJoinStatus?.(u) === true : false;
			if (!f && u?.inCall === true && u.manualAction === void 0 && (!s || u.micMuted !== true)) return {
				launched: true,
				browser: u,
				tab: o
			};
			if (!f && u?.manualAction) return {
				launched: true,
				browser: u,
				tab: o
			};
		} catch (t) {
			if (isMeetingBrowserTransientNavigationError(t) && performance.now() < l) u = mergeBrowserNotes(u, [`${e.adapter.browserLabel} navigated while joining; retrying browser inspection.`]);
			else {
				const n = e.adapter.browser.browserControlUnavailable(t);
				u = {
					...u,
					inCall: false,
					manualAction: {
						reason: n.reason,
						message: n.message
					},
					notes: [...c, `Browser control could not inspect or auto-join ${e.adapter.browserLabel}: ${coerceErrorMessage(t)}`]
				};
				break;
			}
		}
		const r = l - performance.now();
		if (r > 0) await sleep(Math.min(750, r));
	} while (performance.now() < l);
	return {
		launched: true,
		browser: u,
		tab: o
	};
}
function findRecoverableTab(e) {
	const t = e.tabs.filter((t) => e.adapter.urls.isRecoverableTab(t, e.requestedMeetingUrl));
	if (!e.requestedMeetingUrl) {
		const n = t.filter((t) => e.adapter.urls.normalizeForReuse(t.url));
		return n.find((t) => e.adapter.urls.isPreferredJoinUrl(t.url)) ?? n[0] ?? t[0];
	}
	const n = e.adapter.urls.accountHint(e.requestedMeetingUrl);
	const r = n ? t.filter((t) => e.adapter.urls.accountHint(t.url) === n) : t;
	return r.find((t) => e.adapter.urls.isPreferredJoinUrl(t.url)) ?? r[0];
}
async function recoverMeetingBrowserTab(e) {
	const t = Math.max(1e3, e.config.joinTimeoutMs);
	const n = e.timeoutMs === void 0 ? t : Math.max(1, Math.min(t, e.timeoutMs));
	const r = e.timeoutMs === void 0 ? void 0 : performance.now() + n;
	const i = asMeetingBrowserTabs(await e.callBrowser({
		method: "GET",
		path: "/tabs",
		timeoutMs: r === void 0 ? Math.min(n, 5e3) : Math.min(Math.max(1, Math.floor(r - performance.now())), 5e3)
	}));
	const a = e.trackedTargetId ? i.find((t) => t.targetId === e.trackedTargetId) : void 0;
	const o = Boolean(e.adapter.urls.normalizeForReuse(a?.url));
	const s = e.adapter.urls.isSameMeeting(e.trackedMeetingUrl, e.requestedMeetingUrl);
	const c = e.adapter.urls.isSameMeeting(a?.url, e.requestedMeetingUrl);
	const l = (a && s && (!o || c) ? a : void 0) ?? findRecoverableTab({
		adapter: e.adapter,
		tabs: i,
		requestedMeetingUrl: e.requestedMeetingUrl
	});
	const u = l?.targetId;
	if (!l || !u) return {
		found: false,
		tab: l,
		message: e.requestedMeetingUrl ? `No existing ${e.adapter.browserLabel} tab matched ${e.requestedMeetingUrl}.` : `No existing ${e.adapter.browserLabel} tab found ${e.locationLabel}.`
	};
	const d = e.adapter.browser.allowsMicrophone(e.mode);
	const f = r === void 0 ? n : Math.floor(r - performance.now());
	if (f <= 0) throw new Error("Meeting browser recovery timed out.");
	await e.callBrowser({
		method: "POST",
		path: "/tabs/focus",
		body: { targetId: u },
		timeoutMs: Math.min(f, 5e3)
	});
	const p = e.adapter.urls.localeAction(l);
	if (p) return {
		found: true,
		targetId: u,
		tab: l,
		browser: {
			status: "browser-control",
			browserUrl: l.url,
			browserTitle: l.title,
			manualAction: {
				reason: p.reason,
				message: p.message
			}
		},
		message: p.message
	};
	const m = e.readOnly ? [] : await prepareMeetingBrowserTab({
		adapter: e.adapter,
		allowMicrophone: d,
		callBrowser: e.callBrowser,
		meetingUrl: e.requestedMeetingUrl ?? l.url ?? "",
		targetId: u,
		timeoutMs: r === void 0 ? n : Math.max(1, Math.floor(r - performance.now()))
	});
	const h = [];
	const g = r ?? performance.now() + Math.min(n, 1e4);
	let _ = e.allowSessionAdoption ?? false;
	let v;
	for (;;) try {
		const t = _;
		_ = false;
		v = await evaluateMeetingBrowser({
			callBrowser: e.callBrowser,
			deadline: g,
			targetId: u,
			script: () => e.adapter.browser.buildStatusJoinScript({
				allowSessionAdoption: t,
				meetingSessionId: e.meetingSessionId ?? "",
				mode: e.mode,
				url: e.requestedMeetingUrl ?? l.url ?? "",
				autoJoin: e.autoJoin ?? false,
				captureCaptions: e.captureCaptions ?? e.adapter.browser.captions.enabled(e.mode),
				guestName: e.config.guestName,
				readOnly: e.readOnly,
				waitForInCallMs: e.config.waitForInCallMs
			})
		});
		break;
	} catch (t) {
		const n = g - performance.now();
		if (!isMeetingBrowserTransientNavigationError(t) || n <= 0) throw t;
		h.push(`${e.adapter.browserLabel} navigated while recovering; retrying browser inspection.`);
		await sleep(Math.min(250, n));
		if (performance.now() >= g) throw t;
	}
	const y = mergeBrowserNotes(e.adapter.browser.parseStatus(v) ?? {
		status: "browser-control",
		browserUrl: l.url,
		browserTitle: l.title
	}, [...m, ...h]);
	const b = y ? e.adapter.browser.classifyManualAction(y) : void 0;
	const x = applyMeetingManualAction(y, b);
	return {
		found: true,
		targetId: u,
		tab: l,
		browser: x,
		message: b?.message ?? (x?.inCall ? `Existing ${e.adapter.browserLabel} tab is in-call.` : `Existing ${e.adapter.browserLabel} tab focused.`)
	};
}
//#endregion
//#region src/meeting-bot/browser-session-control.ts
async function leaveMeetingInPage(e) {
	const t = performance.now() + e.timeoutMs;
	let n = false;
	let r = false;
	do {
		const i = Math.floor(t - performance.now());
		if (i <= 0) throw new Error("Meeting browser leave timed out.");
		const a = await e.callBrowser({
			method: "POST",
			path: "/act",
			body: {
				kind: "evaluate",
				targetId: e.targetId,
				fn: e.adapter.browser.buildSessionLeaveScript?.({
					leaveInitiated: n,
					meetingSessionId: e.meetingSessionId ?? "",
					meetingUrl: e.meetingUrl
				}) ?? e.adapter.browser.buildLeaveScript(e.meetingUrl)
			},
			timeoutMs: i
		});
		const o = e.adapter.browser.parseLeaveResult(a);
		n ||= o.leaveAction === "leave";
		if (o.sessionMatched === false) {
			const e = n && o.sessionConflict !== true;
			if (o.departed || !e) return {
				departed: e ? o.departed : false,
				clickedLeave: n,
				ownershipRetained: e,
				sessionConflict: o.sessionConflict,
				sessionMatched: false,
				urlMatched: o.urlMatched
			};
			r = true;
		}
		if (o.departed || o.urlMatched !== true) return {
			departed: o.departed,
			clickedLeave: n,
			...r && o.sessionConflict !== true ? { ownershipRetained: true } : {},
			urlMatched: o.urlMatched
		};
		if (!o.leaveAction && !n) return {
			departed: false,
			clickedLeave: n,
			urlMatched: true
		};
		if (!o.leaveAction) await sleep(100);
	} while (performance.now() < t);
	return {
		departed: false,
		clickedLeave: n,
		...r ? {
			ownershipRetained: true,
			sessionMatched: false
		} : {},
		urlMatched: true
	};
}
async function leaveMeetingWithBrowser(e) {
	if (!e.launch) return {
		left: false,
		note: "Browser leave skipped because chrome.launch is disabled."
	};
	const t = Math.min(Math.max(1e3, e.timeoutMs), 5e3);
	const { targetId: n, openedByPlugin: r } = e.tab;
	try {
		if (!asMeetingBrowserTabs(await e.callBrowser({
			method: "GET",
			path: "/tabs",
			timeoutMs: t
		})).find((e) => e.targetId === n)) return {
			left: true,
			note: `${e.adapter.browserLabel} tab is already closed.`
		};
		let i;
		let a = false;
		try {
			const o = await runMeetingBrowserAct({
				deadline: performance.now() + t,
				targetId: n,
				operation: async (t) => {
					const i = performance.now() + t;
					const a = r ? Math.min(1e3, Math.max(250, Math.floor(t / 4))) : 0;
					const o = await leaveMeetingInPage({
						adapter: e.adapter,
						callBrowser: e.callBrowser,
						meetingSessionId: e.meetingSessionId,
						meetingUrl: e.meetingUrl,
						targetId: n,
						timeoutMs: Math.max(1, t - a)
					});
					if (!(r && (o.urlMatched === true || o.departed) && (o.sessionMatched !== false || o.ownershipRetained === true))) return {
						leaveResult: o,
						tabClosed: false
					};
					const s = Math.floor(i - performance.now());
					if (s <= 0) throw new Error("Meeting browser leave timed out before the tab could close.");
					await e.callBrowser({
						method: "DELETE",
						path: `/tabs/${n}`,
						timeoutMs: s
					});
					return {
						leaveResult: o,
						tabClosed: true
					};
				}
			});
			i = o.leaveResult;
			a = o.tabClosed;
		} catch (t) {
			return {
				left: false,
				note: `Browser control could not verify the ${e.adapter.browserLabel} tab before leaving: ${coerceErrorMessage(t)}`
			};
		}
		if (i.urlMatched === false) return {
			left: true,
			note: `${e.adapter.browserLabel} tab moved away from this session; left its current page untouched.`
		};
		if (i.sessionMatched === false && i.ownershipRetained !== true) {
			if (i.sessionConflict !== true) return {
				left: false,
				note: `Browser control could not verify that the ${e.adapter.browserLabel} tab still belongs to this OpenClaw meeting session.`
			};
			return {
				left: true,
				note: `${e.adapter.browserLabel} tab belongs to another OpenClaw meeting session; left its current call untouched.`
			};
		}
		if (i.urlMatched !== true && !i.departed) return {
			left: false,
			note: "Browser control could not verify that the tracked tab still showed this meeting."
		};
		const { clickedLeave: o, departed: s } = i;
		return {
			left: r ? a : s,
			note: r ? o ? `Clicked ${e.adapter.browserLabel}'s Leave call button and closed the ${e.adapter.browserLabel} tab.` : `Closed the ${e.adapter.browserLabel} tab to leave the meeting (Leave call button was not found).` : s ? `Clicked ${e.adapter.browserLabel}'s Leave call button; kept the reused browser tab open.` : o ? `Clicked ${e.adapter.browserLabel}'s Leave call button, but could not verify departure; leave it manually.` : `Could not find ${e.adapter.browserLabel}'s Leave call button in the reused browser tab; leave it manually.`
		};
	} catch (t) {
		return {
			left: false,
			note: `Browser control could not leave the ${e.adapter.browserLabel} tab: ${coerceErrorMessage(t)}`
		};
	}
}
async function readMeetingTranscriptWithBrowser(e) {
	const t = await evaluateMeetingBrowser({
		callBrowser: e.callBrowser,
		deadline: performance.now() + Math.max(1, e.timeoutMs),
		targetId: e.tab.targetId,
		script: () => e.adapter.browser.captions.buildTranscriptScript({
			finalize: e.finalize,
			meetingSessionId: e.meetingSessionId,
			meetingUrl: e.meetingUrl
		})
	});
	const n = e.adapter.browser.captions.parseTranscript(t);
	if (n.urlMatched === false) throw new Error(`The tracked ${e.adapter.browserLabel} tab no longer shows this session's meeting URL.`);
	if (n.sessionMatched === false) throw new Error(`The tracked ${e.adapter.browserLabel} tab now belongs to another OpenClaw meeting session.`);
	return {
		droppedLines: n.droppedLines,
		...n.epoch ? { epoch: n.epoch } : {},
		lines: n.lines,
		...n.pendingLines ? { pendingLines: n.pendingLines } : {}
	};
}
//#endregion
//#region src/meeting-bot/browser-node.ts
function matchesRequestedNode(e, t) {
	return [
		e.nodeId,
		e.displayName,
		e.remoteIp
	].some((e) => e === t);
}
function formatNodeLabel(e) {
	const t = [
		e.displayName,
		e.nodeId,
		e.remoteIp
	].filter(Boolean);
	return t.length > 0 ? t.join(" / ") : "unknown node";
}
function describeNodeUsabilityIssues(e, t) {
	const n = Array.isArray(e.commands) ? e.commands : [];
	const r = Array.isArray(e.caps) ? e.caps : [];
	const i = [];
	if (e.connected !== true) i.push("offline");
	if (!n.includes(t.nodeCommandName)) i.push(`missing ${t.nodeCommandName}`);
	if (!n.includes("browser.proxy") && !r.includes("browser")) i.push("missing browser.proxy/browser capability");
	return i;
}
async function listMeetingNodes(e, t, n) {
	try {
		return n ? await e.nodes.list(n) : await e.nodes.list();
	} catch (e) {
		throw new Error(`${t.displayName} node inventory unavailable`, { cause: e });
	}
}
async function resolveMeetingBrowserNodeInfo(e) {
	const t = e.requestedNode?.trim();
	if (t) {
		const n = (await listMeetingNodes(e.runtime, e.adapter)).nodes.filter((e) => matchesRequestedNode(e, t));
		if (n.length > 1) throw new Error(`Configured ${e.adapter.displayName} node ${t} is ambiguous (${n.length} matches). Pin ${e.adapter.nodeConfigPath} to a unique node id, display name, or remote IP.`);
		const [r] = n;
		if (!r) throw new Error(`Configured ${e.adapter.displayName} node ${t} was not found. Run \`openclaw nodes status\` and start or approve the Chrome node.`);
		const i = describeNodeUsabilityIssues(r, e.adapter);
		if (i.length === 0) return r;
		throw new Error(`Configured ${e.adapter.displayName} node ${t} is not usable (${formatNodeLabel(r)}): ${i.join("; ")}. Start or reinstall \`openclaw node run\` on that Chrome host, approve pairing, and allow ${e.adapter.nodeCommandName} plus browser.proxy.`);
	}
	const n = (await listMeetingNodes(e.runtime, e.adapter, { connected: true })).nodes.filter((t) => describeNodeUsabilityIssues(t, e.adapter).length === 0);
	const [r] = n;
	if (!r) throw new Error(`No connected ${e.adapter.displayName}-capable node with browser proxy. Run \`openclaw node run\` on the Chrome host with browser proxy enabled, approve pairing, and allow ${e.adapter.nodeCommandName} plus browser.proxy.`);
	if (n.length === 1) return r;
	throw new Error(`Multiple ${e.adapter.displayName}-capable nodes connected. Set ${e.adapter.nodeConfigPath}.`);
}
async function resolveMeetingBrowserNode(e) {
	const t = await resolveMeetingBrowserNodeInfo(e);
	if (!t.nodeId) throw new Error(`${e.adapter.displayName} node did not include a node id.`);
	return t.nodeId;
}
function unwrapNodeInvokePayload(e, t) {
	const n = e && typeof e === "object" ? e : {};
	if (typeof n.payloadJSON === "string" && n.payloadJSON.trim()) try {
		return JSON.parse(n.payloadJSON);
	} catch (e) {
		throw new Error(`${t.displayName} browser proxy returned malformed payloadJSON.`, { cause: e });
	}
	if ("payload" in n) return n.payload;
	return e;
}
function parseBrowserProxyResult(e, t) {
	const n = unwrapNodeInvokePayload(e, t);
	const r = n && typeof n === "object" ? n : void 0;
	if (!r || !("result" in r)) throw new Error(`${t.displayName} browser proxy returned an invalid result.`);
	return r.result;
}
async function callMeetingBrowserProxyOnNode(e) {
	return parseBrowserProxyResult(await e.runtime.nodes.invoke({
		nodeId: e.nodeId,
		command: "browser.proxy",
		params: {
			method: e.method,
			path: e.path,
			body: e.body,
			timeoutMs: e.timeoutMs
		},
		timeoutMs: addTimerTimeoutGraceMs(e.timeoutMs) ?? 1,
		scopes: ["operator.admin"]
	}), e.adapter);
}
//#endregion
//#region src/meeting-bot/meeting-modes.ts
function isMeetingTalkBackMode(e) {
	return e === "agent" || e === "bidi";
}
function isMeetingRealtimeRouteReady(e, t) {
	return isMeetingTalkBackMode(e) && t?.inCall === true && t.micMuted === false && t.audioInputRouted === true && t.audioOutputRouted === true && t.manualAction === void 0;
}
//#endregion
//#region src/meeting-bot/browser-adapter-options.ts
function createMeetingBrowserAdapterOptions(e) {
	const { scripts: t, manualActionReasonPrefix: n } = e;
	const r = e.transcriptDisplayName ?? e.displayName;
	return {
		browser: {
			buildAudioCaptureScript: t.audioCapture,
			allowsMicrophone: isMeetingTalkBackMode,
			buildStatusJoinScript: (e) => t.status({
				allowMicrophone: isMeetingTalkBackMode(e.mode),
				allowSessionAdoption: e.allowSessionAdoption,
				autoJoin: e.autoJoin,
				captureCaptions: e.captureCaptions,
				guestName: e.guestName,
				meetingSessionId: e.meetingSessionId || void 0,
				meetingUrl: e.url,
				readOnly: e.readOnly,
				waitForInCallMs: e.waitForInCallMs
			}),
			shouldRetryJoinStatus: (t) => t.inCall === true && (t.manualAction?.reason === `${n}-audio-choice-required` && t.audioInputRouted === true && t.audioOutputRouteRetryable === true || e.retryCaptions && t.manualAction === void 0 && t.captionCaptureRequested === true && t.captioning !== true),
			browserControlUnavailable: () => ({
				category: "browser-control-unavailable",
				reason: "browser-control-unavailable",
				message: e.unavailableMessage
			}),
			buildLeaveScript: (e) => t.leave({
				leaveInitiated: false,
				meetingSessionId: "",
				meetingUrl: e
			}),
			buildSessionLeaveScript: t.leave,
			captions: {
				enabled: () => true,
				buildTranscriptScript: ({ finalize: e, meetingSessionId: n, meetingUrl: r }) => t.transcript(r, n, e)
			},
			permissions: ({ allowMicrophone: t, meetingUrl: n }) => {
				const r = e.origin(n);
				return t && r ? {
					origin: r,
					permissions: ["audioCapture"],
					optionalPermissions: ["speakerSelection"]
				} : void 0;
			}
		},
		parsing: {
			classifyManualActionReason: (t) => {
				if (t === "browser-control-unavailable") return t;
				if (e.admissionReasons?.includes(t)) return "admission-required";
				return [
					"login-required",
					"admission-required",
					"permission-required",
					"audio-choice-required",
					"session-conflict"
				].find((e) => t === `${n}-${e}`) ?? "custom";
			},
			displayName: e.displayName,
			invalidTranscriptMessage: `${r} transcript payload is invalid.`,
			malformedStatusMessage: `${r} browser status JSON is malformed.`,
			malformedTranscriptMessage: `${r} transcript JSON is malformed.`,
			...e.statusFields ? { statusFields: e.statusFields } : {}
		}
	};
}
//#endregion
//#region src/meeting-bot/chrome-node-result.ts
/** Unwraps the node.invoke envelope while keeping result validation transport-generic. */
function parseMeetingChromeNodeResult(e, t) {
	const n = e && typeof e === "object" && "payload" in e ? e.payload : e;
	if (!n || typeof n !== "object") throw new Error(t);
	return n;
}
//#endregion
//#region src/meeting-bot/realtime-browser-audio-transport.ts
async function createBrowserMeetingRealtimeAudioTransport(e) {
	const { buildCaptureScript: t, targetId: n } = e;
	if (e.hasConfiguredInputCommand || !t) return e.nativeTransport;
	if (!n) throw new Error("Meeting browser audio capture requires its tracked tab.");
	const r = randomUUID();
	let i = false;
	let a = false;
	let o = false;
	let s;
	let c;
	let l;
	const u = captureCurrentPluginBackgroundRunner();
	const callCapture = (a) => runMeetingBrowserAct({
		deadline: performance.now() + 5e3,
		targetId: n,
		operation: async (o) => {
			if (i && a !== "stop") return { closed: true };
			const s = await e.callBrowser({
				method: "POST",
				path: "/act",
				timeoutMs: o,
				body: {
					kind: "evaluate",
					targetId: n,
					fn: t({
						action: a,
						captureId: r,
						meetingSessionId: e.meetingSessionId,
						meetingUrl: e.meetingUrl
					})
				}
			});
			const c = asOptionalRecord(s)?.result;
			const l = typeof c === "string" ? asOptionalRecord(JSON.parse(c)) : void 0;
			if (!l || l.captureId !== r) throw new Error("Meeting browser returned an invalid audio capture response.");
			return l;
		}
	});
	const stop = () => {
		c ??= (async () => {
			i = true;
			clearTimeout(l);
			await Promise.all([e.nativeTransport.stop(), u(() => callCapture("stop")).catch((t) => {
				e.logger.warn(`Meeting browser audio cleanup failed: ${formatErrorMessage(t)}`);
			})]);
		})();
		return c;
	};
	const fail = (t) => {
		if (i || o) return;
		o = true;
		if (t) e.logger.warn(`Meeting browser audio capture failed: ${formatErrorMessage(t)}`);
		stop().catch((t) => {
			e.logger.warn(`Meeting audio cleanup failed: ${formatErrorMessage(t)}`);
		});
		s?.();
	};
	e.nativeTransport.onFatal(() => fail());
	try {
		const e = await callCapture("start");
		if (i || e.isolated !== true) throw new Error("Meeting browser could not isolate remote playback from its virtual microphone.");
	} catch (e) {
		await stop();
		throw e;
	}
	return {
		inputAudioIsolated: true,
		onFatal(e) {
			s = e;
			if (o) e();
		},
		startInput(t) {
			if (a) throw new Error("audio input transport already started");
			a = true;
			e.nativeTransport.startInput(() => {});
			const pull = async () => {
				if (i) return;
				try {
					const n = await u(() => callCapture("pull"));
					if (i) return;
					if (n.closed === true || n.isolated !== true) {
						fail(/* @__PURE__ */ new Error("Meeting browser audio capture lost its session."));
						return;
					}
					if (typeof n.base64 === "string" && n.base64) {
						if (n.base64.length > 65536) throw new Error("Meeting browser audio exceeded its input buffer.");
						const r = decodeMeetingAudioBase64(n.base64, "meeting browser audio");
						if (r.length % 2 !== 0) throw new Error("Meeting browser returned incomplete PCM samples.");
						t(e.audioFormat === "pcm16-24khz" ? r : convertPcmToMulaw8k(r, 24e3));
					}
					if (!i) l = setTimeout(() => void pull(), 50);
				} catch (e) {
					fail(e);
				}
			};
			pull();
		},
		beginOutput: () => e.nativeTransport.beginOutput?.(),
		writeOutput: (t) => i ? Promise.resolve() : e.nativeTransport.writeOutput(t),
		clearOutput: () => i ? Promise.resolve() : e.nativeTransport.clearOutput(),
		...e.nativeTransport.startBargeInMonitor ? { startBargeInMonitor: (t) => {
			if (!i) e.nativeTransport.startBargeInMonitor?.(t);
		} } : {},
		getHealth: () => e.nativeTransport.getHealth?.() ?? {},
		stop,
		dispose: stop
	};
}
//#endregion
//#region src/meeting-bot/chrome-transport.ts
function createMeetingChromeTransportWithAudioPolicy(e, t) {
	async function openOrRecoverMeeting(t) {
		const n = t.mode === "transcribe" || resolveTranscriptsConfig(t.fullConfig.transcripts).enabled;
		if (t.config.chrome.launch) return await openMeetingWithBrowser({
			adapter: e.platform,
			callBrowser: t.callBrowser,
			config: t.config.chrome,
			session: {
				captureCaptions: n,
				meetingSessionId: t.meetingSessionId,
				mode: t.mode,
				url: t.url
			}
		});
		const r = await recoverMeetingBrowserTab({
			adapter: e.platform,
			allowSessionAdoption: true,
			autoJoin: t.config.chrome.autoJoin,
			callBrowser: t.callBrowser,
			captureCaptions: n,
			config: t.config.chrome,
			locationLabel: t.locationLabel,
			meetingSessionId: t.meetingSessionId,
			mode: t.mode,
			requestedMeetingUrl: t.url,
			trackedMeetingUrl: t.url,
			trackedTargetId: t.trackedTargetId
		});
		return {
			launched: false,
			browser: r.browser,
			tab: r.targetId ? {
				targetId: r.targetId,
				openedByPlugin: false
			} : void 0
		};
	}
	async function rollbackBrowserJoin(t) {
		if (!t.tab) return;
		if (e.startupFailurePolicy === "owned" && (!t.config.chrome.launch || !t.tab.openedByPlugin)) return;
		const n = await leaveMeetingWithBrowser({
			adapter: e.platform,
			callBrowser: t.callBrowser,
			launch: true,
			meetingSessionId: t.meetingSessionId,
			meetingUrl: t.url,
			tab: t.tab,
			timeoutMs: t.config.chrome.joinTimeoutMs
		}).catch((e) => ({
			left: false,
			note: e instanceof Error ? e.message : String(e)
		}));
		if (!n.left) t.logger.warn(`${e.platform.logScope} browser rollback after realtime startup failure did not complete: ${n.note}`);
	}
	async function prepareAudioRuntime(e) {
		const t = resolveMeetingAudioRuntimeForFormat({
			backend: e.config.chrome.audioBackend,
			bufferBytes: e.config.chrome.audioBufferBytes,
			format: e.config.chrome.audioFormat,
			inputCommand: e.config.chrome.audioInputCommandOverride,
			outputCommand: e.config.chrome.audioOutputCommandOverride
		});
		await ensureMeetingAudioBackend({
			backend: t.backend,
			timeoutMs: e.timeoutMs,
			run: async (t, n) => {
				const r = await e.runtime.system.runCommandWithTimeout(t, { timeoutMs: n });
				return {
					...r,
					code: r.code ?? 1
				};
			}
		});
		return t;
	}
	async function startRealtimeEngine(t, n, r) {
		const i = e.runtime.createBindings({
			platform: e.platform,
			...t
		});
		const a = {
			config: t.config,
			fullConfig: t.fullConfig,
			runtime: t.runtime,
			meetingSessionId: t.meetingSessionId,
			requesterSessionKey: t.requesterSessionKey,
			...r ? { logPrefix: "node" } : {},
			transport: n,
			logger: t.logger
		};
		if (t.mode === "agent") return await e.runtime.startAgentRealtimeEngine({
			platform: i.platform,
			...a,
			consultAgent: i.consultAgent
		});
		return await e.runtime.startRealtimeEngine({
			...a,
			config: {
				...t.config,
				realtime: {
					...t.config.realtime,
					strategy: "bidi"
				}
			},
			...i,
			...r ? {
				talkSessionId: `${e.platform.id}:${t.meetingSessionId}:${r.bridgeId}:node-realtime`,
				talkContext: r
			} : {}
		});
	}
	async function startLocalAudioBridge(n) {
		if (!e.isTalkBackMode(n.mode)) return;
		if (t.external) {
			if (n.config.chrome.audioBridgeCommand) {
				if (n.mode === "agent") throw new Error("Chrome agent mode requires chrome.audioInputCommand and chrome.audioOutputCommand so OpenClaw can run STT and regular TTS directly.");
				const e = await n.runtime.system.runCommandWithTimeout(n.config.chrome.audioBridgeCommand, { timeoutMs: n.config.chrome.joinTimeoutMs });
				if (e.code !== 0) throw new Error(`failed to start Chrome audio bridge: ${e.stderr || e.stdout || e.code}`);
				return t.external();
			}
			if (!n.config.chrome.audioInputCommand || !n.config.chrome.audioOutputCommand) throw new Error("Chrome talk-back mode requires chrome.audioInputCommand and chrome.audioOutputCommand, or chrome.audioBridgeCommand for an external bridge.");
		}
		let r = e.runtime.createLocalAudioTransport({
			inputCommand: n.audio.inputCommand,
			outputCommand: n.audio.outputCommand,
			audioFormat: n.config.chrome.audioFormat,
			bargeInInputCommand: n.config.chrome.bargeInInputCommand,
			bargeInRmsThreshold: n.config.chrome.bargeInRmsThreshold,
			bargeInPeakThreshold: n.config.chrome.bargeInPeakThreshold,
			bargeInCooldownMs: n.config.chrome.bargeInCooldownMs,
			logger: n.logger,
			logScope: e.platform.logScope
		});
		try {
			r = await captureBrowserAudio(n, r, n.callBrowser, n.tab);
			const e = await startRealtimeEngine(n, r);
			return t.local(e, n.audio);
		} catch (t) {
			await r.dispose().catch((t) => {
				n.logger.warn(`${e.platform.logScope} audio transport cleanup after realtime startup failure did not complete: ${formatErrorMessage(t)}`);
			});
			throw t;
		}
	}
	function captureBrowserAudio(t, n, r, i) {
		return createBrowserMeetingRealtimeAudioTransport({
			...t,
			nativeTransport: n,
			callBrowser: r,
			hasConfiguredInputCommand: t.config.chrome.audioInputCommandOverride !== void 0,
			buildCaptureScript: e.platform.browser.buildAudioCaptureScript?.bind(e.platform.browser),
			meetingUrl: t.url,
			targetId: i?.targetId,
			audioFormat: t.config.chrome.audioFormat
		});
	}
	async function launchInChrome(n) {
		const r = e.isTalkBackMode(n.mode) ? await prepareAudioRuntime({
			runtime: n.runtime,
			config: n.config,
			timeoutMs: Math.min(n.config.chrome.joinTimeoutMs, 1e4)
		}) : void 0;
		if (r && t.external && n.config.chrome.audioBridgeHealthCommand) {
			const e = await n.runtime.system.runCommandWithTimeout(n.config.chrome.audioBridgeHealthCommand, { timeoutMs: n.config.chrome.joinTimeoutMs });
			if (e.code !== 0) throw new Error(`Chrome audio bridge health check failed: ${e.stderr || e.stdout || e.code}`);
		}
		const i = await resolveLocalMeetingBrowserRequest(n.runtime);
		const a = await openOrRecoverMeeting({
			...n,
			callBrowser: i,
			locationLabel: "in local Chrome"
		});
		if (!e.isRealtimeRouteReady(n.mode, a.browser)) return {
			...a,
			audioBackend: r?.backend
		};
		try {
			return {
				...a,
				audioBackend: r?.backend,
				audioBridge: r ? await startLocalAudioBridge({
					...n,
					audio: r,
					callBrowser: i,
					tab: a.tab
				}) : void 0
			};
		} catch (t) {
			if (!e.preserveTrackedBrowserOnEngineFailure || !n.trackedTargetId) await rollbackBrowserJoin({
				...n,
				callBrowser: i,
				tab: a.tab
			});
			throw t;
		}
	}
	const parseNodeResult = (t) => parseMeetingChromeNodeResult(t, `${e.meetingLabel} node returned an invalid start result.`);
	async function resolveBrowserRequest(t, n) {
		return n ? async (r) => await callMeetingBrowserProxyOnNode({
			runtime: t,
			nodeId: n,
			adapter: e.browserNodeAdapter,
			...r
		}) : await resolveLocalMeetingBrowserRequest(t);
	}
	async function launchOnNode(n) {
		const r = await resolveMeetingBrowserNode({
			adapter: e.browserNodeAdapter,
			runtime: n.runtime,
			requestedNode: n.config.chromeNode.node
		});
		const i = {
			audioBackend: n.config.chrome.audioBackend,
			audioFormat: n.config.chrome.audioFormat,
			audioBufferBytes: n.config.chrome.audioBufferBytes,
			...n.config.chrome.audioInputCommandOverride ? { audioInputCommand: n.config.chrome.audioInputCommandOverride } : {},
			...n.config.chrome.audioOutputCommandOverride ? { audioOutputCommand: n.config.chrome.audioOutputCommandOverride } : {}
		};
		try {
			await n.runtime.nodes.invoke({
				nodeId: r,
				command: e.nodeCommandName,
				params: {
					action: "stopByUrl",
					url: n.url,
					mode: n.mode
				},
				timeoutMs: 5e3
			});
		} catch (t) {
			n.logger.debug?.(`${e.platform.logScope} node bridge cleanup ignored: ${t instanceof Error ? t.message : String(t)}`);
		}
		const a = e.isTalkBackMode(n.mode) ? parseNodeResult(await n.runtime.nodes.invoke({
			nodeId: r,
			command: e.nodeCommandName,
			params: {
				action: "setup",
				...i
			},
			timeoutMs: 12e3
		})) : void 0;
		const o = await resolveBrowserRequest(n.runtime, r);
		const s = await openOrRecoverMeeting({
			...n,
			callBrowser: o,
			locationLabel: "on the selected Chrome node"
		});
		if (!e.isRealtimeRouteReady(n.mode, s.browser)) return {
			nodeId: r,
			launched: s.launched,
			audioBackend: a?.audioBackend,
			browser: s.browser,
			tab: s.tab
		};
		let c;
		let l;
		try {
			const u = await n.runtime.nodes.invoke({
				nodeId: r,
				command: e.nodeCommandName,
				params: {
					action: "start",
					url: n.url,
					mode: n.mode,
					launch: false,
					browserProfile: n.config.chrome.browserProfile,
					joinTimeoutMs: n.config.chrome.joinTimeoutMs,
					...i,
					...t.external ? {
						audioBridgeCommand: n.config.chrome.audioBridgeCommand,
						audioBridgeHealthCommand: n.config.chrome.audioBridgeHealthCommand
					} : {}
				},
				timeoutMs: addTimerTimeoutGraceMs(n.config.chrome.joinTimeoutMs) ?? 1
			});
			const d = parseNodeResult(u);
			if (d.audioBridge?.type !== "node-command-pair") return {
				nodeId: r,
				launched: s.launched || d.launched === true,
				audioBackend: d.audioBackend ?? a?.audioBackend,
				browser: s.browser ?? d.browser,
				tab: s.tab,
				...t.external && d.audioBridge?.type === "external-command" ? { audioBridge: t.external() } : {}
			};
			if (!d.bridgeId) throw new Error(`${e.meetingLabel} node did not return an audio bridge id.`);
			c = d.bridgeId;
			let f = e.runtime.createNodeAudioTransport({
				runtime: n.runtime,
				nodeId: r,
				bridgeId: d.bridgeId,
				audioFormat: n.config.chrome.audioFormat,
				logger: n.logger,
				commandName: e.nodeCommandName,
				logScope: e.platform.logScope,
				logPrefix: n.mode === "agent" ? "node agent" : "node"
			});
			l = f;
			Reflect.set(f, Symbol.for("openclaw.internal.meeting-node-output-generation.v1"), d.audioBridge.outputGeneration === true);
			f = await captureBrowserAudio(n, f, o, s.tab);
			l = f;
			const p = await startRealtimeEngine(n, f, {
				nodeId: r,
				bridgeId: d.bridgeId
			});
			return {
				nodeId: r,
				launched: s.launched || d.launched === true,
				audioBackend: d.audioBackend ?? a?.audioBackend,
				audioBridge: {
					type: "node-command-pair",
					nodeId: r,
					bridgeId: d.bridgeId,
					...p
				},
				browser: s.browser ?? d.browser,
				tab: s.tab
			};
		} catch (t) {
			await l?.dispose().catch((t) => {
				n.logger.warn(`${e.platform.logScope} node audio transport cleanup after realtime startup failure did not complete: ${formatErrorMessage(t)}`);
			});
			if (e.startupFailurePolicy === "owned") {
				if (!l && c) await n.runtime.nodes.invoke({
					nodeId: r,
					command: e.nodeCommandName,
					params: {
						action: "stop",
						bridgeId: c
					},
					timeoutMs: 5e3
				}).catch((t) => {
					n.logger.warn(`${e.platform.logScope} node bridge cleanup after realtime startup failure did not complete: ${formatErrorMessage(t)}`);
				});
			} else await n.runtime.nodes.invoke({
				nodeId: r,
				command: e.nodeCommandName,
				params: {
					action: "stopByUrl",
					url: n.url,
					mode: n.mode
				},
				timeoutMs: 5e3
			}).catch((t) => {
				n.logger.warn(`${e.platform.logScope} node meeting cleanup after realtime startup failure did not complete: ${formatErrorMessage(t)}`);
			});
			if (!e.preserveTrackedBrowserOnEngineFailure || !n.trackedTargetId) await rollbackBrowserJoin({
				...n,
				callBrowser: o,
				tab: s.tab
			});
			throw t;
		}
	}
	async function recoverCurrentTab(t) {
		const n = t.transport === "chrome-node" ? t.nodeId ?? await resolveMeetingBrowserNode({
			adapter: e.browserNodeAdapter,
			runtime: t.runtime,
			requestedNode: t.config.chromeNode.node
		}) : void 0;
		return {
			transport: t.transport,
			...n ? { nodeId: n } : {},
			...await recoverMeetingBrowserTab({
				adapter: e.platform,
				callBrowser: await resolveBrowserRequest(t.runtime, n),
				captureCaptions: t.mode === "transcribe" || resolveTranscriptsConfig(t.fullConfig?.transcripts).enabled,
				config: t.config.chrome,
				locationLabel: n ? "on the selected Chrome node" : "in local Chrome",
				meetingSessionId: t.meetingSessionId,
				mode: t.mode,
				readOnly: t.readOnly,
				requestedMeetingUrl: t.url,
				trackedMeetingUrl: t.trackedMeetingUrl,
				trackedTargetId: t.trackedTargetId,
				timeoutMs: t.timeoutMs
			})
		};
	}
	async function leaveInBrowser(t) {
		return await leaveMeetingWithBrowser({
			adapter: e.platform,
			callBrowser: await resolveBrowserRequest(t.runtime, t.nodeId),
			launch: t.config.chrome.launch || !t.tab.openedByPlugin,
			meetingSessionId: t.meetingSessionId,
			meetingUrl: t.meetingUrl,
			tab: t.tab,
			timeoutMs: t.config.chrome.joinTimeoutMs
		});
	}
	async function readTranscript(t) {
		return await readMeetingTranscriptWithBrowser({
			adapter: e.platform,
			callBrowser: await resolveBrowserRequest(t.runtime, t.nodeId),
			finalize: t.finalize === true,
			meetingUrl: t.meetingUrl,
			meetingSessionId: t.meetingSessionId,
			tab: t.tab,
			timeoutMs: Math.min(Math.max(1e3, t.config.chrome.joinTimeoutMs), 1e4)
		});
	}
	return {
		assertAudioDeviceAvailable: async (e) => {
			await prepareAudioRuntime(e);
		},
		launchInChrome,
		launchOnNode,
		leaveInBrowser,
		readTranscript,
		recoverCurrentTab
	};
}
function createMeetingChromeTransport(e) {
	return createMeetingChromeTransportWithAudioPolicy(e, { local: (e) => ({
		type: "command-pair",
		...e
	}) });
}
function createMeetingChromeTransportWithExternalAudio(e) {
	return createMeetingChromeTransportWithAudioPolicy(e, {
		local: (e, t) => ({
			type: "command-pair",
			inputCommand: t.inputCommand,
			outputCommand: t.outputCommand,
			...e
		}),
		external: () => ({ type: "external-command" })
	});
}
//#endregion
//#region src/meeting-bot/node-audio-config.ts
const DEFAULT_NODE_AUDIO_BUFFER_BYTES = 4096;
const DEFAULT_NODE_AUDIO_FORMAT = "pcm16-24khz";
function readMeetingNodeCommand(e) {
	if (!Array.isArray(e)) return;
	const t = e.filter((e) => typeof e === "string" && e.length > 0);
	return t.length > 0 ? t : void 0;
}
function readAudioBackend(e) {
	if (e === void 0) return;
	if (e === "auto" || e === "blackhole-2ch" || e === "pipewire-pulse") return e;
	throw new Error("audioBackend must be auto, blackhole-2ch, or pipewire-pulse");
}
function readAudioFormat(e) {
	if (e === void 0) return;
	if (e === "pcm16-24khz" || e === "g711-ulaw-8khz") return e;
	throw new Error("audioFormat must be pcm16-24khz or g711-ulaw-8khz");
}
function readAudioBufferBytes(e) {
	if (e === void 0) return;
	if (typeof e === "number" && Number.isSafeInteger(e) && e > 0) return e;
	throw new Error("audioBufferBytes must be a positive safe integer");
}
/** Resolves untrusted node params before any backend or command process starts. */
async function prepareMeetingNodeAudio(e, t, n) {
	const r = n.defaultAudio;
	const i = {
		backend: readAudioBackend(e.audioBackend) ?? r?.backend ?? "auto",
		bufferBytes: readAudioBufferBytes(e.audioBufferBytes) ?? r?.bufferBytes ?? DEFAULT_NODE_AUDIO_BUFFER_BYTES,
		format: readAudioFormat(e.audioFormat) ?? r?.format ?? DEFAULT_NODE_AUDIO_FORMAT,
		inputCommand: readMeetingNodeCommand(e.audioInputCommand),
		outputCommand: readMeetingNodeCommand(e.audioOutputCommand),
		bargeInInputCommand: readMeetingNodeCommand(e.bargeInInputCommand)
	};
	if (n.prepareAudio) return await n.prepareAudio(i, t);
	await n.assertAudioAvailable(t);
	return {
		backend: "blackhole-2ch",
		deviceLabel: "BlackHole 2ch",
		inputCommand: i.inputCommand ?? [...n.defaultAudioInputCommand],
		outputCommand: i.outputCommand ?? [...n.defaultAudioOutputCommand]
	};
}
//#endregion
//#region src/meeting-bot/node-audio-pull-waiters.ts
/** Internal pull-wait ownership used by the node-host long poll. */
var MeetingNodeAudioPullWaiters = class {
	#e = /* @__PURE__ */ new Set();
	get size() {
		return this.#e.size;
	}
	async wait(e) {
		const { promise: t, resolve: n } = createDeferredCore();
		this.#e.add(n);
		try {
			await raceWithTimeout(t, e, () => {});
		} finally {
			this.#e.delete(n);
		}
	}
	wake() {
		const e = [...this.#e];
		this.#e.clear();
		for (const t of e) t();
	}
};
//#endregion
//#region src/meeting-bot/node-host.ts
const NODE_BRIDGE_TERMINATION_GRACE_MS = 2e3;
const NODE_BRIDGE_INPUT_DRAIN_MS = 3e3;
const NODE_BRIDGE_TERMINAL_RETENTION_MS = 5e3;
const NODE_BRIDGE_MAX_QUEUED_INPUT_CHUNKS = 200;
const NODE_BRIDGE_MAX_QUEUED_INPUT_BYTES = 1048576;
function readOutputGeneration(e) {
	if (e === void 0) return;
	if (typeof e === "number" && Number.isSafeInteger(e) && e >= 0) return e;
	throw new Error("outputGeneration must be a non-negative integer");
}
function runCommandWithTimeout(e, t, n) {
	const { command: r, args: i } = splitCommandArgv(e, "command");
	const a = spawnSync(r, i, {
		encoding: "utf8",
		timeout: t
	});
	const o = a.error ? formatErrorMessage(a.error) : "";
	const s = o && a.stderr ? `${o}: ${a.stderr}` : o || a.stderr || (a.signal ? `terminated by ${a.signal}` : "");
	const c = typeof a.status === "number" ? a.status : 1;
	if (c !== 0) throw new Error(`${n}: ${s || a.stdout || c}`);
}
function waitForInputDrain(e) {
	if (!e || e.readableEnded || e.destroyed) return Promise.resolve();
	return new Promise((t) => {
		let n = false;
		const finish = () => {
			if (n) return;
			n = true;
			clearTimeout(r);
			e.off("end", finish);
			e.off("close", finish);
			t();
		};
		const r = setTimeout(finish, NODE_BRIDGE_INPUT_DRAIN_MS);
		r.unref?.();
		e.once("end", finish);
		e.once("close", finish);
		if (e.readableEnded || e.destroyed) finish();
	});
}
function createMeetingNodeHost(e) {
	const t = /* @__PURE__ */ new Map();
	const n = /* @__PURE__ */ new Set();
	const trackProcess = (e) => {
		n.add(e);
		e.once("close", () => n.delete(e));
		return e;
	};
	const deleteSession = (e) => {
		if (e.terminalEvictionTimer) {
			clearTimeout(e.terminalEvictionTimer);
			e.terminalEvictionTimer = void 0;
		}
		e.chunks.length = 0;
		e.queuedInputBytes = 0;
		if (t.get(e.id) === e) t.delete(e.id);
	};
	const armTerminalEviction = (e) => {
		if (e.terminalEvictionTimer) clearTimeout(e.terminalEvictionTimer);
		e.terminalEvictionTimer = setTimeout(() => {
			deleteSession(e);
		}, NODE_BRIDGE_TERMINAL_RETENTION_MS);
		e.terminalEvictionTimer.unref?.();
	};
	const stopSession = (e, t = {}) => {
		e.stopping = true;
		if (t.discardQueuedAudio) {
			e.discardQueuedAudioOnStop = true;
			if (e.terminalEvictionTimer) {
				clearTimeout(e.terminalEvictionTimer);
				e.terminalEvictionTimer = void 0;
			}
			e.chunks.length = 0;
			e.queuedInputBytes = 0;
			e.closed = true;
			e.waiters.wake();
		}
		e.outputOwner.release();
		if (e.stopPromise) return e.stopPromise;
		const n = e.discardQueuedAudioOnStop ? Promise.resolve() : waitForInputDrain(e.input?.stdout).then(() => {
			if (e.discardQueuedAudioOnStop || e.closed) return;
			e.closed = true;
			e.waiters.wake();
		});
		e.stopPromise = Promise.all([e.outputOwner.stop(e.input, e.output), n]).then(() => {
			if (e.discardQueuedAudioOnStop) {
				deleteSession(e);
				return;
			}
			armTerminalEviction(e);
		});
		return e.stopPromise;
	};
	const attachOutputProcessHandlers = (e, t) => {
		const stopIfCurrent = () => {
			if (e.output === t) stopSession(e);
		};
		t.on("exit", stopIfCurrent);
		t.on("error", stopIfCurrent);
		t.stdin?.on("error", stopIfCurrent);
		t.stderr?.on("error", stopIfCurrent);
	};
	const startOutputProcess = (e) => trackProcess(spawn(e.command, e.args, { stdio: [
		"pipe",
		"ignore",
		"pipe"
	] }));
	const startCommandPair = (n) => {
		const r = splitCommandArgv(n.inputCommand, "audio command");
		const i = splitCommandArgv(n.outputCommand, "audio command");
		const a = {
			id: `${e.bridgeIdPrefix}${randomUUID()}`,
			url: n.url,
			mode: n.mode,
			outputCommand: i,
			chunks: [],
			queuedInputBytes: 0,
			waiters: new MeetingNodeAudioPullWaiters(),
			closed: false,
			createdAt: (/* @__PURE__ */ new Date()).toISOString(),
			lastInputBytes: 0,
			lastOutputBytes: 0,
			clearCount: 0,
			outputGeneration: 0,
			outputOwner: new MeetingOutputProcessOwner(NODE_BRIDGE_TERMINATION_GRACE_MS),
			stopping: false,
			discardQueuedAudioOnStop: false
		};
		const o = startOutputProcess(i);
		let s;
		try {
			s = trackProcess(spawn(r.command, r.args, { stdio: [
				"ignore",
				"pipe",
				"pipe"
			] }));
		} catch (e) {
			o.on("error", () => {});
			terminateMeetingBridgeProcess(o, { graceMs: NODE_BRIDGE_TERMINATION_GRACE_MS });
			throw e;
		}
		a.input = s;
		a.output = o;
		s.stdout?.on("data", (e) => {
			if (a.discardQueuedAudioOnStop || a.closed) return;
			const t = Buffer.isBuffer(e) ? e : Buffer.from(e);
			a.lastInputAt = (/* @__PURE__ */ new Date()).toISOString();
			a.lastInputBytes += t.byteLength;
			const n = copyOwnedBuffer(t.subarray(Math.max(0, t.byteLength - NODE_BRIDGE_MAX_QUEUED_INPUT_BYTES)));
			a.chunks.push(n);
			a.queuedInputBytes += n.byteLength;
			while (a.chunks.length > NODE_BRIDGE_MAX_QUEUED_INPUT_CHUNKS || a.queuedInputBytes > NODE_BRIDGE_MAX_QUEUED_INPUT_BYTES) {
				const e = a.chunks.shift();
				if (e) a.queuedInputBytes -= e.byteLength;
			}
			if (!a.stopPromise) a.waiters.wake();
		});
		const stop = () => {
			stopSession(a);
		};
		s.on("exit", stop);
		s.on("error", stop);
		s.stdout?.on("error", stop);
		s.stderr?.on("error", stop);
		attachOutputProcessHandlers(a, o);
		t.set(a.id, a);
		return a;
	};
	const pullAudio = async (e) => {
		const n = readNonEmptyStringPreservingWhitespace(e.bridgeId);
		if (!n) throw new Error("bridgeId required");
		const r = t.get(n);
		if (!r) throw new Error(`unknown bridgeId: ${n}`);
		const i = Math.min(asPositiveFiniteNumber(e.timeoutMs) ?? 250, 2e3);
		if (r.chunks.length === 0 && !r.closed) await r.waiters.wait(i);
		const a = r.chunks.shift();
		if (a) r.queuedInputBytes -= a.byteLength;
		const o = r.closed && r.chunks.length === 0;
		if (o) deleteSession(r);
		else if (a && r.closed && r.terminalEvictionTimer) armTerminalEviction(r);
		return {
			bridgeId: n,
			closed: o,
			base64: a ? a.toString("base64") : void 0
		};
	};
	const staleOutputResult = (e) => ({
		bridgeId: e.id,
		ok: true,
		stale: true
	});
	const pushAudio = async (e) => {
		const n = readNonEmptyStringPreservingWhitespace(e.bridgeId);
		const r = readNonEmptyStringPreservingWhitespace(e.base64);
		if (!n || !r) throw new Error("bridgeId and base64 required");
		const i = t.get(n);
		if (!i || i.stopping || i.closed) throw new Error(`bridge is not open: ${n}`);
		const a = readOutputGeneration(e.outputGeneration);
		if (a !== void 0 && a !== i.outputGeneration) return staleOutputResult(i);
		const o = i.output;
		if (!o?.stdin) throw new Error(`bridge is not open: ${n}`);
		const s = decodeMeetingAudioBase64(r, "pushAudio");
		try {
			await i.outputOwner.write(o, o.stdin, s);
		} catch {
			if (i.output !== o || a !== void 0 && a !== i.outputGeneration) return staleOutputResult(i);
			stopSession(i);
			throw new Error(`bridge is not open: ${n}`);
		}
		if (i.stopping || i.closed || i.output !== o || a !== void 0 && a !== i.outputGeneration) return staleOutputResult(i);
		i.lastOutputAt = (/* @__PURE__ */ new Date()).toISOString();
		i.lastOutputBytes += s.byteLength;
		return {
			bridgeId: n,
			ok: true
		};
	};
	const clearAudio = (e) => {
		const n = readNonEmptyStringPreservingWhitespace(e.bridgeId);
		if (!n) throw new Error("bridgeId required");
		const r = t.get(n);
		if (!r || r.stopping || r.closed) throw new Error(`bridge is not open: ${n}`);
		const i = readOutputGeneration(e.outputGeneration);
		if (i !== void 0 && i <= r.outputGeneration) return staleOutputResult(r);
		if (i === void 0 && r.outputGeneration >= Number.MAX_SAFE_INTEGER) throw new Error("outputGeneration exhausted");
		const a = i ?? r.outputGeneration + 1;
		const o = r.output;
		const s = startOutputProcess(r.outputCommand);
		r.output = s;
		r.outputGeneration = a;
		attachOutputProcessHandlers(r, s);
		r.outputOwner.release(o);
		r.clearCount += 1;
		r.lastClearAt = (/* @__PURE__ */ new Date()).toISOString();
		r.outputOwner.retire(o);
		return {
			bridgeId: n,
			ok: true,
			clearCount: r.clearCount
		};
	};
	const startBrowser = async (n) => {
		const r = e.normalizeUrl(n.url);
		const i = asPositiveFiniteNumber(n.joinTimeoutMs) ?? 3e4;
		const a = readNonEmptyStringPreservingWhitespace(n.mode);
		let o;
		let s;
		let c;
		if (a && e.talkBackModes.has(a)) {
			o = await prepareMeetingNodeAudio(n, Math.min(i, 1e4), e);
			const t = readMeetingNodeCommand(n.audioBridgeHealthCommand);
			if (t) runCommandWithTimeout(t, i, "Chrome audio bridge health check failed");
			const l = readMeetingNodeCommand(n.audioBridgeCommand);
			if (l) {
				if (a === e.agentMode) throw new Error("Chrome agent mode requires audioInputCommand and audioOutputCommand so OpenClaw can run STT and regular TTS directly.");
				runCommandWithTimeout(l, i, "failed to start Chrome audio bridge");
				c = { type: "external-command" };
			} else {
				s = startCommandPair({
					inputCommand: o.inputCommand,
					outputCommand: o.outputCommand,
					url: r,
					mode: a
				}).id;
				c = {
					type: "node-command-pair",
					outputGeneration: true
				};
			}
		}
		if (n.launch !== false) {
			const a = [
				"open",
				"-a",
				e.browser.application,
				r
			];
			const o = readNonEmptyStringPreservingWhitespace(n.browserProfile);
			if (o) a.push(...e.browser.buildProfileArgs(o));
			try {
				runCommandWithTimeout(a, i, `failed to launch Chrome for ${e.browserLabel}`);
			} catch (e) {
				if (s) {
					const e = t.get(s);
					if (e) stopSession(e, { discardQueuedAudio: true });
				}
				throw e;
			}
		}
		return {
			launched: n.launch !== false,
			audioBackend: o?.backend,
			audioDeviceLabel: o?.deviceLabel,
			bridgeId: s,
			audioBridge: c,
			browser: n.launch !== false ? {
				status: e.browser.openedStatus,
				browserUrl: r,
				notes: e.browser.openedNotes
			} : void 0
		};
	};
	const bridgeStatus = (e) => {
		const n = readNonEmptyStringPreservingWhitespace(e.bridgeId);
		const r = n ? t.get(n) : void 0;
		return { bridge: r ? {
			bridgeId: n,
			closed: r.stopping || r.closed,
			createdAt: r.createdAt,
			lastInputAt: r.lastInputAt,
			lastOutputAt: r.lastOutputAt,
			lastClearAt: r.lastClearAt,
			lastInputBytes: r.lastInputBytes,
			lastOutputBytes: r.lastOutputBytes,
			clearCount: r.clearCount,
			queuedInputChunks: r.chunks.length
		} : n ? {
			bridgeId: n,
			closed: true
		} : void 0 };
	};
	const summarizeSession = (e) => ({
		bridgeId: e.id,
		url: e.url,
		mode: e.mode,
		closed: e.closed,
		createdAt: e.createdAt,
		lastInputAt: e.lastInputAt,
		lastOutputAt: e.lastOutputAt,
		lastInputBytes: e.lastInputBytes,
		lastOutputBytes: e.lastOutputBytes
	});
	const listSessions = (n) => {
		const r = e.normalizeMeetingKey(readNonEmptyStringPreservingWhitespace(n.url));
		const i = readNonEmptyStringPreservingWhitespace(n.mode);
		return { bridges: [...t.values()].filter((e) => !e.stopping && !e.closed).filter((t) => !r || e.normalizeMeetingKey(t.url) === r).filter((e) => !i || e.mode === i).map(summarizeSession) };
	};
	const stopSessionsByUrl = async (n) => {
		const r = e.normalizeMeetingKey(readNonEmptyStringPreservingWhitespace(n.url));
		if (!r) throw new Error("url required");
		const i = readNonEmptyStringPreservingWhitespace(n.mode);
		const a = readNonEmptyStringPreservingWhitespace(n.exceptBridgeId);
		let o = 0;
		const s = [];
		for (const [n, c] of t) {
			if (a && n === a) continue;
			if (e.normalizeMeetingKey(c.url) !== r) continue;
			if (i && c.mode !== i) continue;
			const t = c.stopping || c.closed;
			s.push(stopSession(c, { discardQueuedAudio: true }));
			if (!t) o += 1;
		}
		await Promise.all(s);
		return {
			ok: true,
			stopped: o
		};
	};
	const stopBrowser = async (e) => {
		const n = readNonEmptyStringPreservingWhitespace(e.bridgeId);
		const r = n ? t.get(n) : void 0;
		if (!r) return {
			ok: true,
			stopped: false
		};
		const i = r.stopping || r.closed;
		await stopSession(r, { discardQueuedAudio: true });
		return {
			ok: true,
			stopped: !i
		};
	};
	const r = new Map(Object.entries({
		setup: async (t) => {
			const n = await prepareMeetingNodeAudio(t, 1e4, e);
			return {
				ok: true,
				audioBackend: n.backend,
				audioDeviceLabel: n.deviceLabel
			};
		},
		start: startBrowser,
		status: bridgeStatus,
		list: listSessions,
		stopByUrl: stopSessionsByUrl,
		pullAudio,
		pushAudio,
		clearAudio,
		stop: stopBrowser
	}));
	return {
		hasActiveWork: () => t.size > 0 || n.size > 0,
		async handleCommand(t) {
			let n = {};
			if (t) try {
				n = JSON.parse(t);
			} catch {
				throw new Error(`${e.displayName} node host received malformed params JSON.`);
			}
			const i = asOptionalRecord(n) ?? {};
			const a = r.get(readNonEmptyStringPreservingWhitespace(i.action) ?? "");
			if (!a) throw new Error(`unsupported ${e.commandName} action`);
			return JSON.stringify(await a(i));
		}
	};
}
//#endregion
//#region src/meeting-bot/configured-node-host.ts
function isSpawnSyncTimeout(e) {
	return e instanceof Error && "code" in e && e.code === "ETIMEDOUT";
}
function createMeetingConfiguredNodeHost(e) {
	const runCommand = (t, n) => {
		const [r, ...i] = t;
		if (!r) return {
			code: 1,
			stderr: "command must not be empty"
		};
		const a = spawnSync(r, i, {
			encoding: "utf8",
			timeout: n
		});
		if (isSpawnSyncTimeout(a.error)) throw new Error(`${e.meetingLabel} audio prerequisite check timed out on the node.`);
		const o = [
			a.error ? coerceErrorMessage(a.error) : "",
			a.stderr,
			a.signal ? `terminated by ${a.signal}` : ""
		].filter(Boolean).join(": ");
		return {
			code: typeof a.status === "number" ? a.status : 1,
			stdout: a.stdout ?? "",
			stderr: o
		};
	};
	const probeCommand = (e, t) => {
		const n = spawnSync("/bin/sh", [
			"-lc",
			"command -v \"$1\" >/dev/null 2>&1",
			"sh",
			e
		], {
			encoding: "utf8",
			timeout: t
		});
		if (isSpawnSyncTimeout(n.error)) return "timed-out";
		return n.status === 0 ? "found" : "missing";
	};
	const prepareAudio = async (t, n) => {
		const r = monotonicNow() + n;
		const commandTimeout = () => {
			if (!e.sharePrerequisiteDeadline) return n;
			const t = r - monotonicNow();
			if (t <= 0) throw new Error(`${e.meetingLabel} audio prerequisite check timed out on the node.`);
			return Math.max(1, Math.floor(t));
		};
		const i = resolveMeetingAudioRuntimeForFormat({
			backend: t.backend,
			bufferBytes: t.bufferBytes,
			format: t.format,
			inputCommand: t.inputCommand,
			outputCommand: t.outputCommand
		});
		await ensureMeetingAudioBackend({
			backend: i.backend,
			run: async (e, t) => {
				return runCommand(e, Math.min(t, commandTimeout()));
			},
			timeoutMs: n
		});
		const a = new Set([
			i.inputCommand,
			i.outputCommand,
			t.bargeInInputCommand
		].flatMap((e) => e?.[0] ? [e[0]] : []));
		for (const t of a) {
			const n = probeCommand(t, commandTimeout());
			if (n === "timed-out") throw new Error(`${e.meetingLabel} audio prerequisite check timed out on the node.`);
			if (n === "missing") throw new Error(`Configured audio command not found on the node: ${t}`);
		}
		return i;
	};
	const t = createMeetingNodeHost({
		...e,
		assertAudioAvailable: async (t) => {
			await prepareAudio({
				backend: e.defaultAudio?.backend ?? "auto",
				bufferBytes: e.defaultAudio?.bufferBytes ?? 4096,
				format: e.defaultAudio?.format ?? "pcm16-24khz"
			}, t);
		},
		prepareAudio
	});
	return Object.assign(t.handleCommand, { hasActiveWork: t.hasActiveWork });
}
//#endregion
//#region src/meeting-bot/plugin-config.ts
const DEFAULT_AUDIO_BUFFER_BYTES = 4096;
const DEFAULT_AUDIO_FORMAT = "pcm16-24khz";
const DEFAULT_MODE_HELP = "Agent consults OpenClaw, bidi uses direct realtime voice, and transcribe observes only.";
const CHROME_NODE_HELP = "Node id/name/IP that owns Chrome and the native virtual-audio backend.";
function resolveMode(e) {
	const t = normalizeOptionalLowercaseString(e);
	return t === "agent" || t === "bidi" || t === "transcribe" ? t : "agent";
}
function resolveAudioFormat(e) {
	const t = normalizeOptionalLowercaseString(e)?.replaceAll("_", "-");
	return t === "g711-ulaw-8khz" ? t : DEFAULT_AUDIO_FORMAT;
}
function createMeetingPluginConfigSchema(e) {
	const t = buildMeetingConfigAudioCommands("auto", DEFAULT_AUDIO_FORMAT, DEFAULT_AUDIO_BUFFER_BYTES);
	const resolveConfig = (t) => {
		const n = asRecord(t);
		const r = asRecord(n.chrome);
		const i = asRecord(n.chromeNode);
		const a = asRecord(n.realtime);
		return {
			enabled: typeof n.enabled === "boolean" ? n.enabled : true,
			defaultMode: resolveMode(n.defaultMode),
			chrome: resolveMeetingChromeConfig(r, {
				resolveAudioFormat: () => resolveAudioFormat(r.audioFormat),
				waitForInCallMs: 6e4
			}),
			chromeNode: { node: normalizeOptionalString(i.node) },
			realtime: resolveMeetingRealtimeConfig(a, {
				instructions: e.defaultRealtimeInstructions,
				transcriptionProvider: "openai"
			})
		};
	};
	return {
		configSchema: {
			parse: resolveConfig,
			uiHints: {
				defaultMode: {
					label: "Default Mode",
					help: DEFAULT_MODE_HELP
				},
				"chrome.audioBackend": {
					label: "Chrome Audio Backend",
					help: "Auto selects BlackHole 2ch on macOS or PipeWire-Pulse on Linux."
				},
				"chrome.browserProfile": {
					label: "Chrome Profile",
					advanced: true
				},
				"chrome.guestName": { label: "Guest Name" },
				"chrome.waitForInCallMs": {
					label: "Wait For In-Call (ms)",
					advanced: true
				},
				"chrome.audioInputCommand": {
					label: "Audio Input Command",
					advanced: true
				},
				"chrome.audioOutputCommand": {
					label: "Audio Output Command",
					advanced: true
				},
				"chromeNode.node": {
					label: "Chrome Node",
					help: CHROME_NODE_HELP,
					advanced: true
				},
				"realtime.transcriptionProvider": { label: "Realtime Transcription Provider" },
				"realtime.voiceProvider": { label: "Bidi Voice Provider" },
				"realtime.model": {
					label: "Bidi Realtime Model",
					advanced: true
				},
				"realtime.instructions": {
					label: "Realtime Instructions",
					advanced: true
				},
				"realtime.introMessage": { label: "Realtime Intro Message" },
				"realtime.agentId": {
					label: "Realtime Consult Agent",
					advanced: true
				},
				"realtime.toolPolicy": {
					label: "Realtime Tool Policy",
					advanced: true
				}
			}
		},
		defaultAudioInputCommand: t.inputCommand,
		defaultAudioOutputCommand: t.outputCommand,
		resolveConfig,
		resolveGatewayOperationTimeoutMs: (t) => e.resolveGatewayOperationTimeoutMs(t)
	};
}
//#endregion
//#region src/meeting-bot/transcripts-bridge.ts
function createMeetingTranscriptSourceProvider(e) {
	return {
		id: e.id,
		aliases: e.aliases,
		name: e.name,
		sourceKinds: ["live-caption"],
		start: async (t) => await (await e.runtime()).startTranscriptSource(t),
		stop: async (t) => await (await e.runtime()).stopTranscriptSource(t)
	};
}
//#endregion
//#region src/meeting-bot/plugin-entry.ts
function readErrorDetails(e) {
	return e && typeof e === "object" && "details" in e ? e.details : void 0;
}
function createMeetingPluginEntryOptions(e) {
	const invalidRequest = (t) => {
		throw e.invalidRequest(t);
	};
	const normalizeTransport = (e) => {
		if (e === void 0) return;
		if (e === "chrome" || e === "chrome-node") return e;
		return invalidRequest("transport must be chrome or chrome-node");
	};
	const normalizeMode = (e) => {
		if (e === void 0) return;
		if (e === "agent" || e === "bidi" || e === "transcribe") return e;
		return invalidRequest("mode must be agent, bidi, or transcribe");
	};
	const requireString = (e, t) => {
		return normalizeOptionalString(e) ?? invalidRequest(`${t} required`);
	};
	const readSinceIndex = (e) => {
		try {
			return readNonNegativeIntegerParam(e, "sinceIndex");
		} catch (e) {
			return invalidRequest(formatErrorMessage(e));
		}
	};
	const keepTrustedToolContext = (t, n) => {
		const { agentId: r, requesterSessionKey: i, ...a } = t;
		const o = n?.internal?.pluginRuntimeOwnerId === e.id;
		const s = o ? normalizeOptionalString(r) : void 0;
		const c = e.normalizeRequesterSessionKey(i, o);
		return {
			...a,
			...s ? { agentId: s } : {},
			...c ? { requesterSessionKey: c } : {}
		};
	};
	const trustedToolAgentId = (e, t) => keepTrustedToolContext(e, t).agentId;
	const joinRequest = (t, n) => {
		if (!n?.allowTimeout && t.timeoutMs !== void 0) return invalidRequest("timeoutMs is supported only by testSpeech or testListen");
		try {
			return {
				url: e.normalizeUrl(requireString(t.url, "url")),
				transport: normalizeTransport(t.transport),
				mode: normalizeMode(t.mode),
				message: normalizeOptionalString(t.message),
				requesterSessionKey: normalizeOptionalString(t.requesterSessionKey),
				agentId: normalizeOptionalString(t.agentId),
				timeoutMs: readPositiveIntegerParam(t, "timeoutMs")
			};
		} catch (t) {
			if (e.isInvalidRequest(t)) throw t;
			return invalidRequest(formatErrorMessage(t));
		}
	};
	const gatewayMethod = (t) => `${e.gatewayMethodPrefix}.${t}`;
	const callGatewayFromTool = async (t) => {
		try {
			const n = e.resolveGatewayTimeoutMs(t.config);
			if (t.runtime) return await t.runtime.gateway.request(gatewayMethod(t.action), t.raw, {
				timeoutMs: n,
				scopes: ["operator.admin"]
			});
			return await callGatewayFromCli(gatewayMethod(t.action), {
				json: true,
				timeout: String(n)
			}, t.raw, {
				progress: false,
				scopes: ["operator.admin"]
			});
		} catch (e) {
			const t = readErrorDetails(e);
			if (t && typeof t === "object") return t;
			throw e;
		}
	};
	return {
		id: e.id,
		name: e.name,
		description: e.description,
		configSchema: e.configSchema,
		register(t) {
			const n = e.configSchema.parse(t.pluginConfig);
			let r = t.config.transcripts?.enabled !== false;
			let i;
			const ensureRuntime = async () => {
				if (!n.enabled) throw new Error(e.disabledMessage);
				if (!i) {
					i = e.createRuntime({
						api: t,
						config: n
					});
					await i.reconcileTranscriptPolicy?.(r);
				}
				return i;
			};
			if (e.transcriptSource) {
				t.registerService({
					id: `${e.id}-transcripts`,
					reload: { configPrefixes: ["transcripts.enabled"] },
					start: ({ config: e }) => {
						r = e.transcripts?.enabled !== false;
						return i?.reconcileTranscriptPolicy?.(r);
					},
					stop: () => {
						r = false;
						return i?.reconcileTranscriptPolicy?.(false);
					}
				});
				t.registerTranscriptSourceProvider(createMeetingTranscriptSourceProvider({
					...e.transcriptSource,
					runtime: async () => {
						const t = await ensureRuntime();
						if (!t.startTranscriptSource || !t.stopTranscriptSource) throw new Error(`${e.name} transcript source runtime is unavailable`);
						return t;
					}
				}));
			}
			const registerGatewayMethod = (n, r) => {
				t.registerGatewayMethod(`${e.gatewayMethodPrefix}.${n}`, async (t) => {
					const { respond: n } = t;
					try {
						n(true, await r(t));
					} catch (t) {
						const r = e.isInvalidRequest(t) ? ErrorCodes.INVALID_REQUEST : ErrorCodes.UNAVAILABLE;
						const i = { error: formatErrorMessage(t) };
						n(false, i, errorShape(r, i.error, { details: i }));
					}
				});
			};
			registerGatewayMethod("join", async ({ params: e, client: t }) => {
				const n = keepTrustedToolContext(asOptionalRecord(e) ?? {}, t);
				return await (await ensureRuntime()).join(joinRequest(n));
			});
			registerGatewayMethod("leave", async ({ params: e, client: t }) => {
				const n = asOptionalRecord(e) ?? {};
				const r = trustedToolAgentId(n, t);
				const i = requireString(n.sessionId, "sessionId");
				const a = await ensureRuntime();
				return r && !a.ownsSession(r, i) ? { found: false } : await a.leave(i);
			});
			registerGatewayMethod("status", async ({ params: e, client: t }) => {
				const n = asOptionalRecord(e) ?? {};
				const r = trustedToolAgentId(n, t);
				const i = await ensureRuntime();
				return r ? await i.statusForAgent(r, normalizeOptionalString(n.sessionId)) : await i.status(normalizeOptionalString(n.sessionId));
			});
			registerGatewayMethod("transcript", async ({ params: e, client: t }) => {
				const n = asOptionalRecord(e) ?? {};
				const r = requireString(n.sessionId, "sessionId");
				const i = readSinceIndex(n);
				const a = trustedToolAgentId(n, t);
				const o = await ensureRuntime();
				return a && !o.ownsSession(a, r) ? { found: false } : await o.transcript(r, i === void 0 ? {} : { sinceIndex: i });
			});
			registerGatewayMethod("speak", async ({ params: e, client: t }) => {
				const n = asOptionalRecord(e) ?? {};
				const r = requireString(n.sessionId, "sessionId");
				const i = trustedToolAgentId(n, t);
				const a = await ensureRuntime();
				return i && !a.ownsSession(i, r) ? {
					found: false,
					spoken: false
				} : await a.speak(r, normalizeOptionalString(n.message));
			});
			registerGatewayMethod("setup", async ({ params: e }) => await (await ensureRuntime()).setupStatus({
				mode: normalizeMode(e?.mode),
				transport: normalizeTransport(e?.transport)
			}));
			for (const e of ["testSpeech", "testListen"]) registerGatewayMethod(e, async ({ params: t, client: n }) => {
				const r = keepTrustedToolContext(asOptionalRecord(t) ?? {}, n);
				return await (await ensureRuntime())[e](joinRequest(r, { allowTimeout: true }));
			});
			t.registerTool((r) => ({
				name: e.toolName,
				label: e.toolLabel,
				description: e.toolDescription,
				parameters: e.toolParameters,
				async execute(i, a) {
					const o = asOptionalRecord(a) ?? {};
					const s = o.action;
					const c = normalizeOptionalString(r.sessionKey);
					const l = r.agentId ?? parseAgentSessionKey(c)?.agentId;
					const u = e.normalizeToolAgentId(l);
					try {
						if (![
							"join",
							"leave",
							"status",
							"transcript",
							"speak"
						].includes(s)) throw new Error(e.unknownActionMessage);
						const r = await e.resolveToolRuntime(t, u);
						return jsonResult(await callGatewayFromTool({
							action: s,
							config: n,
							raw: {
								...o,
								...c ? { requesterSessionKey: c } : {},
								...r && u ? { agentId: u } : {}
							},
							runtime: r
						}));
					} catch (e) {
						return jsonResult({ error: formatErrorMessage(e) });
					}
				}
			}), { name: e.toolName });
			if (e.registerNodeWhen(n)) {
				t.registerNodeHostCommand({
					command: e.nodeCommand,
					cap: e.cap,
					dangerous: true,
					handle: (t) => e.nodeHandler(t),
					hasActiveWork: e.nodeHandler.hasActiveWork
				});
				t.registerNodeInvokePolicy(e.createNodePolicy(n));
			}
			e.registerCli(t, n);
		}
	};
}
//#endregion
//#region src/meeting-bot/agent-consult.ts
function createMeetingRealtimeEngineBindings(e) {
	const t = {
		id: e.platform.id,
		provider: e.platform.id,
		lane: e.platform.id,
		...e.platform.agentConsult
	};
	return {
		platform: {
			displayName: e.platform.displayName,
			logScope: e.platform.logScope,
			sessionIdPrefix: e.platform.id
		},
		consultAgent: async (n) => await consultMeetingAgent({
			surface: t,
			config: e.fullConfig,
			runtime: e.runtime,
			logger: e.logger,
			agentId: e.config.realtime.agentId,
			toolPolicy: e.config.realtime.toolPolicy,
			...n
		}),
		tools: resolveRealtimeVoiceAgentConsultTools(e.config.realtime.toolPolicy),
		handleToolCall: async (n) => {
			const r = readMeetingRealtimeToolAbortSignal(n.session);
			const i = {
				surface: t,
				config: e.fullConfig,
				runtime: e.runtime,
				logger: e.logger,
				agentId: e.config.realtime.agentId,
				toolPolicy: e.config.realtime.toolPolicy,
				abortSignal: r,
				...n
			};
			const a = i.event.callId || i.event.itemId;
			if (i.abortSignal?.aborted) return;
			const submitError = async (e) => {
				await i.session.submitToolResult(a, { error: e });
				if (!i.abortSignal?.aborted) i.onTalkEvent({
					type: "tool.error",
					callId: a,
					payload: {
						name: i.event.name,
						error: e
					},
					final: true
				});
			};
			const o = i.strategy !== "bidi" ? `Tool "${i.event.name}" is only available in bidi realtime strategy` : i.event.name !== "openclaw_agent_consult" ? `Tool "${i.event.name}" not available` : void 0;
			if (o) {
				await submitError(o);
				return;
			}
			await (i.abortSignal?.aborted || !i.session.bridge.supportsToolResultContinuation ? void 0 : i.session.submitToolResult(a, buildRealtimeVoiceAgentConsultWorkingResponse(i.surface.workingResponseLabel), { willContinue: true }));
			if (i.abortSignal?.aborted) return;
			i.onTalkEvent({
				type: "tool.progress",
				callId: a,
				payload: {
					name: i.event.name,
					status: "working"
				}
			});
			let s;
			try {
				s = await consultMeetingAgent({
					...i,
					args: i.event.args
				});
			} catch (e) {
				if (i.abortSignal?.aborted) return;
				await submitError(formatErrorMessage(e));
				return;
			}
			if (i.abortSignal?.aborted) return;
			await i.session.submitToolResult(a, s);
			if (i.abortSignal?.aborted) return;
			i.onTalkEvent({
				type: "tool.result",
				callId: a,
				payload: {
					name: i.event.name,
					result: s
				},
				final: true
			});
		}
	};
}
async function consultMeetingAgent(e) {
	const t = e.agentId ? normalizeAgentId(e.agentId) : resolveDefaultAgentId(e.config);
	const n = normalizeOptionalString(e.requesterSessionKey) ?? `agent:${t}:main`;
	const r = `agent:${t}:subagent:${e.surface.id}:${e.meetingSessionId}`;
	return await consultRealtimeVoiceAgent({
		cfg: e.config,
		agentRuntime: e.runtime.agent,
		logger: e.logger,
		agentId: t,
		sessionKey: r,
		messageProvider: e.surface.provider,
		lane: e.surface.lane,
		runIdPrefix: `${e.surface.id}:${e.meetingSessionId}`,
		spawnedBy: n,
		contextMode: "fork",
		args: e.args,
		transcript: e.transcript,
		surface: e.surface.surface,
		userLabel: e.surface.userLabel,
		assistantLabel: e.surface.assistantLabel,
		questionSourceLabel: e.surface.questionSourceLabel,
		toolsAllow: resolveRealtimeVoiceAgentConsultToolsAllow(e.toolPolicy),
		extraSystemPrompt: e.surface.extraSystemPrompt,
		abortSignal: e.abortSignal
	});
}
//#endregion
//#region src/meeting-bot/node-invoke-policy.ts
function copyCommand(e) {
	return e && e.length > 0 ? [...e] : void 0;
}
function copyConfiguredAudio(e, t) {
	if (t.audioBackend === "auto" || t.audioBackend === "blackhole-2ch" || t.audioBackend === "pipewire-pulse") e.audioBackend = t.audioBackend;
	if (typeof t.audioBufferBytes === "number" && t.audioBufferBytes > 0) e.audioBufferBytes = t.audioBufferBytes;
	if (t.audioFormat === "pcm16-24khz" || t.audioFormat === "g711-ulaw-8khz") e.audioFormat = t.audioFormat;
	const n = "audioInputCommandOverride" in t || "audioOutputCommandOverride" in t;
	for (const r of ["audioInputCommand", "audioOutputCommand"]) {
		const i = copyCommand(t[`${r}Override`] ?? (n ? void 0 : t[r]));
		if (i) e[r] = i;
	}
	for (const n of [
		"bargeInInputCommand",
		"audioBridgeCommand",
		"audioBridgeHealthCommand"
	]) {
		const r = copyCommand(t[n]);
		if (r) e[n] = r;
	}
}
function denied(e, t) {
	return {
		ok: false,
		code: e.deniedCode,
		message: t
	};
}
function approved(e) {
	return {
		ok: true,
		params: e
	};
}
function buildStartParams(e, t) {
	let n;
	try {
		n = t.normalizeUrl(e.url);
	} catch (e) {
		return denied(t, e instanceof Error ? e.message : `${t.commandName} start requires url`);
	}
	const r = readNonEmptyStringPreservingWhitespace(e.mode);
	if (r && !t.supportedModes.has(r)) return denied(t, `${t.commandName} start mode is unsupported: ${r}`);
	const i = {
		action: "start",
		url: n,
		launch: e.launch === false ? false : t.start.launch,
		browserProfile: t.start.browserProfile,
		joinTimeoutMs: t.start.joinTimeoutMs
	};
	if (r) i.mode = r;
	copyConfiguredAudio(i, t.start);
	return approved(i);
}
function denyMissing(e, t, n) {
	return denied(e, `${e.commandName} ${t} requires ${n}`);
}
function buildForwardParams(e, t) {
	const n = readNonEmptyStringPreservingWhitespace(e.action);
	switch (n) {
		case "setup": return approved({ action: n });
		case "stop":
		case "status": {
			const t = readNonEmptyStringPreservingWhitespace(e.bridgeId);
			return approved(t ? {
				action: n,
				bridgeId: t
			} : { action: n });
		}
		case "list":
		case "stopByUrl": {
			const r = { action: n };
			const i = readNonEmptyStringPreservingWhitespace(e.url);
			const a = readNonEmptyStringPreservingWhitespace(e.mode);
			const o = n === "stopByUrl" ? readNonEmptyStringPreservingWhitespace(e.exceptBridgeId) : void 0;
			if (n === "stopByUrl" && !i) return denyMissing(t, n, "url");
			if (i) try {
				r.url = t.normalizeUrl(i);
			} catch (e) {
				return denied(t, e instanceof Error ? e.message : `${t.commandName} ${n} url`);
			}
			if (a) r.mode = a;
			if (o) r.exceptBridgeId = o;
			return approved(r);
		}
		case "pullAudio":
		case "pushAudio":
		case "clearAudio": {
			const r = { action: n };
			const i = readNonEmptyStringPreservingWhitespace(e.bridgeId);
			const a = n === "pushAudio" ? readNonEmptyStringPreservingWhitespace(e.base64) : void 0;
			if (!i) return denyMissing(t, n, "bridgeId");
			if (n === "pullAudio") {
				const t = asPositiveFiniteNumber(e.timeoutMs);
				return approved({
					action: n,
					bridgeId: i,
					...t ? { timeoutMs: t } : {}
				});
			}
			if (n === "pushAudio") {
				if (!a) return denyMissing(t, n, "base64");
				if (!isMeetingAudioBase64(a)) return denied(t, "base64 must be a valid audio payload");
			}
			r.bridgeId = i;
			if (a) r.base64 = a;
			const o = asSafeIntegerInRange(e.outputGeneration, { min: 0 });
			if (e.outputGeneration !== void 0 && o === void 0) return denied(t, "outputGeneration must be a non-negative safe integer");
			if (o !== void 0) r.outputGeneration = o;
			return approved(r);
		}
		default: return null;
	}
}
function createMeetingBrowserNodeInvokePolicy(e) {
	return {
		commands: [e.commandName],
		dangerous: true,
		async handle(t) {
			if (t.command !== e.commandName) return denied(e, `unsupported ${e.displayName} node command: ${t.command}`);
			const n = asOptionalRecord(t.params) ?? {};
			const r = readNonEmptyStringPreservingWhitespace(n.action);
			if (r === "setup" && e.useConfiguredSetupCommands) {
				const n = { action: r };
				copyConfiguredAudio(n, e.start);
				return await t.invokeNode({ params: n });
			}
			const i = r === "start" ? buildStartParams(n, e) : buildForwardParams(n, e) ?? denied(e, `unsupported ${e.commandName} action`);
			if (!i.ok) return i;
			return await t.invokeNode({ params: i.params });
		}
	};
}
//#endregion
//#region src/meeting-bot/plugin-shell.ts
function createMeetingPluginNodeHostHandler(e) {
	const t = e.platform;
	return createMeetingConfiguredNodeHost({
		...e,
		commandName: t.nodeCommandName,
		displayName: t.displayName,
		browserLabel: t.browserLabel,
		bridgeIdPrefix: `${t.session.idPrefix}_node_`,
		talkBackModes: /* @__PURE__ */ new Set(["agent", "bidi"]),
		agentMode: "agent",
		defaultAudio: {
			backend: "auto",
			bufferBytes: 4096,
			format: "pcm16-24khz"
		},
		normalizeUrl: (e) => t.urls.validateAndNormalize(e),
		normalizeMeetingKey: (e) => t.urls.normalizeForReuse(e),
		browser: {
			application: "Google Chrome",
			buildProfileArgs: (e) => ["--args", `--profile-directory=${e}`],
			openedStatus: "chrome-opened",
			openedNotes: [`${e.browserPageName} page control is handled by OpenClaw browser automation when using chrome-node.`]
		}
	});
}
function createMeetingPluginNodeInvokePolicy(e, t) {
	const n = t.platform;
	return createMeetingBrowserNodeInvokePolicy({
		commandName: n.nodeCommandName,
		displayName: n.displayName,
		deniedCode: t.deniedCode,
		supportedModes: /* @__PURE__ */ new Set([
			"agent",
			"bidi",
			"transcribe"
		]),
		normalizeUrl: (e) => n.urls.validateAndNormalize(e),
		useConfiguredSetupCommands: true,
		start: e.chrome
	});
}
function createMeetingChromeRuntimeBindings() {
	return {
		createBindings: createMeetingRealtimeEngineBindings,
		createLocalAudioTransport: createLocalMeetingRealtimeAudioTransport,
		createNodeAudioTransport: createNodeMeetingRealtimeAudioTransport,
		startAgentRealtimeEngine: startMeetingAgentRealtimeEngine,
		startRealtimeEngine: startMeetingRealtimeEngine
	};
}
function createMeetingPluginChromeTransport(e) {
	return createMeetingChromeTransport({
		...e,
		browserNodeAdapter: e.platform,
		isRealtimeRouteReady: isMeetingRealtimeRouteReady,
		isTalkBackMode: isMeetingTalkBackMode,
		nodeCommandName: e.platform.nodeCommandName
	});
}
function createMeetingPluginShellEntry(e) {
	const t = e.platform.id;
	const n = t.replaceAll("-", "");
	const r = t.replaceAll("-", "_");
	const i = createLazyRuntimeModule(() => e.cli.load());
	return createMeetingPluginEntryOptions({
		...e,
		id: t,
		name: e.platform.displayName,
		cap: t,
		description: `Join ${e.platform.displayName} as a Chrome browser guest`,
		disabledMessage: `${e.platform.displayName} plugin disabled in plugin config`,
		gatewayMethodPrefix: n,
		nodeCommand: e.platform.nodeCommandName,
		normalizeUrl: (t) => e.platform.urls.validateAndNormalize(t),
		toolDescription: `Join and manage ${e.browserGuestLabel} browser guests. Guest admission, tenant sign-in, and media permissions may require manual action in the OpenClaw Chrome profile.`,
		toolLabel: e.platform.displayName,
		toolName: r,
		transcriptSource: {
			...e.transcriptSource,
			name: e.platform.displayName
		},
		unknownActionMessage: `unknown ${r} action`,
		createRuntime: ({ api: t, config: n }) => new e.runtime({
			config: n,
			fullConfig: t.config,
			runtime: t.runtime,
			logger: t.logger
		}),
		registerCli: (t, n) => {
			t.registerCli(async ({ program: e }) => (await i())({
				program: e,
				config: n
			}), {
				commands: [e.cli.descriptor.name],
				descriptors: [e.cli.descriptor]
			});
		}
	});
}
function createMeetingPluginTypes() {
	return null;
}
//#endregion
//#region src/meeting-bot/runtime-facade.ts
const nowIso = () => (/* @__PURE__ */ new Date()).toISOString();
function createMeetingRuntimeFacade(e) {
	return class MeetingRuntimeFacade extends MeetingSessionRuntime {
		#e;
		#t = /* @__PURE__ */ new Map();
		constructor(t) {
			super({
				logger: t.logger,
				logScope: e.platform.logScope,
				formatError: formatErrorMessage,
				reuseExistingBrowserTab: t.config.chrome.reuseExistingTab,
				waitForInCallMs: t.config.chrome.waitForInCallMs,
				joinTimeoutMs: t.config.chrome.joinTimeoutMs,
				defaultSpeechInstructions: t.config.realtime.introMessage,
				transientSpeechBlockedReasons: /* @__PURE__ */ new Set([
					"not-in-call",
					"browser-unverified",
					e.messages.sessionRuntime.speech.microphoneMutedReason
				]),
				messages: e.messages.sessionRuntime,
				resolveJoin: (e) => this.#n(e),
				createSession: ({ request: n, resolved: r, createdAt: i }) => {
					const a = createMeetingSession({
						platform: e.platform,
						config: t.config,
						resolved: r,
						createdAt: i
					});
					if (n.requesterSessionKey) this.#t.set(a.id, n.requesterSessionKey);
					return a;
				},
				resolveSpeechInstructions: (e) => e.message ?? t.config.realtime.introMessage,
				isBrowserTransport: () => true,
				isTalkBackMode: (e) => e === "agent" || e === "bidi",
				isTranscribeMode: (e) => e === "transcribe",
				sameMeetingUrl: (t, n) => e.platform.urls.isSameMeeting(t, n),
				normalizeMeetingUrlForReuse: (t) => e.platform.urls.normalizeForReuse(t),
				getBrowser: (t) => t.chrome ? {
					launched: t.chrome.launched,
					nodeId: t.chrome.nodeId,
					tab: t.chrome.browserTab,
					health: t.chrome.health,
					hasAudioBridge: e.hooks?.isAudioBridgeActive?.(t) ?? Boolean(t.chrome.audioBridge)
				} : void 0,
				setBrowserTab: (e, t) => {
					if (e.chrome) e.chrome.browserTab = t;
				},
				setBrowserHealth: (e, t) => {
					if (e.chrome) e.chrome.health = t;
				},
				joinTransport: async ({ request: e, session: t, context: n }) => await this.#a(e, t, n),
				releaseBrowserTab: async (e) => await this.#d(e),
				refreshBrowserHealth: async (e, t) => await this.#l(e, t),
				refreshStatus: async (e) => await this.#c(e),
				refreshReusableSession: async (t, n) => await e.hooks?.refreshReusableSession?.(t, n, this.#r()),
				ensureRealtimeBridge: async (e) => await this.#s(e),
				captureTranscript: async (e, t) => await this.#u(e, t),
				speakViaTransport: async () => void 0,
				durableTranscripts: {
					config: t.fullConfig.transcripts,
					openclawConfig: t.fullConfig,
					...e.messages.durableTranscripts
				}
			});
			this.params = t;
			this.#e = normalizeAgentId(t.config.realtime.agentId ?? resolveDefaultAgentId(t.fullConfig));
		}
		ownsSession(e, t) {
			return this.list().some((n) => n.id === t && n.agentId === e);
		}
		async join(t) {
			try {
				return await super.join(e.hooks?.normalizeJoinRequest?.(t, this.#r()) ?? t);
			} catch (e) {
				const t = new Set(this.list().map((e) => e.id));
				for (const e of this.#t.keys()) if (!t.has(e)) this.#t.delete(e);
				throw e;
			}
		}
		async leave(e) {
			try {
				return await super.leave(e);
			} finally {
				this.#t.delete(e);
			}
		}
		async statusForAgent(e, t) {
			if (t) return this.ownsSession(e, t) ? await this.status(t) : { found: false };
			const n = this.list().filter((t) => t.agentId === e);
			await Promise.all(n.map((e) => this.status(e.id)));
			return {
				found: true,
				sessions: n
			};
		}
		async setupStatus(t) {
			return await e.probes.setupStatus({
				...this.params,
				options: t
			});
		}
		async testSpeech(t) {
			return await e.probes.testSpeech(this.#i(), t);
		}
		async testListen(t) {
			return await e.probes.testListening(this.#i(), t);
		}
		#n(t) {
			return {
				url: e.platform.urls.validateAndNormalize(t.url),
				transport: t.transport ?? (this.params.config.chromeNode.node ? "chrome-node" : "chrome"),
				mode: t.mode ?? this.params.config.defaultMode,
				agentId: normalizeAgentId(t.agentId ?? this.#e)
			};
		}
		#r() {
			return {
				deleteRequesterSessionKey: (e) => this.#t.delete(e),
				endSession: async (e, t) => {
					await super.leave(e, t);
					this.#t.delete(e);
				},
				noteSession: (e, t) => this.#p(e, t),
				refreshBrowserHealth: async (e, t) => await this.refreshBrowserHealth(e, t),
				resolvedJoin: (e) => this.#n(e)
			};
		}
		#i() {
			return {
				config: this.params.config,
				resolveAgentId: (e) => normalizeAgentId(e.agentId ?? this.#e),
				list: () => this.list(),
				join: async (e) => await this.join(e),
				isReusable: (e, t) => this.isReusableSession(e, t),
				hasHealthHandle: (e) => this.hasHealthHandle(e),
				refreshHealth: (e) => this.refreshHealth(e),
				refreshCaptionHealth: async (e, t) => await this.#l(e, { timeoutMs: t })
			};
		}
		async #a(t, n, r) {
			const i = this.#f(n.agentId);
			const a = {
				runtime: this.params.runtime,
				config: i,
				fullConfig: this.params.fullConfig,
				meetingSessionId: n.id,
				requesterSessionKey: t.requesterSessionKey,
				mode: n.mode,
				url: n.url,
				logger: this.params.logger
			};
			const o = n.transport === "chrome-node" ? await e.transport.launchOnNode(a) : await e.transport.launchInChrome(a);
			const s = o.nodeId;
			const c = r.inheritedBrowserTab({
				session: n,
				transport: n.transport,
				nodeId: s,
				meetingUrl: n.url,
				tab: o.tab
			});
			n.chrome = {
				audioBackend: o.audioBackend,
				launched: o.launched,
				nodeId: s,
				browserProfile: this.params.config.chrome.browserProfile,
				browserTab: c,
				health: o.browser
			};
			e.hooks?.validateLaunchResult?.(o);
			const l = this.#o(n, o.audioBridge);
			if (l) r.attachRuntimeHandles(n, l);
			n.notes.push(o.audioBridge ? n.transport === "chrome-node" ? e.messages.joined.node : e.messages.joined.local : n.mode === "transcribe" ? e.messages.joined.transcribe : e.messages.joined.waiting);
			this.refreshSpeechReadiness(n);
			return {};
		}
		#o(t, n) {
			if (!t.chrome || !n) return;
			t.chrome.audioBridge = {
				type: n.type,
				provider: n.providerId
			};
			e.hooks?.afterAudioBridgeAttached?.(t);
			return {
				stop: n.stop,
				speak: n.speak,
				getHealth: n.getHealth
			};
		}
		async #s(t) {
			const n = e.hooks?.isAudioBridgeActive?.(t) ?? Boolean(t.chrome?.audioBridge);
			if (t.mode !== "agent" && t.mode !== "bidi" || t.state !== "active" || !t.chrome || n || !isMeetingRealtimeRouteReady(t.mode, t.chrome.health)) return;
			if (t.chrome.audioBridge) t.chrome.audioBridge = void 0;
			const r = this.#f(t.agentId);
			const i = {
				...r,
				chrome: {
					...r.chrome,
					launch: false
				},
				chromeNode: { node: t.chrome.nodeId ?? r.chromeNode.node }
			};
			const a = {
				runtime: this.params.runtime,
				config: i,
				fullConfig: this.params.fullConfig,
				meetingSessionId: t.id,
				requesterSessionKey: this.#t.get(t.id),
				mode: t.mode,
				trackedTargetId: t.chrome.browserTab?.targetId,
				url: t.url,
				logger: this.params.logger
			};
			const o = t.transport === "chrome-node" ? await e.transport.launchOnNode(a) : await e.transport.launchInChrome(a);
			if (o.tab) {
				const e = t.chrome.browserTab;
				t.chrome.browserTab = {
					...o.tab,
					openedByPlugin: o.tab.targetId === e?.targetId ? e.openedByPlugin : o.tab.openedByPlugin
				};
			}
			if (o.browser) t.chrome.health = {
				...t.chrome.health,
				...o.browser
			};
			t.updatedAt = nowIso();
			return this.#o(t, o.audioBridge);
		}
		async #c(t) {
			await this.refreshBrowserHealth(t, {
				force: true,
				readOnly: !(e.hooks?.isAwaitingAdmission?.(t) ?? false)
			});
			await e.hooks?.afterStatusRefresh?.(t, this.#r());
		}
		async #l(t, n = {}) {
			try {
				const r = await e.transport.recoverCurrentTab({
					runtime: this.params.runtime,
					config: this.params.config,
					fullConfig: this.params.fullConfig,
					meetingSessionId: t.id,
					mode: t.mode,
					nodeId: t.chrome?.nodeId,
					readOnly: n.readOnly,
					trackedMeetingUrl: t.url,
					trackedTargetId: t.chrome?.browserTab?.targetId,
					transport: t.transport,
					timeoutMs: n.timeoutMs,
					url: t.url
				});
				if (r.found && t.chrome) {
					if (r.tab?.targetId) {
						const e = t.chrome.browserTab;
						t.chrome.browserTab = {
							targetId: r.tab.targetId,
							openedByPlugin: r.tab.targetId === e?.targetId ? e.openedByPlugin : false
						};
					}
					if (r.browser) t.chrome.health = {
						...t.chrome.health,
						...r.browser
					};
					t.updatedAt = nowIso();
				} else if (t.chrome) e.hooks?.recordBrowserRecoveryFailure?.(t, {
					kind: "missing",
					message: r.message
				});
			} catch (n) {
				const r = formatErrorMessage(n);
				const i = e.messages.browserReadinessFailed?.(r) ?? r;
				if (e.hooks?.recordBrowserRecoveryFailure) {
					this.params.logger.debug?.(`${e.platform.logScope} ${i}`);
					e.hooks.recordBrowserRecoveryFailure(t, {
						kind: "error",
						message: i
					});
				} else this.params.logger.debug?.(`${e.platform.logScope} browser readiness refresh ignored: ${formatErrorMessage(n)}`);
			}
		}
		async #u(t, n = {}) {
			await this.refreshCaptionHealth(t);
			const r = t.chrome?.browserTab;
			if (!r) return;
			return await e.transport.readTranscript({
				runtime: this.params.runtime,
				config: this.params.config,
				finalize: n.finalize,
				meetingUrl: t.url,
				meetingSessionId: t.id,
				nodeId: t.chrome?.nodeId,
				tab: r
			});
		}
		async #d(t) {
			const n = t.chrome?.browserTab;
			if (!n) {
				this.#p(t, e.messages.noTrackedTab);
				t.browserLeft = false;
				return false;
			}
			if (this.list().some((e) => e.id !== t.id && e.state === "active" && e.chrome?.browserTab?.targetId === n.targetId && e.chrome?.nodeId === t.chrome?.nodeId)) {
				this.#p(t, e.messages.sharedTab);
				return;
			}
			try {
				const r = await e.transport.leaveInBrowser({
					runtime: this.params.runtime,
					config: this.params.config,
					meetingSessionId: t.id,
					meetingUrl: t.url,
					nodeId: t.chrome?.nodeId,
					tab: n
				});
				this.#p(t, r.note);
				if (r.left && t.chrome) {
					t.chrome.browserTab = void 0;
					if (t.chrome.health) t.chrome.health = {
						...t.chrome.health,
						captioning: false,
						audioInputRouted: false,
						audioOutputRouted: false,
						providerConnected: false,
						realtimeReady: false,
						audioInputActive: false,
						audioOutputActive: false
					};
				}
				t.browserLeft = r.left;
				return r.left;
			} catch (n) {
				this.#p(t, e.messages.leaveFailed(formatErrorMessage(n)));
				t.browserLeft = false;
				return false;
			}
		}
		#f(e) {
			return this.params.config.realtime.agentId === e ? this.params.config : {
				...this.params.config,
				realtime: {
					...this.params.config.realtime,
					agentId: e
				}
			};
		}
		#p(e, t) {
			e.notes = [...e.notes.filter((e) => e !== t), t];
		}
	};
}
//#endregion
//#region src/meeting-bot/runtime-probes.ts
function resolveMeetingProbeTimeoutMs(e, t, n = (e) => new Error(e)) {
	if (e === void 0) return Math.min(Math.max(t, 1), 12e4);
	if (!Number.isFinite(e) || e <= 0) throw n("timeoutMs must be a positive number");
	return Math.min(Math.trunc(e), 12e4);
}
function createMeetingRuntimeProbes(e) {
	const resolveJoin = (t, n, r) => ({
		url: e.normalizeUrl?.(n.url) ?? n.url,
		transport: n.transport ?? e.defaultTransport?.(t.config) ?? (t.config.chromeNode.node ? "chrome-node" : "chrome"),
		mode: r,
		agentId: t.resolveAgentId(n)
	});
	const testSpeech = async (t, n) => {
		const r = e.resolveRequestMode?.(n.mode, t.config) ?? n.mode;
		if (r === "transcribe") throw e.invalidRequest(e.speechModeError ?? "test_speech requires mode: agent or bidi");
		const i = r ?? t.config.defaultMode;
		const a = e.talkBackMode(i) ? i : "agent";
		const o = resolveJoin(t, n, a);
		const s = t.list();
		const c = new Set(s.map((e) => e.id));
		const l = s.find((e) => t.isReusable(e, o));
		const u = {
			outputBytes: l?.chrome?.health?.lastOutputBytes ?? 0,
			outputGeneration: l?.chrome?.health?.outputGeneration ?? 0
		};
		const d = await t.join({
			...n,
			...o,
			message: n.message ?? e.defaultSpeechMessage
		});
		const f = l?.id === d.session.id ? u : {
			outputBytes: 0,
			outputGeneration: 0
		};
		let p = d.session.chrome?.health;
		const verified = () => (p?.lastOutputBytes ?? 0) > f.outputBytes && (p?.outputGeneration ?? 0) > f.outputGeneration && p?.verifiedOutputGeneration === p?.outputGeneration;
		const m = d.spoken === true && p?.manualAction === void 0 && t.hasHealthHandle(d.session.id);
		if (m && !verified()) {
			const r = performance.now() + (e.resolveSpeechTimeoutMs?.(n, t.config) ?? e.resolveTimeoutMs(n.timeoutMs, t.config.chrome.joinTimeoutMs));
			while (performance.now() < r && !verified()) {
				await sleep(100);
				t.refreshHealth(d.session.id);
				p = d.session.chrome?.health;
			}
		}
		const h = verified();
		return {
			createdSession: !c.has(d.session.id),
			inCall: p?.inCall,
			manualAction: p?.manualAction,
			spoken: d.spoken ?? false,
			speechOutputVerified: h,
			speechOutputTimedOut: m && !h,
			speechReady: p?.speechReady,
			speechBlockedReason: p?.speechBlockedReason,
			speechBlockedMessage: p?.speechBlockedMessage,
			audioOutputActive: p?.audioOutputActive,
			lastOutputBytes: p?.lastOutputBytes,
			outputLoopbackSignalBytes: p?.outputLoopbackSignalBytes,
			lastOutputLoopbackAt: p?.lastOutputLoopbackAt,
			lastOutputLoopbackCorrelation: p?.lastOutputLoopbackCorrelation,
			lastOutputLoopbackRms: p?.lastOutputLoopbackRms,
			lastOutputLoopbackPeak: p?.lastOutputLoopbackPeak,
			outputGeneration: p?.outputGeneration,
			verifiedOutputGeneration: p?.verifiedOutputGeneration,
			session: d.session
		};
	};
	const testListening = async (t, n) => {
		const r = e.resolveRequestMode?.(n.mode, t.config) ?? n.mode;
		if (r && r !== "transcribe") throw e.invalidRequest(e.listeningModeError ?? "test_listen requires mode: transcribe");
		const i = resolveJoin(t, n, "transcribe");
		e.validateListeningTransport?.(i.transport);
		const a = t.list();
		const o = new Set(a.map((e) => e.id));
		const s = a.find((e) => t.isReusable(e, i));
		const c = {
			lines: s?.chrome?.health?.transcriptLines ?? 0,
			at: s?.chrome?.health?.lastCaptionAt,
			text: s?.chrome?.health?.lastCaptionText
		};
		const l = await t.join({
			...n,
			...i,
			message: void 0
		});
		let u = l.session.chrome?.health;
		const advanced = () => (u?.transcriptLines ?? 0) > (s?.id === l.session.id ? c.lines : 0) || Boolean(u?.lastCaptionAt && u.lastCaptionAt !== c.at) || Boolean(u?.lastCaptionText && u.lastCaptionText !== c.text);
		const d = u?.manualAction === void 0 && e.shouldWaitForListening(l.session);
		let f = advanced();
		if (d && !f) {
			const r = performance.now() + e.resolveTimeoutMs(n.timeoutMs, t.config.chrome.joinTimeoutMs);
			while (performance.now() < r) {
				const n = Math.floor(r - performance.now());
				if (n <= 0) break;
				if (!await raceWithTimeout(() => (e.refreshCaptionHealth?.(t, l.session, n) ?? t.refreshCaptionHealth(l.session, n)).then(() => true), n, () => false)) break;
				u = l.session.chrome?.health;
				if (performance.now() >= r) break;
				if (advanced()) f = true;
				if (f || u?.manualAction) break;
				const i = r - performance.now();
				if (i <= 0) break;
				await sleep(Math.min(250, i));
			}
		}
		return {
			createdSession: !o.has(l.session.id),
			inCall: u?.inCall,
			manualAction: u?.manualAction,
			listenVerified: f,
			listenTimedOut: d && !f && u?.manualAction === void 0,
			captioning: u?.captioning,
			captionsEnabledAttempted: u?.captionsEnabledAttempted,
			transcriptLines: u?.transcriptLines,
			lastCaptionAt: u?.lastCaptionAt,
			lastCaptionSpeaker: u?.lastCaptionSpeaker,
			lastCaptionText: u?.lastCaptionText,
			recentTranscript: u?.recentTranscript,
			session: l.session
		};
	};
	return {
		testListening,
		testSpeech
	};
}
//#endregion
//#region src/meeting-bot/setup-checks.ts
function createMeetingSetupStatus(e) {
	return {
		ok: e.every((e) => e.ok),
		checks: e
	};
}
function addMeetingSetupCheck(e, t) {
	return createMeetingSetupStatus([...e.checks, t]);
}
//#endregion
//#region src/meeting-bot/runtime-setup.ts
async function commandExists(e, t) {
	return (await e.system.runCommandWithTimeout([
		"/bin/sh",
		"-lc",
		"command -v \"$1\" >/dev/null 2>&1",
		"sh",
		t
	], { timeoutMs: 5e3 })).code === 0;
}
function createMeetingRuntimeSetup(e) {
	return async (t) => {
		const n = t.options?.mode ?? t.config.defaultMode;
		const r = t.options?.transport ?? (t.config.chromeNode.node ? "chrome-node" : "chrome");
		const i = isMeetingTalkBackMode(n);
		const a = e.guestJoinCheck(t.config);
		let o = createMeetingSetupStatus([
			{
				id: "chrome-profile",
				ok: true,
				message: t.config.chrome.browserProfile ? `Chrome node profile configured: ${t.config.chrome.browserProfile}` : "Local Chrome uses the configured OpenClaw browser profile"
			},
			{
				id: "guest-join",
				...a
			},
			{
				id: "captions",
				ok: true,
				message: e.captionsMessage(n)
			}
		]);
		if (r === "chrome-node") try {
			const n = await resolveMeetingBrowserNodeInfo({
				runtime: t.runtime,
				requestedNode: t.config.chromeNode.node,
				adapter: e.nodeAdapter
			});
			o = addMeetingSetupCheck(o, {
				id: "chrome-node-connected",
				ok: true,
				message: e.connectedNodeMessage(n.displayName ?? n.remoteIp ?? n.nodeId)
			});
			if (i) {
				if (!n.nodeId) throw new Error(e.missingNodeIdMessage);
				await t.runtime.nodes.invoke({
					nodeId: n.nodeId,
					command: e.nodeAdapter.nodeCommandName,
					params: {
						action: "setup",
						audioBackend: t.config.chrome.audioBackend,
						audioFormat: t.config.chrome.audioFormat,
						audioBufferBytes: t.config.chrome.audioBufferBytes,
						...t.config.chrome.audioInputCommandOverride ? { audioInputCommand: t.config.chrome.audioInputCommandOverride } : {},
						...t.config.chrome.audioOutputCommandOverride ? { audioOutputCommand: t.config.chrome.audioOutputCommandOverride } : {},
						...t.config.chrome.bargeInInputCommand ? { bargeInInputCommand: t.config.chrome.bargeInInputCommand } : {}
					},
					timeoutMs: 12e3
				});
				o = addMeetingSetupCheck(o, {
					id: "chrome-node-audio-prerequisites",
					ok: true,
					message: "Remote virtual audio backend and command-pair prerequisites are ready"
				});
			}
		} catch (e) {
			const t = o.checks.some((e) => e.id === "chrome-node-connected" && e.ok);
			o = addMeetingSetupCheck(o, {
				id: t ? "chrome-node-audio-prerequisites" : "chrome-node-connected",
				ok: false,
				message: formatErrorMessage(e)
			});
		}
		if (!i) return o;
		o = addMeetingSetupCheck(o, {
			id: "audio-bridge",
			ok: true,
			message: `Command-pair audio bridge configured (${t.config.chrome.audioFormat})`
		});
		if (r === "chrome-node") return o;
		let s;
		try {
			s = resolveMeetingAudioRuntimeForFormat({
				backend: t.config.chrome.audioBackend,
				bufferBytes: t.config.chrome.audioBufferBytes,
				format: t.config.chrome.audioFormat,
				inputCommand: t.config.chrome.audioInputCommandOverride,
				outputCommand: t.config.chrome.audioOutputCommandOverride
			});
			await e.assertAudioDeviceAvailable({
				config: t.config,
				runtime: t.runtime,
				timeoutMs: Math.min(t.config.chrome.joinTimeoutMs, 1e4)
			});
			o = addMeetingSetupCheck(o, {
				id: "chrome-local-audio-device",
				ok: true,
				message: "Virtual meeting audio backend is ready"
			});
		} catch (e) {
			o = addMeetingSetupCheck(o, {
				id: "chrome-local-audio-device",
				ok: false,
				message: formatErrorMessage(e)
			});
			if (!s) return o;
		}
		const c = uniqueStrings([
			s.inputCommand[0],
			s.outputCommand[0],
			t.config.chrome.bargeInInputCommand?.[0]
		].filter((e) => Boolean(e?.trim())));
		const l = [];
		for (const e of c) if (!await commandExists(t.runtime, e).catch(() => false)) l.push(e);
		return addMeetingSetupCheck(o, {
			id: "chrome-local-audio-commands",
			ok: l.length === 0,
			message: l.length === 0 ? "Configured Chrome audio commands are available" : `Chrome audio commands missing: ${l.join(", ")}`
		});
	};
}
//#endregion
//#region src/meeting-bot/platform-adapter.ts
function defineBrowserMeetingPlugin(e) {
	const { platform: t, labels: n } = e;
	const r = n.tab ?? n.meeting;
	const i = createMeetingPluginConfigSchema(e.config);
	const invalidRequest = (t) => new e.InvalidRequestError(t);
	const a = createMeetingPluginChromeTransport({
		meetingLabel: n.meeting,
		platform: t,
		preserveTrackedBrowserOnEngineFailure: e.preserveTrackedBrowserOnEngineFailure,
		runtime: e.chromeRuntime ?? createMeetingChromeRuntimeBindings()
	});
	const o = createMeetingRuntimeSetup({
		...e.setup,
		assertAudioDeviceAvailable: a.assertAudioDeviceAvailable,
		nodeAdapter: t
	});
	const s = createMeetingRuntimeProbes({
		defaultSpeechMessage: e.defaultSpeechMessage,
		invalidRequest,
		resolveTimeoutMs: (e, t) => resolveMeetingProbeTimeoutMs(e, t, invalidRequest),
		shouldWaitForListening: e.shouldWaitForListening,
		talkBackMode: isMeetingTalkBackMode
	});
	const c = createMeetingRuntimeFacade({
		platform: t,
		transport: a,
		probes: {
			setupStatus: o,
			...s
		},
		hooks: e.hooks,
		messages: {
			browserReadinessFailed: e.browserReadinessFailed,
			durableTranscripts: {
				providerId: e.transcriptSource.id,
				providerName: e.transcriptSource.providerName
			},
			joined: {
				local: `${n.participant} joined in local Chrome with realtime audio through the native virtual-audio backend.`,
				node: `${n.participant} joined in Chrome on the selected node with realtime audio through the node bridge.`,
				transcribe: `${n.participant} joined observe-only with live-caption transcript capture.`,
				waiting: `${n.participant} join is waiting for the browser to become ready before starting realtime audio.`
			},
			leaveFailed: (e) => `Browser control could not leave the ${r} tab: ${e}`,
			noTrackedTab: `No tracked ${r} tab; leave the browser meeting manually if it is still active.`,
			sharedTab: `Kept the shared ${r} tab open for another active session.`,
			sessionRuntime: {
				previousBrowserLeaveFailed: `Could not leave the previous ${r} tab before reassignment.`,
				replacementBrowserLeaveFailed: `Could not leave the previous ${r} tab before reassignment.`,
				reassignedSessionNote: `Ended before the same ${r} tab was reassigned to another agent.`,
				reusedSessionNote: `Reused existing active ${n.brand} meeting session.`,
				speechBlockedFallback: `Realtime speech blocked until ${n.brand} is ready.`,
				speech: {
					audioBridgeUnavailable: "Realtime speech requires an active Chrome audio bridge.",
					browserUnverified: `${n.brand} browser state has not been verified yet.`,
					microphoneMuted: `Turn on the OpenClaw ${n.microphone} microphone before asking OpenClaw to speak.`,
					microphoneMutedReason: e.microphoneMutedReason,
					notInCall: e.notInCallMessage ?? `${n.brand} has not reported that the browser guest is in the call.`,
					notInCallReason: "not-in-call",
					browserUnverifiedReason: "browser-unverified",
					audioBridgeUnavailableReason: "audio-bridge-unavailable"
				}
			}
		}
	});
	const l = createMeetingPluginNodeHostHandler({
		platform: t,
		browserPageName: n.browserPage,
		meetingLabel: n.meeting,
		defaultAudioInputCommand: i.defaultAudioInputCommand,
		defaultAudioOutputCommand: i.defaultAudioOutputCommand,
		sharePrerequisiteDeadline: e.sharePrerequisiteDeadline
	});
	const createNodePolicy = (n) => createMeetingPluginNodeInvokePolicy(n, {
		platform: t,
		deniedCode: e.nodePolicyDeniedCode
	});
	const resolveCliGatewayTimeoutMs = (t, n) => {
		const r = i.resolveGatewayOperationTimeoutMs(t);
		if (e.cli.resolveTimeoutMs) return e.cli.resolveTimeoutMs(r, n);
		const a = n.probe ? resolveMeetingProbeTimeoutMs(n.requestedTimeoutMs, t.chrome.joinTimeoutMs, invalidRequest) : void 0;
		return a === void 0 ? r : addTimerTimeoutGraceMs(r, a) ?? 1;
	};
	const loadCli = async () => {
		const { registerBrowserMeetingCli: t } = await import("../browser-plugin-cli-pZ57Ywrq.mjs");
		return (n) => t({
			...n,
			callGateway: e.cli.callGateway,
			descriptor: e.cli.descriptor,
			joinDescription: e.cli.joinDescription,
			meetingLabel: r,
			resolveTimeoutMs: resolveCliGatewayTimeoutMs
		});
	};
	return {
		plugin: createMeetingPluginShellEntry({
			platform: t,
			browserGuestLabel: n.meeting,
			configSchema: i.configSchema,
			invalidRequest,
			isInvalidRequest: (t) => t instanceof e.InvalidRequestError,
			toolParameters: Type.Object({
				action: Type.String({ enum: [
					"join",
					"leave",
					"status",
					"transcript",
					"speak"
				] }),
				url: Type.Optional(Type.String({ description: e.toolUrlDescription })),
				transport: Type.Optional(Type.String({ enum: ["chrome", "chrome-node"] })),
				mode: Type.Optional(Type.String({ enum: [
					"agent",
					"bidi",
					"transcribe"
				] })),
				sessionId: Type.Optional(Type.String({ description: `${r} session ID` })),
				sinceIndex: Type.Optional(Type.Integer({
					minimum: 0,
					description: "Resume transcript from this index"
				})),
				message: Type.Optional(Type.String({ description: "Instructions to speak" }))
			}),
			resolveGatewayTimeoutMs: i.resolveGatewayOperationTimeoutMs,
			normalizeRequesterSessionKey: (e, t) => t && typeof e === "string" && e.trim() ? e.trim() : void 0,
			normalizeToolAgentId: (e) => normalizeAgentId(e),
			resolveToolRuntime: async (e) => {
				if (!await e.runtime.gateway.isAvailable()) throw new Error(`${n.meeting} tools require a Gateway-hosted agent run.`);
				return e.runtime;
			},
			transcriptSource: {
				id: e.transcriptSource.id,
				aliases: e.transcriptSource.aliases
			},
			runtime: c,
			nodeHandler: l,
			createNodePolicy,
			registerNodeWhen: (e) => e.enabled,
			...e.entry,
			cli: {
				descriptor: e.cli.descriptor,
				load: loadCli
			}
		}),
		config: i,
		chrome: a,
		Runtime: c,
		probes: s,
		setupStatus: o,
		nodeHandler: l,
		createNodePolicy,
		loadCli,
		resolveCliGatewayTimeoutMs
	};
}
function browserResultString(e) {
	if (!e || typeof e !== "object") return;
	const t = e.result;
	return typeof t === "string" && t.trim() ? t : void 0;
}
const optionalBrowserString = string().optional().catch(void 0);
const optionalBrowserBoolean = boolean().optional().catch(void 0);
const optionalBrowserNumber = number().optional().catch(void 0);
const meetingTranscriptLineSchema = object({
	at: optionalBrowserString,
	speaker: optionalBrowserString,
	text: string().refine((e) => e.trim().length > 0),
	provenance: unknown().optional()
}).transform(({ at: e, speaker: t, text: n, provenance: r }) => ({
	...e !== void 0 ? { at: e } : {},
	...t !== void 0 ? { speaker: t } : {},
	text: n,
	...r !== void 0 ? { provenance: r } : {}
}));
const meetingTranscriptLinesSchema = array(meetingTranscriptLineSchema.nullable().catch(null)).transform((e) => e.filter((e) => e !== null));
const meetingCaptionLinesSchema = array(meetingTranscriptLineSchema.and(object({ source: unknown().optional() })).nullable().catch(null)).transform((e) => e.filter((e) => e !== null));
const meetingBrowserStatusSchema = looseObject({
	inCall: optionalBrowserBoolean,
	micMuted: optionalBrowserBoolean,
	cameraOff: optionalBrowserBoolean,
	lobbyWaiting: optionalBrowserBoolean,
	captionCaptureRequested: optionalBrowserBoolean,
	captioning: optionalBrowserBoolean,
	captionsEnabledAttempted: optionalBrowserBoolean,
	transcriptLines: optionalBrowserNumber,
	lastCaptionAt: optionalBrowserString,
	lastCaptionSpeaker: optionalBrowserString,
	lastCaptionText: optionalBrowserString,
	recentTranscript: meetingTranscriptLinesSchema.optional().catch(void 0),
	audioInputRouted: optionalBrowserBoolean,
	audioInputDeviceLabel: optionalBrowserString,
	audioInputRouteError: optionalBrowserString,
	audioOutputRouted: optionalBrowserBoolean,
	audioOutputDeviceLabel: optionalBrowserString,
	audioOutputRouteError: optionalBrowserString,
	audioOutputRouteRetryable: optionalBrowserBoolean,
	manualAction: object({
		reason: string(),
		message: string()
	}).optional().catch(void 0),
	url: optionalBrowserString,
	title: optionalBrowserString,
	notes: array(string().nullable().catch(null)).transform((e) => e.filter((e) => e !== null)).optional().catch(void 0)
});
function parseMeetingLeaveResult(e) {
	const t = browserResultString(e);
	if (!t) return { departed: false };
	try {
		const e = JSON.parse(t);
		const n = e.leaveAction === "leave" || e.leaveAction === "confirm" ? e.leaveAction : void 0;
		return {
			departed: e.departed === true,
			...n ? { leaveAction: n } : {},
			...typeof e.sessionConflict === "boolean" ? { sessionConflict: e.sessionConflict } : {},
			...typeof e.sessionMatched === "boolean" ? { sessionMatched: e.sessionMatched } : {},
			...typeof e.urlMatched === "boolean" ? { urlMatched: e.urlMatched } : {}
		};
	} catch {
		return { departed: false };
	}
}
function createMeetingPlatformAdapter(e) {
	const { browser: t, parsing: n, ...r } = e;
	return {
		...r,
		browser: {
			...t,
			parseStatus: (t) => {
				const r = e.id;
				const i = browserResultString(t);
				if (!i) return;
				let a;
				try {
					a = meetingBrowserStatusSchema.parse(JSON.parse(i));
				} catch {
					throw new Error(n.malformedStatusMessage);
				}
				return {
					inCall: a.inCall,
					micMuted: a.micMuted,
					cameraOff: a.cameraOff,
					lobbyWaiting: a.lobbyWaiting,
					captionCaptureRequested: a.captionCaptureRequested,
					captioning: a.captioning,
					captionsEnabledAttempted: a.captionsEnabledAttempted,
					transcriptLines: a.transcriptLines,
					lastCaptionAt: a.lastCaptionAt,
					lastCaptionSpeaker: a.lastCaptionSpeaker,
					lastCaptionText: a.lastCaptionText,
					recentTranscript: a.recentTranscript?.map((e) => ({
						...e,
						...e.provenance !== void 0 ? { provenance: normalizeMeetingObservationProvenance(e.provenance, {
							observer: r,
							observedAt: e.at,
							speaker: e.speaker
						}) } : {}
					})),
					audioInputRouted: a.audioInputRouted,
					audioInputDeviceLabel: a.audioInputDeviceLabel,
					audioInputRouteError: a.audioInputRouteError,
					audioOutputRouted: a.audioOutputRouted,
					audioOutputDeviceLabel: a.audioOutputDeviceLabel,
					audioOutputRouteError: a.audioOutputRouteError,
					audioOutputRouteRetryable: a.audioOutputRouteRetryable,
					manualAction: a.manualAction,
					browserUrl: a.url,
					browserTitle: a.title,
					status: "browser-control",
					notes: a.notes,
					...n.statusFields?.(a)
				};
			},
			classifyManualAction: (e) => {
				if (!e.manualAction) return;
				return {
					category: n.classifyManualActionReason(e.manualAction.reason),
					reason: e.manualAction.reason,
					message: e.manualAction.message
				};
			},
			parseLeaveResult: parseMeetingLeaveResult,
			captions: {
				...t.captions,
				parseTranscript: (t) => {
					const r = e.id;
					const i = browserResultString(t);
					if (!i) return {
						droppedLines: 0,
						lines: []
					};
					let a;
					try {
						a = JSON.parse(i);
					} catch {
						throw new Error(n.malformedTranscriptMessage);
					}
					if (!a || typeof a !== "object") throw new Error(n.invalidTranscriptMessage);
					const o = a;
					const s = typeof o.droppedLines === "number" && Number.isSafeInteger(o.droppedLines) ? Math.max(0, o.droppedLines) : 0;
					const parseLines = (e) => meetingCaptionLinesSchema.catch([]).parse(e).map((e) => {
						const t = meetingCaptionSourceSchema.safeParse(e.source);
						const n = t.success && t.data.epoch === o.epoch ? t.data : void 0;
						const i = { text: e.text };
						if (e.at !== void 0) i.at = e.at;
						if (e.speaker !== void 0) i.speaker = e.speaker;
						if (e.provenance !== void 0 || e.source !== void 0) i.provenance = normalizeMeetingObservationProvenance(e.provenance, {
							observer: r,
							epoch: o.epoch,
							observedAt: e.at,
							speaker: e.speaker
						});
						if (n) i.source = n;
						return i;
					});
					return {
						droppedLines: s,
						...typeof o.epoch === "string" ? { epoch: o.epoch } : {},
						lines: parseLines(o.lines),
						...Array.isArray(o.pendingLines) ? { pendingLines: parseLines(o.pendingLines) } : {},
						...typeof o.urlMatched === "boolean" ? { urlMatched: o.urlMatched } : {},
						...typeof o.sessionMatched === "boolean" ? { sessionMatched: o.sessionMatched } : {}
					};
				}
			},
			permissionNotes: t.permissionNotes ?? (({ allowMicrophone: e, error: t, result: r }) => {
				if (!e) return [`Observe-only mode does not request ${n.displayName} microphone access.`];
				if (t) return [`Could not grant ${n.displayName} media permissions automatically: ${formatErrorMessage(t)}`];
				const i = r && typeof r === "object" ? r : {};
				const a = Array.isArray(i.unsupportedPermissions) ? i.unsupportedPermissions.filter((e) => typeof e === "string") : [];
				const o = [`Granted ${n.displayName} microphone permission through browser control.`];
				if (a.includes("speakerSelection")) o.push(`Chrome did not accept the optional ${n.displayName} speaker-selection permission.`);
				return o;
			})
		}
	};
}
const MeetingPlatformAdapter = {
	create: createMeetingPlatformAdapter,
	createBrowserAdapterOptions: createMeetingBrowserAdapterOptions,
	createPageScripts: createMeetingPageScripts,
	defineBrowserMeetingPlugin,
	createChromeTransport: createMeetingChromeTransport,
	createChromeTransportWithExternalAudio: createMeetingChromeTransportWithExternalAudio,
	createChromeRuntimeBindings: createMeetingChromeRuntimeBindings,
	/** @deprecated Use defineBrowserMeetingPlugin for browser meeting plugins. */
	createPluginChromeTransport: createMeetingPluginChromeTransport,
	/** @deprecated Use defineBrowserMeetingPlugin for browser meeting plugins. */
	createPluginConfigSchema: createMeetingPluginConfigSchema,
	/** @deprecated Use defineBrowserMeetingPlugin for browser meeting plugins. */
	createPluginNodeHostHandler: createMeetingPluginNodeHostHandler,
	/** @deprecated Use defineBrowserMeetingPlugin for browser meeting plugins. */
	createPluginNodeInvokePolicy: createMeetingPluginNodeInvokePolicy,
	/** @deprecated Use defineBrowserMeetingPlugin for browser meeting plugins. */
	createPluginShellEntry: createMeetingPluginShellEntry,
	/** @deprecated Use defineBrowserMeetingPlugin for browser meeting plugins. */
	createRuntimeFacade: createMeetingRuntimeFacade,
	/** @deprecated Use defineBrowserMeetingPlugin for browser meeting plugins. */
	createRuntimeSetup: createMeetingRuntimeSetup,
	pluginTypes: createMeetingPluginTypes,
	/** @deprecated Use defineBrowserMeetingPlugin for browser meeting plugins. */
	registerPluginCli: registerMeetingPluginCli,
	resolveProbeTimeoutMs: resolveMeetingProbeTimeoutMs,
	createRuntimeProbes: createMeetingRuntimeProbes,
	createNodeHostHandler: createMeetingConfiguredNodeHost,
	createPluginEntry: createMeetingPluginEntryOptions,
	createStatusCallSource: createMeetingStatusCallSource,
	createStatusPreludeSource: createMeetingStatusPreludeSource,
	isRealtimeRouteReady: isMeetingRealtimeRouteReady,
	isTalkBackMode: isMeetingTalkBackMode,
	ensureAudioBackend: ensureMeetingAudioBackend,
	resolveAudioRuntimeForFormat: resolveMeetingAudioRuntimeForFormat
};
//#endregion
//#region src/meeting-bot/participation-browser.ts
async function runMeetingParticipationWithBrowser(e) {
	let t = false;
	let n = false;
	const assertCurrent = () => {
		try {
			e.assertCurrent();
		} catch (e) {
			n = true;
			throw e;
		}
	};
	try {
		assertCurrent();
		if (!e.adapter.capabilities.includes(e.action.type)) return {
			status: "unsupported",
			message: "This meeting does not support that action."
		};
		const n = e.adapter.validateAction(e.action);
		if (n) return {
			status: "rejected",
			message: n
		};
		const r = performance.now() + Math.max(1, e.timeoutMs);
		const i = await runMeetingBrowserAct({
			deadline: r,
			targetId: e.targetId,
			operation: async (n) => {
				assertCurrent();
				const i = asMeetingBrowserTabs(await e.callBrowser({
					method: "GET",
					path: "/tabs",
					timeoutMs: n
				}));
				assertCurrent();
				const a = i.find((t) => t.targetId === e.targetId);
				if (!a || !e.isSameMeetingUrl(a.url, e.meetingUrl)) return {
					status: "rejected",
					message: "The tracked browser tab no longer shows this meeting; no action was sent."
				};
				const o = {
					meetingSessionId: e.meetingSessionId,
					meetingUrl: e.meetingUrl,
					requestId: e.requestId,
					action: e.action
				};
				const remainingTimeoutMs = () => {
					const e = Math.floor(r - performance.now());
					if (e <= 0) throw new Error("Meeting participation timed out before dispatch.");
					return e;
				};
				if (e.adapter.buildPreparationScript) {
					if (!e.adapter.parsePreparationResult) return {
						status: "failed",
						message: "The meeting adapter cannot verify action preparation."
					};
					const t = e.adapter.buildPreparationScript(o);
					const n = remainingTimeoutMs();
					assertCurrent();
					const r = await e.callBrowser({
						method: "POST",
						path: "/act",
						body: {
							kind: "evaluate",
							targetId: e.targetId,
							fn: t
						},
						timeoutMs: n
					});
					assertCurrent();
					const i = e.adapter.parsePreparationResult(r, e.action);
					if (i.status !== "succeeded") return i;
				}
				const s = e.adapter.buildActionScript(o);
				const c = remainingTimeoutMs();
				assertCurrent();
				t = true;
				const l = await e.callBrowser({
					method: "POST",
					path: "/act",
					body: {
						kind: "evaluate",
						targetId: e.targetId,
						fn: s
					},
					timeoutMs: c
				});
				assertCurrent();
				return e.adapter.parseActionResult(l, e.action);
			}
		});
		assertCurrent();
		return i;
	} catch (e) {
		return {
			status: t ? "uncertain" : n ? "rejected" : "failed",
			message: coerceErrorMessage(e)
		};
	}
}
//#endregion
//#region src/plugin-sdk/meeting-runtime.ts
function createMeetingVoiceCallGateway(e) {
	if (!e.config.gatewayUrl) return {
		trustedPluginIdentity: true,
		request: (t, n) => e.runtime.gateway.request(t, n, { timeoutMs: e.config.requestTimeoutMs })
	};
	return {
		trustedPluginIdentity: false,
		async request(t, n) {
			const r = await e.connectClient(e);
			try {
				return await r.request(t, n, { timeoutMs: e.config.requestTimeoutMs });
			} finally {
				await r.stopAndWait({ timeoutMs: 1e3 }).catch(() => {});
			}
		}
	};
}
function isMeetingVoiceCallMissingError(e) {
	const t = formatErrorMessage(e).toLowerCase();
	return t.includes("call not found") || t.includes("call is not active");
}
async function joinMeetingViaVoiceCallGateway(e) {
	if (e.agentId && e.agentId !== "main" && !e.gateway.trustedPluginIdentity) throw new Error(`Per-agent Voice Call routing requires the local Gateway runtime. Remove ${e.surface.configPath} or omit agent routing.`);
	e.logger?.info(`${e.surface.logScope} Delegating ${e.surface.providerLabel} join to Voice Call (dtmf=${e.dtmfSequence ? "pre-connect" : "none"}, intro=${e.message ? "delayed" : "none"})`);
	const t = await e.gateway.request("voicecall.start", {
		to: e.dialInNumber,
		mode: "conversation",
		...e.dtmfSequence ? { dtmfSequence: e.dtmfSequence } : {},
		...e.requesterSessionKey ? { requesterSessionKey: e.requesterSessionKey } : {},
		...e.agentId && e.gateway.trustedPluginIdentity ? { agentId: e.agentId } : {},
		...e.sessionKey ? { sessionKey: e.sessionKey } : {}
	});
	if (!t.callId) throw new Error(t.error || "voicecall.start did not return callId");
	e.logger?.info(`${e.surface.logScope} Voice Call ${e.surface.providerLabel} phone leg started: callId=${t.callId}`);
	const n = Boolean(e.dtmfSequence);
	if (n) e.logger?.info(`${e.surface.logScope} ${e.surface.meetingLabel} DTMF queued before realtime connect: callId=${t.callId} digits=${e.dtmfSequence?.length ?? 0}`);
	let r = false;
	if (e.message) {
		const n = e.dtmfSequence ? e.config.postDtmfSpeechDelayMs : 0;
		if (n > 0) {
			e.logger?.info(`${e.surface.logScope} Waiting ${n}ms after ${e.surface.meetingLabel} DTMF before speaking intro for callId=${t.callId}`);
			await sleep(n);
		}
		let i;
		try {
			i = await e.gateway.request("voicecall.speak", {
				callId: t.callId,
				allowTwimlFallback: false,
				message: e.message
			});
		} catch (t) {
			e.logger?.warn?.(`${e.surface.logScope} Skipped intro speech because realtime bridge was not ready: ${formatErrorMessage(t)}`);
			i = { success: false };
		}
		if (i.success === false) e.logger?.warn?.(`${e.surface.logScope} Skipped intro speech because realtime bridge was not ready: ${i.error || "voicecall.speak failed"}`);
		else {
			r = true;
			e.logger?.info(`${e.surface.logScope} Intro speech requested after ${e.surface.meetingLabel} dial sequence: callId=${t.callId}`);
		}
	}
	return {
		callId: t.callId,
		dtmfSent: n,
		introSent: r
	};
}
async function endMeetingVoiceCallGatewayCall(e) {
	try {
		await e.gateway.request("voicecall.end", { callId: e.callId });
	} catch (e) {
		if (!isMeetingVoiceCallMissingError(e)) throw e;
	}
}
async function getMeetingVoiceCallGatewayCall(e) {
	return await e.gateway.request("voicecall.status", { callId: e.callId });
}
async function speakMeetingViaVoiceCallGateway(e) {
	const t = await e.gateway.request("voicecall.speak", {
		callId: e.callId,
		message: e.message
	});
	if (t.success === false) throw new Error(t.error || "voicecall.speak failed");
}
//#endregion
export { MeetingPlatformAdapter, MeetingSessionRuntime, addMeetingSetupCheck, asMeetingBrowserTabs, buildMeetingSoxAudioCommands, callMeetingBrowserProxyOnNode, convertMeetingTtsAudioForBridge, createLocalMeetingRealtimeAudioTransport, createMeetingBrowserNodeInvokePolicy, createMeetingNodeHost, createMeetingRealtimeEngineBindings, createMeetingSession, createMeetingSetupStatus, createMeetingVoiceCallGateway, createNodeMeetingRealtimeAudioTransport, endMeetingVoiceCallGatewayCall, getMeetingVoiceCallGatewayCall, isMeetingVoiceCallMissingError, joinMeetingViaVoiceCallGateway, leaveMeetingWithBrowser, openMeetingWithBrowser, readMeetingBrowserTab, readMeetingTranscriptWithBrowser, recoverMeetingBrowserTab, resolveLocalMeetingBrowserRequest, resolveMeetingBrowserNode, resolveMeetingBrowserNodeInfo, runMeetingParticipationWithBrowser, speakMeetingViaVoiceCallGateway, startMeetingAgentRealtimeEngine, startMeetingRealtimeEngine };