import { createContext as e, useCallback as t, useContext as n, useEffect as r, useRef as i, useState as a } from "react";
import { jsx as o } from "react/jsx-runtime";
//#region src/lib/ai/crypto.ts
var s = "ai-device-key";
function c(e) {
	return e.buffer.slice(e.byteOffset, e.byteOffset + e.byteLength);
}
async function l() {
	let e = [];
	e.push(navigator.userAgent), e.push(navigator.language), e.push(navigator.platform), e.push(`${screen.width}x${screen.height}x${screen.colorDepth}`), e.push(Intl.DateTimeFormat().resolvedOptions().timeZone), e.push(String(navigator.hardwareConcurrency || 0));
	let t = navigator;
	return t.deviceMemory && e.push(String(t.deviceMemory)), e.push(String(navigator.maxTouchPoints || 0)), e.join("|");
}
async function u(e, t) {
	let n = new TextEncoder(), r = await crypto.subtle.importKey("raw", n.encode(e), "PBKDF2", !1, ["deriveBits", "deriveKey"]);
	return crypto.subtle.deriveKey({
		name: "PBKDF2",
		salt: c(t),
		iterations: 1e5,
		hash: "SHA-256"
	}, r, {
		name: "AES-GCM",
		length: 256
	}, !1, ["encrypt", "decrypt"]);
}
async function d() {
	let e;
	try {
		e = localStorage.getItem(s) || "";
	} catch {
		e = "";
	}
	if (!e) {
		e = `${await l()}:${Array.from(crypto.getRandomValues(new Uint8Array(16))).map((e) => e.toString(16).padStart(2, "0")).join("")}`;
		try {
			localStorage.setItem(s, e);
		} catch {}
	}
	return e;
}
async function f(e) {
	if (!e) return "";
	try {
		let t = await d(), n = crypto.getRandomValues(new Uint8Array(16)), r = crypto.getRandomValues(new Uint8Array(12)), i = await u(t, n), a = new TextEncoder(), o = await crypto.subtle.encrypt({
			name: "AES-GCM",
			iv: r
		}, i, a.encode(e)), s = new Uint8Array(n.length + r.length + o.byteLength);
		return s.set(n, 0), s.set(r, n.length), s.set(new Uint8Array(o), n.length + r.length), btoa(String.fromCharCode(...s));
	} catch (e) {
		throw console.error("Failed to encrypt API key:", e), Error("加密失败");
	}
}
async function p(e) {
	if (!e) return "";
	try {
		let t = await d(), n = new Uint8Array(atob(e).split("").map((e) => e.charCodeAt(0))), r = n.slice(0, 16), i = n.slice(16, 28), a = n.slice(28), o = await u(t, r), s = await crypto.subtle.decrypt({
			name: "AES-GCM",
			iv: i
		}, o, a);
		return new TextDecoder().decode(s);
	} catch (e) {
		return console.error("Failed to decrypt API key:", e), "";
	}
}
function m() {
	return typeof crypto < "u" && crypto.subtle !== void 0;
}
function h(e) {
	if (!e) return "";
	let t = [];
	for (let n = 0; n < e.length; n++) t.push(e.charCodeAt(n) ^ "react-docs-ui-ai-key".charCodeAt(n % 20));
	return btoa(String.fromCharCode(...t));
}
function g(e) {
	if (!e) return "";
	try {
		let t = atob(e), n = [];
		for (let e = 0; e < t.length; e++) n.push(String.fromCharCode(t.charCodeAt(e) ^ "react-docs-ui-ai-key".charCodeAt(e % 20)));
		return n.join("");
	} catch {
		return "";
	}
}
//#endregion
//#region src/lib/ai/config.ts
var _ = "ai-config", v = [
	"openai",
	"claude",
	"gemini"
], y = (e) => v.includes(e);
function b(e) {
	return {
		openai: {
			modelId: "gpt-4o-mini",
			apiKey: "",
			baseUrl: "https://api.openai.com/v1",
			maxTokens: 4096,
			temperature: .7,
			enabled: !0
		},
		claude: {
			modelId: "claude-3-5-sonnet-20241022",
			apiKey: "",
			baseUrl: "https://api.anthropic.com",
			maxTokens: 4096,
			temperature: .7,
			enabled: !0
		},
		gemini: {
			modelId: "gemini-1.5-flash",
			apiKey: "",
			baseUrl: "https://generativelanguage.googleapis.com/v1beta",
			maxTokens: 4096,
			temperature: .7,
			enabled: !0
		}
	}[e] || {
		modelId: "",
		apiKey: "",
		baseUrl: "",
		maxTokens: 4096,
		temperature: .7,
		enabled: !0
	};
}
function x() {
	return {
		enabled: !0,
		provider: "openai",
		systemPrompt: "你是一个专业的文档助手，请根据用户的问题，提供准确、有帮助的回答。",
		models: {
			openai: b("openai"),
			claude: b("claude"),
			gemini: b("gemini")
		},
		features: {
			chatAssistant: !0,
			documentSummary: !0,
			codeExplanation: !0,
			searchEnhancement: !1
		},
		ui: {
			position: "bottom-right",
			theme: "auto",
			size: "medium"
		}
	};
}
async function S(e) {
	if (!e.apiKey) return e;
	let t = m() ? await f(e.apiKey) : h(e.apiKey);
	return {
		...e,
		apiKey: t
	};
}
async function C(e) {
	if (!e.apiKey) return e;
	let t = m() ? await p(e.apiKey) : g(e.apiKey);
	return {
		...e,
		apiKey: t
	};
}
async function w(e) {
	try {
		let t = Object.entries(e.models), n = await Promise.all(t.map(async ([e, t]) => [e, await S(t)])), r = Object.fromEntries(n), i = {
			...e,
			models: r
		};
		localStorage.setItem(_, JSON.stringify(i));
	} catch (e) {
		throw console.error("Failed to save AI config:", e), Error("保存配置失败");
	}
}
async function T() {
	try {
		let e = localStorage.getItem(_);
		if (!e) return null;
		let t = JSON.parse(e), n = Object.entries(t.models), r = await Promise.all(n.map(async ([e, t]) => [e, await C(t)])), i = Object.fromEntries(r), a = {
			enabled: t.enabled !== !1,
			provider: t.provider || "openai",
			systemPrompt: t.systemPrompt || "",
			models: i,
			features: t.features || {
				chatAssistant: !0,
				documentSummary: !0,
				codeExplanation: !0,
				searchEnhancement: !1
			},
			ui: t.ui || {
				position: "bottom-right",
				theme: "auto",
				size: "medium"
			}
		};
		if (!a.models[a.provider]?.apiKey) {
			let e = Object.keys(a.models).find((e) => a.models[e]?.apiKey);
			e && (a.provider = e, await w(a));
		}
		return a;
	} catch (e) {
		return console.error("Failed to read AI config:", e), null;
	}
}
async function E() {
	let e = await T();
	if (!e || !e.enabled) return !1;
	let t = e.models[e.provider];
	return !!(t?.apiKey && t?.modelId);
}
async function D(e) {
	let t = e || await T();
	return t && t.models[t.provider] || null;
}
async function O(e, t) {
	let n = await T() || x();
	n.models[e] = {
		...n.models[e],
		...t
	}, await w(n);
}
async function k(e) {
	let t = await T();
	if (!t) return;
	if (y(e)) throw Error("不能删除预定义的 Provider");
	let n = { ...t.models };
	delete n[e];
	let r = t.provider === e ? "openai" : t.provider;
	await w({
		...t,
		models: n,
		provider: r
	});
}
function A() {
	try {
		localStorage.removeItem(_);
	} catch (e) {
		console.error("Failed to clear AI config:", e);
	}
}
function j(e) {
	if (!e.apiKey) return {
		valid: !1,
		message: "API密钥不能为空"
	};
	if (!e.modelId) return {
		valid: !1,
		message: "模型ID不能为空"
	};
	if (!e.baseUrl) return {
		valid: !1,
		message: "API地址不能为空"
	};
	try {
		new URL(e.baseUrl);
	} catch {
		return {
			valid: !1,
			message: "API地址格式不正确"
		};
	}
	return {
		valid: !0,
		message: ""
	};
}
async function M() {
	let e = await T();
	if (!e) return [...v];
	let t = Object.keys(e.models).filter((e) => !y(e));
	return [...v, ...t];
}
//#endregion
//#region src/lib/ai/providers/base.ts
var N = class {
	config;
	constructor(e) {
		this.config = e;
	}
	validateConfig() {
		return !!(this.config.apiKey && this.config.baseUrl && this.config.modelId);
	}
	updateConfig(e) {
		this.config = {
			...this.config,
			...e
		};
	}
	generateId() {
		return `msg_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
	}
	formatMessages(e) {
		return e.filter((e) => e.role !== "system").map((e) => ({
			role: e.role,
			content: e.content
		}));
	}
	async makeRequest(e, t, n, r) {
		let i = await fetch(e, {
			method: "POST",
			headers: n,
			body: JSON.stringify(t),
			signal: r
		});
		if (!i.ok) {
			let e = await i.text(), t = `HTTP ${i.status}`;
			try {
				let n = JSON.parse(e);
				t = n.error?.message || n.message || t;
			} catch {}
			throw Error(t);
		}
		return i;
	}
	async readStream(e, t, n) {
		let r = e.body?.getReader();
		if (!r) throw Error("无法读取响应流");
		let i = new TextDecoder(), a = "";
		try {
			for (;;) {
				let { done: e, value: t } = await r.read();
				if (e) {
					a.trim() && n(a);
					break;
				}
				a += i.decode(t, { stream: !0 });
				let o = a.split("\n");
				a = o.pop() || "";
				for (let e of o) e.trim() && n(e);
			}
		} finally {
			r.releaseLock();
		}
	}
}, P = class extends N {
	async chat(e, t, n) {
		let r = `${this.config.baseUrl}/chat/completions`, i = this.buildHeaders(), a = this.buildRequestBody(e);
		t({ type: "start" });
		try {
			let e = await this.makeRequest(r, a, i, n);
			await this.readStream(e, t, (e) => {
				this.parseStreamChunk(e, t);
			}), t({ type: "done" });
		} catch (e) {
			e instanceof Error && e.name === "AbortError" ? t({
				type: "error",
				error: "请求已取消"
			}) : t({
				type: "error",
				error: e instanceof Error ? e.message : "未知错误"
			});
		}
	}
	async testConnection() {
		try {
			let e = `${this.config.baseUrl}/models`, t = this.buildHeaders(), n = await fetch(e, {
				method: "GET",
				headers: t
			});
			if (!n.ok) {
				let e = await n.text(), t = `HTTP ${n.status}`;
				try {
					let n = JSON.parse(e);
					t = n.error?.message || n.message || t;
				} catch {}
				return {
					success: !1,
					message: t
				};
			}
			let r = await n.json(), i = (r.data || r.models || []).find((e) => e.id === this.config.modelId || e.id?.includes(this.config.modelId));
			return {
				success: !0,
				message: "连接成功",
				modelInfo: {
					id: this.config.modelId,
					name: i?.id || this.config.modelId
				}
			};
		} catch (e) {
			return {
				success: !1,
				message: e instanceof Error ? e.message : "连接失败"
			};
		}
	}
	buildHeaders() {
		return {
			"Content-Type": "application/json",
			Authorization: `Bearer ${this.config.apiKey}`
		};
	}
	buildRequestBody(e) {
		let t = [];
		this.config.systemPrompt && t.push({
			role: "system",
			content: this.config.systemPrompt
		});
		for (let n of e) n.role !== "system" && t.push({
			role: n.role,
			content: n.content
		});
		return {
			model: this.config.modelId,
			messages: t,
			max_tokens: this.config.maxTokens,
			temperature: this.config.temperature,
			stream: !0
		};
	}
	parseStreamChunk(e, t) {
		let n = e.split("\n");
		for (let e of n) {
			let n = e.trim();
			if (!n || !n.startsWith("data: ")) continue;
			let r = n.slice(6);
			if (r === "[DONE]") {
				t({ type: "done" });
				return;
			}
			try {
				let e = JSON.parse(r), n = e.choices?.[0]?.delta?.content;
				n && t({
					type: "delta",
					content: n
				}), e.choices?.[0]?.finish_reason === "stop" && t({ type: "done" });
			} catch {}
		}
	}
}, F = class extends N {
	async chat(e, t, n) {
		let r = `${this.config.baseUrl}/v1/messages`, i = this.buildHeaders(), a = this.buildRequestBody(e);
		t({ type: "start" });
		try {
			let e = await this.makeRequest(r, a, i, n);
			await this.readStream(e, t, (e) => {
				this.parseStreamChunk(e, t);
			}), t({ type: "done" });
		} catch (e) {
			e instanceof Error && e.name === "AbortError" ? t({
				type: "error",
				error: "请求已取消"
			}) : t({
				type: "error",
				error: e instanceof Error ? e.message : "未知错误"
			});
		}
	}
	async testConnection() {
		try {
			let e = `${this.config.baseUrl}/v1/messages`, t = this.buildHeaders(), n = await fetch(e, {
				method: "POST",
				headers: t,
				body: JSON.stringify({
					model: this.config.modelId,
					max_tokens: 1,
					messages: [{
						role: "user",
						content: "hi"
					}]
				})
			});
			if (!n.ok) {
				let e = await n.text(), t = `HTTP ${n.status}`;
				try {
					let n = JSON.parse(e);
					t = n.error?.message || n.message || t;
				} catch {}
				return {
					success: !1,
					message: t
				};
			}
			return {
				success: !0,
				message: "连接成功",
				modelInfo: { id: this.config.modelId }
			};
		} catch (e) {
			return {
				success: !1,
				message: e instanceof Error ? e.message : "连接失败"
			};
		}
	}
	buildHeaders() {
		return {
			"Content-Type": "application/json",
			"x-api-key": this.config.apiKey,
			"anthropic-version": "2023-06-01",
			"anthropic-dangerous-direct-browser-access": "true"
		};
	}
	buildRequestBody(e) {
		let t = [];
		for (let n of e) n.role !== "system" && t.push({
			role: n.role,
			content: n.content
		});
		(t.length === 0 || t[t.length - 1].role !== "user") && t.push({
			role: "user",
			content: "请继续"
		});
		let n = {
			model: this.config.modelId,
			messages: t,
			max_tokens: this.config.maxTokens || 4096,
			stream: !0
		};
		return this.config.systemPrompt && (n.system = this.config.systemPrompt), this.config.temperature !== void 0 && (n.temperature = this.config.temperature), n;
	}
	parseStreamChunk(e, t) {
		let n = e.split("\n");
		for (let e of n) {
			let n = e.trim();
			if (!n || !n.startsWith("data: ")) continue;
			let r = n.slice(6);
			try {
				let e = JSON.parse(r);
				switch (e.type) {
					case "content_block_delta":
						e.delta?.type === "text_delta" && e.delta.text && t({
							type: "delta",
							content: e.delta.text
						});
						break;
					case "message_delta": break;
					case "message_start": break;
					case "message_stop":
						t({ type: "done" });
						break;
					case "content_block_stop": break;
					case "error":
						e.error && t({
							type: "error",
							error: e.error.message || "API错误"
						});
						break;
					case "ping": break;
				}
			} catch {}
		}
	}
}, I = class extends N {
	async chat(e, t, n) {
		let r = this.buildStreamUrl(), i = this.buildHeaders(), a = this.buildRequestBody(e);
		t({ type: "start" });
		try {
			let e = await this.makeRequest(r, a, i, n);
			await this.readStream(e, t, (e) => {
				this.parseStreamChunk(e, t);
			}), t({ type: "done" });
		} catch (e) {
			e instanceof Error && e.name === "AbortError" ? t({
				type: "error",
				error: "请求已取消"
			}) : t({
				type: "error",
				error: e instanceof Error ? e.message : "未知错误"
			});
		}
	}
	async testConnection() {
		try {
			let e = this.buildGenerateContentUrl(), t = await fetch(e, {
				method: "POST",
				headers: this.buildHeaders(),
				body: JSON.stringify({
					contents: [{
						parts: [{ text: "hi" }],
						role: "user"
					}],
					generationConfig: { maxOutputTokens: 1 }
				})
			});
			if (!t.ok) {
				let e = await t.text(), n = `HTTP ${t.status}`;
				try {
					n = JSON.parse(e).error?.message || n;
				} catch {}
				return {
					success: !1,
					message: n
				};
			}
			return {
				success: !0,
				message: "连接成功",
				modelInfo: { id: this.config.modelId }
			};
		} catch (e) {
			return {
				success: !1,
				message: e instanceof Error ? e.message : "连接失败"
			};
		}
	}
	buildStreamUrl() {
		return `${this.config.baseUrl}/models/${this.config.modelId}:streamGenerateContent?alt=sse&key=${this.config.apiKey}`;
	}
	buildGenerateContentUrl() {
		return `${this.config.baseUrl}/models/${this.config.modelId}:generateContent?key=${this.config.apiKey}`;
	}
	buildHeaders() {
		return { "Content-Type": "application/json" };
	}
	buildRequestBody(e) {
		let t = [];
		for (let n of e) n.role !== "system" && t.push({
			role: n.role === "assistant" ? "model" : "user",
			parts: [{ text: n.content }]
		});
		let n = {
			contents: t,
			generationConfig: {
				maxOutputTokens: this.config.maxTokens,
				temperature: this.config.temperature
			}
		};
		return this.config.systemPrompt && (n.systemInstruction = { parts: [{ text: this.config.systemPrompt }] }), n;
	}
	parseStreamChunk(e, t) {
		let n = e.split("\n");
		for (let e of n) {
			let n = e.trim();
			if (!n || !n.startsWith("data: ")) continue;
			let r = n.slice(6);
			try {
				let e = JSON.parse(r);
				if (e.error) {
					t({
						type: "error",
						error: e.error.message || "API错误"
					});
					return;
				}
				if (e.candidates && e.candidates.length > 0) {
					let n = e.candidates[0];
					if (n.content?.parts) for (let e of n.content.parts) e.text && t({
						type: "delta",
						content: e.text
					});
					(n.finishReason === "STOP" || n.finishReason === "MAX_TOKENS") && t({ type: "done" });
				}
			} catch {}
		}
	}
}, L = [
	"openai",
	"claude",
	"gemini"
], R = (e) => L.includes(e);
function z(e, t) {
	if (R(e)) switch (e) {
		case "openai": return new P(t);
		case "claude": return new F(t);
		case "gemini": return new I(t);
	}
	return new P(t);
}
function B(e) {
	if (!e) return "Unknown";
	let t = {
		openai: "OpenAI",
		claude: "Claude (Anthropic)",
		gemini: "Google Gemini"
	};
	return e in t ? t[e] : e.charAt(0).toUpperCase() + e.slice(1);
}
function V(e) {
	if (!e) return [];
	let t = {
		openai: [
			"gpt-4o",
			"gpt-4o-mini",
			"gpt-4-turbo",
			"gpt-4",
			"gpt-3.5-turbo"
		],
		claude: [
			"claude-3-5-sonnet-20241022",
			"claude-3-5-haiku-20241022",
			"claude-3-opus-20240229",
			"claude-3-sonnet-20240229",
			"claude-3-haiku-20240307"
		],
		gemini: [
			"gemini-1.5-pro",
			"gemini-1.5-flash",
			"gemini-1.5-flash-8b",
			"gemini-1.0-pro"
		]
	};
	return e in t ? t[e] : [];
}
function H(e) {
	if (!e) return {
		apiKeyUrl: "",
		docsUrl: ""
	};
	let t = {
		openai: {
			apiKeyUrl: "https://platform.openai.com/api-keys",
			docsUrl: "https://platform.openai.com/docs"
		},
		claude: {
			apiKeyUrl: "https://console.anthropic.com/settings/keys",
			docsUrl: "https://docs.anthropic.com"
		},
		gemini: {
			apiKeyUrl: "https://aistudio.google.com/apikey",
			docsUrl: "https://ai.google.dev/docs"
		}
	};
	return e in t ? t[e] : {
		apiKeyUrl: "",
		docsUrl: ""
	};
}
//#endregion
//#region src/lib/ai/chat.ts
var U = 6e4, W = 3, G = 1e3;
async function ee(e) {
	return new Promise((t) => setTimeout(t, e));
}
function te(e) {
	let t = [
		"network",
		"timeout",
		"ECONNREFUSED",
		"ETIMEDOUT",
		"ENOTFOUND",
		"rate limit",
		"429",
		"503",
		"502",
		"500"
	], n = e.message.toLowerCase();
	return t.some((e) => n.includes(e.toLowerCase()));
}
function ne(e, t) {
	if (!t) return e;
	let n = [];
	return t.selectedText && n.push(`【选中的内容】\n${t.selectedText}\n`), t.pageTitle && n.push(`【当前页面】${t.pageTitle}`), n.push(e), n.join("\n");
}
function re(e, t) {
	if (!t) return e;
	let n = [e];
	return t.selectedText && n.push("\n用户选中了文章中的部分内容，请基于选中的内容回答问题。"), t.extraContext && n.push(`\n${t.extraContext}`), n.join("");
}
async function K(e, t, n, r, i, a) {
	let o = a?.timeout ?? U, s = a?.retryCount ?? W, c = a?.retryDelay ?? G, l = n || await T();
	if (!l || !l.enabled) {
		t({
			type: "error",
			error: "AI功能未启用"
		});
		return;
	}
	let u = await D(l);
	if (!u?.apiKey) {
		t({
			type: "error",
			error: "请先配置API密钥"
		});
		return;
	}
	let d = {
		type: l.provider,
		apiKey: u.apiKey,
		baseUrl: u.baseUrl,
		modelId: u.modelId,
		systemPrompt: re(l.systemPrompt, r),
		maxTokens: u.maxTokens,
		temperature: u.temperature
	}, f = z(l.provider, d), p = null;
	for (let n = 0; n < s; n++) {
		if (i?.aborted) {
			t({
				type: "error",
				error: "请求已取消"
			});
			return;
		}
		try {
			let n = setTimeout(() => {
				t({
					type: "error",
					error: `请求超时（${o / 1e3}秒）`
				});
			}, o);
			await f.chat(e, t, i), clearTimeout(n);
			return;
		} catch (e) {
			if (p = e instanceof Error ? e : /* @__PURE__ */ Error("未知错误"), i?.aborted) {
				t({
					type: "error",
					error: "请求已取消"
				});
				return;
			}
			if (!te(p)) {
				t({
					type: "error",
					error: p.message
				});
				return;
			}
			n < s - 1 && (t({
				type: "error",
				error: `连接失败，${c / 1e3}秒后重试 (${n + 1}/${s})...`
			}), await ee(c * (n + 1)));
		}
	}
	t({
		type: "error",
		error: p?.message || "请求失败，请稍后重试"
	});
}
async function ie(e, t, n) {
	return t.apiKey ? z(e, {
		type: e,
		apiKey: t.apiKey,
		baseUrl: t.baseUrl,
		modelId: t.modelId,
		systemPrompt: n || "",
		maxTokens: t.maxTokens,
		temperature: t.temperature
	}).testConnection() : {
		success: !1,
		message: "API密钥不能为空"
	};
}
function q() {
	return `msg_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
}
function J(e) {
	return {
		id: q(),
		role: "user",
		content: e,
		timestamp: Date.now()
	};
}
function Y(e = "") {
	return {
		id: q(),
		role: "assistant",
		content: e,
		timestamp: Date.now(),
		isStreaming: !0
	};
}
function X(e, t, n = !1, r) {
	return {
		...e,
		content: t,
		isStreaming: n,
		error: r
	};
}
//#endregion
//#region src/components/ai/AIProvider.tsx
var Z = "ai-current-session", ae = 6e4, Q = e(null), $ = null;
async function oe() {
	let e = Date.now();
	if ($ && e - $.timestamp < ae) return $.config;
	let t = await T();
	return $ = {
		config: t,
		timestamp: e
	}, t;
}
function se() {
	$ = null;
}
function ce({ children: e }) {
	let [n, s] = a(null), [c, l] = a(!1), [u, d] = a(!1), [f, p] = a(null), [m, h] = a(null), [g, _] = a([]), [v, y] = a(""), [b, x] = a(), [S, C] = a(!1), [T, D] = a(!1), O = i(null);
	r(() => {
		let e = !1;
		return (async () => {
			try {
				let t = await oe();
				if (e) return;
				s(t);
				let n = await E();
				if (e) return;
				l(n);
				let r = localStorage.getItem(Z);
				if (r && !e) try {
					let e = JSON.parse(r);
					h(e), _(e.messages);
				} catch {
					console.error("[AI] Failed to load session");
				}
			} catch (e) {
				console.error("[AI] 加载 AI 配置失败:", e);
			}
		})(), () => {
			e = !0;
		};
	}, []);
	let k = t((e) => {
		try {
			let t = m || {
				id: `session_${Date.now()}`,
				title: "新对话",
				messages: [],
				createdAt: Date.now(),
				updatedAt: Date.now()
			}, n = {
				...t,
				messages: e,
				updatedAt: Date.now(),
				title: e[0]?.content?.slice(0, 50) || t.title
			};
			h(n), localStorage.setItem(Z, JSON.stringify(n));
		} catch {
			console.error("[AI] Failed to save session");
		}
	}, [m]), A = t((e) => {
		e && (x(e), y(e.selectedText || "")), C(!0);
	}, []), j = t(() => {
		C(!1);
	}, []), M = t(() => {
		D(!0);
	}, []), N = t(() => {
		D(!1);
	}, []), P = t(async (e, t) => {
		if (!n || u) return;
		let r = Y();
		_([...e, r]), d(!0), p(null), O.current = new AbortController();
		let i = "";
		try {
			await K(e, (e) => {
				switch (e.type) {
					case "delta":
						e.content && (i += e.content, _((e) => {
							let t = [...e], n = t.length - 1;
							return n >= 0 && t[n].role === "assistant" && (t[n] = X(t[n], i, !0)), t;
						}));
						break;
					case "done":
						_((e) => {
							let t = [...e], n = t.length - 1;
							return n >= 0 && t[n].role === "assistant" && (t[n] = X(t[n], i, !1)), k(t), t;
						}), t?.();
						break;
					case "error":
						e.error === "请求已取消" ? _((e) => {
							let t = [...e], n = t.length - 1;
							if (n >= 0 && t[n].role === "assistant") {
								let e = t[n].content, r = e.match(/```/g);
								r && r.length % 2 != 0 && (e += "\n```"), t[n] = X(t[n], e, !1);
							}
							return k(t), t;
						}) : (p(e.error || "发生错误"), _((t) => {
							let n = [...t], r = n.length - 1;
							return r >= 0 && n[r].role === "assistant" && (n[r] = X(n[r], i, !1, e.error)), n;
						}));
						break;
				}
			}, n ?? void 0, b, O.current.signal);
		} catch (e) {
			p(e instanceof Error ? e.message : "发送失败");
		} finally {
			d(!1), O.current = null;
		}
	}, [
		n,
		u,
		b,
		k
	]), F = t(async (e) => {
		if (!n || u) return;
		let t = J(ne(e, b));
		await P(g.concat(t));
	}, [
		n,
		g,
		u,
		b,
		P
	]), I = t(async () => {
		if (g.length < 2 || u) return;
		let e = g.slice(0, -1);
		_(e), e.filter((e) => e.role === "user").pop() && await P(e);
	}, [
		g,
		u,
		P
	]), L = t(() => {
		_([]), h(null), localStorage.removeItem(Z);
	}, []), R = t(async (e) => {
		let t = n ? {
			...n,
			...e
		} : { ...e };
		e.models && n?.models && (t.models = {
			...n.models,
			...e.models
		}), await w(t), se(), s(t), l(await E());
	}, [n]), z = t(() => {
		O.current &&= (O.current.abort(), null);
	}, []), B = {
		config: n,
		isConfigured: c,
		isLoading: u,
		error: f,
		currentSession: m,
		messages: g,
		selectedText: v,
		setSelectedText: y,
		isDialogOpen: S,
		openDialog: A,
		closeDialog: j,
		isSettingsOpen: T,
		openSettings: M,
		closeSettings: N,
		sendMessage: F,
		regenerateLast: I,
		clearHistory: L,
		updateConfig: R,
		switchProvider: t(async (e) => {
			await R({ provider: e });
		}, [R]),
		stopGeneration: z,
		editMessage: t((e, t) => {
			_((n) => {
				let r = n.findIndex((t) => t.id === e);
				if (r === -1) return n;
				let i = [...n];
				if (i[r] = {
					...i[r],
					content: t,
					timestamp: Date.now()
				}, i[r].role === "user") {
					let e = i.slice(0, r + 1);
					return k(e), e;
				}
				return k(i), i;
			});
		}, [k]),
		deleteMessage: t((e) => {
			_((t) => {
				let n = t.findIndex((t) => t.id === e);
				if (n === -1) return t;
				let r = t.slice(0, n);
				return k(r), r;
			});
		}, [k])
	};
	return /* @__PURE__ */ o(Q.Provider, {
		value: B,
		children: e
	});
}
function le() {
	let e = n(Q);
	if (!e) throw Error("useAI must be used within an AIProvider");
	return e;
}
//#endregion
export { j as S, x as _, q as a, w as b, z as c, H as d, A as f, D as g, M as h, J as i, V as l, T as m, le as n, K as o, k as p, Y as r, ie as s, ce as t, B as u, b as v, O as x, E as y };
