UNPKG

@catalystlabs/tryai

Version:

Dead simple AI library. One line setup. Zero config. Just works.

55 lines (44 loc) 86.4 kB
import{a as f,b as qe}from"./chunk-6OHLTKOL.mjs";import{a as M}from"./chunk-Y2S2737B.mjs";import{a as J}from"./chunk-MCZFF7ET.mjs";import{a as A}from"./chunk-DDTMVTDM.mjs";import{a as V}from"./chunk-OHGL2J3M.mjs";import{a as R}from"./chunk-LX6LO5NW.mjs";import{a as Fe,b as De}from"./chunk-LMOWCXXE.mjs";import{a as W}from"./chunk-DCIJQ6HA.mjs";import{a as _}from"./chunk-WCXX5QYV.mjs";import{v4 as z}from"uuid";var ge={"gpt-4.1-2025-04-14":{text:!0,image:!1,video:!1,audio:!1,functionCalling:!0,jsonMode:!0,maxTokens:1e6,maxOutput:32e3,costPer1MTokens:{input:2,output:8},rateLimit:{rpm:500,tpm:3e5}},"gpt-4.1-mini-2025-04-14":{text:!0,image:!1,video:!1,audio:!1,functionCalling:!0,jsonMode:!0,maxTokens:1e6,maxOutput:32e3,costPer1MTokens:{input:.4,output:1.6},rateLimit:{rpm:500,tpm:3e5}},"gpt-4.1-nano-2025-04-14":{text:!0,image:!1,video:!1,audio:!1,functionCalling:!0,jsonMode:!0,maxTokens:1e6,maxOutput:32e3,costPer1MTokens:{input:.1,output:.4},rateLimit:{rpm:500,tpm:3e5}},"gpt-4o-2024-08-06":{text:!0,image:!0,video:!0,audio:!0,functionCalling:!0,jsonMode:!0,maxTokens:128e3,maxOutput:16384,costPer1MTokens:{input:2.5,output:10},rateLimit:{rpm:500,tpm:3e5}},"gpt-4o-mini-2024-07-18":{text:!0,image:!0,video:!0,audio:!0,functionCalling:!0,jsonMode:!0,maxTokens:128e3,maxOutput:16384,costPer1MTokens:{input:.15,output:.6},rateLimit:{rpm:500,tpm:3e5}},"o3-2025-04-16":{text:!0,image:!1,video:!1,audio:!1,functionCalling:!0,jsonMode:!0,maxTokens:2e5,maxOutput:32768,costPer1MTokens:{input:2,output:8},rateLimit:{rpm:100,tpm:1e5}},"o4-mini-2025-04-16":{text:!0,image:!1,video:!1,audio:!1,functionCalling:!0,jsonMode:!0,maxTokens:2e5,maxOutput:32768,costPer1MTokens:{input:1.1,output:4.4},rateLimit:{rpm:100,tpm:1e5}},"gpt-3.5-turbo-0125":{text:!0,image:!1,video:!1,audio:!1,functionCalling:!0,jsonMode:!0,maxTokens:16385,maxOutput:4096,costPer1MTokens:{input:.5,output:1.5},rateLimit:{rpm:3500,tpm:35e4}}},fe={"claude-opus-4-20250514":{text:!0,image:!0,video:!1,audio:!1,functionCalling:!0,jsonMode:!0,maxTokens:2e5,maxOutput:32e3,costPer1MTokens:{input:15,output:75}},"claude-sonnet-4-20250514":{text:!0,image:!0,video:!1,audio:!1,functionCalling:!0,jsonMode:!0,maxTokens:2e5,maxOutput:64e3,costPer1MTokens:{input:3,output:15}},"claude-3-7-sonnet-20250219":{text:!0,image:!0,video:!1,audio:!1,functionCalling:!0,jsonMode:!0,maxTokens:2e5,maxOutput:128e3,costPer1MTokens:{input:3,output:15}},"claude-3-5-haiku-20241022":{text:!0,image:!0,video:!1,audio:!1,functionCalling:!0,jsonMode:!0,maxTokens:2e5,maxOutput:8192,costPer1MTokens:{input:.8,output:4}}},he={"gemini-2.5-pro":{text:!0,image:!0,video:!0,audio:!0,functionCalling:!0,jsonMode:!0,maxTokens:1e6,maxOutput:32e3,costPer1MTokens:{input:1.25,output:10}},"gemini-2.5-flash":{text:!0,image:!0,video:!0,audio:!0,functionCalling:!0,jsonMode:!0,maxTokens:1e6,maxOutput:64e3,costPer1MTokens:{input:.3,output:2.5}},"gemini-2.5-flash-lite":{text:!0,image:!0,video:!0,audio:!0,functionCalling:!0,jsonMode:!0,maxTokens:1e6,maxOutput:64e3,costPer1MTokens:{input:.1,output:.4}}},ye={"Llama-4-Maverick-17B-128E-Instruct-FP8":{text:!0,image:!0,video:!1,audio:!1,functionCalling:!0,jsonMode:!0,maxTokens:128e3,maxOutput:8192,costPer1MTokens:{input:.1,output:.1}},"Llama-4-Scout-17B-16E-Instruct-FP8":{text:!0,image:!0,video:!1,audio:!1,functionCalling:!0,jsonMode:!0,maxTokens:16e3,maxOutput:8192,costPer1MTokens:{input:.08,output:.08}},"Llama-3.3-70B-Instruct":{text:!0,image:!1,video:!1,audio:!1,functionCalling:!0,jsonMode:!0,maxTokens:8192,maxOutput:8192,costPer1MTokens:{input:.35,output:.4}},"Llama-3.3-8B-Instruct":{text:!0,image:!1,video:!1,audio:!1,functionCalling:!0,jsonMode:!0,maxTokens:8192,maxOutput:8192,costPer1MTokens:{input:.05,output:.05}}},E={...ge,...fe,...he,...ye};var S=class{messages=[];config;conversationId;currentModel;currentProvider;databaseRecorder;files={uploaded:[],generated:[]};constructor(e,t){this.config=e||{maxHistory:50},this.conversationId=z(),this.databaseRecorder=t}recordMessageAsync(e){this.databaseRecorder&&this.databaseRecorder.recordAsync(async()=>{await this.databaseRecorder.recordMessage({conversation_id:this.conversationId,role:e.role,content:e.content,message_index:this.messages.length-1,in_context:!0,tokens_estimate:e.metadata?.tokens?.total})})}addMessage(e,t){let r={id:z(),timestamp:new Date,...e};if(t&&(r.metadata=t,e.role==="assistant"&&t.provider&&t.model&&this.setModel(t.provider,t.model)),this.messages.push(r),this.recordMessageAsync(r),this.config.maxHistory&&this.messages.length>this.config.maxHistory){let n=this.messages.filter(o=>o.role==="system"),i=this.messages.filter(o=>o.role!=="system").slice(-(this.config.maxHistory-n.length));this.messages=[...n,...i]}return this.updateContextWindow(),r}getHistory(e){return e?this.messages.slice(-e):[...this.messages]}getFormattedHistory(e){return(e?this.messages.slice(-e):this.messages).map(r=>({role:r.role,content:r.content}))}clear(){let e=this.messages.length;return this.messages=[],this.conversationId=z(),e}setModel(e,t){this.currentProvider=e,this.currentModel=t,this.updateContextWindow()}updateContextWindow(){if(!this.currentModel||!this.currentProvider)return;let e=`${this.currentModel}`,t=E[e]||E[this.currentModel];if(!t)return;let r=t.maxTokens,n=0,i=[];for(let o=this.messages.length-1;o>=0;o--){let s=this.messages[o],a=s.metadata?.tokens?.total||Math.ceil(s.content.length/4);n+a<=r?(n+=a,i.unshift(o),this.messages[o].inContext=!0):this.messages[o].inContext=!1}}addFile(e,t){this.files[t].push(e)}getConversationMetadata(){let e=this.getStats(),t={input:0,output:0,total:0},r={input:0,output:0,total:0,currency:"USD"},n=0,i=0,o=0,s=[];this.messages.forEach((m,c)=>{m.metadata?.tokens&&(t.input+=m.metadata.tokens.input,t.output+=m.metadata.tokens.output,t.total+=m.metadata.tokens.total,m.inContext&&(o+=m.metadata.tokens.total,s.push(c))),m.metadata?.cost&&(r.input+=m.metadata.cost.input,r.output+=m.metadata.cost.output,r.total+=m.metadata.cost.total),m.metadata?.latency&&(n+=m.metadata.latency,i++)});let a=this.currentModel||"",b=(E[a]||E[this.currentModel||""])?.maxTokens||0;return{id:this.conversationId,messageCount:this.messages.length,startedAt:this.messages[0]?.timestamp,lastMessageAt:this.messages[this.messages.length-1]?.timestamp,contextWindow:{size:b,used:o,messagesInContext:{start:s[0]||0,end:s[s.length-1]||0,count:s.length}},totalTokens:t,totalCost:r,files:this.files,stats:e,averageLatency:i>0?n/i:0}}export(){return JSON.stringify({conversationId:this.conversationId,exportedAt:new Date().toISOString(),messages:this.messages,config:this.config,metadata:this.getConversationMetadata()},null,2)}import(e){try{let t=JSON.parse(e);this.conversationId=t.conversationId||z(),this.messages=t.messages||[],this.config=t.config||this.config,this.messages=this.messages.map(r=>({...r,timestamp:new Date(r.timestamp),metadata:r.metadata?{...r.metadata,timestamp:new Date(r.metadata.timestamp)}:void 0}))}catch(t){throw new Error(`Failed to import conversation: ${t}`)}}getMessage(e){return this.messages.find(t=>t.id===e)}updateMessage(e,t){let r=this.messages.findIndex(n=>n.id===e);return r===-1?!1:(this.messages[r]={...this.messages[r],...t,id:this.messages[r].id,timestamp:this.messages[r].timestamp},!0)}removeMessage(e){let t=this.messages.findIndex(r=>r.id===e);return t===-1?!1:(this.messages.splice(t,1),!0)}getStats(){let e=this.messages.filter(i=>i.role==="user").length,t=this.messages.filter(i=>i.role==="assistant").length,r=this.messages.filter(i=>i.role==="system").length,n=this.messages.filter(i=>i.role==="tool").length;return{total:this.messages.length,userMessages:e,assistantMessages:t,systemMessages:r,toolMessages:n,averageMessageLength:this.messages.reduce((i,o)=>i+o.content.length,0)/this.messages.length||0}}getLastAssistantMessage(){return[...this.messages].reverse().find(e=>e.role==="assistant")}getTotalCost(){return this.messages.reduce((e,t)=>e+(t.metadata?.cost?.total||0),0)}};import{v4 as ve}from"uuid";var x=class{pricing={"openai:gpt-4.1-2025-04-14":{inputPer1k:.002,outputPer1k:.008},"openai:gpt-4.1-mini-2025-04-14":{inputPer1k:4e-4,outputPer1k:.0016},"openai:gpt-4.1-nano-2025-04-14":{inputPer1k:1e-4,outputPer1k:4e-4},"openai:gpt-4.5-preview-2025-02-27":{inputPer1k:.075,outputPer1k:.15},"openai:gpt-4o-2024-08-06":{inputPer1k:.0025,outputPer1k:.01},"openai:gpt-4o-mini-2024-07-18":{inputPer1k:15e-5,outputPer1k:6e-4},"openai:gpt-4o-audio-preview-2025-06-03":{inputPer1k:.0025,outputPer1k:.01,notes:"Audio: $40/1M input, $80/1M output"},"openai:o1-2024-12-17":{inputPer1k:.015,outputPer1k:.06},"openai:o1-pro-2025-03-19":{inputPer1k:.15,outputPer1k:.6},"openai:o3-2025-04-16":{inputPer1k:.002,outputPer1k:.008},"openai:o3-pro-2025-06-10":{inputPer1k:.02,outputPer1k:.08},"openai:o3-mini-2025-01-31":{inputPer1k:.0011,outputPer1k:.0044},"openai:o4-mini-2025-04-16":{inputPer1k:.0011,outputPer1k:.0044},"openai:o1-mini-2024-09-12":{inputPer1k:.0011,outputPer1k:.0044},"openai:gpt-4-turbo-2024-04-09":{inputPer1k:.01,outputPer1k:.03},"openai:gpt-4":{inputPer1k:.03,outputPer1k:.06},"openai:gpt-4-32k":{inputPer1k:.06,outputPer1k:.12},"openai:gpt-3.5-turbo-0125":{inputPer1k:5e-4,outputPer1k:.0015},"openai:gpt-3.5-turbo":{inputPer1k:5e-4,outputPer1k:.0015},"anthropic:claude-opus-4-20250514":{inputPer1k:.015,outputPer1k:.075},"anthropic:claude-sonnet-4-20250514":{inputPer1k:.003,outputPer1k:.015},"anthropic:claude-3-7-sonnet-20250219":{inputPer1k:.003,outputPer1k:.015},"anthropic:claude-3-5-haiku-20241022":{inputPer1k:8e-4,outputPer1k:.004},"anthropic:claude-3-5-sonnet-20241022":{inputPer1k:.003,outputPer1k:.015},"anthropic:claude-3-5-sonnet-20240620":{inputPer1k:.003,outputPer1k:.015},"anthropic:claude-3-haiku-20240307":{inputPer1k:25e-5,outputPer1k:.00125},"anthropic:claude-3-opus-20240229":{inputPer1k:.015,outputPer1k:.075},"anthropic:claude-3-sonnet-20240229":{inputPer1k:.003,outputPer1k:.015},"google:gemini-2.5-pro":{inputPer1k:.00125,outputPer1k:.01,notes:">200K: $2.50 input, $15 output per 1M"},"google:gemini-2.5-flash":{inputPer1k:3e-4,outputPer1k:.0025,notes:"Audio: $1 per 1M input"},"google:gemini-2.5-flash-lite":{inputPer1k:1e-4,outputPer1k:4e-4,notes:"Audio: $0.30 per 1M input"},"google:gemini-2.5-flash-native-audio":{inputPer1k:5e-4,outputPer1k:.002,notes:"Audio: $3/1M input, $12/1M output"},"google:gemini-2.5-flash-preview-tts":{inputPer1k:5e-4,outputPer1k:.01},"google:gemini-2.5-pro-preview-tts":{inputPer1k:.001,outputPer1k:.02},"google:gemini-pro":{inputPer1k:25e-5,outputPer1k:.00125},"google:gemini-pro-vision":{inputPer1k:25e-5,outputPer1k:.00125},"google:gemini-1.5-pro":{inputPer1k:.00125,outputPer1k:.005},"google:gemini-1.5-flash":{inputPer1k:25e-5,outputPer1k:75e-5},"llama:Llama-4-Maverick-17B-128E-Instruct-FP8":{inputPer1k:1e-4,outputPer1k:1e-4},"llama:Llama-4-Scout-17B-16E-Instruct-FP8":{inputPer1k:8e-5,outputPer1k:8e-5},"llama:Llama-3.3-70B-Instruct":{inputPer1k:35e-5,outputPer1k:4e-4},"llama:Llama-3.3-8B-Instruct":{inputPer1k:5e-5,outputPer1k:5e-5},"llama:llama-3-70b":{inputPer1k:8e-4,outputPer1k:8e-4},"llama:llama-3-8b":{inputPer1k:2e-4,outputPer1k:2e-4},"llama:code-llama-70b":{inputPer1k:8e-4,outputPer1k:8e-4},"lmstudio:any":{inputPer1k:0,outputPer1k:0}};providerDefaults={openai:{inputPer1k:.002,outputPer1k:.008},anthropic:{inputPer1k:.003,outputPer1k:.015},google:{inputPer1k:5e-4,outputPer1k:.002},llama:{inputPer1k:1e-4,outputPer1k:1e-4},lmstudio:{inputPer1k:0,outputPer1k:0}};cacheMultipliers={openai:.25,anthropic:1.25,google:.25,llama:0,lmstudio:0};async estimate(e,t,r,n,i){let o=`${e}:${t}`,s=this.pricing[o];s||(s=this.providerDefaults[e]||{inputPer1k:.001,outputPer1k:.001});let a=r/1e3*s.inputPer1k,p=n/1e3*s.outputPer1k;return i?.cached&&this.cacheMultipliers[e]&&(a*=this.cacheMultipliers[e]),i?.audioTokens&&(t.includes("audio")||t.includes("native-audio")),{input:this.roundCost(a),output:this.roundCost(p),total:this.roundCost(a+p),currency:"USD",estimated:!this.pricing[o]}}async estimateImageGeneration(e,t,r=1,n="1024x1024",i="standard"){let o={"openai:dall-e-3:standard:1024x1024":.04,"openai:dall-e-3:standard:1024x1792":.08,"openai:dall-e-3:standard:1792x1024":.08,"openai:dall-e-3:hd:1024x1024":.08,"openai:dall-e-3:hd:1024x1792":.12,"openai:dall-e-3:hd:1792x1024":.12,"openai:dall-e-2:standard:256x256":.016,"openai:dall-e-2:standard:512x512":.018,"openai:dall-e-2:standard:1024x1024":.02,"google:imagen-3":.03,"google:veo-3":.75,"google:veo-2":.5},s=`${e}:${t}:${i}:${n}`,p=(o[s]||o[`${e}:${t}`]||.05)*r;return{input:0,output:this.roundCost(p),total:this.roundCost(p),currency:"USD",estimated:!o[s]}}roundCost(e){return Math.round(e*1e6)/1e6}getPricing(e,t){let r=`${e}:${t}`;return this.pricing[r]||this.providerDefaults[e]||null}isFree(e){return e==="lmstudio"}getProviderModels(e){return Object.keys(this.pricing).filter(t=>t.startsWith(`${e}:`)).map(t=>t.split(":")[1])}};var be={enabled:!0,trackCosts:!0,trackLatency:!0,trackTokens:!0,includeTimestamp:!0},P=class{static costEstimator=new x;static getMetadataConfig(e,t){let r={...be};return t?.metadata&&(r={...r,...t.metadata}),e?.metadata&&(r={...r,...e.metadata}),r}static isEnabled(e,t){return this.getMetadataConfig(e,t).enabled}static async createMessageMetadata(e,t,r){let n=this.getMetadataConfig(t,r);if(!n.enabled)return;let i={id:ve(),timestamp:new Date(e.startTime),provider:e.provider,model:e.model,latency:0};if(n.trackLatency&&(i.latency=Date.now()-e.startTime),n.trackTokens){let o,s,a=!1;if(e.usage?(o=e.usage.promptTokens,s=e.usage.completionTokens):(o=Math.ceil(e.inputText.length/4),s=Math.ceil(e.outputText.length/4),a=!0),i.tokens={input:o,output:s,total:o+s,estimated:a},n.trackCosts&&i.tokens){let p=await this.costEstimator.estimate(e.provider,e.model,o,s);i.cost={input:p.input,output:p.output,total:p.total,currency:p.currency,estimated:p.estimated||a}}}return i}static filterMetadata(e,t,r){let n=this.getMetadataConfig(t,r),i={id:e.id,timestamp:e.timestamp,provider:e.provider,model:e.model,latency:n.trackLatency?e.latency:0};return n.trackTokens&&e.tokens&&(i.tokens=e.tokens),n.trackCosts&&e.cost&&(i.cost=e.cost),i}static mergeConfigs(e,t,r){let n=r?{...r}:{};return t&&(n=this.deepMerge(n,t)),e&&(n=this.deepMerge(n,e)),n}static deepMerge(e,t){let r={...e};for(let n in t)t[n]&&typeof t[n]=="object"&&!Array.isArray(t[n])?r[n]=this.deepMerge(r[n]||{},t[n]):r[n]=t[n];return r}};import{EventEmitter as Pe}from"events";var Te={openai:{requestsPerMinute:500,tokensPerMinute:3e5,requestsPerHour:1e4,tokensPerHour:18e6},anthropic:{requestsPerMinute:50,tokensPerMinute:1e5,requestsPerHour:1e3,tokensPerHour:5e6},google:{requestsPerMinute:60,tokensPerMinute:1e6,requestsPerHour:1500,tokensPerHour:6e7},llama:{requestsPerMinute:100,tokensPerMinute:5e5,requestsPerHour:5e3,tokensPerHour:3e7},lmstudio:{requestsPerMinute:1e3,tokensPerMinute:1e7,requestsPerHour:6e4,tokensPerHour:6e8},router:{requestsPerMinute:200,tokensPerMinute:1e6,requestsPerHour:1e4,tokensPerHour:6e7}},Ce={"gpt-3.5-turbo":7,"gpt-4.1-nano":5,"gpt-4.1-mini":3,"claude-3-5-haiku":2,"gemini-2.5-flash-lite":3,"gemini-2.5-flash":2,"Llama-3.3-8B-Instruct":2},I=class extends Pe{queues=new Map;usage=new Map;processing=new Set;config;constructor(e){super(),this.config={enabled:!0,requestsPerMinute:60,tokensPerMinute:15e4,...e},["openai","anthropic","google","llama","lmstudio"].forEach(r=>{this.queues.set(r,[])}),this.config.enabled&&this.startProcessingLoop()}async execute(e,t,r,n){return this.config.enabled?this.canExecute(e,t,n)?(this.recordUsage(e,t,n),r()):new Promise((i,o)=>{let s={id:Math.random().toString(36).substr(2,9),provider:e,model:t,execute:r,resolve:i,reject:o,timestamp:Date.now(),estimatedTokens:n,retryCount:0};this.enqueue(s),this.emit("queued",{provider:e,model:t,queueLength:this.getQueueLength(e)})}):r()}canExecute(e,t,r=100){let n=this.getLimits(e,t),i=this.getUsage(e);return i.resetAt<Date.now()?(this.resetUsage(e),!0):!(i.requests>=n.requestsPerMinute||r&&i.tokens+r>n.tokensPerMinute)}getLimits(e,t){let r=Te[e]||{},n=Ce[t]||1;return{enabled:!0,requestsPerMinute:Math.floor((r.requestsPerMinute||this.config.requestsPerMinute)*n),tokensPerMinute:Math.floor((r.tokensPerMinute||this.config.tokensPerMinute)*n),requestsPerHour:r.requestsPerHour?Math.floor(r.requestsPerHour*n):void 0,tokensPerHour:r.tokensPerHour?Math.floor(r.tokensPerHour*n):void 0}}getUsage(e){let t=`${e}:minute`,r=this.usage.get(t);return(!r||r.resetAt<Date.now())&&(r={requests:0,tokens:0,resetAt:Date.now()+6e4},this.usage.set(t,r)),r}recordUsage(e,t,r=100){let n=this.getUsage(e);n.requests++,n.tokens+=r}resetUsage(e){let t=`${e}:minute`;this.usage.set(t,{requests:0,tokens:0,resetAt:Date.now()+6e4})}enqueue(e){let t=this.queues.get(e.provider)||[];t.push(e),this.queues.set(e.provider,t)}getQueueLength(e){return this.queues.get(e)?.length||0}startProcessingLoop(){setInterval(()=>{this.processQueues()},100)}async processQueues(){let e=["openai","anthropic","google","llama","lmstudio"];for(let t of e){if(this.processing.has(t))continue;let r=this.queues.get(t);!r||r.length===0||(this.processing.add(t),this.processProviderQueue(t).finally(()=>this.processing.delete(t)))}}async processProviderQueue(e){let t=this.queues.get(e)||[],r=[];for(;t.length>0;){let n=t[0];if(!this.canExecute(e,n.model,n.estimatedTokens)){if(await new Promise(i=>setTimeout(i,1e3)),Date.now()-n.timestamp>3e5){t.shift(),n.reject(new Error("Request timed out in rate limit queue"));continue}break}t.shift(),r.push(n.id);try{this.recordUsage(e,n.model,n.estimatedTokens);let i=await n.execute();n.resolve(i),this.emit("executed",{provider:e,model:n.model,queueTime:Date.now()-n.timestamp})}catch(i){this.isRateLimitError(i)&&n.retryCount<3?(n.retryCount++,n.timestamp=Date.now(),this.enqueue(n),this.emit("retry",{provider:e,model:n.model,retryCount:n.retryCount,error:i.message})):(n.reject(i),this.emit("failed",{provider:e,model:n.model,error:i.message}))}}this.queues.set(e,t)}isRateLimitError(e){let t=e.message?.toLowerCase()||"",r=e.code?.toLowerCase()||"";return t.includes("rate limit")||t.includes("too many requests")||t.includes("quota exceeded")||r==="rate_limit_exceeded"||r==="429"||e.status===429}getStatus(){let e={};return this.queues.forEach((t,r)=>{let n=this.getUsage(r);e[r]={queueLength:t.length,usage:{requests:n.requests,tokens:n.tokens,resetIn:Math.max(0,n.resetAt-Date.now())},processing:this.processing.has(r)}}),e}clearQueues(){this.queues.forEach((e,t)=>{e.forEach(r=>{r.reject(new Error("Queue cleared"))}),this.queues.set(t,[])})}};import{existsSync as _e}from"fs";import{join as O}from"path";var L=class{static cachedSettings;static load(){if(this.cachedSettings)return this.cachedSettings;let e=this.loadFromFile()||this.loadFromEnv();return e&&(this.cachedSettings=e),e}static loadFromFile(){let e=[O(process.cwd(),"tryai","settings.ts"),O(process.cwd(),"tryai","settings.js"),O(process.cwd(),".tryai","settings.ts"),O(process.cwd(),".tryai","settings.js")];for(let t of e)if(_e(t))try{delete _.cache[_.resolve(t)];let r=_(t);return r.default||r}catch(r){console.warn(`Failed to load settings from ${t}:`,r)}}static loadFromEnv(){if(process.env.OPENAI_API_KEY||process.env.ANTHROPIC_API_KEY||process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY||process.env.LLAMA_API_KEY)return{apiKeys:{openai:process.env.OPENAI_API_KEY,anthropic:process.env.ANTHROPIC_API_KEY,google:process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY,llama:process.env.LLAMA_API_KEY,lmstudio:void 0},defaultProvider:process.env.OPENAI_API_KEY?"openai":process.env.ANTHROPIC_API_KEY?"anthropic":process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY?"google":process.env.LLAMA_API_KEY?"llama":"openai",temperature:process.env.AI_TEMPERATURE?parseFloat(process.env.AI_TEMPERATURE):void 0,maxTokens:process.env.AI_MAX_TOKENS?parseInt(process.env.AI_MAX_TOKENS):void 0,features:{autoModelSelection:process.env.AI_AUTO_MODEL_SELECTION==="true",costOptimization:process.env.AI_COST_OPTIMIZATION==="true",latencyOptimization:process.env.AI_LATENCY_OPTIMIZATION==="true"},metadata:{enabled:process.env.AI_METADATA_ENABLED!=="false",trackCosts:process.env.AI_TRACK_COSTS!=="false",trackLatency:process.env.AI_TRACK_LATENCY!=="false",trackTokens:process.env.AI_TRACK_TOKENS!=="false",includeTimestamp:process.env.AI_INCLUDE_TIMESTAMP!=="false"},rateLimit:{enabled:process.env.AI_RATE_LIMIT_ENABLED!=="false",requestsPerMinute:process.env.AI_REQUESTS_PER_MINUTE?parseInt(process.env.AI_REQUESTS_PER_MINUTE):void 0,tokensPerMinute:process.env.AI_TOKENS_PER_MINUTE?parseInt(process.env.AI_TOKENS_PER_MINUTE):void 0}}}static clearCache(){this.cachedSettings=void 0}static async save(e,t){let r=await import("fs/promises"),n=t||O(process.cwd(),"tryai","settings.ts"),i=n.substring(0,n.lastIndexOf("/"));await r.mkdir(i,{recursive:!0});let o=`/** * TryAI Global Settings * Generated on ${new Date().toISOString()} */ import type { GlobalConfig } from '@catalystlabs/tryai'; const settings: GlobalConfig = ${JSON.stringify(e,null,2)}; export default settings; `;await r.writeFile(n,o,"utf8")}};var h=class{static processTemplate(e,t={}){let n=(typeof e=="string"?e:e.content).replace(/\{\{(\s*[\w.]+\s*)\}\}/g,(i,o)=>{let s=o.trim(),a=this.getNestedValue(t,s);return a!==void 0?String(a):i});return n=n.replace(/\$\{(\s*[\w.]+\s*)\}/g,(i,o)=>{let s=o.trim(),a=this.getNestedValue(t,s);return a!==void 0?String(a):i}),n=n.replace(/\{(\w+)\}/g,(i,o)=>{let s=t[o];return s!==void 0?String(s):i}),n}static validateTemplate(e,t){let r=[];if(!e.variables)return{valid:!0,errors:r};for(let n of e.variables){let i=t[n.name];if(n.required&&i===void 0){r.push(`Required variable '${n.name}' is missing`);continue}if(i!==void 0&&n.type){let o=Array.isArray(i)?"array":typeof i;o!==n.type&&r.push(`Variable '${n.name}' should be ${n.type} but got ${o}`)}}return{valid:r.length===0,errors:r}}static applyDefaults(e,t){if(!e.variables)return t;let r={...t};for(let n of e.variables)r[n.name]===void 0&&n.default!==void 0&&(r[n.name]=n.default);return r}static extractVariables(e){let t=new Set,r=e.matchAll(/\{\{(\s*[\w.]+\s*)\}\}/g);for(let o of r)t.add(o[1].trim());let n=e.matchAll(/\$\{(\s*[\w.]+\s*)\}/g);for(let o of n)t.add(o[1].trim());let i=e.matchAll(/\{(\w+)\}/g);for(let o of i)t.add(o[1]);return Array.from(t)}static getNestedValue(e,t){let r=t.split("."),n=e;for(let i of r){if(n==null)return;n=n[i]}return n}static SYSTEM_PROMPTS={default:"You are a helpful AI assistant.",coder:`You are an expert software developer with deep knowledge of multiple programming languages, frameworks, and best practices. Provide clear, efficient, and well-documented code solutions.`,analyst:`You are a data analyst expert. Analyze data thoroughly, identify patterns and insights, and present findings in a clear and actionable manner.`,teacher:`You are an expert teacher and educator. Explain concepts clearly, break down complex topics into understandable parts, and adapt your teaching style to the learner's needs.`,creative:`You are a creative writing assistant. Help with storytelling, creative content, and engaging narratives while maintaining coherence and originality.`,technical:`You are a technical documentation expert. Write clear, precise, and comprehensive technical documentation that is both accurate and accessible.`};static PROMPT_TEMPLATES={codeReview:{id:"code-review",name:"Code Review",content:`Review the following code for: 1. Code quality and readability 2. Potential bugs or issues 3. Performance optimizations 4. Security concerns 5. Best practices Code to review: \`\`\`{{language}} {{code}} \`\`\` Focus areas: {{focus}}`,variables:[{name:"language",type:"string",required:!0},{name:"code",type:"string",required:!0},{name:"focus",type:"string",default:"general review"}]},explain:{id:"explain",name:"Explain Concept",content:`Explain {{concept}} in {{style}} terms. Target audience: {{audience}} Detail level: {{detail}}`,variables:[{name:"concept",type:"string",required:!0},{name:"style",type:"string",default:"simple"},{name:"audience",type:"string",default:"general"},{name:"detail",type:"string",default:"moderate"}]},refactor:{id:"refactor",name:"Code Refactoring",content:`Refactor the following code to improve {{goals}}. Maintain the same functionality while enhancing code quality. Original code: \`\`\`{{language}} {{code}} \`\`\` Constraints: {{constraints}}`,variables:[{name:"language",type:"string",required:!0},{name:"code",type:"string",required:!0},{name:"goals",type:"string",default:"readability and performance"},{name:"constraints",type:"string",default:"none"}]},summarize:{id:"summarize",name:"Summarize Text",content:`Summarize the following text in {{length}} format: {{text}} Focus on: {{focus}} Style: {{style}}`,variables:[{name:"text",type:"string",required:!0},{name:"length",type:"string",default:"concise"},{name:"focus",type:"string",default:"key points"},{name:"style",type:"string",default:"bullet points"}]}};static formatResponse(e,t="plain"){switch(t){case"markdown":return e.trim();case"json":try{let r=JSON.parse(e);return JSON.stringify(r,null,2)}catch{return JSON.stringify({response:e},null,2)}case"xml":return`<?xml version="1.0" encoding="UTF-8"?> <response> ${e.split(` `).map(r=>` <line>${this.escapeXml(r)}</line>`).join(` `)} </response>`;case"plain":default:return e.trim()}}static escapeXml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}};import{readFileSync as ie,readdirSync as xe,statSync as we}from"fs";import{join as oe,extname as se,basename as ae}from"path";var F=class{static loadFromDirectory(e){let t=[];try{let r=xe(e);for(let n of r){let i=oe(e,n),o=we(i);if(o.isDirectory()){let s=n,a=this.loadFromDirectory(i);a.forEach(p=>{p.category||(p.category=s)}),t.push(...a)}else if(o.isFile()&&[".json",".txt",".md"].includes(se(n))){let s=this.loadTemplateFile(i);s&&t.push(...s)}}}catch(r){console.error(`Failed to load prompt templates from ${e}:`,r)}return t}static loadTemplateFile(e){try{let t=se(e),r=ae(e,t),n=ae(oe(e,".."));if(t===".json"){let i=ie(e,"utf-8"),o=JSON.parse(i),s=[];return Array.isArray(o)?o.forEach((a,p)=>{s.push(this.parseTemplate(a,`${r}_${p}`,n))}):typeof o=="object"&&!o.content?Object.entries(o).forEach(([a,p])=>{s.push(this.parseTemplate(p,a,n))}):s.push(this.parseTemplate(o,r,n)),s}else if(t===".txt"||t===".md"){let i=ie(e,"utf-8"),o=i.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(o){let s=this.parseSimpleFrontmatter(o[1]),a=o[2].trim();return[{id:s.id||r,name:s.name||r,content:a,category:s.category||n,variables:s.variables,metadata:s}]}else return[{id:r,name:r,content:i.trim(),category:n}]}}catch(t){console.error(`Failed to load prompt template file ${e}:`,t)}return null}static parseTemplate(e,t,r){return typeof e=="string"?{id:t,name:t,content:e,category:r}:{id:e.id||t,name:e.name||e.id||t,content:e.content||e.template||e.prompt||"",category:e.category||r,variables:e.variables,metadata:e.metadata||e}}static parseSimpleFrontmatter(e){let t={},r=e.split(` `);for(let n of r){let i=n.match(/^(\w+):\s*(.+)$/);if(i){let[,o,s]=i;try{t[o]=JSON.parse(s)}catch{t[o]=s.trim()}}}return t}};import{readFileSync as ke,readdirSync as Me,statSync as Ae}from"fs";import{join as Re,extname as le,basename as Ee}from"path";import{z as u}from"zod";var D=class{static loadFromDirectory(e){let t=[];try{let r=Me(e);for(let n of r){let i=Re(e,n),o=Ae(i);if(o.isDirectory()){let s=this.loadFromDirectory(i);t.push(...s)}else if(o.isFile()&&[".json",".ts",".js"].includes(le(n))){let s=this.loadTemplateFile(i);s&&t.push(...s)}}}catch(r){console.error(`Failed to load response templates from ${e}:`,r)}return t}static loadTemplateFile(e){try{let t=le(e),r=Ee(e,t);if(t===".json"){let n=ke(e,"utf-8"),i=JSON.parse(n),o=[];return Array.isArray(i)?i.forEach((s,a)=>{o.push(this.parseResponseTemplate(s,`${r}_${a}`))}):typeof i=="object"&&!i.schema?Object.entries(i).forEach(([s,a])=>{o.push(this.parseResponseTemplate(a,s))}):o.push(this.parseResponseTemplate(i,r)),o}(t===".ts"||t===".js")&&console.warn(`Loading .ts/.js response templates requires dynamic import: ${e}`)}catch(t){console.error(`Failed to load response template file ${e}:`,t)}return null}static parseResponseTemplate(e,t){let r={id:e.id||t,name:e.name||e.id||t,description:e.description,format:e.format};if(e.schema&&(r.schema=this.parseSchema(e.schema)),e.transform&&typeof e.transform=="string")try{r.transform=new Function("response",e.transform)}catch(n){console.error(`Failed to parse transform function for ${r.id}:`,n)}if(e.validate&&typeof e.validate=="string")try{r.validate=new Function("response",e.validate)}catch(n){console.error(`Failed to parse validate function for ${r.id}:`,n)}return r}static parseSchema(e){if(e.type==="object"&&e.properties){let t={};for(let[n,i]of Object.entries(e.properties))t[n]=this.parseSchemaProperty(i);let r=u.object(t);if(e.required&&Array.isArray(e.required)){for(let n of Object.keys(t))e.required.includes(n)||(t[n]=t[n].optional());r=u.object(t)}return r}return this.parseSchemaProperty(e)}static parseSchemaProperty(e){switch(e.type){case"string":if(e.enum)return u.enum(e.enum);let t=u.string();return e.minLength&&(t=t.min(e.minLength)),e.maxLength&&(t=t.max(e.maxLength)),e.pattern&&(t=t.regex(new RegExp(e.pattern))),e.format==="email"&&(t=t.email()),e.format==="url"&&(t=t.url()),e.format==="uuid"&&(t=t.uuid()),t;case"number":let r=u.number();return e.minimum&&(r=r.min(e.minimum)),e.maximum&&(r=r.max(e.maximum)),e.multipleOf&&(r=r.multipleOf(e.multipleOf)),r;case"integer":let n=u.number().int();return e.minimum&&(n=n.min(e.minimum)),e.maximum&&(n=n.max(e.maximum)),n;case"boolean":return u.boolean();case"array":return e.items?u.array(this.parseSchemaProperty(e.items)):u.array(u.any());case"object":return e.properties?this.parseSchema(e):u.object({});case"null":return u.null();default:return u.any()}}static createExampleTemplate(){return{id:"financial-report",name:"Financial Report",description:"Structured financial report with metrics",format:"json",schema:u.object({executive_summary:u.string(),revenue:u.object({current:u.number(),previous:u.number(),growth_rate:u.number()}),key_metrics:u.array(u.object({name:u.string(),value:u.number(),target:u.number(),status:u.enum(["on_track","at_risk","behind"])})),recommendations:u.array(u.string()),outlook:u.string()})}}};var w=class{promptTemplates=new Map;responseTemplates=new Map;systemPrompts=new Map;constructor(){this.registerBuiltInTemplates()}registerPromptTemplate(e){this.promptTemplates.set(e.id,e)}registerResponseTemplate(e){this.responseTemplates.set(e.id,e)}registerSystemPrompt(e){this.systemPrompts.set(e.id,e)}processTemplateConfig(e){let t={};if(e.systemPrompt)if(typeof e.systemPrompt=="string"){let r=this.systemPrompts.get(e.systemPrompt);r?t.systemPrompt=h.processTemplate(r,e.variables||{}):t.systemPrompt=e.systemPrompt}else t.systemPrompt=h.processTemplate(e.systemPrompt,e.variables||{});if(!e.prompt)throw new Error("Prompt is required in template config");if(typeof e.prompt=="string"){let r=this.promptTemplates.get(e.prompt);r?t.prompt=h.processTemplate(r,e.variables||{}):t.prompt=h.processTemplate(e.prompt,e.variables||{})}else t.prompt=h.processTemplate(e.prompt,e.variables||{});if(e.responseTemplate)if(typeof e.responseTemplate=="string"){let r=this.responseTemplates.get(e.responseTemplate);r&&(t.responseFormat=r)}else t.responseFormat=e.responseTemplate;return t}async applyResponseTemplate(e,t){let r=e;if(t.format&&t.format!=="text"&&(r=h.formatResponse(e,t.format)),t.transform&&(r=await t.transform(r)),t.schema)try{let n=JSON.parse(r);return t.schema.parse(n)}catch(n){throw new Error(`Response validation failed: ${n}`)}if(t.validate&&!await t.validate(r))throw new Error("Response validation failed");return r}getPromptTemplate(e){return this.promptTemplates.get(e)}getResponseTemplate(e){return this.responseTemplates.get(e)}getSystemPrompt(e){return this.systemPrompts.get(e)}listTemplates(){return{prompts:Array.from(this.promptTemplates.keys()),responses:Array.from(this.responseTemplates.keys()),systemPrompts:Array.from(this.systemPrompts.keys())}}registerBuiltInTemplates(){this.registerSystemPrompt({id:"analyst",name:"Data Analyst",content:h.SYSTEM_PROMPTS.analyst}),this.registerSystemPrompt({id:"coder",name:"Code Expert",content:h.SYSTEM_PROMPTS.coder}),Object.entries(h.PROMPT_TEMPLATES).forEach(([e,t])=>{this.registerPromptTemplate(t)}),this.registerResponseTemplate({id:"json",name:"JSON Response",format:"json",validate:e=>{try{return JSON.parse(e),!0}catch{return!1}}}),this.registerResponseTemplate({id:"markdown",name:"Markdown Response",format:"markdown"})}loadTemplatesFromDirectory(e){F.loadFromDirectory(e).forEach(n=>this.registerPromptTemplate(n)),D.loadFromDirectory(e).forEach(n=>this.registerResponseTemplate(n))}loadPromptTemplatesFromDirectory(e){F.loadFromDirectory(e).forEach(r=>this.registerPromptTemplate(r))}loadResponseTemplatesFromDirectory(e){D.loadFromDirectory(e).forEach(r=>this.registerResponseTemplate(r))}};var q=class{transformers=new Map;order=[];constructor(){this.registerBuiltInTransformers()}register(e){this.transformers.set(e.id,e),this.updateOrder()}unregister(e){this.transformers.delete(e),this.updateOrder()}setEnabled(e,t){let r=this.transformers.get(e);r&&(r.enabled=t)}async transform(e,t){let r=e;for(let n of this.order){let i=this.transformers.get(n);if(i&&i.enabled!==!1)try{r=await i.transform(r,t)}catch(o){console.error(`Transformer ${n} failed:`,o)}}return r}updateOrder(){this.order=Array.from(this.transformers.keys()).sort((e,t)=>{let r=this.transformers.get(e),n=this.transformers.get(t);return(r.priority||100)-(n.priority||100)})}registerBuiltInTransformers(){this.register({id:"remove-artifacts",name:"Remove Claude Artifacts",description:"Remove artifact markdown blocks from Claude responses",priority:10,transform:e=>e.replace(/```artifact[\s\S]*?```/g,"").trim()}),this.register({id:"remove-thinking",name:"Remove Thinking Blocks",description:"Remove <thinking> blocks from responses",priority:20,transform:e=>e.replace(/<thinking>[\s\S]*?<\/thinking>/g,"").trim()}),this.register({id:"clean-markdown",name:"Clean Markdown",description:"Clean up markdown formatting",priority:30,enabled:!1,transform:e=>{let t=e.replace(/\n{3,}/g,` `);return t=t.replace(/\n#/g,` #`),t=t.replace(/^#/,"#"),t=t.replace(/\n```/g,"\n\n```"),t=t.replace(/```\n/g,"```\n\n"),t.trim()}}),this.register({id:"extract-json",name:"Extract JSON",description:"Extract JSON from code blocks or mixed content",priority:40,enabled:!1,transform:e=>{let t=e.match(/```json\n([\s\S]*?)\n```/);if(t)return t[1];let r=e.match(/\{[\s\S]*\}/);if(r)try{return JSON.parse(r[0]),r[0]}catch{}return e}}),this.register({id:"remove-code-markers",name:"Remove Code Block Markers",description:"Remove ```language markers but keep code",priority:50,enabled:!1,transform:e=>e.replace(/```[\w]*\n/g,"").replace(/```/g,"")}),this.register({id:"sanitize",name:"Sanitize Output",description:"Remove potentially harmful content",priority:60,enabled:!1,transform:e=>{let t=e.replace(/<script[\s\S]*?<\/script>/gi,"");return t=t.replace(/<style[\s\S]*?<\/style>/gi,""),t=t.replace(/on\w+="[^"]*"/gi,""),t}}),this.register({id:"regex-replace",name:"Regex Replace",description:"Custom regex replacement",priority:70,enabled:!1,transform:(e,t)=>{if(t?.regex&&t?.replacement!==void 0){let r=new RegExp(t.regex,t.flags||"g");return e.replace(r,t.replacement)}return e}})}static createTransformer(e,t,r,n){return{id:e,name:t,transform:r,priority:n||100,enabled:!0}}static patterns={removeBetween:(e,t)=>r=>{let n=new RegExp(`${H(e)}[\\s\\S]*?${H(t)}`,"g");return r.replace(n,"")},extractBetween:(e,t)=>r=>{let n=new RegExp(`${H(e)}([\\s\\S]*?)${H(t)}`),i=r.match(n);return i?i[1]:r},prefixLines:e=>t=>t.split(` `).map(r=>e+r).join(` `),truncate:(e,t="...")=>r=>r.length<=e?r:r.substring(0,e-t.length)+t};list(){return this.order.map(e=>this.transformers.get(e))}};function H(l){return l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var T=class{static toOpenAIFormat(e){let t={},r=[];if(e.parameters)for(let n of e.parameters)t[n.name]=this.buildOpenAIParameter(n),n.required&&r.push(n.name);return{name:e.name,description:e.description,parameters:{type:"object",properties:t,required:r.length>0?r:void 0}}}static toAnthropicFormat(e){let t={},r=[];if(e.parameters)for(let n of e.parameters)t[n.name]=this.buildAnthropicParameter(n),n.required&&r.push(n.name);return{name:e.name,description:e.description,input_schema:{type:"object",properties:t,required:r.length>0?r:void 0}}}static toGoogleFormat(e){let t={},r=[];if(e.parameters)for(let n of e.parameters)t[n.name]=this.buildGoogleParameter(n),n.required&&r.push(n.name);return{name:e.name,description:e.description,parameters:{type:"object",properties:t,required:r.length>0?r:void 0}}}static buildOpenAIParameter(e){let t={type:e.type,description:e.description};if(e.enum&&(t.enum=e.enum),e.type==="array"&&e.items&&(t.items=this.buildOpenAIParameter(e.items)),e.type==="object"&&e.properties){t.properties={};for(let[r,n]of Object.entries(e.properties))t.properties[r]=this.buildOpenAIParameter(n)}return t}static buildAnthropicParameter(e){let t={type:e.type,description:e.description};if(e.enum&&(t.enum=e.enum),e.type==="array"&&e.items&&(t.items=this.buildAnthropicParameter(e.items)),e.type==="object"&&e.properties){t.properties={};for(let[r,n]of Object.entries(e.properties))t.properties[r]=this.buildAnthropicParameter(n)}return t}static buildGoogleParameter(e){let t={type:e.type.toUpperCase(),description:e.description};if(e.enum&&(t.enum=e.enum),e.type==="array"&&e.items&&(t.items=this.buildGoogleParameter(e.items)),e.type==="object"&&e.properties){t.properties={};for(let[r,n]of Object.entries(e.properties))t.properties[r]=this.buildGoogleParameter(n)}return t}static parseFunctionCall(e,t){if(t==="openai"){let r=e.choices?.[0]?.message;if(r?.function_call)return{name:r.function_call.name,arguments:JSON.parse(r.function_call.arguments||"{}")};if(r?.tool_calls?.[0]){let n=r.tool_calls[0];return{name:n.function.name,arguments:JSON.parse(n.function.arguments||"{}"),id:n.id}}}else if(t==="anthropic"){let r=e.content;if(Array.isArray(r)){for(let n of r)if(n.type==="tool_use")return{name:n.name,arguments:n.input||{},id:n.id}}}else if(t==="google"){let r=e.candidates?.[0]?.content?.parts?.[0]?.functionCall;if(r)return{name:r.name,arguments:r.args||{}}}return null}static formatFunctionResult(e,t){return t==="openai"?{tool_call_id:e.id,role:"tool",name:e.name,content:e.error||JSON.stringify(e.result)}:t==="anthropic"?{type:"tool_result",tool_use_id:e.id,content:e.error?[{type:"text",text:`Error: ${e.error}`}]:[{type:"text",text:JSON.stringify(e.result)}]}:t==="google"?{functionResponse:{name:e.name,response:e.error?{error:e.error}:{result:e.result}}}:e}static validateArguments(e,t){let r=[];if(!e.parameters)return{valid:!0,errors:r};for(let n of e.parameters)n.required&&!(n.name in t)&&r.push(`Missing required parameter: ${n.name}`);for(let[n,i]of Object.entries(t)){let o=e.parameters.find(a=>a.name===n);if(!o)continue;let s=Array.isArray(i)?"array":typeof i;s!==o.type&&i!==null&&r.push(`Parameter '${n}' should be ${o.type} but got ${s}`),o.enum&&!o.enum.includes(i)&&r.push(`Parameter '${n}' must be one of: ${o.enum.join(", ")}`)}return{valid:r.length===0,errors:r}}static COMMON_FUNCTIONS={search:{name:"search",description:"Search for information on the web",parameters:[{name:"query",type:"string",description:"The search query",required:!0},{name:"num_results",type:"number",description:"Number of results to return",required:!1}]},calculate:{name:"calculate",description:"Perform mathematical calculations",parameters:[{name:"expression",type:"string",description:"The mathematical expression to evaluate",required:!0}]},getWeather:{name:"get_weather",description:"Get current weather for a location",parameters:[{name:"location",type:"string",description:"The city and country",required:!0},{name:"units",type:"string",description:"Temperature units",enum:["celsius","fahrenheit"],required:!1}]}}};var j=class{tools=new Map;config;constructor(e={}){this.config={autoExecute:!0,maxIterations:5,...e},this.registerBuiltInTools()}register(e){this.tools.set(e.name,e)}unregister(e){this.tools.delete(e)}getTool(e){return this.tools.get(e)}listTools(e,t=!0){return Array.from(this.tools.values()).filter(r=>!(t&&r.enabled===!1||e&&r.category!==e))}getToolsForProvider(e,t){return(t?t.map(n=>this.tools.get(n)).filter(Boolean):this.listTools()).map(n=>{let i={name:n.name,description:n.description,parameters:n.parameters,returns:n.returns};switch(e){case"openai":return T.toOpenAIFormat(i);case"anthropic":return T.toAnthropicFormat(i);case"google":return T.toGoogleFormat(i);default:return i}})}async executeTool(e){let t=this.tools.get(e.name);if(!t)return{name:e.name,result:null,error:`Tool '${e.name}' not found`,id:e.id};if(t.enabled===!1)return{name:e.name,result:null,error:`Tool '${e.name}' is disabled`,id:e.id};let r=T.validateArguments(t,e.arguments);if(!r.valid)return{name:e.name,result:null,error:`Invalid arguments: ${r.errors.join(", ")}`,id:e.id};try{if(this.config.requireConfirmation&&!await this.config.requireConfirmation(t,e.arguments))return{name:e.name,result:null,error:"Tool execution cancelled by user",id:e.id};this.config.onToolCall&&this.config.onToolCall(t,e.arguments);let n=await t.handler(e.arguments);return this.config.onToolResult&&this.config.onToolResult(t,n),{name:e.name,result:n,id:e.id}}catch(n){return this.config.onToolError&&this.config.onToolError(t,n),{name:e.name,result:null,error:n instanceof Error?n.message:String(n),id:e.id}}}async processToolCalls(e,t){let r=[],n=!1,i=T.parseFunctionCall(e,t);if(i){let o=this.tools.get(i.name);if(o){let s={tool:o,call:i};if(this.config.autoExecute){let a=await this.executeTool(i);s.result=a.result,a.error&&(s.error=new Error(a.error)),n=!0}r.push(s)}}return{toolCalls:r,needsResponse:n}}formatToolResults(e,t){return e.map(r=>T.formatFunctionResult(r,t))}registerBuiltInTools(){this.register({name:"calculate",description:"Perform mathematical calculations",parameters:[{name:"expression",type:"string",description:"Mathematical expression to evaluate",required:!0}],handler:async({expression:e})=>{try{return{result:Function(`"use strict"; return (${e})`)(),expression:e}}catch(t){throw new Error(`Failed to calculate: ${t}`)}},category:"math",tags:["calculation","math"]}),this.register({name:"getCurrentTime",description:"Get the current date and time",parameters:[{name:"timezone",type:"string",description:'Timezone (e.g., "UTC", "America/New_York")',required:!1}],handler:async({timezone:e})=>{let t=new Date;return e?{time:t.toLocaleString("en-US",{timeZone:e}),timezone:e,timestamp:t.getTime()}:{time:t.toISOString(),timezone:"UTC",timestamp:t.getTime()}},category:"utility",tags:["time","date"]}),this.register({name:"formatJSON",description:"Format JSON string with proper indentation",parameters:[{name:"json",type:"string",description:"JSON string to format",required:!0},{name:"indent",type:"number",description:"Number of spaces for indentation",required:!1}],handler:async({json:e,indent:t=2})=>{try{let r=JSON.parse(e);return JSON.stringify(r,null,t)}catch(r){throw new Error(`Invalid JSON: ${r}`)}},category:"utility",tags:["json","format"]})}static createTool(e,t,r,n){return!n&&r.length>0&&(n=(r.toString().match(/\(([^)]*)\)/)?.[1].split(",").map(o=>o.trim())||[]).map(o=>({name:o,type:"string",required:!0}))),{name:e,description:t,parameters:n||[],handler:r,enabled:!0}}static createAsyncTool(e,t,r,n){return{name:e,description:t,parameters:n||[],handler:async i=>{try{return await r(i)}catch(o){throw new Error(`Tool ${e} failed: ${o}`)}},enabled:!0}}};var $=class{client;templateSystem;pipelines=new Map;constructor(e,t){this.client=e,this.templateSystem=t||new w}registerPipeline(e){e.id&&this.pipelines.set(e.id,e)}async execute(e,t){let r=typeof e=="string"?this.pipelines.get(e):e;if(!r)throw new Error(`Pipeline not found: ${e}`);let n={steps:[],variables:{...r.variables,...t},metadata:{}};for(let i=0;i<r.steps.length;i++){let o=r.steps[i];if(o.skipIf&&o.skipIf(n)){n.steps.push({stepIndex:i,stepId:o.id,input:{prompt:""},output:null,skipped:!0});continue}try{let s=await this.executeStep(o,i,n,r.config);n.steps.push(s)}catch(s){throw n.steps.push({stepIndex:i,stepId:o.id,input:{prompt:""},output:null,error:s}),s}}return r.transformFinal?r.transformFinal(n.steps,n):n.steps}async executeStep(e,t,r,n){let i=this.buildStepVariables(e,t,r),o=this.templateSystem.processTemplateConfig({...e,variables:i}),s={...n,...e.config,systemPrompt:o.systemPrompt},a=await this.client.completion(o.prompt,s),p=a.content;return o.responseFormat&&(p=await this.templateSystem.applyResponseTemplate(a.content,o.responseFormat)),e.transform&&(p=await e.transform(p,r)),{stepIndex:t,stepId:e.id,input:{systemPrompt:o.systemPrompt,prompt:o.prompt},output:p,raw:a,metadata:a.metadata}}buildStepVariables(e,t,r){let n={...r.variables};if(n.stepIndex=t,n.totalSteps=r.steps.length,!e.includeSteps||e.includeSteps==="none")return n;if(n.steps={},e.includeSteps==="all"?r.steps.forEach((i,o)=>{n.steps[o+1]={output:i.output,input:i.input,metadata:i.metadata}}):Array.isArray(e.includeSteps)&&e.includeSteps.forEach(i=>{let o=i-1;if(o>=0&&o<r.steps.length){let s=r.steps[o];n.steps[i]={output:s.output,input:s.input,metadata:s.metadata}}}),r.steps.length>0){let i=r.steps[r.steps.length-1];n.lastOutput=i.output,n.lastInput=i.input}return n}static createSequential(e){return{name:"Sequential Pipeline",steps:e.map((t,r)=>typeof t=="string"?{prompt:t,includeSteps:r>0?[r]:"none"}:t)}}static createMapReduce(e,t,r){let n=[];t.forEach((o,s)=>{let a=typeof e=="string"?{prompt:e}:e;n.push({...a,id:`map-${s}`,variables:{item:o,itemIndex:s},includeSteps:"none"})});let i=typeof r=="string"?{prompt:r}:r;return n.push({...i,id:"reduce",includeSteps:"all"}),{name:"Map-Reduce Pipeline",steps:n}}listPipelines(){return Array.from(this.pipelines.keys())}getPipeline(e){return this.pipelines.get(e)}};import{v4 as Y}from"uuid";var Q=class{db=null;config;isHealthy=!0;lastError=null;constructor(e){this.config={silentFail:!0,capture:{completions:!0,conversations:!0,messages:!0,toolCalls:!0},...e},this.initializeDatabase()}async initializeDatabase(){try{let e=this.getConnectionString();if(!e){this.handleError(new Error("No database connection string available"));return}let t=await import("./knex-I7SCIQUG.mjs");this.db=t.default({client:this.config.type==="postgres"?"pg":"mysql2",connection:e,pool:{min:0,max:5,idleTimeoutMillis:3e4},acquireConnectionTimeout:5e3}),await this.db.raw("SELECT 1"),this.isHealthy=!0,process.env.TRYAI_DEBUG&&console.log("DatabaseRecorder: Connection established")}catch(e){this.handleError(e)}}getConnectionString(){return this.config.connection?this.config.connection:process.env.TRYAI_DATABASE_URL?process.env.TRYAI_DATABASE_URL:process.env.DATABASE_URL?process.env.DATABASE_URL:null}getCurrentUserId(){if(!this.config.userTracking?.enabled)return null;if(this.config.userTracking.userIdSource==="env"){let e=this.config.userTracking.envVar||"TRYAI_USER_ID";return process.env[e]||null}return null}async recordCompletion(e){if(!this.shouldCapture("completions"))return;let t={id:Y(),user_id:this.getCurrentUserId(),created_at:new Date,success:!0,...e};await this.executeWithErrorHandling(async()=>{await this.db("tryai_completions").insert(t)})}async recordConversation(e){if(!this.shouldCapture("conversations"))return;let t={id:Y(),user_id:this.getCurrentUserId(),started_at:new Date,message_count:0,total_tokens_input:0,total_tokens_output:0,total_tokens:0,total_cost_input:0,total_cost_output:0,total_cost:0,...e};await this.executeWithErrorHandling(async()=>{await this.db("tryai_conversations").insert(t)})}async recordMessage(e){if(!this.shouldCapture("messages"))return;let t={id:Y(),user_id:this.getCurrentUserId(),created_at:new Date,in_context:!0,...e};await this.executeWithErrorHandling(async()=>{await this.db("tryai_messages").insert(t)})}async recordToolCall(e){if(!this.shouldCapture("toolCalls"))return;let t={id:Y(),user_id:this.getCurrentUserId(),created_at:new Date,success:!0,...e};await this.executeWithErrorHandling(async()=>{await this.db("tryai_tool_calls").insert(t)})}async updateConversationStats(e,t){this.shouldCapture("conversations")&&await this.executeWithErrorHandling(async()=>{await this.db("tryai_conversations").where({id:e}).update({message_count:t.messageCount,total_tokens_input:t.totalTokensInput,total_tokens_output:t.totalTokensOutput,total_tokens:t.totalTokens,total_cost_input:t.totalCostInput,total_cost_output:t.totalCostOutput,total_cost:t.totalCost,average_latency:t.averageLatency,last_message_at:t.lastMessageAt})})}shouldCapture(e){return!this.db||!this.isHealthy?!1:this.config.capture?.[e]!==!1}async executeWithErrorHandling(e){if(!(!this.db||!this.isHealthy))try{await e()}catch(t){this.handleError(t)}}handleError(e){if(this.lastError=e,this.isHealthy=!1,this.config.silentFail===!1)throw e;process.env.TRYAI_DEBUG&&console.warn("TryAI DatabaseRecorder Error:",e.message),setTimeout(()=>{this.checkHealth()},3e4)}async checkHealth(){if(this.db)try{await this.db.raw("SELECT 1"),this.isHealthy=!0,this.lastError=null,process.env.TRYAI_DEBUG&&console.log("DatabaseRecorder: Health check passed - reconnected")}catch(e){this.handleError(e)}}getHealth(){return{healthy:this.isHealthy,lastError:this.lastError?.message}}async close(){if(this.db){try{await this.db.destroy()}catch{}this.db=null}}recordAsync(e){setImmediate(async()=>{try{await e()}catch(t){this.handleError(t)}})}};function pe(l){if(!l.enabled)return null;try{return new Q(l)}catch(e){if(l.silentFail===!1)throw e;return process.env.TRYAI_DEBUG&&console.warn("Failed to create DatabaseRecorder:",e),null}}var ue={temperature:.7,maxTokens:2048,metadata:{enabled:!0,trackCosts:!0,trackLatency:!0,trackTokens:!0,includeTimestamp:!0},retry:{enabled:!0,maxAttempts:3,initialDelay:1e3,maxDelay:1e4,backoffMultiplier:2},conversation:{maxHistory:50,persistHistory:!1}}