"use strict";exports.id=7486,exports.ids=[7486],exports.modules={64451:(e,t,T)=>{T.d(t,{L:()=>E});var i=T(53236),r=T(23734),o=T.n(r),a=T(92795),n=T(93334);let E={session:{strategy:"jwt"},pages:{signIn:"/login"},providers:[(0,i.Z)({name:"credentials",credentials:{email:{label:"Email",type:"email"},password:{label:"Password",type:"password"}},async authorize(e){if(!e?.email||!e?.password)return null;await (0,n.X)(a._);let t=await a._.user.findUnique({where:{email:e.email.toLowerCase()}});if(!t||!await o().compare(e.password,t.password))return null;if(!t.emailVerified)throw Error("EMAIL_NOT_VERIFIED");return{id:t.id,email:t.email,name:t.name??void 0}}})],callbacks:{jwt:async({token:e,user:t})=>(t&&(e.id=t.id),e),session:async({session:e,token:t})=>(e.user&&t.id&&(e.user.id=t.id),e)}}},93334:(e,t,T)=>{T.d(t,{X:()=>a});let i=globalThis,r=[`
  CREATE TABLE IF NOT EXISTS "User" (
      "id" TEXT NOT NULL,
      "email" TEXT NOT NULL,
      "password" TEXT NOT NULL,
      "name" TEXT,
      "firstName" TEXT,
      "lastName" TEXT,
      "photoUrl" TEXT,
      "emailVerified" TIMESTAMP(3),
      "verificationToken" TEXT,
      "verificationTokenExpiry" TIMESTAMP(3),
      "aiProvider" TEXT NOT NULL DEFAULT 'gemini',
      "aiModel" TEXT,
      "aiOpenaiKey" TEXT,
      "aiAnthropicKey" TEXT,
      "aiGeminiKey" TEXT,
      "aiMistralKey" TEXT,
      "aiGroqKey" TEXT,
      "aiDeepseekKey" TEXT,
      "aiXaiKey" TEXT,
      "aiCohereKey" TEXT,
      "aiPerplexityKey" TEXT,
      "aiOllamaKey" TEXT,
      "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
      "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
      CONSTRAINT "User_pkey" PRIMARY KEY ("id")
  )
  `,'ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "name" TEXT','ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "firstName" TEXT','ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "lastName" TEXT','ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "photoUrl" TEXT','ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "emailVerified" TIMESTAMP(3)','ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "verificationToken" TEXT','ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "verificationTokenExpiry" TIMESTAMP(3)','ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "aiProvider" TEXT DEFAULT \'gemini\'','ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "aiModel" TEXT','ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "aiOpenaiKey" TEXT','ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "aiAnthropicKey" TEXT','ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "aiGeminiKey" TEXT','ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "aiMistralKey" TEXT','ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "aiGroqKey" TEXT','ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "aiDeepseekKey" TEXT','ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "aiXaiKey" TEXT','ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "aiCohereKey" TEXT','ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "aiPerplexityKey" TEXT','ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "aiOllamaKey" TEXT','ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP','ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP','CREATE UNIQUE INDEX IF NOT EXISTS "User_email_key" ON "User"("email")',`
  CREATE TABLE IF NOT EXISTS "Profile" (
      "id" TEXT NOT NULL,
      "userId" TEXT NOT NULL,
      "fullName" TEXT NOT NULL DEFAULT '',
      "email" TEXT NOT NULL DEFAULT '',
      "phone" TEXT NOT NULL DEFAULT '',
      "location" TEXT NOT NULL DEFAULT '',
      "linkedinUrl" TEXT NOT NULL DEFAULT '',
      "websiteUrl" TEXT NOT NULL DEFAULT '',
      "summary" TEXT NOT NULL DEFAULT '',
      "skills" JSONB NOT NULL DEFAULT '[]',
      "experience" JSONB NOT NULL DEFAULT '[]',
      "education" JSONB NOT NULL DEFAULT '[]',
      "certifications" JSONB NOT NULL DEFAULT '[]',
      "projects" JSONB NOT NULL DEFAULT '[]',
      "languages" JSONB NOT NULL DEFAULT '[]',
      "atsScore" INTEGER,
      "lastAnalysis" TEXT,
      "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
      "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
      CONSTRAINT "Profile_pkey" PRIMARY KEY ("id")
  )
  `,'ALTER TABLE "Profile" ADD COLUMN IF NOT EXISTS "fullName" TEXT NOT NULL DEFAULT \'\'','ALTER TABLE "Profile" ADD COLUMN IF NOT EXISTS "email" TEXT NOT NULL DEFAULT \'\'','ALTER TABLE "Profile" ADD COLUMN IF NOT EXISTS "phone" TEXT NOT NULL DEFAULT \'\'','ALTER TABLE "Profile" ADD COLUMN IF NOT EXISTS "location" TEXT NOT NULL DEFAULT \'\'','ALTER TABLE "Profile" ADD COLUMN IF NOT EXISTS "linkedinUrl" TEXT NOT NULL DEFAULT \'\'','ALTER TABLE "Profile" ADD COLUMN IF NOT EXISTS "websiteUrl" TEXT NOT NULL DEFAULT \'\'','ALTER TABLE "Profile" ADD COLUMN IF NOT EXISTS "summary" TEXT NOT NULL DEFAULT \'\'','ALTER TABLE "Profile" ADD COLUMN IF NOT EXISTS "skills" JSONB NOT NULL DEFAULT \'[]\'','ALTER TABLE "Profile" ADD COLUMN IF NOT EXISTS "experience" JSONB NOT NULL DEFAULT \'[]\'','ALTER TABLE "Profile" ADD COLUMN IF NOT EXISTS "education" JSONB NOT NULL DEFAULT \'[]\'','ALTER TABLE "Profile" ADD COLUMN IF NOT EXISTS "certifications" JSONB NOT NULL DEFAULT \'[]\'','ALTER TABLE "Profile" ADD COLUMN IF NOT EXISTS "projects" JSONB NOT NULL DEFAULT \'[]\'','ALTER TABLE "Profile" ADD COLUMN IF NOT EXISTS "languages" JSONB NOT NULL DEFAULT \'[]\'','ALTER TABLE "Profile" ADD COLUMN IF NOT EXISTS "atsScore" INTEGER','ALTER TABLE "Profile" ADD COLUMN IF NOT EXISTS "lastAnalysis" TEXT','ALTER TABLE "Profile" ADD COLUMN IF NOT EXISTS "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP','ALTER TABLE "Profile" ADD COLUMN IF NOT EXISTS "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP','ALTER TABLE "Profile" DROP COLUMN IF EXISTS "targetTitle"','CREATE UNIQUE INDEX IF NOT EXISTS "Profile_userId_key" ON "Profile"("userId")',`
  CREATE TABLE IF NOT EXISTS "JobListing" (
      "id" TEXT NOT NULL,
      "userId" TEXT NOT NULL,
      "url" TEXT NOT NULL,
      "title" TEXT NOT NULL DEFAULT '',
      "company" TEXT NOT NULL DEFAULT '',
      "location" TEXT NOT NULL DEFAULT '',
      "rawContent" TEXT NOT NULL DEFAULT '',
      "description" TEXT NOT NULL DEFAULT '',
      "fitScore" INTEGER,
      "fitAnalysis" TEXT,
      "tailoredCvHtml" TEXT,
      "coverLetterHtml" TEXT,
      "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
      "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
      CONSTRAINT "JobListing_pkey" PRIMARY KEY ("id")
  )
  `,'ALTER TABLE "JobListing" ADD COLUMN IF NOT EXISTS "title" TEXT NOT NULL DEFAULT \'\'','ALTER TABLE "JobListing" ADD COLUMN IF NOT EXISTS "company" TEXT NOT NULL DEFAULT \'\'','ALTER TABLE "JobListing" ADD COLUMN IF NOT EXISTS "location" TEXT NOT NULL DEFAULT \'\'','ALTER TABLE "JobListing" ADD COLUMN IF NOT EXISTS "rawContent" TEXT NOT NULL DEFAULT \'\'','ALTER TABLE "JobListing" ADD COLUMN IF NOT EXISTS "description" TEXT NOT NULL DEFAULT \'\'','ALTER TABLE "JobListing" ADD COLUMN IF NOT EXISTS "fitScore" INTEGER','ALTER TABLE "JobListing" ADD COLUMN IF NOT EXISTS "fitAnalysis" TEXT','ALTER TABLE "JobListing" ADD COLUMN IF NOT EXISTS "tailoredCvHtml" TEXT','ALTER TABLE "JobListing" ADD COLUMN IF NOT EXISTS "coverLetterHtml" TEXT','ALTER TABLE "JobListing" ADD COLUMN IF NOT EXISTS "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP','ALTER TABLE "JobListing" ADD COLUMN IF NOT EXISTS "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP',`
  CREATE TABLE IF NOT EXISTS "PromptTemplate" (
      "id" TEXT NOT NULL,
      "key" TEXT NOT NULL,
      "label" TEXT NOT NULL,
      "description" TEXT NOT NULL DEFAULT '',
      "defaultContent" TEXT NOT NULL,
      "activeContent" TEXT NOT NULL,
      "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
      "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
      CONSTRAINT "PromptTemplate_pkey" PRIMARY KEY ("id")
  )
  `,'ALTER TABLE "PromptTemplate" ADD COLUMN IF NOT EXISTS "key" TEXT NOT NULL DEFAULT \'\'','ALTER TABLE "PromptTemplate" ADD COLUMN IF NOT EXISTS "label" TEXT NOT NULL DEFAULT \'\'','ALTER TABLE "PromptTemplate" ADD COLUMN IF NOT EXISTS "description" TEXT NOT NULL DEFAULT \'\'','ALTER TABLE "PromptTemplate" ADD COLUMN IF NOT EXISTS "defaultContent" TEXT NOT NULL DEFAULT \'\'','ALTER TABLE "PromptTemplate" ADD COLUMN IF NOT EXISTS "activeContent" TEXT NOT NULL DEFAULT \'\'','ALTER TABLE "PromptTemplate" ADD COLUMN IF NOT EXISTS "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP','ALTER TABLE "PromptTemplate" ADD COLUMN IF NOT EXISTS "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP','CREATE UNIQUE INDEX IF NOT EXISTS "PromptTemplate_key_key" ON "PromptTemplate"("key")',`
  CREATE TABLE IF NOT EXISTS "PromptTemplateVersion" (
      "id" TEXT NOT NULL,
      "promptKey" TEXT NOT NULL,
      "version" INTEGER NOT NULL,
      "content" TEXT NOT NULL,
      "updatedBy" TEXT,
      "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
      CONSTRAINT "PromptTemplateVersion_pkey" PRIMARY KEY ("id")
  )
  `,'ALTER TABLE "PromptTemplateVersion" ADD COLUMN IF NOT EXISTS "promptKey" TEXT NOT NULL DEFAULT \'\'','ALTER TABLE "PromptTemplateVersion" ADD COLUMN IF NOT EXISTS "version" INTEGER NOT NULL DEFAULT 1','ALTER TABLE "PromptTemplateVersion" ADD COLUMN IF NOT EXISTS "content" TEXT NOT NULL DEFAULT \'\'','ALTER TABLE "PromptTemplateVersion" ADD COLUMN IF NOT EXISTS "updatedBy" TEXT','ALTER TABLE "PromptTemplateVersion" ADD COLUMN IF NOT EXISTS "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP','CREATE INDEX IF NOT EXISTS "PromptTemplateVersion_promptKey_version_idx" ON "PromptTemplateVersion"("promptKey", "version")',`
  DO $$
  BEGIN
      IF NOT EXISTS (
          SELECT 1 FROM pg_constraint WHERE conname = 'Profile_userId_fkey'
      ) THEN
          ALTER TABLE "Profile"
              ADD CONSTRAINT "Profile_userId_fkey"
              FOREIGN KEY ("userId") REFERENCES "User"("id")
              ON DELETE CASCADE ON UPDATE CASCADE;
      END IF;
  END $$;
  `,`
  DO $$
  BEGIN
      IF NOT EXISTS (
          SELECT 1 FROM pg_constraint WHERE conname = 'JobListing_userId_fkey'
      ) THEN
          ALTER TABLE "JobListing"
              ADD CONSTRAINT "JobListing_userId_fkey"
              FOREIGN KEY ("userId") REFERENCES "User"("id")
              ON DELETE CASCADE ON UPDATE CASCADE;
      END IF;
  END $$;
  `,`
  DO $$
  BEGIN
      IF NOT EXISTS (
          SELECT 1 FROM pg_constraint WHERE conname = 'PromptTemplateVersion_promptKey_fkey'
      ) THEN
          ALTER TABLE "PromptTemplateVersion"
              ADD CONSTRAINT "PromptTemplateVersion_promptKey_fkey"
              FOREIGN KEY ("promptKey") REFERENCES "PromptTemplate"("key")
              ON DELETE CASCADE ON UPDATE CASCADE;
      END IF;
  END $$;
  `];async function o(e){for(let t of r)await e.$executeRawUnsafe(t)}async function a(e){"true"!==String(process.env.LOCAL_DEV_MODE||"").toLowerCase()&&(i.hyremeSchemaReady||(i.hyremeSchemaReady=o(e).catch(e=>{throw i.hyremeSchemaReady=void 0,e})),await i.hyremeSchemaReady)}},4355:(e,t,T)=>{T.d(t,{Cw:()=>N,Q7:()=>r,_C:()=>c,aA:()=>o,cp:()=>l,sG:()=>X,vA:()=>a});var i=T(92795);class r extends Error{constructor(e="No AI provider is configured. Open Settings → AI Providers to add one."){super(e),this.code="AI_NOT_CONFIGURED"}}let o=["openai","anthropic","gemini","mistral","groq","deepseek","xai","cohere","perplexity","ollama"],a={openai:"OpenAI (ChatGPT)",anthropic:"Anthropic (Claude)",gemini:"Google (Gemini)",mistral:"Mistral AI",groq:"Groq",deepseek:"DeepSeek",xai:"xAI (Grok)",cohere:"Cohere",perplexity:"Perplexity",ollama:"Ollama Cloud"},n={openai:"gpt-4o-mini",anthropic:"claude-3-5-sonnet-latest",gemini:"gemini-1.5-flash",mistral:"mistral-large-latest",groq:"llama-3.3-70b-versatile",deepseek:"deepseek-chat",xai:"grok-2-latest",cohere:"command-r-plus",perplexity:"sonar",ollama:"gpt-oss:20b-cloud"},E={openai:"aiOpenaiKey",anthropic:"aiAnthropicKey",gemini:"aiGeminiKey",mistral:"aiMistralKey",groq:"aiGroqKey",deepseek:"aiDeepseekKey",xai:"aiXaiKey",cohere:"aiCohereKey",perplexity:"aiPerplexityKey",ollama:"aiOllamaKey"},s={openai:"https://api.openai.com/v1/chat/completions",mistral:"https://api.mistral.ai/v1/chat/completions",groq:"https://api.groq.com/openai/v1/chat/completions",deepseek:"https://api.deepseek.com/chat/completions",xai:"https://api.x.ai/v1/chat/completions",perplexity:"https://api.perplexity.ai/chat/completions"};async function L(e){let t=await i._.user.findUnique({where:{id:e},select:{aiProvider:!0,aiModel:!0,aiOpenaiKey:!0,aiAnthropicKey:!0,aiGeminiKey:!0,aiMistralKey:!0,aiGroqKey:!0,aiDeepseekKey:!0,aiXaiKey:!0,aiCohereKey:!0,aiPerplexityKey:!0,aiOllamaKey:!0}});if(!t)throw new r;let T=o.includes(t.aiProvider)?t.aiProvider:"gemini",s=E[T],L=t[s]?.trim()||"";if(!L)throw new r(`No API key saved for ${a[T]||T}. Open Settings \u2192 AI Providers to add one.`);let N=t.aiModel&&t.aiModel.trim()||n[T];return{provider:T,model:N,apiKey:L}}function N(e,t="Unknown AI error"){if(e instanceof Error&&e.message.trim())return e.message.trim();if("string"==typeof e&&e.trim())return e.trim();if(e&&"object"==typeof e){let t="string"==typeof e.message?e.message.trim():"";if(t)return t;let T="string"==typeof e.error?e.error.trim():"";if(T)return T;let i=e.error;if(i&&"object"==typeof i){let e="string"==typeof i.message?String(i.message).trim():"";if(e)return e}try{let t=JSON.stringify(e);if(t&&"{}"!==t)return t}catch{}}return t}async function A(e,t,T=function(){let e=Number(process.env.AI_REQUEST_TIMEOUT_MS);return!Number.isFinite(e)||e<5e3?45e3:e}()){let i=new AbortController,r=setTimeout(()=>i.abort(`Timed out after ${T}ms`),T);try{return await fetch(e,{...t,signal:i.signal})}catch(e){if(e?.name==="AbortError")throw Error(`AI request timed out after ${Math.round(T/1e3)} seconds`);throw e}finally{clearTimeout(r)}}async function l(e,t){return p(await L(e),t)}async function p(e,t){let{messages:T,maxTokens:i=3e3,jsonSchema:r}=t;try{return await O(e,{messages:T,maxTokens:i,jsonSchema:r})}catch(t){if(r)return!function(e){let t=N(e,"").toLowerCase();return t.includes("invalid_argument")||t.includes("invalid argument")||t.includes("unsupported response_format")||t.includes("response_schema")||t.includes("response schema")}(t)&&console.warn(`structured output failed for ${e.provider}/${e.model}, retrying with plain JSON fallback`,N(t,"unknown")),await O(e,{messages:function(e,t){let T=t?.schema||t,i=`Return a single valid JSON object only. Do not use markdown fences, commentary, or prose. The JSON must match this schema exactly:
${JSON.stringify(T,null,2)}`,r=e.map(e=>({...e})),o=r.findIndex(e=>"system"===e.role);if(o>=0){let e=r[o],t="string"==typeof e.content?e.content:JSON.stringify(e.content);return r[o]={...e,content:`${t}

${i}`},r}return[{role:"system",content:i},...r]}(T,r),maxTokens:i});throw t}}async function O(e,t){let{messages:T,maxTokens:i=3e3,jsonSchema:r}=t;if(s[e.provider])return U(e,T,i,r);if("anthropic"===e.provider)return I(e,T,i,r);if("gemini"===e.provider)return d(e,T,i,r);if("cohere"===e.provider)return y(e,T,i,r);if("ollama"===e.provider)return f(e,T,i,r);throw Error(`Unsupported provider: ${e.provider}`)}async function c(e,t){let T=await L(e);return s[T.provider]?S(T,t.messages,t.maxTokens??2500):u(await p(T,t))}function m(e){let t=s[e];if(!t)throw Error(`No OpenAI-compatible endpoint for provider: ${e}`);return t}async function U(e,t,T,i){let r={model:e.model,messages:t,max_tokens:T,stream:!1};if(i){if("openai"===e.provider||"groq"===e.provider||"deepseek"===e.provider||"mistral"===e.provider)r.response_format={type:"json_schema",json_schema:i};else{r.response_format={type:"json_object"};let e=t.find(e=>"system"===e.role),T=`Respond with a single valid JSON object matching this schema:
${JSON.stringify(i.schema||i,null,2)}`;e?e.content=("string"==typeof e.content?e.content:JSON.stringify(e.content))+"\n\n"+T:t.unshift({role:"system",content:T})}}let o=await A(m(e.provider),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},body:JSON.stringify(r)});if(!o.ok){let t=await o.text().catch(()=>"");throw Error(`LLM ${e.provider} ${o.status}: ${t.slice(0,400)}`)}let a=await o.json();return a?.choices?.[0]?.message?.content??""}async function*S(e,t,T){let i={model:e.model,messages:t,max_tokens:T,stream:!0},r=await A(m(e.provider),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},body:JSON.stringify(i)});if(!r.ok||!r.body){let t=await r.text().catch(()=>"");throw Error(`LLM ${e.provider} ${r.status}: ${t.slice(0,400)}`)}let o=new TextDecoder,a=r.body.getReader(),n="";for(;;){let{done:e,value:t}=await a.read();if(e)break;let T=(n+=o.decode(t,{stream:!0})).split("\n");for(let e of(n=T.pop()||"",T)){if(!e.startsWith("data: "))continue;let t=e.slice(6).trim();if("[DONE]"!==t)try{let e=JSON.parse(t),T=e?.choices?.[0]?.delta?.content??"";T&&(yield T)}catch{}}}if(n.trim().startsWith("data: ")){let e=n.trim().slice(6).trim();if(e&&"[DONE]"!==e)try{let t=JSON.parse(e),T=t?.choices?.[0]?.delta?.content??"";T&&(yield T)}catch{}}}async function I(e,t,T,i){let r=[],o=[];for(let e of t)"system"===e.role?r.push("string"==typeof e.content?e.content:JSON.stringify(e.content)):o.push({role:e.role,content:"string"==typeof e.content?e.content:JSON.stringify(e.content)});let a={model:e.model,max_tokens:T,system:r.join("\n\n"),messages:o};i?.schema&&(a.tools=[{name:i.name||"output",description:"Return the structured response in this exact schema.",input_schema:i.schema}],a.tool_choice={type:"tool",name:i.name||"output"});let n=await A("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":e.apiKey,"anthropic-version":"2023-06-01"},body:JSON.stringify(a)});if(!n.ok){let e=await n.text().catch(()=>"");throw Error(`LLM anthropic ${n.status}: ${e.slice(0,400)}`)}let E=await n.json();if(i&&Array.isArray(E?.content)){let e=E.content.find(e=>"tool_use"===e.type);if(e?.input)return JSON.stringify(e.input)}return Array.isArray(E?.content)?E.content.filter(e=>"text"===e.type).map(e=>e.text).join(""):""}async function d(e,t,T,i){let r=[],o=[];for(let e of t){let t="string"==typeof e.content?e.content:JSON.stringify(e.content);"system"===e.role?r.push(t):o.push({role:"assistant"===e.role?"model":"user",parts:[{text:t}]})}let a={contents:o,generationConfig:{maxOutputTokens:T,temperature:.7}};r.length&&(a.systemInstruction={role:"system",parts:[{text:r.join("\n\n")}]}),i?.schema&&(a.generationConfig.responseMimeType="application/json",a.generationConfig.responseSchema=D(i.schema));let n=function(e){let t=String(e||"").trim();if(!t)return"models/gemini-1.5-flash";let T=t.replace(/:(generateContent|streamGenerateContent)$/i,"");return T.startsWith("models/")||T.startsWith("tunedModels/")?T:`models/${T}`}(e.model),E=`https://generativelanguage.googleapis.com/v1beta/${n}:generateContent?key=${encodeURIComponent(e.apiKey)}`,s=await A(E,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!s.ok){let e=await s.text().catch(()=>"");throw Error(`LLM gemini ${s.status}: ${e.slice(0,400)}`)}let L=await s.json(),N=L?.candidates?.[0]?.content?.parts;return Array.isArray(N)?N.map(e=>e.text||"").join(""):""}function D(e){if(Array.isArray(e))return e.map(D);if(e&&"object"==typeof e){let t={};for(let[T,i]of Object.entries(e))"additionalProperties"!==T&&"strict"!==T&&"$schema"!==T&&(t[T]=D(i));return t}return e}async function y(e,t,T,i){let r=t.map(e=>({role:"assistant"===e.role?"assistant":e.role,content:"string"==typeof e.content?e.content:JSON.stringify(e.content)})),o={model:e.model,messages:r,max_tokens:T,stream:!1};i?.schema&&(o.response_format={type:"json_object",schema:D(i.schema)});let a=await A("https://api.cohere.com/v2/chat",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},body:JSON.stringify(o)});if(!a.ok){let e=await a.text().catch(()=>"");throw Error(`LLM cohere ${a.status}: ${e.slice(0,400)}`)}let n=await a.json(),E=n?.message?.content;return Array.isArray(E)?E.map(e=>e.text||"").join(""):"string"==typeof E?E:""}async function f(e,t,T,i){let r=t.map(e=>({role:e.role,content:"string"==typeof e.content?e.content:JSON.stringify(e.content)})),o={model:e.model,messages:r,stream:!1,options:{num_predict:T}};i?.schema&&(o.format=D(i.schema));let a=await A("https://ollama.com/api/chat",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},body:JSON.stringify(o)});if(!a.ok){let e=await a.text().catch(()=>"");throw Error(`LLM ollama ${a.status}: ${e.slice(0,400)}`)}let n=await a.json();return n?.message?.content??""}async function*u(e){for(let t=0;t<e.length;t+=60)yield e.slice(t,t+60),await new Promise(e=>setTimeout(e,5))}function X(e){if(!e)return"";let t=e.trim();return t.length<=8?"•".repeat(t.length):t.slice(0,4)+"•".repeat(Math.max(4,t.length-8))+t.slice(-4)}}};