import { j as TtsConfigSchema } from "./zod-schema.core-urFIFYTN.js";
import { c as REALTIME_VOICE_AGENT_CONSULT_TOOL_NAME, l as REALTIME_VOICE_AGENT_CONSULT_TOOL_POLICIES } from "./session-runtime-y8hoNrLe.js";
import "./realtime-voice-DkH2Ds4J.js";
import { t as zod_exports } from "./zod-C2RJs7Tu.js";
import "./api-BKmC2vtG.js";
//#region extensions/voice-call/src/deep-merge.ts
const BLOCKED_MERGE_KEYS = new Set([
	"__proto__",
	"prototype",
	"constructor"
]);
function deepMergeDefined(base, override) {
	if (!isPlainObject(base) || !isPlainObject(override)) return override === void 0 ? base : override;
	const result = { ...base };
	for (const [key, value] of Object.entries(override)) {
		if (BLOCKED_MERGE_KEYS.has(key) || value === void 0) continue;
		const existing = result[key];
		result[key] = key in result ? deepMergeDefined(existing, value) : value;
	}
	return result;
}
function isPlainObject(value) {
	return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
//#endregion
//#region extensions/voice-call/src/realtime-defaults.ts
const DEFAULT_VOICE_CALL_REALTIME_INSTRUCTIONS = `You are OpenClaw's phone-call realtime voice interface. Keep spoken replies brief and natural. When a question needs deeper reasoning, current information, or tools, call ${REALTIME_VOICE_AGENT_CONSULT_TOOL_NAME} before answering.`;
//#endregion
//#region extensions/voice-call/src/config.ts
/**
* E.164 phone number format: +[country code][number]
* Examples use 555 prefix (reserved for fictional numbers)
*/
const E164Schema = zod_exports.z.string().regex(/^\+[1-9]\d{1,14}$/, "Expected E.164 format, e.g. +15550001234");
/**
* Controls how inbound calls are handled:
* - "disabled": Block all inbound calls (outbound only)
* - "allowlist": Only accept calls from numbers in allowFrom
* - "pairing": Unknown callers can request pairing (future)
* - "open": Accept all inbound calls (dangerous!)
*/
const InboundPolicySchema = zod_exports.z.enum([
	"disabled",
	"allowlist",
	"pairing",
	"open"
]);
const TelnyxConfigSchema = zod_exports.z.object({
	/** Telnyx API v2 key */
	apiKey: zod_exports.z.string().min(1).optional(),
	/** Telnyx connection ID (from Call Control app) */
	connectionId: zod_exports.z.string().min(1).optional(),
	/** Public key for webhook signature verification */
	publicKey: zod_exports.z.string().min(1).optional()
}).strict();
const TwilioConfigSchema = zod_exports.z.object({
	/** Twilio Account SID */
	accountSid: zod_exports.z.string().min(1).optional(),
	/** Twilio Auth Token */
	authToken: zod_exports.z.string().min(1).optional()
}).strict();
const PlivoConfigSchema = zod_exports.z.object({
	/** Plivo Auth ID (starts with MA/SA) */
	authId: zod_exports.z.string().min(1).optional(),
	/** Plivo Auth Token */
	authToken: zod_exports.z.string().min(1).optional()
}).strict();
const VoiceCallServeConfigSchema = zod_exports.z.object({
	/** Port to listen on */
	port: zod_exports.z.number().int().positive().default(3334),
	/** Bind address */
	bind: zod_exports.z.string().default("127.0.0.1"),
	/** Webhook path */
	path: zod_exports.z.string().min(1).default("/voice/webhook")
}).strict().default({
	port: 3334,
	bind: "127.0.0.1",
	path: "/voice/webhook"
});
const VoiceCallTailscaleConfigSchema = zod_exports.z.object({
	/**
	* Tailscale exposure mode:
	* - "off": No Tailscale exposure
	* - "serve": Tailscale serve (private to tailnet)
	* - "funnel": Tailscale funnel (public HTTPS)
	*/
	mode: zod_exports.z.enum([
		"off",
		"serve",
		"funnel"
	]).default("off"),
	/** Path for Tailscale serve/funnel (should usually match serve.path) */
	path: zod_exports.z.string().min(1).default("/voice/webhook")
}).strict().default({
	mode: "off",
	path: "/voice/webhook"
});
const VoiceCallTunnelConfigSchema = zod_exports.z.object({
	/**
	* Tunnel provider:
	* - "none": No tunnel (use publicUrl if set, or manual setup)
	* - "ngrok": Use ngrok for public HTTPS tunnel
	* - "tailscale-serve": Tailscale serve (private to tailnet)
	* - "tailscale-funnel": Tailscale funnel (public HTTPS)
	*/
	provider: zod_exports.z.enum([
		"none",
		"ngrok",
		"tailscale-serve",
		"tailscale-funnel"
	]).default("none"),
	/** ngrok auth token (optional, enables longer sessions and more features) */
	ngrokAuthToken: zod_exports.z.string().min(1).optional(),
	/** ngrok custom domain (paid feature, e.g., "myapp.ngrok.io") */
	ngrokDomain: zod_exports.z.string().min(1).optional(),
	/**
	* Allow ngrok free tier compatibility mode.
	* When true, forwarded headers may be trusted for loopback requests
	* to reconstruct the public ngrok URL used for signing.
	*
	* IMPORTANT: This does NOT bypass signature verification.
	*/
	allowNgrokFreeTierLoopbackBypass: zod_exports.z.boolean().default(false)
}).strict().default({
	provider: "none",
	allowNgrokFreeTierLoopbackBypass: false
});
const VoiceCallWebhookSecurityConfigSchema = zod_exports.z.object({
	/**
	* Allowed hostnames for webhook URL reconstruction.
	* Only these hosts are accepted from forwarding headers.
	*/
	allowedHosts: zod_exports.z.array(zod_exports.z.string().min(1)).default([]),
	/**
	* Trust X-Forwarded-* headers without a hostname allowlist.
	* WARNING: Only enable if you trust your proxy configuration.
	*/
	trustForwardingHeaders: zod_exports.z.boolean().default(false),
	/**
	* Trusted proxy IP addresses. Forwarded headers are only trusted when
	* the remote IP matches one of these addresses.
	*/
	trustedProxyIPs: zod_exports.z.array(zod_exports.z.string().min(1)).default([])
}).strict().default({
	allowedHosts: [],
	trustForwardingHeaders: false,
	trustedProxyIPs: []
});
/**
* Call mode determines how outbound calls behave:
* - "notify": Deliver message and auto-hangup after delay (one-way notification)
* - "conversation": Stay open for back-and-forth until explicit end or timeout
*/
const CallModeSchema = zod_exports.z.enum(["notify", "conversation"]);
const OutboundConfigSchema = zod_exports.z.object({
	/** Default call mode for outbound calls */
	defaultMode: CallModeSchema.default("notify"),
	/** Seconds to wait after TTS before auto-hangup in notify mode */
	notifyHangupDelaySec: zod_exports.z.number().int().nonnegative().default(3)
}).strict().default({
	defaultMode: "notify",
	notifyHangupDelaySec: 3
});
const RealtimeToolSchema = zod_exports.z.object({
	type: zod_exports.z.literal("function"),
	name: zod_exports.z.string().min(1),
	description: zod_exports.z.string(),
	parameters: zod_exports.z.object({
		type: zod_exports.z.literal("object"),
		properties: zod_exports.z.record(zod_exports.z.string(), zod_exports.z.unknown()),
		required: zod_exports.z.array(zod_exports.z.string()).optional()
	})
}).strict();
const VoiceCallRealtimeProvidersConfigSchema = zod_exports.z.record(zod_exports.z.string(), zod_exports.z.record(zod_exports.z.string(), zod_exports.z.unknown())).default({});
const VoiceCallRealtimeToolPolicySchema = zod_exports.z.enum(REALTIME_VOICE_AGENT_CONSULT_TOOL_POLICIES);
const VoiceCallStreamingProvidersConfigSchema = zod_exports.z.record(zod_exports.z.string(), zod_exports.z.record(zod_exports.z.string(), zod_exports.z.unknown())).default({});
const VoiceCallRealtimeConfigSchema = zod_exports.z.object({
	/** Enable realtime voice-to-voice mode. */
	enabled: zod_exports.z.boolean().default(false),
	/** Provider id from registered realtime voice providers. */
	provider: zod_exports.z.string().min(1).optional(),
	/** Optional override for the local WebSocket route path. */
	streamPath: zod_exports.z.string().min(1).optional(),
	/** System instructions passed to the realtime provider. */
	instructions: zod_exports.z.string().default(DEFAULT_VOICE_CALL_REALTIME_INSTRUCTIONS),
	/** Tool policy for the shared OpenClaw agent consult tool. */
	toolPolicy: VoiceCallRealtimeToolPolicySchema.default("safe-read-only"),
	/** Tool definitions exposed to the realtime provider. */
	tools: zod_exports.z.array(RealtimeToolSchema).default([]),
	/** Provider-owned raw config blobs keyed by provider id. */
	providers: VoiceCallRealtimeProvidersConfigSchema
}).strict().default({
	enabled: false,
	instructions: DEFAULT_VOICE_CALL_REALTIME_INSTRUCTIONS,
	toolPolicy: "safe-read-only",
	tools: [],
	providers: {}
});
const VoiceCallStreamingConfigSchema = zod_exports.z.object({
	/** Enable real-time audio streaming (requires WebSocket support) */
	enabled: zod_exports.z.boolean().default(false),
	/** Provider id from registered realtime transcription providers. */
	provider: zod_exports.z.string().min(1).optional(),
	/** WebSocket path for media stream connections */
	streamPath: zod_exports.z.string().min(1).default("/voice/stream"),
	/** Provider-owned raw config blobs keyed by provider id. */
	providers: VoiceCallStreamingProvidersConfigSchema,
	/**
	* Close unauthenticated media stream sockets if no valid `start` frame arrives in time.
	* Protects against pre-auth idle connection hold attacks.
	*/
	preStartTimeoutMs: zod_exports.z.number().int().positive().default(5e3),
	/** Maximum number of concurrently pending (pre-start) media stream sockets. */
	maxPendingConnections: zod_exports.z.number().int().positive().default(32),
	/** Maximum pending media stream sockets per source IP. */
	maxPendingConnectionsPerIp: zod_exports.z.number().int().positive().default(4),
	/** Hard cap for all open media stream sockets (pending + active). */
	maxConnections: zod_exports.z.number().int().positive().default(128)
}).strict().default({
	enabled: false,
	streamPath: "/voice/stream",
	providers: {},
	preStartTimeoutMs: 5e3,
	maxPendingConnections: 32,
	maxPendingConnectionsPerIp: 4,
	maxConnections: 128
});
const VoiceCallConfigSchema = zod_exports.z.object({
	/** Enable voice call functionality */
	enabled: zod_exports.z.boolean().default(false),
	/** Active provider (telnyx, twilio, plivo, or mock) */
	provider: zod_exports.z.enum([
		"telnyx",
		"twilio",
		"plivo",
		"mock"
	]).optional(),
	/** Telnyx-specific configuration */
	telnyx: TelnyxConfigSchema.optional(),
	/** Twilio-specific configuration */
	twilio: TwilioConfigSchema.optional(),
	/** Plivo-specific configuration */
	plivo: PlivoConfigSchema.optional(),
	/** Phone number to call from (E.164) */
	fromNumber: E164Schema.optional(),
	/** Default phone number to call (E.164) */
	toNumber: E164Schema.optional(),
	/** Inbound call policy */
	inboundPolicy: InboundPolicySchema.default("disabled"),
	/** Allowlist of phone numbers for inbound calls (E.164) */
	allowFrom: zod_exports.z.array(E164Schema).default([]),
	/** Greeting message for inbound calls */
	inboundGreeting: zod_exports.z.string().optional(),
	/** Outbound call configuration */
	outbound: OutboundConfigSchema,
	/** Maximum call duration in seconds */
	maxDurationSeconds: zod_exports.z.number().int().positive().default(300),
	/**
	* Maximum age of a call in seconds before it is automatically reaped.
	* Catches calls stuck before answer (for example, local mock calls that
	* never receive provider webhooks). Set to 0 to disable.
	*/
	staleCallReaperSeconds: zod_exports.z.number().int().nonnegative().default(120),
	/** Silence timeout for end-of-speech detection (ms) */
	silenceTimeoutMs: zod_exports.z.number().int().positive().default(800),
	/** Timeout for user transcript (ms) */
	transcriptTimeoutMs: zod_exports.z.number().int().positive().default(18e4),
	/** Ring timeout for outbound calls (ms) */
	ringTimeoutMs: zod_exports.z.number().int().positive().default(3e4),
	/** Maximum concurrent calls */
	maxConcurrentCalls: zod_exports.z.number().int().positive().default(1),
	/** Webhook server configuration */
	serve: VoiceCallServeConfigSchema,
	/** Tailscale exposure configuration (legacy, prefer tunnel config) */
	tailscale: VoiceCallTailscaleConfigSchema,
	/** Tunnel configuration (unified ngrok/tailscale) */
	tunnel: VoiceCallTunnelConfigSchema,
	/** Webhook signature reconstruction and proxy trust configuration */
	webhookSecurity: VoiceCallWebhookSecurityConfigSchema,
	/** Real-time audio streaming configuration */
	streaming: VoiceCallStreamingConfigSchema,
	/** Realtime voice-to-voice configuration */
	realtime: VoiceCallRealtimeConfigSchema,
	/** Public webhook URL override (if set, bypasses tunnel auto-detection) */
	publicUrl: zod_exports.z.string().url().optional(),
	/** Skip webhook signature verification (development only, NOT for production) */
	skipSignatureVerification: zod_exports.z.boolean().default(false),
	/** TTS override (deep-merges with core messages.tts) */
	tts: TtsConfigSchema,
	/** Store path for call logs */
	store: zod_exports.z.string().optional(),
	/** Agent ID to use for voice response generation. Defaults to "main". */
	agentId: zod_exports.z.string().min(1).optional(),
	/** Optional model override for generating voice responses. */
	responseModel: zod_exports.z.string().optional(),
	/** System prompt for voice responses */
	responseSystemPrompt: zod_exports.z.string().optional(),
	/** Timeout for response generation in ms (default 30s) */
	responseTimeoutMs: zod_exports.z.number().int().positive().default(3e4)
}).strict();
const DEFAULT_VOICE_CALL_CONFIG = VoiceCallConfigSchema.parse({});
function cloneDefaultVoiceCallConfig() {
	return structuredClone(DEFAULT_VOICE_CALL_CONFIG);
}
function normalizeWebhookLikePath(pathname) {
	const trimmed = pathname.trim();
	if (!trimmed) return "/";
	const prefixed = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
	if (prefixed === "/") return prefixed;
	return prefixed.endsWith("/") ? prefixed.slice(0, -1) : prefixed;
}
function defaultRealtimeStreamPathForServePath(servePath) {
	const normalized = normalizeWebhookLikePath(servePath);
	if (normalized.endsWith("/webhook")) return `${normalized.slice(0, -8)}/stream/realtime`;
	if (normalized === "/") return "/voice/stream/realtime";
	return `${normalized}/stream/realtime`;
}
function normalizeVoiceCallTtsConfig(defaults, overrides) {
	if (!defaults && !overrides) return;
	return TtsConfigSchema.parse(deepMergeDefined(defaults ?? {}, overrides ?? {}));
}
function sanitizeVoiceCallProviderConfigs(value) {
	if (!value) return {};
	return Object.fromEntries(Object.entries(value).filter((entry) => entry[1] !== void 0));
}
function normalizeVoiceCallConfig(config) {
	const defaults = cloneDefaultVoiceCallConfig();
	const serve = {
		...defaults.serve,
		...config.serve
	};
	const streamingProvider = config.streaming?.provider;
	const streamingProviders = sanitizeVoiceCallProviderConfigs(config.streaming?.providers ?? defaults.streaming.providers);
	const realtimeProvider = config.realtime?.provider ?? defaults.realtime.provider;
	const realtimeProviders = sanitizeVoiceCallProviderConfigs(config.realtime?.providers ?? defaults.realtime.providers);
	return {
		...defaults,
		...config,
		allowFrom: config.allowFrom ?? defaults.allowFrom,
		outbound: {
			...defaults.outbound,
			...config.outbound
		},
		serve,
		tailscale: {
			...defaults.tailscale,
			...config.tailscale
		},
		tunnel: {
			...defaults.tunnel,
			...config.tunnel
		},
		webhookSecurity: {
			...defaults.webhookSecurity,
			...config.webhookSecurity,
			allowedHosts: config.webhookSecurity?.allowedHosts ?? defaults.webhookSecurity.allowedHosts,
			trustedProxyIPs: config.webhookSecurity?.trustedProxyIPs ?? defaults.webhookSecurity.trustedProxyIPs
		},
		streaming: {
			...defaults.streaming,
			...config.streaming,
			provider: streamingProvider,
			providers: streamingProviders
		},
		realtime: {
			...defaults.realtime,
			...config.realtime,
			provider: realtimeProvider,
			streamPath: config.realtime?.streamPath ?? defaultRealtimeStreamPathForServePath(serve.path ?? defaults.serve.path),
			tools: config.realtime?.tools ?? defaults.realtime.tools,
			providers: realtimeProviders
		},
		tts: normalizeVoiceCallTtsConfig(defaults.tts, config.tts)
	};
}
/**
* Resolves the configuration by merging environment variables into missing fields.
* Returns a new configuration object with environment variables applied.
*/
function resolveVoiceCallConfig(config) {
	const resolved = normalizeVoiceCallConfig(config);
	if (resolved.provider === "telnyx") {
		resolved.telnyx = resolved.telnyx ?? {};
		resolved.telnyx.apiKey = resolved.telnyx.apiKey ?? process.env.TELNYX_API_KEY;
		resolved.telnyx.connectionId = resolved.telnyx.connectionId ?? process.env.TELNYX_CONNECTION_ID;
		resolved.telnyx.publicKey = resolved.telnyx.publicKey ?? process.env.TELNYX_PUBLIC_KEY;
	}
	if (resolved.provider === "twilio") {
		resolved.fromNumber = resolved.fromNumber ?? process.env.TWILIO_FROM_NUMBER;
		resolved.twilio = resolved.twilio ?? {};
		resolved.twilio.accountSid = resolved.twilio.accountSid ?? process.env.TWILIO_ACCOUNT_SID;
		resolved.twilio.authToken = resolved.twilio.authToken ?? process.env.TWILIO_AUTH_TOKEN;
	}
	if (resolved.provider === "plivo") {
		resolved.plivo = resolved.plivo ?? {};
		resolved.plivo.authId = resolved.plivo.authId ?? process.env.PLIVO_AUTH_ID;
		resolved.plivo.authToken = resolved.plivo.authToken ?? process.env.PLIVO_AUTH_TOKEN;
	}
	resolved.tunnel = resolved.tunnel ?? {
		provider: "none",
		allowNgrokFreeTierLoopbackBypass: false
	};
	resolved.tunnel.allowNgrokFreeTierLoopbackBypass = resolved.tunnel.allowNgrokFreeTierLoopbackBypass ?? false;
	resolved.tunnel.ngrokAuthToken = resolved.tunnel.ngrokAuthToken ?? process.env.NGROK_AUTHTOKEN;
	resolved.tunnel.ngrokDomain = resolved.tunnel.ngrokDomain ?? process.env.NGROK_DOMAIN;
	resolved.webhookSecurity = resolved.webhookSecurity ?? {
		allowedHosts: [],
		trustForwardingHeaders: false,
		trustedProxyIPs: []
	};
	resolved.webhookSecurity.allowedHosts = resolved.webhookSecurity.allowedHosts ?? [];
	resolved.webhookSecurity.trustForwardingHeaders = resolved.webhookSecurity.trustForwardingHeaders ?? false;
	resolved.webhookSecurity.trustedProxyIPs = resolved.webhookSecurity.trustedProxyIPs ?? [];
	return normalizeVoiceCallConfig(resolved);
}
/**
* Validate that the configuration has all required fields for the selected provider.
*/
function validateProviderConfig(config) {
	const errors = [];
	if (!config.enabled) return {
		valid: true,
		errors: []
	};
	if (!config.provider) errors.push("plugins.entries.voice-call.config.provider is required");
	if (!config.fromNumber && config.provider !== "mock") errors.push(config.provider === "twilio" ? "plugins.entries.voice-call.config.fromNumber is required (or set TWILIO_FROM_NUMBER env)" : "plugins.entries.voice-call.config.fromNumber is required");
	if (config.provider === "telnyx") {
		if (!config.telnyx?.apiKey) errors.push("plugins.entries.voice-call.config.telnyx.apiKey is required (or set TELNYX_API_KEY env)");
		if (!config.telnyx?.connectionId) errors.push("plugins.entries.voice-call.config.telnyx.connectionId is required (or set TELNYX_CONNECTION_ID env)");
		if (!config.skipSignatureVerification && !config.telnyx?.publicKey) errors.push("plugins.entries.voice-call.config.telnyx.publicKey is required (or set TELNYX_PUBLIC_KEY env)");
	}
	if (config.provider === "twilio") {
		if (!config.twilio?.accountSid) errors.push("plugins.entries.voice-call.config.twilio.accountSid is required (or set TWILIO_ACCOUNT_SID env)");
		if (!config.twilio?.authToken) errors.push("plugins.entries.voice-call.config.twilio.authToken is required (or set TWILIO_AUTH_TOKEN env)");
	}
	if (config.provider === "plivo") {
		if (!config.plivo?.authId) errors.push("plugins.entries.voice-call.config.plivo.authId is required (or set PLIVO_AUTH_ID env)");
		if (!config.plivo?.authToken) errors.push("plugins.entries.voice-call.config.plivo.authToken is required (or set PLIVO_AUTH_TOKEN env)");
	}
	if (config.realtime.enabled && config.inboundPolicy === "disabled") errors.push("plugins.entries.voice-call.config.inboundPolicy must not be \"disabled\" when realtime.enabled is true");
	if (config.realtime.enabled && config.streaming.enabled) errors.push("plugins.entries.voice-call.config.realtime.enabled and plugins.entries.voice-call.config.streaming.enabled cannot both be true");
	if (config.realtime.enabled && config.provider && config.provider !== "twilio") errors.push("plugins.entries.voice-call.config.provider must be \"twilio\" when realtime.enabled is true");
	return {
		valid: errors.length === 0,
		errors
	};
}
//#endregion
export { deepMergeDefined as a, validateProviderConfig as i, normalizeVoiceCallConfig as n, resolveVoiceCallConfig as r, VoiceCallConfigSchema as t };
