@juspay/neurolink 13.8.15 → 13.8.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +2 -2
- package/dist/browser/neurolink.min.js +3 -3
- package/dist/core/conversationMemoryFactory.d.ts +2 -2
- package/dist/core/conversationMemoryFactory.js +2 -2
- package/dist/core/conversationMemoryInitializer.d.ts +2 -2
- package/dist/core/conversationMemoryInitializer.js +2 -2
- package/dist/core/redisConversationMemoryManager.d.ts +13 -2
- package/dist/core/redisConversationMemoryManager.js +31 -1
- package/dist/neurolink.js +1 -1
- package/dist/types/common.d.ts +2 -1
- package/dist/types/conversation.d.ts +12 -0
- package/docs-site/static/search-index.json +4 -2
- package/package.json +1 -1
|
@@ -1913,14 +1913,14 @@ For "closing" slides (shows checkmarks \u2713):
|
|
|
1913
1913
|
- For summary/thank you \u2192 type="closing" (checkmarks \u2713)
|
|
1914
1914
|
- For regular content \u2192 type="content" (disc bullets \u2022)
|
|
1915
1915
|
|
|
1916
|
-
\u26A0\uFE0F CRITICAL: Content MUST fit within slide box. Keep text SHORT.`,Upr=5,Bpr=50,zpr=10,Gpr=5e3,qpr=Object.keys(kI),jpr=["business","students","technical","general"],Vpr=["professional","casual","educational","persuasive"],Hpr=["16:9","4:3"],ZF={content:{bulletStyle:"disc",baseFontSize:18},bullets:{bulletStyle:"disc",baseFontSize:18},agenda:{bulletStyle:"number",baseFontSize:18},"numbered-list":{bulletStyle:"number",baseFontSize:18},conclusion:{bulletStyle:"checkmark",baseFontSize:18},closing:{bulletStyle:"checkmark",baseFontSize:18},"two-column":{bulletStyle:"disc",baseFontSize:16},"three-column":{bulletStyle:"disc",baseFontSize:14},"split-content":{bulletStyle:"disc",baseFontSize:16},comparison:{bulletStyle:"arrow",baseFontSize:16},features:{bulletStyle:"none",baseFontSize:16},icons:{bulletStyle:"none",baseFontSize:16},default:{bulletStyle:"disc",baseFontSize:18}},mme=6e4,QF=3e4,hme=5,Ul=3e5}}),Rc,Ku,fme=S({"src/lib/features/ppt/pptError.ts"(){"use strict";et(),Rc={PLANNING_FAILED:"PPT_PLANNING_FAILED",INVALID_AI_RESPONSE:"PPT_INVALID_AI_RESPONSE",IMAGE_GENERATION_FAILED:"PPT_IMAGE_GENERATION_FAILED",ASSEMBLY_FAILED:"PPT_ASSEMBLY_FAILED",FILE_WRITE_FAILED:"PPT_FILE_WRITE_FAILED",INVALID_INPUT:"PPT_INVALID_INPUT",TIMEOUT:"PPT_TIMEOUT"},Ku=class extends Me{constructor(e,t,r,n){super({code:t,message:e,category:"execution",severity:"high",retriable:!1,context:{...r,originalMessage:n?.message},originalError:n}),this.name="PPTError"}}}}),Wpr={};ue(Wpr,{PPT_VALID_PROVIDERS:()=>d_,bufferToDataUrl:()=>AI,calculateFontSize:()=>tmr,createFormattedTextProps:()=>c_,ensureOutputDirectory:()=>Jpr,extractPPTContext:()=>tEn,generateOutputPath:()=>Kpr,getEffectivePPTProvider:()=>rEn,getFailureStage:()=>gme,getLayoutName:()=>Qpr,hasMarkdownFormatting:()=>l_,isLogoConfig:()=>Ypr,isObject:()=>Xpr,normalizeLogoConfig:()=>Zpr,parseMarkdownText:()=>u_,toError:()=>emr,validateImageBuffer:()=>yme});function tEn(e){const t=e.output?.ppt;if(!t)throw new Ku("PPT options are required when mode is 'ppt'",Rc.INVALID_INPUT,{field:"output.ppt"});let r;if(t.logoPath){if(Buffer.isBuffer(t.logoPath)||typeof t.logoPath=="string")r=t.logoPath;else if(typeof t.logoPath=="object"&&"data"in t.logoPath){const o=t.logoPath.data;r=Buffer.isBuffer(o)||typeof o=="string"?o:void 0}}const n=[];if(e.input?.images){for(const o of e.input.images)if(Buffer.isBuffer(o)||typeof o=="string")n.push(o);else if(typeof o=="object"&&"data"in o){const i=o.data;(Buffer.isBuffer(i)||typeof i=="string")&&n.push(i)}}return!r&&n.length>0&&(r=n[0]),{topic:e.input?.text||"",pages:t.pages,theme:t.theme??"AI will decide",audience:t.audience??"AI will decide",tone:t.tone??"AI will decide",generateAIImages:t.generateAIImages??!1,aspectRatio:t.aspectRatio||"16:9",outputPath:t.outputPath,logo:r,images:n.length>0?n:void 0,provider:e.provider,model:e.model}}async function rEn(e,t,r,n){const{ErrorFactory:o}=await Promise.resolve().then(()=>(et(),yk)),i=t.toLowerCase();if(d_.includes(i)){const s=e,a=r||s?.modelName||s?.getDefaultModel?.()||"";return f.debug("[PPT Utils] Current provider is valid for PPT",{provider:t,model:a}),{provider:e,providerName:t,modelName:a,wasAutoSelected:!1}}f.info("[PPT Utils] Current provider not valid for PPT, auto-selecting",{currentProvider:t});for(const s of d_)if(mpe(s)){f.info("[PPT Utils] Auto-selected PPT provider",{originalProvider:t,selectedProvider:s});const{AIProviderFactory:a}=await Promise.resolve().then(()=>(lu(),fR)),{withTimeout:u}=await Promise.resolve().then(()=>(et(),yk)),{PPT_GENERATION_TIMEOUT_MS:l}=await Promise.resolve().then(()=>(a_(),lme)),c=await u(a.createProvider(s,void 0,!0,n),l/4,o.toolTimeout("createProvider",l/4));return{provider:c,providerName:s,modelName:c.modelName,wasAutoSelected:!0}}throw o.invalidParameters("ppt-generation",new Error(`No PPT-compatible provider available. Configure one of: ${d_.join(", ")}`),{currentProvider:t,validProviders:d_})}function Kpr(e){const t=new Date().toISOString().replace(/[:.]/g,"-").substring(0,19),n=`${e.topic.substring(0,30).replace(/[^a-zA-Z0-9]/g,"_").toLowerCase()}_${t}.pptx`;return e.outputPath?e.outputPath.endsWith(".pptx")?e.outputPath:Nt(e.outputPath,n):Nt(process.cwd(),"output",n)}async function Jpr(e){const t=QV(e);try{const{withTimeout:r,ErrorFactory:n}=await Promise.resolve().then(()=>(et(),yk)),{PPT_GENERATION_TIMEOUT_MS:o}=await Promise.resolve().then(()=>(a_(),lme));await r(Aee(t,{recursive:!0}),o/8,n.toolTimeout("mkdirOutputDirectory",o/8))}catch(r){const n=r instanceof Error?r:new Error(String(r));throw new Ku(`Failed to create output directory: ${t}`,Rc.FILE_WRITE_FAILED,{directory:t},n)}}function Xpr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ypr(e){return Xpr(e)?"data"in e&&(Buffer.isBuffer(e.data)||typeof e.data=="string"):!1}function Zpr(e){return e===null?null:Buffer.isBuffer(e)||typeof e=="string"?{data:e,position:"bottom-right",width:1,height:.4,showOn:"all-slides"}:Ypr(e)?e:null}function Qpr(e){switch(e){case"16:9":return"LAYOUT_16x9";case"4:3":return"LAYOUT_4x3";default:return"LAYOUT_16x9"}}function emr(e){return e instanceof Error?e:new Error(String(e))}function gme(e){return e.contentPlan===null?"content-planning":e.slides===null?"slide-generation":e.outputPath===null?"pptx-assembly":"file-output"}function yme(e){return!e||e.length===0?{isValid:!1,mimeType:"",format:"",error:"Empty or undefined buffer"}:e.length<100?{isValid:!1,mimeType:"",format:"",error:`Buffer too small (${e.length} bytes)`}:e[0]===255&&e[1]===216&&e[2]===255?{isValid:!0,mimeType:"image/jpeg",format:"JPEG"}:e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71?{isValid:!0,mimeType:"image/png",format:"PNG"}:e[0]===71&&e[1]===73&&e[2]===70?{isValid:!0,mimeType:"image/gif",format:"GIF"}:e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e.length>12&&e.slice(8,12).toString()==="WEBP"?{isValid:!0,mimeType:"image/webp",format:"WebP"}:e[0]===66&&e[1]===77?{isValid:!0,mimeType:"image/bmp",format:"BMP"}:{isValid:!1,mimeType:"image/png",format:"unknown",error:`Unknown format (magic bytes: ${e.slice(0,4).toString("hex")})`}}function AI(e){const t=yme(e);return!t.isValid&&t.format===""?(f.warn("[bufferToDataUrl] Invalid image buffer",{error:t.error}),null):`data:${t.mimeType||"image/png"};base64,${e.toString("base64")}`}function u_(e){if(!e||typeof e!="string")return[{text:e||""}];const t=[],r=/(\*\*\*(.+?)\*\*\*|\*\*(.+?)\*\*|\*(.+?)\*)/g;let n=0;for(;;){const o=r.exec(e);if(o===null)break;o.index>n&&t.push({text:e.slice(n,o.index)}),o[2]?t.push({text:o[2],bold:!0,italic:!0}):o[3]?t.push({text:o[3],bold:!0}):o[4]&&t.push({text:o[4],italic:!0}),n=r.lastIndex}return n<e.length&&t.push({text:e.slice(n)}),t.length===0&&t.push({text:e}),t}function l_(e){return!e||typeof e!="string"?!1:/\*{1,3}[^*]+\*{1,3}/.test(e)}function c_(e,t){return e.map(r=>({text:r.text,options:{fontSize:t.fontSize,fontFace:t.fontFace,color:t.color,bold:r.bold||t.baseBold||!1,italic:r.italic||!1}}))}function tmr(e,t=18){return e<=5?t:e<=7?Math.max(12,t-2):e<=10?Math.max(12,t-4):12}var d_,vme=S({"src/lib/features/ppt/utils.ts"(){"use strict";_i(),Er(),lf(),z(),fme(),d_=["vertex","openai","azure","anthropic","google-ai","bedrock"]}});function nEn(e,t,r=!1){const n=t/72,o=.42,i=r?1.1:1,s=n*o*i;return e.length*s}function Bs(e,t,r,n=!0){if(e.addText(t,{x:Vt.title.x,y:Vt.title.y,w:Vt.title.w,h:Vt.title.h,fontSize:r.fonts.sizes.heading,fontFace:r.fonts.heading,color:r.colors.text.replace("#",""),bold:!0,fit:$t}),n){const o=nEn(t,r.fonts.sizes.heading,!0),i=Vt.title.w,a=Math.min(i,Math.max(1,o));e.addShape("rect",{x:Vt.title.x,y:Vt.title.y+Vt.title.h+.1,w:a,h:.03,fill:{color:r.colors.primary.replace("#","")}})}}function rmr(e){const{slide:t,bullets:r,startX:n,startY:o,width:i,theme:s,itemSpacing:a=.45}=e;if(!r||r.length===0)return;const u=Math.max(a,m_*2);r.forEach((l,c)=>{if(!l||!l.text)return;const d=l.bold||l.emphasis||!1,p=l.color?.replace("#","")||s.colors.text.replace("#","");if(l_(l.text)){const m=u_(l.text),h=[{text:"\u2022 ",options:{fontSize:s.fonts.sizes.body,fontFace:s.fonts.body,color:p}},...c_(m,{fontSize:s.fonts.sizes.body,fontFace:s.fonts.body,color:p,baseBold:d})];t.addText(h,{x:n,y:o+c*u,w:i,h:Math.max(.4,u-m_),fit:$t})}else{const m=`\u2022 ${l.text}`;t.addText(m,{x:n,y:o+c*u,w:i,h:Math.max(.4,u-m_),fontSize:s.fonts.sizes.body,fontFace:s.fonts.body,color:p,bold:d,fit:$t})}})}function nmr(e,t,r,n,o="content",i){if(!t||t.length===0)return;if(i?.useIndividualBullets){rmr({slide:e,bullets:t,startX:r.x,startY:r.y,width:r.w,theme:n,itemSpacing:i.itemSpacing??.45});return}const s=Epr(o),a=tmr(t.length,s.baseFontSize||n.fonts.sizes.body),u=[];t.forEach(l=>{if(!l||!l.text)return;const c=l.bulletStyle||s.bulletStyle||"disc",d=l.fontSize||a,p=l.color?.replace("#","")||n.colors.text.replace("#",""),m=l.bold??l.emphasis??!1;let h;if(l.icon?h={code:l.icon}:h=Spr(c),l_(l.text)){const g=u_(l.text),y=c_(g,{fontSize:d,fontFace:n.fonts.body,color:p,baseBold:m});u.push({text:y,options:{bullet:h,indentLevel:0,paraSpaceBefore:6,paraSpaceAfter:6}})}else u.push({text:l.text,options:{bullet:h,fontSize:d,fontFace:n.fonts.body,color:p,bold:m,indentLevel:0,paraSpaceBefore:6,paraSpaceAfter:6}});l.subBullets&&l.subBullets.length>0&&l.subBullets.forEach(g=>{if(l_(g)){const y=u_(g),v=c_(y,{fontSize:Math.max(10,d-2),fontFace:n.fonts.body,color:n.colors.muted.replace("#","")});u.push({text:v,options:{bullet:!0,indentLevel:1,paraSpaceBefore:3,paraSpaceAfter:3}})}else u.push({text:g,options:{bullet:!0,fontSize:Math.max(10,d-2),fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),indentLevel:1,paraSpaceBefore:3,paraSpaceAfter:3}})})}),e.addText(u,{x:r.x,y:r.y,w:r.w,h:r.h,valign:"top",fit:$t})}function wme(e,t,r){const n=yme(t);if(!n.isValid&&n.format===""){f.warn("[addImage] Invalid image buffer",{error:n.error});return}n.isValid||f.warn("[addImage] Image validation warning, attempting to add anyway",{error:n.error,mimeType:n.mimeType});const o=AI(t);if(!o){f.warn("[addImage] Failed to convert buffer to data URL");return}try{e.addImage({data:o,x:r.x,y:r.y,w:r.w,h:r.h,sizing:{type:"cover",w:r.w,h:r.h}})}catch(i){f.error("[addImage] Failed to add image to slide",{error:i instanceof Error?i.message:String(i)})}}function oEn(e){switch(e){case"chart-bar":return"bar";case"chart-line":return"line";case"chart-pie":return"pie";case"chart-area":return"area";default:return"bar"}}function iEn(e,t,r,n,o){const i=r.layoutOptions||{},s=i.title||{},a=i.subtitle||{},u=i.background||{},l=o?AI(o):null;if(l)e.background={data:l},e.addShape("rect",{x:0,y:0,w:"100%",h:"100%",fill:{color:"000000",transparency:40}});else if(u.color||u.useThemePrimary||u.useThemeSecondary){const m=u.useThemePrimary?n.colors.primary:u.useThemeSecondary?n.colors.secondary:u.color||n.colors.background;e.addShape("rect",{x:0,y:0,w:10,h:5.625,fill:{color:m.replace("#","")}})}const c=o||u.color||u.useThemePrimary||u.useThemeSecondary,d=c?"FFFFFF":n.colors.text.replace("#",""),p=c?"FFFFFF":n.colors.muted.replace("#","");e.addText(t,{x:s.x??.5,y:s.y??2,w:s.w??9,h:s.h??1.2,fontSize:s.fontSize??n.fonts.sizes.title,fontFace:n.fonts.heading,color:s.color?.replace("#","")??d,align:s.align??"center",bold:!0,fit:$t}),r.subtitle&&e.addText(r.subtitle,{x:a.x??.5,y:a.y??3.3,w:a.w??9,h:a.h??.6,fontSize:a.fontSize??n.fonts.sizes.subtitle,fontFace:n.fonts.body,color:a.color?.replace("#","")??p,align:a.align??"center",fit:$t})}function sEn(e,t,r,n){const o=r.layoutOptions||{},i=o.sectionNumber||{},s=o.title||{},a=o.subtitle||{},u=o.background||{};if(u.color&&e.addShape("rect",{x:0,y:0,w:10,h:5.625,fill:{color:u.color.replace("#","")}}),r.sectionNumber){const l=i.style==="watermark",c=i.style==="small";e.addText(String(r.sectionNumber).padStart(2,"0"),{x:i.x??(l?5.5:.5),y:i.y??(l?.5:1.5),w:l?5:2,h:l?4:1,fontSize:i.fontSize??(l?200:c?32:72),fontFace:n.fonts.heading,color:n.colors.primary.replace("#",""),bold:!0,align:l?"right":"left",transparency:l?70:0})}e.addText(t,{x:s.x??.5,y:s.y??2.5,w:s.w??9,h:s.h??1,fontSize:s.fontSize??n.fonts.sizes.title,fontFace:n.fonts.heading,color:n.colors.text.replace("#",""),bold:!0,align:s.align??"left"}),r.subtitle&&e.addText(r.subtitle,{x:a.x??.5,y:a.y??3.6,w:a.w??8,h:a.h??.6,fontSize:a.fontSize??n.fonts.sizes.subtitle,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:a.align??"left"})}function aEn(e,t,r,n,o){if(o){const s=AI(o);s&&(e.background={data:s},e.addShape("rect",{x:0,y:0,w:"100%",h:"100%",fill:{color:"000000",transparency:40}}))}const i=o?"FFFFFF":n.colors.text.replace("#","");if(e.addText(t||"Thank You!",{x:.5,y:1.8,w:9,h:1,fontSize:n.fonts.sizes.title,fontFace:n.fonts.heading,color:i,align:"center",bold:!0,fit:$t}),r.cta&&e.addText(r.cta,{x:.5,y:2.9,w:9,h:.5,fontSize:n.fonts.sizes.subtitle,fontFace:n.fonts.body,color:o?"FFFFFF":n.colors.muted.replace("#",""),align:"center",fit:$t}),r.contactInfo){const s=[];if(r.contactInfo.email&&s.push(`Email: ${r.contactInfo.email}`),r.contactInfo.website&&s.push(`Web: ${r.contactInfo.website}`),r.contactInfo.phone&&s.push(`Phone: ${r.contactInfo.phone}`),s.length>0&&e.addText(s.join(" \u2022 "),{x:.5,y:4.2,w:9,h:.4,fontSize:n.fonts.sizes.body,fontFace:n.fonts.body,color:i,align:"center",fit:$t}),r.contactInfo.social&&Array.isArray(r.contactInfo.social)&&r.contactInfo.social.length>0){const a=r.contactInfo.social.map(u=>`${u.platform||""}: ${u.handle||""}`).join(" \u2022 ");e.addText(a,{x:.5,y:4.7,w:9,h:.3,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:o?"CCCCCC":n.colors.muted.replace("#",""),align:"center"})}}}function bme(e){const{slide:t,title:r,content:n,layout:o,theme:i,imageBuffer:s,slideType:a="content"}=e;Bs(t,r,i);const u=s&&o.includes("image"),l=u?o.includes("left")?Vt.contentRight:Vt.contentLeft:Vt.contentFull;if(n.bullets&&n.bullets.length>0?nmr(t,n.bullets,l,i,a):n.body&&t.addText(n.body,{x:l.x,y:l.y,w:l.w,h:l.h,fontSize:i.fonts.sizes.body,fontFace:i.fonts.body,color:i.colors.text.replace("#",""),valign:"top"}),s&&u){const c=o.includes("left")?Vt.imageLeft:Vt.imageRight;wme(t,s,c)}}function uEn(e,t,r,n,o,i){if(n==="image-full-overlay"&&i){const s=AI(i);s?(e.background={data:s},e.addShape("rect",{x:0,y:0,w:"100%",h:"100%",fill:{color:"000000",transparency:50}}),e.addText(t,{x:.5,y:4.2,w:9,h:1,fontSize:o.fonts.sizes.heading,fontFace:o.fonts.heading,color:"FFFFFF",bold:!0,fit:$t})):Bs(e,t,o)}else n==="image-centered"||n==="image-full-overlay"?(Bs(e,t,o),i?wme(e,i,Vt.imageCentered):(e.addShape("rect",{x:1.5,y:1.8,w:7,h:3.5,fill:{color:o.colors.muted.replace("#",""),transparency:90},line:{color:o.colors.muted.replace("#",""),width:1,dashType:"dash"}}),e.addText("\u{1F4F7}",{x:1.5,y:2.8,w:7,h:1,fontSize:48,align:"center",valign:"middle",fit:$t}),e.addText("Image not available",{x:1.5,y:3.8,w:7,h:.5,fontSize:12,fontFace:o.fonts.body,color:o.colors.muted.replace("#",""),align:"center",fit:$t})),r.caption&&e.addText(r.caption,{x:.5,y:5,w:9,h:.4,fontSize:o.fonts.sizes.caption,fontFace:o.fonts.body,color:o.colors.muted.replace("#",""),align:"center",fit:$t})):bme({slide:e,title:t,content:r,layout:n,theme:o,imageBuffer:i})}function omr(e,t,r,n,o){Bs(e,t,n,!1);const i={headerY:o?.headerY??1.3,headerHeight:o?.headerHeight??.5,bulletsStartY:o?.bulletsStartY??2,columnGap:o?.columnGap??.3,highlightFirstColumn:o?.highlightFirstColumn??!0},s=r.length;if(s===0)return;const a=9,u=(s-1)*i.columnGap,l=(a-u)/s,c=.5;r.forEach((d,p)=>{if(!d)return;const m=c+p*(l+i.columnGap),h=i.highlightFirstColumn&&p===0;if(d.title){e.addShape("roundRect",{x:m,y:i.headerY,w:l,h:i.headerHeight,fill:{color:h?n.colors.primary.replace("#",""):n.colors.muted.replace("#","")},rectRadius:.05});const g=s<=2?n.fonts.sizes.body:n.fonts.sizes.body-2;e.addText(d.title,{x:m,y:i.headerY,w:l,h:i.headerHeight,fontSize:g,fontFace:n.fonts.heading,color:h?n.colors.textOnPrimary.replace("#",""):n.colors.text.replace("#",""),align:"center",bold:!0,valign:"middle",fit:$t})}d.bullets&&d.bullets.length>0&&rmr({slide:e,bullets:d.bullets,startX:m,startY:i.bulletsStartY,width:l,theme:n})})}function lEn(e,t,r,n,o,i){const s=[];r.leftColumn&&s.push(r.leftColumn),r.rightColumn&&s.push(r.rightColumn),s.length>0&&omr(e,t,s,o,{highlightFirstColumn:!0}),i&&!r.rightColumn?.bullets&&wme(e,i,Vt.columnRight)}function cEn(e,t,r,n){const o=[];r.leftColumn&&o.push(r.leftColumn),r.centerColumn&&o.push(r.centerColumn),r.rightColumn&&o.push(r.rightColumn),o.length>0&&omr(e,t,o,n,{highlightFirstColumn:!0})}function dEn(e,t,r,n){if(e.addText("\u201C",{x:.5,y:1,w:1,h:1,fontSize:120,fontFace:"Georgia",color:n.colors.primary.replace("#",""),fit:$t}),r.quote&&e.addText(r.quote,{x:Vt.quote.x,y:Vt.quote.y,w:Vt.quote.w,h:Vt.quote.h,fontSize:n.fonts.sizes.heading,fontFace:"Georgia",color:n.colors.text.replace("#",""),italic:!0,valign:"middle",fit:$t}),r.quoteAuthor){let o=`\u2014 ${r.quoteAuthor}`;r.quoteAuthorTitle&&(o+=`, ${r.quoteAuthorTitle}`),e.addText(o,{x:Vt.quoteAuthor.x,y:Vt.quoteAuthor.y,w:Vt.quoteAuthor.w,h:Vt.quoteAuthor.h,fontSize:n.fonts.sizes.body,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:"right",fit:$t})}}function pEn(e,t,r,n){if(Bs(e,t,n),!r.statistics||r.statistics.length===0)return;const o=r.statistics.slice(0,4),i=9/o.length;o.forEach((s,a)=>{const u=.5+a*i;if(e.addText(s.value,{x:u,y:Vt.statRow.y,w:i-.2,h:1.2,fontSize:48,fontFace:n.fonts.heading,color:n.colors.primary.replace("#",""),bold:!0,align:"center",fit:$t}),e.addText(s.label,{x:u,y:Vt.statRow.y+1.3,w:i-.2,h:.5,fontSize:n.fonts.sizes.body,fontFace:n.fonts.body,color:n.colors.text.replace("#",""),align:"center",fit:$t}),s.change||s.trend){const l=s.trend==="up"?"22C55E":s.trend==="down"?"EF4444":n.colors.muted.replace("#",""),c=s.trend==="up"?"(+)":s.trend==="down"?"(-)":"";e.addText(`${c} ${s.change||""}`,{x:u,y:Vt.statRow.y+1.8,w:i-.2,h:.4,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:l,align:"center",fit:$t})}})}function mEn(e,t,r,n,o){if(Bs(e,t,o),!r.chartData||!r.chartData.series||r.chartData.series.length===0){e.addText("No chart data available",{x:Vt.chart.x,y:Vt.chart.y+1,w:Vt.chart.w,h:1,fontSize:18,color:o.colors.muted.replace("#",""),align:"center",fit:$t});return}const i=r.chartData.series.filter(u=>u.name&&Array.isArray(u.labels)&&u.labels.length>0&&Array.isArray(u.values)&&u.values.length>0);if(i.length===0){e.addText("Invalid chart data format",{x:Vt.chart.x,y:Vt.chart.y+1,w:Vt.chart.w,h:1,fontSize:18,color:o.colors.muted.replace("#",""),align:"center",fit:$t});return}const s=oEn(n),a=i.map(u=>({name:u.name,labels:u.labels,values:u.values}));e.addChart(s,a,{x:Vt.chart.x,y:Vt.chart.y,w:Vt.chart.w,h:Vt.chart.h,showTitle:!!r.chartData.title,title:r.chartData.title,showLegend:r.chartData.legendPosition!=="none",legendPos:umr[r.chartData.legendPosition||"bottom"]||"b",showValue:r.chartData.showLabels,chartColors:[o.colors.primary.replace("#",""),o.colors.secondary.replace("#",""),o.colors.accent.replace("#","")]})}function hEn(e,t,r,n){if(Bs(e,t,n),!r.tableData)return;const{headers:o,rows:i,hasHeader:s}=r.tableData,a=[];s&&o&&a.push(o.map(u=>({text:u,options:{bold:!0,fill:{color:n.colors.primary.replace("#","")},color:n.colors.textOnPrimary.replace("#",""),align:"center"}}))),i.forEach((u,l)=>{a.push(u.map(c=>({text:c.text,options:{fill:{color:l%2===0?"F8FAFC":"FFFFFF"},color:n.colors.text.replace("#",""),align:c.align||"left"}})))}),e.addTable(a,{x:Vt.chart.x,y:Vt.chart.y,w:Vt.chart.w,colW:Array(o?.length||i[0]?.length||1).fill(Vt.chart.w/(o?.length||i[0]?.length||1)),fontSize:n.fonts.sizes.body-2,fontFace:n.fonts.body,border:{pt:.5,color:"E2E8F0"},autoPage:!0}),r.tableData.caption&&e.addText(r.tableData.caption,{x:.5,y:5.1,w:9,h:.3,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:"center"})}function fEn(e,t,r,n){if(Bs(e,t,n),!r.timeline?.items)return;const o=r.timeline.items.slice(0,5);r.timeline.orientation!=="vertical"?gEn(e,o,n):yEn(e,o,n)}function gEn(e,t,r){const n=8/t.length,o=2.8;e.addShape("rect",{x:1,y:o,w:8,h:.02,fill:{color:r.colors.primary.replace("#","")}}),t.forEach((i,s)=>{const a=1+s*n+n/2-.15;e.addShape("ellipse",{x:a,y:o-.15,w:.3,h:.3,fill:{color:r.colors.primary.replace("#","")}}),e.addText(i.date,{x:a-n/2+.15,y:o-.8,w:n,h:.4,fontSize:r.fonts.sizes.caption,fontFace:r.fonts.body,color:r.colors.primary.replace("#",""),align:"center",bold:!0,fit:$t}),e.addText(i.title,{x:a-n/2+.15,y:o+.4,w:n,h:.4,fontSize:r.fonts.sizes.body,fontFace:r.fonts.heading,color:r.colors.text.replace("#",""),align:"center",bold:!0,fit:$t}),i.description&&e.addText(i.description,{x:a-n/2+.15,y:o+.85,w:n,h:.8,fontSize:r.fonts.sizes.caption,fontFace:r.fonts.body,color:r.colors.muted.replace("#",""),align:"center",fit:$t})})}function yEn(e,t,r){const n=3/t.length,o=1.5;e.addShape("rect",{x:o,y:1.5,w:.04,h:3.5,fill:{color:r.colors.primary.replace("#","")}}),t.forEach((i,s)=>{const a=1.7+s*n;e.addShape("ellipse",{x:o-.12,y:a,w:.28,h:.28,fill:{color:r.colors.primary.replace("#","")}}),e.addText(i.date,{x:.3,y:a-.1,w:1,h:.3,fontSize:r.fonts.sizes.caption,fontFace:r.fonts.body,color:r.colors.primary.replace("#",""),bold:!0,fit:$t}),e.addText(i.title,{x:2,y:a-.1,w:7,h:.4,fontSize:r.fonts.sizes.body,fontFace:r.fonts.heading,color:r.colors.text.replace("#",""),bold:!0,fit:$t}),i.description&&e.addText(i.description,{x:2,y:a+.3,w:7,h:.4,fontSize:r.fonts.sizes.caption,fontFace:r.fonts.body,color:r.colors.muted.replace("#",""),fit:$t})})}function vEn(e,t,r,n){if(Bs(e,t,n),!r.processSteps)return;const o=r.processSteps.slice(0,5),i=8/o.length;o.forEach((s,a)=>{const u=1+a*i,l=i-.4;e.addShape("roundRect",{x:u,y:2,w:l,h:2,fill:{color:n.colors.primary.replace("#","")},rectRadius:.1}),e.addText(String(s.step),{x:u,y:2.1,w:l,h:.5,fontSize:24,fontFace:n.fonts.heading,color:n.colors.textOnPrimary.replace("#",""),align:"center",bold:!0,fit:$t}),e.addText(s.title,{x:u,y:2.6,w:l,h:.5,fontSize:n.fonts.sizes.body,fontFace:n.fonts.heading,color:n.colors.textOnPrimary.replace("#",""),align:"center",bold:!0,fit:$t}),s.description&&e.addText(s.description,{x:u,y:3.2,w:l,h:.7,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:n.colors.textOnPrimary.replace("#",""),align:"center",fit:$t}),a<o.length-1&&e.addShape("rightArrow",{x:u+l+.02,y:2.85,w:.35,h:.3,fill:{color:n.colors.primary.replace("#","")}})})}function wEn(e,t,r,n){if(Bs(e,t,n,!1),!r.comparison?.columns)return;const o=r.comparison.columns.slice(0,2),i=4.2,s=2,u=5-s,l=Math.max(...o.map(p=>Math.min(p.items?.length||0,6))),c=l>0?Math.min(.7,(u-m_*l)/l):.5,d=c+m_;o.forEach((p,m)=>{const h=.5+m*4.8;e.addShape("roundRect",{x:h,y:1.4,w:i,h:.5,fill:{color:p.highlight?n.colors.primary.replace("#",""):n.colors.muted.replace("#","")},rectRadius:.05}),e.addText(p.title,{x:h,y:1.4,w:i,h:.5,fontSize:n.fonts.sizes.body,fontFace:n.fonts.heading,color:p.highlight?n.colors.textOnPrimary.replace("#",""):n.colors.text.replace("#",""),align:"center",bold:!0,valign:"middle",fit:$t});const g=(p.items||[]).slice(0,6),y=g.length>4?Math.max(12,n.fonts.sizes.body-2):n.fonts.sizes.body;g.forEach((v,w)=>{if(l_(v)){const b=u_(v),E=[{text:"\u2022 ",options:{fontSize:y,fontFace:n.fonts.body,color:n.colors.text.replace("#","")}},...c_(b,{fontSize:y,fontFace:n.fonts.body,color:n.colors.text.replace("#","")})];e.addText(E,{x:h+.2,y:s+w*d,w:i-.4,h:c,valign:"top",fit:$t})}else e.addText(`\u2022 ${v}`,{x:h+.2,y:s+w*d,w:i-.4,h:c,fontSize:y,fontFace:n.fonts.body,color:n.colors.text.replace("#",""),valign:"top",fit:$t})})})}function bEn(e,t,r,n){Bs(e,t,n);const o=r.features||[],i=r.icons||[],s=o.length>0?o:i.map(l=>({title:l.label,description:l.description||"",icon:l.icon}));if(s.length===0)return;const a=Math.min(s.length,3),u=9/a;s.slice(0,6).forEach((l,c)=>{const d=Math.floor(c/a),m=.5+c%a*u,h=1.6+d*1.8;if(l.icon){const g=parseInt(l.icon,16);if(!Number.isNaN(g)&&g>=0&&g<=1114111){const y=String.fromCodePoint(g);e.addText(y,{x:m,y:h,w:u-.2,h:.6,fontSize:36,fontFace:"Segoe UI Emoji",color:n.colors.primary.replace("#",""),align:"center",fit:$t})}}e.addText(l.title,{x:m,y:h+.6,w:u-.2,h:.4,fontSize:n.fonts.sizes.body,fontFace:n.fonts.heading,color:n.colors.text.replace("#",""),align:"center",bold:!0,fit:$t}),l.description&&e.addText(l.description,{x:m,y:h+1,w:u-.2,h:.6,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:"center",fit:$t})})}function TEn(e,t,r,n){if(Bs(e,t,n),!r.teamMembers)return;const o=r.teamMembers.slice(0,4),i=9/o.length;o.forEach((s,a)=>{const u=.5+a*i;e.addShape("ellipse",{x:u+(i-1.5)/2,y:1.6,w:1.5,h:1.5,fill:{color:n.colors.muted.replace("#","")}});const l=s.name.split(" ").map(c=>c[0]).join("").substring(0,2);e.addText(l,{x:u+(i-1.5)/2,y:2,w:1.5,h:.7,fontSize:28,fontFace:n.fonts.heading,color:"FFFFFF",align:"center",bold:!0,fit:$t}),e.addText(s.name,{x:u,y:3.3,w:i-.2,h:.4,fontSize:n.fonts.sizes.body,fontFace:n.fonts.heading,color:n.colors.text.replace("#",""),align:"center",bold:!0,fit:$t}),e.addText(s.role,{x:u,y:3.7,w:i-.2,h:.3,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:"center",fit:$t})})}function _En(e,t,r,n){if(Bs(e,t,n),r.bullets){const o=r.bullets.map(i=>({...i,icon:i.icon||"2713"}));nmr(e,o,Vt.contentFull,n,"conclusion")}r.cta&&e.addText(r.cta,{x:.5,y:4.6,w:9,h:.5,fontSize:n.fonts.sizes.heading-4,fontFace:n.fonts.heading,color:n.colors.primary.replace("#",""),align:"center",bold:!0,fit:$t})}function p_(e,t,r,n,o=!1){e.addShape("roundRect",{x:t.x,y:t.y,w:t.w,h:t.h,fill:{color:o?n.colors.primary.replace("#","")+"15":"F8F9FA"},line:{color:o?n.colors.primary.replace("#",""):"E5E7EB",width:1},rectRadius:.1});let i=t.y+.15,s=t.h-.3;return r&&(e.addText(r,{x:t.x+.15,y:t.y+.1,w:t.w-.3,h:.35,fontSize:14,fontFace:n.fonts.heading,color:o?n.colors.primary.replace("#",""):n.colors.text.replace("#",""),bold:!0,fit:$t}),i=t.y+.45,s=t.h-.55),{contentY:i,contentH:s}}function imr(e,t,r,n,o,i){if(!t||t.length===0)return;const s=Math.max(11,Math.min(14,16-t.length)),a=n.colors.text.replace("#","");t.forEach((u,l)=>{if(!u||!u.text)return;const c=o+l*(i/t.length);if(l_(u.text)){const d=u_(u.text),p=[{text:"\u2022 ",options:{fontSize:s,fontFace:n.fonts.body,color:a}},...c_(d,{fontSize:s,fontFace:n.fonts.body,color:a})];e.addText(p,{x:r.x+.15,y:c,w:r.w-.3,h:i/t.length,valign:"top",fit:$t})}else e.addText(`\u2022 ${u.text}`,{x:r.x+.15,y:c,w:r.w-.3,h:i/t.length,fontSize:s,fontFace:n.fonts.body,color:a,valign:"top",fit:$t})})}function Tme(e,t,r,n,o,i){e.addText(t.value,{x:r.x,y:o,w:r.w,h:i*.6,fontSize:Math.min(32,r.w*8),fontFace:n.fonts.heading,color:n.colors.primary.replace("#",""),bold:!0,align:"center",valign:"bottom",fit:$t}),e.addText(t.label,{x:r.x,y:o+i*.6,w:r.w,h:i*.4,fontSize:11,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:"center",valign:"top",fit:$t})}function smr(e){const{slide:t,icon:r,label:n,description:o,pos:i,theme:s,contentY:a,contentH:u}=e,l=Math.min(.6,i.w*.2);t.addShape("ellipse",{x:i.x+(i.w-l)/2,y:a,w:l,h:l,fill:{color:s.colors.primary.replace("#","")}});const c=parseInt(r,16);if(Number.isNaN(c)||c<0||c>1114111){f.warn("[renderIconBoxInZone] Invalid icon code",{icon:r});return}const d=String.fromCodePoint(c);t.addText(d,{x:i.x+(i.w-l)/2,y:a,w:l,h:l,fontSize:16,color:"FFFFFF",align:"center",valign:"middle",fit:$t}),t.addText(n,{x:i.x,y:a+l+.1,w:i.w,h:.3,fontSize:12,fontFace:s.fonts.heading,color:s.colors.text.replace("#",""),bold:!0,align:"center",fit:$t}),o&&t.addText(o,{x:i.x+.1,y:a+l+.4,w:i.w-.2,h:u-l-.5,fontSize:10,fontFace:s.fonts.body,color:s.colors.muted.replace("#",""),align:"center",fit:$t})}function amr(e,t,r,n,o,i){const s=t.type==="pie"?"pie":t.type==="line"?"line":"bar",a=t.series||[];if(a.length===0)return;const u=a.map(l=>({name:l.name||"Data",labels:l.labels||[],values:l.values||[]}));try{e.addChart(s,u,{x:r.x+.1,y:o,w:r.w-.2,h:i,showLegend:!1,showTitle:!1,chartColors:[n.colors.primary.replace("#",""),n.colors.secondary.replace("#",""),n.colors.accent.replace("#",""),n.colors.muted.replace("#","")]})}catch{e.addText("Chart",{x:r.x,y:o,w:r.w,h:i,fontSize:14,color:n.colors.muted.replace("#",""),align:"center",valign:"middle",fit:$t})}}function EEn(e,t,r,n){Bs(e,t,n,!1);const o=ia[r.layout]||ia["left-right"];(r.zones||[]).forEach((s,a)=>{if(a>=o.length)return;const u=o[a],{contentY:l,contentH:c}=p_(e,u,s.title,n,s.isPrimary);switch(s.type){case"bullets":Array.isArray(s.data)&&imr(e,s.data,u,n,l,c);break;case"stats":s.data&&typeof s.data=="object"&&Tme(e,s.data,u,n,l,c);break;case"icon-box":if(s.data&&typeof s.data=="object"){const d=s.data;smr({slide:e,icon:d.icon,label:d.label,description:d.description,pos:u,theme:n,contentY:l,contentH:c})}break;case"chart":s.data&&typeof s.data=="object"&&amr(e,s.data,u,n,l,c);break;case"text-box":typeof s.data=="string"&&e.addText(s.data,{x:u.x+.15,y:l,w:u.w-.3,h:c,fontSize:12,fontFace:n.fonts.body,color:n.colors.text.replace("#",""),valign:"top"});break}})}function SEn(e,t,r,n){if(Bs(e,t,n,!1),r.bullets&&r.bullets.length>0){const o=ia["left-right"][0],{contentY:i,contentH:s}=p_(e,o,r.leftColumn?.title,n,!0);imr(e,r.bullets,o,n,i,s)}if(r.chartData){const o=ia["left-right"][1],{contentY:i,contentH:s}=p_(e,o,"Data",n,!1);amr(e,r.chartData,o,n,i,s)}else if(r.statistics&&r.statistics.length>0){const o=ia["left-right"][1];p_(e,o,"Metrics",n,!1);const i=r.statistics.slice(0,3),s=o.h/i.length;i.forEach((a,u)=>{Tme(e,a,{...o,y:o.y+u*s,h:s},n,o.y+u*s+.1,s-.2)})}}function kEn(e,t,r,n){Bs(e,t,n,!1);const o=r.statistics||[];if(o.length===0)return;let i;o.length<=2?i=ia["left-right"]:o.length<=3?i=ia["three-cols"]:o.length<=4?i=ia.quadrants:o.length<=5?i=ia["five-boxes"]:i=ia["six-boxes"],o.slice(0,i.length).forEach((s,a)=>{const u=i[a],l=a===0,{contentY:c,contentH:d}=p_(e,u,void 0,n,l);Tme(e,s,u,n,c,d)})}function AEn(e,t,r,n){Bs(e,t,n,!1);const o=r.icons||r.features||[];if(o.length===0)return;let i;o.length<=2?i=ia["left-right"]:o.length<=3?i=ia["three-cols"]:o.length<=4?i=ia.quadrants:o.length<=5?i=ia["five-boxes"]:i=ia["six-boxes"],o.slice(0,i.length).forEach((s,a)=>{const u=i[a],l=a===0,{contentY:c,contentH:d}=p_(e,u,void 0,n,l),p=s.icon||"1F4A1",m=s.title||s.label||"",h=s.description;smr({slide:e,icon:p,label:m,description:h,pos:u,theme:n,contentY:c,contentH:d})})}var m_,$t,Vt,umr,ia,xEn=S({"src/lib/features/ppt/slideRenderers.ts"(){"use strict";z(),a_(),vme(),m_=.1,$t="shrink",Vt={margin:{x:.5,y:.4},title:{x:.5,y:.4,w:9,h:.8},subtitle:{x:.5,y:1.4,w:9,h:.5},content:{x:.5,y:1.4,w:9,h:3.8},contentFull:{x:.5,y:1.4,w:9,h:3.8},contentLeft:{x:.5,y:1.4,w:4.2,h:3.8},contentRight:{x:5.3,y:1.4,w:4.2,h:3.8},imageRight:{x:5.3,y:1.4,w:4.2,h:3.8},imageLeft:{x:.5,y:1.4,w:4.2,h:3.8},imageFull:{x:0,y:0,w:10,h:5.625},imageCentered:{x:2,y:1.2,w:6,h:3.6},columnLeft:{x:.5,y:1.4,w:4.2,h:3.8},columnRight:{x:5.3,y:1.4,w:4.2,h:3.8},col1:{x:.5,y:1.4,w:2.8,h:3.8},col2:{x:3.5,y:1.4,w:2.8,h:3.8},col3:{x:6.5,y:1.4,w:2.8,h:3.8},chart:{x:.5,y:1.4,w:9,h:3.8},statRow:{y:2.2,h:2.5},footer:{x:.5,y:5.2,w:9,h:.3},logo:{"top-left":{x:.3,y:.2},"top-right":{x:8.5,y:.2},"bottom-left":{x:.3,y:5},"bottom-right":{x:8.5,y:5}},quote:{x:1,y:1.5,w:8,h:2.5},quoteAuthor:{x:1,y:4.2,w:8,h:.5}},umr={top:"t",bottom:"b",left:"l",right:"r"},ia={"left-right":[{x:.5,y:1.4,w:4.3,h:3.6},{x:5.2,y:1.4,w:4.3,h:3.6}],"top-bottom":[{x:.5,y:1.2,w:9,h:1.8},{x:.5,y:3.2,w:9,h:2}],"three-cols":[{x:.5,y:1.4,w:2.8,h:3.6},{x:3.5,y:1.4,w:2.8,h:3.6},{x:6.5,y:1.4,w:2.8,h:3.6}],quadrants:[{x:.5,y:1.2,w:4.3,h:1.8},{x:5.2,y:1.2,w:4.3,h:1.8},{x:.5,y:3.2,w:4.3,h:1.8},{x:5.2,y:3.2,w:4.3,h:1.8}],"five-boxes":[{x:.5,y:1.2,w:4.3,h:1.6},{x:5.2,y:1.2,w:4.3,h:1.6},{x:.5,y:3,w:2.8,h:2},{x:3.5,y:3,w:2.8,h:2},{x:6.5,y:3,w:2.8,h:2}],"six-boxes":[{x:.5,y:1.2,w:2.8,h:1.6},{x:3.5,y:1.2,w:2.8,h:1.6},{x:6.5,y:1.2,w:2.8,h:1.6},{x:.5,y:3,w:2.8,h:1.8},{x:3.5,y:3,w:2.8,h:1.8},{x:6.5,y:3,w:2.8,h:1.8}],"main-sidebar":[{x:.5,y:1.4,w:5.8,h:3.6},{x:6.5,y:1.4,w:3,h:3.6}],"top-three":[{x:.5,y:1.2,w:9,h:1.6},{x:.5,y:3,w:2.8,h:2},{x:3.5,y:3,w:2.8,h:2},{x:6.5,y:3,w:2.8,h:2}]}}});async function CEn(){if(xI)return xI;const t=(await Uu("pptxgenjs","PPT generation")).default;return xI=typeof t=="function"?t:t.default,xI}var xI,lmr,cmr=S({async"src/lib/features/ppt/slideGenerator.ts"(){"use strict";Tx(),vn(),lt(),a_(),z(),Dd(),et(),ro(),xEn(),xI=null,lmr=class{theme;config;neurolink;imageLimit;userImageIndex=0;constructor(e){this.config=e,this.theme=typeof e.theme=="string"?wpr(e.theme):e.theme,this.neurolink=e.neurolink||null,this.imageLimit=y0(hme)}getNextUserImage(){const e=this.config.userImages;if(!e||e.length===0)return;const t=e[this.userImageIndex%e.length];return this.userImageIndex++,t}async loadUserImage(e){try{if(Buffer.isBuffer(e))return e;if(e.startsWith("http://")||e.startsWith("https://")){const n=await Ge(fetch(e),15e3,ve.toolTimeout("userImageFetch",15e3));if(!n.ok){f.warn(`[SlideGenerator] Failed to fetch user image: ${e}`);return}return Buffer.from(await n.arrayBuffer())}return await(await Promise.resolve().then(()=>(_i(),f0))).readFile(e)}catch(r){f.warn("[SlideGenerator] Failed to load user image",{error:r instanceof Error?r.message:String(r)});return}}async generateSlide(e){const t=Ce.createSpan("ppt.generation","ppt.generateSlide",{"ppt.operation":"generateSlide","ppt.slideIndex":e.slideNumber,"ppt.theme":this.theme.name}),r=Date.now();try{let n,o;if(WF(e.type)){const a=this.getNextUserImage();if(a&&(f.info(`[SlideGenerator] \u{1F4F7} Using user-provided image for slide ${e.slideNumber}: "${e.title}"`),n=await this.loadUserImage(a),n&&(o={prompt:"User-provided image",model:"user-upload",generatedAt:new Date})),!n&&this.config.generateAIImages&&e.imagePrompt){f.info(`[SlideGenerator] \u23F3 Generating AI image for slide ${e.slideNumber}: "${e.title}"...`);const u=await this.generateImage(e.imagePrompt,e.type);u&&(n=u.buffer,o={prompt:e.imagePrompt,model:u.model,generatedAt:new Date})}}const i=Date.now()-r;f.debug(`[SlideGenerator] Generated slide ${e.slideNumber} (${e.type})`,{hasImage:!!n,generationTime:i});const s=Ce.endSpan(t,1);return nt().recordSpan(s),{slideNumber:e.slideNumber,schema:e,imageBuffer:n,imageMetadata:o,generationTime:i}}catch(n){const o=Ce.endSpan(t,2);o.statusMessage=n instanceof Error?n.message:String(n),nt().recordSpan(o);const i=n instanceof Me?n:ve.toolExecutionFailed("slideGenerator",n instanceof Error?n:new Error(String(n)));return f.error(`[SlideGenerator] Failed to generate slide ${e.slideNumber}`,{error:i.message,type:e.type}),{slideNumber:e.slideNumber,schema:e,generationTime:Date.now()-r}}}async generateSlides(e){const t=Date.now(),r=this.config.generateAIImages?e.filter(l=>l.imagePrompt&&WF(l.type)).length:0,n=this.config.userImages?.length??0;f.info(`[SlideGenerator] Generating ${e.length} slides...`,{theme:this.theme.name,generateAIImages:this.config.generateAIImages,slidesNeedingAIImages:r,userImagesProvided:n}),this.userImageIndex=0;const o=e.map(l=>this.imageLimit(()=>this.generateSlide(l))),i=await Promise.all(o),s=i.filter(l=>l.imageBuffer).length,a=this.config.generateAIImages?e.filter(l=>l.imagePrompt&&WF(l.type)&&!i.find(c=>c.slideNumber===l.slideNumber)?.imageBuffer).length:0,u=Date.now()-t;return f.info("[SlideGenerator] Slide generation complete",{totalSlides:i.length,totalImages:s,failedImages:a,generationTime:u}),{slides:i,totalImages:s,failedImages:a,generationTime:u}}renderSlide(e,t,r,n){const{schema:o,imageBuffer:i}=t,s=e.addSlide();return this.applyBackground(s,o.type),this.applyLayout(s,o,i),o.type!=="title"&&o.type!=="thank-you"&&this.addSlideNumber(s,r,n),this.addLogo(s,o.type),o.speakerNotes&&s.addNotes(o.speakerNotes),s}async generateImage(e,t){if(!this.neurolink)return f.warn("[SlideGenerator] No NeuroLink instance provided, skipping image generation"),null;try{const r=_pr(e,this.theme.name);f.debug(`[SlideGenerator] Generating image for ${t}`,{promptPreview:r.substring(0,100)});const n=await Ge(this.neurolink.generate({input:{text:r},provider:this.config.provider||"vertex",model:this.config.imageModel||"gemini-2.5-flash-image"}),QF,ve.toolTimeout("imageGeneration",QF));if(!n||!n.imageOutput?.base64)return f.warn(`[SlideGenerator] No image data returned for ${t}`),null;const o=Buffer.from(n.imageOutput.base64,"base64");return o.length<100?(f.warn(`[SlideGenerator] Image buffer too small (${o.length} bytes) for ${t}`),null):(o[0]===255&&o[1]===216&&o[2]===255||o[0]===137&&o[1]===80&&o[2]===78&&o[3]===71||o[0]===71&&o[1]===73&&o[2]===70||o[0]===82&&o[1]===73&&o[2]===70&&o[3]===70||f.warn(`[SlideGenerator] Unknown image format for ${t}, magic bytes: ${o.slice(0,4).toString("hex")}`),f.debug(`[SlideGenerator] Image generated successfully for ${t}`,{size:o.length,format:o[0]===255?"JPEG":o[0]===137?"PNG":o[0]===71?"GIF":"unknown"}),{buffer:o,model:n.model||this.config.imageModel})}catch(r){const n=r instanceof Me?r:ve.toolExecutionFailed("imageGeneration",r instanceof Error?r:new Error(String(r)));return f.error("[SlideGenerator] Image generation failed",{error:n.message,slideType:t}),null}}applyBackground(e,t){e.background={color:this.theme.colors.background.replace("#","")}}applyLayout(e,t,r){const{type:n,layout:o,title:i,content:s}=t;switch(n){case"title":iEn(e,i,s,this.theme,r);break;case"section-header":sEn(e,i,s,this.theme);break;case"content":case"bullets":case"agenda":case"numbered-list":bme({slide:e,title:i,content:s,layout:o,theme:this.theme,imageBuffer:r,slideType:n});break;case"image-focus":case"image-left":case"image-right":case"full-bleed-image":uEn(e,i,s,o,this.theme,r);break;case"two-column":case"split-content":lEn(e,i,s,o,this.theme,r);break;case"three-column":cEn(e,i,s,this.theme);break;case"quote":dEn(e,i,s,this.theme);break;case"statistics":pEn(e,i,s,this.theme);break;case"chart-bar":case"chart-line":case"chart-pie":case"chart-area":mEn(e,i,s,n,this.theme);break;case"table":hEn(e,i,s,this.theme);break;case"timeline":fEn(e,i,s,this.theme);break;case"process-flow":vEn(e,i,s,this.theme);break;case"comparison":wEn(e,i,s,this.theme);break;case"features":case"icons":bEn(e,i,s,this.theme);break;case"team":TEn(e,i,s,this.theme);break;case"conclusion":_En(e,i,s,this.theme);break;case"thank-you":case"closing":aEn(e,i,s,this.theme,r);break;case"dashboard":s.dashboard&&EEn(e,i,s.dashboard,this.theme);break;case"mixed-content":SEn(e,i,s,this.theme);break;case"stats-grid":kEn(e,i,s,this.theme);break;case"icon-grid":AEn(e,i,s,this.theme);break;case"blank":break;default:bme({slide:e,title:i,content:s,layout:o,theme:this.theme,imageBuffer:r,slideType:n})}}getLogoConfig(){return this.config.logo?Buffer.isBuffer(this.config.logo)||typeof this.config.logo=="string"?{data:this.config.logo,position:"bottom-right",width:1,height:.4,showOn:"all-slides"}:{data:this.config.logo.data,position:this.config.logo.position||"bottom-right",width:this.config.logo.width||1,height:this.config.logo.height||.4,showOn:this.config.logo.showOn||"all-slides"}:null}getLogoDataUri(e){if(Buffer.isBuffer(e))return`data:image/png;base64,${e.toString("base64")}`;if(e.startsWith("data:"))return e;if(e.includes("/")||e.includes("\\")||e.endsWith(".png")||e.endsWith(".jpg")||e.endsWith(".jpeg")||e.endsWith(".svg"))try{if(ks(e)){const t=kp(e),r=e.split(".").pop()?.toLowerCase();return`data:${r==="svg"?"image/svg+xml":r==="jpg"||r==="jpeg"?"image/jpeg":"image/png"};base64,${t.toString("base64")}`}}catch{f.warn("[SlideGenerator] Could not read logo file, treating as base64")}return`data:image/png;base64,${e}`}addLogo(e,t){const r=this.getLogoConfig();if(!r)return;const n=r.showOn||"all-slides";if(n==="title-only"&&t!=="title"||n==="title-and-closing"&&t!=="title"&&t!=="thank-you"&&t!=="closing")return;const o=this.getLogoDataUri(r.data),i=r.position||"bottom-right",s=r.width||1,a=r.height||.4;let u,l;const c=Vt.logo;if(i==="title-only"?(u=c["bottom-right"].x,l=c["bottom-right"].y):(u=c[i].x,l=c[i].y),i==="top-right"||i==="bottom-right"){const{width:d}=B2[this.config.aspectRatio];u=d-s-.3}if(i==="bottom-left"||i==="bottom-right"){const{height:d}=B2[this.config.aspectRatio];l=d-a-.2}e.addImage({data:o,x:u,y:l,w:s,h:a,sizing:{type:"contain",w:s,h:a}})}addSlideNumber(e,t,r){e.addText(`${t} / ${r}`,{x:Vt.footer.x,y:Vt.footer.y,w:Vt.footer.w,h:Vt.footer.h,fontSize:this.theme.fonts.sizes.caption,fontFace:this.theme.fonts.body,color:this.theme.colors.muted.replace("#",""),align:"right"})}}}});function IEn(e){const t=e.trim();for(const{patterns:r,slideType:n,bulletStyle:o}of pmr)for(const i of r)if(i.test(t))return{slideType:n,bulletStyle:o};return{slideType:null,bulletStyle:null}}function REn(e){if(!e||e.length===0)return null;for(const t of e)for(const{pattern:r,bulletStyle:n}of mmr)if(r.test(t.text))return n;return null}function dmr(e){switch(e){case"agenda":case"numbered-list":return"number";case"conclusion":case"closing":case"thank-you":return"checkmark";case"comparison":return"arrow";case"features":case"icons":case"quote":case"statistics":case"title":case"section-header":return"none";default:return"disc"}}function MEn(e,t,r){const{slideType:n,bulletStyle:o}=IEn(e);if(n)return{type:n,bulletStyle:o||dmr(n),wasInferred:!0};const i=r.bullets?REn(r.bullets):null;return i?{type:t,bulletStyle:i,wasInferred:!0}:{type:t,bulletStyle:dmr(t),wasInferred:!1}}function PEn(e,t){return(e.bullets?.length??0)>0||(e.leftColumn?.bullets?.length??0)>0||(e.rightColumn?.bullets?.length??0)>0||(e.centerColumn?.bullets?.length??0)>0?{...e,bullets:e.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||t})),leftColumn:e.leftColumn?{...e.leftColumn,bullets:e.leftColumn.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||t}))}:void 0,rightColumn:e.rightColumn?{...e.rightColumn,bullets:e.rightColumn.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||t}))}:void 0,centerColumn:e.centerColumn?{...e.centerColumn,bullets:e.centerColumn.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||t}))}:void 0}:e}var pmr,mmr,DEn=S({"src/lib/features/ppt/slideTypeInference.ts"(){"use strict";pmr=[{patterns:[/\bagenda\b/i,/\btable\s+of\s+contents\b/i,/\boutline\b/i,/\boverview\b/i,/\bwhat\s+we('ll)?\s+cover\b/i,/\btoday('s)?\s+topics?\b/i,/\bsession\s+outline\b/i],slideType:"agenda",bulletStyle:"number"},{patterns:[/\bconclusion\b/i,/\bsummary\b/i,/\bkey\s+takeaways?\b/i,/\btakeaways?\b/i,/\brecap\b/i,/\bin\s+summary\b/i,/\bwhat\s+we('ve)?\s+learned\b/i,/\bmain\s+points?\b/i,/\bkey\s+points?\b/i,/\bhighlights?\b/i,/\bachievements?\b/i,/\baccomplishments?\b/i],slideType:"conclusion",bulletStyle:"checkmark"},{patterns:[/\bthank\s+you\b/i,/\bthanks?\b/i,/\bquestions?\b\??/i,/\bq\s*&\s*a\b/i,/\bcontact(\s+us)?\b/i,/\bnext\s+steps?\b/i,/\baction\s+items?\b/i,/\blet('s)?\s+connect\b/i,/\bget\s+(in\s+)?touch\b/i],slideType:"closing",bulletStyle:"checkmark"},{patterns:[/\bcomparison\b/i,/\bcompare\b/i,/\bvs\.?\b/i,/\bversus\b/i,/\bbefore\s+(and|&|vs\.?)\s+after\b/i,/\bpros?\s+(and|&|vs\.?)\s+cons?\b/i,/\badvantages?\s+(and|&|vs\.?)\s+disadvantages?\b/i,/\bbenefits?\s+(and|&|vs\.?)\s+risks?\b/i,/\bold\s+vs\.?\s+new\b/i],slideType:"comparison",bulletStyle:"arrow"},{patterns:[/\bprocess\b/i,/\bsteps?\b/i,/\bstep[\s-]+by[\s-]+step\b/i,/\bhow\s+to\b/i,/\bworkflow\b/i,/\bprocedure\b/i,/\bmethodology\b/i,/\d+\s+steps?\s+to\b/i,/\bimplementation\s+steps?\b/i,/\bgetting\s+started\b/i],slideType:"numbered-list",bulletStyle:"number"},{patterns:[/\bfeatures?\b/i,/\bcapabilities?\b/i,/\bwhat\s+(we|it)\s+offers?\b/i,/\bour\s+offerings?\b/i],slideType:"features",bulletStyle:"disc"},{patterns:[/\bbenefits?\b/i,/\badvantages?\b/i,/\bwhy\s+choose\b/i,/\breasons?\s+to\b/i,/\bvalue\s+proposition\b/i],slideType:"content",bulletStyle:"checkmark"},{patterns:[/\bgoals?\b/i,/\bobjectives?\b/i,/\btargets?\b/i,/\baims?\b/i,/\bour\s+mission\b/i,/\bwhat\s+we\s+aim\s+for\b/i],slideType:"content",bulletStyle:"checkmark"},{patterns:[/\bchallenges?\b/i,/\brisks?\b/i,/\bobstacles?\b/i,/\bbarriers?\b/i,/\bconcerns?\b/i,/\bissues?\b/i,/\bproblems?\b/i],slideType:"content",bulletStyle:"arrow"},{patterns:[/\brequirements?\b/i,/\bchecklist\b/i,/\bprerequisites?\b/i,/\bwhat\s+you\s+need\b/i,/\bmust\s+haves?\b/i,/\bessentials?\b/i],slideType:"content",bulletStyle:"checkmark"}],mmr=[{pattern:/^\d+[.)]\s+/m,bulletStyle:"number"},{pattern:/^step\s+\d+/im,bulletStyle:"number"},{pattern:/^[✓✔☑]\s*/m,bulletStyle:"checkmark"},{pattern:/^\[x\]\s*/im,bulletStyle:"checkmark"},{pattern:/^done:/im,bulletStyle:"checkmark"},{pattern:/^completed:/im,bulletStyle:"checkmark"},{pattern:/^[→➜➡]\s*/m,bulletStyle:"arrow"},{pattern:/^->\s*/m,bulletStyle:"arrow"},{pattern:/^=>\s*/m,bulletStyle:"arrow"}]}});function OEn(e,t="content"){return typeof e=="string"&&hmr.has(e)?e:(f.warn(`[ContentPlanner] Invalid slide type "${e}", using "${t}"`),t)}function NEn(e,t){if(typeof e=="string"&&fmr.has(e))return e;const n=KF[t]?.[0]||"title-content";return f.warn(`[ContentPlanner] Invalid layout "${e}" for type "${t}", using "${n}"`),n}function LEn(e){if(e&&typeof e=="object"&&"text"in e){const t=e,r={text:String(t.text||"")};return Array.isArray(t.subBullets)&&(r.subBullets=t.subBullets.map(n=>String(n))),typeof t.icon=="string"&&(r.icon=t.icon),typeof t.emphasis=="boolean"&&(r.emphasis=t.emphasis),typeof t.fontSize=="number"&&t.fontSize>=8&&t.fontSize<=48&&(r.fontSize=t.fontSize),typeof t.bulletStyle=="string"&&gmr.has(t.bulletStyle)&&(r.bulletStyle=t.bulletStyle),typeof t.color=="string"&&t.color.match(/^#?[0-9A-Fa-f]{6}$/)&&(r.color=t.color.startsWith("#")?t.color:`#${t.color}`),typeof t.bold=="boolean"&&(r.bold=t.bold),r.text?r:null}return typeof e=="string"&&e.trim()?{text:e.trim()}:null}function e5(e){if(!Array.isArray(e))return[];const t=[];for(const r of e){const n=LEn(r);n&&t.push(n)}return t}function $En(e){if(!e||typeof e!="object")return{};const t=e,r={};if(t.bullets&&(r.bullets=e5(t.bullets)),t.leftColumn&&typeof t.leftColumn=="object"){const o=t.leftColumn;r.leftColumn={title:typeof o.title=="string"?o.title:void 0,bullets:o.bullets?e5(o.bullets):void 0,image:typeof o.image=="string"?o.image:void 0}}if(t.rightColumn&&typeof t.rightColumn=="object"){const o=t.rightColumn;r.rightColumn={title:typeof o.title=="string"?o.title:void 0,bullets:o.bullets?e5(o.bullets):void 0,image:typeof o.image=="string"?o.image:void 0}}if(t.centerColumn&&typeof t.centerColumn=="object"){const o=t.centerColumn;r.centerColumn={title:typeof o.title=="string"?o.title:void 0,bullets:o.bullets?e5(o.bullets):void 0,image:typeof o.image=="string"?o.image:void 0}}const n=["subtitle","body","sectionNumber","quote","quoteAuthor","quoteAuthorTitle","caption","galleryImages","statistics","chartData","tableData","timeline","processSteps","features","icons","teamMembers","comparison","nextSteps","cta","ctaButton","contactInfo","layoutOptions","dashboard"];for(const o of n)t[o]!==void 0&&(r[o]=t[o]);return r}function FEn(e,t){if(!e||typeof e!="object")throw new Ku("AI returned invalid response: expected object",Rc.INVALID_AI_RESPONSE,{received:typeof e});const r=e;if(typeof r.title!="string"||!r.title.trim())throw new Ku("AI response missing valid 'title' field",Rc.INVALID_AI_RESPONSE,{field:"title",received:r.title});if(!Array.isArray(r.slides))throw new Ku("AI response missing 'slides' array",Rc.INVALID_AI_RESPONSE,{field:"slides",received:typeof r.slides});r.slides.length!==t&&f.warn(`[ContentPlanner] AI returned ${r.slides.length} slides, expected ${t}. Adjusting...`);const n=[];for(let o=0;o<r.slides.length;o++){const i=r.slides[o];if(!i||typeof i!="object")throw new Ku(`Invalid slide at index ${o}`,Rc.INVALID_AI_RESPONSE,{index:o,received:typeof i});typeof i.title!="string"&&(i.title=`Slide ${o+1}`,f.warn(`[ContentPlanner] Slide ${o+1} missing title, using default`));const s=OEn(i.type,"content"),a=$En(i.content),{type:u,bulletStyle:l,wasInferred:c}=MEn(i.title,s,a),d=c&&u!==s?u:s;c&&u!==s&&f.debug(`[ContentPlanner] Slide ${o+1} type inferred from title: "${i.title}" \u2192 ${d}`);const p=PEn(a,l),m=NEn(i.layout,d);typeof i.speakerNotes!="string"&&(i.speakerNotes=""),i.imagePrompt!==null&&typeof i.imagePrompt!="string"&&(i.imagePrompt=null),n.push({slideNumber:o+1,type:d,layout:m,title:i.title,content:p,imagePrompt:i.imagePrompt,speakerNotes:i.speakerNotes})}return{title:r.title,totalSlides:n.length,audience:r.audience||"general",tone:r.tone||"professional",theme:r.theme||"modern",slides:n,keyMessages:Array.isArray(r.keyMessages)?r.keyMessages:void 0}}function UEn(e){const t=e.trim(),r=[],n=t.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);n&&n[1]&&r.push(n[1].trim()),t.startsWith("```")&&r.push(t.replace(/^```(?:json)?\s*\n?/,"").replace(/\n?```\s*$/,""));const o=t.indexOf("{"),i=t.indexOf("["),s=o===-1?i:i===-1?o:Math.min(o,i);if(s>0){const l=t[s]==="{"?"}":"]",c=t.lastIndexOf(l);c>s&&r.push(t.slice(s,c+1))}r.push(t);const a=[];for(const u of r)try{return JSON.parse(u)}catch(l){a.push(l instanceof Error?l.message:String(l))}throw new Ku(`Failed to parse AI response as JSON: ${a[a.length-1]}`,Rc.INVALID_AI_RESPONSE,{contentPreview:e.substring(0,500),parseError:a.join(" | ")})}async function BEn(e,t){const r=Date.now(),n=`session-${Date.now()}`;f.info("[ContentPlanner] Starting content planning",{topic:e.topic.substring(0,100),pages:e.pages,audience:e.audience,tone:e.tone,theme:e.theme,generateAIImages:e.generateAIImages,provider:e.provider,model:e.model,sessionId:n});const o=Tpr({topic:e.topic,pages:e.pages,audience:e.audience,tone:e.tone,theme:e.theme,generateAIImages:e.generateAIImages,modelInfo:{name:e.model||"unknown",provider:e.provider||"auto-selected"}});try{const i=await t.generate({prompt:o,systemPrompt:pme,temperature:.7,maxTokens:8192,disableTools:!0,timeout:mme});if(!i||!i.content)throw new Ku("AI provider returned empty response",Rc.PLANNING_FAILED,{provider:e.provider});const s=Date.now()-r;f.debug("[ContentPlanner] AI response received",{contentLength:i.content.length,planningTime:s});const a=UEn(i.content),u=FEn(a,e.pages);return f.info("[ContentPlanner] Content plan generated successfully",{title:u.title,totalSlides:u.totalSlides,planningTime:s,keyMessages:u.keyMessages?.length||0}),u}catch(i){if(i instanceof Ku)throw i;const s=i instanceof Error?i.message:String(i);throw new Ku(`Content planning failed: ${s}`,Rc.PLANNING_FAILED,{topic:e.topic.substring(0,100),provider:e.provider},i instanceof Error?i:void 0)}}function zEn(e){return e.slides.length>0&&e.slides[0].type!=="title"&&(e.slides[0]={...e.slides[0],type:"title",layout:"title-centered"}),e}function GEn(e){const t=e.slides.length-1;return t>=0&&e.slides[t].type!=="thank-you"&&(e.slides[t]={...e.slides[t],type:"thank-you",layout:"contact-info"}),e}function qEn(e){let t={...e,slides:[...e.slides]};return t=zEn(t),t=GEn(t),t}var hmr,fmr,gmr,jEn=S({"src/lib/features/ppt/contentPlanner.ts"(){"use strict";fme(),a_(),DEn(),z(),hmr=new Set(["title","section-header","thank-you","closing","content","agenda","bullets","numbered-list","image-focus","image-left","image-right","full-bleed-image","gallery","two-column","three-column","split-content","table","chart-bar","chart-line","chart-pie","chart-area","statistics","quote","timeline","process-flow","comparison","features","team","icons","conclusion","blank","dashboard","mixed-content","stats-grid","icon-grid"]),fmr=new Set(["title-centered","title-bottom","title-left-aligned","title-content","title-content-footer","content-only","image-left-content-right","image-right-content-left","image-top-content-bottom","image-bottom-content-top","image-full-overlay","image-centered","image-grid-2x2","two-column-equal","two-column-wide-left","two-column-wide-right","three-column-equal","chart-full","chart-with-bullets","table-full","table-with-notes","quote-centered","quote-with-image","statistics-row","statistics-grid","timeline-horizontal","timeline-vertical","process-horizontal","process-vertical","comparison-side-by-side","comparison-table","team-grid","icon-grid","summary-bullets","contact-info","blank-full"]),gmr=new Set(["disc","number","checkmark","arrow","dash","none"])}}),ymr={};ue(ymr,{generatePresentation:()=>VEn});async function VEn(e){const t=Ce.createSpan("ppt.generation","ppt.orchestrate",{"ppt.operation":"orchestrate","ppt.slideCount":e.context.pages,"ppt.theme":typeof e.context.theme=="string"?e.context.theme:"custom"}),r={startTime:Date.now(),contentPlan:null,slides:null,outputPath:null},{context:n,provider:o,providerName:i,modelName:s,neurolink:a,imageProvider:u,imageModel:l}=e;f.info("[PresentationOrchestrator] Starting presentation generation",{topic:n.topic.substring(0,100),pages:n.pages,theme:n.theme,audience:n.audience,tone:n.tone,generateAIImages:n.generateAIImages,provider:n.provider});try{f.info("[PresentationOrchestrator] Step 1: Content planning...");const c=await Ge(BEn(n,o),Ul/2,ve.toolTimeout("contentPlanning",Ul/2));r.contentPlan=qEn(c),t.attributes["ppt.slideCount"]=r.contentPlan.totalSlides,t.attributes["ppt.theme"]=typeof r.contentPlan.theme=="string"?r.contentPlan.theme:"custom",f.info("[PresentationOrchestrator] Content plan ready",{title:r.contentPlan.title,totalSlides:r.contentPlan.totalSlides,theme:r.contentPlan.theme,audience:r.contentPlan.audience,tone:r.contentPlan.tone}),f.info("[PresentationOrchestrator] Step 2: Generating slides...");const d=n.logo??null,p=Zpr(d),h={theme:r.contentPlan.theme||n.theme,generateAIImages:n.generateAIImages,aspectRatio:n.aspectRatio,provider:u??n.provider??"vertex",imageModel:l??"gemini-2.5-flash-image",logo:p??void 0,userImages:n.images,neurolink:a},g=new lmr(h),y=await Ge(g.generateSlides(r.contentPlan.slides),Ul/2,ve.toolTimeout("slideGeneration",Ul/2));r.slides=y.slides,f.info("[PresentationOrchestrator] Slides generated",{totalSlides:r.slides.length,totalImages:y.totalImages,failedImages:y.failedImages,generationTime:y.generationTime}),f.info("[PresentationOrchestrator] Step 3: Assembling PPTX...");const v=await CEn(),w=new v;w.title=r.contentPlan.title,w.subject=`Generated presentation about: ${n.topic.substring(0,100)}`,w.author="NeuroLink PPT Generator",w.company="NeuroLink",w.layout=Qpr(n.aspectRatio);const b=[...r.slides].sort((P,D)=>P.slideNumber-D.slideNumber);for(let P=0;P<b.length;P++){const D=b[P];g.renderSlide(w,D,P+1,b.length)}f.info("[PresentationOrchestrator] PPTX assembled",{totalSlides:b.length,layout:w.layout,title:w.title}),f.info("[PresentationOrchestrator] Step 4: Writing file..."),r.outputPath=Kpr(n),await Ge(Jpr(r.outputPath),Ul/4,ve.toolTimeout("outputDirectory",Ul/4)),await Ge(w.writeFile({fileName:r.outputPath}),Ul/4,ve.toolTimeout("pptxWrite",Ul/4));let E=0;try{E=(await Ge(Co(r.outputPath),Ul/8,ve.toolTimeout("pptxStat",Ul/8))).size}catch{f.warn("[PresentationOrchestrator] Could not get file size")}const k=Date.now()-r.startTime;f.info("[PresentationOrchestrator] Presentation generation complete",{filePath:r.outputPath,fileSize:E,totalSlides:b.length,totalTime:k});const A=Ce.endSpan(t,1);nt().recordSpan(A),a?.recordMetricsSpan(A);const x=r.contentPlan?.theme||n.theme,R=r.contentPlan?.audience||n.audience,C=r.contentPlan?.tone||n.tone;return{filePath:r.outputPath,totalSlides:b.length,format:"pptx",provider:i,model:s,metadata:{theme:x,audience:R,tone:C,imageModel:n.generateAIImages?l??"gemini-2.5-flash-image":"",fileSize:E>0?E:0}}}catch(c){const d=Ce.endSpan(t,2);if(d.statusMessage=c instanceof Error?c.message:String(c),nt().recordSpan(d),a?.recordMetricsSpan(d),c instanceof Ku)throw f.error("[PresentationOrchestrator] Generation failed",{error:c.message,code:c.code,context:c.context}),c;const p=emr(c);throw f.error("[PresentationOrchestrator] Unexpected error",{error:p.message,stage:gme(r)}),new Ku(`Presentation generation failed: ${p.message}`,Rc.ASSEMBLY_FAILED,{topic:n.topic.substring(0,100),stage:gme(r),elapsedTime:Date.now()-r.startTime},p)}}var HEn=S({async"src/lib/features/ppt/presentationOrchestrator.ts"(){"use strict";await cmr(),_i(),fme(),jEn(),await cmr(),a_(),z(),et(),ro(),vme()}}),vmr={};ue(vmr,{MUSIC_ERROR_CODES:()=>er,MusicError:()=>Yt,MusicProcessor:()=>sm});var er,Yt,sm,am=S({"src/lib/utils/musicProcessor.ts"(){"use strict";ro(),et(),z(),lb(),er={PROVIDER_NOT_SUPPORTED:"MUSIC_PROVIDER_NOT_SUPPORTED",PROVIDER_NOT_CONFIGURED:"MUSIC_PROVIDER_NOT_CONFIGURED",GENERATION_FAILED:"MUSIC_GENERATION_FAILED",POLL_TIMEOUT:"MUSIC_POLL_TIMEOUT",PROMPT_REQUIRED:"MUSIC_PROMPT_REQUIRED",DURATION_INVALID:"MUSIC_DURATION_INVALID",INVALID_INPUT:"MUSIC_INVALID_INPUT"},Yt=class extends Me{constructor(e){super({code:e.code,message:e.message,category:e.category??"execution",severity:e.severity??"high",retriable:e.retriable??!1,context:e.context,originalError:e.originalError}),this.name="MusicError"}},sm=class{static registry=new d0("MusicProcessor");static registerHandler(e,t){const r=e&&e.toLowerCase();this.registry.register(e,t),f.debug(`[MusicProcessor] Registered music handler: ${r}`)}static supports(e){return this.registry.supports(e)}static listProviders(){return this.registry.list()}static getHandler(e){return this.registry.get(e)}static clearHandlers(){this.registry.clear()}static buildSpanAttributes(e,t){return{"music.operation":"generate","music.provider":e,"music.duration":t.duration,"music.format":t.format,"music.genre":t.genre,"music.mood":t.mood}}static async generate(e,t){const r=Ce.createSpan("media.generation","music.generate",this.buildSpanAttributes(e,t));try{const n=t.prompt?.trim();if(!n)throw new Yt({code:er.PROMPT_REQUIRED,message:"Music generation requires a non-empty prompt",category:"validation",severity:"low",retriable:!1,context:{provider:e}});const o=this.getHandler(e);if(!o)throw new Yt({code:er.PROVIDER_NOT_SUPPORTED,message:`Music provider "${e}" is not registered. Available: ${this.listProviders().join(", ")}`,category:"configuration",severity:"high",retriable:!1,context:{provider:e,available:this.listProviders()}});if(!o.isConfigured())throw new Yt({code:er.PROVIDER_NOT_CONFIGURED,message:`Music provider "${e}" is not configured. Set the required credentials.`,category:"configuration",severity:"high",retriable:!1,context:{provider:e}});if(t.duration!==void 0&&o.maxDurationSeconds!==void 0&&t.duration>o.maxDurationSeconds)throw new Yt({code:er.DURATION_INVALID,message:`Requested duration (${t.duration}s) exceeds provider maximum (${o.maxDurationSeconds}s) for "${e}"`,category:"validation",severity:"medium",retriable:!1,context:{provider:e,requested:t.duration,maximum:o.maxDurationSeconds}});f.debug(`[MusicProcessor] Starting music generation with provider: ${e}`);const i=await o.generate({...t,prompt:n}),s=Ce.endSpan(r,1);return nt().recordSpan(s),f.info(`[MusicProcessor] Generated ${i.size} bytes (${e})`),i}catch(n){const o=Ce.endSpan(r,2,n instanceof Error?n.message:String(n));if(nt().recordSpan(o),n instanceof Yt)throw n;const i=n instanceof Error?n.message:String(n);throw new Yt({code:er.GENERATION_FAILED,message:`Music generation failed for provider "${e}": ${i}`,category:"execution",severity:"high",retriable:!0,context:{provider:e,duration:t.duration,format:t.format,genre:t.genre,mood:t.mood,tempo:t.tempo},originalError:n instanceof Error?n:void 0})}}}}}),wmr,Fy,bmr,Tmr,h_,_mr=S({"src/lib/music/providers/BeatovenMusic.ts"(){"use strict";z(),am(),Ma(),_I(),wmr="https://public-api.beatoven.ai",Fy=3e4,bmr=3e3,Tmr=5*6e4,h_=class{maxDurationSeconds=300;supportedFormats=["mp3","wav"];supportedGenres=["ambient","cinematic","corporate","lo-fi","rock","pop","electronic","orchestral","folk"];apiKey;baseUrl;constructor(e){const t=(e??process.env.BEATOVEN_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.BEATOVEN_BASE_URL??wmr).replace(/\/$/,"")}isConfigured(){return this.apiKey!==null}async generate(e){if(!this.apiKey)throw new Yt({code:er.PROVIDER_NOT_CONFIGURED,message:"BEATOVEN_API_KEY not configured",category:"configuration",severity:"high",retriable:!1});const t=Date.now(),r=e.format??"mp3";this.supportedFormats.includes(r)||f.warn(`[BeatovenMusic] Format "${r}" not supported \u2014 falling back to "mp3"`);const n=this.supportedFormats.includes(r)?r:"mp3",i=(await this.submitCompose(e,n)).task_id,s=await this.pollUntilComposed(i,e.timeout??Tmr),a=s.meta?.track_url;if(!a)throw new Yt({code:er.GENERATION_FAILED,message:`Beatoven task ${i} completed but no track_url returned`,category:"execution",severity:"high",retriable:!1,context:{taskId:i,taskResult:s}});const u=await this.downloadTrack(a),l=Date.now()-t;return f.info(`[BeatovenMusic] Generated ${u.length} bytes (${n}) in ${l}ms \u2014 task ${i}`),{buffer:u,format:n,size:u.length,duration:s.meta?.duration,provider:"beatoven",metadata:{latency:l,provider:"beatoven",model:"beatoven-default",jobId:i,trackId:s.meta?.track_id,projectId:s.meta?.project_id,requestedFormat:e.format}}}async submitCompose(e,t){const r=(e.duration??60)*1e3,n=[e.prompt];e.genre&&n.push(`Genre: ${e.genre}`),e.mood&&n.push(`Mood: ${e.mood}`),e.tempo!==void 0&&n.push(`Tempo: ${e.tempo} BPM`);const o={prompt:{text:n.join(". ")},duration:r,format:t},i=new AbortController,s=setTimeout(()=>i.abort(),Fy);let a;try{a=await fetch(`${this.baseUrl}/api/v1/tracks/compose`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(o),signal:i.signal})}catch(l){throw l instanceof Error&&l.name==="AbortError"?new Yt({code:er.GENERATION_FAILED,message:`Beatoven compose request timed out after ${Fy/1e3}s`,category:"network",severity:"high",retriable:!0,originalError:l}):new Yt({code:er.GENERATION_FAILED,message:`Beatoven compose network error: ${l instanceof Error?l.message:String(l)}`,category:"network",severity:"high",retriable:!0,originalError:l instanceof Error?l:void 0})}finally{clearTimeout(s)}if(!a.ok){const l=await a.text(),c=a.status===408||a.status===429||a.status>=500;throw new Yt({code:er.GENERATION_FAILED,message:`Beatoven compose failed: ${a.status} \u2014 ${l}`,category:c?"network":"execution",severity:"high",retriable:c,context:{status:a.status,body:l}})}const u=await a.json();if(!u.task_id)throw new Yt({code:er.GENERATION_FAILED,message:"Beatoven compose response missing task_id",category:"execution",severity:"high",retriable:!1,context:{response:u}});return u}async pollUntilComposed(e,t){const r=Date.now();for(;Date.now()-r<t;){const n=await this.fetchTaskStatus(e);if(n.status==="composed")return n;if(n.status==="failed")throw new Yt({code:er.GENERATION_FAILED,message:`Beatoven task ${e} failed: ${n.message??"unknown"}`,category:"execution",severity:"high",retriable:!1,context:{taskId:e,status:n}});await new Promise(o=>setTimeout(o,bmr))}throw new Yt({code:er.POLL_TIMEOUT,message:`Beatoven task ${e} did not complete within ${Math.round(t/1e3)}s`,category:"timeout",severity:"medium",retriable:!0,context:{taskId:e,totalTimeoutMs:t}})}async fetchTaskStatus(e){const t=new AbortController,r=setTimeout(()=>t.abort(),Fy);let n;try{n=await fetch(`${this.baseUrl}/api/v1/tasks/${e}`,{method:"GET",headers:{Authorization:`Bearer ${this.apiKey}`},signal:t.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?new Yt({code:er.GENERATION_FAILED,message:`Beatoven status poll timed out after ${Fy/1e3}s`,category:"network",severity:"medium",retriable:!0,originalError:o}):new Yt({code:er.GENERATION_FAILED,message:`Beatoven status poll network error: ${o instanceof Error?o.message:String(o)}`,category:"network",severity:"medium",retriable:!0,originalError:o instanceof Error?o:void 0,context:{taskId:e}})}finally{clearTimeout(r)}if(!n.ok){const o=await n.text();throw new Yt({code:er.GENERATION_FAILED,message:`Beatoven status request failed: ${n.status} \u2014 ${o}`,category:"execution",severity:"medium",retriable:n.status>=500,context:{status:n.status,taskId:e}})}return await n.json()}async downloadTrack(e){try{await TI(e)}catch(o){throw new Yt({code:er.GENERATION_FAILED,message:`Beatoven track URL rejected: ${o instanceof Error?o.message:String(o)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}const t=new AbortController,r=setTimeout(()=>t.abort(),Fy);let n;try{n=await fetch(e,{signal:t.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?new Yt({code:er.GENERATION_FAILED,message:`Beatoven track download timed out after ${Fy/1e3}s`,category:"network",severity:"medium",retriable:!0,originalError:o}):new Yt({code:er.GENERATION_FAILED,message:`Beatoven track download network error: ${o instanceof Error?o.message:String(o)}`,category:"network",severity:"medium",retriable:!0,originalError:o instanceof Error?o:void 0,context:{url:e}})}finally{clearTimeout(r)}if(!n.ok)throw new Yt({code:er.GENERATION_FAILED,message:`Beatoven track download failed: ${n.status}`,category:"network",severity:"medium",retriable:n.status>=500,context:{status:n.status,url:e}});try{return await Ly(n,pf,"Beatoven track")}catch(o){throw new Yt({code:er.GENERATION_FAILED,message:`Beatoven track download exceeded size limit: ${o instanceof Error?o.message:String(o)}`,category:"execution",severity:"high",retriable:!1,context:{url:e}})}}}}}),Emr,_me,f_,Smr=S({"src/lib/music/providers/ElevenLabsMusic.ts"(){"use strict";am(),z(),Ma(),Emr="https://api.elevenlabs.io/v1",_me=6e4,f_=class{maxDurationSeconds=22;supportedFormats=["mp3"];supportedGenres=["ambient","cinematic","lo-fi","electronic","orchestral","soundscape"];apiKey;baseUrl;constructor(e){const t=(e??process.env.ELEVENLABS_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.ELEVENLABS_BASE_URL??Emr).replace(/\/$/,"")}isConfigured(){return this.apiKey!==null}async generate(e){if(!this.apiKey)throw new Yt({code:er.PROVIDER_NOT_CONFIGURED,message:"ELEVENLABS_API_KEY not configured (shared with ElevenLabs TTS \u2014 same account, different endpoint)",category:"configuration",severity:"high",retriable:!1});const t=e.prompt?.trim();if(!t)throw new Yt({code:er.INVALID_INPUT,message:"ElevenLabs Music requires a non-empty prompt",category:"validation",severity:"low",retriable:!1});const r=e.duration??8;if(r<=0||r>this.maxDurationSeconds)throw new Yt({code:er.INVALID_INPUT,message:`ElevenLabs Music duration must be between 1 and ${this.maxDurationSeconds} seconds; got ${r}`,category:"validation",severity:"low",retriable:!1,context:{requested:r,maximum:this.maxDurationSeconds}});const n=Date.now(),o=r,i={text:this.buildPrompt({...e,prompt:t}),duration_seconds:o,prompt_influence:.3},s=new AbortController,a=setTimeout(()=>s.abort(),_me);let u;try{u=await fetch(`${this.baseUrl}/sound-generation`,{method:"POST",headers:{"xi-api-key":this.apiKey,"Content-Type":"application/json",Accept:"audio/mpeg"},body:JSON.stringify(i),signal:s.signal})}catch(d){throw d instanceof Error&&d.name==="AbortError"?new Yt({code:er.GENERATION_FAILED,message:`ElevenLabs Music request timed out after ${_me/1e3}s`,category:"network",severity:"high",retriable:!0,originalError:d}):new Yt({code:er.GENERATION_FAILED,message:`ElevenLabs Music network error: ${d instanceof Error?d.message:String(d)}`,category:"network",severity:"high",retriable:!0,originalError:d instanceof Error?d:void 0})}finally{clearTimeout(a)}if(!u.ok){const d=await u.text(),p=u.status===408||u.status===429||u.status>=500;throw new Yt({code:er.GENERATION_FAILED,message:`ElevenLabs Music synthesis failed: ${u.status} \u2014 ${d}`,category:p?"network":"execution",severity:"high",retriable:p,context:{status:u.status}})}const l=await Ly(u,pf,"ElevenLabs music"),c=Date.now()-n;return f.info(`[ElevenLabsMusic] Generated ${l.length} bytes in ${c}ms`),{buffer:l,format:"mp3",size:l.length,duration:o,provider:"elevenlabs-music",metadata:{latency:c,provider:"elevenlabs-music",model:"elevenlabs-sound-v1"}}}buildPrompt(e){const t=[e.prompt];return e.genre&&t.push(`Genre: ${e.genre}`),e.mood&&t.push(`Mood: ${e.mood}`),e.tempo!==void 0&&t.push(`${e.tempo} BPM`),t.join(". ")}}}}),kmr,Amr,Eme,g_,xmr=S({"src/lib/music/providers/LyriaMusic.ts"(){"use strict";am(),z(),zt(),kmr="https://generativelanguage.googleapis.com/v1beta",Amr="lyria-3-pro-preview",Eme=12e4,g_=class{maxDurationSeconds=30;supportedFormats=["wav"];supportedGenres=["ambient","classical","electronic","jazz","rock","pop","lo-fi","cinematic","orchestral","world"];apiKey;baseUrl;model;constructor(e){const t=(e??process.env.GOOGLE_AI_LYRIA_API_KEY??process.env.GOOGLE_API_KEY??process.env.GOOGLE_AI_API_KEY??process.env.GEMINI_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.LYRIA_BASE_URL??kmr).replace(/\/$/,""),this.model=process.env.LYRIA_MODEL??Amr}isConfigured(){return this.apiKey!==null}async generate(e){if(!this.apiKey)throw new Yt({code:er.PROVIDER_NOT_CONFIGURED,message:"Lyria requires one of: GOOGLE_API_KEY, GOOGLE_AI_LYRIA_API_KEY, GOOGLE_AI_API_KEY, or GEMINI_API_KEY",category:"configuration",severity:"high",retriable:!1});const t=Date.now(),r=Math.min(e.duration??16,this.maxDurationSeconds),o={contents:[{parts:[{text:`${this.buildPrompt(e)}. Duration: ${r} seconds`}]}],generationConfig:{responseModalities:["AUDIO"]}},i=new AbortController,s=setTimeout(()=>i.abort(),Eme);let a;try{a=await fetch(`${this.baseUrl}/models/${this.model}:generateContent?key=${this.apiKey}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:i.signal})}catch(p){throw p instanceof Error&&p.name==="AbortError"?new Yt({code:er.GENERATION_FAILED,message:`Lyria request timed out after ${Eme/1e3}s`,category:"network",severity:"high",retriable:!0,originalError:p}):p}finally{clearTimeout(s)}if(!a.ok){const p=await a.text(),m=a.status===408||a.status===429||a.status>=500;throw new Yt({code:er.GENERATION_FAILED,message:`Lyria generation failed: ${a.status} \u2014 ${pr(p)}`,category:m?"network":"execution",severity:"high",retriable:m,context:{status:a.status}})}const u=await a.json(),l=u.candidates?.[0]?.content?.parts?.find(p=>p.inlineData?.mimeType?.startsWith("audio/"));if(!l?.inlineData?.data)throw new Yt({code:er.GENERATION_FAILED,message:"Lyria response missing audio data",category:"execution",severity:"high",retriable:!1,context:{response:u}});const c=Buffer.from(l.inlineData.data,"base64"),d=Date.now()-t;return f.info(`[LyriaMusic] Generated ${c.length} bytes in ${d}ms \u2014 model ${this.model}`),{buffer:c,format:"wav",size:c.length,duration:r,provider:"lyria",metadata:{latency:d,provider:"lyria",model:this.model,sampleRate:48e3}}}buildPrompt(e){const t=[e.prompt];return e.genre&&t.push(`Genre: ${e.genre}`),e.mood&&t.push(`Mood: ${e.mood}`),e.tempo!==void 0&&t.push(`${e.tempo} BPM`),t.join(". ")}}}});function hf(e){const t=(e?.apiToken??process.env.REPLICATE_API_TOKEN??"").trim();return t?{apiToken:t,baseUrl:(e?.baseUrl??process.env.REPLICATE_BASE_URL??Cmr).replace(/\/$/,"")}:null}var Cmr,t5=S({"src/lib/adapters/replicate/auth.ts"(){"use strict";Cmr="https://api.replicate.com"}});async function WEn(e,t,r){const n=e.baseUrl??"https://api.replicate.com",[o,i]=t.model.split(":",2),s=i?`${n}/v1/predictions`:`${n}/v1/models/${o}/predictions`,a=i?{version:i,input:t.input}:{input:t.input};return t.webhook&&(a.webhook=t.webhook),t.webhookEventsFilter&&t.webhookEventsFilter.length>0&&(a.webhook_events_filter=t.webhookEventsFilter),kw(async()=>{const u=new AbortController,l=setTimeout(()=>u.abort(),y_);try{const c=await fetch(s,{method:"POST",headers:{Authorization:`Token ${e.apiToken}`,"Content-Type":"application/json",Prefer:"wait=60"},body:JSON.stringify(a),signal:u.signal});if(!c.ok){const d=await c.text();throw new Me({code:He.PROVIDER_NOT_AVAILABLE,message:`Replicate predictions submit failed: ${c.status} \u2014 ${pr(d,500)}`,category:"network",severity:"high",retriable:c.status>=500||c.status===429,retryAfterMs:Sw(c.headers)})}return await c.json()}catch(c){throw c instanceof Me?c:c instanceof Error&&c.name==="AbortError"?new Me({code:He.OPERATION_ABORTED,message:`Replicate predictions submit timed out after ${y_/1e3}s`,category:"timeout",severity:"high",retriable:!0,originalError:c}):c}finally{clearTimeout(l)}},void 0,"Replicate prediction submission",r)}async function KEn(e,t,r={}){const n=e.baseUrl??"https://api.replicate.com",o=Date.now(),i=r.timeoutMs??Rmr,s=r.pollIntervalMs??Imr;for(;Date.now()-o<i;){if(r.abortSignal?.aborted)throw new Me({code:He.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1});const a=new AbortController,u=setTimeout(()=>a.abort(),y_),l=()=>a.abort();r.abortSignal?.addEventListener("abort",l,{once:!0});let c;try{c=await fetch(`${n}/v1/predictions/${t}`,{method:"GET",headers:{Authorization:`Token ${e.apiToken}`},signal:a.signal})}catch(p){throw p instanceof Me?p:p instanceof Error&&p.name==="AbortError"?r.abortSignal?.aborted?new Me({code:He.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1,originalError:p}):new Me({code:He.OPERATION_ABORTED,message:`Replicate poll request timed out after ${y_/1e3}s`,category:"timeout",severity:"high",retriable:!0,originalError:p}):p}finally{r.abortSignal?.removeEventListener("abort",l),clearTimeout(u)}if(!c.ok){const p=await c.text();throw new Me({code:He.PROVIDER_NOT_AVAILABLE,message:`Replicate poll failed: ${c.status} \u2014 ${pr(p,500)}`,category:"network",severity:"high",retriable:c.status>=500||c.status===429,retryAfterMs:Sw(c.headers)})}const d=await c.json();if(d.status==="succeeded")return d;if(d.status==="failed"||d.status==="canceled")throw new Me({code:He.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${d.id} ${d.status}: ${d.error??"unknown"}`,category:"execution",severity:"high",retriable:d.status==="failed"});await new Promise((p,m)=>{const h=()=>{clearTimeout(g),m(new Me({code:He.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1}))},g=setTimeout(()=>{r.abortSignal?.removeEventListener("abort",h),p()},s);r.abortSignal?.addEventListener("abort",h,{once:!0})})}throw new Me({code:He.OPERATION_ABORTED,message:`Replicate prediction ${t} did not complete within ${Math.round(i/1e3)}s`,category:"timeout",severity:"high",retriable:!0})}async function CI(e,t,r={}){const n=await WEn(e,t);if(n.status==="succeeded")return n;if(n.status==="failed"||n.status==="canceled")throw new Me({code:He.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${n.id} ${n.status} on submit: ${n.error??"unknown"}`,category:"execution",severity:"high",retriable:n.status==="failed"});return KEn(e,n.id,r)}async function r5(e,t=$y){const r=e.output,n=Array.isArray(r)?r[0]:r;if(typeof n!="string")throw new Me({code:He.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${e.id} output is not a URL: ${typeof r}`,category:"execution",severity:"high",retriable:!1});try{const o=await im(n,{maxBytes:t,label:`Replicate prediction ${e.id}`,timeoutMs:y_});return f.debug(`[Replicate] Downloaded prediction ${e.id} output: ${o.length} bytes`),o}catch(o){if(o instanceof Me)throw o;const i=o instanceof Error?o.message:String(o);throw new Me({code:He.PROVIDER_NOT_AVAILABLE,message:`Replicate output download failed: ${i} \u2014 ${n}`,category:"network",severity:"high",retriable:!0,originalError:o instanceof Error?o:void 0})}}var y_,Imr,Rmr,n5=S({"src/lib/adapters/replicate/predictionLifecycle.ts"(){"use strict";z(),et(),zt(),Tp(),Q2(),Wd(),Ma(),y_=9e4,Imr=2e3,Rmr=5*6e4}}),Mmr,v_,Pmr=S({"src/lib/music/providers/ReplicateMusic.ts"(){"use strict";am(),z(),t5(),n5(),Ma(),_I(),Mmr="meta/musicgen:7be0f12c54a8d033a0fbd14418c9af98962da9a86f5ff7811f9b3423a1f0b7d7",v_=class{maxDurationSeconds=30;supportedFormats=["mp3","wav"];supportedGenres=["ambient","classical","electronic","rock","jazz","hip-hop","pop","lo-fi","cinematic","orchestral"];isConfigured(){return hf()!==null}async generate(e){const t=hf();if(!t)throw new Yt({code:er.PROVIDER_NOT_CONFIGURED,message:"REPLICATE_API_TOKEN not configured",category:"configuration",severity:"high",retriable:!1});const r=Date.now(),n=e.model??Mmr,o=e.format??"mp3",i=this.supportedFormats.includes(o)?o:"mp3",s=Math.min(e.duration??8,this.maxDurationSeconds),a={prompt:this.buildPrompt(e),duration:s,output_format:i,model_version:"stereo-large",normalization_strategy:"loudness"};if(e.tempo!==void 0&&(a.bpm=e.tempo),e.referenceAudio){const d=await this.resolveBuffer(e.referenceAudio);a.input_audio=`data:audio/${this.detectAudioType(d)};base64,${d.toString("base64")}`}let u;try{u=await CI(t,{model:n,input:a})}catch(d){throw new Yt({code:er.GENERATION_FAILED,message:`Replicate music generation failed: ${d instanceof Error?d.message:String(d)}`,category:"execution",severity:"high",retriable:!0,context:{model:n,duration:s,format:i,hasReferenceAudio:e.referenceAudio!==void 0},originalError:d instanceof Error?d:void 0})}let l;try{l=await r5(u,pf)}catch(d){throw new Yt({code:er.GENERATION_FAILED,message:`Replicate music download failed: ${d instanceof Error?d.message:String(d)}`,category:"network",severity:"medium",retriable:!0,context:{predictionId:u.id},originalError:d instanceof Error?d:void 0})}const c=Date.now()-r;return f.info(`[ReplicateMusic] Generated ${l.length} bytes in ${c}ms \u2014 model ${n}`),{buffer:l,format:i,size:l.length,duration:s,provider:"replicate",metadata:{latency:c,provider:"replicate",model:n,jobId:u.id}}}buildPrompt(e){const t=[e.prompt];return e.genre&&t.push(`Genre: ${e.genre}`),e.mood&&t.push(`Mood: ${e.mood}`),e.tempo!==void 0&&t.push(`${e.tempo} BPM`),t.join(". ")}async resolveBuffer(e){if(Buffer.isBuffer(e))return e;if(!/^https:\/\//.test(e))throw new Yt({code:er.INVALID_INPUT,message:`Invalid input: expected Buffer or HTTPS URL, got string "${e}". Local file reads are not supported.`,category:"validation",severity:"high",retriable:!1});try{await TI(e)}catch(i){throw new Yt({code:er.INVALID_INPUT,message:`Unsafe URL rejected: ${i instanceof Error?i.message:String(i)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}const t=6e4,r=new AbortController,n=setTimeout(()=>r.abort(),t);let o;try{o=await fetch(e,{signal:r.signal})}catch(i){throw i instanceof Error&&i.name==="AbortError"?new Yt({code:er.GENERATION_FAILED,message:`Replicate music reference-audio fetch timed out after ${t/1e3}s: ${e}`,category:"network",severity:"medium",retriable:!0}):i}finally{clearTimeout(n)}if(!o.ok)throw new Yt({code:er.GENERATION_FAILED,message:`Failed to fetch reference audio: ${e}: ${o.status}`,category:"network",severity:"medium",retriable:o.status>=500});try{return await Ly(o,pf,"Replicate reference audio")}catch(i){throw new Yt({code:er.INVALID_INPUT,message:`Replicate reference audio too large: ${i instanceof Error?i.message:String(i)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}}detectAudioType(e){return e.length<4?"mp3":e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70?"wav":e[0]===79&&e[1]===103&&e[2]===103&&e[3]===83?"ogg":e[0]===73&&e[1]===68&&e[2]===51?"mp3":e[0]===255&&(e[1]&224)===224?"mpeg":e.length>=8&&e[4]===102&&e[5]===116&&e[6]===121&&e[7]===112?"mp4":"mp3"}}}}),Sme={};ue(Sme,{BeatovenMusic:()=>h_,BeatovenMusicHandler:()=>h_,ElevenLabsMusic:()=>f_,ElevenLabsMusicHandler:()=>f_,LyriaMusic:()=>g_,LyriaMusicHandler:()=>g_,MUSIC_ERROR_CODES:()=>er,MusicError:()=>Yt,MusicProcessor:()=>sm,ReplicateMusic:()=>v_,ReplicateMusicHandler:()=>v_,registerDefaultMusicHandlers:()=>Dmr});function Dmr(){for(const{name:e,aliases:t,factory:r}of Nmr){const n=!sm.supports(e),o=(t??[]).filter(i=>!sm.supports(i));if(!(!n&&o.length===0))try{let i;if(n||(i=sm.getHandler(e)),!i&&(i=r(),!i.isConfigured()))continue;n&&sm.registerHandler(e,i);for(const s of o)sm.registerHandler(s,i)}catch(i){f.debug(`[music] ${e} auto-registration skipped: ${i instanceof Error?i.message:String(i)}`)}}}var Omr,Nmr,kme=S({"src/lib/music/index.ts"(){"use strict";Pw(),z(),am(),am(),_mr(),Smr(),xmr(),Pmr(),_mr(),Smr(),xmr(),Pmr(),Omr={beatoven:()=>new h_,"elevenlabs-music":()=>new f_,lyria:()=>new g_,replicate:()=>new v_},Nmr=Ep.filter(e=>e.kind==="music").map(e=>{const t=Omr[e.name];if(!t)throw new Error(`[music] no handler factory for catalog entry "${e.name}"`);return{name:e.name,aliases:e.aliases,factory:t}})}}),Lmr={};ue(Lmr,{AVATAR_ERROR_CODES:()=>Ct,AvatarError:()=>At,AvatarProcessor:()=>um});var Ct,At,um,ff=S({"src/lib/utils/avatarProcessor.ts"(){"use strict";ro(),et(),z(),lb(),Ct={PROVIDER_NOT_SUPPORTED:"AVATAR_PROVIDER_NOT_SUPPORTED",PROVIDER_NOT_CONFIGURED:"AVATAR_PROVIDER_NOT_CONFIGURED",GENERATION_FAILED:"AVATAR_GENERATION_FAILED",POLL_TIMEOUT:"AVATAR_POLL_TIMEOUT",INVALID_INPUT:"AVATAR_INVALID_INPUT",AUDIO_REQUIRED:"AVATAR_AUDIO_REQUIRED",IMAGE_REQUIRED:"AVATAR_IMAGE_REQUIRED",AUDIO_TOO_LONG:"AVATAR_AUDIO_TOO_LONG"},At=class extends Me{constructor(e){super({code:e.code,message:e.message,category:e.category??"execution",severity:e.severity??"high",retriable:e.retriable??!1,context:e.context,originalError:e.originalError}),this.name="AvatarError"}},um=class{static registry=new d0("AvatarProcessor");static registerHandler(e,t){const r=e&&e.toLowerCase();this.registry.register(e,t),f.debug(`[AvatarProcessor] Registered avatar handler: ${r}`)}static supports(e){return this.registry.supports(e)}static listProviders(){return this.registry.list()}static getHandler(e){return this.registry.get(e)}static clearHandlers(){this.registry.clear()}static buildSpanAttributes(e,t){return{"avatar.operation":"generate","avatar.provider":e,"avatar.quality":t.quality,"avatar.format":t.format,"avatar.has_text":t.text!==void 0,"avatar.has_audio":t.audio!==void 0}}static async generate(e,t){const r=Ce.createSpan("media.generation","avatar.generate",this.buildSpanAttributes(e,t));try{if(!t.image)throw new At({code:Ct.IMAGE_REQUIRED,message:"Avatar generation requires an `image` (Buffer, path, or URL)",category:"validation",severity:"medium",retriable:!1,context:{provider:e}});if(!t.audio&&!t.text)throw new At({code:Ct.INVALID_INPUT,message:"Avatar generation requires either `audio` (a Buffer/URL) or `text` (to be TTS'd by the provider).",category:"validation",severity:"high",retriable:!1,context:{provider:e}});const n=this.getHandler(e);if(!n)throw new At({code:Ct.PROVIDER_NOT_SUPPORTED,message:`Avatar provider "${e}" is not registered. Available: ${this.listProviders().join(", ")}`,category:"configuration",severity:"high",retriable:!1,context:{provider:e,available:this.listProviders()}});if(!n.isConfigured())throw new At({code:Ct.PROVIDER_NOT_CONFIGURED,message:`Avatar provider "${e}" is not configured. Set the required credentials.`,category:"configuration",severity:"high",retriable:!1,context:{provider:e}});f.debug(`[AvatarProcessor] Starting avatar generation with provider: ${e}`);const o=await n.generate(t),i=Ce.endSpan(r,1);return nt().recordSpan(i),f.info(`[AvatarProcessor] Generated ${o.size} bytes (${e})`),o}catch(n){const o=Ce.endSpan(r,2,n instanceof Error?n.message:String(n));if(nt().recordSpan(o),n instanceof At)throw n;const i=n instanceof Error?n.message:String(n);throw new At({code:Ct.GENERATION_FAILED,message:`Avatar generation failed for provider "${e}": ${i}`,category:"execution",severity:"high",retriable:!0,context:{provider:e},originalError:n instanceof Error?n:void 0})}}}}}),$mr,Ame,Fmr,Umr,w_,Bmr=S({"src/lib/avatar/providers/DIDAvatar.ts"(){"use strict";z(),zt(),ff(),_I(),Ma(),$mr="https://api.d-id.com",Ame=3e4,Fmr=3e3,Umr=5*6e4,w_=class{maxAudioDurationSeconds=60;supportedFormats=["mp4"];apiKey;baseUrl;constructor(e){const t=(e??process.env.DID_API_KEY??process.env.D_ID_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.DID_BASE_URL??process.env.D_ID_BASE_URL??$mr).replace(/\/$/,"")}isConfigured(){return this.apiKey!==null}async generate(e){if(!this.apiKey)throw new At({code:Ct.PROVIDER_NOT_CONFIGURED,message:"DID_API_KEY not configured",category:"configuration",severity:"high",retriable:!1});if(!e.audio&&!e.text)throw new At({code:Ct.AUDIO_REQUIRED,message:"D-ID requires either `audio` (Buffer/path) or `text` (with voice id) to drive the talk",category:"validation",severity:"medium",retriable:!1});const t=Date.now(),r=await this.uploadImage(e.image),n=e.audio?await this.uploadAudio(e.audio):void 0,o=await this.submitTalk(e,r,n),i=await this.pollUntilDone(o,e.timeout??Umr,e.abortSignal);if(!i.result_url)throw new At({code:Ct.GENERATION_FAILED,message:`D-ID talk ${o} completed but no result_url returned`,category:"execution",severity:"high",retriable:!1,context:{talkId:o,completed:i}});try{await TI(i.result_url)}catch(u){throw new At({code:Ct.GENERATION_FAILED,message:`D-ID result_url rejected as unsafe: ${u instanceof Error?u.message:String(u)}`,category:"validation",severity:"high",retriable:!1,context:{talkId:o,url:i.result_url}})}const s=await this.downloadResult(i.result_url),a=Date.now()-t;return f.info(`[DIDAvatar] Generated ${s.length} bytes in ${a}ms \u2014 talk ${o}`),{buffer:s,format:"mp4",size:s.length,duration:i.duration,provider:"d-id",metadata:{latency:a,provider:"d-id",jobId:o}}}async uploadImage(e){if(typeof e=="string"&&/^https:\/\//.test(e))return e;const t=await this.resolveBuffer(e),r=new FormData;r.append("image",new Blob([new Uint8Array(t)],{type:this.detectImageMime(t)}),"source.png");const n=await this.fetchWithTimeout(`${this.baseUrl}/images`,{method:"POST",headers:{Authorization:`Basic ${this.apiKey}`},body:r}),o=await this.assertOk(n,"image upload");if(!o.url)throw new At({code:Ct.GENERATION_FAILED,message:"D-ID image upload succeeded but returned no URL",category:"execution",severity:"high",retriable:!1});return o.url}async uploadAudio(e){if(typeof e=="string"&&/^https:\/\//.test(e))return e;const t=await this.resolveBuffer(e),r=this.detectAudioType(t),o={mp3:"mp3",mpeg:"mp3",wav:"wav",ogg:"ogg",mp4:"m4a"}[r]??"mp3",i=new FormData;i.append("audio",new Blob([new Uint8Array(t)],{type:`audio/${r}`}),`narration.${o}`);const s=await this.fetchWithTimeout(`${this.baseUrl}/audios`,{method:"POST",headers:{Authorization:`Basic ${this.apiKey}`},body:i}),a=await this.assertOk(s,"audio upload");if(!a.url)throw new At({code:Ct.GENERATION_FAILED,message:"D-ID audio upload succeeded but returned no URL",category:"execution",severity:"high",retriable:!1});return a.url}async submitTalk(e,t,r){const n=r?{type:"audio",audio_url:r}:{type:"text",input:e.text,provider:{type:"microsoft",voice_id:e.voice??"en-US-JennyNeural"}},o={source_url:t,script:n,config:{result_format:"mp4",stitch:!0}},i=await this.fetchWithTimeout(`${this.baseUrl}/talks`,{method:"POST",headers:{Authorization:`Basic ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(o)}),s=await this.assertOk(i,"talk submit");if(!s.id)throw new At({code:Ct.GENERATION_FAILED,message:"D-ID talk submit returned no id",category:"execution",severity:"high",retriable:!1});return s.id}async pollUntilDone(e,t,r){const n=Date.now();for(;Date.now()-n<t;){if(r?.aborted)throw new At({code:Ct.GENERATION_FAILED,message:`D-ID poll for talk ${e} aborted by caller`,category:"network",severity:"medium",retriable:!1,context:{talkId:e}});const o=await this.fetchWithTimeout(`${this.baseUrl}/talks/${e}`,{method:"GET",headers:{Authorization:`Basic ${this.apiKey}`}},r),i=await this.assertOk(o,"talk status");if(i.status==="done")return i;if(i.status==="error"||i.status==="rejected")throw new At({code:Ct.GENERATION_FAILED,message:`D-ID talk ${e} ${i.status}: ${i.error?.description??"unknown"}`,category:"execution",severity:"high",retriable:!1,context:{talkId:e,status:i.status,error:i.error}});await new Promise((s,a)=>{const u=()=>{clearTimeout(l),a(new At({code:Ct.GENERATION_FAILED,message:`D-ID poll for talk ${e} aborted by caller`,category:"network",severity:"medium",retriable:!1,context:{talkId:e}}))},l=setTimeout(()=>{r?.removeEventListener("abort",u),s()},Fmr);r?.addEventListener("abort",u,{once:!0})})}throw new At({code:Ct.POLL_TIMEOUT,message:`D-ID talk ${e} did not complete within ${Math.round(t/1e3)}s`,category:"timeout",severity:"medium",retriable:!0,context:{talkId:e}})}async downloadResult(e){const t=await this.fetchWithTimeout(e,{method:"GET"});if(!t.ok)throw new At({code:Ct.GENERATION_FAILED,message:`D-ID result download failed: ${t.status}`,category:"network",severity:"medium",retriable:t.status>=500,context:{status:t.status,url:e}});try{return await Ly(t,$y,"D-ID result")}catch(r){throw new At({code:Ct.GENERATION_FAILED,message:`D-ID result download rejected: ${r instanceof Error?r.message:String(r)}`,category:"network",severity:"high",retriable:!1,context:{url:e},originalError:r instanceof Error?r:void 0})}}async resolveBuffer(e){if(Buffer.isBuffer(e))return e;if(!/^https:\/\//.test(e))throw new At({code:Ct.INVALID_INPUT,message:`Invalid input: expected Buffer or HTTPS URL, got string "${e}". Local file reads are not supported.`,category:"validation",severity:"high",retriable:!1});try{await TI(e)}catch(n){throw new At({code:Ct.INVALID_INPUT,message:`Unsafe URL rejected: ${n instanceof Error?n.message:String(n)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}const t=await this.fetchWithTimeout(e,{method:"GET"});if(!t.ok)throw new At({code:Ct.INVALID_INPUT,message:`Failed to fetch input from ${e}: ${t.status}`,category:"network",severity:"medium",retriable:t.status>=500,context:{url:e,status:t.status}});const r=Math.max(pf,mf);try{return await Ly(t,r,"D-ID input")}catch(n){throw new At({code:Ct.INVALID_INPUT,message:`D-ID input download rejected: ${n instanceof Error?n.message:String(n)}`,category:"network",severity:"high",retriable:!1,context:{url:e},originalError:n instanceof Error?n:void 0})}}detectImageMime(e){return e.length<4?"image/jpeg":e[0]===137&&e[1]===80?"image/png":e[0]===255&&e[1]===216?"image/jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":"image/jpeg"}detectAudioType(e){return e.length<4?"mp3":e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70?"wav":e[0]===79&&e[1]===103&&e[2]===103&&e[3]===83?"ogg":e[0]===73&&e[1]===68&&e[2]===51?"mp3":e[0]===255&&(e[1]&224)===224?"mpeg":e.length>=8&&e[4]===102&&e[5]===116&&e[6]===121&&e[7]===112?"mp4":"mp3"}async fetchWithTimeout(e,t,r){const n=new AbortController,o=setTimeout(()=>n.abort(),Ame),i=()=>n.abort();r?.addEventListener("abort",i,{once:!0});try{return await fetch(e,{...t,signal:n.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?r?.aborted?new At({code:Ct.GENERATION_FAILED,message:`D-ID request to ${e} aborted by caller`,category:"network",severity:"medium",retriable:!1,originalError:s}):new At({code:Ct.GENERATION_FAILED,message:`D-ID request to ${e} timed out after ${Ame/1e3}s`,category:"network",severity:"high",retriable:!0,originalError:s}):s}finally{r?.removeEventListener("abort",i),clearTimeout(o)}}async assertOk(e,t){if(e.ok)return e.json();const r=await e.text(),n=e.status===408||e.status===429||e.status>=500;throw new At({code:Ct.GENERATION_FAILED,message:`D-ID ${t} failed: ${e.status} \u2014 ${pr(r,500)}`,category:n?"network":"execution",severity:"high",retriable:n,context:{status:e.status,label:t}})}}}}),zmr,o5,Gmr,xme,b_,qmr=S({"src/lib/avatar/providers/HeyGenAvatar.ts"(){"use strict";ff(),z(),zt(),Wd(),Ma(),zmr="https://api.heygen.com/v2",o5=3e4,Gmr=5e3,xme=5*6e4,b_=class{maxAudioDurationSeconds=300;supportedFormats=["mp4"];apiKey;baseUrl;constructor(e){const t=(e??process.env.HEYGEN_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.HEYGEN_BASE_URL??zmr).replace(/\/$/,"")}isConfigured(){return this.apiKey!==null}async generate(e){if(!this.apiKey)throw new At({code:Ct.PROVIDER_NOT_CONFIGURED,message:"HEYGEN_API_KEY not configured",category:"configuration",severity:"high",retriable:!1});if(!e.text&&!e.audio)throw new At({code:Ct.AUDIO_REQUIRED,message:"HeyGen requires either `text` or `audio` to drive the avatar",category:"validation",severity:"medium",retriable:!1});const t=Date.now(),r=e.abortSignal,n=await this.submitVideo(e),o=await this.pollUntilComplete(n,r),i=await this.download(o),s=Date.now()-t;return f.info(`[HeyGenAvatar] Generated ${i.length} bytes in ${s}ms \u2014 video ${n}`),{buffer:i,format:"mp4",size:i.length,provider:"heygen",metadata:{latency:s,provider:"heygen",jobId:n}}}async submitVideo(e){const t=e,r=t.avatarId??(typeof e.image=="string"&&/^[a-zA-Z0-9_-]{20,}$/.test(e.image)?e.image:void 0);if(!r)throw new At({code:Ct.INVALID_INPUT,message:"HeyGen requires `avatarId` (HeyGen avatar catalog id). Pass via options.avatarId or as options.image with a valid HeyGen id.",category:"validation",severity:"medium",retriable:!1});if(e.audio!==void 0){if(Buffer.isBuffer(e.audio))throw new At({code:Ct.INVALID_INPUT,message:"HeyGen requires a publicly accessible audio URL; got a binary Buffer. Upload the audio to a hosted location and pass the HTTPS URL instead.",category:"validation",severity:"medium",retriable:!1});if(typeof e.audio!="string"||!/^https?:\/\//i.test(e.audio))throw new At({code:Ct.INVALID_INPUT,message:"HeyGen requires a publicly accessible HTTPS audio URL; got an unsupported audio input type. Upload the audio to a hosted location and pass the HTTPS URL instead.",category:"validation",severity:"medium",retriable:!1})}const n=e.audio?{type:"audio",audio_url:e.audio}:{type:"text",input_text:e.text,voice_id:e.voice??"1bd001e7e50f421d891986aad5158bc8"},o={video_inputs:[{character:{type:"avatar",avatar_id:r,avatar_style:"normal"},voice:n,background:{type:"color",value:t.backgroundColor??"#FFFFFF"}}],dimension:{width:t.width??1280,height:t.height??720}},i=await this.fetchWithTimeout(`${this.baseUrl}/video/generate`,{method:"POST",headers:{"X-API-Key":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify(o)});if(!i.ok){const u=await i.text(),l=i.status===408||i.status===429||i.status>=500;throw new At({code:Ct.GENERATION_FAILED,message:`HeyGen submit failed: ${i.status} \u2014 ${pr(u,500)}`,category:l?"network":"execution",severity:"high",retriable:l,context:{status:i.status}})}const s=await i.json(),a=s.data?.video_id;if(!a)throw new At({code:Ct.GENERATION_FAILED,message:"HeyGen submit response missing video_id",category:"execution",severity:"high",retriable:!1,context:{response:s}});return a}async pollUntilComplete(e,t){const r=Date.now(),n=this.baseUrl.replace(/\/v2$/,"/v1");for(;Date.now()-r<xme;){if(t?.aborted)throw new At({code:Ct.GENERATION_FAILED,message:`HeyGen poll for video ${e} aborted by caller`,category:"network",severity:"medium",retriable:!1,context:{videoId:e}});const o=await this.fetchWithTimeout(`${n}/video_status.get?video_id=${e}`,{method:"GET",headers:{"X-API-Key":this.apiKey}},t);if(!o.ok){const s=await o.text();throw new At({code:Ct.GENERATION_FAILED,message:`HeyGen poll failed: ${o.status} \u2014 ${pr(s,500)}`,category:"network",severity:"medium",retriable:o.status>=500,context:{status:o.status,videoId:e}})}const i=await o.json();if(i.data?.status==="completed"){const s=i.data.video_url;if(!s)throw new At({code:Ct.GENERATION_FAILED,message:`HeyGen video ${e} completed but no URL returned`,category:"execution",severity:"high",retriable:!1,context:{videoId:e,data:i}});return s}if(i.data?.status==="failed")throw new At({code:Ct.GENERATION_FAILED,message:`HeyGen video ${e} failed: ${i.data?.error?.message??"unknown"}`,category:"execution",severity:"high",retriable:!1,context:{videoId:e,data:i}});await new Promise((s,a)=>{const u=()=>{clearTimeout(l),a(new At({code:Ct.GENERATION_FAILED,message:`HeyGen poll for video ${e} aborted by caller`,category:"network",severity:"medium",retriable:!1,context:{videoId:e}}))},l=setTimeout(()=>{t?.removeEventListener("abort",u),s()},Gmr);t?.addEventListener("abort",u,{once:!0})})}throw new At({code:Ct.POLL_TIMEOUT,message:`HeyGen video ${e} did not complete within ${xme/1e3}s`,category:"timeout",severity:"medium",retriable:!0,context:{videoId:e}})}async download(e){try{return await im(e,{maxBytes:$y,label:"HeyGen video",timeoutMs:o5})}catch(t){throw new At({code:Ct.GENERATION_FAILED,message:`HeyGen video download rejected: ${t instanceof Error?t.message:String(t)}`,category:"network",severity:"high",retriable:!1,context:{url:e},originalError:t instanceof Error?t:void 0})}}async fetchWithTimeout(e,t,r){const n=new AbortController;let o=!1;const i=setTimeout(()=>{o=!0,n.abort()},o5),s=()=>n.abort();r?.addEventListener("abort",s,{once:!0});try{return await fetch(e,{...t,signal:n.signal})}catch(a){throw a instanceof Error&&a.name==="AbortError"?r?.aborted?new At({code:Ct.GENERATION_FAILED,message:`HeyGen request to ${e} was aborted by the caller`,category:"network",severity:"medium",retriable:!1,originalError:a}):o?new At({code:Ct.GENERATION_FAILED,message:`HeyGen request to ${e} timed out after ${o5/1e3}s`,category:"network",severity:"high",retriable:!0,originalError:a}):new At({code:Ct.GENERATION_FAILED,message:`HeyGen request to ${e} was aborted`,category:"network",severity:"high",retriable:!0,originalError:a}):a}finally{r?.removeEventListener("abort",s),clearTimeout(i)}}}}}),jmr,T_,Vmr=S({"src/lib/avatar/providers/ReplicateAvatar.ts"(){"use strict";ff(),z(),t5(),n5(),Ma(),_I(),jmr="douwantech/musetalk:5501004e78525e4bbd9fa20d1e75ad51fddce5a274bec07b9b16d685e34eeaf8",T_=class{maxAudioDurationSeconds=60;supportedFormats=["mp4"];isConfigured(){return hf()!==null}async generate(e){const t=hf();if(!t)throw new At({code:Ct.PROVIDER_NOT_CONFIGURED,message:"REPLICATE_API_TOKEN not configured",category:"configuration",severity:"high",retriable:!1});if(!e.audio)throw new At({code:Ct.AUDIO_REQUIRED,message:"Replicate avatar handler (MuseTalk) requires `audio` (Buffer or path); text-only is not supported. Use D-ID for text-driven talks or chain TTS + Replicate.",category:"validation",severity:"medium",retriable:!1});const r=Date.now(),n=e.model??jmr,o=await this.resolveBuffer(e.image,mf,"Replicate avatar reference image"),i=await this.resolveBuffer(e.audio,pf,"Replicate avatar reference audio"),s=`data:image/${this.detectImageType(o)};base64,${o.toString("base64")}`,a=`data:audio/${this.detectAudioType(i)};base64,${i.toString("base64")}`;let u;try{u=await CI(t,{model:n,input:{image:s,audio:a,bbox_shift:0,fps:25}})}catch(d){throw new At({code:Ct.GENERATION_FAILED,message:`Replicate avatar generation failed: ${d instanceof Error?d.message:String(d)}`,category:"execution",severity:"high",retriable:!0,context:{model:n},originalError:d instanceof Error?d:void 0})}let l;try{l=await r5(u,$y)}catch(d){throw new At({code:Ct.GENERATION_FAILED,message:`Replicate avatar download failed: ${d instanceof Error?d.message:String(d)}`,category:"network",severity:"medium",retriable:!0,context:{predictionId:u.id},originalError:d instanceof Error?d:void 0})}const c=Date.now()-r;return f.info(`[ReplicateAvatar] Generated ${l.length} bytes in ${c}ms \u2014 model ${n}`),{buffer:l,format:"mp4",size:l.length,provider:"replicate",metadata:{latency:c,provider:"replicate",model:n,jobId:u.id}}}async resolveBuffer(e,t=mf,r="Replicate avatar input"){if(Buffer.isBuffer(e)){if(e.length>t)throw new At({code:Ct.INVALID_INPUT,message:`${r} too large: ${e.length} bytes exceeds ${t}`,category:"validation",severity:"high",retriable:!1});return e}if(!/^https:\/\//.test(e))throw new At({code:Ct.INVALID_INPUT,message:`Invalid input: expected Buffer or HTTPS URL, got string "${e}". Local file reads are not supported.`,category:"validation",severity:"high",retriable:!1});try{await TI(e)}catch(a){throw new At({code:Ct.INVALID_INPUT,message:`Unsafe URL rejected: ${a instanceof Error?a.message:String(a)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}const n=6e4,o=new AbortController,i=setTimeout(()=>o.abort(),n);let s;try{s=await fetch(e,{signal:o.signal})}catch(a){throw a instanceof Error&&a.name==="AbortError"?new At({code:Ct.INVALID_INPUT,message:`Replicate avatar input fetch timed out after ${n/1e3}s: ${e}`,category:"network",severity:"medium",retriable:!0}):a}finally{clearTimeout(i)}if(!s.ok)throw new At({code:Ct.INVALID_INPUT,message:`Failed to fetch ${e}: ${s.status}`,category:"network",severity:"medium",retriable:s.status>=500});try{return await Ly(s,t,r)}catch(a){throw new At({code:Ct.INVALID_INPUT,message:`${r} too large: ${a instanceof Error?a.message:String(a)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}}detectAudioType(e){return e.length<4?"mp3":e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70?"wav":e[0]===79&&e[1]===103&&e[2]===103&&e[3]===83?"ogg":e[0]===73&&e[1]===68&&e[2]===51?"mp3":e[0]===255&&(e[1]&224)===224?"mpeg":e.length>=8&&e[4]===102&&e[5]===116&&e[6]===121&&e[7]===112?"mp4":"mp3"}detectImageType(e){return e.length<4?"jpeg":e[0]===137&&e[1]===80?"png":e[0]===255&&e[1]===216?"jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"webp":"jpeg"}}}}),Cme={};ue(Cme,{AVATAR_ERROR_CODES:()=>Ct,AvatarError:()=>At,AvatarProcessor:()=>um,DIDAvatar:()=>w_,DIDAvatarHandler:()=>w_,HeyGenAvatar:()=>b_,HeyGenAvatarHandler:()=>b_,ReplicateAvatar:()=>T_,ReplicateAvatarHandler:()=>T_,registerDefaultAvatarHandlers:()=>Hmr});function Hmr(){for(const{name:e,aliases:t,factory:r}of Kmr){const n=!um.supports(e),o=(t??[]).filter(i=>!um.supports(i));if(!(!n&&o.length===0))try{let i;if(n||(i=um.getHandler(e)),!i&&(i=r(),!i.isConfigured()))continue;n&&um.registerHandler(e,i);for(const s of o)um.registerHandler(s,i)}catch(i){f.debug(`[avatar] ${e} auto-registration skipped: ${i instanceof Error?i.message:String(i)}`)}}}var Wmr,Kmr,Ime=S({"src/lib/avatar/index.ts"(){"use strict";Pw(),z(),ff(),ff(),Bmr(),qmr(),Vmr(),Bmr(),qmr(),Vmr(),Wmr={"d-id":()=>new w_,heygen:()=>new b_,replicate:()=>new T_},Kmr=Ep.filter(e=>e.kind==="avatar").map(e=>{const t=Wmr[e.name];if(!t)throw new Error(`[avatar] no handler factory for catalog entry "${e.name}"`);return{name:e.name,aliases:e.aliases,factory:t}})}}),__,i5,Rme=S({"src/lib/mcp/elicitation/elicitationManager.ts"(){"use strict";oo(),qt(),z(),__=class extends wn{config;pendingRequests=new Map;constructor(e={}){super(),this.config={defaultTimeout:e.defaultTimeout??6e4,enabled:e.enabled??!0,handler:e.handler??this.defaultHandler.bind(this),fallbackBehavior:e.fallbackBehavior??"timeout"}}setHandler(e){this.config.handler=e}setEnabled(e){if(this.config.enabled=e,!e)for(const[t,r]of this.pendingRequests)r.settled||(r.settled=!0,this.handleDisabled(r.request,r.resolve),r.timer&&clearTimeout(r.timer),this.pendingRequests.delete(t))}isEnabled(){return this.config.enabled}async request(e){const t={...e,id:e.id??st()};if(!this.config.enabled)return this.handleDisabledRequest(t);const r=t.timeout??this.config.defaultTimeout;return new Promise(n=>{const o=setTimeout(()=>{const i=this.pendingRequests.get(t.id);!i||i.settled||(i.settled=!0,this.handleTimeout(t,n))},r);this.pendingRequests.set(t.id,{request:t,resolve:n,timer:o,settled:!1}),this.emit("elicitationRequested",t),Promise.resolve().then(()=>this.config.handler(t)).then(i=>{const s=this.pendingRequests.get(t.id);!s||s.settled||(s.settled=!0,clearTimeout(o),this.pendingRequests.delete(t.id),this.emit("elicitationResponded",i),n(i))}).catch(i=>{const s=this.pendingRequests.get(t.id);if(!s||s.settled)return;s.settled=!0,clearTimeout(o),this.pendingRequests.delete(t.id);const a={requestId:t.id,responded:!1,error:i instanceof Error?i.message:String(i),timestamp:Date.now()};this.emit("elicitationError",{request:t,error:i}),n(a)})})}async confirm(e,t){const r={type:"confirmation",message:e,toolName:t?.toolName??"unknown",serverId:t?.serverId,confirmLabel:t?.confirmLabel,cancelLabel:t?.cancelLabel,timeout:t?.timeout};return(await this.request(r)).value===!0}async getText(e,t){const r={type:"text",message:e,toolName:t?.toolName??"unknown",placeholder:t?.placeholder,defaultValue:t?.defaultValue,timeout:t?.timeout};return(await this.request(r)).value}async select(e,t,r){const n={type:"select",message:e,toolName:r?.toolName??"unknown",options:t,timeout:r?.timeout};return(await this.request(n)).value}async multiSelect(e,t,r){const n={type:"multiselect",message:e,toolName:r?.toolName??"unknown",options:t,timeout:r?.timeout,minSelections:r?.minSelections,maxSelections:r?.maxSelections};return(await this.request(n)).value}async form(e,t,r){const n={type:"form",message:e,toolName:r?.toolName??"unknown",serverId:r?.serverId,fields:t,submitLabel:r?.submitLabel,timeout:r?.timeout};return(await this.request(n)).value}async getSecret(e,t){const r={type:"secret",message:e,toolName:t?.toolName??"unknown",hint:t?.hint,timeout:t?.timeout};return(await this.request(r)).value}cancel(e,t){const r=this.pendingRequests.get(e);if(r){if(r.settled)return;r.settled=!0,r.timer&&clearTimeout(r.timer);const n={requestId:e,responded:!1,cancelled:!0,error:t,timestamp:Date.now()};r.resolve(n),this.pendingRequests.delete(e),this.emit("elicitationCancelled",{requestId:e,reason:t})}}async defaultHandler(e){return f.warn(`[ElicitationManager] No handler for elicitation request: ${e.id}`),e.defaultValue!==void 0?{requestId:e.id,responded:!0,value:e.defaultValue,timestamp:Date.now()}:{requestId:e.id,responded:!1,error:"No elicitation handler configured",timestamp:Date.now()}}handleTimeout(e,t){this.pendingRequests.delete(e.id);const r={requestId:e.id,responded:!1,timedOut:!0,value:e.defaultValue,timestamp:Date.now()};this.emit("elicitationTimeout",{request:e}),t(r)}handleDisabled(e,t){t(this.handleDisabledRequest(e))}handleDisabledRequest(e){switch(this.config.fallbackBehavior){case"default":return{requestId:e.id,responded:e.defaultValue!==void 0,value:e.defaultValue,timestamp:Date.now()};case"error":return{requestId:e.id,responded:!1,error:"Elicitation is disabled",timestamp:Date.now()};default:return{requestId:e.id,responded:!1,timedOut:!0,value:e.defaultValue,timestamp:Date.now()}}}getPendingCount(){return this.pendingRequests.size}getPendingRequests(){return Array.from(this.pendingRequests.values()).map(e=>e.request)}clearPending(e){for(const[t]of this.pendingRequests)this.cancel(t,e??"Cleared")}},i5=new __}}),Jmr={};ue(Jmr,{ElicitationManager:()=>__,globalElicitationManager:()=>i5});var Xmr=S({"src/lib/mcp/elicitation/index.ts"(){"use strict";Rme()}});function Mc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function iu(e,t){const r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function Mme(e,t){const r=e[t];return Array.isArray(r)?r:[]}function II(e){return e.filter(t=>t!==void 0)}function JEn(e){return e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e)}function XEn(e){if(e.type!=="official"&&e.type!=="custom")return;const t=e.url??(e.type==="official"?thr:"");let r;try{r=new URL(t)}catch{return}if(r.protocol!=="https:"&&r.protocol!=="http:"||r.username!==""||r.password!==""||e.authToken&&r.protocol==="http:"&&!JEn(r.hostname))return;const n=r.pathname.replace(/\/+$/,""),o=n.endsWith(Pme)?n:`${n}${Pme}`;return{config:e,apiBase:`${r.origin}${o}`}}function YEn(e){if(!Mc(e))return;const t=iu(e,"name");return t===void 0?void 0:{name:t,isRequired:e.isRequired===!0,isSecret:e.isSecret===!0}}function Ymr(e){if(!Mc(e))return;const t=iu(e,"type");if(t===void 0)return;const r=iu(e,"url");return r===void 0?{type:t}:{type:t,url:r}}function ZEn(e){if(!Mc(e))return;const t=iu(e,"registryType"),r=iu(e,"identifier");if(t===void 0||r===void 0)return;const n=iu(e,"version"),o=Ymr(e.transport);return{registryType:t,identifier:r,...n===void 0?{}:{version:n},...o===void 0?{}:{transport:o},environmentVariables:II(Mme(e,"environmentVariables").map(YEn))}}function QEn(e){if(!Mc(e))return;const t=iu(e,"name");if(t===void 0)return;const r=Mc(e.repository)?e.repository:void 0,n=r===void 0?void 0:iu(r,"url"),o=iu(e,"websiteUrl");return{name:t,description:iu(e,"description")??"",version:iu(e,"version")??"",...n===void 0?{}:{repositoryUrl:n},...o===void 0?{}:{websiteUrl:o},packages:II(Mme(e,"packages").map(ZEn)),remotes:II(Mme(e,"remotes").map(Ymr))}}function Zmr(e){if(!Mc(e))return;const t=QEn(e.server);if(t===void 0)return;const r=Mc(e._meta)?e._meta:void 0,n=r!==void 0?r[rhr]:void 0,o=Mc(n)?iu(n,"status"):void 0,i=Mc(n)?iu(n,"updatedAt"):void 0;return{server:t,...o===void 0?{}:{status:o},...i===void 0?{}:{updatedAt:i}}}function eSn(e){if(!Mc(e)||!Array.isArray(e.servers))throw new Error("registry list response has no servers array");const t=Mc(e.metadata)?e.metadata:void 0,r=t===void 0?void 0:iu(t,"nextCursor");return{records:II(e.servers.map(Zmr)),...r===void 0?{}:{nextCursor:r}}}function Qmr(e){switch(e){case"stdio":return"stdio";case"streamable-http":return"http";case"sse":return"sse";default:return}}function tSn(e){if(!(e.registryType!=="npm"||e.identifier.length>ohr||!nhr.test(e.identifier)))return e.version===void 0?e.identifier:e.version.length<=shr&&ihr.test(e.version)?`${e.identifier}@${e.version}`:void 0}function ehr(e,t){const{server:r}=e,n=r.packages.map(u=>({pkg:u,spec:tSn(u)})).find(u=>u.spec!==void 0),o=Array.from(new Set(II([...r.packages.map(u=>u.transport===void 0?void 0:Qmr(u.transport.type)),...r.remotes.map(u=>Qmr(u.type))]))),i=n===void 0?[]:n.pkg.environmentVariables.filter(u=>u.isRequired).map(u=>u.name),s=r.remotes.flatMap(u=>u.url===void 0?[]:[{type:u.type,url:u.url}]),a={source:"remote-registry",registry:t,...e.status===void 0?{}:{registryStatus:e.status},packages:r.packages.map(u=>({registryType:u.registryType,identifier:u.identifier,...u.version===void 0?{}:{version:u.version}})),remotes:s};return{id:r.name,name:r.name,description:r.description,version:r.version,...r.websiteUrl===void 0?{}:{homepage:r.websiteUrl},...r.repositoryUrl===void 0?{}:{repository:r.repositoryUrl},...n===void 0?{}:{npmPackage:n.pkg.identifier,command:"npx",args:["-y",n.spec],installCommand:`npx -y ${n.spec}`},...i.length===0?{}:{requiredEnvVars:i},...o.length===0?{}:{transports:o},...e.updatedAt===void 0?{}:{lastUpdated:e.updatedAt},verified:!1,metadata:a}}var thr,Pme,rhr,nhr,ohr,ihr,shr,rSn=S({"src/lib/mcp/mcpRegistryRemote.ts"(){"use strict";thr="https://registry.modelcontextprotocol.io",Pme="/v0.1",rhr="io.modelcontextprotocol.registry/official",nhr=/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,ohr=214,ihr=/^[0-9A-Za-z][0-9A-Za-z.+_~-]*$/,shr=128}}),ahr={};ue(ahr,{MCPRegistryClient:()=>s5,getAllWellKnownServers:()=>lhr,getWellKnownServer:()=>uhr,globalMCPRegistryClient:()=>Ome});function uhr(e){return RI.find(t=>t.id===e)}function lhr(){return[...RI]}var chr,dhr,Dme,phr,RI,s5,Ome,mhr=S({"src/lib/mcp/mcpRegistryClient.ts"(){"use strict";oo(),z(),rSn(),chr=100,dhr=5,Dme=8*1024*1024,phr=500,RI=[{id:"filesystem",name:"Filesystem",description:"File system operations - read, write, create, list directories",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-filesystem",command:"npx",args:["-y","@modelcontextprotocol/server-filesystem"],transports:["stdio"],categories:["file-system"],tags:["files","directories","read","write"],tools:["read_file","write_file","list_directory","create_directory"],verified:!0},{id:"github",name:"GitHub",description:"GitHub repository management and file operations",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-github",command:"npx",args:["-y","@modelcontextprotocol/server-github"],requiredEnvVars:["GITHUB_PERSONAL_ACCESS_TOKEN"],transports:["stdio"],categories:["version-control","api"],tags:["github","git","repositories","issues","pull-requests"],tools:["create_repository","list_commits","create_issue","create_pull_request"],verified:!0},{id:"postgres",name:"PostgreSQL",description:"PostgreSQL database query and management",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-postgres",command:"npx",args:["-y","@modelcontextprotocol/server-postgres"],requiredEnvVars:["DATABASE_URL"],transports:["stdio"],categories:["database"],tags:["postgres","postgresql","sql","database","query"],tools:["query","list_tables","describe_table"],verified:!0},{id:"sqlite",name:"SQLite",description:"SQLite database operations and queries",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-sqlite",command:"npx",args:["-y","@modelcontextprotocol/server-sqlite"],transports:["stdio"],categories:["database"],tags:["sqlite","sql","database","local"],tools:["query","list_tables","describe_table"],verified:!0},{id:"brave-search",name:"Brave Search",description:"Web search using Brave Search API",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-brave-search",command:"npx",args:["-y","@modelcontextprotocol/server-brave-search"],requiredEnvVars:["BRAVE_API_KEY"],transports:["stdio"],categories:["search","api"],tags:["search","web","brave","internet"],tools:["web_search","local_search"],verified:!0},{id:"puppeteer",name:"Puppeteer",description:"Web scraping and browser automation",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-puppeteer",command:"npx",args:["-y","@modelcontextprotocol/server-puppeteer"],transports:["stdio"],categories:["automation","web"],tags:["browser","scraping","automation","puppeteer"],tools:["navigate","screenshot","click","type","get_content"],verified:!0},{id:"git",name:"Git",description:"Git repository operations and version control",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-git",command:"npx",args:["-y","@modelcontextprotocol/server-git"],transports:["stdio"],categories:["version-control"],tags:["git","vcs","commits","branches"],tools:["git_status","git_log","git_diff","git_commit"],verified:!0},{id:"memory",name:"Memory",description:"Persistent memory and knowledge storage",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-memory",command:"npx",args:["-y","@modelcontextprotocol/server-memory"],transports:["stdio"],categories:["memory","storage"],tags:["memory","knowledge","storage","persistent"],tools:["store","retrieve","search","delete"],verified:!0},{id:"slack",name:"Slack",description:"Slack workspace integration",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-slack",command:"npx",args:["-y","@modelcontextprotocol/server-slack"],requiredEnvVars:["SLACK_BOT_TOKEN"],transports:["stdio"],categories:["communication","api"],tags:["slack","messaging","chat","team"],tools:["send_message","list_channels","get_channel_history"],verified:!0},{id:"google-drive",name:"Google Drive",description:"Google Drive file management",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-gdrive",command:"npx",args:["-y","@modelcontextprotocol/server-gdrive"],transports:["stdio"],categories:["file-system","api"],tags:["google","drive","files","cloud"],tools:["list_files","read_file","create_file","search_files"],verified:!0}],s5=class extends wn{config;cache=new Map;customEntries=new Map;constructor(e={}){super(),this.config={registries:[...e.registries??[{type:"official",enableCache:!0}]],remoteLookup:e.remoteLookup??!1,enableCache:e.enableCache??!0,defaultCacheTTL:e.defaultCacheTTL??36e5,timeout:e.timeout??1e4,userAgent:e.userAgent??"NeuroLink-MCP-Registry-Client/1.0"}}async search(e={}){const{query:t,categories:r,tags:n,transport:o,verifiedOnly:i=!1,sortBy:s="downloads",sortDirection:a="desc",limit:u=25,offset:l=0}=e,c=Math.max(1,u),d=Math.max(0,l);let m=[...t?await this.collectEntries(t):await this.getAllEntries()];if(t){const g=t.toLowerCase();m=m.filter(y=>y.name.toLowerCase().includes(g)||y.description.toLowerCase().includes(g)||y.tags?.some(v=>v.toLowerCase().includes(g)))}r?.length&&(m=m.filter(g=>g.categories?.some(y=>r.includes(y)))),n?.length&&(m=m.filter(g=>g.tags?.some(y=>n.includes(y)))),o&&(m=m.filter(g=>g.transports?.includes(o))),i&&(m=m.filter(g=>g.verified)),m.sort((g,y)=>{let v=0;switch(s){case"name":v=g.name.localeCompare(y.name);break;case"downloads":v=(g.downloads??0)-(y.downloads??0);break;case"stars":v=(g.stars??0)-(y.stars??0);break;case"lastUpdated":v=(g.lastUpdated??"").localeCompare(y.lastUpdated??"");break}return a==="desc"?-v:v});const h=m.length;return m=m.slice(d,d+c),{entries:m,totalCount:h,page:Math.floor(d/c)+1,pageSize:c,hasMore:d+m.length<h}}async getEntry(e){if(this.customEntries.has(e))return this.customEntries.get(e);const t=RI.find(r=>r.id===e);if(t)return t;if(this.config.remoteLookup&&!(e===""||e==="."||e===".."))for(const r of this.getRemoteTargets()){const n=await this.fetchRemoteEntry(r,e);if(n)return n}}async getAllEntries(){return this.collectEntries()}async collectEntries(e){const t=e===void 0||!this.config.remoteLookup?"all-entries":`all-entries:${e.toLowerCase()}`,r=this.config.remoteLookup?this.getRemoteTargets():[],n=this.config.enableCache&&r.every(c=>this.isRemoteCacheEnabled(c)),o=Math.min(this.config.defaultCacheTTL,...r.map(c=>c.config.cacheTTL??this.config.defaultCacheTTL)),i=n?this.readCache(t,o):void 0;if(i)return i;const s=new Set(this.customEntries.keys()),a=[...RI.filter(c=>!s.has(c.id)),...Array.from(this.customEntries.values())];let u=a,l=!0;if(this.config.remoteLookup){const c=await Promise.all(r.map(m=>this.fetchRemoteList(m,e))),d=new Set(a.map(m=>m.id)),p=[];for(const m of c){l=l&&m.ok;for(const h of m.entries)d.has(h.id)||(d.add(h.id),p.push(h))}u=[...a,...p]}return n&&l&&this.writeCache(t,u),u}getRemoteTargets(){return this.config.registries.flatMap(e=>{const t=XEn(e);return t===void 0?(le.debug(`[MCPRegistryClient] Skipping registry of type "${e.type}": not queryable (unsupported type, missing or unusable URL, or a bearer token on plain http to a non-loopback host)`),[]):[t]})}async fetchRemoteEntry(e,t){const r=`remote-entry:${e.apiBase}:${t}`,n=this.readRemoteCache(r,e);if(n)return n;try{const o=await this.requestJson(e,`/servers/${encodeURIComponent(t)}/versions/latest`);if(o.body===void 0)return;const i=Zmr(o.body);if(i===void 0||i.status==="deleted"||i.server.name.toLowerCase()!==t.toLowerCase())throw new Error("registry returned no record for the requested server");const s=ehr(i,e.apiBase);return this.writeRemoteCache(r,s,e),s}catch(o){this.reportRemoteError(e,"getEntry",o);return}}async fetchRemoteList(e,t){const r=`remote-list:${e.apiBase}:${(t??"").toLowerCase()}`,n=this.readRemoteCache(r,e);if(n)return{entries:n,ok:!0};try{const o=e.config.maxPages,i=o!==void 0&&Number.isFinite(o)?Math.max(1,Math.floor(o)):dhr,s=[],a=new Set;let u;for(let l=0;l<i;l++){const c=new URLSearchParams({version:"latest",limit:String(chr)});t&&c.set("search",t),u&&c.set("cursor",u);const d=await this.requestJson(e,"/servers",c),{records:p,nextCursor:m}=eSn(d.body);if(s.push(...p.filter(h=>h.status!=="deleted").map(h=>ehr(h,e.apiBase))),m===void 0||a.has(m))break;if(l===i-1){le.debug(`[MCPRegistryClient] ${e.apiBase}: stopped after ${i} page(s); more servers are available`);break}a.add(m),u=m}return this.writeRemoteCache(r,s,e),{entries:s,ok:!0}}catch(o){return this.reportRemoteError(e,"list",o),{entries:[],ok:!1}}}async requestJson(e,t,r){const n=new URL(`${e.apiBase}${t}`);r?.forEach((s,a)=>n.searchParams.set(a,s));const o={Accept:"application/json","User-Agent":this.config.userAgent,...e.config.authToken?{Authorization:`Bearer ${e.config.authToken}`}:{}},i=await globalThis.fetch(n,{method:"GET",headers:o,signal:AbortSignal.timeout(e.config.timeout??this.config.timeout)});if(i.status===404)return await i.body?.cancel(),{body:void 0};if(!i.ok)throw await i.body?.cancel(),new Error(`registry responded with HTTP ${i.status}`);return{body:await this.readBoundedJson(i)}}async readBoundedJson(e){const t=[];let r=0;if(e.body){const n=e.body.getReader();for(;;){const{done:o,value:i}=await n.read();if(o)break;if(r+=i.byteLength,r>Dme)throw await n.cancel(),new Error(`registry response exceeds ${Dme} bytes`);t.push(i)}}return JSON.parse(Buffer.concat(t).toString("utf8"))}reportRemoteError(e,t,r){const n=r instanceof Error?r.message:String(r),o=r instanceof Error?r.cause:void 0,i=typeof o=="object"&&o!==null&&"code"in o?String(o.code):void 0,s=i===void 0?n:`${n} (${i})`;le.debug(`[MCPRegistryClient] ${t} failed for ${e.apiBase}: ${s}`);try{this.emit("registryError",{registry:e.apiBase,operation:t,message:s})}catch(a){le.debug(`[MCPRegistryClient] registryError listener threw: ${String(a)}`)}}readCache(e,t){const r=this.cache.get(e);return r&&Date.now()-r.timestamp<t?r.data:void 0}readRemoteCache(e,t){return this.isRemoteCacheEnabled(t)?this.readCache(e,t.config.cacheTTL??this.config.defaultCacheTTL):void 0}writeRemoteCache(e,t,r){this.isRemoteCacheEnabled(r)&&this.writeCache(e,t)}isRemoteCacheEnabled(e){return this.config.enableCache&&(e.config.enableCache??!0)}writeCache(e,t){if(!this.cache.has(e)&&this.cache.size>=phr){const r=this.cache.keys().next();r.done||this.cache.delete(r.value)}this.cache.set(e,{data:t,timestamp:Date.now()})}async getByCategory(e){return(await this.getAllEntries()).filter(r=>r.categories?.includes(e))}async getByTag(e){return(await this.getAllEntries()).filter(r=>r.tags?.includes(e))}async getCategories(){const e=await this.getAllEntries(),t=new Set;for(const r of e)for(const n of r.categories??[])t.add(n);return Array.from(t).sort()}async getTags(){const e=await this.getAllEntries(),t=new Set;for(const r of e)for(const n of r.tags??[])t.add(n);return Array.from(t).sort()}toServerInfo(e){return{id:e.id,name:e.name,description:e.description,command:e.command,args:e.args,transport:e.transports?.[0]??"stdio",status:"stopped",tools:e.tools?.map(t=>({name:t,description:`Tool: ${t}`}))??[],metadata:{...e.metadata,version:e.version,author:e.author,license:e.license,homepage:e.homepage,repository:e.repository,npmPackage:e.npmPackage,requiredEnvVars:e.requiredEnvVars,categories:e.categories,tags:e.tags,verified:e.verified}}}addCustomEntry(e){this.customEntries.set(e.id,e),this.clearCache(),this.emit("entryAdded",{entry:e})}removeCustomEntry(e){const t=this.customEntries.delete(e);return t&&(this.clearCache(),this.emit("entryRemoved",{id:e})),t}addRegistry(e){this.config.registries.push(e),this.clearCache();const{authToken:t,...r}=e;this.emit("registryAdded",{config:r})}setRemoteLookup(e){this.config.remoteLookup=e,this.clearCache(),this.emit("remoteLookupChanged",{enabled:e})}clearCache(){this.cache.clear(),this.emit("cacheCleared")}checkRequiredEnvVars(e){const t=[];for(const r of e.requiredEnvVars??[])process.env[r]||t.push(r);return{ready:t.length===0,missing:t}}getInstallCommand(e){if(e.installCommand)return e.installCommand;if(e.npmPackage)return`npx -y ${e.npmPackage}`}async getPopularServers(e=10){return(await this.search({sortBy:"downloads",sortDirection:"desc",limit:e})).entries}async getVerifiedServers(){return(await this.search({verifiedOnly:!0})).entries}async getStatistics(){const e=await this.getAllEntries(),t=await this.getCategories(),r=await this.getTags();return{totalEntries:e.length,verifiedEntries:e.filter(n=>n.verified).length,categories:t.length,tags:r.length,customEntries:this.customEntries.size}}},Ome=new s5}}),Nme={};ue(Nme,{AgentExposureManager:()=>l5,exposeAgentAsTool:()=>a5,exposeAgentsAsTools:()=>hhr,exposeWorkflowAsTool:()=>u5,exposeWorkflowsAsTools:()=>fhr,globalAgentExposureManager:()=>Lme});function a5(e,t={}){const{prefix:r="agent",defaultAnnotations:n={},includeMetadataInDescription:o=!0,nameTransformer:i=y=>y.toLowerCase().replace(/\s+/g,"_"),wrapWithContext:s=!0,executionTimeout:a=3e5,enableLogging:u=!0}=t,l=i(e.name),c=r?`${r}_${l}`:l;let d=e.description;if(o&&e.metadata){const y=[];e.metadata.version&&y.push(`v${e.metadata.version}`),e.metadata.category&&y.push(`category: ${e.metadata.category}`),e.metadata.estimatedDuration&&y.push(`~${e.metadata.estimatedDuration}ms`),y.length>0&&(d+=` [${y.join(", ")}]`)}const p={...n,complexity:n.complexity??"complex",estimatedDuration:e.metadata?.estimatedDuration??n.estimatedDuration,costHint:e.metadata?.costHint??n.costHint,tags:[...n.tags??[],"agent",...e.metadata?.tags??[]]},m=e.inputSchema??{type:"object",properties:{}},h=async(y,v)=>{const w=Date.now();u&&f.debug(`[AgentExposure] Executing agent '${e.id}' as tool '${c}'`);try{const b=v?.config&&typeof v.config=="object"?v.config:{},E=s?{...v,config:{...b,sourceType:"mcp-exposed-agent",agentId:e.id,toolName:c}}:v??{},k=await kt(e.execute(y,E),a),A=Date.now()-w;return u&&f.debug(`[AgentExposure] Agent '${e.id}' completed in ${A}ms`),{success:!0,data:k,metadata:{agentId:e.id,toolName:c,executionTime:A,sourceType:"agent"}}}catch(b){const E=Date.now()-w,k=b instanceof Error?b:ve.toolExecutionFailed(c,new Error(String(b)));return u&&f.error(`[AgentExposure] Agent '${e.id}' failed after ${E}ms: ${k.message}`),{success:!1,error:k.message,metadata:{agentId:e.id,toolName:c,executionTime:E,sourceType:"agent"}}}};return{tool:{name:c,description:d,inputSchema:m,outputSchema:e.outputSchema,annotations:p,execute:h,metadata:{sourceType:"agent",sourceId:e.id,originalName:e.name,...e.metadata}},sourceType:"agent",sourceId:e.id,toolName:c}}function u5(e,t={}){const{prefix:r="workflow",defaultAnnotations:n={},includeMetadataInDescription:o=!0,nameTransformer:i=y=>y.toLowerCase().replace(/\s+/g,"_"),wrapWithContext:s=!0,executionTimeout:a=6e5,enableLogging:u=!0}=t,l=i(e.name),c=r?`${r}_${l}`:l;let d=e.description;if(o){const y=[];e.metadata?.version&&y.push(`v${e.metadata.version}`),e.steps?.length&&y.push(`${e.steps.length} steps`),e.metadata?.estimatedDuration&&y.push(`~${e.metadata.estimatedDuration}ms`),y.length>0&&(d+=` [${y.join(", ")}]`)}const p={...n,complexity:n.complexity??"complex",estimatedDuration:e.metadata?.estimatedDuration??n.estimatedDuration,idempotentHint:e.metadata?.idempotent??n.idempotentHint,tags:[...n.tags??[],"workflow",...e.metadata?.tags??[]]},m=e.inputSchema??{type:"object",properties:{}},h=async(y,v)=>{const w=Date.now();u&&f.debug(`[WorkflowExposure] Executing workflow '${e.id}' as tool '${c}'`);try{const b=v?.config&&typeof v.config=="object"?v.config:{},E=s?{...v,config:{...b,sourceType:"mcp-exposed-workflow",workflowId:e.id,toolName:c}}:v??{},k=await kt(e.execute(y,E),a),A=Date.now()-w;return u&&f.debug(`[WorkflowExposure] Workflow '${e.id}' completed in ${A}ms`),{success:!0,data:k,metadata:{workflowId:e.id,toolName:c,executionTime:A,sourceType:"workflow",stepsCount:e.steps?.length}}}catch(b){const E=Date.now()-w,k=b instanceof Error?b:ve.toolExecutionFailed(c,new Error(String(b)));return u&&f.error(`[WorkflowExposure] Workflow '${e.id}' failed after ${E}ms: ${k.message}`),{success:!1,error:k.message,metadata:{workflowId:e.id,toolName:c,executionTime:E,sourceType:"workflow"}}}};return{tool:{name:c,description:d,inputSchema:m,outputSchema:e.outputSchema,annotations:p,execute:h,metadata:{sourceType:"workflow",sourceId:e.id,originalName:e.name,steps:e.steps,...e.metadata}},sourceType:"workflow",sourceId:e.id,toolName:c}}function hhr(e,t={}){return e.map(r=>a5(r,t))}function fhr(e,t={}){return e.map(r=>u5(r,t))}var l5,Lme,$me=S({"src/lib/mcp/agentExposure.ts"(){"use strict";z(),Vr(),et(),l5=class{exposedTools=new Map;options;constructor(e={}){this.options=e}exposeAgent(e){const t=a5(e,this.options);return this.exposedTools.set(t.toolName,t),t.tool}exposeWorkflow(e){const t=u5(e,this.options);return this.exposedTools.set(t.toolName,t),t.tool}getExposedTools(){return Array.from(this.exposedTools.values()).map(e=>e.tool)}getExposedTool(e){return this.exposedTools.get(e)?.tool}getExposureResult(e){return this.exposedTools.get(e)}getToolsBySourceType(e){return Array.from(this.exposedTools.values()).filter(t=>t.sourceType===e).map(t=>t.tool)}unexpose(e){return this.exposedTools.delete(e)}clear(){this.exposedTools.clear()}getStatistics(){const e=Array.from(this.exposedTools.values());return{totalExposed:e.length,exposedAgents:e.filter(t=>t.sourceType==="agent").length,exposedWorkflows:e.filter(t=>t.sourceType==="workflow").length,toolNames:e.map(t=>t.toolName)}}},Lme=new l5}}),ghr={};ue(ghr,{ToolIntegrationManager:()=>p5,confirmationMiddleware:()=>Bme,createElicitationContext:()=>c5,createRetryMiddleware:()=>whr,createTimeoutMiddleware:()=>vhr,createToolMiddlewareChain:()=>Fme,globalToolIntegrationManager:()=>Gme,loggingMiddleware:()=>Ume,validationMiddleware:()=>zme,wrapToolWithElicitation:()=>d5,wrapToolsWithElicitation:()=>yhr});function c5(e,t,r){return{confirm:async(n,o)=>r.confirm(n,{toolName:e,serverId:t,confirmLabel:o?.confirmLabel,cancelLabel:o?.cancelLabel}),getText:async(n,o)=>r.getText(n,{toolName:e,placeholder:o?.placeholder,defaultValue:o?.defaultValue}),select:async(n,o)=>r.select(n,o,{toolName:e}),multiSelect:async(n,o)=>r.multiSelect(n,o,{toolName:e}),form:async(n,o)=>r.form(n,o,{toolName:e,serverId:t}),request:async n=>r.request({...n,toolName:e,serverId:t})}}function d5(e,t={}){const{elicitationManager:r,autoConfirmDestructive:n=!1,elicitationTimeout:o=6e4,enableLogging:i=!0}=t,s=r??new __({defaultTimeout:o});return{...e,execute:async(a,u)=>{const c=u?.config?.serverId,d=c5(e.name,c,s);if((e.annotations?.requiresConfirmation||e.annotations?.destructiveHint)&&!n&&(i&&f.debug(`[ToolIntegration] Tool '${e.name}' requires confirmation`),!await d.confirm(`This operation (${e.name}) ${e.annotations?.destructiveHint?"is destructive and ":""}requires confirmation. Do you want to proceed?`,{confirmLabel:"Yes, proceed",cancelLabel:"Cancel"})))return{success:!1,error:"Operation cancelled by user",metadata:{toolName:e.name,cancelled:!0}};const m={...u,elicitation:d,toolMeta:{name:e.name,serverId:c,annotations:e.annotations}};return e.execute(a,m)}}}function yhr(e,t={}){return e.map(r=>d5(r,t))}function Fme(e){return async(t,r,n,o)=>{const i=async s=>{if(s>=e.length)return o();const a=e[s];return a(t,r,n,()=>i(s+1))};return i(0)}}function vhr(e){return async(t,r,n,o)=>Ge(o(),e,ve.toolTimeout(t.name,e))}function whr(e,t=1e3){return async(r,n,o,i)=>{if(!(r.annotations?.idempotentHint||r.annotations?.readOnlyHint))return i();const a=Math.max(0,e);let u;for(let l=0;l<=a;l++)try{return await i()}catch(c){u=c instanceof Error?c:ve.toolExecutionFailed(r.name,new Error(String(c))),l<a&&(f.warn(`[ToolMiddleware] Tool '${r.name}' failed, retrying (${l+1}/${a})`),await new Promise(d=>setTimeout(d,t*(l+1))))}throw u??ve.toolExecutionFailed(r.name,new Error("Retry middleware exhausted without captured error"))}}var Ume,Bme,zme,p5,Gme,bhr=S({"src/lib/mcp/toolIntegration.ts"(){"use strict";Rme(),et(),z(),Ume=async(e,t,r,n)=>{const o=Date.now();f.debug(`[ToolMiddleware] Executing tool '${e.name}'`);try{const i=await n(),s=Date.now()-o;return f.debug(`[ToolMiddleware] Tool '${e.name}' completed in ${s}ms`),i}catch(i){const s=Date.now()-o;throw f.error(`[ToolMiddleware] Tool '${e.name}' failed after ${s}ms:`,i),i}},Bme=async(e,t,r,n)=>r.elicitation?.confirm&&(e.annotations?.destructiveHint||e.annotations?.requiresConfirmation)&&!await r.elicitation.confirm(`Confirm execution of ${e.name}?`)?{success:!1,error:"Operation cancelled by user",metadata:{cancelled:!0}}:n(),zme=async(e,t,r,n)=>{if(!e.inputSchema)return n();const o=e.inputSchema,i=o.required??[],s=o.properties??{},a=t??{},u=[];for(const l of i)a[l]===void 0&&u.push(l);if(u.length>0){const l=u.map(d=>{const p=s[d];return{name:d,label:d,type:p?.type??"text",required:!0,description:p?.description}}),c=await r.elicitation.form(`Missing required parameters for ${e.name}`,l);if(!c)return{success:!1,error:`Missing required parameters: ${u.join(", ")}`,metadata:{missingParams:u}};Object.assign(a,c)}return n()},p5=class{elicitationManager;middlewares=[];wrappedTools=new Map;constructor(e){this.elicitationManager=e??new __}setElicitationHandler(e){this.elicitationManager.setHandler(e)}use(e){return this.middlewares.push(e),this}registerTool(e){const t=d5(e,{elicitationManager:this.elicitationManager});return this.wrappedTools.set(e.name,t),t}async executeTool(e,t,r){const n=this.wrappedTools.get(e);if(!n)throw ve.toolNotFound(e,Array.from(this.wrappedTools.keys()));const o=t&&typeof t=="object"?t:{},s=r?.config?.serverId,a=c5(e,s,this.elicitationManager),u={...r,elicitation:a,toolMeta:{name:e,serverId:s,annotations:n.annotations}};return this.middlewares.length===0?n.execute(o,u):Fme(this.middlewares)(n,o,u,()=>n.execute(o,u))}getTool(e){return this.wrappedTools.get(e)}getAllTools(){return Array.from(this.wrappedTools.values())}getElicitationManager(){return this.elicitationManager}},Gme=new p5}}),qme={};ue(qme,{TOOL_COMPATIBILITY:()=>Wme,batchConvertToMCP:()=>Ehr,batchConvertToNeuroLink:()=>Shr,createToolFromFunction:()=>khr,mcpProtocolToolToServerTool:()=>Thr,mcpToolToNeuroLink:()=>Vme,neuroLinkToolToMCP:()=>jme,sanitizeToolName:()=>Hme,serverToolToMCPProtocol:()=>_hr,validateToolName:()=>Ahr});function jme(e,t={}){const{inferAnnotations:r=!0,defaultAnnotations:n={},preserveMetadata:o=!0,namespacePrefix:i}=t,s=i?`${i}_${e.name}`:e.name,a=r?Vp({name:e.name,description:e.description}):{},u={...n,...a};e.tags?.length&&(u.tags=[...new Set([...u.tags??[],...e.tags])]);const l=e.parameters??{type:"object",properties:{}},c=o?{...e.metadata}:{};return e.category&&(c.category=e.category),e.isAsync!==void 0&&(c.isAsync=e.isAsync),{name:s,description:e.description,inputSchema:l,annotations:u,execute:e.execute,metadata:c}}function Vme(e,t={}){const{removeNamespacePrefix:r}=t;let n=e.name;return r&&e.name.startsWith(`${r}_`)&&(n=e.name.slice(r.length+1)),{name:n,description:e.description,parameters:e.inputSchema,execute:e.execute,category:e.metadata?.category,tags:e.annotations?.tags,metadata:e.metadata}}function Thr(e,t,r={}){const{inferAnnotations:n=!0,defaultAnnotations:o={}}=r,i=e.annotations??{},s=n?Vp({name:e.name,description:e.description??""}):{},a={...o,...s,title:i.title??s.title??o.title,readOnlyHint:i.readOnlyHint??s.readOnlyHint??o.readOnlyHint,destructiveHint:i.destructiveHint??s.destructiveHint??o.destructiveHint,idempotentHint:i.idempotentHint??s.idempotentHint??o.idempotentHint,openWorldHint:i.openWorldHint??s.openWorldHint??o.openWorldHint};return{name:e.name,description:e.description??"No description provided",inputSchema:e.inputSchema,annotations:a,execute:t}}function _hr(e){const t={};e.annotations?.title&&(t.title=e.annotations.title),e.annotations?.readOnlyHint!==void 0&&(t.readOnlyHint=e.annotations.readOnlyHint),e.annotations?.destructiveHint!==void 0&&(t.destructiveHint=e.annotations.destructiveHint),e.annotations?.idempotentHint!==void 0&&(t.idempotentHint=e.annotations.idempotentHint),e.annotations?.openWorldHint!==void 0&&(t.openWorldHint=e.annotations.openWorldHint);const r=e.inputSchema??{type:"object",properties:{}};return{name:e.name,description:e.description,inputSchema:{type:"object",properties:r.properties??{},required:"required"in r?r.required:void 0},annotations:Object.keys(t).length>0?t:void 0}}function Ehr(e,t={}){return e.map(r=>jme(r,t))}function Shr(e,t={}){return e.map(r=>Vme(r,t))}function khr(e,t,r,n){const o=Vp({name:e,description:t});return{name:e,description:t,inputSchema:n?.parameters??{type:"object",properties:{}},annotations:{...o,...n?.annotations},execute:async(i,s)=>await kt(r(i,s),3e4,`Tool '${e}' execution timed out after 30000ms`),metadata:n?.metadata}}function Ahr(e){const t=[];return!e||typeof e!="string"?t.push("Tool name is required and must be a string"):(e.length>64&&t.push("Tool name must be 64 characters or less"),/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e)||t.push("Tool name must start with a letter or underscore and contain only alphanumeric characters, underscores, and hyphens")),{valid:t.length===0,errors:t}}function Hme(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return/^[a-zA-Z_]/.test(t)||(t=`_${t}`),t.length>64&&(t=t.slice(0,64)),t}var Wme,m5=S({"src/lib/mcp/toolConverter.ts"(){"use strict";$C(),Vr(),Wme={MCP_2024_11_05:{annotations:!0,inputSchema:!0,outputSchema:!1,streamingResults:!1,batchExecution:!1},NEUROLINK:{annotations:!0,inputSchema:!0,outputSchema:!0,streamingResults:!0,batchExecution:!0,categories:!0,tags:!0}}}}),E_,Uy,xhr,nSn=S({async"src/lib/core/redisConversationMemoryManager.ts"(){"use strict";Kt(),tr(),qt(),Dx(),G0(),ctr(),QKt(),await Oc(),lt(),et(),iT(),z(),sJt(),L3(),V6(),E_=Be.redis,Uy=5e3,xhr=class{config;isInitialized=!1;summarizationEngine=new pie;redisConfig;redisClient=null;pendingToolExecutions=new Map;titleGenerationInProgress=new Set;summarizationInProgress=new Set;constructor(e,t={}){this.config=e,this.redisConfig=tue(t)}async initialize(){if(this.isInitialized){f.debug("[RedisConversationMemoryManager] Already initialized, skipping");return}await E_.startActiveSpan("memory.initialize",{kind:hn.CLIENT,attributes:{"redis.host":this.redisConfig.host,"redis.port":this.redisConfig.port,"redis.key_prefix":this.redisConfig.keyPrefix}},async e=>{try{f.debug("[RedisConversationMemoryManager] Initializing with config",{host:this.redisConfig.host,port:this.redisConfig.port,keyPrefix:this.redisConfig.keyPrefix,ttl:this.redisConfig.ttl}),this.redisClient=await Xae(this.redisConfig),this.isInitialized=!0,f.info("RedisConversationMemoryManager initialized",{storage:"redis",host:this.redisConfig.host,port:this.redisConfig.port,maxSessions:this.config.maxSessions,maxTurnsPerSession:this.config.maxTurnsPerSession}),f.debug("[RedisConversationMemoryManager] Redis client created successfully",{clientType:this.redisClient?.constructor?.name||"unknown",isConnected:!!this.redisClient})}catch(t){throw e.setStatus({code:qe.ERROR,message:t instanceof Error?t.message:String(t)}),e.recordException(t instanceof Error?t:new Error(String(t))),f.error("[RedisConversationMemoryManager] Failed to initialize",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0,config:{host:this.redisConfig.host,port:this.redisConfig.port}}),new Eu("Failed to initialize Redis conversation memory","CONFIG_ERROR",{error:t instanceof Error?t.message:String(t)})}finally{e.end()}})}get canPersist(){return this.isInitialized&&this.redisClient!==null&&this.redisClient.isOpen}get isRedisConfigured(){return this.redisClient!==null&&this.redisClient.isOpen}getHealthStatus(){return{initialized:this.isInitialized,connected:this.redisClient?.isOpen??!1,host:this.redisConfig.host,keyPrefix:this.redisConfig.keyPrefix}}async getSession(e,t,r){if(await this.ensureInitialized(),!this.redisClient)return;const n=this.redisClient;return E_.startActiveSpan("memory.getSession",{kind:hn.CLIENT,attributes:{"session.id":e}},async o=>{t&&o.setAttribute("user.id",t);try{const i=ka(this.redisConfig,e,t),s=await Ge(n.get(i),Uy),a=await this.hydrateMessages(ru(s||null),i);if(!a){o.setAttribute("session.found",!1);return}o.setAttribute("session.found",!0);const u=s?Buffer.byteLength(s,"utf8"):0,l=a.messages.length,c=!!a.summarizedUpToMessageId,d=c?a.messages.findIndex(m=>m.id===a.summarizedUpToMessageId):-1,p=c&&d!==-1?l-d-1:l;return o.setAttribute("message.count",l),o.setAttribute("blob.size_bytes",u),f.info("[ConversationMemory] Session loaded",{requestId:r,sessionId:e,blobSizeBytes:u,messageCount:l,hasSummary:c,recentMessageCount:p}),u>512*1024&&f.warn("[ConversationMemory] Large session blob",{requestId:r,sessionId:e,blobSizeBytes:u,messageCount:l}),{sessionId:a.sessionId,userId:a.userId,messages:a.messages,summarizedUpToMessageId:a.summarizedUpToMessageId,summarizedMessage:a.summarizedMessage,tokenThreshold:a.tokenThreshold,lastTokenCount:a.lastTokenCount,lastCountedAt:a.lastCountedAt,lastApiTokenCount:a.lastApiTokenCount,createdAt:new Date(a.createdAt).getTime(),lastActivity:new Date(a.updatedAt).getTime()}}catch(i){o.setStatus({code:qe.ERROR,message:i instanceof Error?i.message:String(i)}),o.recordException(i instanceof Error?i:new Error(String(i))),f.error("[RedisConversationMemoryManager] Failed to get session",{sessionId:e,userId:t,error:i instanceof Error?i.message:String(i)});return}finally{o.end()}})}async getSessionRaw(e,t){try{if(await this.ensureInitialized(),!this.redisClient)return null;const r=ka(this.redisConfig,e,t),n=await this.redisClient.get(r);return this.hydrateMessages(ru(n||null),r)}catch(r){return f.error("[RedisConversationMemoryManager] Failed to get raw session",{sessionId:e,userId:t,error:r instanceof Error?r.message:String(r)}),null}}async getUserSessions(e){if(await this.ensureInitialized(),!this.redisClient)return f.warn("[RedisConversationMemoryManager] Redis client not available",{userId:e}),[];try{const t=Zae(this.redisConfig,e),r=await this.redisClient.sMembers(t);return Array.from(r).map(String)}catch(t){return f.error("[RedisConversationMemoryManager] Failed to get user sessions",{userId:e,error:t instanceof Error?t.message:String(t)}),[]}}async addUserSession(e,t){if(!(!this.redisClient||!e))try{const r=Zae(this.redisConfig,e);await $hn(this.redisClient,r,t,this.redisConfig.ttl)}catch(r){f.error("[RedisConversationMemoryManager] Failed to add session to user set",{userId:e,sessionId:t,error:r instanceof Error?r.message:String(r)})}}async removeUserSession(e,t){if(!this.redisClient||!e)return!1;try{const r=Zae(this.redisConfig,e),n=await this.redisClient.sRem(r,t);return Number(n)>0}catch(r){return f.error("[RedisConversationMemoryManager] Failed to remove session from user set",{userId:e,sessionId:t,error:r instanceof Error?r.message:String(r)}),!1}}generateTimestamp(){return new Date().toISOString()}async storeToolExecution(e,t,r,n,o){f.debug("[RedisConversationMemoryManager] Storing tool execution temporarily",{sessionId:e,userId:t,toolCallsCount:r?.length||0,toolResultsCount:n?.length||0});try{const i=t||"randomUser",s=`${e}:${i}`,a={toolCalls:(r||[]).map(l=>({...l,timestamp:o})),toolResults:(n||[]).map(l=>({...l,timestamp:o})),timestamp:Date.now()},u=this.pendingToolExecutions.get(s);u&&(f.debug("[RedisConversationMemoryManager] Merging with existing pending tool data",{sessionId:e,existingToolCalls:u.toolCalls.length,existingToolResults:u.toolResults.length,newToolCalls:r?.length||0,newToolResults:n?.length||0}),a.toolCalls=[...u.toolCalls,...a.toolCalls],a.toolResults=[...u.toolResults,...a.toolResults]),this.pendingToolExecutions.set(s,a),f.debug("[RedisConversationMemoryManager] Tool execution stored temporarily",{sessionId:e,userId:i,pendingKey:s,totalToolCalls:a.toolCalls.length,totalToolResults:a.toolResults.length}),this.cleanupStalePendingData()}catch(i){f.error("[RedisConversationMemoryManager] Failed to store tool execution temporarily",{sessionId:e,error:i instanceof Error?i.message:String(i)})}}async storeConversationTurn(e){return f.debug("[RedisConversationMemoryManager] Storing conversation turn",{sessionId:e.sessionId,userId:e.userId}),await this.ensureInitialized(),E_.startActiveSpan("memory.storeTurn",{kind:hn.CLIENT,attributes:{"session.id":e.sessionId,...e.userId&&{"user.id":e.userId}}},async t=>{try{if(!this.redisClient)throw new Error("Redis client not initialized");const r=ka(this.redisConfig,e.sessionId,e.userId),n=await this.redisClient.get(r);let o=await this.hydrateMessages(ru(n),r);if(oJt(o?.messages??[],e.turnId))return;const i=s1(o),s=o?.messages.length??0,a=new Date().toISOString(),u=e.userId||"randomUser";if(o)o.updatedAt=a;else{const h=`${e.sessionId}:${u}`,g=yt.bind(yt.active(),async()=>{if(!this.titleGenerationInProgress.has(h)){this.titleGenerationInProgress.add(h);try{const y=await this.generateConversationTitle(e.userMessage),v=ka(this.redisConfig,e.sessionId,e.userId||void 0),w=await this.redisClient?.get(v),b=ru(w||null);if(b){b.title=y,b.updatedAt=new Date().toISOString();const E=Qae(b);this.redisClient&&await eue(this.redisClient,v,E,this.redisConfig.ttl)}}catch(y){f.warn("[RedisConversationMemoryManager] Failed to generate conversation title in background",{sessionId:e.sessionId,userId:u,error:y instanceof Error?y.message:String(y)})}finally{this.titleGenerationInProgress.delete(h)}}});setImmediate(g),o={id:st(),title:"New Conversation",sessionId:e.sessionId,userId:u,createdAt:e.startTimeStamp?.toISOString()||a,updatedAt:e.startTimeStamp?.toISOString()||a,messages:[]}}const l=e.providerDetails?OKt(e.providerDetails.provider,e.providerDetails.model,this.config.tokenThreshold,o.tokenThreshold):this.config.tokenThreshold||5e4,c={...nJt(tJt(e)),timestamp:e.startTimeStamp?.toISOString()||this.generateTimestamp(),role:"user",content:e.userMessage};o.messages.push(c),await this.flushPendingToolData(o,e.sessionId,u),e.skillMessages&&e.skillMessages.length>0&&o.messages.push(...e.skillMessages);const d={...nJt(rJt(e,e.thoughtSignature)),timestamp:this.generateTimestamp(),role:"assistant",content:e.aiResponse,events:e.events||void 0};o.messages.push(d),e.tokenUsage&&(o.lastApiTokenCount=e.tokenUsage),f.info("[RedisConversationMemoryManager] Added new messages",{sessionId:o.sessionId,userId:o.userId});const p=e.enableSummarization!==void 0?e.enableSummarization:this.config.enableSummarization;if(await this.persistConversation(o,e.sessionId,e.userId,i?s:void 0),p){const h=e.userId||"randomUser",g=`${e.sessionId}:${h}`;if(this.summarizationInProgress.has(g))f.debug("[RedisConversationMemoryManager] Summarization already in progress, skipping",{sessionId:e.sessionId,userId:h});else{const y=yt.bind(yt.active(),async()=>{try{await this.checkAndSummarize(o,l,e.sessionId,e.userId,e.requestId)}catch(v){f.error("Background summarization failed",{sessionId:o.sessionId,error:v instanceof Error?v.message:String(v)})}});setImmediate(y)}}const m=Buffer.byteLength(q6(o),"utf8");f.info("[ConversationMemory] Turn stored",{requestId:e.requestId,sessionId:e.sessionId,blobSizeBytes:m,totalMessages:o.messages.length,userMsgChars:e.userMessage.length,assistantMsgChars:e.aiResponse.length}),m>512*1024&&f.warn("[ConversationMemory] Large session blob",{requestId:e.requestId,sessionId:e.sessionId,blobSizeBytes:m,messageCount:o.messages.length}),e.userId&&await this.addUserSession(e.userId,e.sessionId),t.setAttribute("message.count",o.messages.length),t.setStatus({code:qe.OK}),f.debug("[RedisConversationMemoryManager] Successfully stored conversation turn",{sessionId:e.sessionId,totalMessages:o.messages.length,title:o.title})}catch(r){throw t.setStatus({code:qe.ERROR,message:r instanceof Error?r.message:String(r)}),t.recordException(r instanceof Error?r:new Error(String(r))),new Eu(`Failed to store conversation turn in Redis for session ${e.sessionId}`,"STORAGE_ERROR",{sessionId:e.sessionId,error:r instanceof Error?r.message:String(r)})}finally{t.end()}})}async checkAndSummarize(e,t,r,n,o){const i=n||"randomUser",s=`${r}:${i}`;if(this.summarizationInProgress.has(s)){f.debug("[RedisConversationMemoryManager] Summarization already in progress, skipping",{sessionId:r,userId:i});return}this.summarizationInProgress.add(s);try{const a={sessionId:e.sessionId,userId:e.userId,messages:e.messages,summarizedUpToMessageId:e.summarizedUpToMessageId,summarizedMessage:e.summarizedMessage,tokenThreshold:e.tokenThreshold,lastTokenCount:e.lastTokenCount,lastCountedAt:e.lastCountedAt,createdAt:new Date(e.createdAt).getTime(),lastActivity:new Date(e.updatedAt).getTime()},u=await this.summarizationEngine.checkAndSummarize(a,t,this.config,"[RedisConversationMemoryManager]",o);if(e.lastTokenCount=a.lastTokenCount,e.lastCountedAt=a.lastCountedAt,u&&(e.summarizedUpToMessageId=a.summarizedUpToMessageId,e.summarizedMessage=a.summarizedMessage,this.redisClient)){const l=ka(this.redisConfig,r,n),c=await this.redisClient.get(l);if(c){const d=ru(c);if(d){d.summarizedUpToMessageId=e.summarizedUpToMessageId,d.summarizedMessage=e.summarizedMessage,d.lastTokenCount=e.lastTokenCount,d.lastCountedAt=e.lastCountedAt;const p=s1(d)?q6(d):Qae(d);await eue(this.redisClient,l,p,this.redisConfig.ttl)}}}}catch(a){f.error("Token counting or summarization failed",{sessionId:e.sessionId,error:a instanceof Error?a.message:String(a)})}finally{this.summarizationInProgress.delete(s)}}isConversationBlobKey(e){return!Uhn(e)&&!e.endsWith(":sessions")&&!e.startsWith(this.redisConfig.userSessionsKeyPrefix)}async hydrateMessages(e,t){if(!e||!s1(e)||!this.redisClient)return e;const r=await Ge(this.redisClient.lRange(`${t}${AT}`,0,-1),Uy);return e.messages=Bhn(r.map(n=>n.toString())),e}async countMessages(e,t){return!s1(e)||!this.redisClient?e.messages.length:Number(await Ge(this.redisClient.lLen(`${t}${AT}`),Uy))}async loadConversation(e,t){if(!this.redisClient)return null;const r=ka(this.redisConfig,e,t);return this.hydrateMessages(ru(await this.redisClient.get(r)),r)}async persistConversation(e,t,r,n){if(!this.redisClient)return;const o=ka(this.redisConfig,t,r),i=Fhn(this.redisConfig,t,r),s=this.redisClient.multi();n===void 0&&s.del(i);const a=n===void 0?e.messages:e.messages.slice(n);a.length>0&&s.rPush(i,zhn(a)),s.set(o,q6(e)),this.redisConfig.ttl>0&&(s.expire(o,this.redisConfig.ttl),s.expire(i,this.redisConfig.ttl)),await Ge(s.exec(),Uy)}async buildContextMessages(e,t,r,n){if(f.debug("[RedisConversationMemoryManager] Building context messages",{sessionId:e,userId:t,enableSummarization:r}),await this.ensureInitialized(),!this.redisClient)return f.warn("[RedisConversationMemoryManager] Redis client not available in buildContextMessages"),[];const o=this.redisClient;return E_.startActiveSpan("memory.buildContext",{kind:hn.CLIENT,attributes:{"session.id":e,...t&&{"user.id":t}}},async i=>{try{f.info("[RedisConversationMemoryManager] Building context messages",{sessionId:e,userId:t,method:"buildContextMessages"});const s=ka(this.redisConfig,e,t),a=await Ge(o.get(s),Uy),u=await this.hydrateMessages(ru(a||null),s);if(f.debug("[RedisConversationMemoryManager] Retrieved conversation for context building",{sessionId:e,userId:t,conversationFound:!!u}),!u)return i.setAttribute("session.found",!1),i.setStatus({code:qe.OK}),[];const l={sessionId:u.sessionId,userId:u.userId,messages:u.messages,summarizedUpToMessageId:u.summarizedUpToMessageId,summarizedMessage:u.summarizedMessage,tokenThreshold:u.tokenThreshold,lastTokenCount:u.lastTokenCount,lastCountedAt:u.lastCountedAt,createdAt:new Date(u.createdAt).getTime(),lastActivity:new Date(u.updatedAt).getTime()},c=eie(l,n);f.debug("[RedisConversationMemoryManager] Built context messages from pointer",{sessionId:e,userId:t,contextMessageCount:c.length,pointerMessageId:l.summarizedUpToMessageId||"none"});const d=this.config?.contextCompaction?.sendToolPreview===!0,p=c.map(m=>{if(m.role!=="tool_result")return m;const h=d&&m.metadata?.toolOutputPreview?m.metadata.toolOutputPreview:m.content;let g=m.result;if(m.result&&m.result.result===void 0){let y=h;try{y=JSON.parse(h)}catch{}g={...m.result,result:y}}return f.debug("[RedisConversationMemoryManager] Processing tool_result message for context",{sessionId:e,userId:t,messageId:m.id,sendToolPreview:d,hasPreview:!!m.metadata?.toolOutputPreview,contentLength:h?String(h).length:0,resultHydrated:g!==m.result}),{...m,content:h,result:g}});return i.setAttribute("context.message_count",p.length),i.setStatus({code:qe.OK}),f.info("[RedisConversationMemoryManager] Retrieved context messages",{sessionId:e,userId:t}),p}catch(s){throw i.setStatus({code:qe.ERROR,message:s instanceof Error?s.message:String(s)}),i.recordException(s instanceof Error?s:new Error(String(s))),s}finally{i.end()}})}async getUserSessionMetadata(e,t){if(f.debug("[RedisConversationMemoryManager] Getting user session metadata",{userId:e,sessionId:t}),await this.ensureInitialized(),!this.redisClient)return f.warn("[RedisConversationMemoryManager] Redis client not available",{userId:e,sessionId:t}),null;try{const r=ka(this.redisConfig,t,e),n=await this.redisClient.get(r);if(!n)return f.debug("[RedisConversationMemoryManager] No session data found",{userId:e,sessionId:t,sessionKey:r}),null;const o=ru(n);return o?{id:o.sessionId,title:o.title,createdAt:o.createdAt,updatedAt:o.updatedAt,metadata:o.additionalMetadata?.agenticLoopReports?{agenticLoopReports:o.additionalMetadata.agenticLoopReports}:void 0}:(f.debug("[RedisConversationMemoryManager] No valid conversation data found",{userId:e,sessionId:t,sessionKey:r}),null)}catch(r){return f.error("[RedisConversationMemoryManager] Failed to get user session metadata",{userId:e,sessionId:t,error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0}),null}}async getUserSessionHistory(e,t){f.debug("[RedisConversationMemoryManager] Getting user session history via getUserSessionObject",{userId:e,sessionId:t});try{const r=await this.getUserSessionObject(e,t);return r?r.messages:(f.debug("[RedisConversationMemoryManager] No session object found, returning null",{userId:e,sessionId:t}),null)}catch(r){return f.error("[RedisConversationMemoryManager] Failed to get user session history via getUserSessionObject",{userId:e,sessionId:t,error:r instanceof Error?r.message:String(r),errorName:r instanceof Error?r.name:"UnknownError",stack:r instanceof Error?r.stack:void 0}),null}}async getUserSessionObject(e,t){if(f.debug("[RedisConversationMemoryManager] Getting complete user session object",{userId:e,sessionId:t,method:"getUserSessionObject"}),!e||typeof e!="string")return f.warn("[RedisConversationMemoryManager] Invalid userId provided",{userId:e,sessionId:t}),null;if(!t||typeof t!="string")return f.warn("[RedisConversationMemoryManager] Invalid sessionId provided",{userId:e,sessionId:t}),null;if(await this.ensureInitialized(),!this.redisClient)return f.warn("[RedisConversationMemoryManager] Redis client not available for getUserSessionObject",{userId:e,sessionId:t}),null;try{const r=ka(this.redisConfig,t,e),n=await this.redisClient.get(r);if(!n)return f.debug("[RedisConversationMemoryManager] No conversation data found in Redis",{userId:e,sessionId:t,sessionKey:r}),null;const o=await this.hydrateMessages(ru(n),r);return o?!o.messages||!Array.isArray(o.messages)?(f.warn("[RedisConversationMemoryManager] Invalid conversation structure - missing messages array",{userId:e,sessionId:t,hasMessages:!!o.messages,messagesType:typeof o.messages}),null):o:(f.debug("[RedisConversationMemoryManager] Failed to deserialize conversation data",{userId:e,sessionId:t,sessionKey:r,dataLength:n.length}),null)}catch(r){return f.error("[RedisConversationMemoryManager] Failed to get complete user session object",{userId:e,sessionId:t,error:r instanceof Error?r.message:String(r),errorName:r instanceof Error?r.name:"UnknownError",stack:r instanceof Error?r.stack:void 0}),null}}async generateConversationTitle(e){f.info("[RedisConversationMemoryManager] Generating conversation title",{userMessageLength:e.length,userMessagePreview:e.substring(0,100)});try{const t=new M_({conversationMemory:{enabled:!1}}),r=`Generate a clear, concise, and descriptive title (20-25 letters maximum) for a conversation based on the following user message.
|
|
1916
|
+
\u26A0\uFE0F CRITICAL: Content MUST fit within slide box. Keep text SHORT.`,Upr=5,Bpr=50,zpr=10,Gpr=5e3,qpr=Object.keys(kI),jpr=["business","students","technical","general"],Vpr=["professional","casual","educational","persuasive"],Hpr=["16:9","4:3"],ZF={content:{bulletStyle:"disc",baseFontSize:18},bullets:{bulletStyle:"disc",baseFontSize:18},agenda:{bulletStyle:"number",baseFontSize:18},"numbered-list":{bulletStyle:"number",baseFontSize:18},conclusion:{bulletStyle:"checkmark",baseFontSize:18},closing:{bulletStyle:"checkmark",baseFontSize:18},"two-column":{bulletStyle:"disc",baseFontSize:16},"three-column":{bulletStyle:"disc",baseFontSize:14},"split-content":{bulletStyle:"disc",baseFontSize:16},comparison:{bulletStyle:"arrow",baseFontSize:16},features:{bulletStyle:"none",baseFontSize:16},icons:{bulletStyle:"none",baseFontSize:16},default:{bulletStyle:"disc",baseFontSize:18}},mme=6e4,QF=3e4,hme=5,Ul=3e5}}),Rc,Ku,fme=S({"src/lib/features/ppt/pptError.ts"(){"use strict";et(),Rc={PLANNING_FAILED:"PPT_PLANNING_FAILED",INVALID_AI_RESPONSE:"PPT_INVALID_AI_RESPONSE",IMAGE_GENERATION_FAILED:"PPT_IMAGE_GENERATION_FAILED",ASSEMBLY_FAILED:"PPT_ASSEMBLY_FAILED",FILE_WRITE_FAILED:"PPT_FILE_WRITE_FAILED",INVALID_INPUT:"PPT_INVALID_INPUT",TIMEOUT:"PPT_TIMEOUT"},Ku=class extends Me{constructor(e,t,r,n){super({code:t,message:e,category:"execution",severity:"high",retriable:!1,context:{...r,originalMessage:n?.message},originalError:n}),this.name="PPTError"}}}}),Wpr={};ue(Wpr,{PPT_VALID_PROVIDERS:()=>d_,bufferToDataUrl:()=>AI,calculateFontSize:()=>tmr,createFormattedTextProps:()=>c_,ensureOutputDirectory:()=>Jpr,extractPPTContext:()=>tEn,generateOutputPath:()=>Kpr,getEffectivePPTProvider:()=>rEn,getFailureStage:()=>gme,getLayoutName:()=>Qpr,hasMarkdownFormatting:()=>l_,isLogoConfig:()=>Ypr,isObject:()=>Xpr,normalizeLogoConfig:()=>Zpr,parseMarkdownText:()=>u_,toError:()=>emr,validateImageBuffer:()=>yme});function tEn(e){const t=e.output?.ppt;if(!t)throw new Ku("PPT options are required when mode is 'ppt'",Rc.INVALID_INPUT,{field:"output.ppt"});let r;if(t.logoPath){if(Buffer.isBuffer(t.logoPath)||typeof t.logoPath=="string")r=t.logoPath;else if(typeof t.logoPath=="object"&&"data"in t.logoPath){const o=t.logoPath.data;r=Buffer.isBuffer(o)||typeof o=="string"?o:void 0}}const n=[];if(e.input?.images){for(const o of e.input.images)if(Buffer.isBuffer(o)||typeof o=="string")n.push(o);else if(typeof o=="object"&&"data"in o){const i=o.data;(Buffer.isBuffer(i)||typeof i=="string")&&n.push(i)}}return!r&&n.length>0&&(r=n[0]),{topic:e.input?.text||"",pages:t.pages,theme:t.theme??"AI will decide",audience:t.audience??"AI will decide",tone:t.tone??"AI will decide",generateAIImages:t.generateAIImages??!1,aspectRatio:t.aspectRatio||"16:9",outputPath:t.outputPath,logo:r,images:n.length>0?n:void 0,provider:e.provider,model:e.model}}async function rEn(e,t,r,n){const{ErrorFactory:o}=await Promise.resolve().then(()=>(et(),yk)),i=t.toLowerCase();if(d_.includes(i)){const s=e,a=r||s?.modelName||s?.getDefaultModel?.()||"";return f.debug("[PPT Utils] Current provider is valid for PPT",{provider:t,model:a}),{provider:e,providerName:t,modelName:a,wasAutoSelected:!1}}f.info("[PPT Utils] Current provider not valid for PPT, auto-selecting",{currentProvider:t});for(const s of d_)if(mpe(s)){f.info("[PPT Utils] Auto-selected PPT provider",{originalProvider:t,selectedProvider:s});const{AIProviderFactory:a}=await Promise.resolve().then(()=>(lu(),fR)),{withTimeout:u}=await Promise.resolve().then(()=>(et(),yk)),{PPT_GENERATION_TIMEOUT_MS:l}=await Promise.resolve().then(()=>(a_(),lme)),c=await u(a.createProvider(s,void 0,!0,n),l/4,o.toolTimeout("createProvider",l/4));return{provider:c,providerName:s,modelName:c.modelName,wasAutoSelected:!0}}throw o.invalidParameters("ppt-generation",new Error(`No PPT-compatible provider available. Configure one of: ${d_.join(", ")}`),{currentProvider:t,validProviders:d_})}function Kpr(e){const t=new Date().toISOString().replace(/[:.]/g,"-").substring(0,19),n=`${e.topic.substring(0,30).replace(/[^a-zA-Z0-9]/g,"_").toLowerCase()}_${t}.pptx`;return e.outputPath?e.outputPath.endsWith(".pptx")?e.outputPath:Nt(e.outputPath,n):Nt(process.cwd(),"output",n)}async function Jpr(e){const t=QV(e);try{const{withTimeout:r,ErrorFactory:n}=await Promise.resolve().then(()=>(et(),yk)),{PPT_GENERATION_TIMEOUT_MS:o}=await Promise.resolve().then(()=>(a_(),lme));await r(Aee(t,{recursive:!0}),o/8,n.toolTimeout("mkdirOutputDirectory",o/8))}catch(r){const n=r instanceof Error?r:new Error(String(r));throw new Ku(`Failed to create output directory: ${t}`,Rc.FILE_WRITE_FAILED,{directory:t},n)}}function Xpr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ypr(e){return Xpr(e)?"data"in e&&(Buffer.isBuffer(e.data)||typeof e.data=="string"):!1}function Zpr(e){return e===null?null:Buffer.isBuffer(e)||typeof e=="string"?{data:e,position:"bottom-right",width:1,height:.4,showOn:"all-slides"}:Ypr(e)?e:null}function Qpr(e){switch(e){case"16:9":return"LAYOUT_16x9";case"4:3":return"LAYOUT_4x3";default:return"LAYOUT_16x9"}}function emr(e){return e instanceof Error?e:new Error(String(e))}function gme(e){return e.contentPlan===null?"content-planning":e.slides===null?"slide-generation":e.outputPath===null?"pptx-assembly":"file-output"}function yme(e){return!e||e.length===0?{isValid:!1,mimeType:"",format:"",error:"Empty or undefined buffer"}:e.length<100?{isValid:!1,mimeType:"",format:"",error:`Buffer too small (${e.length} bytes)`}:e[0]===255&&e[1]===216&&e[2]===255?{isValid:!0,mimeType:"image/jpeg",format:"JPEG"}:e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71?{isValid:!0,mimeType:"image/png",format:"PNG"}:e[0]===71&&e[1]===73&&e[2]===70?{isValid:!0,mimeType:"image/gif",format:"GIF"}:e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e.length>12&&e.slice(8,12).toString()==="WEBP"?{isValid:!0,mimeType:"image/webp",format:"WebP"}:e[0]===66&&e[1]===77?{isValid:!0,mimeType:"image/bmp",format:"BMP"}:{isValid:!1,mimeType:"image/png",format:"unknown",error:`Unknown format (magic bytes: ${e.slice(0,4).toString("hex")})`}}function AI(e){const t=yme(e);return!t.isValid&&t.format===""?(f.warn("[bufferToDataUrl] Invalid image buffer",{error:t.error}),null):`data:${t.mimeType||"image/png"};base64,${e.toString("base64")}`}function u_(e){if(!e||typeof e!="string")return[{text:e||""}];const t=[],r=/(\*\*\*(.+?)\*\*\*|\*\*(.+?)\*\*|\*(.+?)\*)/g;let n=0;for(;;){const o=r.exec(e);if(o===null)break;o.index>n&&t.push({text:e.slice(n,o.index)}),o[2]?t.push({text:o[2],bold:!0,italic:!0}):o[3]?t.push({text:o[3],bold:!0}):o[4]&&t.push({text:o[4],italic:!0}),n=r.lastIndex}return n<e.length&&t.push({text:e.slice(n)}),t.length===0&&t.push({text:e}),t}function l_(e){return!e||typeof e!="string"?!1:/\*{1,3}[^*]+\*{1,3}/.test(e)}function c_(e,t){return e.map(r=>({text:r.text,options:{fontSize:t.fontSize,fontFace:t.fontFace,color:t.color,bold:r.bold||t.baseBold||!1,italic:r.italic||!1}}))}function tmr(e,t=18){return e<=5?t:e<=7?Math.max(12,t-2):e<=10?Math.max(12,t-4):12}var d_,vme=S({"src/lib/features/ppt/utils.ts"(){"use strict";_i(),Er(),lf(),z(),fme(),d_=["vertex","openai","azure","anthropic","google-ai","bedrock"]}});function nEn(e,t,r=!1){const n=t/72,o=.42,i=r?1.1:1,s=n*o*i;return e.length*s}function Bs(e,t,r,n=!0){if(e.addText(t,{x:Vt.title.x,y:Vt.title.y,w:Vt.title.w,h:Vt.title.h,fontSize:r.fonts.sizes.heading,fontFace:r.fonts.heading,color:r.colors.text.replace("#",""),bold:!0,fit:$t}),n){const o=nEn(t,r.fonts.sizes.heading,!0),i=Vt.title.w,a=Math.min(i,Math.max(1,o));e.addShape("rect",{x:Vt.title.x,y:Vt.title.y+Vt.title.h+.1,w:a,h:.03,fill:{color:r.colors.primary.replace("#","")}})}}function rmr(e){const{slide:t,bullets:r,startX:n,startY:o,width:i,theme:s,itemSpacing:a=.45}=e;if(!r||r.length===0)return;const u=Math.max(a,m_*2);r.forEach((l,c)=>{if(!l||!l.text)return;const d=l.bold||l.emphasis||!1,p=l.color?.replace("#","")||s.colors.text.replace("#","");if(l_(l.text)){const m=u_(l.text),h=[{text:"\u2022 ",options:{fontSize:s.fonts.sizes.body,fontFace:s.fonts.body,color:p}},...c_(m,{fontSize:s.fonts.sizes.body,fontFace:s.fonts.body,color:p,baseBold:d})];t.addText(h,{x:n,y:o+c*u,w:i,h:Math.max(.4,u-m_),fit:$t})}else{const m=`\u2022 ${l.text}`;t.addText(m,{x:n,y:o+c*u,w:i,h:Math.max(.4,u-m_),fontSize:s.fonts.sizes.body,fontFace:s.fonts.body,color:p,bold:d,fit:$t})}})}function nmr(e,t,r,n,o="content",i){if(!t||t.length===0)return;if(i?.useIndividualBullets){rmr({slide:e,bullets:t,startX:r.x,startY:r.y,width:r.w,theme:n,itemSpacing:i.itemSpacing??.45});return}const s=Epr(o),a=tmr(t.length,s.baseFontSize||n.fonts.sizes.body),u=[];t.forEach(l=>{if(!l||!l.text)return;const c=l.bulletStyle||s.bulletStyle||"disc",d=l.fontSize||a,p=l.color?.replace("#","")||n.colors.text.replace("#",""),m=l.bold??l.emphasis??!1;let h;if(l.icon?h={code:l.icon}:h=Spr(c),l_(l.text)){const g=u_(l.text),y=c_(g,{fontSize:d,fontFace:n.fonts.body,color:p,baseBold:m});u.push({text:y,options:{bullet:h,indentLevel:0,paraSpaceBefore:6,paraSpaceAfter:6}})}else u.push({text:l.text,options:{bullet:h,fontSize:d,fontFace:n.fonts.body,color:p,bold:m,indentLevel:0,paraSpaceBefore:6,paraSpaceAfter:6}});l.subBullets&&l.subBullets.length>0&&l.subBullets.forEach(g=>{if(l_(g)){const y=u_(g),v=c_(y,{fontSize:Math.max(10,d-2),fontFace:n.fonts.body,color:n.colors.muted.replace("#","")});u.push({text:v,options:{bullet:!0,indentLevel:1,paraSpaceBefore:3,paraSpaceAfter:3}})}else u.push({text:g,options:{bullet:!0,fontSize:Math.max(10,d-2),fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),indentLevel:1,paraSpaceBefore:3,paraSpaceAfter:3}})})}),e.addText(u,{x:r.x,y:r.y,w:r.w,h:r.h,valign:"top",fit:$t})}function wme(e,t,r){const n=yme(t);if(!n.isValid&&n.format===""){f.warn("[addImage] Invalid image buffer",{error:n.error});return}n.isValid||f.warn("[addImage] Image validation warning, attempting to add anyway",{error:n.error,mimeType:n.mimeType});const o=AI(t);if(!o){f.warn("[addImage] Failed to convert buffer to data URL");return}try{e.addImage({data:o,x:r.x,y:r.y,w:r.w,h:r.h,sizing:{type:"cover",w:r.w,h:r.h}})}catch(i){f.error("[addImage] Failed to add image to slide",{error:i instanceof Error?i.message:String(i)})}}function oEn(e){switch(e){case"chart-bar":return"bar";case"chart-line":return"line";case"chart-pie":return"pie";case"chart-area":return"area";default:return"bar"}}function iEn(e,t,r,n,o){const i=r.layoutOptions||{},s=i.title||{},a=i.subtitle||{},u=i.background||{},l=o?AI(o):null;if(l)e.background={data:l},e.addShape("rect",{x:0,y:0,w:"100%",h:"100%",fill:{color:"000000",transparency:40}});else if(u.color||u.useThemePrimary||u.useThemeSecondary){const m=u.useThemePrimary?n.colors.primary:u.useThemeSecondary?n.colors.secondary:u.color||n.colors.background;e.addShape("rect",{x:0,y:0,w:10,h:5.625,fill:{color:m.replace("#","")}})}const c=o||u.color||u.useThemePrimary||u.useThemeSecondary,d=c?"FFFFFF":n.colors.text.replace("#",""),p=c?"FFFFFF":n.colors.muted.replace("#","");e.addText(t,{x:s.x??.5,y:s.y??2,w:s.w??9,h:s.h??1.2,fontSize:s.fontSize??n.fonts.sizes.title,fontFace:n.fonts.heading,color:s.color?.replace("#","")??d,align:s.align??"center",bold:!0,fit:$t}),r.subtitle&&e.addText(r.subtitle,{x:a.x??.5,y:a.y??3.3,w:a.w??9,h:a.h??.6,fontSize:a.fontSize??n.fonts.sizes.subtitle,fontFace:n.fonts.body,color:a.color?.replace("#","")??p,align:a.align??"center",fit:$t})}function sEn(e,t,r,n){const o=r.layoutOptions||{},i=o.sectionNumber||{},s=o.title||{},a=o.subtitle||{},u=o.background||{};if(u.color&&e.addShape("rect",{x:0,y:0,w:10,h:5.625,fill:{color:u.color.replace("#","")}}),r.sectionNumber){const l=i.style==="watermark",c=i.style==="small";e.addText(String(r.sectionNumber).padStart(2,"0"),{x:i.x??(l?5.5:.5),y:i.y??(l?.5:1.5),w:l?5:2,h:l?4:1,fontSize:i.fontSize??(l?200:c?32:72),fontFace:n.fonts.heading,color:n.colors.primary.replace("#",""),bold:!0,align:l?"right":"left",transparency:l?70:0})}e.addText(t,{x:s.x??.5,y:s.y??2.5,w:s.w??9,h:s.h??1,fontSize:s.fontSize??n.fonts.sizes.title,fontFace:n.fonts.heading,color:n.colors.text.replace("#",""),bold:!0,align:s.align??"left"}),r.subtitle&&e.addText(r.subtitle,{x:a.x??.5,y:a.y??3.6,w:a.w??8,h:a.h??.6,fontSize:a.fontSize??n.fonts.sizes.subtitle,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:a.align??"left"})}function aEn(e,t,r,n,o){if(o){const s=AI(o);s&&(e.background={data:s},e.addShape("rect",{x:0,y:0,w:"100%",h:"100%",fill:{color:"000000",transparency:40}}))}const i=o?"FFFFFF":n.colors.text.replace("#","");if(e.addText(t||"Thank You!",{x:.5,y:1.8,w:9,h:1,fontSize:n.fonts.sizes.title,fontFace:n.fonts.heading,color:i,align:"center",bold:!0,fit:$t}),r.cta&&e.addText(r.cta,{x:.5,y:2.9,w:9,h:.5,fontSize:n.fonts.sizes.subtitle,fontFace:n.fonts.body,color:o?"FFFFFF":n.colors.muted.replace("#",""),align:"center",fit:$t}),r.contactInfo){const s=[];if(r.contactInfo.email&&s.push(`Email: ${r.contactInfo.email}`),r.contactInfo.website&&s.push(`Web: ${r.contactInfo.website}`),r.contactInfo.phone&&s.push(`Phone: ${r.contactInfo.phone}`),s.length>0&&e.addText(s.join(" \u2022 "),{x:.5,y:4.2,w:9,h:.4,fontSize:n.fonts.sizes.body,fontFace:n.fonts.body,color:i,align:"center",fit:$t}),r.contactInfo.social&&Array.isArray(r.contactInfo.social)&&r.contactInfo.social.length>0){const a=r.contactInfo.social.map(u=>`${u.platform||""}: ${u.handle||""}`).join(" \u2022 ");e.addText(a,{x:.5,y:4.7,w:9,h:.3,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:o?"CCCCCC":n.colors.muted.replace("#",""),align:"center"})}}}function bme(e){const{slide:t,title:r,content:n,layout:o,theme:i,imageBuffer:s,slideType:a="content"}=e;Bs(t,r,i);const u=s&&o.includes("image"),l=u?o.includes("left")?Vt.contentRight:Vt.contentLeft:Vt.contentFull;if(n.bullets&&n.bullets.length>0?nmr(t,n.bullets,l,i,a):n.body&&t.addText(n.body,{x:l.x,y:l.y,w:l.w,h:l.h,fontSize:i.fonts.sizes.body,fontFace:i.fonts.body,color:i.colors.text.replace("#",""),valign:"top"}),s&&u){const c=o.includes("left")?Vt.imageLeft:Vt.imageRight;wme(t,s,c)}}function uEn(e,t,r,n,o,i){if(n==="image-full-overlay"&&i){const s=AI(i);s?(e.background={data:s},e.addShape("rect",{x:0,y:0,w:"100%",h:"100%",fill:{color:"000000",transparency:50}}),e.addText(t,{x:.5,y:4.2,w:9,h:1,fontSize:o.fonts.sizes.heading,fontFace:o.fonts.heading,color:"FFFFFF",bold:!0,fit:$t})):Bs(e,t,o)}else n==="image-centered"||n==="image-full-overlay"?(Bs(e,t,o),i?wme(e,i,Vt.imageCentered):(e.addShape("rect",{x:1.5,y:1.8,w:7,h:3.5,fill:{color:o.colors.muted.replace("#",""),transparency:90},line:{color:o.colors.muted.replace("#",""),width:1,dashType:"dash"}}),e.addText("\u{1F4F7}",{x:1.5,y:2.8,w:7,h:1,fontSize:48,align:"center",valign:"middle",fit:$t}),e.addText("Image not available",{x:1.5,y:3.8,w:7,h:.5,fontSize:12,fontFace:o.fonts.body,color:o.colors.muted.replace("#",""),align:"center",fit:$t})),r.caption&&e.addText(r.caption,{x:.5,y:5,w:9,h:.4,fontSize:o.fonts.sizes.caption,fontFace:o.fonts.body,color:o.colors.muted.replace("#",""),align:"center",fit:$t})):bme({slide:e,title:t,content:r,layout:n,theme:o,imageBuffer:i})}function omr(e,t,r,n,o){Bs(e,t,n,!1);const i={headerY:o?.headerY??1.3,headerHeight:o?.headerHeight??.5,bulletsStartY:o?.bulletsStartY??2,columnGap:o?.columnGap??.3,highlightFirstColumn:o?.highlightFirstColumn??!0},s=r.length;if(s===0)return;const a=9,u=(s-1)*i.columnGap,l=(a-u)/s,c=.5;r.forEach((d,p)=>{if(!d)return;const m=c+p*(l+i.columnGap),h=i.highlightFirstColumn&&p===0;if(d.title){e.addShape("roundRect",{x:m,y:i.headerY,w:l,h:i.headerHeight,fill:{color:h?n.colors.primary.replace("#",""):n.colors.muted.replace("#","")},rectRadius:.05});const g=s<=2?n.fonts.sizes.body:n.fonts.sizes.body-2;e.addText(d.title,{x:m,y:i.headerY,w:l,h:i.headerHeight,fontSize:g,fontFace:n.fonts.heading,color:h?n.colors.textOnPrimary.replace("#",""):n.colors.text.replace("#",""),align:"center",bold:!0,valign:"middle",fit:$t})}d.bullets&&d.bullets.length>0&&rmr({slide:e,bullets:d.bullets,startX:m,startY:i.bulletsStartY,width:l,theme:n})})}function lEn(e,t,r,n,o,i){const s=[];r.leftColumn&&s.push(r.leftColumn),r.rightColumn&&s.push(r.rightColumn),s.length>0&&omr(e,t,s,o,{highlightFirstColumn:!0}),i&&!r.rightColumn?.bullets&&wme(e,i,Vt.columnRight)}function cEn(e,t,r,n){const o=[];r.leftColumn&&o.push(r.leftColumn),r.centerColumn&&o.push(r.centerColumn),r.rightColumn&&o.push(r.rightColumn),o.length>0&&omr(e,t,o,n,{highlightFirstColumn:!0})}function dEn(e,t,r,n){if(e.addText("\u201C",{x:.5,y:1,w:1,h:1,fontSize:120,fontFace:"Georgia",color:n.colors.primary.replace("#",""),fit:$t}),r.quote&&e.addText(r.quote,{x:Vt.quote.x,y:Vt.quote.y,w:Vt.quote.w,h:Vt.quote.h,fontSize:n.fonts.sizes.heading,fontFace:"Georgia",color:n.colors.text.replace("#",""),italic:!0,valign:"middle",fit:$t}),r.quoteAuthor){let o=`\u2014 ${r.quoteAuthor}`;r.quoteAuthorTitle&&(o+=`, ${r.quoteAuthorTitle}`),e.addText(o,{x:Vt.quoteAuthor.x,y:Vt.quoteAuthor.y,w:Vt.quoteAuthor.w,h:Vt.quoteAuthor.h,fontSize:n.fonts.sizes.body,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:"right",fit:$t})}}function pEn(e,t,r,n){if(Bs(e,t,n),!r.statistics||r.statistics.length===0)return;const o=r.statistics.slice(0,4),i=9/o.length;o.forEach((s,a)=>{const u=.5+a*i;if(e.addText(s.value,{x:u,y:Vt.statRow.y,w:i-.2,h:1.2,fontSize:48,fontFace:n.fonts.heading,color:n.colors.primary.replace("#",""),bold:!0,align:"center",fit:$t}),e.addText(s.label,{x:u,y:Vt.statRow.y+1.3,w:i-.2,h:.5,fontSize:n.fonts.sizes.body,fontFace:n.fonts.body,color:n.colors.text.replace("#",""),align:"center",fit:$t}),s.change||s.trend){const l=s.trend==="up"?"22C55E":s.trend==="down"?"EF4444":n.colors.muted.replace("#",""),c=s.trend==="up"?"(+)":s.trend==="down"?"(-)":"";e.addText(`${c} ${s.change||""}`,{x:u,y:Vt.statRow.y+1.8,w:i-.2,h:.4,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:l,align:"center",fit:$t})}})}function mEn(e,t,r,n,o){if(Bs(e,t,o),!r.chartData||!r.chartData.series||r.chartData.series.length===0){e.addText("No chart data available",{x:Vt.chart.x,y:Vt.chart.y+1,w:Vt.chart.w,h:1,fontSize:18,color:o.colors.muted.replace("#",""),align:"center",fit:$t});return}const i=r.chartData.series.filter(u=>u.name&&Array.isArray(u.labels)&&u.labels.length>0&&Array.isArray(u.values)&&u.values.length>0);if(i.length===0){e.addText("Invalid chart data format",{x:Vt.chart.x,y:Vt.chart.y+1,w:Vt.chart.w,h:1,fontSize:18,color:o.colors.muted.replace("#",""),align:"center",fit:$t});return}const s=oEn(n),a=i.map(u=>({name:u.name,labels:u.labels,values:u.values}));e.addChart(s,a,{x:Vt.chart.x,y:Vt.chart.y,w:Vt.chart.w,h:Vt.chart.h,showTitle:!!r.chartData.title,title:r.chartData.title,showLegend:r.chartData.legendPosition!=="none",legendPos:umr[r.chartData.legendPosition||"bottom"]||"b",showValue:r.chartData.showLabels,chartColors:[o.colors.primary.replace("#",""),o.colors.secondary.replace("#",""),o.colors.accent.replace("#","")]})}function hEn(e,t,r,n){if(Bs(e,t,n),!r.tableData)return;const{headers:o,rows:i,hasHeader:s}=r.tableData,a=[];s&&o&&a.push(o.map(u=>({text:u,options:{bold:!0,fill:{color:n.colors.primary.replace("#","")},color:n.colors.textOnPrimary.replace("#",""),align:"center"}}))),i.forEach((u,l)=>{a.push(u.map(c=>({text:c.text,options:{fill:{color:l%2===0?"F8FAFC":"FFFFFF"},color:n.colors.text.replace("#",""),align:c.align||"left"}})))}),e.addTable(a,{x:Vt.chart.x,y:Vt.chart.y,w:Vt.chart.w,colW:Array(o?.length||i[0]?.length||1).fill(Vt.chart.w/(o?.length||i[0]?.length||1)),fontSize:n.fonts.sizes.body-2,fontFace:n.fonts.body,border:{pt:.5,color:"E2E8F0"},autoPage:!0}),r.tableData.caption&&e.addText(r.tableData.caption,{x:.5,y:5.1,w:9,h:.3,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:"center"})}function fEn(e,t,r,n){if(Bs(e,t,n),!r.timeline?.items)return;const o=r.timeline.items.slice(0,5);r.timeline.orientation!=="vertical"?gEn(e,o,n):yEn(e,o,n)}function gEn(e,t,r){const n=8/t.length,o=2.8;e.addShape("rect",{x:1,y:o,w:8,h:.02,fill:{color:r.colors.primary.replace("#","")}}),t.forEach((i,s)=>{const a=1+s*n+n/2-.15;e.addShape("ellipse",{x:a,y:o-.15,w:.3,h:.3,fill:{color:r.colors.primary.replace("#","")}}),e.addText(i.date,{x:a-n/2+.15,y:o-.8,w:n,h:.4,fontSize:r.fonts.sizes.caption,fontFace:r.fonts.body,color:r.colors.primary.replace("#",""),align:"center",bold:!0,fit:$t}),e.addText(i.title,{x:a-n/2+.15,y:o+.4,w:n,h:.4,fontSize:r.fonts.sizes.body,fontFace:r.fonts.heading,color:r.colors.text.replace("#",""),align:"center",bold:!0,fit:$t}),i.description&&e.addText(i.description,{x:a-n/2+.15,y:o+.85,w:n,h:.8,fontSize:r.fonts.sizes.caption,fontFace:r.fonts.body,color:r.colors.muted.replace("#",""),align:"center",fit:$t})})}function yEn(e,t,r){const n=3/t.length,o=1.5;e.addShape("rect",{x:o,y:1.5,w:.04,h:3.5,fill:{color:r.colors.primary.replace("#","")}}),t.forEach((i,s)=>{const a=1.7+s*n;e.addShape("ellipse",{x:o-.12,y:a,w:.28,h:.28,fill:{color:r.colors.primary.replace("#","")}}),e.addText(i.date,{x:.3,y:a-.1,w:1,h:.3,fontSize:r.fonts.sizes.caption,fontFace:r.fonts.body,color:r.colors.primary.replace("#",""),bold:!0,fit:$t}),e.addText(i.title,{x:2,y:a-.1,w:7,h:.4,fontSize:r.fonts.sizes.body,fontFace:r.fonts.heading,color:r.colors.text.replace("#",""),bold:!0,fit:$t}),i.description&&e.addText(i.description,{x:2,y:a+.3,w:7,h:.4,fontSize:r.fonts.sizes.caption,fontFace:r.fonts.body,color:r.colors.muted.replace("#",""),fit:$t})})}function vEn(e,t,r,n){if(Bs(e,t,n),!r.processSteps)return;const o=r.processSteps.slice(0,5),i=8/o.length;o.forEach((s,a)=>{const u=1+a*i,l=i-.4;e.addShape("roundRect",{x:u,y:2,w:l,h:2,fill:{color:n.colors.primary.replace("#","")},rectRadius:.1}),e.addText(String(s.step),{x:u,y:2.1,w:l,h:.5,fontSize:24,fontFace:n.fonts.heading,color:n.colors.textOnPrimary.replace("#",""),align:"center",bold:!0,fit:$t}),e.addText(s.title,{x:u,y:2.6,w:l,h:.5,fontSize:n.fonts.sizes.body,fontFace:n.fonts.heading,color:n.colors.textOnPrimary.replace("#",""),align:"center",bold:!0,fit:$t}),s.description&&e.addText(s.description,{x:u,y:3.2,w:l,h:.7,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:n.colors.textOnPrimary.replace("#",""),align:"center",fit:$t}),a<o.length-1&&e.addShape("rightArrow",{x:u+l+.02,y:2.85,w:.35,h:.3,fill:{color:n.colors.primary.replace("#","")}})})}function wEn(e,t,r,n){if(Bs(e,t,n,!1),!r.comparison?.columns)return;const o=r.comparison.columns.slice(0,2),i=4.2,s=2,u=5-s,l=Math.max(...o.map(p=>Math.min(p.items?.length||0,6))),c=l>0?Math.min(.7,(u-m_*l)/l):.5,d=c+m_;o.forEach((p,m)=>{const h=.5+m*4.8;e.addShape("roundRect",{x:h,y:1.4,w:i,h:.5,fill:{color:p.highlight?n.colors.primary.replace("#",""):n.colors.muted.replace("#","")},rectRadius:.05}),e.addText(p.title,{x:h,y:1.4,w:i,h:.5,fontSize:n.fonts.sizes.body,fontFace:n.fonts.heading,color:p.highlight?n.colors.textOnPrimary.replace("#",""):n.colors.text.replace("#",""),align:"center",bold:!0,valign:"middle",fit:$t});const g=(p.items||[]).slice(0,6),y=g.length>4?Math.max(12,n.fonts.sizes.body-2):n.fonts.sizes.body;g.forEach((v,w)=>{if(l_(v)){const b=u_(v),E=[{text:"\u2022 ",options:{fontSize:y,fontFace:n.fonts.body,color:n.colors.text.replace("#","")}},...c_(b,{fontSize:y,fontFace:n.fonts.body,color:n.colors.text.replace("#","")})];e.addText(E,{x:h+.2,y:s+w*d,w:i-.4,h:c,valign:"top",fit:$t})}else e.addText(`\u2022 ${v}`,{x:h+.2,y:s+w*d,w:i-.4,h:c,fontSize:y,fontFace:n.fonts.body,color:n.colors.text.replace("#",""),valign:"top",fit:$t})})})}function bEn(e,t,r,n){Bs(e,t,n);const o=r.features||[],i=r.icons||[],s=o.length>0?o:i.map(l=>({title:l.label,description:l.description||"",icon:l.icon}));if(s.length===0)return;const a=Math.min(s.length,3),u=9/a;s.slice(0,6).forEach((l,c)=>{const d=Math.floor(c/a),m=.5+c%a*u,h=1.6+d*1.8;if(l.icon){const g=parseInt(l.icon,16);if(!Number.isNaN(g)&&g>=0&&g<=1114111){const y=String.fromCodePoint(g);e.addText(y,{x:m,y:h,w:u-.2,h:.6,fontSize:36,fontFace:"Segoe UI Emoji",color:n.colors.primary.replace("#",""),align:"center",fit:$t})}}e.addText(l.title,{x:m,y:h+.6,w:u-.2,h:.4,fontSize:n.fonts.sizes.body,fontFace:n.fonts.heading,color:n.colors.text.replace("#",""),align:"center",bold:!0,fit:$t}),l.description&&e.addText(l.description,{x:m,y:h+1,w:u-.2,h:.6,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:"center",fit:$t})})}function TEn(e,t,r,n){if(Bs(e,t,n),!r.teamMembers)return;const o=r.teamMembers.slice(0,4),i=9/o.length;o.forEach((s,a)=>{const u=.5+a*i;e.addShape("ellipse",{x:u+(i-1.5)/2,y:1.6,w:1.5,h:1.5,fill:{color:n.colors.muted.replace("#","")}});const l=s.name.split(" ").map(c=>c[0]).join("").substring(0,2);e.addText(l,{x:u+(i-1.5)/2,y:2,w:1.5,h:.7,fontSize:28,fontFace:n.fonts.heading,color:"FFFFFF",align:"center",bold:!0,fit:$t}),e.addText(s.name,{x:u,y:3.3,w:i-.2,h:.4,fontSize:n.fonts.sizes.body,fontFace:n.fonts.heading,color:n.colors.text.replace("#",""),align:"center",bold:!0,fit:$t}),e.addText(s.role,{x:u,y:3.7,w:i-.2,h:.3,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:"center",fit:$t})})}function _En(e,t,r,n){if(Bs(e,t,n),r.bullets){const o=r.bullets.map(i=>({...i,icon:i.icon||"2713"}));nmr(e,o,Vt.contentFull,n,"conclusion")}r.cta&&e.addText(r.cta,{x:.5,y:4.6,w:9,h:.5,fontSize:n.fonts.sizes.heading-4,fontFace:n.fonts.heading,color:n.colors.primary.replace("#",""),align:"center",bold:!0,fit:$t})}function p_(e,t,r,n,o=!1){e.addShape("roundRect",{x:t.x,y:t.y,w:t.w,h:t.h,fill:{color:o?n.colors.primary.replace("#","")+"15":"F8F9FA"},line:{color:o?n.colors.primary.replace("#",""):"E5E7EB",width:1},rectRadius:.1});let i=t.y+.15,s=t.h-.3;return r&&(e.addText(r,{x:t.x+.15,y:t.y+.1,w:t.w-.3,h:.35,fontSize:14,fontFace:n.fonts.heading,color:o?n.colors.primary.replace("#",""):n.colors.text.replace("#",""),bold:!0,fit:$t}),i=t.y+.45,s=t.h-.55),{contentY:i,contentH:s}}function imr(e,t,r,n,o,i){if(!t||t.length===0)return;const s=Math.max(11,Math.min(14,16-t.length)),a=n.colors.text.replace("#","");t.forEach((u,l)=>{if(!u||!u.text)return;const c=o+l*(i/t.length);if(l_(u.text)){const d=u_(u.text),p=[{text:"\u2022 ",options:{fontSize:s,fontFace:n.fonts.body,color:a}},...c_(d,{fontSize:s,fontFace:n.fonts.body,color:a})];e.addText(p,{x:r.x+.15,y:c,w:r.w-.3,h:i/t.length,valign:"top",fit:$t})}else e.addText(`\u2022 ${u.text}`,{x:r.x+.15,y:c,w:r.w-.3,h:i/t.length,fontSize:s,fontFace:n.fonts.body,color:a,valign:"top",fit:$t})})}function Tme(e,t,r,n,o,i){e.addText(t.value,{x:r.x,y:o,w:r.w,h:i*.6,fontSize:Math.min(32,r.w*8),fontFace:n.fonts.heading,color:n.colors.primary.replace("#",""),bold:!0,align:"center",valign:"bottom",fit:$t}),e.addText(t.label,{x:r.x,y:o+i*.6,w:r.w,h:i*.4,fontSize:11,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:"center",valign:"top",fit:$t})}function smr(e){const{slide:t,icon:r,label:n,description:o,pos:i,theme:s,contentY:a,contentH:u}=e,l=Math.min(.6,i.w*.2);t.addShape("ellipse",{x:i.x+(i.w-l)/2,y:a,w:l,h:l,fill:{color:s.colors.primary.replace("#","")}});const c=parseInt(r,16);if(Number.isNaN(c)||c<0||c>1114111){f.warn("[renderIconBoxInZone] Invalid icon code",{icon:r});return}const d=String.fromCodePoint(c);t.addText(d,{x:i.x+(i.w-l)/2,y:a,w:l,h:l,fontSize:16,color:"FFFFFF",align:"center",valign:"middle",fit:$t}),t.addText(n,{x:i.x,y:a+l+.1,w:i.w,h:.3,fontSize:12,fontFace:s.fonts.heading,color:s.colors.text.replace("#",""),bold:!0,align:"center",fit:$t}),o&&t.addText(o,{x:i.x+.1,y:a+l+.4,w:i.w-.2,h:u-l-.5,fontSize:10,fontFace:s.fonts.body,color:s.colors.muted.replace("#",""),align:"center",fit:$t})}function amr(e,t,r,n,o,i){const s=t.type==="pie"?"pie":t.type==="line"?"line":"bar",a=t.series||[];if(a.length===0)return;const u=a.map(l=>({name:l.name||"Data",labels:l.labels||[],values:l.values||[]}));try{e.addChart(s,u,{x:r.x+.1,y:o,w:r.w-.2,h:i,showLegend:!1,showTitle:!1,chartColors:[n.colors.primary.replace("#",""),n.colors.secondary.replace("#",""),n.colors.accent.replace("#",""),n.colors.muted.replace("#","")]})}catch{e.addText("Chart",{x:r.x,y:o,w:r.w,h:i,fontSize:14,color:n.colors.muted.replace("#",""),align:"center",valign:"middle",fit:$t})}}function EEn(e,t,r,n){Bs(e,t,n,!1);const o=ia[r.layout]||ia["left-right"];(r.zones||[]).forEach((s,a)=>{if(a>=o.length)return;const u=o[a],{contentY:l,contentH:c}=p_(e,u,s.title,n,s.isPrimary);switch(s.type){case"bullets":Array.isArray(s.data)&&imr(e,s.data,u,n,l,c);break;case"stats":s.data&&typeof s.data=="object"&&Tme(e,s.data,u,n,l,c);break;case"icon-box":if(s.data&&typeof s.data=="object"){const d=s.data;smr({slide:e,icon:d.icon,label:d.label,description:d.description,pos:u,theme:n,contentY:l,contentH:c})}break;case"chart":s.data&&typeof s.data=="object"&&amr(e,s.data,u,n,l,c);break;case"text-box":typeof s.data=="string"&&e.addText(s.data,{x:u.x+.15,y:l,w:u.w-.3,h:c,fontSize:12,fontFace:n.fonts.body,color:n.colors.text.replace("#",""),valign:"top"});break}})}function SEn(e,t,r,n){if(Bs(e,t,n,!1),r.bullets&&r.bullets.length>0){const o=ia["left-right"][0],{contentY:i,contentH:s}=p_(e,o,r.leftColumn?.title,n,!0);imr(e,r.bullets,o,n,i,s)}if(r.chartData){const o=ia["left-right"][1],{contentY:i,contentH:s}=p_(e,o,"Data",n,!1);amr(e,r.chartData,o,n,i,s)}else if(r.statistics&&r.statistics.length>0){const o=ia["left-right"][1];p_(e,o,"Metrics",n,!1);const i=r.statistics.slice(0,3),s=o.h/i.length;i.forEach((a,u)=>{Tme(e,a,{...o,y:o.y+u*s,h:s},n,o.y+u*s+.1,s-.2)})}}function kEn(e,t,r,n){Bs(e,t,n,!1);const o=r.statistics||[];if(o.length===0)return;let i;o.length<=2?i=ia["left-right"]:o.length<=3?i=ia["three-cols"]:o.length<=4?i=ia.quadrants:o.length<=5?i=ia["five-boxes"]:i=ia["six-boxes"],o.slice(0,i.length).forEach((s,a)=>{const u=i[a],l=a===0,{contentY:c,contentH:d}=p_(e,u,void 0,n,l);Tme(e,s,u,n,c,d)})}function AEn(e,t,r,n){Bs(e,t,n,!1);const o=r.icons||r.features||[];if(o.length===0)return;let i;o.length<=2?i=ia["left-right"]:o.length<=3?i=ia["three-cols"]:o.length<=4?i=ia.quadrants:o.length<=5?i=ia["five-boxes"]:i=ia["six-boxes"],o.slice(0,i.length).forEach((s,a)=>{const u=i[a],l=a===0,{contentY:c,contentH:d}=p_(e,u,void 0,n,l),p=s.icon||"1F4A1",m=s.title||s.label||"",h=s.description;smr({slide:e,icon:p,label:m,description:h,pos:u,theme:n,contentY:c,contentH:d})})}var m_,$t,Vt,umr,ia,xEn=S({"src/lib/features/ppt/slideRenderers.ts"(){"use strict";z(),a_(),vme(),m_=.1,$t="shrink",Vt={margin:{x:.5,y:.4},title:{x:.5,y:.4,w:9,h:.8},subtitle:{x:.5,y:1.4,w:9,h:.5},content:{x:.5,y:1.4,w:9,h:3.8},contentFull:{x:.5,y:1.4,w:9,h:3.8},contentLeft:{x:.5,y:1.4,w:4.2,h:3.8},contentRight:{x:5.3,y:1.4,w:4.2,h:3.8},imageRight:{x:5.3,y:1.4,w:4.2,h:3.8},imageLeft:{x:.5,y:1.4,w:4.2,h:3.8},imageFull:{x:0,y:0,w:10,h:5.625},imageCentered:{x:2,y:1.2,w:6,h:3.6},columnLeft:{x:.5,y:1.4,w:4.2,h:3.8},columnRight:{x:5.3,y:1.4,w:4.2,h:3.8},col1:{x:.5,y:1.4,w:2.8,h:3.8},col2:{x:3.5,y:1.4,w:2.8,h:3.8},col3:{x:6.5,y:1.4,w:2.8,h:3.8},chart:{x:.5,y:1.4,w:9,h:3.8},statRow:{y:2.2,h:2.5},footer:{x:.5,y:5.2,w:9,h:.3},logo:{"top-left":{x:.3,y:.2},"top-right":{x:8.5,y:.2},"bottom-left":{x:.3,y:5},"bottom-right":{x:8.5,y:5}},quote:{x:1,y:1.5,w:8,h:2.5},quoteAuthor:{x:1,y:4.2,w:8,h:.5}},umr={top:"t",bottom:"b",left:"l",right:"r"},ia={"left-right":[{x:.5,y:1.4,w:4.3,h:3.6},{x:5.2,y:1.4,w:4.3,h:3.6}],"top-bottom":[{x:.5,y:1.2,w:9,h:1.8},{x:.5,y:3.2,w:9,h:2}],"three-cols":[{x:.5,y:1.4,w:2.8,h:3.6},{x:3.5,y:1.4,w:2.8,h:3.6},{x:6.5,y:1.4,w:2.8,h:3.6}],quadrants:[{x:.5,y:1.2,w:4.3,h:1.8},{x:5.2,y:1.2,w:4.3,h:1.8},{x:.5,y:3.2,w:4.3,h:1.8},{x:5.2,y:3.2,w:4.3,h:1.8}],"five-boxes":[{x:.5,y:1.2,w:4.3,h:1.6},{x:5.2,y:1.2,w:4.3,h:1.6},{x:.5,y:3,w:2.8,h:2},{x:3.5,y:3,w:2.8,h:2},{x:6.5,y:3,w:2.8,h:2}],"six-boxes":[{x:.5,y:1.2,w:2.8,h:1.6},{x:3.5,y:1.2,w:2.8,h:1.6},{x:6.5,y:1.2,w:2.8,h:1.6},{x:.5,y:3,w:2.8,h:1.8},{x:3.5,y:3,w:2.8,h:1.8},{x:6.5,y:3,w:2.8,h:1.8}],"main-sidebar":[{x:.5,y:1.4,w:5.8,h:3.6},{x:6.5,y:1.4,w:3,h:3.6}],"top-three":[{x:.5,y:1.2,w:9,h:1.6},{x:.5,y:3,w:2.8,h:2},{x:3.5,y:3,w:2.8,h:2},{x:6.5,y:3,w:2.8,h:2}]}}});async function CEn(){if(xI)return xI;const t=(await Uu("pptxgenjs","PPT generation")).default;return xI=typeof t=="function"?t:t.default,xI}var xI,lmr,cmr=S({async"src/lib/features/ppt/slideGenerator.ts"(){"use strict";Tx(),vn(),lt(),a_(),z(),Dd(),et(),ro(),xEn(),xI=null,lmr=class{theme;config;neurolink;imageLimit;userImageIndex=0;constructor(e){this.config=e,this.theme=typeof e.theme=="string"?wpr(e.theme):e.theme,this.neurolink=e.neurolink||null,this.imageLimit=y0(hme)}getNextUserImage(){const e=this.config.userImages;if(!e||e.length===0)return;const t=e[this.userImageIndex%e.length];return this.userImageIndex++,t}async loadUserImage(e){try{if(Buffer.isBuffer(e))return e;if(e.startsWith("http://")||e.startsWith("https://")){const n=await Ge(fetch(e),15e3,ve.toolTimeout("userImageFetch",15e3));if(!n.ok){f.warn(`[SlideGenerator] Failed to fetch user image: ${e}`);return}return Buffer.from(await n.arrayBuffer())}return await(await Promise.resolve().then(()=>(_i(),f0))).readFile(e)}catch(r){f.warn("[SlideGenerator] Failed to load user image",{error:r instanceof Error?r.message:String(r)});return}}async generateSlide(e){const t=Ce.createSpan("ppt.generation","ppt.generateSlide",{"ppt.operation":"generateSlide","ppt.slideIndex":e.slideNumber,"ppt.theme":this.theme.name}),r=Date.now();try{let n,o;if(WF(e.type)){const a=this.getNextUserImage();if(a&&(f.info(`[SlideGenerator] \u{1F4F7} Using user-provided image for slide ${e.slideNumber}: "${e.title}"`),n=await this.loadUserImage(a),n&&(o={prompt:"User-provided image",model:"user-upload",generatedAt:new Date})),!n&&this.config.generateAIImages&&e.imagePrompt){f.info(`[SlideGenerator] \u23F3 Generating AI image for slide ${e.slideNumber}: "${e.title}"...`);const u=await this.generateImage(e.imagePrompt,e.type);u&&(n=u.buffer,o={prompt:e.imagePrompt,model:u.model,generatedAt:new Date})}}const i=Date.now()-r;f.debug(`[SlideGenerator] Generated slide ${e.slideNumber} (${e.type})`,{hasImage:!!n,generationTime:i});const s=Ce.endSpan(t,1);return nt().recordSpan(s),{slideNumber:e.slideNumber,schema:e,imageBuffer:n,imageMetadata:o,generationTime:i}}catch(n){const o=Ce.endSpan(t,2);o.statusMessage=n instanceof Error?n.message:String(n),nt().recordSpan(o);const i=n instanceof Me?n:ve.toolExecutionFailed("slideGenerator",n instanceof Error?n:new Error(String(n)));return f.error(`[SlideGenerator] Failed to generate slide ${e.slideNumber}`,{error:i.message,type:e.type}),{slideNumber:e.slideNumber,schema:e,generationTime:Date.now()-r}}}async generateSlides(e){const t=Date.now(),r=this.config.generateAIImages?e.filter(l=>l.imagePrompt&&WF(l.type)).length:0,n=this.config.userImages?.length??0;f.info(`[SlideGenerator] Generating ${e.length} slides...`,{theme:this.theme.name,generateAIImages:this.config.generateAIImages,slidesNeedingAIImages:r,userImagesProvided:n}),this.userImageIndex=0;const o=e.map(l=>this.imageLimit(()=>this.generateSlide(l))),i=await Promise.all(o),s=i.filter(l=>l.imageBuffer).length,a=this.config.generateAIImages?e.filter(l=>l.imagePrompt&&WF(l.type)&&!i.find(c=>c.slideNumber===l.slideNumber)?.imageBuffer).length:0,u=Date.now()-t;return f.info("[SlideGenerator] Slide generation complete",{totalSlides:i.length,totalImages:s,failedImages:a,generationTime:u}),{slides:i,totalImages:s,failedImages:a,generationTime:u}}renderSlide(e,t,r,n){const{schema:o,imageBuffer:i}=t,s=e.addSlide();return this.applyBackground(s,o.type),this.applyLayout(s,o,i),o.type!=="title"&&o.type!=="thank-you"&&this.addSlideNumber(s,r,n),this.addLogo(s,o.type),o.speakerNotes&&s.addNotes(o.speakerNotes),s}async generateImage(e,t){if(!this.neurolink)return f.warn("[SlideGenerator] No NeuroLink instance provided, skipping image generation"),null;try{const r=_pr(e,this.theme.name);f.debug(`[SlideGenerator] Generating image for ${t}`,{promptPreview:r.substring(0,100)});const n=await Ge(this.neurolink.generate({input:{text:r},provider:this.config.provider||"vertex",model:this.config.imageModel||"gemini-2.5-flash-image"}),QF,ve.toolTimeout("imageGeneration",QF));if(!n||!n.imageOutput?.base64)return f.warn(`[SlideGenerator] No image data returned for ${t}`),null;const o=Buffer.from(n.imageOutput.base64,"base64");return o.length<100?(f.warn(`[SlideGenerator] Image buffer too small (${o.length} bytes) for ${t}`),null):(o[0]===255&&o[1]===216&&o[2]===255||o[0]===137&&o[1]===80&&o[2]===78&&o[3]===71||o[0]===71&&o[1]===73&&o[2]===70||o[0]===82&&o[1]===73&&o[2]===70&&o[3]===70||f.warn(`[SlideGenerator] Unknown image format for ${t}, magic bytes: ${o.slice(0,4).toString("hex")}`),f.debug(`[SlideGenerator] Image generated successfully for ${t}`,{size:o.length,format:o[0]===255?"JPEG":o[0]===137?"PNG":o[0]===71?"GIF":"unknown"}),{buffer:o,model:n.model||this.config.imageModel})}catch(r){const n=r instanceof Me?r:ve.toolExecutionFailed("imageGeneration",r instanceof Error?r:new Error(String(r)));return f.error("[SlideGenerator] Image generation failed",{error:n.message,slideType:t}),null}}applyBackground(e,t){e.background={color:this.theme.colors.background.replace("#","")}}applyLayout(e,t,r){const{type:n,layout:o,title:i,content:s}=t;switch(n){case"title":iEn(e,i,s,this.theme,r);break;case"section-header":sEn(e,i,s,this.theme);break;case"content":case"bullets":case"agenda":case"numbered-list":bme({slide:e,title:i,content:s,layout:o,theme:this.theme,imageBuffer:r,slideType:n});break;case"image-focus":case"image-left":case"image-right":case"full-bleed-image":uEn(e,i,s,o,this.theme,r);break;case"two-column":case"split-content":lEn(e,i,s,o,this.theme,r);break;case"three-column":cEn(e,i,s,this.theme);break;case"quote":dEn(e,i,s,this.theme);break;case"statistics":pEn(e,i,s,this.theme);break;case"chart-bar":case"chart-line":case"chart-pie":case"chart-area":mEn(e,i,s,n,this.theme);break;case"table":hEn(e,i,s,this.theme);break;case"timeline":fEn(e,i,s,this.theme);break;case"process-flow":vEn(e,i,s,this.theme);break;case"comparison":wEn(e,i,s,this.theme);break;case"features":case"icons":bEn(e,i,s,this.theme);break;case"team":TEn(e,i,s,this.theme);break;case"conclusion":_En(e,i,s,this.theme);break;case"thank-you":case"closing":aEn(e,i,s,this.theme,r);break;case"dashboard":s.dashboard&&EEn(e,i,s.dashboard,this.theme);break;case"mixed-content":SEn(e,i,s,this.theme);break;case"stats-grid":kEn(e,i,s,this.theme);break;case"icon-grid":AEn(e,i,s,this.theme);break;case"blank":break;default:bme({slide:e,title:i,content:s,layout:o,theme:this.theme,imageBuffer:r,slideType:n})}}getLogoConfig(){return this.config.logo?Buffer.isBuffer(this.config.logo)||typeof this.config.logo=="string"?{data:this.config.logo,position:"bottom-right",width:1,height:.4,showOn:"all-slides"}:{data:this.config.logo.data,position:this.config.logo.position||"bottom-right",width:this.config.logo.width||1,height:this.config.logo.height||.4,showOn:this.config.logo.showOn||"all-slides"}:null}getLogoDataUri(e){if(Buffer.isBuffer(e))return`data:image/png;base64,${e.toString("base64")}`;if(e.startsWith("data:"))return e;if(e.includes("/")||e.includes("\\")||e.endsWith(".png")||e.endsWith(".jpg")||e.endsWith(".jpeg")||e.endsWith(".svg"))try{if(ks(e)){const t=kp(e),r=e.split(".").pop()?.toLowerCase();return`data:${r==="svg"?"image/svg+xml":r==="jpg"||r==="jpeg"?"image/jpeg":"image/png"};base64,${t.toString("base64")}`}}catch{f.warn("[SlideGenerator] Could not read logo file, treating as base64")}return`data:image/png;base64,${e}`}addLogo(e,t){const r=this.getLogoConfig();if(!r)return;const n=r.showOn||"all-slides";if(n==="title-only"&&t!=="title"||n==="title-and-closing"&&t!=="title"&&t!=="thank-you"&&t!=="closing")return;const o=this.getLogoDataUri(r.data),i=r.position||"bottom-right",s=r.width||1,a=r.height||.4;let u,l;const c=Vt.logo;if(i==="title-only"?(u=c["bottom-right"].x,l=c["bottom-right"].y):(u=c[i].x,l=c[i].y),i==="top-right"||i==="bottom-right"){const{width:d}=B2[this.config.aspectRatio];u=d-s-.3}if(i==="bottom-left"||i==="bottom-right"){const{height:d}=B2[this.config.aspectRatio];l=d-a-.2}e.addImage({data:o,x:u,y:l,w:s,h:a,sizing:{type:"contain",w:s,h:a}})}addSlideNumber(e,t,r){e.addText(`${t} / ${r}`,{x:Vt.footer.x,y:Vt.footer.y,w:Vt.footer.w,h:Vt.footer.h,fontSize:this.theme.fonts.sizes.caption,fontFace:this.theme.fonts.body,color:this.theme.colors.muted.replace("#",""),align:"right"})}}}});function IEn(e){const t=e.trim();for(const{patterns:r,slideType:n,bulletStyle:o}of pmr)for(const i of r)if(i.test(t))return{slideType:n,bulletStyle:o};return{slideType:null,bulletStyle:null}}function REn(e){if(!e||e.length===0)return null;for(const t of e)for(const{pattern:r,bulletStyle:n}of mmr)if(r.test(t.text))return n;return null}function dmr(e){switch(e){case"agenda":case"numbered-list":return"number";case"conclusion":case"closing":case"thank-you":return"checkmark";case"comparison":return"arrow";case"features":case"icons":case"quote":case"statistics":case"title":case"section-header":return"none";default:return"disc"}}function MEn(e,t,r){const{slideType:n,bulletStyle:o}=IEn(e);if(n)return{type:n,bulletStyle:o||dmr(n),wasInferred:!0};const i=r.bullets?REn(r.bullets):null;return i?{type:t,bulletStyle:i,wasInferred:!0}:{type:t,bulletStyle:dmr(t),wasInferred:!1}}function PEn(e,t){return(e.bullets?.length??0)>0||(e.leftColumn?.bullets?.length??0)>0||(e.rightColumn?.bullets?.length??0)>0||(e.centerColumn?.bullets?.length??0)>0?{...e,bullets:e.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||t})),leftColumn:e.leftColumn?{...e.leftColumn,bullets:e.leftColumn.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||t}))}:void 0,rightColumn:e.rightColumn?{...e.rightColumn,bullets:e.rightColumn.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||t}))}:void 0,centerColumn:e.centerColumn?{...e.centerColumn,bullets:e.centerColumn.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||t}))}:void 0}:e}var pmr,mmr,DEn=S({"src/lib/features/ppt/slideTypeInference.ts"(){"use strict";pmr=[{patterns:[/\bagenda\b/i,/\btable\s+of\s+contents\b/i,/\boutline\b/i,/\boverview\b/i,/\bwhat\s+we('ll)?\s+cover\b/i,/\btoday('s)?\s+topics?\b/i,/\bsession\s+outline\b/i],slideType:"agenda",bulletStyle:"number"},{patterns:[/\bconclusion\b/i,/\bsummary\b/i,/\bkey\s+takeaways?\b/i,/\btakeaways?\b/i,/\brecap\b/i,/\bin\s+summary\b/i,/\bwhat\s+we('ve)?\s+learned\b/i,/\bmain\s+points?\b/i,/\bkey\s+points?\b/i,/\bhighlights?\b/i,/\bachievements?\b/i,/\baccomplishments?\b/i],slideType:"conclusion",bulletStyle:"checkmark"},{patterns:[/\bthank\s+you\b/i,/\bthanks?\b/i,/\bquestions?\b\??/i,/\bq\s*&\s*a\b/i,/\bcontact(\s+us)?\b/i,/\bnext\s+steps?\b/i,/\baction\s+items?\b/i,/\blet('s)?\s+connect\b/i,/\bget\s+(in\s+)?touch\b/i],slideType:"closing",bulletStyle:"checkmark"},{patterns:[/\bcomparison\b/i,/\bcompare\b/i,/\bvs\.?\b/i,/\bversus\b/i,/\bbefore\s+(and|&|vs\.?)\s+after\b/i,/\bpros?\s+(and|&|vs\.?)\s+cons?\b/i,/\badvantages?\s+(and|&|vs\.?)\s+disadvantages?\b/i,/\bbenefits?\s+(and|&|vs\.?)\s+risks?\b/i,/\bold\s+vs\.?\s+new\b/i],slideType:"comparison",bulletStyle:"arrow"},{patterns:[/\bprocess\b/i,/\bsteps?\b/i,/\bstep[\s-]+by[\s-]+step\b/i,/\bhow\s+to\b/i,/\bworkflow\b/i,/\bprocedure\b/i,/\bmethodology\b/i,/\d+\s+steps?\s+to\b/i,/\bimplementation\s+steps?\b/i,/\bgetting\s+started\b/i],slideType:"numbered-list",bulletStyle:"number"},{patterns:[/\bfeatures?\b/i,/\bcapabilities?\b/i,/\bwhat\s+(we|it)\s+offers?\b/i,/\bour\s+offerings?\b/i],slideType:"features",bulletStyle:"disc"},{patterns:[/\bbenefits?\b/i,/\badvantages?\b/i,/\bwhy\s+choose\b/i,/\breasons?\s+to\b/i,/\bvalue\s+proposition\b/i],slideType:"content",bulletStyle:"checkmark"},{patterns:[/\bgoals?\b/i,/\bobjectives?\b/i,/\btargets?\b/i,/\baims?\b/i,/\bour\s+mission\b/i,/\bwhat\s+we\s+aim\s+for\b/i],slideType:"content",bulletStyle:"checkmark"},{patterns:[/\bchallenges?\b/i,/\brisks?\b/i,/\bobstacles?\b/i,/\bbarriers?\b/i,/\bconcerns?\b/i,/\bissues?\b/i,/\bproblems?\b/i],slideType:"content",bulletStyle:"arrow"},{patterns:[/\brequirements?\b/i,/\bchecklist\b/i,/\bprerequisites?\b/i,/\bwhat\s+you\s+need\b/i,/\bmust\s+haves?\b/i,/\bessentials?\b/i],slideType:"content",bulletStyle:"checkmark"}],mmr=[{pattern:/^\d+[.)]\s+/m,bulletStyle:"number"},{pattern:/^step\s+\d+/im,bulletStyle:"number"},{pattern:/^[✓✔☑]\s*/m,bulletStyle:"checkmark"},{pattern:/^\[x\]\s*/im,bulletStyle:"checkmark"},{pattern:/^done:/im,bulletStyle:"checkmark"},{pattern:/^completed:/im,bulletStyle:"checkmark"},{pattern:/^[→➜➡]\s*/m,bulletStyle:"arrow"},{pattern:/^->\s*/m,bulletStyle:"arrow"},{pattern:/^=>\s*/m,bulletStyle:"arrow"}]}});function OEn(e,t="content"){return typeof e=="string"&&hmr.has(e)?e:(f.warn(`[ContentPlanner] Invalid slide type "${e}", using "${t}"`),t)}function NEn(e,t){if(typeof e=="string"&&fmr.has(e))return e;const n=KF[t]?.[0]||"title-content";return f.warn(`[ContentPlanner] Invalid layout "${e}" for type "${t}", using "${n}"`),n}function LEn(e){if(e&&typeof e=="object"&&"text"in e){const t=e,r={text:String(t.text||"")};return Array.isArray(t.subBullets)&&(r.subBullets=t.subBullets.map(n=>String(n))),typeof t.icon=="string"&&(r.icon=t.icon),typeof t.emphasis=="boolean"&&(r.emphasis=t.emphasis),typeof t.fontSize=="number"&&t.fontSize>=8&&t.fontSize<=48&&(r.fontSize=t.fontSize),typeof t.bulletStyle=="string"&&gmr.has(t.bulletStyle)&&(r.bulletStyle=t.bulletStyle),typeof t.color=="string"&&t.color.match(/^#?[0-9A-Fa-f]{6}$/)&&(r.color=t.color.startsWith("#")?t.color:`#${t.color}`),typeof t.bold=="boolean"&&(r.bold=t.bold),r.text?r:null}return typeof e=="string"&&e.trim()?{text:e.trim()}:null}function e5(e){if(!Array.isArray(e))return[];const t=[];for(const r of e){const n=LEn(r);n&&t.push(n)}return t}function $En(e){if(!e||typeof e!="object")return{};const t=e,r={};if(t.bullets&&(r.bullets=e5(t.bullets)),t.leftColumn&&typeof t.leftColumn=="object"){const o=t.leftColumn;r.leftColumn={title:typeof o.title=="string"?o.title:void 0,bullets:o.bullets?e5(o.bullets):void 0,image:typeof o.image=="string"?o.image:void 0}}if(t.rightColumn&&typeof t.rightColumn=="object"){const o=t.rightColumn;r.rightColumn={title:typeof o.title=="string"?o.title:void 0,bullets:o.bullets?e5(o.bullets):void 0,image:typeof o.image=="string"?o.image:void 0}}if(t.centerColumn&&typeof t.centerColumn=="object"){const o=t.centerColumn;r.centerColumn={title:typeof o.title=="string"?o.title:void 0,bullets:o.bullets?e5(o.bullets):void 0,image:typeof o.image=="string"?o.image:void 0}}const n=["subtitle","body","sectionNumber","quote","quoteAuthor","quoteAuthorTitle","caption","galleryImages","statistics","chartData","tableData","timeline","processSteps","features","icons","teamMembers","comparison","nextSteps","cta","ctaButton","contactInfo","layoutOptions","dashboard"];for(const o of n)t[o]!==void 0&&(r[o]=t[o]);return r}function FEn(e,t){if(!e||typeof e!="object")throw new Ku("AI returned invalid response: expected object",Rc.INVALID_AI_RESPONSE,{received:typeof e});const r=e;if(typeof r.title!="string"||!r.title.trim())throw new Ku("AI response missing valid 'title' field",Rc.INVALID_AI_RESPONSE,{field:"title",received:r.title});if(!Array.isArray(r.slides))throw new Ku("AI response missing 'slides' array",Rc.INVALID_AI_RESPONSE,{field:"slides",received:typeof r.slides});r.slides.length!==t&&f.warn(`[ContentPlanner] AI returned ${r.slides.length} slides, expected ${t}. Adjusting...`);const n=[];for(let o=0;o<r.slides.length;o++){const i=r.slides[o];if(!i||typeof i!="object")throw new Ku(`Invalid slide at index ${o}`,Rc.INVALID_AI_RESPONSE,{index:o,received:typeof i});typeof i.title!="string"&&(i.title=`Slide ${o+1}`,f.warn(`[ContentPlanner] Slide ${o+1} missing title, using default`));const s=OEn(i.type,"content"),a=$En(i.content),{type:u,bulletStyle:l,wasInferred:c}=MEn(i.title,s,a),d=c&&u!==s?u:s;c&&u!==s&&f.debug(`[ContentPlanner] Slide ${o+1} type inferred from title: "${i.title}" \u2192 ${d}`);const p=PEn(a,l),m=NEn(i.layout,d);typeof i.speakerNotes!="string"&&(i.speakerNotes=""),i.imagePrompt!==null&&typeof i.imagePrompt!="string"&&(i.imagePrompt=null),n.push({slideNumber:o+1,type:d,layout:m,title:i.title,content:p,imagePrompt:i.imagePrompt,speakerNotes:i.speakerNotes})}return{title:r.title,totalSlides:n.length,audience:r.audience||"general",tone:r.tone||"professional",theme:r.theme||"modern",slides:n,keyMessages:Array.isArray(r.keyMessages)?r.keyMessages:void 0}}function UEn(e){const t=e.trim(),r=[],n=t.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);n&&n[1]&&r.push(n[1].trim()),t.startsWith("```")&&r.push(t.replace(/^```(?:json)?\s*\n?/,"").replace(/\n?```\s*$/,""));const o=t.indexOf("{"),i=t.indexOf("["),s=o===-1?i:i===-1?o:Math.min(o,i);if(s>0){const l=t[s]==="{"?"}":"]",c=t.lastIndexOf(l);c>s&&r.push(t.slice(s,c+1))}r.push(t);const a=[];for(const u of r)try{return JSON.parse(u)}catch(l){a.push(l instanceof Error?l.message:String(l))}throw new Ku(`Failed to parse AI response as JSON: ${a[a.length-1]}`,Rc.INVALID_AI_RESPONSE,{contentPreview:e.substring(0,500),parseError:a.join(" | ")})}async function BEn(e,t){const r=Date.now(),n=`session-${Date.now()}`;f.info("[ContentPlanner] Starting content planning",{topic:e.topic.substring(0,100),pages:e.pages,audience:e.audience,tone:e.tone,theme:e.theme,generateAIImages:e.generateAIImages,provider:e.provider,model:e.model,sessionId:n});const o=Tpr({topic:e.topic,pages:e.pages,audience:e.audience,tone:e.tone,theme:e.theme,generateAIImages:e.generateAIImages,modelInfo:{name:e.model||"unknown",provider:e.provider||"auto-selected"}});try{const i=await t.generate({prompt:o,systemPrompt:pme,temperature:.7,maxTokens:8192,disableTools:!0,timeout:mme});if(!i||!i.content)throw new Ku("AI provider returned empty response",Rc.PLANNING_FAILED,{provider:e.provider});const s=Date.now()-r;f.debug("[ContentPlanner] AI response received",{contentLength:i.content.length,planningTime:s});const a=UEn(i.content),u=FEn(a,e.pages);return f.info("[ContentPlanner] Content plan generated successfully",{title:u.title,totalSlides:u.totalSlides,planningTime:s,keyMessages:u.keyMessages?.length||0}),u}catch(i){if(i instanceof Ku)throw i;const s=i instanceof Error?i.message:String(i);throw new Ku(`Content planning failed: ${s}`,Rc.PLANNING_FAILED,{topic:e.topic.substring(0,100),provider:e.provider},i instanceof Error?i:void 0)}}function zEn(e){return e.slides.length>0&&e.slides[0].type!=="title"&&(e.slides[0]={...e.slides[0],type:"title",layout:"title-centered"}),e}function GEn(e){const t=e.slides.length-1;return t>=0&&e.slides[t].type!=="thank-you"&&(e.slides[t]={...e.slides[t],type:"thank-you",layout:"contact-info"}),e}function qEn(e){let t={...e,slides:[...e.slides]};return t=zEn(t),t=GEn(t),t}var hmr,fmr,gmr,jEn=S({"src/lib/features/ppt/contentPlanner.ts"(){"use strict";fme(),a_(),DEn(),z(),hmr=new Set(["title","section-header","thank-you","closing","content","agenda","bullets","numbered-list","image-focus","image-left","image-right","full-bleed-image","gallery","two-column","three-column","split-content","table","chart-bar","chart-line","chart-pie","chart-area","statistics","quote","timeline","process-flow","comparison","features","team","icons","conclusion","blank","dashboard","mixed-content","stats-grid","icon-grid"]),fmr=new Set(["title-centered","title-bottom","title-left-aligned","title-content","title-content-footer","content-only","image-left-content-right","image-right-content-left","image-top-content-bottom","image-bottom-content-top","image-full-overlay","image-centered","image-grid-2x2","two-column-equal","two-column-wide-left","two-column-wide-right","three-column-equal","chart-full","chart-with-bullets","table-full","table-with-notes","quote-centered","quote-with-image","statistics-row","statistics-grid","timeline-horizontal","timeline-vertical","process-horizontal","process-vertical","comparison-side-by-side","comparison-table","team-grid","icon-grid","summary-bullets","contact-info","blank-full"]),gmr=new Set(["disc","number","checkmark","arrow","dash","none"])}}),ymr={};ue(ymr,{generatePresentation:()=>VEn});async function VEn(e){const t=Ce.createSpan("ppt.generation","ppt.orchestrate",{"ppt.operation":"orchestrate","ppt.slideCount":e.context.pages,"ppt.theme":typeof e.context.theme=="string"?e.context.theme:"custom"}),r={startTime:Date.now(),contentPlan:null,slides:null,outputPath:null},{context:n,provider:o,providerName:i,modelName:s,neurolink:a,imageProvider:u,imageModel:l}=e;f.info("[PresentationOrchestrator] Starting presentation generation",{topic:n.topic.substring(0,100),pages:n.pages,theme:n.theme,audience:n.audience,tone:n.tone,generateAIImages:n.generateAIImages,provider:n.provider});try{f.info("[PresentationOrchestrator] Step 1: Content planning...");const c=await Ge(BEn(n,o),Ul/2,ve.toolTimeout("contentPlanning",Ul/2));r.contentPlan=qEn(c),t.attributes["ppt.slideCount"]=r.contentPlan.totalSlides,t.attributes["ppt.theme"]=typeof r.contentPlan.theme=="string"?r.contentPlan.theme:"custom",f.info("[PresentationOrchestrator] Content plan ready",{title:r.contentPlan.title,totalSlides:r.contentPlan.totalSlides,theme:r.contentPlan.theme,audience:r.contentPlan.audience,tone:r.contentPlan.tone}),f.info("[PresentationOrchestrator] Step 2: Generating slides...");const d=n.logo??null,p=Zpr(d),h={theme:r.contentPlan.theme||n.theme,generateAIImages:n.generateAIImages,aspectRatio:n.aspectRatio,provider:u??n.provider??"vertex",imageModel:l??"gemini-2.5-flash-image",logo:p??void 0,userImages:n.images,neurolink:a},g=new lmr(h),y=await Ge(g.generateSlides(r.contentPlan.slides),Ul/2,ve.toolTimeout("slideGeneration",Ul/2));r.slides=y.slides,f.info("[PresentationOrchestrator] Slides generated",{totalSlides:r.slides.length,totalImages:y.totalImages,failedImages:y.failedImages,generationTime:y.generationTime}),f.info("[PresentationOrchestrator] Step 3: Assembling PPTX...");const v=await CEn(),w=new v;w.title=r.contentPlan.title,w.subject=`Generated presentation about: ${n.topic.substring(0,100)}`,w.author="NeuroLink PPT Generator",w.company="NeuroLink",w.layout=Qpr(n.aspectRatio);const b=[...r.slides].sort((P,D)=>P.slideNumber-D.slideNumber);for(let P=0;P<b.length;P++){const D=b[P];g.renderSlide(w,D,P+1,b.length)}f.info("[PresentationOrchestrator] PPTX assembled",{totalSlides:b.length,layout:w.layout,title:w.title}),f.info("[PresentationOrchestrator] Step 4: Writing file..."),r.outputPath=Kpr(n),await Ge(Jpr(r.outputPath),Ul/4,ve.toolTimeout("outputDirectory",Ul/4)),await Ge(w.writeFile({fileName:r.outputPath}),Ul/4,ve.toolTimeout("pptxWrite",Ul/4));let E=0;try{E=(await Ge(Co(r.outputPath),Ul/8,ve.toolTimeout("pptxStat",Ul/8))).size}catch{f.warn("[PresentationOrchestrator] Could not get file size")}const k=Date.now()-r.startTime;f.info("[PresentationOrchestrator] Presentation generation complete",{filePath:r.outputPath,fileSize:E,totalSlides:b.length,totalTime:k});const A=Ce.endSpan(t,1);nt().recordSpan(A),a?.recordMetricsSpan(A);const x=r.contentPlan?.theme||n.theme,R=r.contentPlan?.audience||n.audience,C=r.contentPlan?.tone||n.tone;return{filePath:r.outputPath,totalSlides:b.length,format:"pptx",provider:i,model:s,metadata:{theme:x,audience:R,tone:C,imageModel:n.generateAIImages?l??"gemini-2.5-flash-image":"",fileSize:E>0?E:0}}}catch(c){const d=Ce.endSpan(t,2);if(d.statusMessage=c instanceof Error?c.message:String(c),nt().recordSpan(d),a?.recordMetricsSpan(d),c instanceof Ku)throw f.error("[PresentationOrchestrator] Generation failed",{error:c.message,code:c.code,context:c.context}),c;const p=emr(c);throw f.error("[PresentationOrchestrator] Unexpected error",{error:p.message,stage:gme(r)}),new Ku(`Presentation generation failed: ${p.message}`,Rc.ASSEMBLY_FAILED,{topic:n.topic.substring(0,100),stage:gme(r),elapsedTime:Date.now()-r.startTime},p)}}var HEn=S({async"src/lib/features/ppt/presentationOrchestrator.ts"(){"use strict";await cmr(),_i(),fme(),jEn(),await cmr(),a_(),z(),et(),ro(),vme()}}),vmr={};ue(vmr,{MUSIC_ERROR_CODES:()=>er,MusicError:()=>Yt,MusicProcessor:()=>sm});var er,Yt,sm,am=S({"src/lib/utils/musicProcessor.ts"(){"use strict";ro(),et(),z(),lb(),er={PROVIDER_NOT_SUPPORTED:"MUSIC_PROVIDER_NOT_SUPPORTED",PROVIDER_NOT_CONFIGURED:"MUSIC_PROVIDER_NOT_CONFIGURED",GENERATION_FAILED:"MUSIC_GENERATION_FAILED",POLL_TIMEOUT:"MUSIC_POLL_TIMEOUT",PROMPT_REQUIRED:"MUSIC_PROMPT_REQUIRED",DURATION_INVALID:"MUSIC_DURATION_INVALID",INVALID_INPUT:"MUSIC_INVALID_INPUT"},Yt=class extends Me{constructor(e){super({code:e.code,message:e.message,category:e.category??"execution",severity:e.severity??"high",retriable:e.retriable??!1,context:e.context,originalError:e.originalError}),this.name="MusicError"}},sm=class{static registry=new d0("MusicProcessor");static registerHandler(e,t){const r=e&&e.toLowerCase();this.registry.register(e,t),f.debug(`[MusicProcessor] Registered music handler: ${r}`)}static supports(e){return this.registry.supports(e)}static listProviders(){return this.registry.list()}static getHandler(e){return this.registry.get(e)}static clearHandlers(){this.registry.clear()}static buildSpanAttributes(e,t){return{"music.operation":"generate","music.provider":e,"music.duration":t.duration,"music.format":t.format,"music.genre":t.genre,"music.mood":t.mood}}static async generate(e,t){const r=Ce.createSpan("media.generation","music.generate",this.buildSpanAttributes(e,t));try{const n=t.prompt?.trim();if(!n)throw new Yt({code:er.PROMPT_REQUIRED,message:"Music generation requires a non-empty prompt",category:"validation",severity:"low",retriable:!1,context:{provider:e}});const o=this.getHandler(e);if(!o)throw new Yt({code:er.PROVIDER_NOT_SUPPORTED,message:`Music provider "${e}" is not registered. Available: ${this.listProviders().join(", ")}`,category:"configuration",severity:"high",retriable:!1,context:{provider:e,available:this.listProviders()}});if(!o.isConfigured())throw new Yt({code:er.PROVIDER_NOT_CONFIGURED,message:`Music provider "${e}" is not configured. Set the required credentials.`,category:"configuration",severity:"high",retriable:!1,context:{provider:e}});if(t.duration!==void 0&&o.maxDurationSeconds!==void 0&&t.duration>o.maxDurationSeconds)throw new Yt({code:er.DURATION_INVALID,message:`Requested duration (${t.duration}s) exceeds provider maximum (${o.maxDurationSeconds}s) for "${e}"`,category:"validation",severity:"medium",retriable:!1,context:{provider:e,requested:t.duration,maximum:o.maxDurationSeconds}});f.debug(`[MusicProcessor] Starting music generation with provider: ${e}`);const i=await o.generate({...t,prompt:n}),s=Ce.endSpan(r,1);return nt().recordSpan(s),f.info(`[MusicProcessor] Generated ${i.size} bytes (${e})`),i}catch(n){const o=Ce.endSpan(r,2,n instanceof Error?n.message:String(n));if(nt().recordSpan(o),n instanceof Yt)throw n;const i=n instanceof Error?n.message:String(n);throw new Yt({code:er.GENERATION_FAILED,message:`Music generation failed for provider "${e}": ${i}`,category:"execution",severity:"high",retriable:!0,context:{provider:e,duration:t.duration,format:t.format,genre:t.genre,mood:t.mood,tempo:t.tempo},originalError:n instanceof Error?n:void 0})}}}}}),wmr,Fy,bmr,Tmr,h_,_mr=S({"src/lib/music/providers/BeatovenMusic.ts"(){"use strict";z(),am(),Ma(),_I(),wmr="https://public-api.beatoven.ai",Fy=3e4,bmr=3e3,Tmr=5*6e4,h_=class{maxDurationSeconds=300;supportedFormats=["mp3","wav"];supportedGenres=["ambient","cinematic","corporate","lo-fi","rock","pop","electronic","orchestral","folk"];apiKey;baseUrl;constructor(e){const t=(e??process.env.BEATOVEN_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.BEATOVEN_BASE_URL??wmr).replace(/\/$/,"")}isConfigured(){return this.apiKey!==null}async generate(e){if(!this.apiKey)throw new Yt({code:er.PROVIDER_NOT_CONFIGURED,message:"BEATOVEN_API_KEY not configured",category:"configuration",severity:"high",retriable:!1});const t=Date.now(),r=e.format??"mp3";this.supportedFormats.includes(r)||f.warn(`[BeatovenMusic] Format "${r}" not supported \u2014 falling back to "mp3"`);const n=this.supportedFormats.includes(r)?r:"mp3",i=(await this.submitCompose(e,n)).task_id,s=await this.pollUntilComposed(i,e.timeout??Tmr),a=s.meta?.track_url;if(!a)throw new Yt({code:er.GENERATION_FAILED,message:`Beatoven task ${i} completed but no track_url returned`,category:"execution",severity:"high",retriable:!1,context:{taskId:i,taskResult:s}});const u=await this.downloadTrack(a),l=Date.now()-t;return f.info(`[BeatovenMusic] Generated ${u.length} bytes (${n}) in ${l}ms \u2014 task ${i}`),{buffer:u,format:n,size:u.length,duration:s.meta?.duration,provider:"beatoven",metadata:{latency:l,provider:"beatoven",model:"beatoven-default",jobId:i,trackId:s.meta?.track_id,projectId:s.meta?.project_id,requestedFormat:e.format}}}async submitCompose(e,t){const r=(e.duration??60)*1e3,n=[e.prompt];e.genre&&n.push(`Genre: ${e.genre}`),e.mood&&n.push(`Mood: ${e.mood}`),e.tempo!==void 0&&n.push(`Tempo: ${e.tempo} BPM`);const o={prompt:{text:n.join(". ")},duration:r,format:t},i=new AbortController,s=setTimeout(()=>i.abort(),Fy);let a;try{a=await fetch(`${this.baseUrl}/api/v1/tracks/compose`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(o),signal:i.signal})}catch(l){throw l instanceof Error&&l.name==="AbortError"?new Yt({code:er.GENERATION_FAILED,message:`Beatoven compose request timed out after ${Fy/1e3}s`,category:"network",severity:"high",retriable:!0,originalError:l}):new Yt({code:er.GENERATION_FAILED,message:`Beatoven compose network error: ${l instanceof Error?l.message:String(l)}`,category:"network",severity:"high",retriable:!0,originalError:l instanceof Error?l:void 0})}finally{clearTimeout(s)}if(!a.ok){const l=await a.text(),c=a.status===408||a.status===429||a.status>=500;throw new Yt({code:er.GENERATION_FAILED,message:`Beatoven compose failed: ${a.status} \u2014 ${l}`,category:c?"network":"execution",severity:"high",retriable:c,context:{status:a.status,body:l}})}const u=await a.json();if(!u.task_id)throw new Yt({code:er.GENERATION_FAILED,message:"Beatoven compose response missing task_id",category:"execution",severity:"high",retriable:!1,context:{response:u}});return u}async pollUntilComposed(e,t){const r=Date.now();for(;Date.now()-r<t;){const n=await this.fetchTaskStatus(e);if(n.status==="composed")return n;if(n.status==="failed")throw new Yt({code:er.GENERATION_FAILED,message:`Beatoven task ${e} failed: ${n.message??"unknown"}`,category:"execution",severity:"high",retriable:!1,context:{taskId:e,status:n}});await new Promise(o=>setTimeout(o,bmr))}throw new Yt({code:er.POLL_TIMEOUT,message:`Beatoven task ${e} did not complete within ${Math.round(t/1e3)}s`,category:"timeout",severity:"medium",retriable:!0,context:{taskId:e,totalTimeoutMs:t}})}async fetchTaskStatus(e){const t=new AbortController,r=setTimeout(()=>t.abort(),Fy);let n;try{n=await fetch(`${this.baseUrl}/api/v1/tasks/${e}`,{method:"GET",headers:{Authorization:`Bearer ${this.apiKey}`},signal:t.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?new Yt({code:er.GENERATION_FAILED,message:`Beatoven status poll timed out after ${Fy/1e3}s`,category:"network",severity:"medium",retriable:!0,originalError:o}):new Yt({code:er.GENERATION_FAILED,message:`Beatoven status poll network error: ${o instanceof Error?o.message:String(o)}`,category:"network",severity:"medium",retriable:!0,originalError:o instanceof Error?o:void 0,context:{taskId:e}})}finally{clearTimeout(r)}if(!n.ok){const o=await n.text();throw new Yt({code:er.GENERATION_FAILED,message:`Beatoven status request failed: ${n.status} \u2014 ${o}`,category:"execution",severity:"medium",retriable:n.status>=500,context:{status:n.status,taskId:e}})}return await n.json()}async downloadTrack(e){try{await TI(e)}catch(o){throw new Yt({code:er.GENERATION_FAILED,message:`Beatoven track URL rejected: ${o instanceof Error?o.message:String(o)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}const t=new AbortController,r=setTimeout(()=>t.abort(),Fy);let n;try{n=await fetch(e,{signal:t.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?new Yt({code:er.GENERATION_FAILED,message:`Beatoven track download timed out after ${Fy/1e3}s`,category:"network",severity:"medium",retriable:!0,originalError:o}):new Yt({code:er.GENERATION_FAILED,message:`Beatoven track download network error: ${o instanceof Error?o.message:String(o)}`,category:"network",severity:"medium",retriable:!0,originalError:o instanceof Error?o:void 0,context:{url:e}})}finally{clearTimeout(r)}if(!n.ok)throw new Yt({code:er.GENERATION_FAILED,message:`Beatoven track download failed: ${n.status}`,category:"network",severity:"medium",retriable:n.status>=500,context:{status:n.status,url:e}});try{return await Ly(n,pf,"Beatoven track")}catch(o){throw new Yt({code:er.GENERATION_FAILED,message:`Beatoven track download exceeded size limit: ${o instanceof Error?o.message:String(o)}`,category:"execution",severity:"high",retriable:!1,context:{url:e}})}}}}}),Emr,_me,f_,Smr=S({"src/lib/music/providers/ElevenLabsMusic.ts"(){"use strict";am(),z(),Ma(),Emr="https://api.elevenlabs.io/v1",_me=6e4,f_=class{maxDurationSeconds=22;supportedFormats=["mp3"];supportedGenres=["ambient","cinematic","lo-fi","electronic","orchestral","soundscape"];apiKey;baseUrl;constructor(e){const t=(e??process.env.ELEVENLABS_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.ELEVENLABS_BASE_URL??Emr).replace(/\/$/,"")}isConfigured(){return this.apiKey!==null}async generate(e){if(!this.apiKey)throw new Yt({code:er.PROVIDER_NOT_CONFIGURED,message:"ELEVENLABS_API_KEY not configured (shared with ElevenLabs TTS \u2014 same account, different endpoint)",category:"configuration",severity:"high",retriable:!1});const t=e.prompt?.trim();if(!t)throw new Yt({code:er.INVALID_INPUT,message:"ElevenLabs Music requires a non-empty prompt",category:"validation",severity:"low",retriable:!1});const r=e.duration??8;if(r<=0||r>this.maxDurationSeconds)throw new Yt({code:er.INVALID_INPUT,message:`ElevenLabs Music duration must be between 1 and ${this.maxDurationSeconds} seconds; got ${r}`,category:"validation",severity:"low",retriable:!1,context:{requested:r,maximum:this.maxDurationSeconds}});const n=Date.now(),o=r,i={text:this.buildPrompt({...e,prompt:t}),duration_seconds:o,prompt_influence:.3},s=new AbortController,a=setTimeout(()=>s.abort(),_me);let u;try{u=await fetch(`${this.baseUrl}/sound-generation`,{method:"POST",headers:{"xi-api-key":this.apiKey,"Content-Type":"application/json",Accept:"audio/mpeg"},body:JSON.stringify(i),signal:s.signal})}catch(d){throw d instanceof Error&&d.name==="AbortError"?new Yt({code:er.GENERATION_FAILED,message:`ElevenLabs Music request timed out after ${_me/1e3}s`,category:"network",severity:"high",retriable:!0,originalError:d}):new Yt({code:er.GENERATION_FAILED,message:`ElevenLabs Music network error: ${d instanceof Error?d.message:String(d)}`,category:"network",severity:"high",retriable:!0,originalError:d instanceof Error?d:void 0})}finally{clearTimeout(a)}if(!u.ok){const d=await u.text(),p=u.status===408||u.status===429||u.status>=500;throw new Yt({code:er.GENERATION_FAILED,message:`ElevenLabs Music synthesis failed: ${u.status} \u2014 ${d}`,category:p?"network":"execution",severity:"high",retriable:p,context:{status:u.status}})}const l=await Ly(u,pf,"ElevenLabs music"),c=Date.now()-n;return f.info(`[ElevenLabsMusic] Generated ${l.length} bytes in ${c}ms`),{buffer:l,format:"mp3",size:l.length,duration:o,provider:"elevenlabs-music",metadata:{latency:c,provider:"elevenlabs-music",model:"elevenlabs-sound-v1"}}}buildPrompt(e){const t=[e.prompt];return e.genre&&t.push(`Genre: ${e.genre}`),e.mood&&t.push(`Mood: ${e.mood}`),e.tempo!==void 0&&t.push(`${e.tempo} BPM`),t.join(". ")}}}}),kmr,Amr,Eme,g_,xmr=S({"src/lib/music/providers/LyriaMusic.ts"(){"use strict";am(),z(),zt(),kmr="https://generativelanguage.googleapis.com/v1beta",Amr="lyria-3-pro-preview",Eme=12e4,g_=class{maxDurationSeconds=30;supportedFormats=["wav"];supportedGenres=["ambient","classical","electronic","jazz","rock","pop","lo-fi","cinematic","orchestral","world"];apiKey;baseUrl;model;constructor(e){const t=(e??process.env.GOOGLE_AI_LYRIA_API_KEY??process.env.GOOGLE_API_KEY??process.env.GOOGLE_AI_API_KEY??process.env.GEMINI_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.LYRIA_BASE_URL??kmr).replace(/\/$/,""),this.model=process.env.LYRIA_MODEL??Amr}isConfigured(){return this.apiKey!==null}async generate(e){if(!this.apiKey)throw new Yt({code:er.PROVIDER_NOT_CONFIGURED,message:"Lyria requires one of: GOOGLE_API_KEY, GOOGLE_AI_LYRIA_API_KEY, GOOGLE_AI_API_KEY, or GEMINI_API_KEY",category:"configuration",severity:"high",retriable:!1});const t=Date.now(),r=Math.min(e.duration??16,this.maxDurationSeconds),o={contents:[{parts:[{text:`${this.buildPrompt(e)}. Duration: ${r} seconds`}]}],generationConfig:{responseModalities:["AUDIO"]}},i=new AbortController,s=setTimeout(()=>i.abort(),Eme);let a;try{a=await fetch(`${this.baseUrl}/models/${this.model}:generateContent?key=${this.apiKey}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:i.signal})}catch(p){throw p instanceof Error&&p.name==="AbortError"?new Yt({code:er.GENERATION_FAILED,message:`Lyria request timed out after ${Eme/1e3}s`,category:"network",severity:"high",retriable:!0,originalError:p}):p}finally{clearTimeout(s)}if(!a.ok){const p=await a.text(),m=a.status===408||a.status===429||a.status>=500;throw new Yt({code:er.GENERATION_FAILED,message:`Lyria generation failed: ${a.status} \u2014 ${pr(p)}`,category:m?"network":"execution",severity:"high",retriable:m,context:{status:a.status}})}const u=await a.json(),l=u.candidates?.[0]?.content?.parts?.find(p=>p.inlineData?.mimeType?.startsWith("audio/"));if(!l?.inlineData?.data)throw new Yt({code:er.GENERATION_FAILED,message:"Lyria response missing audio data",category:"execution",severity:"high",retriable:!1,context:{response:u}});const c=Buffer.from(l.inlineData.data,"base64"),d=Date.now()-t;return f.info(`[LyriaMusic] Generated ${c.length} bytes in ${d}ms \u2014 model ${this.model}`),{buffer:c,format:"wav",size:c.length,duration:r,provider:"lyria",metadata:{latency:d,provider:"lyria",model:this.model,sampleRate:48e3}}}buildPrompt(e){const t=[e.prompt];return e.genre&&t.push(`Genre: ${e.genre}`),e.mood&&t.push(`Mood: ${e.mood}`),e.tempo!==void 0&&t.push(`${e.tempo} BPM`),t.join(". ")}}}});function hf(e){const t=(e?.apiToken??process.env.REPLICATE_API_TOKEN??"").trim();return t?{apiToken:t,baseUrl:(e?.baseUrl??process.env.REPLICATE_BASE_URL??Cmr).replace(/\/$/,"")}:null}var Cmr,t5=S({"src/lib/adapters/replicate/auth.ts"(){"use strict";Cmr="https://api.replicate.com"}});async function WEn(e,t,r){const n=e.baseUrl??"https://api.replicate.com",[o,i]=t.model.split(":",2),s=i?`${n}/v1/predictions`:`${n}/v1/models/${o}/predictions`,a=i?{version:i,input:t.input}:{input:t.input};return t.webhook&&(a.webhook=t.webhook),t.webhookEventsFilter&&t.webhookEventsFilter.length>0&&(a.webhook_events_filter=t.webhookEventsFilter),kw(async()=>{const u=new AbortController,l=setTimeout(()=>u.abort(),y_);try{const c=await fetch(s,{method:"POST",headers:{Authorization:`Token ${e.apiToken}`,"Content-Type":"application/json",Prefer:"wait=60"},body:JSON.stringify(a),signal:u.signal});if(!c.ok){const d=await c.text();throw new Me({code:He.PROVIDER_NOT_AVAILABLE,message:`Replicate predictions submit failed: ${c.status} \u2014 ${pr(d,500)}`,category:"network",severity:"high",retriable:c.status>=500||c.status===429,retryAfterMs:Sw(c.headers)})}return await c.json()}catch(c){throw c instanceof Me?c:c instanceof Error&&c.name==="AbortError"?new Me({code:He.OPERATION_ABORTED,message:`Replicate predictions submit timed out after ${y_/1e3}s`,category:"timeout",severity:"high",retriable:!0,originalError:c}):c}finally{clearTimeout(l)}},void 0,"Replicate prediction submission",r)}async function KEn(e,t,r={}){const n=e.baseUrl??"https://api.replicate.com",o=Date.now(),i=r.timeoutMs??Rmr,s=r.pollIntervalMs??Imr;for(;Date.now()-o<i;){if(r.abortSignal?.aborted)throw new Me({code:He.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1});const a=new AbortController,u=setTimeout(()=>a.abort(),y_),l=()=>a.abort();r.abortSignal?.addEventListener("abort",l,{once:!0});let c;try{c=await fetch(`${n}/v1/predictions/${t}`,{method:"GET",headers:{Authorization:`Token ${e.apiToken}`},signal:a.signal})}catch(p){throw p instanceof Me?p:p instanceof Error&&p.name==="AbortError"?r.abortSignal?.aborted?new Me({code:He.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1,originalError:p}):new Me({code:He.OPERATION_ABORTED,message:`Replicate poll request timed out after ${y_/1e3}s`,category:"timeout",severity:"high",retriable:!0,originalError:p}):p}finally{r.abortSignal?.removeEventListener("abort",l),clearTimeout(u)}if(!c.ok){const p=await c.text();throw new Me({code:He.PROVIDER_NOT_AVAILABLE,message:`Replicate poll failed: ${c.status} \u2014 ${pr(p,500)}`,category:"network",severity:"high",retriable:c.status>=500||c.status===429,retryAfterMs:Sw(c.headers)})}const d=await c.json();if(d.status==="succeeded")return d;if(d.status==="failed"||d.status==="canceled")throw new Me({code:He.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${d.id} ${d.status}: ${d.error??"unknown"}`,category:"execution",severity:"high",retriable:d.status==="failed"});await new Promise((p,m)=>{const h=()=>{clearTimeout(g),m(new Me({code:He.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1}))},g=setTimeout(()=>{r.abortSignal?.removeEventListener("abort",h),p()},s);r.abortSignal?.addEventListener("abort",h,{once:!0})})}throw new Me({code:He.OPERATION_ABORTED,message:`Replicate prediction ${t} did not complete within ${Math.round(i/1e3)}s`,category:"timeout",severity:"high",retriable:!0})}async function CI(e,t,r={}){const n=await WEn(e,t);if(n.status==="succeeded")return n;if(n.status==="failed"||n.status==="canceled")throw new Me({code:He.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${n.id} ${n.status} on submit: ${n.error??"unknown"}`,category:"execution",severity:"high",retriable:n.status==="failed"});return KEn(e,n.id,r)}async function r5(e,t=$y){const r=e.output,n=Array.isArray(r)?r[0]:r;if(typeof n!="string")throw new Me({code:He.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${e.id} output is not a URL: ${typeof r}`,category:"execution",severity:"high",retriable:!1});try{const o=await im(n,{maxBytes:t,label:`Replicate prediction ${e.id}`,timeoutMs:y_});return f.debug(`[Replicate] Downloaded prediction ${e.id} output: ${o.length} bytes`),o}catch(o){if(o instanceof Me)throw o;const i=o instanceof Error?o.message:String(o);throw new Me({code:He.PROVIDER_NOT_AVAILABLE,message:`Replicate output download failed: ${i} \u2014 ${n}`,category:"network",severity:"high",retriable:!0,originalError:o instanceof Error?o:void 0})}}var y_,Imr,Rmr,n5=S({"src/lib/adapters/replicate/predictionLifecycle.ts"(){"use strict";z(),et(),zt(),Tp(),Q2(),Wd(),Ma(),y_=9e4,Imr=2e3,Rmr=5*6e4}}),Mmr,v_,Pmr=S({"src/lib/music/providers/ReplicateMusic.ts"(){"use strict";am(),z(),t5(),n5(),Ma(),_I(),Mmr="meta/musicgen:7be0f12c54a8d033a0fbd14418c9af98962da9a86f5ff7811f9b3423a1f0b7d7",v_=class{maxDurationSeconds=30;supportedFormats=["mp3","wav"];supportedGenres=["ambient","classical","electronic","rock","jazz","hip-hop","pop","lo-fi","cinematic","orchestral"];isConfigured(){return hf()!==null}async generate(e){const t=hf();if(!t)throw new Yt({code:er.PROVIDER_NOT_CONFIGURED,message:"REPLICATE_API_TOKEN not configured",category:"configuration",severity:"high",retriable:!1});const r=Date.now(),n=e.model??Mmr,o=e.format??"mp3",i=this.supportedFormats.includes(o)?o:"mp3",s=Math.min(e.duration??8,this.maxDurationSeconds),a={prompt:this.buildPrompt(e),duration:s,output_format:i,model_version:"stereo-large",normalization_strategy:"loudness"};if(e.tempo!==void 0&&(a.bpm=e.tempo),e.referenceAudio){const d=await this.resolveBuffer(e.referenceAudio);a.input_audio=`data:audio/${this.detectAudioType(d)};base64,${d.toString("base64")}`}let u;try{u=await CI(t,{model:n,input:a})}catch(d){throw new Yt({code:er.GENERATION_FAILED,message:`Replicate music generation failed: ${d instanceof Error?d.message:String(d)}`,category:"execution",severity:"high",retriable:!0,context:{model:n,duration:s,format:i,hasReferenceAudio:e.referenceAudio!==void 0},originalError:d instanceof Error?d:void 0})}let l;try{l=await r5(u,pf)}catch(d){throw new Yt({code:er.GENERATION_FAILED,message:`Replicate music download failed: ${d instanceof Error?d.message:String(d)}`,category:"network",severity:"medium",retriable:!0,context:{predictionId:u.id},originalError:d instanceof Error?d:void 0})}const c=Date.now()-r;return f.info(`[ReplicateMusic] Generated ${l.length} bytes in ${c}ms \u2014 model ${n}`),{buffer:l,format:i,size:l.length,duration:s,provider:"replicate",metadata:{latency:c,provider:"replicate",model:n,jobId:u.id}}}buildPrompt(e){const t=[e.prompt];return e.genre&&t.push(`Genre: ${e.genre}`),e.mood&&t.push(`Mood: ${e.mood}`),e.tempo!==void 0&&t.push(`${e.tempo} BPM`),t.join(". ")}async resolveBuffer(e){if(Buffer.isBuffer(e))return e;if(!/^https:\/\//.test(e))throw new Yt({code:er.INVALID_INPUT,message:`Invalid input: expected Buffer or HTTPS URL, got string "${e}". Local file reads are not supported.`,category:"validation",severity:"high",retriable:!1});try{await TI(e)}catch(i){throw new Yt({code:er.INVALID_INPUT,message:`Unsafe URL rejected: ${i instanceof Error?i.message:String(i)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}const t=6e4,r=new AbortController,n=setTimeout(()=>r.abort(),t);let o;try{o=await fetch(e,{signal:r.signal})}catch(i){throw i instanceof Error&&i.name==="AbortError"?new Yt({code:er.GENERATION_FAILED,message:`Replicate music reference-audio fetch timed out after ${t/1e3}s: ${e}`,category:"network",severity:"medium",retriable:!0}):i}finally{clearTimeout(n)}if(!o.ok)throw new Yt({code:er.GENERATION_FAILED,message:`Failed to fetch reference audio: ${e}: ${o.status}`,category:"network",severity:"medium",retriable:o.status>=500});try{return await Ly(o,pf,"Replicate reference audio")}catch(i){throw new Yt({code:er.INVALID_INPUT,message:`Replicate reference audio too large: ${i instanceof Error?i.message:String(i)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}}detectAudioType(e){return e.length<4?"mp3":e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70?"wav":e[0]===79&&e[1]===103&&e[2]===103&&e[3]===83?"ogg":e[0]===73&&e[1]===68&&e[2]===51?"mp3":e[0]===255&&(e[1]&224)===224?"mpeg":e.length>=8&&e[4]===102&&e[5]===116&&e[6]===121&&e[7]===112?"mp4":"mp3"}}}}),Sme={};ue(Sme,{BeatovenMusic:()=>h_,BeatovenMusicHandler:()=>h_,ElevenLabsMusic:()=>f_,ElevenLabsMusicHandler:()=>f_,LyriaMusic:()=>g_,LyriaMusicHandler:()=>g_,MUSIC_ERROR_CODES:()=>er,MusicError:()=>Yt,MusicProcessor:()=>sm,ReplicateMusic:()=>v_,ReplicateMusicHandler:()=>v_,registerDefaultMusicHandlers:()=>Dmr});function Dmr(){for(const{name:e,aliases:t,factory:r}of Nmr){const n=!sm.supports(e),o=(t??[]).filter(i=>!sm.supports(i));if(!(!n&&o.length===0))try{let i;if(n||(i=sm.getHandler(e)),!i&&(i=r(),!i.isConfigured()))continue;n&&sm.registerHandler(e,i);for(const s of o)sm.registerHandler(s,i)}catch(i){f.debug(`[music] ${e} auto-registration skipped: ${i instanceof Error?i.message:String(i)}`)}}}var Omr,Nmr,kme=S({"src/lib/music/index.ts"(){"use strict";Pw(),z(),am(),am(),_mr(),Smr(),xmr(),Pmr(),_mr(),Smr(),xmr(),Pmr(),Omr={beatoven:()=>new h_,"elevenlabs-music":()=>new f_,lyria:()=>new g_,replicate:()=>new v_},Nmr=Ep.filter(e=>e.kind==="music").map(e=>{const t=Omr[e.name];if(!t)throw new Error(`[music] no handler factory for catalog entry "${e.name}"`);return{name:e.name,aliases:e.aliases,factory:t}})}}),Lmr={};ue(Lmr,{AVATAR_ERROR_CODES:()=>Ct,AvatarError:()=>At,AvatarProcessor:()=>um});var Ct,At,um,ff=S({"src/lib/utils/avatarProcessor.ts"(){"use strict";ro(),et(),z(),lb(),Ct={PROVIDER_NOT_SUPPORTED:"AVATAR_PROVIDER_NOT_SUPPORTED",PROVIDER_NOT_CONFIGURED:"AVATAR_PROVIDER_NOT_CONFIGURED",GENERATION_FAILED:"AVATAR_GENERATION_FAILED",POLL_TIMEOUT:"AVATAR_POLL_TIMEOUT",INVALID_INPUT:"AVATAR_INVALID_INPUT",AUDIO_REQUIRED:"AVATAR_AUDIO_REQUIRED",IMAGE_REQUIRED:"AVATAR_IMAGE_REQUIRED",AUDIO_TOO_LONG:"AVATAR_AUDIO_TOO_LONG"},At=class extends Me{constructor(e){super({code:e.code,message:e.message,category:e.category??"execution",severity:e.severity??"high",retriable:e.retriable??!1,context:e.context,originalError:e.originalError}),this.name="AvatarError"}},um=class{static registry=new d0("AvatarProcessor");static registerHandler(e,t){const r=e&&e.toLowerCase();this.registry.register(e,t),f.debug(`[AvatarProcessor] Registered avatar handler: ${r}`)}static supports(e){return this.registry.supports(e)}static listProviders(){return this.registry.list()}static getHandler(e){return this.registry.get(e)}static clearHandlers(){this.registry.clear()}static buildSpanAttributes(e,t){return{"avatar.operation":"generate","avatar.provider":e,"avatar.quality":t.quality,"avatar.format":t.format,"avatar.has_text":t.text!==void 0,"avatar.has_audio":t.audio!==void 0}}static async generate(e,t){const r=Ce.createSpan("media.generation","avatar.generate",this.buildSpanAttributes(e,t));try{if(!t.image)throw new At({code:Ct.IMAGE_REQUIRED,message:"Avatar generation requires an `image` (Buffer, path, or URL)",category:"validation",severity:"medium",retriable:!1,context:{provider:e}});if(!t.audio&&!t.text)throw new At({code:Ct.INVALID_INPUT,message:"Avatar generation requires either `audio` (a Buffer/URL) or `text` (to be TTS'd by the provider).",category:"validation",severity:"high",retriable:!1,context:{provider:e}});const n=this.getHandler(e);if(!n)throw new At({code:Ct.PROVIDER_NOT_SUPPORTED,message:`Avatar provider "${e}" is not registered. Available: ${this.listProviders().join(", ")}`,category:"configuration",severity:"high",retriable:!1,context:{provider:e,available:this.listProviders()}});if(!n.isConfigured())throw new At({code:Ct.PROVIDER_NOT_CONFIGURED,message:`Avatar provider "${e}" is not configured. Set the required credentials.`,category:"configuration",severity:"high",retriable:!1,context:{provider:e}});f.debug(`[AvatarProcessor] Starting avatar generation with provider: ${e}`);const o=await n.generate(t),i=Ce.endSpan(r,1);return nt().recordSpan(i),f.info(`[AvatarProcessor] Generated ${o.size} bytes (${e})`),o}catch(n){const o=Ce.endSpan(r,2,n instanceof Error?n.message:String(n));if(nt().recordSpan(o),n instanceof At)throw n;const i=n instanceof Error?n.message:String(n);throw new At({code:Ct.GENERATION_FAILED,message:`Avatar generation failed for provider "${e}": ${i}`,category:"execution",severity:"high",retriable:!0,context:{provider:e},originalError:n instanceof Error?n:void 0})}}}}}),$mr,Ame,Fmr,Umr,w_,Bmr=S({"src/lib/avatar/providers/DIDAvatar.ts"(){"use strict";z(),zt(),ff(),_I(),Ma(),$mr="https://api.d-id.com",Ame=3e4,Fmr=3e3,Umr=5*6e4,w_=class{maxAudioDurationSeconds=60;supportedFormats=["mp4"];apiKey;baseUrl;constructor(e){const t=(e??process.env.DID_API_KEY??process.env.D_ID_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.DID_BASE_URL??process.env.D_ID_BASE_URL??$mr).replace(/\/$/,"")}isConfigured(){return this.apiKey!==null}async generate(e){if(!this.apiKey)throw new At({code:Ct.PROVIDER_NOT_CONFIGURED,message:"DID_API_KEY not configured",category:"configuration",severity:"high",retriable:!1});if(!e.audio&&!e.text)throw new At({code:Ct.AUDIO_REQUIRED,message:"D-ID requires either `audio` (Buffer/path) or `text` (with voice id) to drive the talk",category:"validation",severity:"medium",retriable:!1});const t=Date.now(),r=await this.uploadImage(e.image),n=e.audio?await this.uploadAudio(e.audio):void 0,o=await this.submitTalk(e,r,n),i=await this.pollUntilDone(o,e.timeout??Umr,e.abortSignal);if(!i.result_url)throw new At({code:Ct.GENERATION_FAILED,message:`D-ID talk ${o} completed but no result_url returned`,category:"execution",severity:"high",retriable:!1,context:{talkId:o,completed:i}});try{await TI(i.result_url)}catch(u){throw new At({code:Ct.GENERATION_FAILED,message:`D-ID result_url rejected as unsafe: ${u instanceof Error?u.message:String(u)}`,category:"validation",severity:"high",retriable:!1,context:{talkId:o,url:i.result_url}})}const s=await this.downloadResult(i.result_url),a=Date.now()-t;return f.info(`[DIDAvatar] Generated ${s.length} bytes in ${a}ms \u2014 talk ${o}`),{buffer:s,format:"mp4",size:s.length,duration:i.duration,provider:"d-id",metadata:{latency:a,provider:"d-id",jobId:o}}}async uploadImage(e){if(typeof e=="string"&&/^https:\/\//.test(e))return e;const t=await this.resolveBuffer(e),r=new FormData;r.append("image",new Blob([new Uint8Array(t)],{type:this.detectImageMime(t)}),"source.png");const n=await this.fetchWithTimeout(`${this.baseUrl}/images`,{method:"POST",headers:{Authorization:`Basic ${this.apiKey}`},body:r}),o=await this.assertOk(n,"image upload");if(!o.url)throw new At({code:Ct.GENERATION_FAILED,message:"D-ID image upload succeeded but returned no URL",category:"execution",severity:"high",retriable:!1});return o.url}async uploadAudio(e){if(typeof e=="string"&&/^https:\/\//.test(e))return e;const t=await this.resolveBuffer(e),r=this.detectAudioType(t),o={mp3:"mp3",mpeg:"mp3",wav:"wav",ogg:"ogg",mp4:"m4a"}[r]??"mp3",i=new FormData;i.append("audio",new Blob([new Uint8Array(t)],{type:`audio/${r}`}),`narration.${o}`);const s=await this.fetchWithTimeout(`${this.baseUrl}/audios`,{method:"POST",headers:{Authorization:`Basic ${this.apiKey}`},body:i}),a=await this.assertOk(s,"audio upload");if(!a.url)throw new At({code:Ct.GENERATION_FAILED,message:"D-ID audio upload succeeded but returned no URL",category:"execution",severity:"high",retriable:!1});return a.url}async submitTalk(e,t,r){const n=r?{type:"audio",audio_url:r}:{type:"text",input:e.text,provider:{type:"microsoft",voice_id:e.voice??"en-US-JennyNeural"}},o={source_url:t,script:n,config:{result_format:"mp4",stitch:!0}},i=await this.fetchWithTimeout(`${this.baseUrl}/talks`,{method:"POST",headers:{Authorization:`Basic ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(o)}),s=await this.assertOk(i,"talk submit");if(!s.id)throw new At({code:Ct.GENERATION_FAILED,message:"D-ID talk submit returned no id",category:"execution",severity:"high",retriable:!1});return s.id}async pollUntilDone(e,t,r){const n=Date.now();for(;Date.now()-n<t;){if(r?.aborted)throw new At({code:Ct.GENERATION_FAILED,message:`D-ID poll for talk ${e} aborted by caller`,category:"network",severity:"medium",retriable:!1,context:{talkId:e}});const o=await this.fetchWithTimeout(`${this.baseUrl}/talks/${e}`,{method:"GET",headers:{Authorization:`Basic ${this.apiKey}`}},r),i=await this.assertOk(o,"talk status");if(i.status==="done")return i;if(i.status==="error"||i.status==="rejected")throw new At({code:Ct.GENERATION_FAILED,message:`D-ID talk ${e} ${i.status}: ${i.error?.description??"unknown"}`,category:"execution",severity:"high",retriable:!1,context:{talkId:e,status:i.status,error:i.error}});await new Promise((s,a)=>{const u=()=>{clearTimeout(l),a(new At({code:Ct.GENERATION_FAILED,message:`D-ID poll for talk ${e} aborted by caller`,category:"network",severity:"medium",retriable:!1,context:{talkId:e}}))},l=setTimeout(()=>{r?.removeEventListener("abort",u),s()},Fmr);r?.addEventListener("abort",u,{once:!0})})}throw new At({code:Ct.POLL_TIMEOUT,message:`D-ID talk ${e} did not complete within ${Math.round(t/1e3)}s`,category:"timeout",severity:"medium",retriable:!0,context:{talkId:e}})}async downloadResult(e){const t=await this.fetchWithTimeout(e,{method:"GET"});if(!t.ok)throw new At({code:Ct.GENERATION_FAILED,message:`D-ID result download failed: ${t.status}`,category:"network",severity:"medium",retriable:t.status>=500,context:{status:t.status,url:e}});try{return await Ly(t,$y,"D-ID result")}catch(r){throw new At({code:Ct.GENERATION_FAILED,message:`D-ID result download rejected: ${r instanceof Error?r.message:String(r)}`,category:"network",severity:"high",retriable:!1,context:{url:e},originalError:r instanceof Error?r:void 0})}}async resolveBuffer(e){if(Buffer.isBuffer(e))return e;if(!/^https:\/\//.test(e))throw new At({code:Ct.INVALID_INPUT,message:`Invalid input: expected Buffer or HTTPS URL, got string "${e}". Local file reads are not supported.`,category:"validation",severity:"high",retriable:!1});try{await TI(e)}catch(n){throw new At({code:Ct.INVALID_INPUT,message:`Unsafe URL rejected: ${n instanceof Error?n.message:String(n)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}const t=await this.fetchWithTimeout(e,{method:"GET"});if(!t.ok)throw new At({code:Ct.INVALID_INPUT,message:`Failed to fetch input from ${e}: ${t.status}`,category:"network",severity:"medium",retriable:t.status>=500,context:{url:e,status:t.status}});const r=Math.max(pf,mf);try{return await Ly(t,r,"D-ID input")}catch(n){throw new At({code:Ct.INVALID_INPUT,message:`D-ID input download rejected: ${n instanceof Error?n.message:String(n)}`,category:"network",severity:"high",retriable:!1,context:{url:e},originalError:n instanceof Error?n:void 0})}}detectImageMime(e){return e.length<4?"image/jpeg":e[0]===137&&e[1]===80?"image/png":e[0]===255&&e[1]===216?"image/jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":"image/jpeg"}detectAudioType(e){return e.length<4?"mp3":e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70?"wav":e[0]===79&&e[1]===103&&e[2]===103&&e[3]===83?"ogg":e[0]===73&&e[1]===68&&e[2]===51?"mp3":e[0]===255&&(e[1]&224)===224?"mpeg":e.length>=8&&e[4]===102&&e[5]===116&&e[6]===121&&e[7]===112?"mp4":"mp3"}async fetchWithTimeout(e,t,r){const n=new AbortController,o=setTimeout(()=>n.abort(),Ame),i=()=>n.abort();r?.addEventListener("abort",i,{once:!0});try{return await fetch(e,{...t,signal:n.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?r?.aborted?new At({code:Ct.GENERATION_FAILED,message:`D-ID request to ${e} aborted by caller`,category:"network",severity:"medium",retriable:!1,originalError:s}):new At({code:Ct.GENERATION_FAILED,message:`D-ID request to ${e} timed out after ${Ame/1e3}s`,category:"network",severity:"high",retriable:!0,originalError:s}):s}finally{r?.removeEventListener("abort",i),clearTimeout(o)}}async assertOk(e,t){if(e.ok)return e.json();const r=await e.text(),n=e.status===408||e.status===429||e.status>=500;throw new At({code:Ct.GENERATION_FAILED,message:`D-ID ${t} failed: ${e.status} \u2014 ${pr(r,500)}`,category:n?"network":"execution",severity:"high",retriable:n,context:{status:e.status,label:t}})}}}}),zmr,o5,Gmr,xme,b_,qmr=S({"src/lib/avatar/providers/HeyGenAvatar.ts"(){"use strict";ff(),z(),zt(),Wd(),Ma(),zmr="https://api.heygen.com/v2",o5=3e4,Gmr=5e3,xme=5*6e4,b_=class{maxAudioDurationSeconds=300;supportedFormats=["mp4"];apiKey;baseUrl;constructor(e){const t=(e??process.env.HEYGEN_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.HEYGEN_BASE_URL??zmr).replace(/\/$/,"")}isConfigured(){return this.apiKey!==null}async generate(e){if(!this.apiKey)throw new At({code:Ct.PROVIDER_NOT_CONFIGURED,message:"HEYGEN_API_KEY not configured",category:"configuration",severity:"high",retriable:!1});if(!e.text&&!e.audio)throw new At({code:Ct.AUDIO_REQUIRED,message:"HeyGen requires either `text` or `audio` to drive the avatar",category:"validation",severity:"medium",retriable:!1});const t=Date.now(),r=e.abortSignal,n=await this.submitVideo(e),o=await this.pollUntilComplete(n,r),i=await this.download(o),s=Date.now()-t;return f.info(`[HeyGenAvatar] Generated ${i.length} bytes in ${s}ms \u2014 video ${n}`),{buffer:i,format:"mp4",size:i.length,provider:"heygen",metadata:{latency:s,provider:"heygen",jobId:n}}}async submitVideo(e){const t=e,r=t.avatarId??(typeof e.image=="string"&&/^[a-zA-Z0-9_-]{20,}$/.test(e.image)?e.image:void 0);if(!r)throw new At({code:Ct.INVALID_INPUT,message:"HeyGen requires `avatarId` (HeyGen avatar catalog id). Pass via options.avatarId or as options.image with a valid HeyGen id.",category:"validation",severity:"medium",retriable:!1});if(e.audio!==void 0){if(Buffer.isBuffer(e.audio))throw new At({code:Ct.INVALID_INPUT,message:"HeyGen requires a publicly accessible audio URL; got a binary Buffer. Upload the audio to a hosted location and pass the HTTPS URL instead.",category:"validation",severity:"medium",retriable:!1});if(typeof e.audio!="string"||!/^https?:\/\//i.test(e.audio))throw new At({code:Ct.INVALID_INPUT,message:"HeyGen requires a publicly accessible HTTPS audio URL; got an unsupported audio input type. Upload the audio to a hosted location and pass the HTTPS URL instead.",category:"validation",severity:"medium",retriable:!1})}const n=e.audio?{type:"audio",audio_url:e.audio}:{type:"text",input_text:e.text,voice_id:e.voice??"1bd001e7e50f421d891986aad5158bc8"},o={video_inputs:[{character:{type:"avatar",avatar_id:r,avatar_style:"normal"},voice:n,background:{type:"color",value:t.backgroundColor??"#FFFFFF"}}],dimension:{width:t.width??1280,height:t.height??720}},i=await this.fetchWithTimeout(`${this.baseUrl}/video/generate`,{method:"POST",headers:{"X-API-Key":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify(o)});if(!i.ok){const u=await i.text(),l=i.status===408||i.status===429||i.status>=500;throw new At({code:Ct.GENERATION_FAILED,message:`HeyGen submit failed: ${i.status} \u2014 ${pr(u,500)}`,category:l?"network":"execution",severity:"high",retriable:l,context:{status:i.status}})}const s=await i.json(),a=s.data?.video_id;if(!a)throw new At({code:Ct.GENERATION_FAILED,message:"HeyGen submit response missing video_id",category:"execution",severity:"high",retriable:!1,context:{response:s}});return a}async pollUntilComplete(e,t){const r=Date.now(),n=this.baseUrl.replace(/\/v2$/,"/v1");for(;Date.now()-r<xme;){if(t?.aborted)throw new At({code:Ct.GENERATION_FAILED,message:`HeyGen poll for video ${e} aborted by caller`,category:"network",severity:"medium",retriable:!1,context:{videoId:e}});const o=await this.fetchWithTimeout(`${n}/video_status.get?video_id=${e}`,{method:"GET",headers:{"X-API-Key":this.apiKey}},t);if(!o.ok){const s=await o.text();throw new At({code:Ct.GENERATION_FAILED,message:`HeyGen poll failed: ${o.status} \u2014 ${pr(s,500)}`,category:"network",severity:"medium",retriable:o.status>=500,context:{status:o.status,videoId:e}})}const i=await o.json();if(i.data?.status==="completed"){const s=i.data.video_url;if(!s)throw new At({code:Ct.GENERATION_FAILED,message:`HeyGen video ${e} completed but no URL returned`,category:"execution",severity:"high",retriable:!1,context:{videoId:e,data:i}});return s}if(i.data?.status==="failed")throw new At({code:Ct.GENERATION_FAILED,message:`HeyGen video ${e} failed: ${i.data?.error?.message??"unknown"}`,category:"execution",severity:"high",retriable:!1,context:{videoId:e,data:i}});await new Promise((s,a)=>{const u=()=>{clearTimeout(l),a(new At({code:Ct.GENERATION_FAILED,message:`HeyGen poll for video ${e} aborted by caller`,category:"network",severity:"medium",retriable:!1,context:{videoId:e}}))},l=setTimeout(()=>{t?.removeEventListener("abort",u),s()},Gmr);t?.addEventListener("abort",u,{once:!0})})}throw new At({code:Ct.POLL_TIMEOUT,message:`HeyGen video ${e} did not complete within ${xme/1e3}s`,category:"timeout",severity:"medium",retriable:!0,context:{videoId:e}})}async download(e){try{return await im(e,{maxBytes:$y,label:"HeyGen video",timeoutMs:o5})}catch(t){throw new At({code:Ct.GENERATION_FAILED,message:`HeyGen video download rejected: ${t instanceof Error?t.message:String(t)}`,category:"network",severity:"high",retriable:!1,context:{url:e},originalError:t instanceof Error?t:void 0})}}async fetchWithTimeout(e,t,r){const n=new AbortController;let o=!1;const i=setTimeout(()=>{o=!0,n.abort()},o5),s=()=>n.abort();r?.addEventListener("abort",s,{once:!0});try{return await fetch(e,{...t,signal:n.signal})}catch(a){throw a instanceof Error&&a.name==="AbortError"?r?.aborted?new At({code:Ct.GENERATION_FAILED,message:`HeyGen request to ${e} was aborted by the caller`,category:"network",severity:"medium",retriable:!1,originalError:a}):o?new At({code:Ct.GENERATION_FAILED,message:`HeyGen request to ${e} timed out after ${o5/1e3}s`,category:"network",severity:"high",retriable:!0,originalError:a}):new At({code:Ct.GENERATION_FAILED,message:`HeyGen request to ${e} was aborted`,category:"network",severity:"high",retriable:!0,originalError:a}):a}finally{r?.removeEventListener("abort",s),clearTimeout(i)}}}}}),jmr,T_,Vmr=S({"src/lib/avatar/providers/ReplicateAvatar.ts"(){"use strict";ff(),z(),t5(),n5(),Ma(),_I(),jmr="douwantech/musetalk:5501004e78525e4bbd9fa20d1e75ad51fddce5a274bec07b9b16d685e34eeaf8",T_=class{maxAudioDurationSeconds=60;supportedFormats=["mp4"];isConfigured(){return hf()!==null}async generate(e){const t=hf();if(!t)throw new At({code:Ct.PROVIDER_NOT_CONFIGURED,message:"REPLICATE_API_TOKEN not configured",category:"configuration",severity:"high",retriable:!1});if(!e.audio)throw new At({code:Ct.AUDIO_REQUIRED,message:"Replicate avatar handler (MuseTalk) requires `audio` (Buffer or path); text-only is not supported. Use D-ID for text-driven talks or chain TTS + Replicate.",category:"validation",severity:"medium",retriable:!1});const r=Date.now(),n=e.model??jmr,o=await this.resolveBuffer(e.image,mf,"Replicate avatar reference image"),i=await this.resolveBuffer(e.audio,pf,"Replicate avatar reference audio"),s=`data:image/${this.detectImageType(o)};base64,${o.toString("base64")}`,a=`data:audio/${this.detectAudioType(i)};base64,${i.toString("base64")}`;let u;try{u=await CI(t,{model:n,input:{image:s,audio:a,bbox_shift:0,fps:25}})}catch(d){throw new At({code:Ct.GENERATION_FAILED,message:`Replicate avatar generation failed: ${d instanceof Error?d.message:String(d)}`,category:"execution",severity:"high",retriable:!0,context:{model:n},originalError:d instanceof Error?d:void 0})}let l;try{l=await r5(u,$y)}catch(d){throw new At({code:Ct.GENERATION_FAILED,message:`Replicate avatar download failed: ${d instanceof Error?d.message:String(d)}`,category:"network",severity:"medium",retriable:!0,context:{predictionId:u.id},originalError:d instanceof Error?d:void 0})}const c=Date.now()-r;return f.info(`[ReplicateAvatar] Generated ${l.length} bytes in ${c}ms \u2014 model ${n}`),{buffer:l,format:"mp4",size:l.length,provider:"replicate",metadata:{latency:c,provider:"replicate",model:n,jobId:u.id}}}async resolveBuffer(e,t=mf,r="Replicate avatar input"){if(Buffer.isBuffer(e)){if(e.length>t)throw new At({code:Ct.INVALID_INPUT,message:`${r} too large: ${e.length} bytes exceeds ${t}`,category:"validation",severity:"high",retriable:!1});return e}if(!/^https:\/\//.test(e))throw new At({code:Ct.INVALID_INPUT,message:`Invalid input: expected Buffer or HTTPS URL, got string "${e}". Local file reads are not supported.`,category:"validation",severity:"high",retriable:!1});try{await TI(e)}catch(a){throw new At({code:Ct.INVALID_INPUT,message:`Unsafe URL rejected: ${a instanceof Error?a.message:String(a)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}const n=6e4,o=new AbortController,i=setTimeout(()=>o.abort(),n);let s;try{s=await fetch(e,{signal:o.signal})}catch(a){throw a instanceof Error&&a.name==="AbortError"?new At({code:Ct.INVALID_INPUT,message:`Replicate avatar input fetch timed out after ${n/1e3}s: ${e}`,category:"network",severity:"medium",retriable:!0}):a}finally{clearTimeout(i)}if(!s.ok)throw new At({code:Ct.INVALID_INPUT,message:`Failed to fetch ${e}: ${s.status}`,category:"network",severity:"medium",retriable:s.status>=500});try{return await Ly(s,t,r)}catch(a){throw new At({code:Ct.INVALID_INPUT,message:`${r} too large: ${a instanceof Error?a.message:String(a)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}}detectAudioType(e){return e.length<4?"mp3":e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70?"wav":e[0]===79&&e[1]===103&&e[2]===103&&e[3]===83?"ogg":e[0]===73&&e[1]===68&&e[2]===51?"mp3":e[0]===255&&(e[1]&224)===224?"mpeg":e.length>=8&&e[4]===102&&e[5]===116&&e[6]===121&&e[7]===112?"mp4":"mp3"}detectImageType(e){return e.length<4?"jpeg":e[0]===137&&e[1]===80?"png":e[0]===255&&e[1]===216?"jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"webp":"jpeg"}}}}),Cme={};ue(Cme,{AVATAR_ERROR_CODES:()=>Ct,AvatarError:()=>At,AvatarProcessor:()=>um,DIDAvatar:()=>w_,DIDAvatarHandler:()=>w_,HeyGenAvatar:()=>b_,HeyGenAvatarHandler:()=>b_,ReplicateAvatar:()=>T_,ReplicateAvatarHandler:()=>T_,registerDefaultAvatarHandlers:()=>Hmr});function Hmr(){for(const{name:e,aliases:t,factory:r}of Kmr){const n=!um.supports(e),o=(t??[]).filter(i=>!um.supports(i));if(!(!n&&o.length===0))try{let i;if(n||(i=um.getHandler(e)),!i&&(i=r(),!i.isConfigured()))continue;n&&um.registerHandler(e,i);for(const s of o)um.registerHandler(s,i)}catch(i){f.debug(`[avatar] ${e} auto-registration skipped: ${i instanceof Error?i.message:String(i)}`)}}}var Wmr,Kmr,Ime=S({"src/lib/avatar/index.ts"(){"use strict";Pw(),z(),ff(),ff(),Bmr(),qmr(),Vmr(),Bmr(),qmr(),Vmr(),Wmr={"d-id":()=>new w_,heygen:()=>new b_,replicate:()=>new T_},Kmr=Ep.filter(e=>e.kind==="avatar").map(e=>{const t=Wmr[e.name];if(!t)throw new Error(`[avatar] no handler factory for catalog entry "${e.name}"`);return{name:e.name,aliases:e.aliases,factory:t}})}}),__,i5,Rme=S({"src/lib/mcp/elicitation/elicitationManager.ts"(){"use strict";oo(),qt(),z(),__=class extends wn{config;pendingRequests=new Map;constructor(e={}){super(),this.config={defaultTimeout:e.defaultTimeout??6e4,enabled:e.enabled??!0,handler:e.handler??this.defaultHandler.bind(this),fallbackBehavior:e.fallbackBehavior??"timeout"}}setHandler(e){this.config.handler=e}setEnabled(e){if(this.config.enabled=e,!e)for(const[t,r]of this.pendingRequests)r.settled||(r.settled=!0,this.handleDisabled(r.request,r.resolve),r.timer&&clearTimeout(r.timer),this.pendingRequests.delete(t))}isEnabled(){return this.config.enabled}async request(e){const t={...e,id:e.id??st()};if(!this.config.enabled)return this.handleDisabledRequest(t);const r=t.timeout??this.config.defaultTimeout;return new Promise(n=>{const o=setTimeout(()=>{const i=this.pendingRequests.get(t.id);!i||i.settled||(i.settled=!0,this.handleTimeout(t,n))},r);this.pendingRequests.set(t.id,{request:t,resolve:n,timer:o,settled:!1}),this.emit("elicitationRequested",t),Promise.resolve().then(()=>this.config.handler(t)).then(i=>{const s=this.pendingRequests.get(t.id);!s||s.settled||(s.settled=!0,clearTimeout(o),this.pendingRequests.delete(t.id),this.emit("elicitationResponded",i),n(i))}).catch(i=>{const s=this.pendingRequests.get(t.id);if(!s||s.settled)return;s.settled=!0,clearTimeout(o),this.pendingRequests.delete(t.id);const a={requestId:t.id,responded:!1,error:i instanceof Error?i.message:String(i),timestamp:Date.now()};this.emit("elicitationError",{request:t,error:i}),n(a)})})}async confirm(e,t){const r={type:"confirmation",message:e,toolName:t?.toolName??"unknown",serverId:t?.serverId,confirmLabel:t?.confirmLabel,cancelLabel:t?.cancelLabel,timeout:t?.timeout};return(await this.request(r)).value===!0}async getText(e,t){const r={type:"text",message:e,toolName:t?.toolName??"unknown",placeholder:t?.placeholder,defaultValue:t?.defaultValue,timeout:t?.timeout};return(await this.request(r)).value}async select(e,t,r){const n={type:"select",message:e,toolName:r?.toolName??"unknown",options:t,timeout:r?.timeout};return(await this.request(n)).value}async multiSelect(e,t,r){const n={type:"multiselect",message:e,toolName:r?.toolName??"unknown",options:t,timeout:r?.timeout,minSelections:r?.minSelections,maxSelections:r?.maxSelections};return(await this.request(n)).value}async form(e,t,r){const n={type:"form",message:e,toolName:r?.toolName??"unknown",serverId:r?.serverId,fields:t,submitLabel:r?.submitLabel,timeout:r?.timeout};return(await this.request(n)).value}async getSecret(e,t){const r={type:"secret",message:e,toolName:t?.toolName??"unknown",hint:t?.hint,timeout:t?.timeout};return(await this.request(r)).value}cancel(e,t){const r=this.pendingRequests.get(e);if(r){if(r.settled)return;r.settled=!0,r.timer&&clearTimeout(r.timer);const n={requestId:e,responded:!1,cancelled:!0,error:t,timestamp:Date.now()};r.resolve(n),this.pendingRequests.delete(e),this.emit("elicitationCancelled",{requestId:e,reason:t})}}async defaultHandler(e){return f.warn(`[ElicitationManager] No handler for elicitation request: ${e.id}`),e.defaultValue!==void 0?{requestId:e.id,responded:!0,value:e.defaultValue,timestamp:Date.now()}:{requestId:e.id,responded:!1,error:"No elicitation handler configured",timestamp:Date.now()}}handleTimeout(e,t){this.pendingRequests.delete(e.id);const r={requestId:e.id,responded:!1,timedOut:!0,value:e.defaultValue,timestamp:Date.now()};this.emit("elicitationTimeout",{request:e}),t(r)}handleDisabled(e,t){t(this.handleDisabledRequest(e))}handleDisabledRequest(e){switch(this.config.fallbackBehavior){case"default":return{requestId:e.id,responded:e.defaultValue!==void 0,value:e.defaultValue,timestamp:Date.now()};case"error":return{requestId:e.id,responded:!1,error:"Elicitation is disabled",timestamp:Date.now()};default:return{requestId:e.id,responded:!1,timedOut:!0,value:e.defaultValue,timestamp:Date.now()}}}getPendingCount(){return this.pendingRequests.size}getPendingRequests(){return Array.from(this.pendingRequests.values()).map(e=>e.request)}clearPending(e){for(const[t]of this.pendingRequests)this.cancel(t,e??"Cleared")}},i5=new __}}),Jmr={};ue(Jmr,{ElicitationManager:()=>__,globalElicitationManager:()=>i5});var Xmr=S({"src/lib/mcp/elicitation/index.ts"(){"use strict";Rme()}});function Mc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function iu(e,t){const r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function Mme(e,t){const r=e[t];return Array.isArray(r)?r:[]}function II(e){return e.filter(t=>t!==void 0)}function JEn(e){return e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e)}function XEn(e){if(e.type!=="official"&&e.type!=="custom")return;const t=e.url??(e.type==="official"?thr:"");let r;try{r=new URL(t)}catch{return}if(r.protocol!=="https:"&&r.protocol!=="http:"||r.username!==""||r.password!==""||e.authToken&&r.protocol==="http:"&&!JEn(r.hostname))return;const n=r.pathname.replace(/\/+$/,""),o=n.endsWith(Pme)?n:`${n}${Pme}`;return{config:e,apiBase:`${r.origin}${o}`}}function YEn(e){if(!Mc(e))return;const t=iu(e,"name");return t===void 0?void 0:{name:t,isRequired:e.isRequired===!0,isSecret:e.isSecret===!0}}function Ymr(e){if(!Mc(e))return;const t=iu(e,"type");if(t===void 0)return;const r=iu(e,"url");return r===void 0?{type:t}:{type:t,url:r}}function ZEn(e){if(!Mc(e))return;const t=iu(e,"registryType"),r=iu(e,"identifier");if(t===void 0||r===void 0)return;const n=iu(e,"version"),o=Ymr(e.transport);return{registryType:t,identifier:r,...n===void 0?{}:{version:n},...o===void 0?{}:{transport:o},environmentVariables:II(Mme(e,"environmentVariables").map(YEn))}}function QEn(e){if(!Mc(e))return;const t=iu(e,"name");if(t===void 0)return;const r=Mc(e.repository)?e.repository:void 0,n=r===void 0?void 0:iu(r,"url"),o=iu(e,"websiteUrl");return{name:t,description:iu(e,"description")??"",version:iu(e,"version")??"",...n===void 0?{}:{repositoryUrl:n},...o===void 0?{}:{websiteUrl:o},packages:II(Mme(e,"packages").map(ZEn)),remotes:II(Mme(e,"remotes").map(Ymr))}}function Zmr(e){if(!Mc(e))return;const t=QEn(e.server);if(t===void 0)return;const r=Mc(e._meta)?e._meta:void 0,n=r!==void 0?r[rhr]:void 0,o=Mc(n)?iu(n,"status"):void 0,i=Mc(n)?iu(n,"updatedAt"):void 0;return{server:t,...o===void 0?{}:{status:o},...i===void 0?{}:{updatedAt:i}}}function eSn(e){if(!Mc(e)||!Array.isArray(e.servers))throw new Error("registry list response has no servers array");const t=Mc(e.metadata)?e.metadata:void 0,r=t===void 0?void 0:iu(t,"nextCursor");return{records:II(e.servers.map(Zmr)),...r===void 0?{}:{nextCursor:r}}}function Qmr(e){switch(e){case"stdio":return"stdio";case"streamable-http":return"http";case"sse":return"sse";default:return}}function tSn(e){if(!(e.registryType!=="npm"||e.identifier.length>ohr||!nhr.test(e.identifier)))return e.version===void 0?e.identifier:e.version.length<=shr&&ihr.test(e.version)?`${e.identifier}@${e.version}`:void 0}function ehr(e,t){const{server:r}=e,n=r.packages.map(u=>({pkg:u,spec:tSn(u)})).find(u=>u.spec!==void 0),o=Array.from(new Set(II([...r.packages.map(u=>u.transport===void 0?void 0:Qmr(u.transport.type)),...r.remotes.map(u=>Qmr(u.type))]))),i=n===void 0?[]:n.pkg.environmentVariables.filter(u=>u.isRequired).map(u=>u.name),s=r.remotes.flatMap(u=>u.url===void 0?[]:[{type:u.type,url:u.url}]),a={source:"remote-registry",registry:t,...e.status===void 0?{}:{registryStatus:e.status},packages:r.packages.map(u=>({registryType:u.registryType,identifier:u.identifier,...u.version===void 0?{}:{version:u.version}})),remotes:s};return{id:r.name,name:r.name,description:r.description,version:r.version,...r.websiteUrl===void 0?{}:{homepage:r.websiteUrl},...r.repositoryUrl===void 0?{}:{repository:r.repositoryUrl},...n===void 0?{}:{npmPackage:n.pkg.identifier,command:"npx",args:["-y",n.spec],installCommand:`npx -y ${n.spec}`},...i.length===0?{}:{requiredEnvVars:i},...o.length===0?{}:{transports:o},...e.updatedAt===void 0?{}:{lastUpdated:e.updatedAt},verified:!1,metadata:a}}var thr,Pme,rhr,nhr,ohr,ihr,shr,rSn=S({"src/lib/mcp/mcpRegistryRemote.ts"(){"use strict";thr="https://registry.modelcontextprotocol.io",Pme="/v0.1",rhr="io.modelcontextprotocol.registry/official",nhr=/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,ohr=214,ihr=/^[0-9A-Za-z][0-9A-Za-z.+_~-]*$/,shr=128}}),ahr={};ue(ahr,{MCPRegistryClient:()=>s5,getAllWellKnownServers:()=>lhr,getWellKnownServer:()=>uhr,globalMCPRegistryClient:()=>Ome});function uhr(e){return RI.find(t=>t.id===e)}function lhr(){return[...RI]}var chr,dhr,Dme,phr,RI,s5,Ome,mhr=S({"src/lib/mcp/mcpRegistryClient.ts"(){"use strict";oo(),z(),rSn(),chr=100,dhr=5,Dme=8*1024*1024,phr=500,RI=[{id:"filesystem",name:"Filesystem",description:"File system operations - read, write, create, list directories",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-filesystem",command:"npx",args:["-y","@modelcontextprotocol/server-filesystem"],transports:["stdio"],categories:["file-system"],tags:["files","directories","read","write"],tools:["read_file","write_file","list_directory","create_directory"],verified:!0},{id:"github",name:"GitHub",description:"GitHub repository management and file operations",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-github",command:"npx",args:["-y","@modelcontextprotocol/server-github"],requiredEnvVars:["GITHUB_PERSONAL_ACCESS_TOKEN"],transports:["stdio"],categories:["version-control","api"],tags:["github","git","repositories","issues","pull-requests"],tools:["create_repository","list_commits","create_issue","create_pull_request"],verified:!0},{id:"postgres",name:"PostgreSQL",description:"PostgreSQL database query and management",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-postgres",command:"npx",args:["-y","@modelcontextprotocol/server-postgres"],requiredEnvVars:["DATABASE_URL"],transports:["stdio"],categories:["database"],tags:["postgres","postgresql","sql","database","query"],tools:["query","list_tables","describe_table"],verified:!0},{id:"sqlite",name:"SQLite",description:"SQLite database operations and queries",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-sqlite",command:"npx",args:["-y","@modelcontextprotocol/server-sqlite"],transports:["stdio"],categories:["database"],tags:["sqlite","sql","database","local"],tools:["query","list_tables","describe_table"],verified:!0},{id:"brave-search",name:"Brave Search",description:"Web search using Brave Search API",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-brave-search",command:"npx",args:["-y","@modelcontextprotocol/server-brave-search"],requiredEnvVars:["BRAVE_API_KEY"],transports:["stdio"],categories:["search","api"],tags:["search","web","brave","internet"],tools:["web_search","local_search"],verified:!0},{id:"puppeteer",name:"Puppeteer",description:"Web scraping and browser automation",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-puppeteer",command:"npx",args:["-y","@modelcontextprotocol/server-puppeteer"],transports:["stdio"],categories:["automation","web"],tags:["browser","scraping","automation","puppeteer"],tools:["navigate","screenshot","click","type","get_content"],verified:!0},{id:"git",name:"Git",description:"Git repository operations and version control",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-git",command:"npx",args:["-y","@modelcontextprotocol/server-git"],transports:["stdio"],categories:["version-control"],tags:["git","vcs","commits","branches"],tools:["git_status","git_log","git_diff","git_commit"],verified:!0},{id:"memory",name:"Memory",description:"Persistent memory and knowledge storage",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-memory",command:"npx",args:["-y","@modelcontextprotocol/server-memory"],transports:["stdio"],categories:["memory","storage"],tags:["memory","knowledge","storage","persistent"],tools:["store","retrieve","search","delete"],verified:!0},{id:"slack",name:"Slack",description:"Slack workspace integration",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-slack",command:"npx",args:["-y","@modelcontextprotocol/server-slack"],requiredEnvVars:["SLACK_BOT_TOKEN"],transports:["stdio"],categories:["communication","api"],tags:["slack","messaging","chat","team"],tools:["send_message","list_channels","get_channel_history"],verified:!0},{id:"google-drive",name:"Google Drive",description:"Google Drive file management",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-gdrive",command:"npx",args:["-y","@modelcontextprotocol/server-gdrive"],transports:["stdio"],categories:["file-system","api"],tags:["google","drive","files","cloud"],tools:["list_files","read_file","create_file","search_files"],verified:!0}],s5=class extends wn{config;cache=new Map;customEntries=new Map;constructor(e={}){super(),this.config={registries:[...e.registries??[{type:"official",enableCache:!0}]],remoteLookup:e.remoteLookup??!1,enableCache:e.enableCache??!0,defaultCacheTTL:e.defaultCacheTTL??36e5,timeout:e.timeout??1e4,userAgent:e.userAgent??"NeuroLink-MCP-Registry-Client/1.0"}}async search(e={}){const{query:t,categories:r,tags:n,transport:o,verifiedOnly:i=!1,sortBy:s="downloads",sortDirection:a="desc",limit:u=25,offset:l=0}=e,c=Math.max(1,u),d=Math.max(0,l);let m=[...t?await this.collectEntries(t):await this.getAllEntries()];if(t){const g=t.toLowerCase();m=m.filter(y=>y.name.toLowerCase().includes(g)||y.description.toLowerCase().includes(g)||y.tags?.some(v=>v.toLowerCase().includes(g)))}r?.length&&(m=m.filter(g=>g.categories?.some(y=>r.includes(y)))),n?.length&&(m=m.filter(g=>g.tags?.some(y=>n.includes(y)))),o&&(m=m.filter(g=>g.transports?.includes(o))),i&&(m=m.filter(g=>g.verified)),m.sort((g,y)=>{let v=0;switch(s){case"name":v=g.name.localeCompare(y.name);break;case"downloads":v=(g.downloads??0)-(y.downloads??0);break;case"stars":v=(g.stars??0)-(y.stars??0);break;case"lastUpdated":v=(g.lastUpdated??"").localeCompare(y.lastUpdated??"");break}return a==="desc"?-v:v});const h=m.length;return m=m.slice(d,d+c),{entries:m,totalCount:h,page:Math.floor(d/c)+1,pageSize:c,hasMore:d+m.length<h}}async getEntry(e){if(this.customEntries.has(e))return this.customEntries.get(e);const t=RI.find(r=>r.id===e);if(t)return t;if(this.config.remoteLookup&&!(e===""||e==="."||e===".."))for(const r of this.getRemoteTargets()){const n=await this.fetchRemoteEntry(r,e);if(n)return n}}async getAllEntries(){return this.collectEntries()}async collectEntries(e){const t=e===void 0||!this.config.remoteLookup?"all-entries":`all-entries:${e.toLowerCase()}`,r=this.config.remoteLookup?this.getRemoteTargets():[],n=this.config.enableCache&&r.every(c=>this.isRemoteCacheEnabled(c)),o=Math.min(this.config.defaultCacheTTL,...r.map(c=>c.config.cacheTTL??this.config.defaultCacheTTL)),i=n?this.readCache(t,o):void 0;if(i)return i;const s=new Set(this.customEntries.keys()),a=[...RI.filter(c=>!s.has(c.id)),...Array.from(this.customEntries.values())];let u=a,l=!0;if(this.config.remoteLookup){const c=await Promise.all(r.map(m=>this.fetchRemoteList(m,e))),d=new Set(a.map(m=>m.id)),p=[];for(const m of c){l=l&&m.ok;for(const h of m.entries)d.has(h.id)||(d.add(h.id),p.push(h))}u=[...a,...p]}return n&&l&&this.writeCache(t,u),u}getRemoteTargets(){return this.config.registries.flatMap(e=>{const t=XEn(e);return t===void 0?(le.debug(`[MCPRegistryClient] Skipping registry of type "${e.type}": not queryable (unsupported type, missing or unusable URL, or a bearer token on plain http to a non-loopback host)`),[]):[t]})}async fetchRemoteEntry(e,t){const r=`remote-entry:${e.apiBase}:${t}`,n=this.readRemoteCache(r,e);if(n)return n;try{const o=await this.requestJson(e,`/servers/${encodeURIComponent(t)}/versions/latest`);if(o.body===void 0)return;const i=Zmr(o.body);if(i===void 0||i.status==="deleted"||i.server.name.toLowerCase()!==t.toLowerCase())throw new Error("registry returned no record for the requested server");const s=ehr(i,e.apiBase);return this.writeRemoteCache(r,s,e),s}catch(o){this.reportRemoteError(e,"getEntry",o);return}}async fetchRemoteList(e,t){const r=`remote-list:${e.apiBase}:${(t??"").toLowerCase()}`,n=this.readRemoteCache(r,e);if(n)return{entries:n,ok:!0};try{const o=e.config.maxPages,i=o!==void 0&&Number.isFinite(o)?Math.max(1,Math.floor(o)):dhr,s=[],a=new Set;let u;for(let l=0;l<i;l++){const c=new URLSearchParams({version:"latest",limit:String(chr)});t&&c.set("search",t),u&&c.set("cursor",u);const d=await this.requestJson(e,"/servers",c),{records:p,nextCursor:m}=eSn(d.body);if(s.push(...p.filter(h=>h.status!=="deleted").map(h=>ehr(h,e.apiBase))),m===void 0||a.has(m))break;if(l===i-1){le.debug(`[MCPRegistryClient] ${e.apiBase}: stopped after ${i} page(s); more servers are available`);break}a.add(m),u=m}return this.writeRemoteCache(r,s,e),{entries:s,ok:!0}}catch(o){return this.reportRemoteError(e,"list",o),{entries:[],ok:!1}}}async requestJson(e,t,r){const n=new URL(`${e.apiBase}${t}`);r?.forEach((s,a)=>n.searchParams.set(a,s));const o={Accept:"application/json","User-Agent":this.config.userAgent,...e.config.authToken?{Authorization:`Bearer ${e.config.authToken}`}:{}},i=await globalThis.fetch(n,{method:"GET",headers:o,signal:AbortSignal.timeout(e.config.timeout??this.config.timeout)});if(i.status===404)return await i.body?.cancel(),{body:void 0};if(!i.ok)throw await i.body?.cancel(),new Error(`registry responded with HTTP ${i.status}`);return{body:await this.readBoundedJson(i)}}async readBoundedJson(e){const t=[];let r=0;if(e.body){const n=e.body.getReader();for(;;){const{done:o,value:i}=await n.read();if(o)break;if(r+=i.byteLength,r>Dme)throw await n.cancel(),new Error(`registry response exceeds ${Dme} bytes`);t.push(i)}}return JSON.parse(Buffer.concat(t).toString("utf8"))}reportRemoteError(e,t,r){const n=r instanceof Error?r.message:String(r),o=r instanceof Error?r.cause:void 0,i=typeof o=="object"&&o!==null&&"code"in o?String(o.code):void 0,s=i===void 0?n:`${n} (${i})`;le.debug(`[MCPRegistryClient] ${t} failed for ${e.apiBase}: ${s}`);try{this.emit("registryError",{registry:e.apiBase,operation:t,message:s})}catch(a){le.debug(`[MCPRegistryClient] registryError listener threw: ${String(a)}`)}}readCache(e,t){const r=this.cache.get(e);return r&&Date.now()-r.timestamp<t?r.data:void 0}readRemoteCache(e,t){return this.isRemoteCacheEnabled(t)?this.readCache(e,t.config.cacheTTL??this.config.defaultCacheTTL):void 0}writeRemoteCache(e,t,r){this.isRemoteCacheEnabled(r)&&this.writeCache(e,t)}isRemoteCacheEnabled(e){return this.config.enableCache&&(e.config.enableCache??!0)}writeCache(e,t){if(!this.cache.has(e)&&this.cache.size>=phr){const r=this.cache.keys().next();r.done||this.cache.delete(r.value)}this.cache.set(e,{data:t,timestamp:Date.now()})}async getByCategory(e){return(await this.getAllEntries()).filter(r=>r.categories?.includes(e))}async getByTag(e){return(await this.getAllEntries()).filter(r=>r.tags?.includes(e))}async getCategories(){const e=await this.getAllEntries(),t=new Set;for(const r of e)for(const n of r.categories??[])t.add(n);return Array.from(t).sort()}async getTags(){const e=await this.getAllEntries(),t=new Set;for(const r of e)for(const n of r.tags??[])t.add(n);return Array.from(t).sort()}toServerInfo(e){return{id:e.id,name:e.name,description:e.description,command:e.command,args:e.args,transport:e.transports?.[0]??"stdio",status:"stopped",tools:e.tools?.map(t=>({name:t,description:`Tool: ${t}`}))??[],metadata:{...e.metadata,version:e.version,author:e.author,license:e.license,homepage:e.homepage,repository:e.repository,npmPackage:e.npmPackage,requiredEnvVars:e.requiredEnvVars,categories:e.categories,tags:e.tags,verified:e.verified}}}addCustomEntry(e){this.customEntries.set(e.id,e),this.clearCache(),this.emit("entryAdded",{entry:e})}removeCustomEntry(e){const t=this.customEntries.delete(e);return t&&(this.clearCache(),this.emit("entryRemoved",{id:e})),t}addRegistry(e){this.config.registries.push(e),this.clearCache();const{authToken:t,...r}=e;this.emit("registryAdded",{config:r})}setRemoteLookup(e){this.config.remoteLookup=e,this.clearCache(),this.emit("remoteLookupChanged",{enabled:e})}clearCache(){this.cache.clear(),this.emit("cacheCleared")}checkRequiredEnvVars(e){const t=[];for(const r of e.requiredEnvVars??[])process.env[r]||t.push(r);return{ready:t.length===0,missing:t}}getInstallCommand(e){if(e.installCommand)return e.installCommand;if(e.npmPackage)return`npx -y ${e.npmPackage}`}async getPopularServers(e=10){return(await this.search({sortBy:"downloads",sortDirection:"desc",limit:e})).entries}async getVerifiedServers(){return(await this.search({verifiedOnly:!0})).entries}async getStatistics(){const e=await this.getAllEntries(),t=await this.getCategories(),r=await this.getTags();return{totalEntries:e.length,verifiedEntries:e.filter(n=>n.verified).length,categories:t.length,tags:r.length,customEntries:this.customEntries.size}}},Ome=new s5}}),Nme={};ue(Nme,{AgentExposureManager:()=>l5,exposeAgentAsTool:()=>a5,exposeAgentsAsTools:()=>hhr,exposeWorkflowAsTool:()=>u5,exposeWorkflowsAsTools:()=>fhr,globalAgentExposureManager:()=>Lme});function a5(e,t={}){const{prefix:r="agent",defaultAnnotations:n={},includeMetadataInDescription:o=!0,nameTransformer:i=y=>y.toLowerCase().replace(/\s+/g,"_"),wrapWithContext:s=!0,executionTimeout:a=3e5,enableLogging:u=!0}=t,l=i(e.name),c=r?`${r}_${l}`:l;let d=e.description;if(o&&e.metadata){const y=[];e.metadata.version&&y.push(`v${e.metadata.version}`),e.metadata.category&&y.push(`category: ${e.metadata.category}`),e.metadata.estimatedDuration&&y.push(`~${e.metadata.estimatedDuration}ms`),y.length>0&&(d+=` [${y.join(", ")}]`)}const p={...n,complexity:n.complexity??"complex",estimatedDuration:e.metadata?.estimatedDuration??n.estimatedDuration,costHint:e.metadata?.costHint??n.costHint,tags:[...n.tags??[],"agent",...e.metadata?.tags??[]]},m=e.inputSchema??{type:"object",properties:{}},h=async(y,v)=>{const w=Date.now();u&&f.debug(`[AgentExposure] Executing agent '${e.id}' as tool '${c}'`);try{const b=v?.config&&typeof v.config=="object"?v.config:{},E=s?{...v,config:{...b,sourceType:"mcp-exposed-agent",agentId:e.id,toolName:c}}:v??{},k=await kt(e.execute(y,E),a),A=Date.now()-w;return u&&f.debug(`[AgentExposure] Agent '${e.id}' completed in ${A}ms`),{success:!0,data:k,metadata:{agentId:e.id,toolName:c,executionTime:A,sourceType:"agent"}}}catch(b){const E=Date.now()-w,k=b instanceof Error?b:ve.toolExecutionFailed(c,new Error(String(b)));return u&&f.error(`[AgentExposure] Agent '${e.id}' failed after ${E}ms: ${k.message}`),{success:!1,error:k.message,metadata:{agentId:e.id,toolName:c,executionTime:E,sourceType:"agent"}}}};return{tool:{name:c,description:d,inputSchema:m,outputSchema:e.outputSchema,annotations:p,execute:h,metadata:{sourceType:"agent",sourceId:e.id,originalName:e.name,...e.metadata}},sourceType:"agent",sourceId:e.id,toolName:c}}function u5(e,t={}){const{prefix:r="workflow",defaultAnnotations:n={},includeMetadataInDescription:o=!0,nameTransformer:i=y=>y.toLowerCase().replace(/\s+/g,"_"),wrapWithContext:s=!0,executionTimeout:a=6e5,enableLogging:u=!0}=t,l=i(e.name),c=r?`${r}_${l}`:l;let d=e.description;if(o){const y=[];e.metadata?.version&&y.push(`v${e.metadata.version}`),e.steps?.length&&y.push(`${e.steps.length} steps`),e.metadata?.estimatedDuration&&y.push(`~${e.metadata.estimatedDuration}ms`),y.length>0&&(d+=` [${y.join(", ")}]`)}const p={...n,complexity:n.complexity??"complex",estimatedDuration:e.metadata?.estimatedDuration??n.estimatedDuration,idempotentHint:e.metadata?.idempotent??n.idempotentHint,tags:[...n.tags??[],"workflow",...e.metadata?.tags??[]]},m=e.inputSchema??{type:"object",properties:{}},h=async(y,v)=>{const w=Date.now();u&&f.debug(`[WorkflowExposure] Executing workflow '${e.id}' as tool '${c}'`);try{const b=v?.config&&typeof v.config=="object"?v.config:{},E=s?{...v,config:{...b,sourceType:"mcp-exposed-workflow",workflowId:e.id,toolName:c}}:v??{},k=await kt(e.execute(y,E),a),A=Date.now()-w;return u&&f.debug(`[WorkflowExposure] Workflow '${e.id}' completed in ${A}ms`),{success:!0,data:k,metadata:{workflowId:e.id,toolName:c,executionTime:A,sourceType:"workflow",stepsCount:e.steps?.length}}}catch(b){const E=Date.now()-w,k=b instanceof Error?b:ve.toolExecutionFailed(c,new Error(String(b)));return u&&f.error(`[WorkflowExposure] Workflow '${e.id}' failed after ${E}ms: ${k.message}`),{success:!1,error:k.message,metadata:{workflowId:e.id,toolName:c,executionTime:E,sourceType:"workflow"}}}};return{tool:{name:c,description:d,inputSchema:m,outputSchema:e.outputSchema,annotations:p,execute:h,metadata:{sourceType:"workflow",sourceId:e.id,originalName:e.name,steps:e.steps,...e.metadata}},sourceType:"workflow",sourceId:e.id,toolName:c}}function hhr(e,t={}){return e.map(r=>a5(r,t))}function fhr(e,t={}){return e.map(r=>u5(r,t))}var l5,Lme,$me=S({"src/lib/mcp/agentExposure.ts"(){"use strict";z(),Vr(),et(),l5=class{exposedTools=new Map;options;constructor(e={}){this.options=e}exposeAgent(e){const t=a5(e,this.options);return this.exposedTools.set(t.toolName,t),t.tool}exposeWorkflow(e){const t=u5(e,this.options);return this.exposedTools.set(t.toolName,t),t.tool}getExposedTools(){return Array.from(this.exposedTools.values()).map(e=>e.tool)}getExposedTool(e){return this.exposedTools.get(e)?.tool}getExposureResult(e){return this.exposedTools.get(e)}getToolsBySourceType(e){return Array.from(this.exposedTools.values()).filter(t=>t.sourceType===e).map(t=>t.tool)}unexpose(e){return this.exposedTools.delete(e)}clear(){this.exposedTools.clear()}getStatistics(){const e=Array.from(this.exposedTools.values());return{totalExposed:e.length,exposedAgents:e.filter(t=>t.sourceType==="agent").length,exposedWorkflows:e.filter(t=>t.sourceType==="workflow").length,toolNames:e.map(t=>t.toolName)}}},Lme=new l5}}),ghr={};ue(ghr,{ToolIntegrationManager:()=>p5,confirmationMiddleware:()=>Bme,createElicitationContext:()=>c5,createRetryMiddleware:()=>whr,createTimeoutMiddleware:()=>vhr,createToolMiddlewareChain:()=>Fme,globalToolIntegrationManager:()=>Gme,loggingMiddleware:()=>Ume,validationMiddleware:()=>zme,wrapToolWithElicitation:()=>d5,wrapToolsWithElicitation:()=>yhr});function c5(e,t,r){return{confirm:async(n,o)=>r.confirm(n,{toolName:e,serverId:t,confirmLabel:o?.confirmLabel,cancelLabel:o?.cancelLabel}),getText:async(n,o)=>r.getText(n,{toolName:e,placeholder:o?.placeholder,defaultValue:o?.defaultValue}),select:async(n,o)=>r.select(n,o,{toolName:e}),multiSelect:async(n,o)=>r.multiSelect(n,o,{toolName:e}),form:async(n,o)=>r.form(n,o,{toolName:e,serverId:t}),request:async n=>r.request({...n,toolName:e,serverId:t})}}function d5(e,t={}){const{elicitationManager:r,autoConfirmDestructive:n=!1,elicitationTimeout:o=6e4,enableLogging:i=!0}=t,s=r??new __({defaultTimeout:o});return{...e,execute:async(a,u)=>{const c=u?.config?.serverId,d=c5(e.name,c,s);if((e.annotations?.requiresConfirmation||e.annotations?.destructiveHint)&&!n&&(i&&f.debug(`[ToolIntegration] Tool '${e.name}' requires confirmation`),!await d.confirm(`This operation (${e.name}) ${e.annotations?.destructiveHint?"is destructive and ":""}requires confirmation. Do you want to proceed?`,{confirmLabel:"Yes, proceed",cancelLabel:"Cancel"})))return{success:!1,error:"Operation cancelled by user",metadata:{toolName:e.name,cancelled:!0}};const m={...u,elicitation:d,toolMeta:{name:e.name,serverId:c,annotations:e.annotations}};return e.execute(a,m)}}}function yhr(e,t={}){return e.map(r=>d5(r,t))}function Fme(e){return async(t,r,n,o)=>{const i=async s=>{if(s>=e.length)return o();const a=e[s];return a(t,r,n,()=>i(s+1))};return i(0)}}function vhr(e){return async(t,r,n,o)=>Ge(o(),e,ve.toolTimeout(t.name,e))}function whr(e,t=1e3){return async(r,n,o,i)=>{if(!(r.annotations?.idempotentHint||r.annotations?.readOnlyHint))return i();const a=Math.max(0,e);let u;for(let l=0;l<=a;l++)try{return await i()}catch(c){u=c instanceof Error?c:ve.toolExecutionFailed(r.name,new Error(String(c))),l<a&&(f.warn(`[ToolMiddleware] Tool '${r.name}' failed, retrying (${l+1}/${a})`),await new Promise(d=>setTimeout(d,t*(l+1))))}throw u??ve.toolExecutionFailed(r.name,new Error("Retry middleware exhausted without captured error"))}}var Ume,Bme,zme,p5,Gme,bhr=S({"src/lib/mcp/toolIntegration.ts"(){"use strict";Rme(),et(),z(),Ume=async(e,t,r,n)=>{const o=Date.now();f.debug(`[ToolMiddleware] Executing tool '${e.name}'`);try{const i=await n(),s=Date.now()-o;return f.debug(`[ToolMiddleware] Tool '${e.name}' completed in ${s}ms`),i}catch(i){const s=Date.now()-o;throw f.error(`[ToolMiddleware] Tool '${e.name}' failed after ${s}ms:`,i),i}},Bme=async(e,t,r,n)=>r.elicitation?.confirm&&(e.annotations?.destructiveHint||e.annotations?.requiresConfirmation)&&!await r.elicitation.confirm(`Confirm execution of ${e.name}?`)?{success:!1,error:"Operation cancelled by user",metadata:{cancelled:!0}}:n(),zme=async(e,t,r,n)=>{if(!e.inputSchema)return n();const o=e.inputSchema,i=o.required??[],s=o.properties??{},a=t??{},u=[];for(const l of i)a[l]===void 0&&u.push(l);if(u.length>0){const l=u.map(d=>{const p=s[d];return{name:d,label:d,type:p?.type??"text",required:!0,description:p?.description}}),c=await r.elicitation.form(`Missing required parameters for ${e.name}`,l);if(!c)return{success:!1,error:`Missing required parameters: ${u.join(", ")}`,metadata:{missingParams:u}};Object.assign(a,c)}return n()},p5=class{elicitationManager;middlewares=[];wrappedTools=new Map;constructor(e){this.elicitationManager=e??new __}setElicitationHandler(e){this.elicitationManager.setHandler(e)}use(e){return this.middlewares.push(e),this}registerTool(e){const t=d5(e,{elicitationManager:this.elicitationManager});return this.wrappedTools.set(e.name,t),t}async executeTool(e,t,r){const n=this.wrappedTools.get(e);if(!n)throw ve.toolNotFound(e,Array.from(this.wrappedTools.keys()));const o=t&&typeof t=="object"?t:{},s=r?.config?.serverId,a=c5(e,s,this.elicitationManager),u={...r,elicitation:a,toolMeta:{name:e,serverId:s,annotations:n.annotations}};return this.middlewares.length===0?n.execute(o,u):Fme(this.middlewares)(n,o,u,()=>n.execute(o,u))}getTool(e){return this.wrappedTools.get(e)}getAllTools(){return Array.from(this.wrappedTools.values())}getElicitationManager(){return this.elicitationManager}},Gme=new p5}}),qme={};ue(qme,{TOOL_COMPATIBILITY:()=>Wme,batchConvertToMCP:()=>Ehr,batchConvertToNeuroLink:()=>Shr,createToolFromFunction:()=>khr,mcpProtocolToolToServerTool:()=>Thr,mcpToolToNeuroLink:()=>Vme,neuroLinkToolToMCP:()=>jme,sanitizeToolName:()=>Hme,serverToolToMCPProtocol:()=>_hr,validateToolName:()=>Ahr});function jme(e,t={}){const{inferAnnotations:r=!0,defaultAnnotations:n={},preserveMetadata:o=!0,namespacePrefix:i}=t,s=i?`${i}_${e.name}`:e.name,a=r?Vp({name:e.name,description:e.description}):{},u={...n,...a};e.tags?.length&&(u.tags=[...new Set([...u.tags??[],...e.tags])]);const l=e.parameters??{type:"object",properties:{}},c=o?{...e.metadata}:{};return e.category&&(c.category=e.category),e.isAsync!==void 0&&(c.isAsync=e.isAsync),{name:s,description:e.description,inputSchema:l,annotations:u,execute:e.execute,metadata:c}}function Vme(e,t={}){const{removeNamespacePrefix:r}=t;let n=e.name;return r&&e.name.startsWith(`${r}_`)&&(n=e.name.slice(r.length+1)),{name:n,description:e.description,parameters:e.inputSchema,execute:e.execute,category:e.metadata?.category,tags:e.annotations?.tags,metadata:e.metadata}}function Thr(e,t,r={}){const{inferAnnotations:n=!0,defaultAnnotations:o={}}=r,i=e.annotations??{},s=n?Vp({name:e.name,description:e.description??""}):{},a={...o,...s,title:i.title??s.title??o.title,readOnlyHint:i.readOnlyHint??s.readOnlyHint??o.readOnlyHint,destructiveHint:i.destructiveHint??s.destructiveHint??o.destructiveHint,idempotentHint:i.idempotentHint??s.idempotentHint??o.idempotentHint,openWorldHint:i.openWorldHint??s.openWorldHint??o.openWorldHint};return{name:e.name,description:e.description??"No description provided",inputSchema:e.inputSchema,annotations:a,execute:t}}function _hr(e){const t={};e.annotations?.title&&(t.title=e.annotations.title),e.annotations?.readOnlyHint!==void 0&&(t.readOnlyHint=e.annotations.readOnlyHint),e.annotations?.destructiveHint!==void 0&&(t.destructiveHint=e.annotations.destructiveHint),e.annotations?.idempotentHint!==void 0&&(t.idempotentHint=e.annotations.idempotentHint),e.annotations?.openWorldHint!==void 0&&(t.openWorldHint=e.annotations.openWorldHint);const r=e.inputSchema??{type:"object",properties:{}};return{name:e.name,description:e.description,inputSchema:{type:"object",properties:r.properties??{},required:"required"in r?r.required:void 0},annotations:Object.keys(t).length>0?t:void 0}}function Ehr(e,t={}){return e.map(r=>jme(r,t))}function Shr(e,t={}){return e.map(r=>Vme(r,t))}function khr(e,t,r,n){const o=Vp({name:e,description:t});return{name:e,description:t,inputSchema:n?.parameters??{type:"object",properties:{}},annotations:{...o,...n?.annotations},execute:async(i,s)=>await kt(r(i,s),3e4,`Tool '${e}' execution timed out after 30000ms`),metadata:n?.metadata}}function Ahr(e){const t=[];return!e||typeof e!="string"?t.push("Tool name is required and must be a string"):(e.length>64&&t.push("Tool name must be 64 characters or less"),/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e)||t.push("Tool name must start with a letter or underscore and contain only alphanumeric characters, underscores, and hyphens")),{valid:t.length===0,errors:t}}function Hme(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return/^[a-zA-Z_]/.test(t)||(t=`_${t}`),t.length>64&&(t=t.slice(0,64)),t}var Wme,m5=S({"src/lib/mcp/toolConverter.ts"(){"use strict";$C(),Vr(),Wme={MCP_2024_11_05:{annotations:!0,inputSchema:!0,outputSchema:!1,streamingResults:!1,batchExecution:!1},NEUROLINK:{annotations:!0,inputSchema:!0,outputSchema:!0,streamingResults:!0,batchExecution:!0,categories:!0,tags:!0}}}}),E_,Uy,xhr,nSn=S({async"src/lib/core/redisConversationMemoryManager.ts"(){"use strict";Kt(),tr(),qt(),Dx(),G0(),ctr(),QKt(),await Oc(),lt(),et(),iT(),z(),sJt(),L3(),V6(),E_=Be.redis,Uy=5e3,xhr=class{config;isInitialized=!1;summarizationEngine=new pie;redisConfig;redisClient=null;eventEmitter;pendingToolExecutions=new Map;titleGenerationInProgress=new Set;summarizationInProgress=new Set;constructor(e,t={},r){this.config=e,this.redisConfig=tue(t),this.eventEmitter=r}async initialize(){if(this.isInitialized){f.debug("[RedisConversationMemoryManager] Already initialized, skipping");return}await E_.startActiveSpan("memory.initialize",{kind:hn.CLIENT,attributes:{"redis.host":this.redisConfig.host,"redis.port":this.redisConfig.port,"redis.key_prefix":this.redisConfig.keyPrefix}},async e=>{try{f.debug("[RedisConversationMemoryManager] Initializing with config",{host:this.redisConfig.host,port:this.redisConfig.port,keyPrefix:this.redisConfig.keyPrefix,ttl:this.redisConfig.ttl}),this.redisClient=await Xae(this.redisConfig),this.isInitialized=!0,f.info("RedisConversationMemoryManager initialized",{storage:"redis",host:this.redisConfig.host,port:this.redisConfig.port,maxSessions:this.config.maxSessions,maxTurnsPerSession:this.config.maxTurnsPerSession}),f.debug("[RedisConversationMemoryManager] Redis client created successfully",{clientType:this.redisClient?.constructor?.name||"unknown",isConnected:!!this.redisClient})}catch(t){throw e.setStatus({code:qe.ERROR,message:t instanceof Error?t.message:String(t)}),e.recordException(t instanceof Error?t:new Error(String(t))),f.error("[RedisConversationMemoryManager] Failed to initialize",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0,config:{host:this.redisConfig.host,port:this.redisConfig.port}}),new Eu("Failed to initialize Redis conversation memory","CONFIG_ERROR",{error:t instanceof Error?t.message:String(t)})}finally{e.end()}})}get canPersist(){return this.isInitialized&&this.redisClient!==null&&this.redisClient.isOpen}get isRedisConfigured(){return this.redisClient!==null&&this.redisClient.isOpen}getHealthStatus(){return{initialized:this.isInitialized,connected:this.redisClient?.isOpen??!1,host:this.redisConfig.host,keyPrefix:this.redisConfig.keyPrefix}}async getSession(e,t,r){if(await this.ensureInitialized(),!this.redisClient)return;const n=this.redisClient;return E_.startActiveSpan("memory.getSession",{kind:hn.CLIENT,attributes:{"session.id":e}},async o=>{t&&o.setAttribute("user.id",t);try{const i=ka(this.redisConfig,e,t),s=await Ge(n.get(i),Uy),a=await this.hydrateMessages(ru(s||null),i);if(!a){o.setAttribute("session.found",!1);return}o.setAttribute("session.found",!0);const u=s?Buffer.byteLength(s,"utf8"):0,l=a.messages.length,c=!!a.summarizedUpToMessageId,d=c?a.messages.findIndex(m=>m.id===a.summarizedUpToMessageId):-1,p=c&&d!==-1?l-d-1:l;return o.setAttribute("message.count",l),o.setAttribute("blob.size_bytes",u),f.info("[ConversationMemory] Session loaded",{requestId:r,sessionId:e,blobSizeBytes:u,messageCount:l,hasSummary:c,recentMessageCount:p}),u>512*1024&&f.warn("[ConversationMemory] Large session blob",{requestId:r,sessionId:e,blobSizeBytes:u,messageCount:l}),{sessionId:a.sessionId,userId:a.userId,messages:a.messages,summarizedUpToMessageId:a.summarizedUpToMessageId,summarizedMessage:a.summarizedMessage,tokenThreshold:a.tokenThreshold,lastTokenCount:a.lastTokenCount,lastCountedAt:a.lastCountedAt,lastApiTokenCount:a.lastApiTokenCount,createdAt:new Date(a.createdAt).getTime(),lastActivity:new Date(a.updatedAt).getTime()}}catch(i){o.setStatus({code:qe.ERROR,message:i instanceof Error?i.message:String(i)}),o.recordException(i instanceof Error?i:new Error(String(i))),f.error("[RedisConversationMemoryManager] Failed to get session",{sessionId:e,userId:t,error:i instanceof Error?i.message:String(i)});return}finally{o.end()}})}async getSessionRaw(e,t){try{if(await this.ensureInitialized(),!this.redisClient)return null;const r=ka(this.redisConfig,e,t),n=await this.redisClient.get(r);return this.hydrateMessages(ru(n||null),r)}catch(r){return f.error("[RedisConversationMemoryManager] Failed to get raw session",{sessionId:e,userId:t,error:r instanceof Error?r.message:String(r)}),null}}async getUserSessions(e){if(await this.ensureInitialized(),!this.redisClient)return f.warn("[RedisConversationMemoryManager] Redis client not available",{userId:e}),[];try{const t=Zae(this.redisConfig,e),r=await this.redisClient.sMembers(t);return Array.from(r).map(String)}catch(t){return f.error("[RedisConversationMemoryManager] Failed to get user sessions",{userId:e,error:t instanceof Error?t.message:String(t)}),[]}}async addUserSession(e,t){if(!(!this.redisClient||!e))try{const r=Zae(this.redisConfig,e);await $hn(this.redisClient,r,t,this.redisConfig.ttl)}catch(r){f.error("[RedisConversationMemoryManager] Failed to add session to user set",{userId:e,sessionId:t,error:r instanceof Error?r.message:String(r)})}}async removeUserSession(e,t){if(!this.redisClient||!e)return!1;try{const r=Zae(this.redisConfig,e),n=await this.redisClient.sRem(r,t);return Number(n)>0}catch(r){return f.error("[RedisConversationMemoryManager] Failed to remove session from user set",{userId:e,sessionId:t,error:r instanceof Error?r.message:String(r)}),!1}}generateTimestamp(){return new Date().toISOString()}async storeToolExecution(e,t,r,n,o){f.debug("[RedisConversationMemoryManager] Storing tool execution temporarily",{sessionId:e,userId:t,toolCallsCount:r?.length||0,toolResultsCount:n?.length||0});try{const i=t||"randomUser",s=`${e}:${i}`,a={toolCalls:(r||[]).map(l=>({...l,timestamp:o})),toolResults:(n||[]).map(l=>({...l,timestamp:o})),timestamp:Date.now()},u=this.pendingToolExecutions.get(s);u&&(f.debug("[RedisConversationMemoryManager] Merging with existing pending tool data",{sessionId:e,existingToolCalls:u.toolCalls.length,existingToolResults:u.toolResults.length,newToolCalls:r?.length||0,newToolResults:n?.length||0}),a.toolCalls=[...u.toolCalls,...a.toolCalls],a.toolResults=[...u.toolResults,...a.toolResults]),this.pendingToolExecutions.set(s,a),f.debug("[RedisConversationMemoryManager] Tool execution stored temporarily",{sessionId:e,userId:i,pendingKey:s,totalToolCalls:a.toolCalls.length,totalToolResults:a.toolResults.length}),this.cleanupStalePendingData()}catch(i){f.error("[RedisConversationMemoryManager] Failed to store tool execution temporarily",{sessionId:e,error:i instanceof Error?i.message:String(i)})}}async storeConversationTurn(e){return f.debug("[RedisConversationMemoryManager] Storing conversation turn",{sessionId:e.sessionId,userId:e.userId}),await this.ensureInitialized(),E_.startActiveSpan("memory.storeTurn",{kind:hn.CLIENT,attributes:{"session.id":e.sessionId,...e.userId&&{"user.id":e.userId}}},async t=>{try{if(!this.redisClient)throw new Error("Redis client not initialized");const r=ka(this.redisConfig,e.sessionId,e.userId),n=await this.redisClient.get(r);let o=await this.hydrateMessages(ru(n),r);if(oJt(o?.messages??[],e.turnId))return;const i=s1(o),s=o?.messages.length??0,a=new Date().toISOString(),u=e.userId||"randomUser";if(o)o.updatedAt=a;else{const h=`${e.sessionId}:${u}`,g=yt.bind(yt.active(),async()=>{if(!this.titleGenerationInProgress.has(h)){this.titleGenerationInProgress.add(h);try{const y=await this.generateConversationTitle(e.userMessage),v=ka(this.redisConfig,e.sessionId,e.userId||void 0),w=await this.redisClient?.get(v),b=ru(w||null);if(b){b.title=y,b.updatedAt=new Date().toISOString();const E=Qae(b);this.redisClient&&(await eue(this.redisClient,v,E,this.redisConfig.ttl),this.emitTitleGenerated({sessionId:e.sessionId,userId:u,title:y,timestamp:Date.now()}))}}catch(y){f.warn("[RedisConversationMemoryManager] Failed to generate conversation title in background",{sessionId:e.sessionId,userId:u,error:y instanceof Error?y.message:String(y)})}finally{this.titleGenerationInProgress.delete(h)}}});setImmediate(g),o={id:st(),title:"New Conversation",sessionId:e.sessionId,userId:u,createdAt:e.startTimeStamp?.toISOString()||a,updatedAt:e.startTimeStamp?.toISOString()||a,messages:[]}}const l=e.providerDetails?OKt(e.providerDetails.provider,e.providerDetails.model,this.config.tokenThreshold,o.tokenThreshold):this.config.tokenThreshold||5e4,c={...nJt(tJt(e)),timestamp:e.startTimeStamp?.toISOString()||this.generateTimestamp(),role:"user",content:e.userMessage};o.messages.push(c),await this.flushPendingToolData(o,e.sessionId,u),e.skillMessages&&e.skillMessages.length>0&&o.messages.push(...e.skillMessages);const d={...nJt(rJt(e,e.thoughtSignature)),timestamp:this.generateTimestamp(),role:"assistant",content:e.aiResponse,events:e.events||void 0};o.messages.push(d),e.tokenUsage&&(o.lastApiTokenCount=e.tokenUsage),f.info("[RedisConversationMemoryManager] Added new messages",{sessionId:o.sessionId,userId:o.userId});const p=e.enableSummarization!==void 0?e.enableSummarization:this.config.enableSummarization;if(await this.persistConversation(o,e.sessionId,e.userId,i?s:void 0),p){const h=e.userId||"randomUser",g=`${e.sessionId}:${h}`;if(this.summarizationInProgress.has(g))f.debug("[RedisConversationMemoryManager] Summarization already in progress, skipping",{sessionId:e.sessionId,userId:h});else{const y=yt.bind(yt.active(),async()=>{try{await this.checkAndSummarize(o,l,e.sessionId,e.userId,e.requestId)}catch(v){f.error("Background summarization failed",{sessionId:o.sessionId,error:v instanceof Error?v.message:String(v)})}});setImmediate(y)}}const m=Buffer.byteLength(q6(o),"utf8");f.info("[ConversationMemory] Turn stored",{requestId:e.requestId,sessionId:e.sessionId,blobSizeBytes:m,totalMessages:o.messages.length,userMsgChars:e.userMessage.length,assistantMsgChars:e.aiResponse.length}),m>512*1024&&f.warn("[ConversationMemory] Large session blob",{requestId:e.requestId,sessionId:e.sessionId,blobSizeBytes:m,messageCount:o.messages.length}),e.userId&&await this.addUserSession(e.userId,e.sessionId),t.setAttribute("message.count",o.messages.length),t.setStatus({code:qe.OK}),f.debug("[RedisConversationMemoryManager] Successfully stored conversation turn",{sessionId:e.sessionId,totalMessages:o.messages.length,title:o.title})}catch(r){throw t.setStatus({code:qe.ERROR,message:r instanceof Error?r.message:String(r)}),t.recordException(r instanceof Error?r:new Error(String(r))),new Eu(`Failed to store conversation turn in Redis for session ${e.sessionId}`,"STORAGE_ERROR",{sessionId:e.sessionId,error:r instanceof Error?r.message:String(r)})}finally{t.end()}})}async checkAndSummarize(e,t,r,n,o){const i=n||"randomUser",s=`${r}:${i}`;if(this.summarizationInProgress.has(s)){f.debug("[RedisConversationMemoryManager] Summarization already in progress, skipping",{sessionId:r,userId:i});return}this.summarizationInProgress.add(s);try{const a={sessionId:e.sessionId,userId:e.userId,messages:e.messages,summarizedUpToMessageId:e.summarizedUpToMessageId,summarizedMessage:e.summarizedMessage,tokenThreshold:e.tokenThreshold,lastTokenCount:e.lastTokenCount,lastCountedAt:e.lastCountedAt,createdAt:new Date(e.createdAt).getTime(),lastActivity:new Date(e.updatedAt).getTime()},u=await this.summarizationEngine.checkAndSummarize(a,t,this.config,"[RedisConversationMemoryManager]",o);if(e.lastTokenCount=a.lastTokenCount,e.lastCountedAt=a.lastCountedAt,u&&(e.summarizedUpToMessageId=a.summarizedUpToMessageId,e.summarizedMessage=a.summarizedMessage,this.redisClient)){const l=ka(this.redisConfig,r,n),c=await this.redisClient.get(l);if(c){const d=ru(c);if(d){d.summarizedUpToMessageId=e.summarizedUpToMessageId,d.summarizedMessage=e.summarizedMessage,d.lastTokenCount=e.lastTokenCount,d.lastCountedAt=e.lastCountedAt;const p=s1(d)?q6(d):Qae(d);await eue(this.redisClient,l,p,this.redisConfig.ttl)}}}}catch(a){f.error("Token counting or summarization failed",{sessionId:e.sessionId,error:a instanceof Error?a.message:String(a)})}finally{this.summarizationInProgress.delete(s)}}isConversationBlobKey(e){return!Uhn(e)&&!e.endsWith(":sessions")&&!e.startsWith(this.redisConfig.userSessionsKeyPrefix)}async hydrateMessages(e,t){if(!e||!s1(e)||!this.redisClient)return e;const r=await Ge(this.redisClient.lRange(`${t}${AT}`,0,-1),Uy);return e.messages=Bhn(r.map(n=>n.toString())),e}async countMessages(e,t){return!s1(e)||!this.redisClient?e.messages.length:Number(await Ge(this.redisClient.lLen(`${t}${AT}`),Uy))}async loadConversation(e,t){if(!this.redisClient)return null;const r=ka(this.redisConfig,e,t);return this.hydrateMessages(ru(await this.redisClient.get(r)),r)}async persistConversation(e,t,r,n){if(!this.redisClient)return;const o=ka(this.redisConfig,t,r),i=Fhn(this.redisConfig,t,r),s=this.redisClient.multi();n===void 0&&s.del(i);const a=n===void 0?e.messages:e.messages.slice(n);a.length>0&&s.rPush(i,zhn(a)),s.set(o,q6(e)),this.redisConfig.ttl>0&&(s.expire(o,this.redisConfig.ttl),s.expire(i,this.redisConfig.ttl)),await Ge(s.exec(),Uy)}async buildContextMessages(e,t,r,n){if(f.debug("[RedisConversationMemoryManager] Building context messages",{sessionId:e,userId:t,enableSummarization:r}),await this.ensureInitialized(),!this.redisClient)return f.warn("[RedisConversationMemoryManager] Redis client not available in buildContextMessages"),[];const o=this.redisClient;return E_.startActiveSpan("memory.buildContext",{kind:hn.CLIENT,attributes:{"session.id":e,...t&&{"user.id":t}}},async i=>{try{f.info("[RedisConversationMemoryManager] Building context messages",{sessionId:e,userId:t,method:"buildContextMessages"});const s=ka(this.redisConfig,e,t),a=await Ge(o.get(s),Uy),u=await this.hydrateMessages(ru(a||null),s);if(f.debug("[RedisConversationMemoryManager] Retrieved conversation for context building",{sessionId:e,userId:t,conversationFound:!!u}),!u)return i.setAttribute("session.found",!1),i.setStatus({code:qe.OK}),[];const l={sessionId:u.sessionId,userId:u.userId,messages:u.messages,summarizedUpToMessageId:u.summarizedUpToMessageId,summarizedMessage:u.summarizedMessage,tokenThreshold:u.tokenThreshold,lastTokenCount:u.lastTokenCount,lastCountedAt:u.lastCountedAt,createdAt:new Date(u.createdAt).getTime(),lastActivity:new Date(u.updatedAt).getTime()},c=eie(l,n);f.debug("[RedisConversationMemoryManager] Built context messages from pointer",{sessionId:e,userId:t,contextMessageCount:c.length,pointerMessageId:l.summarizedUpToMessageId||"none"});const d=this.config?.contextCompaction?.sendToolPreview===!0,p=c.map(m=>{if(m.role!=="tool_result")return m;const h=d&&m.metadata?.toolOutputPreview?m.metadata.toolOutputPreview:m.content;let g=m.result;if(m.result&&m.result.result===void 0){let y=h;try{y=JSON.parse(h)}catch{}g={...m.result,result:y}}return f.debug("[RedisConversationMemoryManager] Processing tool_result message for context",{sessionId:e,userId:t,messageId:m.id,sendToolPreview:d,hasPreview:!!m.metadata?.toolOutputPreview,contentLength:h?String(h).length:0,resultHydrated:g!==m.result}),{...m,content:h,result:g}});return i.setAttribute("context.message_count",p.length),i.setStatus({code:qe.OK}),f.info("[RedisConversationMemoryManager] Retrieved context messages",{sessionId:e,userId:t}),p}catch(s){throw i.setStatus({code:qe.ERROR,message:s instanceof Error?s.message:String(s)}),i.recordException(s instanceof Error?s:new Error(String(s))),s}finally{i.end()}})}async getUserSessionMetadata(e,t){if(f.debug("[RedisConversationMemoryManager] Getting user session metadata",{userId:e,sessionId:t}),await this.ensureInitialized(),!this.redisClient)return f.warn("[RedisConversationMemoryManager] Redis client not available",{userId:e,sessionId:t}),null;try{const r=ka(this.redisConfig,t,e),n=await this.redisClient.get(r);if(!n)return f.debug("[RedisConversationMemoryManager] No session data found",{userId:e,sessionId:t,sessionKey:r}),null;const o=ru(n);return o?{id:o.sessionId,title:o.title,createdAt:o.createdAt,updatedAt:o.updatedAt,metadata:o.additionalMetadata?.agenticLoopReports?{agenticLoopReports:o.additionalMetadata.agenticLoopReports}:void 0}:(f.debug("[RedisConversationMemoryManager] No valid conversation data found",{userId:e,sessionId:t,sessionKey:r}),null)}catch(r){return f.error("[RedisConversationMemoryManager] Failed to get user session metadata",{userId:e,sessionId:t,error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0}),null}}async getUserSessionHistory(e,t){f.debug("[RedisConversationMemoryManager] Getting user session history via getUserSessionObject",{userId:e,sessionId:t});try{const r=await this.getUserSessionObject(e,t);return r?r.messages:(f.debug("[RedisConversationMemoryManager] No session object found, returning null",{userId:e,sessionId:t}),null)}catch(r){return f.error("[RedisConversationMemoryManager] Failed to get user session history via getUserSessionObject",{userId:e,sessionId:t,error:r instanceof Error?r.message:String(r),errorName:r instanceof Error?r.name:"UnknownError",stack:r instanceof Error?r.stack:void 0}),null}}async getUserSessionObject(e,t){if(f.debug("[RedisConversationMemoryManager] Getting complete user session object",{userId:e,sessionId:t,method:"getUserSessionObject"}),!e||typeof e!="string")return f.warn("[RedisConversationMemoryManager] Invalid userId provided",{userId:e,sessionId:t}),null;if(!t||typeof t!="string")return f.warn("[RedisConversationMemoryManager] Invalid sessionId provided",{userId:e,sessionId:t}),null;if(await this.ensureInitialized(),!this.redisClient)return f.warn("[RedisConversationMemoryManager] Redis client not available for getUserSessionObject",{userId:e,sessionId:t}),null;try{const r=ka(this.redisConfig,t,e),n=await this.redisClient.get(r);if(!n)return f.debug("[RedisConversationMemoryManager] No conversation data found in Redis",{userId:e,sessionId:t,sessionKey:r}),null;const o=await this.hydrateMessages(ru(n),r);return o?!o.messages||!Array.isArray(o.messages)?(f.warn("[RedisConversationMemoryManager] Invalid conversation structure - missing messages array",{userId:e,sessionId:t,hasMessages:!!o.messages,messagesType:typeof o.messages}),null):o:(f.debug("[RedisConversationMemoryManager] Failed to deserialize conversation data",{userId:e,sessionId:t,sessionKey:r,dataLength:n.length}),null)}catch(r){return f.error("[RedisConversationMemoryManager] Failed to get complete user session object",{userId:e,sessionId:t,error:r instanceof Error?r.message:String(r),errorName:r instanceof Error?r.name:"UnknownError",stack:r instanceof Error?r.stack:void 0}),null}}emitTitleGenerated(e){try{this.eventEmitter?.emit("conversation:titleGenerated",e)}catch(t){f.warn("[RedisConversationMemoryManager] conversation:titleGenerated listener threw",{sessionId:e.sessionId,error:t instanceof Error?t.message:String(t)})}}async generateConversationTitle(e){f.info("[RedisConversationMemoryManager] Generating conversation title",{userMessageLength:e.length,userMessagePreview:e.substring(0,100)});try{const t=new M_({conversationMemory:{enabled:!1}}),r=`Generate a clear, concise, and descriptive title (20-25 letters maximum) for a conversation based on the following user message.
|
|
1917
1917
|
The title must meaningfully reflect the topic or intent of the message.
|
|
1918
1918
|
Do not output anything unrelated, vague, or generic.
|
|
1919
1919
|
Do not say you cannot create a title. Always return a valid title.
|
|
1920
1920
|
|
|
1921
1921
|
User message: "${e}"`,n=process.env.NEUROLINK_TITLE_PROMPT,o=n?n.replace(/\$\{userMessage\}/g,e):r,i=await t.generate({input:{text:o},provider:this.config.summarizationProvider||"vertex",model:this.config.summarizationModel||"gemini-2.5-flash",disableTools:!0});let s=i.content?.trim()||"New Conversation";return s=s.replace(/^(Title:|Here's a title:|The title is:)\s*/i,""),s=s.replace(/['"]/g,""),s=s.replace(/\.$/,""),s.length<3&&(s="New Conversation"),f.info("[RedisConversationMemoryManager] Generated conversation title",{originalLength:i.content?.length||0,cleanedTitle:s,titleLength:s.length}),s}catch(t){return f.error("[RedisConversationMemoryManager] Failed to generate conversation title",{error:t instanceof Error?t.message:String(t),userMessagePreview:e.substring(0,100)}),e.length>30?e.substring(0,30)+"...":e||"New Conversation"}}createSummarySystemMessage(e,t,r){return{id:`summary-${st()}`,role:"system",content:`Summary of previous conversation turns:
|
|
1922
1922
|
|
|
1923
|
-
${e}`,timestamp:new Date().toISOString(),metadata:{isSummary:!0,summarizesFrom:t,summarizesTo:r}}}async getSessionMessages(e,t){if(await this.ensureInitialized(),!this.redisClient)return[];try{const r=ka(this.redisConfig,e,t),n=await this.redisClient.get(r);return(await this.hydrateMessages(ru(n||null),r))?.messages??[]}catch(r){return f.error("[RedisConversationMemoryManager] Failed to get session messages",{sessionId:e,userId:t,error:r instanceof Error?r.message:String(r)}),[]}}async setSessionMessages(e,t,r){if(await this.ensureInitialized(),!this.redisClient)throw new Eu("Redis client not initialized","STORAGE_ERROR",{sessionId:e});try{const n=ka(this.redisConfig,e,r),o=await this.redisClient.get(n),i=ru(o||null);if(!i)throw new Eu(`Session ${e} not found`,"STORAGE_ERROR",{sessionId:e});i.messages=t,i.updatedAt=new Date().toISOString(),i.summarizedUpToMessageId=void 0,i.summarizedMessage=void 0,i.lastTokenCount=void 0,i.lastCountedAt=void 0,await this.persistConversation(i,e,r),f.debug("[RedisConversationMemoryManager] Session messages replaced",{sessionId:e,userId:r,messageCount:t.length})}catch(n){throw n instanceof Eu?n:new Eu(`Failed to set session messages for session ${e}`,"STORAGE_ERROR",{sessionId:e,error:n instanceof Error?n.message:String(n)})}}async close(){this.redisClient&&(await grr(this.redisConfig),this.redisClient=null,this.isInitialized=!1,f.info("Redis connection closed"))}async getStats(){if(await this.ensureInitialized(),!this.redisClient)return{totalSessions:0,totalTurns:0};const e=`${this.redisConfig.keyPrefix}*`,t=await i1(this.redisClient,e);f.debug("[RedisConversationMemoryManager] Got session keys with SCAN",{pattern:e,keyCount:t.length});const r=t.filter(o=>this.isConversationBlobKey(o));let n=0;for(const o of r){const i=await this.redisClient.get(o),s=await this.hydrateMessages(ru(i),o);s?.messages&&(n+=s.messages.filter(a=>!a.metadata?.isSkill).length/hte)}return{totalSessions:r.length,totalTurns:n}}async clearSession(e,t){if(await this.ensureInitialized(),!this.redisClient)return!1;const r=this.redisClient;return E_.startActiveSpan("memory.clear",{kind:hn.CLIENT,attributes:{"session.id":e,...t&&{"user.id":t}}},async n=>{try{const o=ka(this.redisConfig,e,t),i=await Ge(r.del([o,`${o}${AT}`]),Uy);return Number(i)>0?(t&&await this.removeUserSession(t,e),n.setAttribute("session.deleted",!0),n.setStatus({code:qe.OK}),f.info("Redis session cleared",{sessionId:e}),!0):(n.setAttribute("session.deleted",!1),n.setStatus({code:qe.OK}),!1)}catch(o){throw n.setStatus({code:qe.ERROR,message:o instanceof Error?o.message:String(o)}),n.recordException(o instanceof Error?o:new Error(String(o))),o}finally{n.end()}})}async clearAllSessions(){if(await this.ensureInitialized(),!this.redisClient)return;const e=`${this.redisConfig.keyPrefix}*`,t=`${this.redisConfig.userSessionsKeyPrefix}*`,r=await i1(this.redisClient,e),n=await i1(this.redisClient,t),o=[...r,...n];if(f.debug("[RedisConversationMemoryManager] Got all keys with SCAN for clearing",{conversationPattern:e,userSessionsPattern:t,conversationKeyCount:r.length,userSessionsKeyCount:n.length,totalKeyCount:o.length}),o.length>0){for(let s=0;s<o.length;s+=100){const a=o.slice(s,s+100);await this.redisClient.del(a),f.debug("[RedisConversationMemoryManager] Cleared batch of sessions and user mappings",{batchIndex:Math.floor(s/100)+1,batchSize:a.length,totalProcessed:s+a.length,totalKeys:o.length})}f.info("All Redis sessions and user session mappings cleared",{clearedCount:o.length,conversationSessions:r.length,userSessionMappings:n.length})}}async ensureInitialized(){f.debug("[RedisConversationMemoryManager] Ensuring initialization"),this.isInitialized?f.debug("[RedisConversationMemoryManager] Already initialized"):(f.debug("[RedisConversationMemoryManager] Not initialized, initializing now"),await this.initialize())}async getUserAllSessionsHistory(e){if(await this.ensureInitialized(),!this.redisClient)return f.warn("[RedisConversationMemoryManager] Redis client not available",{userId:e}),[];const t=[];try{const r=await this.getUserSessions(e);if(r.length===0)return t;for(const n of r)try{const o=await this.getUserSessionMetadata(e,n);o?t.push(o):(f.debug("[RedisConversationMemoryManager] Empty or missing session metadata - removing from user history",{userId:e,sessionId:n}),await this.removeUserSession(e,n))}catch(o){f.error("[RedisConversationMemoryManager] Failed to get session metadata",{userId:e,sessionId:n,error:o instanceof Error?o.message:String(o)})}return t}catch(r){return f.error("[RedisConversationMemoryManager] Failed to get user all sessions metadata",{userId:e,error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0}),t}}async listSessions(e){if(await this.ensureInitialized(),!this.redisClient)return[];const t=Date.now(),r=[];if(e){const n=await this.getUserSessions(e);for(const o of n){const i=await this.getUserSessionObject(e,o);i&&r.push({id:i.sessionId,title:i.title||i.sessionId,createdAt:i.createdAt,updatedAt:i.updatedAt,userId:i.userId,messageCount:i.messages.length,lastActive:this.formatTimeAgo(t-new Date(i.updatedAt).getTime())})}}else{const n=await i1(this.redisClient,`${this.redisConfig.keyPrefix}*`);for(const o of n){if(!this.isConversationBlobKey(o))continue;const i=await this.redisClient.get(o);if(!i)continue;const s=ru(i);s&&r.push({id:s.sessionId,title:s.title||s.sessionId,createdAt:s.createdAt,updatedAt:s.updatedAt,userId:s.userId,messageCount:await this.countMessages(s,o),lastActive:this.formatTimeAgo(t-new Date(s.updatedAt).getTime())})}}return r.sort((n,o)=>new Date(o.updatedAt).getTime()-new Date(n.updatedAt).getTime())}formatTimeAgo(e){const t=Math.floor(e/1e3),r=Math.floor(t/60),n=Math.floor(r/60),o=Math.floor(n/24);return o>0?`${o} day${o>1?"s":""} ago`:n>0?`${n} hour${n>1?"s":""} ago`:r>0?`${r} minute${r>1?"s":""} ago`:"just now"}cleanupStalePendingData(){const e=Date.now()-3e5,t=[];for(const[r,n]of this.pendingToolExecutions)n.timestamp<e&&t.push(r);t.length>0&&(f.debug("[RedisConversationMemoryManager] Cleaning up stale pending tool data",{stalePendingKeys:t.length,totalPendingKeys:this.pendingToolExecutions.size}),t.forEach(r=>this.pendingToolExecutions.delete(r)))}async flushPendingToolData(e,t,r){const n=`${t}:${r}`,o=this.pendingToolExecutions.get(n);if(!o){f.debug("[RedisConversationMemoryManager] No pending tool data to flush",{sessionId:t,userId:r,pendingKey:n});return}f.debug("[RedisConversationMemoryManager] Flushing pending tool data",{sessionId:t,userId:r,toolCallsCount:o.toolCalls.length,toolResultsCount:o.toolResults.length});try{const i=new Map;for(const s of o.toolCalls){const a=s.toolCallId??"",u=s.toolName??"";i.set(a,u);const l={id:st(),timestamp:s.timestamp?.toISOString()||this.generateTimestamp(),role:"tool_call",content:"",tool:u,...a?{toolCallId:a}:{},args:s.args||s.arguments||s.parameters||{},metadata:{...s.thoughtSignature?{thoughtSignature:String(s.thoughtSignature)}:{},...s.stepIndex!==null&&s.stepIndex!==void 0?{stepIndex:Number(s.stepIndex)}:{}}};e.messages.push(l)}for(const s of o.toolResults){const a=String(s.toolCallId||s.id||"unknown"),u=i.get(a)||String(s.toolName||"unknown"),l=s,d=("output"in l?"output":"result")==="output"?l.output:s.result;let p;if(typeof d=="string")p=d;else if(d==null)p=String(d??"null");else try{p=JSON.stringify(d,null,2)}catch(k){p=`[Serialization failed: ${k instanceof Error?k.message:String(k)}]`}const{preview:m,truncated:h,originalSize:g}=Bu(p,{maxBytes:this.config?.contextCompaction?.maxToolOutputBytes,maxLines:this.config?.contextCompaction?.maxToolOutputLines});let y;try{const k=d;if(k&&typeof k=="object"){const A=k._meta;if(A&&typeof A=="object"){const x=A[U6];typeof x=="string"&&(y=x)}}}catch{}const v={truncated:h,...h&&{toolOutputPreview:m},...h&&{originalSize:g},...y&&{artifactId:y},...s.stepIndex!==null&&s.stepIndex!==void 0?{stepIndex:Number(s.stepIndex)}:{}},w=s.error!==void 0&&s.error!==null?String(s.error):fC(d),b={success:w===void 0,error:w},E={id:st(),timestamp:s.timestamp?.toISOString()||this.generateTimestamp(),role:"tool_result",content:p,tool:u,...a&&a!=="unknown"?{toolCallId:a}:{},result:b,metadata:v};e.messages.push(E)}f.debug("[RedisConversationMemoryManager] Successfully flushed pending tool data",{sessionId:t,userId:r,toolMessagesAdded:o.toolCalls.length+o.toolResults.length,totalMessages:e.messages.length})}finally{this.pendingToolExecutions.delete(n)}}async updateAgenticLoopReport(e,t,r){if(f.debug("[RedisConversationMemoryManager] Updating agentic loop report",{sessionId:e,userId:t,reportId:r.reportId,reportType:r.reportType,reportStatus:r.reportStatus}),await this.ensureInitialized(),!this.redisClient){f.warn("[RedisConversationMemoryManager] Redis client not available for report update",{sessionId:e,userId:t});return}try{const n=ka(this.redisConfig,e,t||void 0),o=await Ge(this.redisClient.get(n),5e3);if(!o){f.warn("[RedisConversationMemoryManager] No conversation found for report update",{sessionId:e,userId:t});return}const i=ru(o);if(!i){f.warn("[RedisConversationMemoryManager] Failed to deserialize conversation for report update",{sessionId:e,userId:t});return}i.additionalMetadata||(i.additionalMetadata={}),i.additionalMetadata.agenticLoopReports||(i.additionalMetadata.agenticLoopReports=[]);const s=i.additionalMetadata.agenticLoopReports.findIndex(u=>u.reportId===r.reportId);s>=0?(i.additionalMetadata.agenticLoopReports[s]=r,f.debug("[RedisConversationMemoryManager] Updated existing agentic loop report",{sessionId:e,reportId:r.reportId})):(i.additionalMetadata.agenticLoopReports.push(r),f.debug("[RedisConversationMemoryManager] Added new agentic loop report",{sessionId:e,reportId:r.reportId})),i.updatedAt=new Date().toISOString();const a=s1(i)?q6(i):Qae(i);await Ge(eue(this.redisClient,n,a,this.redisConfig.ttl),5e3),f.info("[RedisConversationMemoryManager] Successfully updated agentic loop report",{sessionId:e,userId:t,reportId:r.reportId,reportStatus:r.reportStatus})}catch(n){throw f.error("[RedisConversationMemoryManager] Failed to update agentic loop report",{sessionId:e,userId:t,reportId:r.reportId,error:n instanceof Error?n.message:String(n)}),new Eu("Failed to update agentic loop report","STORAGE_ERROR",{sessionId:e,userId:t,reportId:r.reportId,error:n instanceof Error?n.message:String(n)})}}}}});function Chr(e,t="memory",r){if(f.debug("[conversationMemoryFactory] Creating conversation memory manager",{storageType:t,config:{enabled:e.enabled,maxSessions:e.maxSessions,enableSummarization:e.enableSummarization,summarizationProvider:e.summarizationProvider,summarizationModel:e.summarizationModel},hasRedisConfig:!!r}),t==="memory"||!t){f.debug("[conversationMemoryFactory] Creating in-memory conversation manager");const o=new _L(e);return f.debug("[conversationMemoryFactory] In-memory conversation manager created successfully",{managerType:o.constructor.name}),o}if(t==="redis"){f.debug("[conversationMemoryFactory] Creating Redis conversation manager",{host:r?.host||"localhost",port:r?.port||6379,keyPrefix:r?.keyPrefix||"neurolink:conversation:",ttl:r?.ttl||86400,hasConnectionOptions:!!r?.connectionOptions});const o=new xhr(e,r);return f.debug("[conversationMemoryFactory] Redis conversation manager created successfully",{managerType:o.constructor.name,config:{maxSessions:e.maxSessions,maxTurnsPerSession:e.maxTurnsPerSession}}),o}f.warn(`[conversationMemoryFactory] Unknown storage type: ${t}, falling back to memory storage`);const n=new _L(e);return f.debug("[conversationMemoryFactory] Fallback memory manager created successfully",{managerType:n.constructor.name}),n}function oSn(){const e=process.env.STORAGE_TYPE;if(!e)return f.debug("[conversationMemoryFactory] No storage type configured, using default",{storageType:"memory",fromEnv:!1}),"memory";const t=e.trim().toLowerCase(),r=["memory","redis"];return r.includes(t)?(f.debug("[conversationMemoryFactory] Determined storage type",{storageType:t,fromEnv:!0,envValue:e,normalized:t!==e}),t):(f.warn(`[conversationMemoryFactory] Unrecognized storage type in environment: "${e}", falling back to "memory"`,{providedValue:e,normalizedValue:t,validValues:r,usingDefault:!0}),"memory")}function iSn(){f.debug("[conversationMemoryFactory] Reading Redis configuration from environment",{REDIS_URL:process.env.REDIS_URL?"******":"(not set)",REDIS_HOST:process.env.REDIS_HOST||"(not set)",REDIS_PORT:process.env.REDIS_PORT||"(not set)",REDIS_PASSWORD:process.env.REDIS_PASSWORD?"******":"(not set)",REDIS_DB:process.env.REDIS_DB||"(not set)",REDIS_KEY_PREFIX:process.env.REDIS_KEY_PREFIX||"(not set)",REDIS_TTL:process.env.REDIS_TTL||"(not set)",REDIS_CONNECT_TIMEOUT:process.env.REDIS_CONNECT_TIMEOUT||"(not set)",REDIS_MAX_RETRIES:process.env.REDIS_MAX_RETRIES||"(not set)",REDIS_RETRY_DELAY:process.env.REDIS_RETRY_DELAY||"(not set)"});const e={host:process.env.REDIS_HOST,port:process.env.REDIS_PORT?Number(process.env.REDIS_PORT):void 0,password:process.env.REDIS_PASSWORD,db:process.env.REDIS_DB?Number(process.env.REDIS_DB):void 0,keyPrefix:process.env.REDIS_KEY_PREFIX,ttl:process.env.REDIS_TTL?Number(process.env.REDIS_TTL):void 0,connectionOptions:{connectTimeout:process.env.REDIS_CONNECT_TIMEOUT?Number(process.env.REDIS_CONNECT_TIMEOUT):void 0,maxRetriesPerRequest:process.env.REDIS_MAX_RETRIES?Number(process.env.REDIS_MAX_RETRIES):void 0,retryDelayOnFailover:process.env.REDIS_RETRY_DELAY?Number(process.env.REDIS_RETRY_DELAY):void 0}};return process.env.REDIS_URL&&(f.debug("[conversationMemoryFactory] Using REDIS_URL for connection"),e.url=process.env.REDIS_URL),f.debug("[conversationMemoryFactory] Redis configuration normalized",{host:e.host||"localhost",port:e.port||6379,hasPassword:!!e.password,db:e.db||0,keyPrefix:e.keyPrefix||"neurolink:conversation:",ttl:e.ttl||86400,hasConnectionOptions:!!e.connectionOptions}),e}var sSn=S({async"src/lib/core/conversationMemoryFactory.ts"(){"use strict";z(),aJt(),await nSn()}}),Ihr={};ue(Ihr,{initializeConversationMemory:()=>aSn});async function aSn(e){if(f.debug("[conversationMemoryInitializer] Initialize conversation memory called",{hasConfig:!!e,hasMemoryConfig:!!e?.conversationMemory,memoryEnabled:e?.conversationMemory?.enabled||!1,storageType:process.env.STORAGE_TYPE||"memory"}),!e?.conversationMemory?.enabled)return f.debug("[conversationMemoryInitializer] Conversation memory not enabled - skipping initialization"),null;try{f.debug("[conversationMemoryInitializer] Applying conversation memory defaults");const t=oln(e.conversationMemory);f.debug("[conversationMemoryInitializer] Memory configuration processed",{enabled:t.enabled,maxSessions:t.maxSessions,maxTurnsPerSession:t.maxTurnsPerSession,enableSummarization:t.enableSummarization});const r=!!e.conversationMemory?.redisConfig,n=r?"redis":oSn();if(f.debug("[conversationMemoryInitializer] Storage type determined",{storageType:n,fromConfig:r,fromEnv:!r&&!!process.env.STORAGE_TYPE}),n==="redis"){f.info("[conversationMemoryInitializer] Initializing Redis-based conversation memory manager"),f.debug("[conversationMemoryInitializer] Getting Redis configuration");const o=e.conversationMemory?.redisConfig||iSn(),i=e.conversationMemory?.redisConfig?"SDK input (from Lighthouse)":"environment variables (NeuroLink)";f.debug("[conversationMemoryInitializer] Redis configuration retrieved",{configSource:i,host:o.host||"localhost",port:o.port||6379,hasPassword:!!o.password,db:o.db||0,keyPrefix:o.keyPrefix||"neurolink:conversation:",ttl:o.ttl||86400}),f.debug("[conversationMemoryInitializer] Creating Redis conversation memory manager");const s=Chr(t,"redis",o);return f.debug("[conversationMemoryInitializer] Checking Redis manager creation result",{managerType:s?.constructor?.name||"unknown",isRedisType:s?.constructor?.name==="RedisConversationMemoryManager",hasConfig:!!s?.config}),f.info("[conversationMemoryInitializer] Redis conversation memory manager created successfully"),s?.constructor?.name!=="RedisConversationMemoryManager"&&f.warn("[conversationMemoryInitializer] Created manager is not of RedisConversationMemoryManager type",{actualType:s?.constructor?.name}),s}else{f.info("[conversationMemoryInitializer] Initializing in-memory conversation memory manager"),f.debug("[conversationMemoryInitializer] Creating in-memory conversation memory manager");const o=Chr(t);return f.debug("[conversationMemoryInitializer] Checking memory manager creation result",{managerType:o?.constructor?.name||"unknown",isInMemoryType:o?.constructor?.name==="ConversationMemoryManager",hasConfig:!!o?.config}),f.info("[conversationMemoryInitializer] In-memory conversation memory manager created successfully",{maxSessions:t.maxSessions,maxTurnsPerSession:t.maxTurnsPerSession,managerType:o?.constructor?.name}),o}}catch(t){throw f.error("[conversationMemoryInitializer] Failed to initialize conversation memory",{error:t instanceof Error?t.message:String(t),errorName:t instanceof Error?t.name:"UnknownError",errorStack:t instanceof Error?t.stack:void 0,storageType:process.env.STORAGE_TYPE||"memory",memoryConfig:{enabled:e?.conversationMemory?.enabled,maxSessions:e?.conversationMemory?.maxSessions,maxTurnsPerSession:e?.conversationMemory?.maxTurnsPerSession},redisConfig:{host:process.env.REDIS_HOST||"(not set)",port:process.env.REDIS_PORT||"(not set)",hasPassword:!!process.env.REDIS_PASSWORD,keyPrefix:process.env.REDIS_KEY_PREFIX||"(not set)"}}),process.env.STORAGE_TYPE==="redis"&&f.error("[conversationMemoryInitializer] Redis configuration error details",{REDIS_HOST:process.env.REDIS_HOST||"(not set)",REDIS_PORT:process.env.REDIS_PORT||"(not set)",REDIS_PASSWORD:process.env.REDIS_PASSWORD?"******":"(not set)",REDIS_DB:process.env.REDIS_DB||"(not set)",REDIS_KEY_PREFIX:process.env.REDIS_KEY_PREFIX||"(not set)",REDIS_TTL:process.env.REDIS_TTL||"(not set)",errorMessage:t instanceof Error?t.message:String(t)}),t}}var uSn=S({async"src/lib/core/conversationMemoryInitializer.ts"(){"use strict";iT(),z(),await sSn()}});function h5(e){return e.toLowerCase().replace(/^[\s"'“”‘’([{¿¡]+|[\s"'“”‘’)\]}.,!?;:…।॥]+$/gu,"")}function Rhr(e){const t=e.split(/\s+/u).filter(Boolean);if(t.length<f5)return{text:e,removed:0};const r=t.map(h5),n=[];let o=0,i=0;for(;i<t.length;){let s=!1;for(let a=1;a<=Mhr&&i+a*f5<=t.length;a++){let u=1;for(;i+(u+1)*a<=t.length&&lSn(r,i,i+u*a,a);)u++;if(u>=f5){for(let l=0;l<Kme*a;l++)n.push(t[i+l]);o+=(u-Kme)*a,i+=u*a,s=!0;break}}s||(n.push(t[i]),i++)}return o>0?{text:n.join(" "),removed:o}:{text:e,removed:0}}function lSn(e,t,r,n){for(let o=0;o<n;o++)if(e[t+o]!==e[r+o]||e[t+o]==="")return!1;return!0}function cSn(e,t){const r=e.split(/\s+/u).map(h5).filter(Boolean);if(r.length===0||t.length===0)return!1;const n=new Set;for(const s of t)for(const a of s.split(/\s+/u).map(h5))a&&n.add(a);if(!r.every(s=>n.has(s)))return!1;const o=` ${r.join(" ")} `;if(o.includes(` ${Jme} `))return!0;const i=new Set;for(const s of t){const a=s.split(/\s+/u).map(h5).filter(Boolean).join(" ");a&&a!==Jme&&o.includes(` ${a} `)&&i.add(a)}return i.size>=2}function dSn(e,t){return t>0?e/t:0}var Mhr,f5,Kme,Jme,pSn=S({"src/lib/voice/correction/guards.ts"(){"use strict";Mhr=6,f5=4,Kme=2,Jme="names and terms used"}});function mSn(e){let t=0,r=0,n=0;for(let a=0;a<e.length;a+=Xme){const u=Math.min(e.length,a+Xme);let l=0;for(let d=a;d<u;d++){const p=e[d];l+=p*p;const m=Math.abs(p);m>n&&(n=m)}Math.sqrt(l/Math.max(1,u-a))>=Nhr&&(t+=l,r+=u-a)}if(r===0||n===0)return e;const o=Math.sqrt(t/r),i=Math.min(Dhr,Phr/o,Ohr/n);if(!(i>=Lhr))return e;const s=new Float32Array(e.length);for(let a=0;a<e.length;a++)s[a]=e[a]*i;return s}var Phr,Dhr,Ohr,Nhr,Xme,Lhr,hSn=S({"src/lib/voice/audioLevel.ts"(){"use strict";Phr=.08,Dhr=8,Ohr=.95,Nhr=.002,Xme=320,Lhr=1.1}});function Pc(e){const t=e?.trim().toLowerCase();if(!t||t==="auto"||t==="und")return;const r=t.replace(/^auto[-_]/u,"");if(Object.hasOwn(PI,r))return PI[r];const n=r.split(/[-_]/u)[0];return Object.hasOwn(PI,n)?PI[n]:/^[a-z]{2,3}$/u.test(n)?n:void 0}function Yme(e){const t=Pc(e);return t!==void 0&&zhr.has(t)}function $hr(e){const t=new Map;for(const r of e)for(const[n,o]of Zme)if(o.test(r)){t.set(n,(t.get(n)??0)+1);break}return t}function fSn(e){let t,r=0;for(const[n,o]of $hr(e))o>r&&(t=n,r=o);return t}function MI(e){return qhr.test(e)}function Fhr(e){const t=/^([a-z]{2,3})(?:-([A-Za-z]{4}))?(?:-([A-Za-z]{2}|\d{3}))?$/iu.exec(e.trim());if(!t)return;const r=t[1].toLowerCase(),n=t[2]?`${t[2][0].toUpperCase()}${t[2].slice(1).toLowerCase()}`:void 0,o=n==="Hant"||n==="Hans"?"Hani":Zme.find(([i])=>i===n)?.[0]??(n?void 0:Ghr[r]??"Latn");if(o)return{tag:e.trim(),language:r,script:o,explicitScript:n!==void 0}}function Uhr(e,t){const r=$hr(e);let n=0;for(const i of r.values())n+=i;return n===0?1:((r.get(t)??0)+(t==="Jpan"?r.get("Hani")??0:0))/n}function g5(e){const t=Fhr(e);if(!t)return e;const r=Bhr("language",t.language);return t.explicitScript?`${r} (${Bhr("script",t.script)} script)`:r}function Bhr(e,t){try{return new Intl.DisplayNames(["en"],{type:e}).of(t)??t}catch{return t}}var zhr,PI,Zme,Ghr,qhr,y5=S({"src/lib/voice/languages.ts"(){"use strict";zhr=new Set(["as","bn","brx","doi","gu","hi","kn","kok","ks","mai","ml","mni","mr","ne","or","pa","sa","sat","sd","ta","te","ur"]),PI={english:"en",eng:"en",hindi:"hi",hin:"hi",bengali:"bn",bangla:"bn",ben:"bn",marathi:"mr",mar:"mr",gujarati:"gu",guj:"gu",punjabi:"pa",panjabi:"pa",pan:"pa",odia:"or",oriya:"or",ori:"or",assamese:"as",asm:"as",urdu:"ur",urd:"ur",tamil:"ta",tam:"ta",telugu:"te",tel:"te",kannada:"kn",kan:"kn",malayalam:"ml",mal:"ml",nepali:"ne",nep:"ne",sanskrit:"sa",san:"sa",sindhi:"sd",kashmiri:"ks",konkani:"kok",maithili:"mai",spanish:"es",spa:"es",french:"fr",fra:"fr",german:"de",deu:"de",italian:"it",portuguese:"pt",russian:"ru",japanese:"ja",jpn:"ja",korean:"ko",kor:"ko",chinese:"zh",mandarin:"zh",cantonese:"yue",zho:"zh",arabic:"ar",ara:"ar",persian:"fa",turkish:"tr",dutch:"nl",indonesian:"id",vietnamese:"vi",thai:"th"},Zme=[["Latn",/\p{Script=Latin}/u],["Deva",/\p{Script=Devanagari}/u],["Beng",/\p{Script=Bengali}/u],["Guru",/\p{Script=Gurmukhi}/u],["Gujr",/\p{Script=Gujarati}/u],["Orya",/\p{Script=Oriya}/u],["Taml",/\p{Script=Tamil}/u],["Telu",/\p{Script=Telugu}/u],["Knda",/\p{Script=Kannada}/u],["Mlym",/\p{Script=Malayalam}/u],["Sinh",/\p{Script=Sinhala}/u],["Arab",/\p{Script=Arabic}/u],["Cyrl",/\p{Script=Cyrillic}/u],["Grek",/\p{Script=Greek}/u],["Hebr",/\p{Script=Hebrew}/u],["Thai",/\p{Script=Thai}/u],["Hang",/\p{Script=Hangul}/u],["Jpan",/[\p{Script=Hiragana}\p{Script=Katakana}]/u],["Hani",/\p{Script=Han}/u],["Geor",/\p{Script=Georgian}/u],["Armn",/\p{Script=Armenian}/u],["Ethi",/\p{Script=Ethiopic}/u]],Ghr={hi:"Deva",mr:"Deva",ne:"Deva",sa:"Deva",mai:"Deva",kok:"Deva",doi:"Deva",brx:"Deva",bn:"Beng",as:"Beng",mni:"Beng",pa:"Guru",gu:"Gujr",or:"Orya",ta:"Taml",te:"Telu",kn:"Knda",ml:"Mlym",si:"Sinh",ur:"Arab",ar:"Arab",fa:"Arab",ps:"Arab",sd:"Arab",ks:"Arab",ru:"Cyrl",uk:"Cyrl",bg:"Cyrl",sr:"Cyrl",mk:"Cyrl",be:"Cyrl",kk:"Cyrl",el:"Grek",he:"Hebr",yi:"Hebr",th:"Thai",ko:"Hang",ja:"Jpan",zh:"Hani",yue:"Hani",ka:"Geor",hy:"Armn",am:"Ethi"},qhr=/[\p{Script=Devanagari}\p{Script=Bengali}\p{Script=Gurmukhi}\p{Script=Gujarati}\p{Script=Oriya}\p{Script=Tamil}\p{Script=Telugu}\p{Script=Kannada}\p{Script=Malayalam}\p{Script=Sinhala}]/u}});function v5(e){if(!e)return[];let t;try{t=Array.isArray(e.languages)?e.languages:e.languages.current()}catch{return[]}const r=new Set,n=[];for(const o of t){const i=typeof o=="string"?o.trim():"";if(i&&!r.has(i.toLowerCase())&&(r.add(i.toLowerCase()),n.push(i)),n.length>=DI)break}return n}function gSn(e){return e.split(/\s+/u).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function w5(e){return e.toLowerCase().normalize("NFKC").replace(/[^\p{L}\p{N}]+/gu," ").trim()}function ySn(e,t,r,n,o){if(!e.trim())return"empty";if(e.replace(/[^\p{L}]/gu,"").length>=3&&Uhr(e,n.script)<Jhr)return`not in ${n.script} script`;if(o&&o!==n.language&&gSn(t)>=3&&(w5(e)===w5(t)||w5(e)===w5(r)))return"untranslated"}function vSn(e,t){const r=["- Translate the meaning faithfully and completely: never summarize, explain, add or leave anything out. Keep the speaker's tone and register.","- An output in the language that was spoken is not a translation: keep the speaker's words and only write them in the requested writing system.",'- An output named "<language> (Latin script)" is that language written in Latin letters the way people type it on phones (Hinglish: "mera naam", "kal milte hain"), never English. When the speaker spoke another language (English included), translate into that language first: the sentence must read as that language, keeping only names, terms and the few English words its speakers use as is.',"- Code-mixed speech is rendered entirely in the output language, except names, brands and glossary terms.","- Keep names, numbers (as digits), units, emails, URLs and code exactly.","- The lines come from speech recognition and can hold mis-heard words: render what the speaker most plausibly meant, using the cleaned version when one is given."];return e.length&&r.push(`- Keep these terms exactly as written, in every output: ${e.map(n=>`"${n}"`).join(", ")}.`),r.push(t?"- For every output return one string per input line, in the same order, as many strings as there are lines.":"- For every output return a list with exactly one string: the rendered line."),["You are a professional interpreter writing out live speech in other languages.","For every requested output, render the speaker's lines in that language and writing system:",...r,"Answer with a JSON object whose keys are the output tags, each holding the list of rendered lines."].join(`
|
|
1923
|
+
${e}`,timestamp:new Date().toISOString(),metadata:{isSummary:!0,summarizesFrom:t,summarizesTo:r}}}async getSessionMessages(e,t){if(await this.ensureInitialized(),!this.redisClient)return[];try{const r=ka(this.redisConfig,e,t),n=await this.redisClient.get(r);return(await this.hydrateMessages(ru(n||null),r))?.messages??[]}catch(r){return f.error("[RedisConversationMemoryManager] Failed to get session messages",{sessionId:e,userId:t,error:r instanceof Error?r.message:String(r)}),[]}}async setSessionMessages(e,t,r){if(await this.ensureInitialized(),!this.redisClient)throw new Eu("Redis client not initialized","STORAGE_ERROR",{sessionId:e});try{const n=ka(this.redisConfig,e,r),o=await this.redisClient.get(n),i=ru(o||null);if(!i)throw new Eu(`Session ${e} not found`,"STORAGE_ERROR",{sessionId:e});i.messages=t,i.updatedAt=new Date().toISOString(),i.summarizedUpToMessageId=void 0,i.summarizedMessage=void 0,i.lastTokenCount=void 0,i.lastCountedAt=void 0,await this.persistConversation(i,e,r),f.debug("[RedisConversationMemoryManager] Session messages replaced",{sessionId:e,userId:r,messageCount:t.length})}catch(n){throw n instanceof Eu?n:new Eu(`Failed to set session messages for session ${e}`,"STORAGE_ERROR",{sessionId:e,error:n instanceof Error?n.message:String(n)})}}async close(){this.redisClient&&(await grr(this.redisConfig),this.redisClient=null,this.isInitialized=!1,f.info("Redis connection closed"))}async getStats(){if(await this.ensureInitialized(),!this.redisClient)return{totalSessions:0,totalTurns:0};const e=`${this.redisConfig.keyPrefix}*`,t=await i1(this.redisClient,e);f.debug("[RedisConversationMemoryManager] Got session keys with SCAN",{pattern:e,keyCount:t.length});const r=t.filter(o=>this.isConversationBlobKey(o));let n=0;for(const o of r){const i=await this.redisClient.get(o),s=await this.hydrateMessages(ru(i),o);s?.messages&&(n+=s.messages.filter(a=>!a.metadata?.isSkill).length/hte)}return{totalSessions:r.length,totalTurns:n}}async clearSession(e,t){if(await this.ensureInitialized(),!this.redisClient)return!1;const r=this.redisClient;return E_.startActiveSpan("memory.clear",{kind:hn.CLIENT,attributes:{"session.id":e,...t&&{"user.id":t}}},async n=>{try{const o=ka(this.redisConfig,e,t),i=await Ge(r.del([o,`${o}${AT}`]),Uy);return Number(i)>0?(t&&await this.removeUserSession(t,e),n.setAttribute("session.deleted",!0),n.setStatus({code:qe.OK}),f.info("Redis session cleared",{sessionId:e}),!0):(n.setAttribute("session.deleted",!1),n.setStatus({code:qe.OK}),!1)}catch(o){throw n.setStatus({code:qe.ERROR,message:o instanceof Error?o.message:String(o)}),n.recordException(o instanceof Error?o:new Error(String(o))),o}finally{n.end()}})}async clearAllSessions(){if(await this.ensureInitialized(),!this.redisClient)return;const e=`${this.redisConfig.keyPrefix}*`,t=`${this.redisConfig.userSessionsKeyPrefix}*`,r=await i1(this.redisClient,e),n=await i1(this.redisClient,t),o=[...r,...n];if(f.debug("[RedisConversationMemoryManager] Got all keys with SCAN for clearing",{conversationPattern:e,userSessionsPattern:t,conversationKeyCount:r.length,userSessionsKeyCount:n.length,totalKeyCount:o.length}),o.length>0){for(let s=0;s<o.length;s+=100){const a=o.slice(s,s+100);await this.redisClient.del(a),f.debug("[RedisConversationMemoryManager] Cleared batch of sessions and user mappings",{batchIndex:Math.floor(s/100)+1,batchSize:a.length,totalProcessed:s+a.length,totalKeys:o.length})}f.info("All Redis sessions and user session mappings cleared",{clearedCount:o.length,conversationSessions:r.length,userSessionMappings:n.length})}}async ensureInitialized(){f.debug("[RedisConversationMemoryManager] Ensuring initialization"),this.isInitialized?f.debug("[RedisConversationMemoryManager] Already initialized"):(f.debug("[RedisConversationMemoryManager] Not initialized, initializing now"),await this.initialize())}async getUserAllSessionsHistory(e){if(await this.ensureInitialized(),!this.redisClient)return f.warn("[RedisConversationMemoryManager] Redis client not available",{userId:e}),[];const t=[];try{const r=await this.getUserSessions(e);if(r.length===0)return t;for(const n of r)try{const o=await this.getUserSessionMetadata(e,n);o?t.push(o):(f.debug("[RedisConversationMemoryManager] Empty or missing session metadata - removing from user history",{userId:e,sessionId:n}),await this.removeUserSession(e,n))}catch(o){f.error("[RedisConversationMemoryManager] Failed to get session metadata",{userId:e,sessionId:n,error:o instanceof Error?o.message:String(o)})}return t}catch(r){return f.error("[RedisConversationMemoryManager] Failed to get user all sessions metadata",{userId:e,error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0}),t}}async listSessions(e){if(await this.ensureInitialized(),!this.redisClient)return[];const t=Date.now(),r=[];if(e){const n=await this.getUserSessions(e);for(const o of n){const i=await this.getUserSessionObject(e,o);i&&r.push({id:i.sessionId,title:i.title||i.sessionId,createdAt:i.createdAt,updatedAt:i.updatedAt,userId:i.userId,messageCount:i.messages.length,lastActive:this.formatTimeAgo(t-new Date(i.updatedAt).getTime())})}}else{const n=await i1(this.redisClient,`${this.redisConfig.keyPrefix}*`);for(const o of n){if(!this.isConversationBlobKey(o))continue;const i=await this.redisClient.get(o);if(!i)continue;const s=ru(i);s&&r.push({id:s.sessionId,title:s.title||s.sessionId,createdAt:s.createdAt,updatedAt:s.updatedAt,userId:s.userId,messageCount:await this.countMessages(s,o),lastActive:this.formatTimeAgo(t-new Date(s.updatedAt).getTime())})}}return r.sort((n,o)=>new Date(o.updatedAt).getTime()-new Date(n.updatedAt).getTime())}formatTimeAgo(e){const t=Math.floor(e/1e3),r=Math.floor(t/60),n=Math.floor(r/60),o=Math.floor(n/24);return o>0?`${o} day${o>1?"s":""} ago`:n>0?`${n} hour${n>1?"s":""} ago`:r>0?`${r} minute${r>1?"s":""} ago`:"just now"}cleanupStalePendingData(){const e=Date.now()-3e5,t=[];for(const[r,n]of this.pendingToolExecutions)n.timestamp<e&&t.push(r);t.length>0&&(f.debug("[RedisConversationMemoryManager] Cleaning up stale pending tool data",{stalePendingKeys:t.length,totalPendingKeys:this.pendingToolExecutions.size}),t.forEach(r=>this.pendingToolExecutions.delete(r)))}async flushPendingToolData(e,t,r){const n=`${t}:${r}`,o=this.pendingToolExecutions.get(n);if(!o){f.debug("[RedisConversationMemoryManager] No pending tool data to flush",{sessionId:t,userId:r,pendingKey:n});return}f.debug("[RedisConversationMemoryManager] Flushing pending tool data",{sessionId:t,userId:r,toolCallsCount:o.toolCalls.length,toolResultsCount:o.toolResults.length});try{const i=new Map;for(const s of o.toolCalls){const a=s.toolCallId??"",u=s.toolName??"";i.set(a,u);const l={id:st(),timestamp:s.timestamp?.toISOString()||this.generateTimestamp(),role:"tool_call",content:"",tool:u,...a?{toolCallId:a}:{},args:s.args||s.arguments||s.parameters||{},metadata:{...s.thoughtSignature?{thoughtSignature:String(s.thoughtSignature)}:{},...s.stepIndex!==null&&s.stepIndex!==void 0?{stepIndex:Number(s.stepIndex)}:{}}};e.messages.push(l)}for(const s of o.toolResults){const a=String(s.toolCallId||s.id||"unknown"),u=i.get(a)||String(s.toolName||"unknown"),l=s,d=("output"in l?"output":"result")==="output"?l.output:s.result;let p;if(typeof d=="string")p=d;else if(d==null)p=String(d??"null");else try{p=JSON.stringify(d,null,2)}catch(k){p=`[Serialization failed: ${k instanceof Error?k.message:String(k)}]`}const{preview:m,truncated:h,originalSize:g}=Bu(p,{maxBytes:this.config?.contextCompaction?.maxToolOutputBytes,maxLines:this.config?.contextCompaction?.maxToolOutputLines});let y;try{const k=d;if(k&&typeof k=="object"){const A=k._meta;if(A&&typeof A=="object"){const x=A[U6];typeof x=="string"&&(y=x)}}}catch{}const v={truncated:h,...h&&{toolOutputPreview:m},...h&&{originalSize:g},...y&&{artifactId:y},...s.stepIndex!==null&&s.stepIndex!==void 0?{stepIndex:Number(s.stepIndex)}:{}},w=s.error!==void 0&&s.error!==null?String(s.error):fC(d),b={success:w===void 0,error:w},E={id:st(),timestamp:s.timestamp?.toISOString()||this.generateTimestamp(),role:"tool_result",content:p,tool:u,...a&&a!=="unknown"?{toolCallId:a}:{},result:b,metadata:v};e.messages.push(E)}f.debug("[RedisConversationMemoryManager] Successfully flushed pending tool data",{sessionId:t,userId:r,toolMessagesAdded:o.toolCalls.length+o.toolResults.length,totalMessages:e.messages.length})}finally{this.pendingToolExecutions.delete(n)}}async updateAgenticLoopReport(e,t,r){if(f.debug("[RedisConversationMemoryManager] Updating agentic loop report",{sessionId:e,userId:t,reportId:r.reportId,reportType:r.reportType,reportStatus:r.reportStatus}),await this.ensureInitialized(),!this.redisClient){f.warn("[RedisConversationMemoryManager] Redis client not available for report update",{sessionId:e,userId:t});return}try{const n=ka(this.redisConfig,e,t||void 0),o=await Ge(this.redisClient.get(n),5e3);if(!o){f.warn("[RedisConversationMemoryManager] No conversation found for report update",{sessionId:e,userId:t});return}const i=ru(o);if(!i){f.warn("[RedisConversationMemoryManager] Failed to deserialize conversation for report update",{sessionId:e,userId:t});return}i.additionalMetadata||(i.additionalMetadata={}),i.additionalMetadata.agenticLoopReports||(i.additionalMetadata.agenticLoopReports=[]);const s=i.additionalMetadata.agenticLoopReports.findIndex(u=>u.reportId===r.reportId);s>=0?(i.additionalMetadata.agenticLoopReports[s]=r,f.debug("[RedisConversationMemoryManager] Updated existing agentic loop report",{sessionId:e,reportId:r.reportId})):(i.additionalMetadata.agenticLoopReports.push(r),f.debug("[RedisConversationMemoryManager] Added new agentic loop report",{sessionId:e,reportId:r.reportId})),i.updatedAt=new Date().toISOString();const a=s1(i)?q6(i):Qae(i);await Ge(eue(this.redisClient,n,a,this.redisConfig.ttl),5e3),f.info("[RedisConversationMemoryManager] Successfully updated agentic loop report",{sessionId:e,userId:t,reportId:r.reportId,reportStatus:r.reportStatus})}catch(n){throw f.error("[RedisConversationMemoryManager] Failed to update agentic loop report",{sessionId:e,userId:t,reportId:r.reportId,error:n instanceof Error?n.message:String(n)}),new Eu("Failed to update agentic loop report","STORAGE_ERROR",{sessionId:e,userId:t,reportId:r.reportId,error:n instanceof Error?n.message:String(n)})}}}}});function Chr(e,t="memory",r,n){if(f.debug("[conversationMemoryFactory] Creating conversation memory manager",{storageType:t,config:{enabled:e.enabled,maxSessions:e.maxSessions,enableSummarization:e.enableSummarization,summarizationProvider:e.summarizationProvider,summarizationModel:e.summarizationModel},hasRedisConfig:!!r}),t==="memory"||!t){f.debug("[conversationMemoryFactory] Creating in-memory conversation manager");const i=new _L(e);return f.debug("[conversationMemoryFactory] In-memory conversation manager created successfully",{managerType:i.constructor.name}),i}if(t==="redis"){f.debug("[conversationMemoryFactory] Creating Redis conversation manager",{host:r?.host||"localhost",port:r?.port||6379,keyPrefix:r?.keyPrefix||"neurolink:conversation:",ttl:r?.ttl||86400,hasConnectionOptions:!!r?.connectionOptions});const i=new xhr(e,r,n);return f.debug("[conversationMemoryFactory] Redis conversation manager created successfully",{managerType:i.constructor.name,config:{maxSessions:e.maxSessions,maxTurnsPerSession:e.maxTurnsPerSession}}),i}f.warn(`[conversationMemoryFactory] Unknown storage type: ${t}, falling back to memory storage`);const o=new _L(e);return f.debug("[conversationMemoryFactory] Fallback memory manager created successfully",{managerType:o.constructor.name}),o}function oSn(){const e=process.env.STORAGE_TYPE;if(!e)return f.debug("[conversationMemoryFactory] No storage type configured, using default",{storageType:"memory",fromEnv:!1}),"memory";const t=e.trim().toLowerCase(),r=["memory","redis"];return r.includes(t)?(f.debug("[conversationMemoryFactory] Determined storage type",{storageType:t,fromEnv:!0,envValue:e,normalized:t!==e}),t):(f.warn(`[conversationMemoryFactory] Unrecognized storage type in environment: "${e}", falling back to "memory"`,{providedValue:e,normalizedValue:t,validValues:r,usingDefault:!0}),"memory")}function iSn(){f.debug("[conversationMemoryFactory] Reading Redis configuration from environment",{REDIS_URL:process.env.REDIS_URL?"******":"(not set)",REDIS_HOST:process.env.REDIS_HOST||"(not set)",REDIS_PORT:process.env.REDIS_PORT||"(not set)",REDIS_PASSWORD:process.env.REDIS_PASSWORD?"******":"(not set)",REDIS_DB:process.env.REDIS_DB||"(not set)",REDIS_KEY_PREFIX:process.env.REDIS_KEY_PREFIX||"(not set)",REDIS_TTL:process.env.REDIS_TTL||"(not set)",REDIS_CONNECT_TIMEOUT:process.env.REDIS_CONNECT_TIMEOUT||"(not set)",REDIS_MAX_RETRIES:process.env.REDIS_MAX_RETRIES||"(not set)",REDIS_RETRY_DELAY:process.env.REDIS_RETRY_DELAY||"(not set)"});const e={host:process.env.REDIS_HOST,port:process.env.REDIS_PORT?Number(process.env.REDIS_PORT):void 0,password:process.env.REDIS_PASSWORD,db:process.env.REDIS_DB?Number(process.env.REDIS_DB):void 0,keyPrefix:process.env.REDIS_KEY_PREFIX,ttl:process.env.REDIS_TTL?Number(process.env.REDIS_TTL):void 0,connectionOptions:{connectTimeout:process.env.REDIS_CONNECT_TIMEOUT?Number(process.env.REDIS_CONNECT_TIMEOUT):void 0,maxRetriesPerRequest:process.env.REDIS_MAX_RETRIES?Number(process.env.REDIS_MAX_RETRIES):void 0,retryDelayOnFailover:process.env.REDIS_RETRY_DELAY?Number(process.env.REDIS_RETRY_DELAY):void 0}};return process.env.REDIS_URL&&(f.debug("[conversationMemoryFactory] Using REDIS_URL for connection"),e.url=process.env.REDIS_URL),f.debug("[conversationMemoryFactory] Redis configuration normalized",{host:e.host||"localhost",port:e.port||6379,hasPassword:!!e.password,db:e.db||0,keyPrefix:e.keyPrefix||"neurolink:conversation:",ttl:e.ttl||86400,hasConnectionOptions:!!e.connectionOptions}),e}var sSn=S({async"src/lib/core/conversationMemoryFactory.ts"(){"use strict";z(),aJt(),await nSn()}}),Ihr={};ue(Ihr,{initializeConversationMemory:()=>aSn});async function aSn(e,t){if(f.debug("[conversationMemoryInitializer] Initialize conversation memory called",{hasConfig:!!e,hasMemoryConfig:!!e?.conversationMemory,memoryEnabled:e?.conversationMemory?.enabled||!1,storageType:process.env.STORAGE_TYPE||"memory"}),!e?.conversationMemory?.enabled)return f.debug("[conversationMemoryInitializer] Conversation memory not enabled - skipping initialization"),null;try{f.debug("[conversationMemoryInitializer] Applying conversation memory defaults");const r=oln(e.conversationMemory);f.debug("[conversationMemoryInitializer] Memory configuration processed",{enabled:r.enabled,maxSessions:r.maxSessions,maxTurnsPerSession:r.maxTurnsPerSession,enableSummarization:r.enableSummarization});const n=!!e.conversationMemory?.redisConfig,o=n?"redis":oSn();if(f.debug("[conversationMemoryInitializer] Storage type determined",{storageType:o,fromConfig:n,fromEnv:!n&&!!process.env.STORAGE_TYPE}),o==="redis"){f.info("[conversationMemoryInitializer] Initializing Redis-based conversation memory manager"),f.debug("[conversationMemoryInitializer] Getting Redis configuration");const i=e.conversationMemory?.redisConfig||iSn(),s=e.conversationMemory?.redisConfig?"SDK input (from Lighthouse)":"environment variables (NeuroLink)";f.debug("[conversationMemoryInitializer] Redis configuration retrieved",{configSource:s,host:i.host||"localhost",port:i.port||6379,hasPassword:!!i.password,db:i.db||0,keyPrefix:i.keyPrefix||"neurolink:conversation:",ttl:i.ttl||86400}),f.debug("[conversationMemoryInitializer] Creating Redis conversation memory manager");const a=Chr(r,"redis",i,t);return f.debug("[conversationMemoryInitializer] Checking Redis manager creation result",{managerType:a?.constructor?.name||"unknown",isRedisType:a?.constructor?.name==="RedisConversationMemoryManager",hasConfig:!!a?.config}),f.info("[conversationMemoryInitializer] Redis conversation memory manager created successfully"),a?.constructor?.name!=="RedisConversationMemoryManager"&&f.warn("[conversationMemoryInitializer] Created manager is not of RedisConversationMemoryManager type",{actualType:a?.constructor?.name}),a}else{f.info("[conversationMemoryInitializer] Initializing in-memory conversation memory manager"),f.debug("[conversationMemoryInitializer] Creating in-memory conversation memory manager");const i=Chr(r);return f.debug("[conversationMemoryInitializer] Checking memory manager creation result",{managerType:i?.constructor?.name||"unknown",isInMemoryType:i?.constructor?.name==="ConversationMemoryManager",hasConfig:!!i?.config}),f.info("[conversationMemoryInitializer] In-memory conversation memory manager created successfully",{maxSessions:r.maxSessions,maxTurnsPerSession:r.maxTurnsPerSession,managerType:i?.constructor?.name}),i}}catch(r){throw f.error("[conversationMemoryInitializer] Failed to initialize conversation memory",{error:r instanceof Error?r.message:String(r),errorName:r instanceof Error?r.name:"UnknownError",errorStack:r instanceof Error?r.stack:void 0,storageType:process.env.STORAGE_TYPE||"memory",memoryConfig:{enabled:e?.conversationMemory?.enabled,maxSessions:e?.conversationMemory?.maxSessions,maxTurnsPerSession:e?.conversationMemory?.maxTurnsPerSession},redisConfig:{host:process.env.REDIS_HOST||"(not set)",port:process.env.REDIS_PORT||"(not set)",hasPassword:!!process.env.REDIS_PASSWORD,keyPrefix:process.env.REDIS_KEY_PREFIX||"(not set)"}}),process.env.STORAGE_TYPE==="redis"&&f.error("[conversationMemoryInitializer] Redis configuration error details",{REDIS_HOST:process.env.REDIS_HOST||"(not set)",REDIS_PORT:process.env.REDIS_PORT||"(not set)",REDIS_PASSWORD:process.env.REDIS_PASSWORD?"******":"(not set)",REDIS_DB:process.env.REDIS_DB||"(not set)",REDIS_KEY_PREFIX:process.env.REDIS_KEY_PREFIX||"(not set)",REDIS_TTL:process.env.REDIS_TTL||"(not set)",errorMessage:r instanceof Error?r.message:String(r)}),r}}var uSn=S({async"src/lib/core/conversationMemoryInitializer.ts"(){"use strict";iT(),z(),await sSn()}});function h5(e){return e.toLowerCase().replace(/^[\s"'“”‘’([{¿¡]+|[\s"'“”‘’)\]}.,!?;:…।॥]+$/gu,"")}function Rhr(e){const t=e.split(/\s+/u).filter(Boolean);if(t.length<f5)return{text:e,removed:0};const r=t.map(h5),n=[];let o=0,i=0;for(;i<t.length;){let s=!1;for(let a=1;a<=Mhr&&i+a*f5<=t.length;a++){let u=1;for(;i+(u+1)*a<=t.length&&lSn(r,i,i+u*a,a);)u++;if(u>=f5){for(let l=0;l<Kme*a;l++)n.push(t[i+l]);o+=(u-Kme)*a,i+=u*a,s=!0;break}}s||(n.push(t[i]),i++)}return o>0?{text:n.join(" "),removed:o}:{text:e,removed:0}}function lSn(e,t,r,n){for(let o=0;o<n;o++)if(e[t+o]!==e[r+o]||e[t+o]==="")return!1;return!0}function cSn(e,t){const r=e.split(/\s+/u).map(h5).filter(Boolean);if(r.length===0||t.length===0)return!1;const n=new Set;for(const s of t)for(const a of s.split(/\s+/u).map(h5))a&&n.add(a);if(!r.every(s=>n.has(s)))return!1;const o=` ${r.join(" ")} `;if(o.includes(` ${Jme} `))return!0;const i=new Set;for(const s of t){const a=s.split(/\s+/u).map(h5).filter(Boolean).join(" ");a&&a!==Jme&&o.includes(` ${a} `)&&i.add(a)}return i.size>=2}function dSn(e,t){return t>0?e/t:0}var Mhr,f5,Kme,Jme,pSn=S({"src/lib/voice/correction/guards.ts"(){"use strict";Mhr=6,f5=4,Kme=2,Jme="names and terms used"}});function mSn(e){let t=0,r=0,n=0;for(let a=0;a<e.length;a+=Xme){const u=Math.min(e.length,a+Xme);let l=0;for(let d=a;d<u;d++){const p=e[d];l+=p*p;const m=Math.abs(p);m>n&&(n=m)}Math.sqrt(l/Math.max(1,u-a))>=Nhr&&(t+=l,r+=u-a)}if(r===0||n===0)return e;const o=Math.sqrt(t/r),i=Math.min(Dhr,Phr/o,Ohr/n);if(!(i>=Lhr))return e;const s=new Float32Array(e.length);for(let a=0;a<e.length;a++)s[a]=e[a]*i;return s}var Phr,Dhr,Ohr,Nhr,Xme,Lhr,hSn=S({"src/lib/voice/audioLevel.ts"(){"use strict";Phr=.08,Dhr=8,Ohr=.95,Nhr=.002,Xme=320,Lhr=1.1}});function Pc(e){const t=e?.trim().toLowerCase();if(!t||t==="auto"||t==="und")return;const r=t.replace(/^auto[-_]/u,"");if(Object.hasOwn(PI,r))return PI[r];const n=r.split(/[-_]/u)[0];return Object.hasOwn(PI,n)?PI[n]:/^[a-z]{2,3}$/u.test(n)?n:void 0}function Yme(e){const t=Pc(e);return t!==void 0&&zhr.has(t)}function $hr(e){const t=new Map;for(const r of e)for(const[n,o]of Zme)if(o.test(r)){t.set(n,(t.get(n)??0)+1);break}return t}function fSn(e){let t,r=0;for(const[n,o]of $hr(e))o>r&&(t=n,r=o);return t}function MI(e){return qhr.test(e)}function Fhr(e){const t=/^([a-z]{2,3})(?:-([A-Za-z]{4}))?(?:-([A-Za-z]{2}|\d{3}))?$/iu.exec(e.trim());if(!t)return;const r=t[1].toLowerCase(),n=t[2]?`${t[2][0].toUpperCase()}${t[2].slice(1).toLowerCase()}`:void 0,o=n==="Hant"||n==="Hans"?"Hani":Zme.find(([i])=>i===n)?.[0]??(n?void 0:Ghr[r]??"Latn");if(o)return{tag:e.trim(),language:r,script:o,explicitScript:n!==void 0}}function Uhr(e,t){const r=$hr(e);let n=0;for(const i of r.values())n+=i;return n===0?1:((r.get(t)??0)+(t==="Jpan"?r.get("Hani")??0:0))/n}function g5(e){const t=Fhr(e);if(!t)return e;const r=Bhr("language",t.language);return t.explicitScript?`${r} (${Bhr("script",t.script)} script)`:r}function Bhr(e,t){try{return new Intl.DisplayNames(["en"],{type:e}).of(t)??t}catch{return t}}var zhr,PI,Zme,Ghr,qhr,y5=S({"src/lib/voice/languages.ts"(){"use strict";zhr=new Set(["as","bn","brx","doi","gu","hi","kn","kok","ks","mai","ml","mni","mr","ne","or","pa","sa","sat","sd","ta","te","ur"]),PI={english:"en",eng:"en",hindi:"hi",hin:"hi",bengali:"bn",bangla:"bn",ben:"bn",marathi:"mr",mar:"mr",gujarati:"gu",guj:"gu",punjabi:"pa",panjabi:"pa",pan:"pa",odia:"or",oriya:"or",ori:"or",assamese:"as",asm:"as",urdu:"ur",urd:"ur",tamil:"ta",tam:"ta",telugu:"te",tel:"te",kannada:"kn",kan:"kn",malayalam:"ml",mal:"ml",nepali:"ne",nep:"ne",sanskrit:"sa",san:"sa",sindhi:"sd",kashmiri:"ks",konkani:"kok",maithili:"mai",spanish:"es",spa:"es",french:"fr",fra:"fr",german:"de",deu:"de",italian:"it",portuguese:"pt",russian:"ru",japanese:"ja",jpn:"ja",korean:"ko",kor:"ko",chinese:"zh",mandarin:"zh",cantonese:"yue",zho:"zh",arabic:"ar",ara:"ar",persian:"fa",turkish:"tr",dutch:"nl",indonesian:"id",vietnamese:"vi",thai:"th"},Zme=[["Latn",/\p{Script=Latin}/u],["Deva",/\p{Script=Devanagari}/u],["Beng",/\p{Script=Bengali}/u],["Guru",/\p{Script=Gurmukhi}/u],["Gujr",/\p{Script=Gujarati}/u],["Orya",/\p{Script=Oriya}/u],["Taml",/\p{Script=Tamil}/u],["Telu",/\p{Script=Telugu}/u],["Knda",/\p{Script=Kannada}/u],["Mlym",/\p{Script=Malayalam}/u],["Sinh",/\p{Script=Sinhala}/u],["Arab",/\p{Script=Arabic}/u],["Cyrl",/\p{Script=Cyrillic}/u],["Grek",/\p{Script=Greek}/u],["Hebr",/\p{Script=Hebrew}/u],["Thai",/\p{Script=Thai}/u],["Hang",/\p{Script=Hangul}/u],["Jpan",/[\p{Script=Hiragana}\p{Script=Katakana}]/u],["Hani",/\p{Script=Han}/u],["Geor",/\p{Script=Georgian}/u],["Armn",/\p{Script=Armenian}/u],["Ethi",/\p{Script=Ethiopic}/u]],Ghr={hi:"Deva",mr:"Deva",ne:"Deva",sa:"Deva",mai:"Deva",kok:"Deva",doi:"Deva",brx:"Deva",bn:"Beng",as:"Beng",mni:"Beng",pa:"Guru",gu:"Gujr",or:"Orya",ta:"Taml",te:"Telu",kn:"Knda",ml:"Mlym",si:"Sinh",ur:"Arab",ar:"Arab",fa:"Arab",ps:"Arab",sd:"Arab",ks:"Arab",ru:"Cyrl",uk:"Cyrl",bg:"Cyrl",sr:"Cyrl",mk:"Cyrl",be:"Cyrl",kk:"Cyrl",el:"Grek",he:"Hebr",yi:"Hebr",th:"Thai",ko:"Hang",ja:"Jpan",zh:"Hani",yue:"Hani",ka:"Geor",hy:"Armn",am:"Ethi"},qhr=/[\p{Script=Devanagari}\p{Script=Bengali}\p{Script=Gurmukhi}\p{Script=Gujarati}\p{Script=Oriya}\p{Script=Tamil}\p{Script=Telugu}\p{Script=Kannada}\p{Script=Malayalam}\p{Script=Sinhala}]/u}});function v5(e){if(!e)return[];let t;try{t=Array.isArray(e.languages)?e.languages:e.languages.current()}catch{return[]}const r=new Set,n=[];for(const o of t){const i=typeof o=="string"?o.trim():"";if(i&&!r.has(i.toLowerCase())&&(r.add(i.toLowerCase()),n.push(i)),n.length>=DI)break}return n}function gSn(e){return e.split(/\s+/u).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function w5(e){return e.toLowerCase().normalize("NFKC").replace(/[^\p{L}\p{N}]+/gu," ").trim()}function ySn(e,t,r,n,o){if(!e.trim())return"empty";if(e.replace(/[^\p{L}]/gu,"").length>=3&&Uhr(e,n.script)<Jhr)return`not in ${n.script} script`;if(o&&o!==n.language&&gSn(t)>=3&&(w5(e)===w5(t)||w5(e)===w5(r)))return"untranslated"}function vSn(e,t){const r=["- Translate the meaning faithfully and completely: never summarize, explain, add or leave anything out. Keep the speaker's tone and register.","- An output in the language that was spoken is not a translation: keep the speaker's words and only write them in the requested writing system.",'- An output named "<language> (Latin script)" is that language written in Latin letters the way people type it on phones (Hinglish: "mera naam", "kal milte hain"), never English. When the speaker spoke another language (English included), translate into that language first: the sentence must read as that language, keeping only names, terms and the few English words its speakers use as is.',"- Code-mixed speech is rendered entirely in the output language, except names, brands and glossary terms.","- Keep names, numbers (as digits), units, emails, URLs and code exactly.","- The lines come from speech recognition and can hold mis-heard words: render what the speaker most plausibly meant, using the cleaned version when one is given."];return e.length&&r.push(`- Keep these terms exactly as written, in every output: ${e.map(n=>`"${n}"`).join(", ")}.`),r.push(t?"- For every output return one string per input line, in the same order, as many strings as there are lines.":"- For every output return a list with exactly one string: the rendered line."),["You are a professional interpreter writing out live speech in other languages.","For every requested output, render the speaker's lines in that language and writing system:",...r,"Answer with a JSON object whose keys are the output tags, each holding the list of rendered lines."].join(`
|
|
1924
1924
|
`)}function wSn(e,t,r,n,o){const i=[`Spoken language: ${r?`${g5(r)} (${r})`:"not identified"}`,"Outputs:",...n.map(u=>`- ${u.tag}: ${g5(u.tag)}`)],s=(o??[]).filter(u=>u.text.trim());s.length&&i.push("","Earlier in the conversation (context only, do not render these):",...s.map((u,l)=>{const c=n.map(d=>u.outputs[d.tag]?` | ${d.tag}: ${u.outputs[d.tag]}`:"").join("");return`${l+1}. ${u.text}${c}`})),i.push("","Lines to render (as recognized):",...e.map((u,l)=>`${l+1}. ${u}`));const a=t?.some((u,l)=>u!==e[l]);return t&&a&&i.push("","Cleaned version of the same lines:",...t.map((u,l)=>`${l+1}. ${u}`)),i.join(`
|
|
1925
1925
|
`)}function bSn(e,t){const r=e.reduce((n,o)=>n+o.length,0);return Math.min(Khr,Math.ceil(120+t*(40+2.5*r)))}function TSn(e,t,r){let n=e;if(typeof n=="string")try{n=JSON.parse(n)}catch{n=void 0}const o=new Map,i=typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{};for(const s of t){const a=i[s],u=Array.isArray(a)?a.map(l=>typeof l=="string"?l.trim():""):typeof a=="string"&&r===1?[a.trim()]:void 0;o.set(s,u&&u.length===r?u:void 0)}return o}async function jhr(e,t,r,n,o,i){const s=e.source.slice(t.from,t.to),a=e.corrected?.slice(t.from,t.to),u=e.options?.glossary===!1?[]:[...new Set((e.dictionary??[]).map(g=>g.term.trim()).filter(Boolean))],l=r.map(g=>g.tag),c={};for(const g of l)c[g]=M.array(M.string());const d=e.options?.timeoutMs&&e.options.timeoutMs>0?e.options.timeoutMs:Whr,p=new Map;let m;try{m=await kt(n({system:vSn(u,s.length>1),user:wSn(s,a,o,r,i?void 0:e.previous)+(i?`
|
|
1926
1926
|
|
|
@@ -2007,7 +2007,7 @@ ${r}`:r}}return t?`${t}
|
|
|
2007
2007
|
|
|
2008
2008
|
${r}`:r}async retrieveKnowledgeGrounding(t){const r=this.knowledgeGroundingEngine;if(!r||!r.isEnabled()||t.useKnowledgeGrounding!==!0)return;const n=t.input?.text;if(n)try{const i=(t.conversationMessages!==void 0?t.conversationMessages:await this.fetchRecentRoutingHistory(t)).filter(s=>s.role==="user"||s.role==="assistant").slice(-EL).map(s=>({role:s.role==="assistant"?"assistant":"user",text:typeof s.content=="string"?s.content:""}));return await r.ground({query:n,recentTurns:i,scope:t.knowledgeContext})}catch(o){f.warn("[KnowledgeGrounding] grounding hook failed open",{error:String(o)});return}}async validateStreamRequestOptions(t,r){if(await this.validateStreamInput(t),t.inputValidation&&t.input?.text){const n=t.inputValidation;if(n.trimWhitespace&&(t.input.text=t.input.text.trim()),n.requireContent&&!t.input.text.trim())throw new Error("Input content is required but was empty or whitespace");if(n.minLength&&t.input.text.length<n.minLength)throw new Error(`Input text is too short (${t.input.text.length} < ${n.minLength})`);if(n.maxLength&&t.input.text.length>n.maxLength)throw new Error(`Input text is too long (${t.input.text.length} > ${n.maxLength})`)}if(t.piiDetection?.enabled&&t.input?.text){const n=await zpe(t.input.text,{enabled:!0,action:t.piiDetection.action??"warn",detectTypes:t.piiDetection.detectTypes,customPatterns:t.piiDetection.customPatterns,allowList:t.piiDetection.allowList,redactionText:t.piiDetection.redactionText});if(n.action==="abort")throw new Error(n.feedback??"Request blocked: PII detected in input");t.input.text=n.text}this.enforceSessionBudget(t.maxBudgetUsd),await this.applyAuthenticatedRequestContext(t),this.emitStreamStartEvents(t,r),this.applyMiddlewareDefaults(t),this.applyStreamLifecycleMiddleware(t)}async maybeHandleWorkflowStreamRequest(t){if(!t.options.workflow&&!t.options.workflowConfig)return null;const r=await this.streamWithWorkflow(t.options,t.startTime),n=r.stream,o=this;return r.stream=(async function*(){try{for await(const i of n)yield i;t.streamSpan.setStatus({code:qe.OK})}catch(i){throw t.streamSpan.setStatus({code:qe.ERROR,message:i instanceof Error?i.message:String(i)}),i}finally{o._disableToolCacheForCurrentRequest=!1,o._toolCacheKeysServedThisRequest=new Set,o._generationTurnActive=!1,t.streamSpan.setAttribute("response_time_ms",Date.now()-t.spanStartTime),t.streamSpan.end()}})(),r}async runStandardStreamRequest(t){const{options:r,streamSpan:n,spanStartTime:o,startTime:i,hrTimeStart:s,streamId:a,originalPrompt:u,ttsResolver:l,ttsMetadataSink:c}=t;f.debug("[NeuroLink] Running standard stream request",{streamId:a,provider:r.provider,model:r.model,inputLength:r.input?.text?.length||0,disableTools:r.disableTools,enableAnalytics:r.enableAnalytics,enableEvaluation:r.enableEvaluation,contextKeys:r.context?Object.keys(r.context):[],optionKeys:Object.keys(r),sessionId:r.context?.sessionId});try{const{enhancedOptions:d,factoryResult:p}=await this.prepareStreamOptions(r,a,i,s);f.debug("[NeuroLink] Stream options prepared",{streamId:a,options:d,factoryResult:p,sessionId:d.context?.sessionId});const m={providerEmitted:!1};d._streamDedupContext=m;const h=await this.createMCPStream(d),{stream:g}=h,y=h.provider??"unknown",v={},{stream:w,ttsMetadata:b}=await this.createIncrementalTTSStream({stream:g,ttsOptions:d.tts,providerName:y,fallbackProvider:d.provider,onComplete:$=>{v.result=$}});c?.(b);const E={finishReason:h.finishReason??"stop",toolCalls:void 0,toolResults:void 0},k=()=>E.toolCalls??h.toolCalls??[],A=()=>E.toolResults??h.toolResults??[];n.setAttribute(Ne.NL_PROVIDER,y||"unknown");const{eventSequence:x,cleanup:R}=this.setupStreamEventListeners(),C={fallbackAttempted:!1,guardrailsBlocked:!1,error:void 0,fallbackProvider:void 0,fallbackModel:void 0},P=Date.now(),D=d.context?.sessionId,L={enhancedOptions:d,originalPrompt:u,startTime:i,streamStartTime:P,sessionId:D,streamSpan:n,spanStartTime:o,ttsResolver:l,incrementalStream:w,streamTtsMetadata:b,tts:v,mcpStreamOutcome:h,providerName:y,dedupContext:m,streamState:E,currentToolCalls:k,currentToolResults:A,metadata:C,eventSequence:x,cleanupListeners:R},O=this.drainStandardStreamOnce(L),N=await this.processStreamResult(O,d,p);return E.finishReason=E.finishReason||N.finishReason,Object.defineProperty(N,"finishReason",{enumerable:!0,configurable:!0,get:()=>E.finishReason,set:$=>{E.finishReason=$}}),Object.defineProperty(N,"toolCalls",{enumerable:!0,configurable:!0,get:()=>k()}),Object.defineProperty(N,"toolResults",{enumerable:!0,configurable:!0,get:()=>A()}),N.usage||(N.usage=h.usage),N.analytics||(N.analytics=h.analytics),Promise.resolve(N.analytics).then($=>{$?.cost&&$.cost>0&&(this._sessionCostUsd+=$.cost)}).catch(()=>{}),this.emitStreamEndEvents(N),this.createStreamResponse(N,O,{providerName:y,options:r,startTime:i,responseTime:Date.now()-i,streamId:a,fallback:C.fallbackAttempted,guardrailsBlocked:C.guardrailsBlocked,error:C.error,events:x,sourceResult:h})}catch(d){if(l?.(void 0),r.disableInternalFallback)throw d;return this.handleStreamError(d,r,i,a,void 0,void 0)}}drainStandardStreamOnce(t){const r=this.drainStandardStream(t);let n=!1;const o={next:()=>(n=!0,r.next()),return:async i=>(n||(n=!0,await this.settleStandardStreamDrain(t,{accumulatedContent:"",chunkCount:0,streamError:void 0,resolvedUsage:void 0})),r.return(i)),throw:async i=>(n||(n=!0,await this.settleStandardStreamDrain(t,{accumulatedContent:"",chunkCount:0,streamError:i instanceof Error?i:new Error(String(i)),resolvedUsage:void 0})),r.throw(i)),[Symbol.asyncIterator]:()=>o};return o}async*drainStandardStream(t){const{enhancedOptions:r,originalPrompt:n,streamStartTime:o,sessionId:i,ttsResolver:s,incrementalStream:a,streamTtsMetadata:u,tts:l,mcpStreamOutcome:c,providerName:d,streamState:p,currentToolCalls:m,currentToolResults:h,metadata:g}=t;let y="",v=0,w,b,E=0;try{for await(const x of a){v++;const R=x!==null&&typeof x=="object"&&"metadata"in x&&x.metadata?.noOutput===!0,C=x&&"content"in x&&typeof x.content=="string"&&x.content.length>0,P=x!==null&&typeof x=="object"&&"type"in x&&(x.type==="audio"||x.type==="tts_audio"||x.type==="image");!R&&(C||P)&&E++,x&&"content"in x&&typeof x.content=="string"&&(y+=x.content,this.emitter.emit("response:chunk",x.content),this.emitter.emit("stream:chunk",{type:"stream:chunk",content:x.content,metadata:{chunkIndex:v,totalLength:y.length,...R&&{noOutput:!0}},timestamp:Date.now()})),yield x}const k=r.fallbackOnMaxSteps===!1&&c.metadata?.stopReason==="step-cap";if(E===0&&!k&&!g.fallbackAttempted&&!r.disableInternalFallback&&m().length===0&&h().length===0){const x=this.handleStreamFallback(g,p,n,r,d,C=>{y+=C}),{stream:R}=await this.createIncrementalTTSStream({stream:x,ttsOptions:r.tts,providerName:d,fallbackProvider:r.provider,ttsMetadata:u,onComplete:C=>{l.result=C}});yield*R}s?.(l.result);const A=c.metadata?.finishReason;if(!g.fallbackAttempted&&(A==="length"||A==="tool-calls"||A==="content-filter")&&(p.finishReason=A),b=c.usage,!b&&c.analytics)try{const x=await Promise.resolve(c.analytics);x?.tokenUsage&&(b=x.tokenUsage)}catch{}b&&(c.usage=b),this.emitter.emit("stream:complete",{type:"stream:complete",content:y,provider:g.fallbackProvider??d,model:g.fallbackModel??c.model??r.model,finishReason:p.finishReason??"stop",prompt:r.input?.text||r.prompt,metadata:{chunkCount:v,totalLength:y.length,durationMs:Date.now()-o,sessionId:i,usage:b,finishReason:p.finishReason??"stop",...g.fallbackAttempted&&{primaryProvider:d,primaryModel:r.model,fallback:!0}},timestamp:Date.now()})}catch(k){throw f.debug("[NeuroLink.stream] Stream error occurred",{error:k instanceof Error?k.message:String(k),name:k instanceof Error?k.name:"UnknownError",provider:d,model:r.model,chunkCount:v,totalLength:y.length,durationMs:Date.now()-o,sessionId:i}),w=k instanceof Error?k:new Error(String(k)),this.emitter.emit("stream:error",{type:"stream:error",content:k instanceof Error?k.message:String(k),provider:d,model:r.model,metadata:{chunkCount:v,totalLength:y.length,durationMs:Date.now()-o,errorName:k instanceof Error?k.name:"UnknownError",sessionId:i},timestamp:Date.now()}),k}finally{await this.settleStandardStreamDrain(t,{accumulatedContent:y,chunkCount:v,streamError:w,resolvedUsage:b})}}async settleStandardStreamDrain(t,r){const{enhancedOptions:n,originalPrompt:o,startTime:i,streamStartTime:s,streamSpan:a,spanStartTime:u,ttsResolver:l,mcpStreamOutcome:c,providerName:d,dedupContext:p,streamState:m,currentToolCalls:h,metadata:g,eventSequence:y,cleanupListeners:v}=t,{accumulatedContent:w,chunkCount:b,streamError:E,resolvedUsage:k}=r;if(l?.(void 0),f.debug("[NeuroLink.stream] Stream finished, performing cleanup",{provider:d,model:n.model,totalChunks:b,totalLength:w.length,durationMs:Date.now()-s,fallbackAttempted:g.fallbackAttempted,guardrailsBlocked:g.guardrailsBlocked,error:g.error}),!p.providerEmitted)try{const x=g.fallbackProvider??d??"unknown",R=g.fallbackModel??c.model??n.model??"unknown",C=E?"error":m.finishReason??"stop";this.emitter.emit("generation:end",{provider:x,model:R,responseTime:Date.now()-s,toolsUsed:h().map(P=>P.toolName),timestamp:Date.now(),result:{content:w,usage:k,model:R,provider:x,finishReason:C},prompt:n.input?.text||n.prompt,temperature:n.temperature,maxTokens:n.maxTokens,success:!E,error:E?.message,streamed:!0})}catch(x){f.debug("[NeuroLink.stream] generation:end listener threw \u2014 ignored",{error:x instanceof Error?x.message:String(x)})}this._disableToolCacheForCurrentRequest=!1,this._toolCacheKeysServedThisRequest=new Set,this._generationTurnActive=!1,v(),a.setAttribute("response_time_ms",Date.now()-u),a.setAttribute(Ne.NL_OUTPUT_LENGTH,w.length);const A=!!(g.error||E);a.setAttribute(Ne.GEN_AI_FINISH_REASON,A?"error":"stop"),g.fallbackAttempted&&(a.setAttribute("fallback_triggered",!0),g.fallbackProvider&&a.setAttribute("fallback_provider",g.fallbackProvider)),A?a.setStatus({code:qe.ERROR,message:g.error||E?.message}):a.setStatus({code:qe.OK}),a.end(),w.trim()&&f.info("[NeuroLink.stream] stream() - COMPLETE SUCCESS",{provider:d,model:n.model,responseTimeMs:Date.now()-i,contentLength:w.length,fallback:g.fallbackAttempted}),await this.storeStreamConversationMemory({enhancedOptions:n,providerName:d,originalPrompt:o,accumulatedContent:w,startTime:i,eventSequence:y,resultToolsUsed:(()=>{const x=c.toolsUsed;if(Array.isArray(x)&&x.length>0)return x;const R=h().map(C=>C.toolName);return R.length>0?R:void 0})()})}async createIncrementalTTSStream(t){const{stream:r,ttsOptions:n,providerName:o,fallbackProvider:i,onComplete:s}=t;if(!n?.enabled)return s(void 0),{stream:r};const{TTSProcessor:a}=await Promise.resolve().then(()=>(Nu(),ult)),u=i==="auto"?void 0:i,l=n.provider??u??o,c=l&&a.supports(l)?l:void 0,d=t.ttsMetadata??{attempted:c!==void 0,success:!1};d.attempted=c!==void 0,d.success=!1,delete d.error,delete d.latency;const p=Date.now();let m=!1;const h=(g,y)=>{m||(m=!0,d.success=y===void 0&&g!==void 0,y?d.error=y:delete d.error,d.latency=Date.now()-p,s(g))};return c?{stream:Slt({stream:r,provider:c,options:n,onComplete:h}),ttsMetadata:d}:(f.warn(`[NeuroLink.stream] No TTS provider resolved for incremental streaming (set tts.provider explicitly \u2014 chat provider "${l??"<unset>"}" is not a registered TTS handler)`),h(void 0),{stream:r,ttsMetadata:d})}deferProviderStreamTTS(t){return t.tts?.enabled?{...t,tts:void 0}:t}async prepareStreamOptions(t,r,n,o){if(await this.initializeConversationMemoryForGeneration(r,n,o),this.shouldReadMemory(t.memory,t.context?.userId)&&t.context?.userId)try{t.input.text=await this.retrieveMemory(t.input.text??"",t.context.userId,t.memory?.additionalUsers),f.debug("Memory retrieval successful")}catch(a){f.warn("Memory retrieval failed:",a)}if(await this.applySkillsAugmentation(t),this.enableOrchestration&&!t.provider&&!t.model)try{const a=await this.applyStreamOrchestration(t);f.debug("Stream orchestration applied",{originalProvider:t.provider||"auto",orchestratedProvider:a.provider,orchestratedModel:a.model,prompt:t.input.text?.substring(0,100)}),t={...t,...a},a.model&&(t.model=R1(t.model,this.modelAliasConfig))}catch(a){f.warn("Stream orchestration failed, continuing with original options",{error:a instanceof Error?a.message:String(a),originalProvider:t.provider||"auto"})}if(await this.autoDisableOllamaStreamTools(t),t.disableTools||await this.initializeMCP(),t.rag?.files?.length)try{const{prepareRAGTool:a}=await Promise.resolve().then(()=>(ume(),ame)),u=await a(t.rag,t.provider);t.tools||(t.tools={}),t.tools[u.toolName]=u.tool;const l=[`
|
|
2009
2009
|
|
|
2010
|
-
IMPORTANT: You have a tool called "${u.toolName}" that searches through`,`${u.filesLoaded} loaded document(s) containing ${u.chunksIndexed} indexed chunks.`,`ALWAYS use the "${u.toolName}" tool FIRST to answer the user's question before using any other tools.`,"This tool searches your local knowledge base of pre-loaded documents and is the primary source of truth.","Do NOT use websearchGrounding or any web search tools when the answer can be found in the loaded documents."].join(" ");t.systemPrompt=(t.systemPrompt||"")+l,f.info("[RAG] Tool injected into stream()",{toolName:u.toolName,filesLoaded:u.filesLoaded,chunksIndexed:u.chunksIndexed})}catch(a){f.warn("[RAG] Failed to prepare RAG tool, continuing without RAG",{error:a instanceof Error?a.message:String(a)})}const i=zyn(t),s=Gyn(t);if(t.input?.text){const{toolResults:a,enhancedPrompt:u}=await this.detectAndExecuteTools(t.input.text,void 0);u!==t.input.text&&(s.input.text=u)}return{enhancedOptions:s,factoryResult:i}}async autoDisableOllamaStreamTools(t){if((t.provider==="ollama"||t.provider?.toLowerCase().includes("ollama"))&&!t.disableTools){const{ModelConfigurationManager:r}=await Promise.resolve().then(()=>(TC(),GHt)),i=r.getInstance().getProviderConfiguration("ollama")?.modelBehavior?.toolCapableModels||[],s=t.model;i.length>0&&s&&(i.some(u=>s.toLowerCase().includes(u.toLowerCase()))||(t.disableTools=!0,f.debug("Auto-disabled tools for Ollama model that doesn't support them (stream)",{model:t.model,toolCapableModels:i.slice(0,3)})))}}setupStreamEventListeners(){const t=[];let r=0;const n=this.conversationEventContext.getStore(),o=new Set,i=g=>{if(!(!g||typeof g!="object"||!("payload"in g)||!g.payload||typeof g.payload!="object"||!("confirmationId"in g.payload)||typeof g.payload.confirmationId!="string"))return g.payload.confirmationId},s=(g,y,v)=>{const w=n!==void 0&&this.conversationEventContext.getStore()===n,b=v!==void 0&&o.has(v);!w&&!b||t.push({type:g,seq:r++,timestamp:Date.now(),...y&&typeof y=="object"?y:{data:y}})},a=(...g)=>{const y=g[0];s("response:chunk",{content:y})},u=(...g)=>{const y=g[0];s("tool:start",{...y,toolName:y.toolName??y.tool})},l=(...g)=>{const y=g[0],v=y.toolName??y.tool,w=y.responseTime??y.duration,b=y.success??(y.error!==void 0?!1:void 0),E={...y,toolName:v,...w!==void 0?{responseTime:w}:{},...b!==void 0?{success:b}:{},...y.error!==void 0?{error:y.error}:{}};s("tool:end",E),E.result&&E.result.uiComponent===!0&&s("ui-component",{toolName:v,componentData:E.result,timestamp:Date.now(),...b!==void 0?{success:b}:{},...w!==void 0?{responseTime:w}:{}})},c=(...g)=>{const y=g[0];y&&typeof y=="object"&&"type"in y&&typeof y.type=="string"&&"data"in y&&y.data&&typeof y.data=="object"&&!Array.isArray(y.data)&&s(y.type,{data:y.data})},d=(...g)=>{s("ui-component",g[0])},p=(...g)=>{if(n!==void 0&&this.conversationEventContext.getStore()===n){const y=i(g[0]);y!==void 0&&o.add(y),s("hitl:confirmation-request",g[0])}},m=(...g)=>{const y=i(g[0]);y!==void 0&&o.has(y)&&(s("hitl:confirmation-response",g[0],y),o.delete(y))};return this.emitter.on("response:chunk",a),this.emitter.on("tool:start",u),this.emitter.on("tool:end",l),this.emitter.on("ui-component",d),this.emitter.on("host:conversation-event",c),this.emitter.on("hitl:confirmation-request",p),this.emitter.on("hitl:confirmation-response",m),{eventSequence:t,cleanup:()=>{this.emitter.off("response:chunk",a),this.emitter.off("tool:start",u),this.emitter.off("tool:end",l),this.emitter.off("ui-component",d),this.emitter.off("host:conversation-event",c),this.emitter.off("hitl:confirmation-request",p),this.emitter.off("hitl:confirmation-response",m)}}}async*handleStreamFallback(t,r,n,o,i,s){t.fallbackAttempted=!0;const a="Stream completed with 0 chunks (possible guardrails block)";t.error=a;try{const h=this._metricsTraceContext;let g=Ce.createGenerationSpan({provider:i,model:o.model||"unknown",name:`gen_ai.${i}.stream.failed`,traceId:h?.traceId,parentSpanId:h?.parentSpanId});g=Ce.endSpan(g,2),g.statusMessage=a,g.durationMs=0,this.metricsAggregator.recordSpan(g),nt().recordSpan(g)}catch{}const u=o.fallbackProvider?.trim()||void 0,l=o.fallbackModel?.trim()||void 0,c=process.env.FALLBACK_PROVIDER?.trim()||void 0,d=process.env.FALLBACK_MODEL?.trim()||void 0,p=k$.getFallbackRoute(n||o.input.text||"",{provider:i,model:o.model||"gpt-4o",reasoning:"primary failed",confidence:.5},{fallbackStrategy:"auto"}),m={...p,provider:u??c??p.provider,model:l??d??p.model};f.warn("Retrying with fallback provider",{originalProvider:i,fallbackProvider:m.provider,fallbackModel:m.model,fallbackSource:u||l?"options":c||d?"env":"model_config",reason:a});try{const h=await ao.createProvider(m.provider,m.model,!0,void 0,void 0,this.resolveCredentials(o.credentials));h.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(x,R)=>this.executeTool(x,R,{disableToolCache:o.disableToolCache})},"NeuroLink.fallbackStream");const g=o.conversationMessages!==void 0?o.conversationMessages:await zh(this.conversationMemory,{prompt:o.input.text,context:o.context});h.setFileToolRootPolicy?.(this.fileToolRootsFor(o));const y=await h.stream({...this.deferProviderStreamTTS(o),model:m.model,conversationMessages:g}),v=y.toolCalls??[],w=y.toolResults??[];(v.length>0||w.length>0)&&(r.toolCalls=v,r.toolResults=w,r.finishReason=y.finishReason??r.finishReason);let b=0,E=0;for await(const x of y.stream){b++;const R=x!==null&&typeof x=="object"&&"metadata"in x&&x.metadata?.noOutput===!0,C=x&&"content"in x&&typeof x.content=="string"&&x.content.length>0,P=x!==null&&typeof x=="object"&&"type"in x&&(x.type==="audio"||x.type==="tts_audio"||x.type==="image");!R&&(C||P)&&E++,x&&"content"in x&&typeof x.content=="string"&&(s(x.content),this.emitter.emit("response:chunk",x.content)),yield x}const k=y.toolCalls??[],A=y.toolResults??[];if(E===0&&k.length===0&&A.length===0)throw new Error(`Fallback provider ${m.provider} also returned 0 real output chunks (chunkCount=${b}, sentinel-only or empty)`);r.toolCalls=k,r.toolResults=A,r.finishReason=y.finishReason??r.finishReason,t.fallbackProvider=m.provider,t.fallbackModel=m.model,t.guardrailsBlocked=!0}catch(h){const g=h instanceof Error?h.message:String(h);throw t.error=`${a}; Fallback failed: ${g}`,f.error("Fallback provider failed",{fallbackProvider:m.provider,error:g}),h}}async storeStreamConversationMemory(t){const{enhancedOptions:r,providerName:n,originalPrompt:o,accumulatedContent:i,startTime:s,eventSequence:a,resultToolsUsed:u}=t;f.shouldLog("debug")&&f.debug("[NeuroLink.stream] Preparing to store conversation turn in memory",{options:rD(nD(r)),sessionId:r.context?.sessionId});const l=a.some(c=>c.type==="tool:start"||c.type==="tool:end");if(!i.trim()&&!l){f.warn("[NeuroLink.stream] Skipping conversation turn storage \u2014 no text content or tool activity",{sessionId:r.context?.sessionId});return}if(f.shouldLog("debug")&&f.debug("[NeuroLink.stream] Storing conversation turn in memory",{options:rD(nD(r)),sessionId:r.context?.sessionId,conversationMemoryExists:!!this.conversationMemory}),this.conversationMemory&&r.context?.sessionId){const c=r.context?.sessionId,d=r.context?.userId;let p;r.model&&(p={provider:n,model:r.model});const m=Date.now();try{const h=this.drainPendingSkillMessages(c);await this.conversationMemory.storeConversationTurn({sessionId:c,userId:d,userMessage:o??"",aiResponse:i,startTimeStamp:new Date(s),providerDetails:p,enableSummarization:r.enableSummarization,events:a.length>0?a:void 0,requestId:r.context?.requestId,...h.length>0?{skillMessages:h}:{},...r.modality?{modality:r.modality}:{}}),this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,1),f.debug("[NeuroLink.stream] Stored conversation turn with events",{sessionId:c,eventCount:a.length,eventTypes:[...new Set(a.map(g=>g.type))]})}catch(h){this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,2,h instanceof Error?h.message:String(h)),f.warn("Failed to store stream conversation turn",{error:h instanceof Error?h.message:String(h)})}}if(this.shouldWriteMemory(r.memory,r.context?.userId,i)){const c=r.context?.sessionId,d=[...new Set(u??[])];this.storeMemoryInBackground({prompt:o??"",response:i.trim(),userId:r.context?.userId,...typeof c=="string"?{sessionId:c}:{},provider:n,model:r.model,...d.length>0?{toolsUsed:d}:{}},r.memory,r.context)}}async validateStreamInput(t){const r=process.hrtime.bigint();f.debug("[NeuroLink] \u{1F3AF} LOG_POINT_003_VALIDATION_START",{logPoint:"003_VALIDATION_START",validationStartTimeNs:r.toString(),message:"Starting comprehensive input validation process"});const n=typeof t?.input?.text=="string"&&t.input.text.trim().length>0,o=!!(t?.input?.audio&&t.input.audio.frames&&typeof t.input.audio.frames[Symbol.asyncIterator]=="function"),i=!!(t?.stt?.enabled&&t?.stt?.audio);if(!n&&!o&&!i)throw new Error("Stream options must include either input.text, input.audio, or stt.audio")}emitStreamStartEvents(t,r){this.emitter.emit("stream:start",{provider:t.provider||"auto",timestamp:r}),this.emitter.emit("response:start"),this.emitter.emit("message",`Starting ${t.provider||"auto"} stream...`)}async createMCPStream(t){const r=t.provider&&t.provider!=="auto"?t.provider:this.getOrchestratedPreferredProvider(t),n=await r_(r),o=await ao.createProvider(n,t.model,!t.disableTools,this,t.region,this.resolveCredentials(t.credentials));await o.ensureModelLimits?.(),o.setTraceContext(this._metricsTraceContext),o.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(g,y)=>this.executeTool(g,y,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream");let i=await this.getAllAvailableTools();i=this.applyToolInfoFiltering(i,t),Sr.getDescriptor(n)?.toolSupport==="none"&&(i=[]);const s=t.skipToolPromptInjection?t.systemPrompt||"":this.createToolAwareSystemPrompt(t.systemPrompt,i,o.supportsTools?.()??!0),a=t.conversationMessages!==void 0,u=a?t.conversationMessages:await zh(this.conversationMemory,{...t,prompt:t.input.text,context:t.context});t.conversationMessages=u;let l=u;const c=Ea({provider:n,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,toolReplayMode:this.resolveToolReplayModeForBudget(t),conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:i,compactionThreshold:t.compactionThreshold}),d=l?.length||0,p=this.getCompactionSessionId(t),m=d>0;if(!c.withinBudget&&!m){try{this.emitter.emit("compaction.insufficient",{stagesAttempted:["pre-dispatch hard cap"],finalTokens:c.estimatedInputTokens,budget:c.availableInputTokens,provider:n,model:t.model,phase:"pre-dispatch-no-recovery",timestamp:Date.now()})}catch{}throw new Qa(`Stream context exceeds model budget and no compaction is possible (no conversationMemory, no inline conversationMessages \u2014 only prompt + tools). Estimated: ${c.estimatedInputTokens} tokens, budget: ${c.availableInputTokens} tokens. Reduce prompt or tool-definition size, or trim the request.`,{estimatedTokens:c.estimatedInputTokens,availableTokens:c.availableInputTokens,stagesUsed:[],breakdown:c.breakdown})}if(c.shouldCompact&&(a||this.conversationMemory)&&d>(this.lastCompactionMessageCount.get(p)??0)){const y=await new aT({provider:n,summarizationProvider:this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:this.conversationMemoryConfig?.conversationMemory?.summarizationModel},this.contextCompactorDeps(this.decisionSiteContext(t,p))).compact(l,fL(c,t.compactionThreshold),this.conversationMemoryConfig?.conversationMemory,t.context?.requestId,{currentRequest:t.input.text});y.compacted&&(l=Hb(y.messages).messages,t.conversationMessages=l,this.lastCompactionMessageCount.set(p,l.length));const v=Ea({provider:n,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,toolReplayMode:this.resolveToolReplayModeForBudget(t),conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:i});if(!v.withinBudget){f.warn("[NeuroLink] Stream: post-compaction still over budget, emergency truncation",{estimatedTokens:v.estimatedInputTokens,availableTokens:v.availableInputTokens,overagePercent:Math.round((v.usageRatio-1)*100)});try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:v.estimatedInputTokens,budget:v.availableInputTokens,provider:n,model:t.model,phase:"mid-compaction",willEmergencyTruncate:!0,timestamp:Date.now()})}catch{}l=aie(l,v.availableInputTokens,v.breakdown,n),t.conversationMessages=l;const w=Ea({provider:n,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,toolReplayMode:this.resolveToolReplayModeForBudget(t),conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:i});if(!w.withinBudget){this.lastCompactionMessageCount.delete(p);try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:w.estimatedInputTokens,budget:w.availableInputTokens,provider:n,model:t.model,phase:"post-emergency-truncation",timestamp:Date.now()})}catch{}throw new Qa(`Stream context exceeds model budget after all compaction stages. Estimated: ${w.estimatedInputTokens} tokens, Budget: ${w.availableInputTokens} tokens.`,{estimatedTokens:w.estimatedInputTokens,availableTokens:w.availableInputTokens,stagesUsed:y.stagesUsed,breakdown:w.breakdown})}}}if(this.modelPool){const g=this.modelPool,y=g.maxAttempts,v=new Set;let w=null;for(let b=0;b<y;b++){if(t.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError");const E=g.selectNext(v);if(!E)break;v.add(g.memberKey(E));const k=E.provider,A=E.model??void 0,x=E.region??void 0;f.debug(`[createMCPStream] ModelPool: attempting member ${k}`,{model:A,attempt:b});try{const R=await ao.createProvider(k,A,!t.disableTools,this,x,this.resolveCredentials(t.credentials));R.setTraceContext(this._metricsTraceContext),R.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(L,O)=>this.executeTool(L,O,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream"),R.setFileToolRootPolicy?.(this.fileToolRootsFor(t));const C=await R.stream({...this.deferProviderStreamTTS(t),provider:k,model:A,region:x,systemPrompt:s,conversationMessages:l});f.debug("[createMCPStream] ModelPool stream handle obtained",{provider:k});const P=E,D=(async function*(){try{yield*C.stream,g.recordSuccess(P)}catch(L){throw g.recordFailure(P,n_(L)),L}})();return Zb(C,{...C,stream:D,provider:k,model:C.model||A,toolCalls:C.toolCalls??[],toolResults:C.toolResults??[]})}catch(R){if(cr(R))throw R;if($he(R)){const C=R instanceof Error?R.message:String(R);throw g.recordFailure(E,n_(R)),new Error(`[ModelPool] non-retryable: ${C}`,{cause:R})}g.recordFailure(E,n_(R)),w=R instanceof Error?R:new Error(String(R)),f.warn(`[createMCPStream] ModelPool: member ${k} failed`,{error:w.message})}}throw new Error(`[ModelPool] all stream members failed: ${w?.message??"no stream members available"}`)}o.setFileToolRootPolicy?.(this.fileToolRootsFor(t));const h=await o.stream({...this.deferProviderStreamTTS(t),systemPrompt:s,conversationMessages:l});return f.debug("[createMCPStream] Stream created successfully",{provider:n,systemPromptPassedLength:s.length}),Zb(h,{...h,provider:n,model:h.model||t.model,toolCalls:h.toolCalls??[],toolResults:h.toolResults??[]})}async processStreamResult(t,r,n){return{content:"",usage:void 0,finishReason:"stop",toolCalls:[],toolResults:[],analytics:void 0,evaluation:void 0}}emitStreamEndEvents(t){this.emitter.emit("stream:end",{responseTime:Date.now(),timestamp:Date.now()}),this.emitter.emit("response:end",t.content||"")}createStreamResponse(t,r,n){const o=n.sourceResult,i={streamId:n.streamId,startTime:n.startTime,responseTime:n.responseTime,fallback:n.fallback||!1,guardrailsBlocked:n.guardrailsBlocked,error:n.error},s={...o??{},stream:r,provider:o?.provider??n.providerName,model:o?.model??n.options.model,usage:t.usage,finishReason:t.finishReason,analytics:t.analytics,evaluation:t.evaluation,events:n.events&&n.events.length>0?n.events:void 0,metadata:o?void 0:Object.assign({},i)},a=Object.getOwnPropertyDescriptor(t,"toolCalls");a&&Object.defineProperty(s,"toolCalls",a);const u=Object.getOwnPropertyDescriptor(t,"toolResults");u&&Object.defineProperty(s,"toolResults",u);const l=Object.getOwnPropertyDescriptor(t,"finishReason");if(l&&Object.defineProperty(s,"finishReason",l),!o)return s;const c=new Set(["finishReason","stopReason","rawFinishReason","toolCalls","toolResults"]);for(const d of Object.getOwnPropertyNames(o)){const p=Object.getOwnPropertyDescriptor(o,d);!c.has(d)&&p&&typeof p.get=="function"&&Object.defineProperty(s,d,p)}return Object.defineProperty(s,"metadata",{enumerable:!0,configurable:!0,get:()=>(o.metadata===void 0&&(o.metadata={}),Object.assign(o.metadata,i)),set:d=>{o.metadata=d}}),s}async handleStreamError(t,r,n,o,i,s){if(t instanceof Qa)throw t;f.error("Stream generation failed, attempting fallback",{error:t instanceof Error?t.message:String(t)});try{this.emitter.emit("stream:error",{content:t instanceof Error?t.message:String(t),metadata:{errorName:t instanceof Error?t.name:"UnknownError",durationMs:Date.now()-n,chunkCount:0},provider:r.provider||"unknown",model:r.model||"unknown"})}catch{}const a=r.input.text,u=Date.now()-n,l=await r_(r.provider),c=await ao.createProvider(l,r.model,!0,void 0,void 0,this.resolveCredentials(r.credentials));c.setFileToolRootPolicy?.(this.fileToolRootsFor(r));const d=await c.stream({input:{text:r.input.text},model:r.model,temperature:r.temperature,maxTokens:r.maxTokens,conversationMessages:r.conversationMessages});let p="";return{stream:(async function*(h){try{for await(const g of d.stream)g&&"content"in g&&typeof g.content=="string"&&(p+=g.content,h.emitter.emit("response:chunk",g.content)),yield g}finally{if(p.trim()){f.info("[NeuroLink.handleStreamError] stream() - COMPLETE SUCCESS (fallback)",{provider:l,model:r.model,responseTimeMs:Date.now()-n,contentLength:p.length});try{const g=r.model||"unknown",y=Date.now()-n;h.emitter.emit("stream:complete",{content:p,provider:l,model:g,finishReason:"stop",metadata:{durationMs:y,chunkCount:0,totalLength:p.length,isFallback:!0,finishReason:"stop"}}),h.emitter.emit("generation:end",{provider:l,model:g,responseTime:y,timestamp:Date.now(),result:{content:p,usage:{input:0,output:0,total:0},model:g,provider:l,finishReason:"stop"},success:!0,streamed:!0})}catch{}}if(h.conversationMemory&&i?.context?.sessionId&&p.trim()){const g=i?.context?.sessionId,y=i?.context?.userId;let v;r.model&&(v={provider:l,model:r.model});const w=Date.now();try{const b=g||r.context?.sessionId,E=h.drainPendingSkillMessages(b);await h.conversationMemory.storeConversationTurn({sessionId:b,userId:y||r.context?.userId,userMessage:a??"",aiResponse:p,startTimeStamp:new Date(n),providerDetails:v,enableSummarization:i?.enableSummarization,requestId:i?.context?.requestId||r.context?.requestId,...E.length>0?{skillMessages:E}:{}}),h.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-w,1)}catch(b){h.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-w,2,b instanceof Error?b.message:String(b)),f.warn("Failed to store fallback stream conversation turn",{error:b instanceof Error?b.message:String(b)})}}}})(this),provider:l,model:r.model,usage:d.usage,finishReason:d.finishReason||"stop",toolCalls:d.toolCalls||[],toolResults:d.toolResults||[],analytics:d.analytics,evaluation:d.evaluation,metadata:{streamId:o,startTime:n,responseTime:u,fallback:!0}}}getEventEmitter(){return this.emitter}hasPendingHITLConfirmation(t){return this.hitlManager?.hasPendingConfirmation(t)??!1}getToolDedupConfig(){return this.toolDedupConfig}fileToolRootsFor(t){return WX(t)??this.resolveFileToolRoots(t.toolRoots)}workerToolsConfig(t){const r=this.toolsConfig?.fileRoots;if(t?.fileRoots===void 0)return r===void 0?t:{...t,fileRoots:r};const n=lO({perCall:t.fileRoots,instance:r}).roots;return{...t,fileRoots:n?[...n]:[]}}resolveFileToolRoots(t){return lO({perCall:t,instance:this.toolsConfig?.fileRoots})}getToolsConfig(){return this.toolsConfig}getDiscoveryPins(t){const r=this.discoveryPins.get(t);return r?(this.discoveryPins.delete(t),this.discoveryPins.set(t,r),r):new Set}pinDiscoveredTools(t,r){let n=this.discoveryPins.get(t);n?this.discoveryPins.delete(t):n=new Set,this.discoveryPins.set(t,n);for(const o of r)n.add(o);if(this.discoveryPins.size>1e3){const o=this.discoveryPins.keys().next().value;o!==void 0&&this.discoveryPins.delete(o)}}async checkCredentials(t){const{provider:r,model:n}=t,o="ping";try{return await this.generate({provider:r,...n&&{model:n},input:{text:o},maxTokens:16,disableTools:!0}),{provider:r,status:"ok",detail:"credentials valid"}}catch(i){const s=i instanceof Error?i.message:String(i),a=s.toLowerCase();return i instanceof ww?{provider:r,status:"denied",detail:s}:a.includes("authentication")||a.includes("401")||a.includes("invalid api key")||a.includes("incorrect api key")||a.includes("api_key_invalid")||a.includes("token has expired")||a.includes("expired credentials")?{provider:r,status:"expired",detail:s}:a.includes("not configured")||a.includes("missing api")||a.includes("api key is required")||a.includes("no api key")||a.includes("application default credentials")||a.includes("google_application_credentials")||a.includes("project_id")||a.includes("default credentials")||a.includes("service account")?{provider:r,status:"missing",detail:s}:a.includes("econnrefused")||a.includes("enotfound")||a.includes("could not resolve")||a.includes("timeout")||a.includes("network")||a.includes("cannot connect")?{provider:r,status:"network",detail:s}:{provider:r,status:"unknown",detail:s}}}emitToolStart(t,r,n=Date.now()){const o=eWt(t,n),i={executionId:o,tool:t,startTime:n,metadata:{inputType:typeof r,hasInput:r!=null}};return this.activeToolExecutions.set(o,i),this.currentStreamToolExecutions.push(i),this.emitter.emit("tool:start",_C(t,{input:r,timestamp:n,executionId:o})),f.debug(`tool:start emitted for ${t}`,{toolName:t,executionId:o,timestamp:n,inputProvided:r!==void 0}),o}emitToolEnd(t,r,n,o,i=Date.now(),s){const a=o||i-1e3,u=i-a,l=!n;let c;s?c=this.activeToolExecutions.get(s):c=Array.from(this.activeToolExecutions.values()).find(m=>m.tool===t&&!m.endTime);const d=s||c?.executionId||`${t}-${a}-fallback-${Math.random().toString(36).substr(2,9)}`;c&&(c.endTime=i,c.result=r,c.error=n,this.activeToolExecutions.delete(c.executionId));const p={tool:t,startTime:a,endTime:i,duration:u,success:l,result:r,error:n,executionId:d,metadata:{toolCategory:"custom"}};this.toolExecutionHistory.push(p),this.emitter.emit("tool:end",_C(t,{result:r,error:n,success:l,responseTime:u,timestamp:i,duration:u,executionId:d})),f.debug(`tool:end emitted for ${t}`,{toolName:t,executionId:d,duration:u,success:l,hasResult:r!==void 0,hasError:!!n})}getCurrentToolExecutions(){return[...this.currentStreamToolExecutions]}getToolExecutionHistory(){return[...this.toolExecutionHistory]}clearCurrentStreamExecutions(){this.currentStreamToolExecutions=[]}registerTool(t,r,n){this.invalidateToolCache(),this.emitter.emit("tools-register:start",{toolName:t,timestamp:Date.now()});try{if(!t||typeof t!="string")throw new Error("Invalid tool name");if(!r||typeof r!="object")throw new Error(`Invalid tool object provided for tool: ${t}`);if(typeof r.execute!="function")throw new Error(`Tool '${t}' must have an execute method.`);if(t.trim()==="")throw new Error("Tool name cannot be empty");if(t.length>100)throw new Error("Tool name is too long (maximum 100 characters)");if(/[\x00-\x1F\x7F]/.test(t))throw new Error("Tool name contains invalid control characters");const o={name:r.name||t,description:r.description||t,execute:r.execute,inputSchema:"parameters"in r&&r.parameters&&(KQ(r.parameters)||typeof r.parameters=="object")?r.parameters:r.inputSchema||{}};if(n?.timeout!==void 0&&n.timeout>0&&Number.isFinite(n.timeout)&&typeof o.execute=="function"){const s=o.execute,a=n.timeout,u=t;o.execute=async(...l)=>{const c=AbortSignal.timeout(a),d=l[1],p=d?.abortSignal,m=p?AbortSignal.any([p,c]):c,h={...d,abortSignal:m};return Promise.race([s(l[0],h),new Promise((g,y)=>{m.addEventListener("abort",()=>{c.aborted?y(ve.toolTimeout(u,a)):y(new DOMException("The operation was aborted","AbortError"))},{once:!0})})])}}const i=Ahn(t,o,n?.timeout,n?.maxRetries,n?.totalTimeoutMs);this.toolRegistry.registerServer(i),n?.cacheable===!1?this.uncacheableTools.add(t):this.uncacheableTools.delete(t),this.emitter.emit("tools-register:end",{toolName:t,success:!0,timestamp:Date.now(),timeoutMs:n?.timeout})}catch(o){throw f.error(`Failed to register tool ${t}:`,o),o}}setToolContext(t){this.toolExecutionContext={...t},f.debug("Tool execution context updated",{sessionId:t.sessionId,contextKeys:Object.keys(t),hasJuspayToken:!!t.juspayToken,hasShopId:!!t.shopId})}getToolContext(){return this.toolExecutionContext?{...this.toolExecutionContext}:void 0}clearToolContext(){this.toolExecutionContext=void 0,f.debug("Tool execution context cleared")}registerTools(t){if(Array.isArray(t))for(const{name:r,tool:n}of t)this.registerTool(r,n);else for(const[r,n]of Object.entries(t))this.registerTool(r,n)}unregisterTool(t){this.invalidateToolCache();const r=`custom-tool-${t}`,n=this.toolRegistry.unregisterServer(r);return n&&(this.uncacheableTools.delete(t),f.info(`Unregistered custom tool: ${t}`)),n}useToolMiddleware(t){return this.mcpToolMiddlewares.push(t),f.debug(`[NeuroLink] Registered tool middleware (total: ${this.mcpToolMiddlewares.length})`),this}getToolMiddlewares(){return[...this.mcpToolMiddlewares]}async flushToolBatch(){this.mcpToolBatcher&&await this.mcpToolBatcher.flush()}getMCPEnhancementsConfig(){return this.mcpEnhancementsConfig}async updateAgenticLoopReport(t,r,n){if(!this.conversationMemory)throw new Eu("Conversation memory is not initialized. Enable conversationMemory in NeuroLink options.","CONFIG_ERROR");if(!("updateAgenticLoopReport"in this.conversationMemory)||typeof this.conversationMemory.updateAgenticLoopReport!="function")throw new Eu("updateAgenticLoopReport is only supported with Redis conversation memory.","CONFIG_ERROR");await Ge(this.conversationMemory.updateAgenticLoopReport(t,n,r),5e3)}getCustomTools(){const t=this.toolRegistry.getToolsByCategory(Sa({isCustomTool:!0})),r=new Map;for(const o of t){const i=o.inputSchema||o.parameters;f.debug("Processing tool schema for Claude",{toolName:o.name,hasDescription:!!o.description,description:o.description,hasParameters:!!o.parameters,parametersType:typeof o.parameters,parametersKeys:o.parameters&&typeof o.parameters=="object"?Object.keys(o.parameters):"NOT_OBJECT",hasInputSchema:!!o.inputSchema,inputSchemaType:typeof o.inputSchema,inputSchemaKeys:o.inputSchema&&typeof o.inputSchema=="object"?Object.keys(o.inputSchema):"NOT_OBJECT",hasEffectiveSchema:!!i,effectiveSchemaType:typeof i,effectiveSchemaHasProperties:!!i?.properties,effectiveSchemaHasRequired:!!i?.required,originalInputSchema:o.inputSchema,phase:"AFTER_SCHEMA_FIX",timestamp:Date.now()}),r.set(o.name,{name:o.name,description:o.description||"",inputSchema:typeof o.inputSchema=="object"&&o.inputSchema!==null?o.inputSchema:typeof o.parameters=="object"&&o.parameters!==null?o.parameters:{},execute:async(s,a)=>{const u=this.toolExecutionContext||{},l=a&&ar(a)?a:{},c={...u,...l,sessionId:l.sessionId||u.sessionId||`fallback-${Date.now()}`};return f.debug("Tool execution context merged",{toolName:o.name,storedContextKeys:Object.keys(u),runtimeContextKeys:Object.keys(l),finalContextKeys:Object.keys(c),hasJuspayToken:!!c.juspayToken,hasShopId:!!c.shopId,sessionId:c.sessionId}),await this.toolRegistry.executeTool(o.name,s,c)}})}this.cachedFileTools||(this.cachedFileTools=yXt(this.fileRegistry));const n=this.cachedFileTools;for(const[o,i]of Object.entries(n))if(!r.has(o)){const s=i,a=s.inputSchema??s.parameters;r.set(o,{name:o,description:i.description||`File tool: ${o}`,inputSchema:typeof a=="object"&&a!==null?a:{type:"object",properties:{}},execute:async u=>await i.execute(u,{toolCallId:`file-tool-${Date.now()}`,messages:[]})})}return r}async addInMemoryMCPServer(t,r){this.invalidateToolCache();try{le.debug(`[NeuroLink] Registering in-memory MCP server: ${t}`),r.tools||(r.tools=[]),await this.toolRegistry.registerServer(r),le.info(`[NeuroLink] Successfully registered in-memory server: ${t}`,{category:r.metadata?.category,provider:r.metadata?.provider,version:r.metadata?.version})}catch(n){throw le.error(`[NeuroLink] Failed to register in-memory server ${t}:`,n),n}}getInMemoryServers(){const t=this.getInMemoryServerInfos(),r=new Map;for(const n of t)r.set(n.id,n);return r}getInMemoryServerInfos(){return this.toolRegistry.getBuiltInServerInfos().filter(r=>Sa({existingCategory:r.metadata?.category,serverId:r.id})==="in-memory")}getAutoDiscoveredServerInfos(){return this.autoDiscoveredServerInfos}async executeTool(t,r={},n){if(this.mcpToolBatcher&&!n?.bypassBatcher)return this.mcpToolBatcher.execute(t,r);const o=this.createToolExecutionContext(t,r,n);return Be.mcp.startActiveSpan(t,{attributes:{"tool.name":t,"tool.type":o.toolType,"tool.input_size":o.inputSize}},i=>(no(i,"tool",{input:r}),this.executeToolWithSpan(t,r,n,o,i)))}createToolExecutionContext(t,r,n){const o=this.externalServerManager.getAllTools().find(l=>l.name===t),i=o?"mcp":this.getCustomTools().has(t)?"custom":"external",s=r?Aw(r):"",a=Date.now(),u=`${t}-${a}-${Math.random().toString(36).slice(2,11)}`;return{functionTag:"NeuroLink.executeTool",executionStartTime:a,executionId:u,externalTool:o,toolType:i,inputSize:s.length,options:n,hitlState:{triggered:!1}}}async executeToolWithSpan(t,r,n,o,i){try{const s=await this.prepareToolExecutionState(t,r,n,o),a=await this.runPreparedToolExecution(t,r,s,o,i),u=ar(a)&&"isError"in a&&a.isError===!0;return no(i,"tool",{output:a,...u&&{level:"ERROR",statusMessage:C6(a)}}),a}catch(s){const a=s instanceof Error?s.message:String(s);throw no(i,"tool",{level:"ERROR",statusMessage:a}),s instanceof Me||(i.recordException(s instanceof Error?s:new Error(a)),i.setStatus({code:qe.ERROR,message:a})),s}finally{i.end()}}async prepareToolExecutionState(t,r,n,o){f.debug(`[${o.functionTag}] Tool execution requested:`,{toolName:t,params:ar(r)?cct(r):r,hasExternalManager:!!this.externalServerManager}),f.debug("Tool execution detailed analysis",{toolName:t,executionStartTime:o.executionStartTime,paramsAnalysis:{type:typeof r,isNull:r===null,isUndefined:r===void 0,isEmpty:r&&typeof r=="object"&&Object.keys(r).length===0,keys:r&&typeof r=="object"?Object.keys(r):"NOT_OBJECT",keysLength:r&&typeof r=="object"?Object.keys(r).length:0},isTargetTool:t==="juspay-analytics_SuccessRateSRByTime",options:n,hasExternalManager:!!this.externalServerManager}),this.emitter.emit("tool:start",_C(t,{timestamp:o.executionStartTime,input:r,executionId:o.executionId}));const i=this.toolRegistry.getToolInfo(t),s=n?.timeout??i?.tool?.timeoutMs??dl.EXECUTION_BATCH_MS,a=n?.maxRetries??i?.tool?.maxRetries??Ci.DEFAULT,u=n?.retryDelayMs||lo.BASE_MS,l={timeout:s,maxRetries:a,totalTimeout:n?.totalTimeoutMs??i?.tool?.totalTimeoutMs??s*(a+1)+u*a,retryDelayMs:u,authContext:n?.authContext,disableToolCache:n?.disableToolCache},{MemoryManager:c}=await Promise.resolve().then(()=>(yI(),s_)),d=c.getMemoryUsageMB(),m=`${o.externalTool?.serverId||i?.tool?.serverId||"unknown"}.${t}`;let h=this.toolCircuitBreakers.get(m);h||(h=new Z2(N2.FAILURE_THRESHOLD,vV),this.toolCircuitBreakers.set(m,h));let g=this.toolExecutionMetrics.get(t);return g||(g={totalExecutions:0,successfulExecutions:0,failedExecutions:0,averageExecutionTime:0,lastExecutionTime:0,errorCategories:{}},this.toolExecutionMetrics.set(t,g)),g.totalExecutions++,{finalOptions:l,startMemory:d,circuitBreaker:h,breakerKey:m,metrics:g}}async runPreparedToolExecution(t,r,n,o,i){let s=0;try{le.debug(`[${o.functionTag}] Executing tool: ${t}`,{toolName:t,params:r,options:n.finalOptions,circuitBreakerState:n.circuitBreaker.getState()});const a=n.finalOptions.maxRetries+1,u=n.finalOptions.totalTimeout,l=Date.now(),c=l+u;let d=0;const p=await n.circuitBreaker.execute(async()=>u4e(async()=>{d++;const m=c-Date.now();if(m<=0)throw ve.toolTimeout(t,u,void 0,{attempt:d,maxAttempts:a,attemptTimeoutMs:n.finalOptions.timeout,totalTimeoutMs:u,elapsedMs:Date.now()-l,exhausted:!0});const h=Math.min(n.finalOptions.timeout,m);return Ge(this.executeToolInternal(t,r,n.finalOptions,o.hitlState),h,ve.toolTimeout(t,h,void 0,{attempt:d,maxAttempts:a,attemptTimeoutMs:n.finalOptions.timeout,totalTimeoutMs:u,elapsedMs:Date.now()-l}))},{maxAttempts:a,delayMs:n.finalOptions.retryDelayMs,isRetriable:m=>Date.now()+n.finalOptions.retryDelayMs<c&&UV(m),onRetry:(m,h)=>{s=m,le.warn(`[${o.functionTag}] Retrying tool execution (attempt ${m})`,{toolName:t,error:h.message,attempt:m})}}));return i.setAttribute("tool.retry_count",s),await this.handleSuccessfulToolExecution(t,p,n,o,i)}catch(a){return i.setAttribute("tool.retry_count",s),this.handleFailedToolExecution(t,r,a,n,o,i)}}async handleSuccessfulToolExecution(t,r,n,o,i){const s=Date.now()-o.executionStartTime;n.metrics.successfulExecutions++,n.metrics.lastExecutionTime=s,n.metrics.averageExecutionTime=(n.metrics.averageExecutionTime*(n.metrics.successfulExecutions-1)+s)/n.metrics.successfulExecutions;const{MemoryManager:a}=await Promise.resolve().then(()=>(yI(),s_)),l=a.getMemoryUsageMB().heapUsed-n.startMemory.heapUsed;l>20&&le.warn(`Tool '${t}' used excessive memory: ${l}MB`,{toolName:t,memoryDelta:l,executionTime:s}),le.debug(`[${o.functionTag}] Tool executed successfully`,{toolName:t,executionTime:s,memoryDelta:l,circuitBreakerState:n.circuitBreaker.getState()});const c=r&&typeof r=="object"?r:void 0,d=c&&"isError"in c&&c.isError===!0||c&&"success"in c&&c.success===!1,p=d?c?.content:void 0,m=d?p?.filter(h=>h.type==="text"&&h.text).map(h=>h.text).join(" ")||(typeof c?.error=="string"?c.error:"Unknown error"):void 0;if(d){try{await n.circuitBreaker.execute(async()=>{throw new Error(`Tool ${t} returned isError:true`)})}catch{}le.debug(`[${o.functionTag}] Circuit breaker failure recorded for isError result`,{toolName:t,circuitBreakerState:n.circuitBreaker.getState(),circuitBreakerFailures:n.circuitBreaker.getFailureCount()});const h=$kn(m??"Unknown error"),g=`[TOOL_ERROR: ${t} failed (${h})] `;if(c&&Array.isArray(p)){const w=p.map(b=>({...b}));for(const b of w)if(b.type==="text"&&b.text){b.text=g+b.text;break}c.content=w}i.setAttribute("tool.error.message",(m??"Unknown error").substring(0,500)),i.setAttribute("tool.error.category",h),i.setStatus({code:qe.ERROR,message:`MCP tool returned isError: ${(m??"Unknown error").substring(0,200)}`}),n.metrics.failedExecutions++;const y=n.metrics.successfulExecutions;n.metrics.successfulExecutions=Math.max(0,n.metrics.successfulExecutions-1),n.metrics.averageExecutionTime=y>1?(n.metrics.averageExecutionTime*y-s)/(y-1):0;const v=Fkn(h);n.metrics.errorCategories[v]=(n.metrics.errorCategories[v]||0)+1}return this.emitToolEndEvent(t,o.executionStartTime,!d,r,d&&m?new Error(m):void 0,o.executionId),i.setAttribute("tool.result.status",d?"error":"success"),i.setAttribute("tool.duration_ms",s),r}async handleFailedToolExecution(t,r,n,o,i,s){o.metrics.failedExecutions++;const a=Date.now()-i.executionStartTime;if(n instanceof Km)return le.warn(`[${i.functionTag}] Tool blocked by circuit breaker: ${t}`,{toolName:t,breakerState:n.breakerState,retryAfter:n.retryAfter,retryAfterMs:n.retryAfterMs,failureCount:n.failureCount,executionTime:a}),o.metrics.errorCategories.execution=(o.metrics.errorCategories.execution||0)+1,this.emitToolEndEvent(t,i.executionStartTime,!1,void 0,new Error(`Circuit breaker open for ${t} (state=${n.breakerState}, failures=${n.failureCount})`),i.executionId),s.setAttribute("tool.result.status","circuit_breaker_open"),s.setAttribute("tool.duration_ms",a),s.setAttribute("tool.circuit_breaker.state",n.breakerState),s.setAttribute("tool.circuit_breaker.retry_after_ms",n.retryAfterMs),s.setAttribute("tool.circuit_breaker.failure_count",n.failureCount),s.setStatus({code:qe.ERROR,message:`Circuit breaker open for ${t}: ${n.message}`}),{isError:!0,content:[{type:"text",text:`TOOL TEMPORARILY UNAVAILABLE: "${t}" has been disabled after ${n.failureCount} failures. This is a circuit breaker protection \u2014 do NOT retry this tool. It will become available again after ${Math.ceil(n.retryAfterMs/1e3)} seconds (at ${n.retryAfter}). Instead, inform the user that the operation failed and suggest trying again later.`}]};let u;if(n instanceof Me)u=n;else if(n instanceof Error)if(n.message.includes("timeout"))u=ve.toolTimeout(t,o.finalOptions.timeout);else if(n.message.includes("not found")){const c=await this.getAllAvailableTools();u=ve.toolNotFound(t,lnn(c.map(d=>({name:d.name}))))}else n.message.includes("validation")||n.message.includes("parameter")?u=ve.invalidParameters(t,n,r):n.message.includes("network")||n.message.includes("connection")?u=ve.networkError(t,n):u=ve.toolExecutionFailed(t,n);else u=ve.toolExecutionFailed(t,new Error(String(n)));const l=u.category||"execution";throw o.metrics.errorCategories[l]=(o.metrics.errorCategories[l]||0)+1,this.emitToolEndEvent(t,i.executionStartTime,!1,void 0,u,i.executionId),this.emitter.listenerCount("error")>0&&this.emitter.emit("error",u),u=new Me({...u,context:{...u.context,executionTime:a,params:r,options:o.finalOptions,circuitBreakerState:o.circuitBreaker.getState(),circuitBreakerFailures:o.circuitBreaker.getFailureCount(),metrics:{...o.metrics}}}),l4e(u),s.setAttribute("tool.result.status","error"),s.setAttribute("tool.duration_ms",a),s.recordException(u),s.setStatus({code:qe.ERROR,message:u.message}),u}toolCacheRepeatKey(t,r){try{return`${t}:${JSON.stringify(r)??""}`}catch{return}}async executeToolInternal(t,r,n,o){const i="NeuroLink.executeToolInternal",s=this.getToolAnnotationsForExecution(t),a=this.mcpToolResultCache&&!n.disableToolCache&&!this._disableToolCacheForCurrentRequest&&!this.uncacheableTools.has(t)&&!s?.destructiveHint,u=this.mcpToolResultCache,l=n.authContext||this.toolExecutionContext?{__args:r,__ctx:n.authContext??this.toolExecutionContext}:r,c=this._generationTurnActive?this.toolCacheRepeatKey(t,l):void 0,d=c!==void 0&&this._toolCacheKeysServedThisRequest.has(c);if(c!==void 0&&this._toolCacheKeysServedThisRequest.add(c),a&&u&&!d){const h=u.getCachedResult(t,l);if(h!==void 0)return f.debug(`[${i}] Cache HIT for tool: ${t}`),h}else d&&f.debug(`[${i}] Repeat call within this request \u2014 bypassing tool cache for: ${t}`);const p=async h=>{if(this.mcpToolMiddlewares.length===0)return h();let g=0;const y=async()=>{if(g<this.mcpToolMiddlewares.length){const v=this.mcpToolMiddlewares[g++];return v({name:t,description:"",inputSchema:{},annotations:s,execute:async()=>({})},r,{toolMeta:{name:t,annotations:s}},y)}return h()};return await y()},m=async()=>{const h=this.externalServerManager.getAllTools(),g=h.filter(v=>v.name===t&&v.isAvailable);let y;if(g.length>1&&this.mcpToolRouter)try{const v={name:t,description:g[0].description??"",serverId:g[0].serverId,inputSchema:{}},w=this.mcpToolRouter.route(v);y=g.find(b=>b.serverId===w.serverId)||g[0],f.debug(`[${i}] Router selected server: ${w.serverId}`,{strategy:w.strategy,confidence:w.confidence})}catch(v){f.warn(`[${i}] Router failed, falling back to first match`,{error:v}),y=g[0]}else y=g[0];if(f.debug(`[${i}] External MCP tool search:`,{toolName:t,externalToolsCount:h.length,foundTool:!!y,isAvailable:y?.isAvailable,serverId:y?.serverId}),y&&y.isAvailable)try{le.debug(`[${i}] Executing external MCP tool: ${t} from ${y.serverId}`);const v=await this.externalServerManager.executeTool(y.serverId,t,r,{timeout:n.timeout});return f.debug(`[${i}] External MCP tool execution successful:`,{toolName:t,serverId:y.serverId,resultType:typeof v}),v}catch(v){throw f.error(`[${i}] External MCP tool execution failed:`,{toolName:t,serverId:y.serverId,error:v instanceof Error?v.message:String(v)}),ve.toolExecutionFailed(t,v instanceof Error?v:new Error(String(v)),y.serverId)}try{const v=this.toolExecutionContext||{},w=n.authContext||{},b=gA({...v,...w,hitlState:o},this.resolveFileToolRoots(void 0));f.debug("[Using merged context for unified registry tool:",{toolName:t,storedContextKeys:Object.keys(v),finalContextKeys:Object.keys(b)});const E=await this.toolRegistry.executeTool(t,r,b);if(E&&typeof E=="object"&&"success"in E&&E.success===!1){const k=E.error||"Tool execution failed",A=new Error(k);this.emitter.listenerCount("error")>0&&this.emitter.emit("error",A)}return E}catch(v){const w=v instanceof Error?v:new Error(String(v));if(this.emitter.listenerCount("error")>0&&this.emitter.emit("error",w),v instanceof Error&&v.message.includes("not found")){const b=await this.getAllAvailableTools();throw ve.toolNotFound(t,b.map(E=>E.name))}throw ve.toolExecutionFailed(t,v instanceof Error?v:new Error(String(v)))}};try{const h=await p(m);return a&&u&&h!==void 0&&(u.cacheResult(t,l,h),f.debug(`[${i}] Cached result for tool: ${t}`)),h}catch(h){const g=s?{name:t,description:"",annotations:s,execute:async()=>({})}:void 0;if(g&&tse(g)&&h instanceof Error&&UV(h)){f.debug(`[${i}] Tool ${t} is safe to retry, attempting once more`);try{const y=await p(m);return a&&u&&y!==void 0&&u.cacheResult(t,l,y),y}catch{}}throw h}}getToolAnnotationsForExecution(t){if(this.toolCache?.tools){const r=this.toolCache.tools.find(n=>n.name===t);if(r?.annotations)return r.annotations}if(this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)return Vp({name:t,description:""})}invalidateToolCache(){this.toolCache=null,f.debug("Tool cache invalidated")}async getAllAvailableTools(){if(this.toolCache&&Date.now()-this.toolCache.timestamp<this.toolCacheDuration)return f.debug("Returning available tools from cache"),this.toolCache.tools;const t=`get-all-tools-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,r=Date.now(),n=process.hrtime.bigint();f.debug("[NeuroLink] \u{1F6E0}\uFE0F LOG_POINT_A001_GET_ALL_TOOLS_START",{logPoint:"A001_GET_ALL_TOOLS_START",getAllToolsId:t,timestamp:new Date().toISOString(),getAllToolsStartTime:r,getAllToolsHrTimeStart:n.toString(),toolRegistryState:{hasToolRegistry:!!this.toolRegistry,toolRegistrySize:0,toolRegistryType:this.toolRegistry?.constructor?.name||"NOT_SET",hasExternalServerManager:!!this.externalServerManager,externalServerManagerType:this.externalServerManager?.constructor?.name||"NOT_SET"},mcpState:{mcpInitialized:this.mcpInitialized,hasProviderRegistry:!!ao,providerRegistrySize:0},message:"Starting comprehensive tool discovery across all sources"});const{MemoryManager:o}=await Promise.resolve().then(()=>(yI(),s_)),i=o.getMemoryUsageMB();try{const s=new Map,a=await this.toolRegistry.listTools();for(const g of a)if(!s.has(g.name)){const y=_N(g,{serverId:g.serverId==="direct"?"neurolink-direct":g.serverId});s.set(g.name,y)}const u=this.toolRegistry.getToolsByCategory(Sa({isCustomTool:!0}));for(const g of u)if(!s.has(g.name)){const y=_N(g,{description:"Custom tool",serverId:`custom-tool-${g.name}`,category:Sa({isCustomTool:!0,serverId:g.serverId}),inputSchema:{}});s.set(g.name,y)}const l=this.toolRegistry.getToolsByCategory("in-memory");for(const g of l)if(!s.has(g.name)){const y=_N(g,{description:"In-memory MCP tool",serverId:"unknown",category:"in-memory",inputSchema:{}});s.set(g.name,y)}const c=this.externalServerManager.getAllTools();for(const g of c)if(!s.has(g.name)){const y=_N(g,{category:Sa({existingCategory:typeof g.metadata?.category=="string"?g.metadata.category:void 0,isExternal:!0,serverId:g.serverId}),inputSchema:{}});s.set(g.name,y)}const d=Array.from(s.values());le.debug("Tool discovery results",{mcpTools:a.length,customTools:u.length,inMemoryTools:l.length,externalMCPTools:c.length,total:d.length});const m=o.getMemoryUsageMB().heapUsed-i.heapUsed;if(m>Xm.LOW_USAGE_MB&&(le.debug(`\u{1F50D} Tool listing used ${m}MB memory (large tool registry detected)`),d.length>xRe.LARGE_TOOL_COLLECTION&&le.debug("\u{1F4A1} Tool collection optimized for large sets. Memory usage reduced through efficient object reuse.")),this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)for(const g of d)g.annotations||(g.annotations=Vp({name:g.name,description:g.description||""}));const h=d.sort((g,y)=>g.name<y.name?-1:g.name>y.name?1:0);return this.toolCache={tools:h,timestamp:Date.now()},h}catch(s){return le.error("Failed to list available tools",{error:s}),[]}}async getProviderStatus(t){const{MemoryManager:r}=await Promise.resolve().then(()=>(yI(),s_)),n=r.getMemoryUsageMB();t?.quiet||le.debug("\u{1F50D} DEBUG: Initializing MCP for provider status..."),await this.initializeMCP(),t?.quiet||le.debug("\u{1F50D} DEBUG: MCP initialized:",this.mcpInitialized);const{AIProviderFactory:o}=await Promise.resolve().then(()=>(lu(),fR)),{hasProviderEnvVars:i}=await Promise.resolve().then(()=>(lf(),hI)),s=Sr.getAllDescriptors().map(p=>p.name),a=y0(ja.DEFAULT_CONCURRENCY_LIMIT),u=s.map(p=>a(async()=>{const m=Date.now();try{if(!await this.hasProviderEnvVars(p)&&p!=="ollama")return{provider:p,status:"not-configured",configured:!1,authenticated:!1,error:"Missing required environment variables",responseTime:Date.now()-m};if(p==="bedrock"||p==="sagemaker")return{provider:p,status:"not-configured",configured:!0,authenticated:!1,error:`Live status check is skipped for ${p}`,responseTime:Date.now()-m};if(p==="ollama"){let E,k="not-run";try{const A=CC(),x=IC(A);if(x.kind==="suppressed")throw new Error(x.reason);E=x,k="transport-failure";const R=await fetch(A.url,{method:"GET",signal:AbortSignal.timeout(pl.AUTH_MS)});if(!R.ok)throw new Error("Ollama service not responding");k="protocol-failure";const C=await R.json(),P=C?.models;if(!Array.isArray(P))throw f.warn("Ollama API returned invalid models format in testProvider",{responseData:C,modelsType:typeof P}),new Error("Invalid models format from Ollama API");k="success";const D=P.filter(L=>L&&typeof L=="object"&&typeof L.name=="string");return D.length>0?{provider:p,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-m,model:D[0].name}:{provider:p,status:"failed",configured:!0,authenticated:!1,error:"Ollama service running but no models installed",responseTime:Date.now()-m}}catch(A){return{provider:p,status:"failed",configured:!1,authenticated:!1,error:A instanceof Error?rT(A):"Ollama service not running",responseTime:Date.now()-m}}finally{E&&nT(E,k)}}const g=5e3,y=new AbortController,v=this.testProviderConnection(p,y.signal);let w;const b=new Promise((E,k)=>{w=setTimeout(()=>{k(new Error("Provider test timeout (5s)"))},g)});try{await Promise.race([v,b])}finally{clearTimeout(w),v.catch(()=>{}),y.abort()}return{provider:p,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-m}}catch(h){const g=h instanceof Error?h.message:String(h);return{provider:p,status:"failed",configured:!0,authenticated:!1,error:g,responseTime:Date.now()-m}}})),l=await Promise.all(u),d=r.getMemoryUsageMB().heapUsed-n.heapUsed;return!t?.quiet&&d>20&&le.debug(`\u{1F50D} Memory usage: +${d}MB (consider cleanup for large operations)`),d>50&&r.forceGC(),l}async testProvider(t){try{return await this.testProviderConnection(t),!0}catch{return!1}}async testProviderConnection(t,r){const{AIProviderFactory:n}=await Promise.resolve().then(()=>(lu(),fR));await(await n.createProvider(t,null)).generate({prompt:"test",maxTokens:1,disableTools:!0,abortSignal:r})}async getBestProvider(t){const{getBestProvider:r}=await Promise.resolve().then(()=>(lf(),hI));return r(t)}async getAvailableProviders(){const{getAvailableProviders:t}=await Promise.resolve().then(()=>(lf(),hI));return t()}async isValidProvider(t){const{isValidProvider:r}=await Promise.resolve().then(()=>(lf(),hI));return r(t)}async getMCPStatus(){try{await this.initializeMCP();const t=await this.toolRegistry.listTools(),r=this.externalServerManager.getStatistics(),n=this.externalServerManager.listServers(),o=this.getInMemoryServerInfos(),i=this.toolRegistry.getBuiltInServerInfos(),s=this.getAutoDiscoveredServerInfos(),a=n.length+o.length+i.length+s.length,u=r.connectedServers+o.length+i.length,l=t.length+r.totalTools;return{mcpInitialized:this.mcpInitialized,totalServers:a,availableServers:u,autoDiscoveredCount:s.length,totalTools:l,autoDiscoveredServers:s,customToolsCount:this.toolRegistry.getToolsByCategory(Sa({isCustomTool:!0})).length,inMemoryServersCount:o.length,externalMCPServersCount:n.length,externalMCPConnectedCount:r.connectedServers,externalMCPFailedCount:r.failedServers,externalMCPServers:n}}catch(t){return{mcpInitialized:!1,totalServers:0,availableServers:0,autoDiscoveredCount:0,totalTools:0,autoDiscoveredServers:[],customToolsCount:this.toolRegistry.getToolsByCategory(Sa({isCustomTool:!0})).length,inMemoryServersCount:0,externalMCPServersCount:0,externalMCPConnectedCount:0,externalMCPFailedCount:0,externalMCPServers:[],error:t instanceof Error?t.message:String(t)}}}async listMCPServers(){return[...this.externalServerManager.listServers(),...this.getInMemoryServerInfos(),...this.toolRegistry.getBuiltInServerInfos(),...this.getAutoDiscoveredServerInfos()]}async testMCPServer(t){try{if(t==="neurolink-direct")return(await this.toolRegistry.listTools()).length>0;const r=this.getInMemoryServers();if(r.has(t)){const o=r.get(t);return!!(o?.tools&&o.tools.length>0)}const n=this.externalServerManager.getServer(t);return n?n.status==="connected"&&n.client!==null:!1}catch(r){return le.error(`[NeuroLink] Error testing MCP server ${t}:`,r),!1}}async hasProviderEnvVars(t){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(Py(),e_));try{const n=await r.checkProviderHealth(t,{includeConnectivityTest:!1,cacheResults:!1});return n.isConfigured&&n.hasApiKey}catch(n){return f.warn(`Provider env var check failed for ${t}`,{error:n instanceof Error?n.message:String(n)}),!1}}async checkProviderHealth(t,r={}){const{ProviderHealthChecker:n}=await Promise.resolve().then(()=>(Py(),e_)),o=await n.checkProviderHealth(t,r);return{provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}}async checkAllProvidersHealth(t={}){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(Py(),e_));return(await r.checkAllProvidersHealth(t)).map(o=>({provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}))}async getProviderHealthSummary(){const{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(Py(),e_)),r=await t.checkAllProvidersHealth({cacheResults:!0,includeConnectivityTest:!1}),n=t.getHealthSummary(r),o=[];return n.healthy===0?o.push("No providers are healthy. Check your environment configuration."):n.healthy<2&&o.push("Consider configuring additional providers for better reliability."),n.hasIssues>0&&o.push("Some providers have configuration issues. Run checkAllProvidersHealth() for details."),{...n,recommendations:o}}async clearProviderHealthCache(t){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(Py(),e_));r.clearHealthCache(t)}getToolExecutionMetrics(){const t={};for(const[r,n]of this.toolExecutionMetrics.entries())t[r]={...n,errorCategories:{...n.errorCategories},successRate:n.totalExecutions>0?n.successfulExecutions/n.totalExecutions:0};return t}setModelAliasConfig(t){this.modelAliasConfig=t,f.info(`[ModelAlias] Configured ${Object.keys(t.aliases).length} model aliases`)}getToolCircuitBreakerStatus(){const t={};for(const[r,n]of this.toolCircuitBreakers.entries())t[r]={state:n.getState(),failureCount:n.getFailureCount(),isHealthy:n.getState()==="closed"};return t}resetToolCircuitBreaker(t){this.toolCircuitBreakers.has(t)&&(this.toolCircuitBreakers.set(t,new Z2(N2.FAILURE_THRESHOLD,vV)),le.info(`Circuit breaker reset for tool: ${t}`))}clearToolExecutionMetrics(){this.toolExecutionMetrics.clear(),le.info("All tool execution metrics cleared")}async getToolHealthReport(){const t={};let r=0;const n=await this.toolRegistry.listTools(),o=new Set(n.map(s=>s.name)),i=new Map;for(const s of n)i.has(s.name)||i.set(s.name,s.serverId||"unknown");for(const s of o){const a=this.toolExecutionMetrics.get(s),u=`${i.get(s)||"unknown"}.${s}`,l=this.toolCircuitBreakers.get(u),c=a&&a.totalExecutions>0?a.successfulExecutions/a.totalExecutions:0,d=(!l||l.getState()==="closed")&&c>=.8;d&&r++;const p=[],m=[];if(l&&l.getState()==="open"&&(p.push("Circuit breaker is open due to repeated failures"),m.push("Check tool implementation and fix underlying issues")),c<.8&&a&&a.totalExecutions>0&&(p.push(`Low success rate: ${(c*100).toFixed(1)}%`),m.push("Review error logs and improve tool reliability")),a&&a.averageExecutionTime>1e4&&(p.push("High average execution time"),m.push("Optimize tool performance or increase timeout")),a&&a.errorCategories){const h=a.errorCategories;h.timeout>0&&(p.push(`Timeout errors: ${h.timeout}`),m.push("Consider increasing the tool timeout configuration")),h.validation>0&&(p.push(`Validation errors: ${h.validation}`),m.push("Review input schemas and parameter validation")),h.network>0&&(p.push(`Network errors: ${h.network}`),m.push("Check network connectivity and endpoint availability"))}t[s]={name:s,isHealthy:d,metrics:{totalExecutions:a?.totalExecutions||0,successRate:c,averageExecutionTime:a?.averageExecutionTime||0,lastExecutionTime:a?.lastExecutionTime||0,errorCategories:a?.errorCategories?{...a.errorCategories}:{}},circuitBreaker:{state:l?.getState()||"closed",failureCount:l?.getFailureCount()||0},issues:p,recommendations:m}}return{totalTools:o.size,healthyTools:r,unhealthyTools:o.size-r,tools:t}}async ensureConversationMemoryInitialized(){try{const t=`manual-init-${Date.now()}`;return await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!!this.conversationMemory}catch(t){return f.error("Failed to initialize conversation memory",{error:t instanceof Error?t.message:String(t)}),!1}}async getConversationStats(){const t=`stats-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:He.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return await this.conversationMemory.getStats()}async getConversationHistory(t){const r=`history-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:He.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Me({code:He.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});try{const n=await this.conversationMemory.buildContextMessages(t);return f.debug("Retrieved conversation history",{sessionId:t,messageCount:n.length,turnCount:n.length/2}),n}catch(n){return f.error("Failed to retrieve conversation history",{sessionId:t,error:n instanceof Error?n.message:String(n)}),[]}}async clearConversationSession(t){const r=`clear-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:He.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return this.lastCompactionMessageCount.delete(t),await this.conversationMemory.clearSession(t)}async clearAllConversations(){const t=`clear-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:He.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});this.lastCompactionMessageCount.clear(),await this.conversationMemory.clearAllSessions()}async listSessions(t){const r=`list-sessions-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");if(!this.conversationMemory.listSessions)return f.warn("listSessions not available on current memory manager"),[];const n=3e4;try{const o=await Ge(this.conversationMemory.listSessions(t),n,new Error("listSessions operation timed out after 30s"));return f.debug("Listed conversation sessions",{userId:t,sessionCount:o.length}),o}catch(o){return f.error("Failed to list conversation sessions",{userId:t,error:o instanceof Error?o.message:String(o)}),[]}}async exportSession(t,r={}){const n=`export-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");if(!t||typeof t!="string")throw new Error("Session ID must be a non-empty string");const o=3e4;try{const i=await Ge(this.conversationMemory.buildContextMessages(t),o,new Error("buildContextMessages operation timed out after 30s"));if(i.length===0)return f.debug("No messages found for session export",{sessionId:t}),null;const s=this.conversationMemory.getSession(t),a=await Ge(s instanceof Promise?s:Promise.resolve(s),o,new Error("getSession operation timed out after 30s")),u=new Date().toISOString(),l={sessionId:t,title:t,userId:a?.userId,createdAt:a?.createdAt?new Date(a.createdAt).toISOString():u,updatedAt:a?.lastActivity?new Date(a.lastActivity).toISOString():u,messages:i};return r.includeMetadata&&(l.exportMetadata={exportedAt:u,exportFormat:r.format||"json"}),f.debug("Exported conversation session",{sessionId:t,messageCount:i.length}),l}catch(i){return f.error("Failed to export conversation session",{sessionId:t,error:i instanceof Error?i.message:String(i)}),null}}async exportAllSessions(t,r={}){const n=`export-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");const o=3e4,i=6e4;try{const s=await Ge(this.listSessions(t),o,new Error("listSessions operation timed out after 30s")),a=[];for(const u of s){const l=await Ge(this.exportSession(u.id,r),i,new Error(`exportSession operation timed out after 60s for session ${u.id}`));l&&a.push(l)}return f.debug("Exported all conversation sessions",{userId:t,sessionCount:a.length}),a}catch(s){return f.error("Failed to export all conversation sessions",{userId:t,error:s instanceof Error?s.message:String(s)}),[]}}async storeToolExecutions(t,r,n,o,i){const s=n&&n.length>0||o&&o.length>0;if(!s){f.debug("Tool execution storage skipped",{hasToolData:s,toolCallsCount:n?.length||0,toolResultsCount:o?.length||0});return}const a=this.conversationMemory;if(!a?.storeToolExecution){f.debug("Tool execution storage not supported by this memory backend");return}try{await a.storeToolExecution(t,r,n,o,i)}catch(u){f.warn("Failed to store tool executions",{sessionId:t,userId:r,error:u instanceof Error?u.message:String(u)})}}isToolExecutionStorageAvailable(){return typeof this.conversationMemory?.storeToolExecution=="function"}async getSessionMessages(t,r){const n=`get-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:He.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Me({code:He.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});return await this.conversationMemory.getSessionMessages(t,r)}async recordConversationTurn(t){const{sessionId:r,userId:n,turnId:o}=t;qf.assertConversationIdentity(r,n);const i={sessionId:r,userId:n,...o?{turnId:o}:{}};if(!t.userMessage.trim())return{recorded:!1,reason:"empty-user-message",...i};const s=(t.events??[]).some(u=>u.type==="tool:start"||u.type==="tool:end");if(!t.aiResponse.trim()&&!s)return{recorded:!1,reason:"empty-response",...i};if(await this.initializeConversationMemoryForGeneration(t.requestId??`record-turn-${Date.now()}`,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:He.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(await this.isOwnedByAnotherUser(r,n))throw new Me({code:He.INVALID_PARAMETERS,message:"The conversation belongs to another user",category:"validation",severity:"medium",retriable:!1});const a=Date.now();try{await this.conversationMemory.storeConversationTurn({sessionId:r,userId:n,userMessage:t.userMessage,aiResponse:t.aiResponse,startTimeStamp:t.startTime,...t.provider&&t.model?{providerDetails:{provider:t.provider,model:t.model}}:{},enableSummarization:t.enableSummarization,events:t.events?.length?t.events:void 0,requestId:t.requestId,...t.modality?{modality:t.modality}:{},...o?{turnId:o}:{},...t.interrupted?{interrupted:!0}:{},...t.callEnded?{callEnded:!0}:{}}),this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"record"},Date.now()-a,1)}catch(u){throw this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"record"},Date.now()-a,2,u instanceof Error?u.message:String(u)),u}return this.shouldWriteMemory(t.memory,n,t.aiResponse)&&this.storeMemoryInBackground({prompt:t.userMessage,response:t.aiResponse.trim(),userId:n,sessionId:r,provider:t.provider??"",model:t.model},t.memory,{sessionId:r}),{recorded:!0,...i}}async getConversationSeed(t){const{sessionId:r,userId:n}=t,o=Math.max(0,Math.floor(t.maxTurns??10)),i=Math.max(0,Math.floor(t.maxChars??6e3));try{qf.assertConversationIdentity(r,n);const s=await this.getSessionMessages(r,n),a=[];for(const d of s)d.role!=="user"&&d.role!=="assistant"||d.metadata?.isSummary||d.metadata?.isSkill||typeof d.content!="string"||!d.content.trim()||a.push({role:d.role,content:d.content,...d.metadata?.modality?{modality:d.metadata.modality}:{}});const u=a.slice(-(o*2));let l=0,c=u.length;for(let d=u.length-1;d>=0&&(l+=u[d].content.length,!(l>i));d-=1)c=d;return u.slice(c)}catch(s){return f.warn("[NeuroLink] getConversationSeed failed, starting unseeded",{error:s instanceof Error?s.message:String(s)}),[]}}async conversationExists(t){return qf.assertConversationIdentity(t.sessionId,t.userId),(await this.getSessionMessages(t.sessionId,t.userId)).length===0?!1:!await this.isOwnedByAnotherUser(t.sessionId,t.userId)}async isOwnedByAnotherUser(t,r){const n=this.conversationMemory;if(!n||n.isRedisConfigured)return!1;const o=await n.getSession(t);return o!==void 0&&o.userId!==r}static assertConversationIdentity(t,r){const n=typeof t!="string"||!t.trim()?"sessionId must be a non-empty string":t.includes(":")?'sessionId must not contain ":"':typeof r!="string"||!r.trim()?"userId must be a non-empty string":void 0;if(n)throw new Me({code:He.INVALID_PARAMETERS,message:n,category:"validation",severity:"medium",retriable:!1})}async setSessionMessages(t,r,n){const o=`set-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(o,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:He.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Me({code:He.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});await this.conversationMemory.setSessionMessages(t,r,n)}async modifyLastAssistantMessage(t,r,n){const o=await this.getSessionMessages(t,n);for(let i=o.length-1;i>=0;i--)if(o[i].role==="assistant")return o[i]={...o[i],content:r(o[i].content)},await this.setSessionMessages(t,o,n),!0;return!1}async addExternalMCPServer(t,r){this.invalidateToolCache();try{le.info(`[NeuroLink] Adding external MCP server: ${t}`,{command:r.command,transport:r.transport});const n=await this.externalServerManager.addServer(t,r);if(n.success){if(le.info(`[NeuroLink] External MCP server added successfully: ${t}`,{toolsDiscovered:n.metadata?.toolsDiscovered||0,duration:n.duration}),this.mcpEnhancementsConfig?.router?.enabled!==!1){const o=this.externalServerManager.listServers();if(o.length>=2&&!this.mcpToolRouter){this.mcpToolRouter=new W6({strategy:this.mcpEnhancementsConfig?.router?.strategy??"least-loaded",enableAffinity:this.mcpEnhancementsConfig?.router?.enableAffinity??!1});for(const i of o)this.mcpToolRouter.registerServer(i.id||t);f.debug("[NeuroLink] ToolRouter auto-initialized (2+ external servers)")}else this.mcpToolRouter&&this.mcpToolRouter.registerServer(t)}this.emitter.emit("externalMCP:serverAdded",{serverId:t,serverName:r.name||t,config:r,toolCount:n.metadata?.toolsDiscovered||0,timestamp:Date.now()})}else le.error(`[NeuroLink] Failed to add external MCP server: ${t}`,{error:n.error,transport:r.transport,command:r.command,url:r.url?ui(r.url):void 0});return n}catch(n){throw le.error(`[NeuroLink] Error adding external MCP server: ${t}`,n),n}}async removeExternalMCPServer(t){this.invalidateToolCache();try{le.info(`[NeuroLink] Removing external MCP server: ${t}`);const r=this.externalServerManager.getServerName(t),n=await this.externalServerManager.removeServer(t);return n.success?(le.info(`[NeuroLink] External MCP server removed successfully: ${t}`),this.emitter.emit("externalMCP:serverRemoved",{serverId:t,serverName:r,timestamp:Date.now()})):n.error?.includes("not found")?le.debug(`[NeuroLink] Remove skipped \u2014 external MCP server not registered: ${t}`):le.error(`[NeuroLink] Failed to remove external MCP server: ${t}`,{error:n.error}),n}catch(r){throw le.error(`[NeuroLink] Error removing external MCP server: ${t}`,r),r}}getExternalMCPServerHealth(){return this.externalServerManager.getServerStatuses()}listExternalMCPServers(){const t=this.externalServerManager.getServerStatuses(),r=this.externalServerManager.listServers();return t.map(n=>{const o=r.find(i=>i.id===n.serverId);return{serverId:n.serverId,status:n.status,toolCount:n.toolCount,uptime:n.performance.uptime,isHealthy:n.isHealthy,config:o||{}}})}getExternalMCPServer(t){return this.externalServerManager.getServer(t)}async executeExternalMCPTool(t,r,n,o){let i=r;try{i=this.resolveDirectMcpToolName(t,r),le.debug(`[NeuroLink] Executing external MCP tool: ${i} on ${t}`);const s=this.getToolAnnotationsForExecution(i),a=!!this.mcpToolResultCache&&!this._disableToolCacheForCurrentRequest&&!s?.destructiveHint,u={__serverId:t,__args:n,...this.toolExecutionContext?{__ctx:this.toolExecutionContext}:{}},l=this._generationTurnActive?this.toolCacheRepeatKey(i,u):void 0,c=l!==void 0&&this._toolCacheKeysServedThisRequest.has(l);if(l!==void 0&&this._toolCacheKeysServedThisRequest.add(l),a&&this.mcpToolResultCache&&!c){const h=this.mcpToolResultCache.getCachedResult(i,u);if(h!==void 0)return le.debug(`[NeuroLink] Tool result cache HIT: ${i} on ${t}`),h}const d=await this.externalServerManager.executeTool(t,i,n,o),p=d&&typeof d=="object"?d:void 0,m=!!(p&&"isError"in p&&p.isError===!0||p&&"success"in p&&p.success===!1);return a&&this.mcpToolResultCache&&!m&&d!==void 0&&this.mcpToolResultCache.cacheResult(i,u,d),le.debug(`[NeuroLink] External MCP tool ${m?"returned error":"executed successfully"}: ${i}`),d}catch(s){throw le.error(`[NeuroLink] External MCP tool execution failed: ${i}`,s),s}}resolveDirectMcpToolName(t,r){const n=this.getExternalMCPServer(t);if(!n||n.status!=="connected"||!n.client)return r;const o=this.getExternalMCPServerTools(t).map(s=>s.name);if(o.includes(r))return r;const i=zoe(r,o);if(!i)throw new qoe(r,t,VWt(r,o));return Be.mcp.startActiveSpan("mcp.toolNameRepair",{attributes:{"mcp.server_id":t,"mcp.tool_name.requested":r,"mcp.tool_name.resolved":i.name,"mcp.tool_name.repair_strategy":i.strategy,...i.score!==void 0?{"mcp.tool_name.repair_score":i.score}:{}}},s=>s.end()),le.info(`[NeuroLink] Repaired external MCP tool name at direct execution boundary: "${r}" \u2192 "${i.name}" (${i.strategy}) on server '${t}'`),i.name}getExternalMCPTools(){return this.externalServerManager.getAllTools()}getExternalMCPServerTools(t){return this.externalServerManager.getServerTools(t)}async testExternalMCPConnection(t){try{const{MCPClientFactory:r}=await Ge(Promise.resolve().then(()=>(Sae(),Per)),1e4),n=await r.testConnection(t,1e4);return{success:n.success,error:n.error,toolCount:n.capabilities?1:0}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r)}}}getExternalMCPStatistics(){return this.externalServerManager.getStatistics()}async shutdownExternalMCPServers(){try{le.info("[NeuroLink] Shutting down all external MCP servers..."),this.unregisterAllExternalMCPToolsFromRegistry(),await this.externalServerManager.shutdown(),le.info("[NeuroLink] All external MCP servers shut down successfully")}catch(t){throw le.error("[NeuroLink] Error shutting down external MCP servers:",t),t}}async getElicitationManager(){return(await Ge(Promise.resolve().then(()=>(Xmr(),Jmr)),1e4)).globalElicitationManager}async registerElicitationHandler(t){(await this.getElicitationManager()).registerHandler(t)}async getMultiServerManager(){return(await Ge(Promise.resolve().then(()=>(nse(),DXt)),1e4)).globalMultiServerManager}async getEnhancedToolDiscovery(){const t=await Ge(Promise.resolve().then(()=>(ose(),OXt)),1e4);return new t.EnhancedToolDiscovery(this.toolRegistry)}async getMCPRegistryClient(){return(await Ge(Promise.resolve().then(()=>(mhr(),ahr)),1e4)).globalMCPRegistryClient}async exposeAgentAsTool(t,r){return(await Ge(Promise.resolve().then(()=>($me(),Nme)),1e4)).exposeAgentAsTool(t,r)}async exposeWorkflowAsTool(t,r){return(await Ge(Promise.resolve().then(()=>($me(),Nme)),1e4)).exposeWorkflowAsTool(t,r)}async getToolIntegrationManager(){return(await Ge(Promise.resolve().then(()=>(bhr(),ghr)),1e4)).globalToolIntegrationManager}async convertToolsToMCPFormat(t,r={}){const n=await Ge(Promise.resolve().then(()=>(m5(),qme)),1e4),o=t.map(i=>({...i,execute:i.execute??(async()=>({success:!1,error:"No execute function provided"}))}));return n.batchConvertToMCP(o,r)}async convertToolsFromMCPFormat(t,r={}){return(await Ge(Promise.resolve().then(()=>(m5(),qme)),1e4)).batchConvertToNeuroLink(t,r)}async getToolAnnotations(t){const{inferAnnotations:r,mergeAnnotations:n,getAnnotationSummary:o}=await Ge(Promise.resolve().then(()=>($C(),AXt)),1e4),i=this.toolRegistry.getToolInfo(t);if(!i)return null;const s=i.tool.annotations,a=r({name:i.tool.name,description:i.tool.description??""}),u=n(a,s);return{annotations:u,summary:o(u)}}convertExternalMCPToolsToAISDKFormat(){const t=this.externalServerManager.getAllTools(),r={};for(const n of t)if(n.isAvailable){const o={description:n.description,execute:async i=>{try{le.debug(`[NeuroLink] Executing external MCP tool via AI SDK: ${n.name}`,{params:i});const s=await this.externalServerManager.executeTool(n.serverId,n.name,i,{timeout:3e4});return le.debug(`[NeuroLink] External MCP tool execution result: ${n.name}`,{success:!!s,hasData:!!(s&&typeof s=="object"&&"content"in s)}),s}catch(s){throw le.error(`[NeuroLink] External MCP tool execution failed: ${n.name}`,s),s}}};r[n.name]=o,le.debug(`[NeuroLink] Converted external MCP tool to AI SDK format: ${n.name} from server ${n.serverId}`)}return le.info(`[NeuroLink] Converted ${Object.keys(r).length} external MCP tools to AI SDK format`),r}convertJSONSchemaToAISDKFormat(t){}unregisterExternalMCPToolsFromRegistry(t){try{const r=this.externalServerManager.getServerTools(t);for(const n of r)this.toolRegistry.removeTool(n.name),le.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${n.name}`)}catch(r){le.error(`[NeuroLink] Failed to unregister external MCP tools from registry for server ${t}:`,r)}}unregisterExternalMCPToolFromRegistry(t){try{this.toolRegistry.removeTool(t),le.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${t}`)}catch(r){le.error(`[NeuroLink] Failed to unregister external MCP tool ${t} from registry:`,r)}}async lazyInitializeConversationMemory(t,r,n){try{const{initializeConversationMemory:o}=await uSn().then(()=>Ihr),i=await o(this.conversationMemoryConfig);this.conversationMemory=i,this.conversationMemoryNeedsInit=!1}catch(o){throw f.error("[NeuroLink] \u274C LOG_POINT_G005_MEMORY_LAZY_INIT_ERROR",{logPoint:"G005_MEMORY_LAZY_INIT_ERROR",generateInternalId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-r,elapsedNs:(process.hrtime.bigint()-n).toString(),error:o instanceof Error?o.message:String(o),errorName:o instanceof Error?o.name:"UnknownError",errorStack:o instanceof Error?o.stack:void 0,message:"Lazy conversation memory initialization failed"}),o}}unregisterAllExternalMCPToolsFromRegistry(){try{const t=this.externalServerManager.getAllTools();for(const r of t)this.toolRegistry.removeTool(r.name);le.debug(`[NeuroLink] Unregistered ${t.length} external MCP tools from main registry`)}catch(t){le.error("[NeuroLink] Failed to unregister all external MCP tools from registry:",t)}}async createEvaluationPipeline(t){const{EvaluationPipeline:r,getPreset:n}=await Ge(Promise.resolve().then(()=>(ax(),sx)),1e4,ve.evaluationTimeout("evaluation module load",1e4));let o;typeof t=="string"?o=n(t):o=t;const i=new r(o);return await Ge(i.initialize(),3e4,ve.evaluationTimeout("pipeline initialization",3e4)),f.debug(`[NeuroLink] Created evaluation pipeline: ${o.name??"custom"}`),i}async decide(t){const{sessionId:r,requestId:n}=t;return this.holdTelemetry(),xA({...t.context,sessionId:r??t.context?.sessionId,requestId:n??t.context?.requestId},()=>this.runDecide(t))}resolveDecisionProviderName(t,r){return t??iD(this.resolveCredentials(r))}registeredDecisionModel(t){const r=Sr.getProviderInfo(t.name)?.defaultModel;return r||(t.envVars.model?process.env[t.envVars.model]:void 0)||t.defaultModel}decisionLimits(t){const r=this.resolveDecisionProviderName(t?.provider,t?.credentials);if(!r)return null;const n=fl.get(r.toLowerCase())??r,o=nr.get(n);if(!o)return null;const i=t?.model??this.registeredDecisionModel(o);return mD(o,i)}decisionHookTimeout(){if(this.decisionHookTimeoutMs!==void 0)return this.decisionHookTimeoutMs;const t=this.decisionHooks?.hookTimeoutMs;let r=V2;return t!==void 0&&(typeof t=="number"&&Number.isFinite(t)&&t>0&&t<=H2?r=t:f.warn(`[Decision] decisionHooks.hookTimeoutMs must be a finite number from 1 to ${H2} ms; using the default ${V2} ms`,{configured:String(t)})),this.decisionHookTimeoutMs=r,r}emitDecisionEvent(t,r){try{this.emitter.emit(t,r)}catch(n){f.warn(`[Decision] a ${t} listener threw`,{error:n instanceof Error?n.message:String(n)})}}async siteDecide(t,r){const n={...t,credentials:r?.credentials??t.credentials,signal:r?.signal&&t.signal?AbortSignal.any([r.signal,t.signal]):r?.signal??t.signal,sessionId:r?.sessionId??t.sessionId,requestId:r?.requestId??t.requestId},o=n.site;if(!o)return this.tryRunDecide(n);if(!this.resolveDecisionProviderName(n.provider,n.credentials))return this.tryRunDecide(n);const i=new Map;let s;try{const a=n.questions,u=Object.keys(a).length,l=this.decisionHooks,c=this.decisionHookTimeout();let d;const p=()=>(d??={state:structuredClone(n.state),questions:structuredClone(a)},d),m=()=>({site:o,...p(),sessionId:n.sessionId,requestId:n.requestId});let h=a;if(l?.extendQuestions){let A;try{A=await Ge(Promise.resolve(l.extendQuestions(m())),c,new Error(`extendQuestions exceeded ${c}ms`))??void 0}catch(R){f.warn(`[Decision] extendQuestions hook failed for site "${o}" \u2014 proceeding with NeuroLink's own questions`,{error:R instanceof Error?R.message:String(R)})}const x=A?Object.entries(A):[];if(x.length>0){const R=this.decisionLimits({provider:n.provider,model:n.model,credentials:n.credentials}),C=R?.maxQuestions!==void 0?Math.max(0,R.maxQuestions-u):Number.POSITIVE_INFINITY,P={...a};let D=0,L=0,O=0;for(const[N,$]of x){const U=hln($);if(U===void 0){D+=1;continue}if(JNe(U,R)!==void 0){L+=1;continue}if(i.size>=C){O+=1;continue}const q=qh(bL,i.size);P[q]=U,i.set(q,N)}D>0&&f.warn(`[Decision] dropped ${D} malformed host question(s) for site "${o}"`),L>0&&f.warn(`[Decision] dropped ${L} host question(s) for site "${o}" that ${R?.provider??"the decision provider"} cannot answer`),O>0&&R&&f.warn(`[Decision] dropped ${O} host question(s) for site "${o}": ${R.provider} accepts ${R.maxQuestions} per request and NeuroLink asks ${u}`),h=P}}const g=i.size;if(this.emitter.listenerCount("decision:before")>0){const A={site:o,state:p().state,questions:g===0?p().questions:structuredClone(h),hostQuestionCount:g,sessionId:n.sessionId,requestId:n.requestId};this.emitDecisionEvent("decision:before",A)}const y=Date.now(),v=await this.tryRunDecide({...n,questions:h});s=v;const w=Object.create(null),b=Object.create(null);if(v)for(const[A,x]of Object.entries(v.answers)){const R=i.get(A);R===void 0?w[A]=x:b[R]=x}const E=v?structuredClone(v):null,k={site:o,answers:structuredClone(w),hostAnswers:structuredClone(b),latencyMs:v?.latencyMs??Date.now()-y,provider:v?.provider??this.resolveDecisionProviderName(n.provider,n.credentials),model:v?.model,result:E,sessionId:n.sessionId,requestId:n.requestId};if(this.emitDecisionEvent("decision:after",k),!v||!E)return null;if(l?.onAnswers)try{await Ge(Promise.resolve(l.onAnswers({...m(),answers:structuredClone(b),result:E})),c,new Error(`onAnswers exceeded ${c}ms`))}catch(A){f.warn(`[Decision] onAnswers hook failed for site "${o}"`,{error:A instanceof Error?A.message:String(A)})}return g===0?v:{...v,answers:w}}catch(a){return f.warn(`[Decision] site "${o}" hook or event handling threw \u2014 ${s===void 0?"deciding with NeuroLink's own questions":"handing the consumer the answers already obtained"}`,{error:a instanceof Error?a.message:String(a)}),s===void 0?this.tryRunDecide(n):s?fln(s,i):null}}async runDecide(t){const r=this.resolveDecisionProviderName(t.provider,t.credentials),n=Object.keys(t.questions),o=n.length,i=r?nr.get(fl.get(r.toLowerCase())??r):void 0,s=t.model??(i&&this.registeredDecisionModel(i)),a=t,u=n.filter(mln).length,l=a.site?{"decision.site":a.site,"decision.host_question_count":u}:{};return pt({name:"decide",tracer:Be.decision,expectedFailure:()=>!r,attributes:{"gen_ai.system":r,"gen_ai.operation.name":"decide","ai.provider":r,"decision.question_count":o,"decision.images.count":t.images?.length??0,"decision.audio.count":t.audio===void 0?0:1,...l}},async c=>{if(no(c,"generation",{model:s,input:{state:t.state,questions:t.questions},metadata:{provider:r,...a.site&&{site:a.site,host_question_count:u}}}),!r){const g=`No decision provider is configured. Set ${kzr()} (in the environment or in \`credentials\`), or pass \`provider\` explicitly.`;throw no(c,"generation",{level:"WARNING",statusMessage:g}),new Error(g)}const{traceId:d,parentSpanId:p}=t0(),m=Date.now();let h=Ce.createSpan("model.decision",`decision.${r}`,{"ai.provider":r,"ai.model":t.model??"","decision.question_count":o,"decision.images.count":t.images?.length??0,"decision.audio.count":t.audio===void 0?0:1,...l},p,d);try{const g=await ao.createProvider(r,t.model,!1,this,void 0,this.resolveCredentials(t.credentials));if(typeof g.decide!="function")throw new Error(`Provider "${r}" does not serve the decide inference type.`);const y=await g.decide({state:t.state,questions:t.questions,images:t.images,video:t.video,audio:t.audio,model:t.model,signal:t.signal,timeoutMs:t.timeoutMs}),v=Object.keys(y.answers).length,w=fl.get(r.toLowerCase())??r,b=bl(w,y.model,{input:y.usage.inputTokens,output:y.usage.outputTokens,total:y.usage.inputTokens+y.usage.outputTokens});c.setAttribute("gen_ai.response.model",y.model),c.setAttribute("gen_ai.usage.input_tokens",y.usage.inputTokens),c.setAttribute("gen_ai.usage.output_tokens",y.usage.outputTokens),c.setAttribute("decision.answer_count",v),c.setAttribute("decision.media.bytes",y.mediaBytes??0),c.setAttribute("ai.cost.total",b),y.upstreamMs!==void 0&&c.setAttribute("decision.upstream_ms",y.upstreamMs),y.requestId&&c.setAttribute("gen_ai.response.id",y.requestId),no(c,"generation",{model:y.model,output:y.answers,usageDetails:TZ({input:y.usage.inputTokens,output:y.usage.outputTokens}),costDetails:{total:b}}),h.durationMs=Date.now()-m,h=Ce.updateAttributes(h,{"ai.model":y.model,"ai.tokens.input":y.usage.inputTokens,"ai.tokens.output":y.usage.outputTokens,"ai.cost.input":b,"ai.cost.output":0,"ai.cost.total":b,"decision.answer_count":v,"decision.media.bytes":y.mediaBytes??0,"decision.latency_ms":y.latencyMs,...y.upstreamMs!==void 0?{"decision.upstream_ms":y.upstreamMs}:{}});const E=Ce.endSpan(h,1);return this.metricsAggregator.recordSpan(E),nt().recordSpan(E),y}catch(g){h.durationMs=Date.now()-m;const y=Ce.endSpan(h,2,g instanceof Error?g.message:String(g));throw this.metricsAggregator.recordSpan(y),nt().recordSpan(y),g}})}async tryDecide(t){return this.holdTelemetry(),this.siteDecide(t)}async transcribe(t){const[r,{runTranscribe:n}]=await Promise.all([this.buildTranscribeDeps(t.credentials?.stt),Promise.resolve().then(()=>(qgr(),She))]);return n(t,r)}async*transcribeStream(t){const[r,{runTranscribeStream:n}]=await Promise.all([this.buildTranscribeDeps(t.credentials?.stt),Promise.resolve().then(()=>(Sgr(),bgr))]);yield*n(t,r)}resolveSTTCredentials(t){const r=this.credentials?.stt;if(!r||!t)return t??r;const n={...r};for(const[o,i]of Object.entries(t)){const s=n[o];n[o]=s&&typeof s=="object"&&i&&typeof i=="object"?{...s,...i}:i??s}return n}resolveSTTProvider(t,r){const n=t?.trim();return n?Rw(n)??n:Rk(r)}async buildTranscribeDeps(t){await Jd.registerAllProviders();const[{STTProcessor:r},{createSTTHandler:n},{STTError:o}]=await Promise.all([Promise.resolve().then(()=>(Dh(),a3)),Promise.resolve().then(()=>(Ph(),Mh)),Promise.resolve().then(()=>(Fi(),f1t))]),i=this.resolveSTTCredentials(t),s=u=>{const l=this.resolveSTTProvider(u,i);if(Rw(l)===void 0&&!r.supports(l)&&!Ik(i)[l.trim().toLowerCase()])throw o.unknownProvider(l,NNe(i),$Ne());return l},a=u=>{if(Ik(i)[u.trim().toLowerCase()])return n(u,i);const l=ih(u);return l?i?.[l.credentialsKey]!==void 0?n(l.name,i):r.getHandler(l.name)??n(l.name):r.getHandler(u)};return{...this.buildSTTCorrectionDeps(),transcribe:(u,l,c)=>r.transcribe(u,l,c,i),resolveProvider:s,getHandler:a}}buildSTTCorrectionDeps(){return{decide:async t=>{const r=await this.tryDecide({state:t.state,questions:t.questions,...t.timeoutMs!==void 0?{timeoutMs:t.timeoutMs}:{}});return r?{answers:r.answers}:null},rewrite:async t=>{const r=new AbortController,n=setTimeout(()=>r.abort(),t.timeoutMs),o=t.provider??process.env.NEUROLINK_STT_REWRITE_PROVIDER?.trim(),i=t.model??process.env.NEUROLINK_STT_REWRITE_MODEL?.trim(),s={input:{text:t.user},systemPrompt:t.system,...o?{provider:o}:{},...i?{model:i}:{},maxTokens:t.maxTokens,temperature:0,disableTools:!0,memory:{enabled:!1},abortSignal:r.signal};try{const u=(await this.generate(s)).content??"";return t.onPartial&&u&&t.onPartial(u),u}finally{clearTimeout(n)}},render:async t=>{const r=new AbortController,n=setTimeout(()=>r.abort(),t.timeoutMs),o=t.provider??(process.env.NEUROLINK_STT_OUTPUT_PROVIDER?.trim()||process.env.NEUROLINK_STT_REWRITE_PROVIDER?.trim()),i=t.model??(process.env.NEUROLINK_STT_OUTPUT_MODEL?.trim()||process.env.NEUROLINK_STT_REWRITE_MODEL?.trim());try{const s=await this.generate({input:{text:t.user},systemPrompt:t.system,schema:t.schema,...o?{provider:o}:{},...i?{model:i}:{},maxTokens:t.maxTokens,temperature:0,disableTools:!0,memory:{enabled:!1},abortSignal:r.signal});return s.structuredData??s.content??""}finally{clearTimeout(n)}}}}async tryRunDecide(t){try{const r=await this.decideInBatches(t);return f.shouldLog("debug")&&f.debug(`decide: ${Object.keys(r.answers).length} answers in ${r.latencyMs}ms`+(r.upstreamMs?` (upstream ${r.upstreamMs}ms)`:""),{provider:r.provider,model:r.model,requestId:r.requestId,usage:r.usage}),r}catch(r){return f.debug(`decide unavailable: ${r instanceof Error?r.message:String(r)} \u2014 falling back`),null}}async decideInBatches(t){const r=t.provider??iD(this.resolveCredentials(t.credentials)),n=r?fl.get(r.toLowerCase()):void 0,o=n?nr.get(n)?.decisionLimits?.maxQuestions:void 0,i=Pln(t,o);if(i.length===1)return this.decide(t);const s=[];let a;for(let c=0;c<i.length;c+=Wie){const d=await Promise.allSettled(i.slice(c,c+Wie).map(p=>this.decide(p)));for(const p of d)p.status==="fulfilled"?s.push(p.value):a??=p.reason}const[u,...l]=s;if(u===void 0)throw a instanceof Error?a:new Error(String(a));return l.length+1<i.length&&f.debug(`decide: ${i.length-s.length} of ${i.length} batches failed; using the answers of the rest`),Dln([u,...l])}async evaluate(t,r){const{EvaluationPipeline:n,getPreset:o}=await Ge(Promise.resolve().then(()=>(ax(),sx)),1e4,ve.evaluationTimeout("evaluation module load",1e4));let i;if(r?.pipeline&&r?.scorers)throw new Error("Cannot specify both 'pipeline' and 'scorers' options. Use one or the other.");if(r?.scorers&&r.scorers.length===0)throw new Error("The 'scorers' array must not be empty. Provide at least one scorer ID or omit the option to use the default 'quality' preset.");r?.pipeline?i={...o(r.pipeline)}:r?.scorers&&r.scorers.length>0?i={name:"SDK Evaluation",description:"Evaluation from NeuroLink SDK",scorers:r.scorers.map(l=>({id:l})),executionMode:r.executionMode??"parallel",passThreshold:r.passThreshold??.7}:i=o("quality"),r?.passThreshold!==void 0&&(i.passThreshold=r.passThreshold),r?.executionMode!==void 0&&(i.executionMode=r.executionMode);const s=new n(i);await Ge(s.initialize(),3e4,ve.evaluationTimeout("pipeline initialization",3e4));const a=r?.timeoutMs??6e4,u=await Ge(s.execute(t,{correlationId:r?.correlationId}),a,ve.evaluationTimeout("pipeline execution",a));return f.debug("[NeuroLink] Evaluation completed",{pipeline:i.name,overallScore:u.overallScore,passed:u.passed,scorerCount:u.scores.length}),u}async score(t,r,n){const{ScorerRegistry:o}=await Ge(Promise.resolve().then(()=>(nQ(),rQ)),1e4,ve.evaluationTimeout("scorer module load",1e4));await Ge(o.registerBuiltInScorers(),3e4,ve.evaluationTimeout("scorer bootstrap",3e4));const i=await Ge(o.getScorer(t,n),3e4,ve.evaluationTimeout(`scorer load: ${t}`,3e4));if(!i)throw ve.scorerNotFound(t);const s=i.validateInput(r);if(!s.valid)throw ve.evaluationValidationFailed(t,s.errors);const a=await Ge(i.score(r),6e4,ve.evaluationTimeout("scorer execution",6e4));return f.debug("[NeuroLink] Scoring completed",{scorerId:t,score:a.score,passed:a.passed,computeTime:a.computeTime}),a}async getAvailableScorers(t){const{ScorerRegistry:r}=await Ge(Promise.resolve().then(()=>(nQ(),rQ)),1e4,ve.evaluationTimeout("scorer module load",1e4));await Ge(r.registerBuiltInScorers(),3e4,ve.evaluationTimeout("scorer bootstrap",3e4));let n=r.list();return t?.category&&(n=n.filter(o=>o.category===t.category)),t?.type&&(n=n.filter(o=>o.type===t.type)),n}async getEvaluationPresets(){const{getPresetNames:t}=await Ge(Promise.resolve().then(()=>(ax(),sx)),1e4,ve.evaluationTimeout("evaluation module load",1e4));return t()}async getEvaluationPreset(t){const{getPreset:r}=await Ge(Promise.resolve().then(()=>(ax(),sx)),1e4,ve.evaluationTimeout("evaluation module load",1e4));return r(t)}async createAgent(t){const{Agent:r}=await Promise.resolve().then(()=>(xhe(),jgr));return f.debug("[NeuroLink] Creating agent",{id:t.id,name:t.name,tools:t.tools?.length||0}),new r(t,this)}async createNetwork(t){const{AgentNetwork:r}=await Promise.resolve().then(()=>(Hgr(),Vgr));return f.debug("[NeuroLink] Creating agent network",{name:t.name,agentCount:t.agents.length,workflowCount:t.workflows?.length||0,toolCount:t.tools?.length||0}),new r(t,this)}createWorkerInstance(t){const r=t?.logTag??"worker",n=this.emitter,o=t?.config??{},i={...this.credentials?{credentials:this.credentials}:{},...o,conversationMemory:{enabled:!1},enableOrchestration:!1,observability:this.observabilityConfig,...t?.shareToolRegistry!==!1&&{toolRegistry:this.toolRegistry}},s=this.workerToolsConfig(o.tools),a=new qf(s?{...i,tools:s}:i);if(t?.shareToolRegistry!==!1)for(const u of this.uncacheableTools)a.uncacheableTools.add(u);if(f.setEventEmitter(n),t?.onLog){const u=t.onLog,l=h=>{try{const g=h??{};u({tag:r,level:String(g.level??"info"),message:String(g.message??""),timestamp:typeof g.timestamp=="number"?g.timestamp:Date.now(),data:g.data})}catch{}},c={emit:(h,...g)=>(h==="log-event"&&l(g[0]),!0)},d=a.logInstanceId;f.addScopedEventEmitter(d,c);const p=()=>{f.removeScopedEventEmitter(d,c),this.ownedWorkerLogBridgeDetachers.delete(p)};this.ownedWorkerLogBridgeDetachers.add(p);const m=a.dispose.bind(a);a.dispose=async()=>{p(),await m()}}return f.debug("[NeuroLink] Created worker instance",{tag:r,sharedToolRegistry:t?.shareToolRegistry!==!1}),a}async runIsolatedAgent(t,r,n){const{runIsolatedAgent:o}=await Promise.resolve().then(()=>(w1(),Q6));return o(this,t,r,n)}async continueAgent(t,r){const{continueIsolatedAgent:n}=await Promise.resolve().then(()=>(w1(),Q6));return n(this,t,r)}async stopAgent(t){const{stopIsolatedAgent:r}=await Promise.resolve().then(()=>(w1(),Q6));return r(this,t)}async registerAgentTool(t,r){const{registerAgentTool:n}=await Promise.resolve().then(()=>(T1(),n$)),o=n(this,t,r);return this.hasAgentTools=!0,o}registerTaskTools(){if(this.hasTaskChecklistTools)return;const t=ngn(this);for(const[r,n]of Object.entries(t))this.registerTool(r,n,{cacheable:!1});this.hasTaskChecklistTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(t).length} task checklist tools`)}getTaskState(t){return Qfn(t??Si(this))}clearTaskState(t){return egn(t??Si(this))}registerDelegationTools(t){if(_gn(this,t),this.hasBackgroundDelegationTools)return;const r=Pgn(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundDelegationTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(r).length} background delegation tools`)}async spawnDelegate(t){return For(this,t)}async collectDelegates(t){return Bor(this,t)}async cancelDelegates(t){return Ele(this,t)}getArtifactStore(){return this.mcpArtifactStore||(this.mcpArtifactStore=this.createConfiguredArtifactStore()),this.registerMemoryRetrievalTools(),this.mcpArtifactStore}setArtifactStore(t){const r=this.mcpArtifactStore;r!==t&&(r&&(f.warn("[NeuroLink] Artifact store replaced \u2014 artifacts already written to the previous store will not resolve through this instance"),this.ownsArtifactStore&&r.close&&r.close().catch(n=>{f.warn("[NeuroLink] Previous artifact store close failed",{error:n instanceof Error?n.message:String(n)})})),this.mcpArtifactStore=t,this.ownsArtifactStore=!1,this.installOutputNormalizer(t),this.registerMemoryRetrievalTools())}createConfiguredArtifactStore(){const t=this.artifactsConfig?.store!==void 0,r=krr(this.artifactsConfig,this.conversationMemoryConfig?.conversationMemory?.redisConfig);return this.ownsArtifactStore=!t,f.debug("[NeuroLink] Artifact store initialized",{backend:t?"custom":sue(this.artifactsConfig)}),r}installOutputNormalizer(t){this.mcpOutputNormalizerConfig&&(this.externalServerManager.setOutputNormalizer(new ltr(this.mcpOutputNormalizerConfig,t)),f.debug("[NeuroLink] MCP output normalizer initialized",{...this.mcpOutputNormalizerConfig,hasArtifactStore:t!==void 0}))}async bankArtifact(t,r){return Khn(this,t,r)}async readArtifact(t,r){return Jhn(this,t,r)}registerBackgroundCommandTools(t){if(Hor(this,t),this.hasBackgroundCommandTools)return;const r=zgn(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundCommandTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(r).length} background command tools`)}setBackgroundCommandPolicy(t){Hor(this,t)}async startBackgroundCommand(t,r){return eir(this,t,r)}getBackgroundCommandStatus(t){return tir(this,t)}async awaitBackgroundCommand(t,r){return Lle(this,t,r)}async killBackgroundCommand(t,r){return rir(this,t,r)}async readBackgroundCommandOutput(t,r){return p$(this,t,r)}registerGitTools(t){if(Ggn(this,t),this.hasGitTools)return;const r=Jgn(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasGitTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(r).length} read-only git tools`)}async runGitCommand(t,r){return fir(this,t,r)}async executeNetwork(t,r,n){return f.debug("[NeuroLink] Executing agent network",{networkId:t.id,networkName:t.name,hasContext:!!r.context}),t.execute(r,n)}async*streamNetwork(t,r,n){f.debug("[NeuroLink] Streaming agent network",{networkId:t.id,networkName:t.name,hasContext:!!r.context}),yield*t.stream(r,n)}async createOrchestrator(t){const{NetworkOrchestrator:r}=await Promise.resolve().then(()=>(Xgr(),Jgr));return f.debug("[NeuroLink] Creating network orchestrator",{maxConcurrentExecutions:t?.maxConcurrentExecutions,defaultMode:t?.defaultMode}),new r(this,t)}async createCoordinator(t){const{AgentCoordinator:r}=await Promise.resolve().then(()=>(Zgr(),Ygr));return f.debug("[NeuroLink] Creating agent coordinator",{strategy:t?.strategy,maxConcurrency:t?.maxConcurrency}),new r(t)}async createMessageBus(t){const{MessageBus:r}=await Promise.resolve().then(()=>(e0r(),Qgr));return f.debug("[NeuroLink] Creating message bus",{maxHistorySize:t?.maxHistorySize}),new r(t)}async dispose(){f.debug("[NeuroLink] Starting disposal of resources..."),this.lastCompactionMessageCount.clear();const t=[];try{try{await nir(this),await Ele(this)}catch(r){const n=r instanceof Error?r:new Error(`Background work cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error stopping background work:",r)}try{await this.releaseMemoryCondenser()}catch(r){t.push(r instanceof Error?r:new Error(String(r)))}try{f.debug("[NeuroLink] Flushing and shutting down OpenTelemetry..."),await this.releaseTelemetryHold(),f.debug("[NeuroLink] OpenTelemetry shutdown successfully")}catch(r){const n=r instanceof Error?r:new Error(`OpenTelemetry shutdown error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error shutting down OpenTelemetry:",r)}if(this.externalServerManager)try{f.debug("[NeuroLink] Shutting down external MCP servers..."),await this.externalServerManager.shutdown(),f.debug("[NeuroLink] External MCP servers shutdown successfully")}catch(r){const n=r instanceof Error?r:new Error(`External server shutdown error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error shutting down external MCP servers:",r)}if(this.ownsArtifactStore&&this.mcpArtifactStore?.close)try{await this.mcpArtifactStore.close(),f.debug("[NeuroLink] Artifact store closed")}catch(r){const n=r instanceof Error?r:new Error(`Artifact store close error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error closing artifact store:",r)}if(this.emitter)try{f.debug("[NeuroLink] Removing all event listeners..."),this.emitter.removeAllListeners(),f.clearEventEmitter(this.emitter),f.clearScopedEventEmitters(this.logInstanceId),f.debug("[NeuroLink] Event listeners removed successfully")}catch(r){const n=r instanceof Error?r:new Error(`Event emitter cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error removing event listeners:",r)}if(this.ownedWorkerLogBridgeDetachers.size>0)try{const r=this.ownedWorkerLogBridgeDetachers.size;for(const n of[...this.ownedWorkerLogBridgeDetachers])n();f.debug(`[NeuroLink] Detached ${r} undisposed worker log bridge(s)`)}catch(r){const n=r instanceof Error?r:new Error(`Worker log bridge cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error detaching worker log bridges:",r)}if(this.toolCircuitBreakers&&this.toolCircuitBreakers.size>0)try{f.debug(`[NeuroLink] Clearing ${this.toolCircuitBreakers.size} circuit breakers...`),this.toolCircuitBreakers.clear(),f.debug("[NeuroLink] Circuit breakers cleared successfully")}catch(r){const n=r instanceof Error?r:new Error(`Circuit breaker cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error clearing circuit breakers:",r)}try{f.debug("[NeuroLink] Clearing maps and caches..."),this.toolExecutionMetrics&&this.toolExecutionMetrics.clear(),this.activeToolExecutions&&this.activeToolExecutions.clear(),this.currentStreamToolExecutions&&(this.currentStreamToolExecutions.length=0),this.toolExecutionHistory&&(this.toolExecutionHistory.length=0),this.toolCache&&(this.toolCache.tools=[],this.toolCache.timestamp=0),this.mcpToolResultCache?.destroy(),this.mcpToolRouter?.destroy(),this.mcpToolBatcher?.destroy(),this.mcpToolResultCache=void 0,this.mcpToolRouter=void 0,this.mcpToolBatcher=void 0,this.mcpEnhancedDiscovery=void 0,this.mcpToolMiddlewares=[],f.debug("[NeuroLink] Maps and caches cleared successfully")}catch(r){const n=r instanceof Error?r:new Error(`Cache cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error clearing caches:",r)}if(this._taskManager)try{f.debug("[NeuroLink] Shutting down TaskManager..."),await Ge(this._taskManager.shutdown(),5e3,new Error("TaskManager shutdown timed out"))}catch(r){f.warn("[NeuroLink] TaskManager shutdown error:",r)}finally{this._taskManager=void 0}try{f.debug("[NeuroLink] Resetting initialization state..."),this.mcpInitialized=!1,this.mcpInitPromise=null,this.conversationMemoryNeedsInit=!1,this.credentials=void 0,f.debug("[NeuroLink] Initialization state reset successfully")}catch(r){const n=r instanceof Error?r:new Error(`State reset error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error resetting state:",r)}t.length===0?f.debug("[NeuroLink] \u2705 Resource disposal completed successfully"):f.warn(`[NeuroLink] \u26A0\uFE0F Resource disposal completed with ${t.length} errors`,{errors:t.map(r=>r.message)})}catch(r){throw f.error("[NeuroLink] Critical error during disposal:",r),r}}getToolRegistry(){return this.toolRegistry}async compactSession(t,r){if(!this.conversationMemory)return null;const n=await this.conversationMemory.buildContextMessages(t);if(!n||n.length===0)return null;const o=new aT({...r,summarizationProvider:r?.summarizationProvider??this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:r?.summarizationModel??this.conversationMemoryConfig?.conversationMemory?.summarizationModel},this.contextCompactorDeps({sessionId:t})),i=Ea({provider:r?.provider||"openai",conversationMessages:n,toolReplayMode:this.resolveToolReplayModeForBudget({})}),s=Math.floor(i.availableInputTokens*.6),a=await o.compact(n,s,this.conversationMemoryConfig?.conversationMemory);return a.compacted&&Hb(a.messages),a}async getContextStats(t,r,n){if(!this.conversationMemory)return null;const o=await this.conversationMemory.buildContextMessages(t);if(!o||o.length===0)return null;const i=Ea({provider:r||"openai",model:n,conversationMessages:o,toolReplayMode:this.resolveToolReplayModeForBudget({})});return{estimatedInputTokens:i.estimatedInputTokens,availableInputTokens:i.availableInputTokens,usageRatio:i.usageRatio,shouldCompact:i.shouldCompact,messageCount:o.length}}needsCompaction(t,r,n){if(!this.conversationMemory)return!1;const o=this.conversationMemory.getSession?.(t);return o?Ea({provider:r||"openai",model:n,conversationMessages:o.messages,toolReplayMode:this.resolveToolReplayModeForBudget({})}).shouldCompact:!1}async setAuthProvider(t){this.authInitPromise=void 0,await this.initializeAuthProviderFromConfig(t)}async initializeAuthProviderFromConfig(t){let r,n;if("authenticateToken"in t&&typeof t.authenticateToken=="function")r=t,n=r.type;else if("provider"in t)r=t.provider,n=r.type;else{const o=t,{AuthProviderFactory:i}=await Promise.resolve().then(()=>($5(),t0r));r=await i.createProvider(o.type,o.config),n=o.type}this.authProvider=r,f.info(`Auth provider set: ${n}`),this.emitter.emit("auth:provider:set",{type:r.type,timestamp:Date.now()})}getAuthProvider(){return this.authProvider}async ensureAuthProvider(){if(this.authProvider||!this.pendingAuthConfig)return;const t=this.pendingAuthConfig;this.authInitPromise??=(async()=>{try{await this.initializeAuthProviderFromConfig(t),this.pendingAuthConfig=void 0}finally{this.authInitPromise&&(this.pendingAuthConfig===void 0||this.pendingAuthConfig===t)&&(this.authInitPromise=void 0)}})(),await this.authInitPromise}async setAuthContext(t){const{globalAuthContext:r}=await Promise.resolve().then(()=>(r1(),P6));r.set(t),f.debug("Auth context set",{userId:t.user.id,provider:t.provider,sessionId:t.session?.id})}async getAuthContext(){const{getAuthContext:t}=await Promise.resolve().then(()=>(r1(),P6));return t()}async clearAuthContext(){const{globalAuthContext:t}=await Promise.resolve().then(()=>(r1(),P6)),r=t.get()?.user.id;t.clear(),r&&f.debug(`Auth context cleared for user: ${r}`)}getExternalServerManager(){return this.externalServerManager}buildResolutionContext(t,r){return{requestContext:r||{},signal:t}}async resolveDynamicOptions(t){const r=["model","provider","temperature","maxTokens","systemPrompt","timeout","thinkingLevel","disableTools","enableAnalytics","enableEvaluation"];if(!(r.some(i=>typeof t[i]=="function")||typeof t.tools=="function"))return;const o=t.dynamicContext;await this.resolveDynamicFields(t,r,o)}async resolveDynamicFields(t,r,n){const o=this.buildResolutionContext(t.abortSignal,n);if(f.debug("[NeuroLink] Resolving dynamic arguments"),await Promise.all(r.map(async i=>{if(typeof t[i]=="function"){const s=await due(t[i],o);t[i]=s.value,f.debug(`[NeuroLink] Resolved dynamic ${i}: ${s.resolutionType}`)}})),typeof t.tools=="function"){const i=await due(t.tools,o);if(!Array.isArray(i.value))throw new TypeError(`Dynamic tools resolver must return string[] (tool names), got ${typeof i.value=="object"?"object":typeof i.value}`);t.enabledToolNames=i.value,delete t.tools}}},Fhe=new M_,s0r=Fhe}});function qI(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10?"image/png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56&&(e[4]===55||e[4]===57)&&e[5]===97?"image/gif":null}function jI(e){return qI(e)??"image/png"}var P_=S({"src/lib/utils/imageDetection.ts"(){"use strict"}});function Vkn(e){return bb(e)&&FN(e)===null?"video/mp4":m0r.every((t,r)=>e[r]===t)?"video/webm":null}function Hkn(e){return dm(e,0,4)==="RIFF"&&dm(e,8,12)==="WAVE"?"wav":dm(e,0,4)==="fLaC"?"flac":dm(e,0,4)==="OggS"?"ogg":bb(e)?"aac":dm(e,0,3)==="ID3"?"mp3":e.length>=2&&e[0]===255&&(e[1]&224)===224?(e[1]&6)===0?"aac":"mp3":null}function Wkn(e){let t,r=12;for(;r+8<=e.length;){const n=dm(e,r,r+4),o=e.readUInt32LE(r+4),i=r+8;if(n==="fmt "&&i+12<=e.length)t=e.readUInt32LE(i+8);else if(n==="data"){const s=o===0||o===4294967295?e.length-i:Math.min(o,e.length-i);return t?s/t:void 0}r=i+o+o%2}}function Kkn(e){if(e.length<26||(e[4]&127)!==0)return;const t=8,r=e[t+10]<<12|e[t+11]<<4|e[t+12]>>4,n=(e[t+13]&15)*2**32+e.readUInt32BE(t+14);return r>0&&n>0?n/r:void 0}function Jkn(e){const t=e[26];if(e.length<28||t===void 0)return;const r=27+t;let n,o=0;dm(e,r,r+8)==="OpusHead"?(n=48e3,o=e.length>=r+12?e.readUInt16LE(r+10):0):dm(e,r,r+7)==="vorbis"&&(n=e.length>=r+16?e.readUInt32LE(r+12):void 0);const i=e.lastIndexOf("OggS");if(!n||i<0||i+14>e.length||e[i+4]!==0)return;const s=e.readBigInt64LE(i+6);if(!(s<=0n))return Math.max(0,Number(s)-o)/n}function Xkn(e,t,r){const n=Hkn(e);if(n===null)return{status:"error",message:`${r} ${Bhe.audio}.`};if(n==="aac")return{status:"error",message:`${r} is AAC or M4A audio, which the model does not decode. Convert it to WAV, FLAC, Ogg or MP3.`};const o=n==="wav"?Wkn(e):n==="flac"?Kkn(e):n==="ogg"?Jkn(e):void 0;return n==="wav"&&o===void 0?{status:"error",message:`${r} is a WAV file without a complete fmt and data chunk.`}:o!==void 0&&o>t.maxSeconds?{status:"error",message:`${r} runs ${o.toFixed(1)} seconds; the model hears at most ${t.maxSeconds}. Trim it, or split it across requests.`}:{status:"ok",audio:{data:e.toString("base64"),format:n}}}function Ykn(e,t,r){const n=t==="image"?qI(e):Vkn(e);return n===null?{status:"error",message:`${r} ${Bhe[t]}.`}:{status:"ok",dataUrl:`data:${n};base64,${e.toString("base64")}`}}function Uhe(e){return e.length<=d0r?`(${e})`:`(a ${e.length}-character string)`}async function Zkn(e,t,r){try{const n=await SD.stat(e);return n.isFile()?n.size>r?{status:"error",message:`${t} ${Uhe(e)} is ${n.size} bytes; a request may carry at most ${r}.`}:{status:"ok",buffer:await SD.readFile(e)}:{status:"error",message:`${t} ${Uhe(e)} is not a file.`}}catch(n){const o=n instanceof Error&&"code"in n?String(n.code):"unreadable";return{status:"error",message:`Could not read ${t} ${Uhe(e)}: ${o}.`}}}async function a0r(e,t,r,n){if(typeof e!="string")return e.length===0?{status:"error",message:`${r} is an empty Buffer.`}:{status:"buffer",buffer:e};const o=e.trim();if(o==="")return{status:"error",message:`${r} is an empty string.`};if(l0r.test(o))return{status:"error",message:`${r} is a remote URL. Media is not fetched for you; pass a Buffer, a file path or a data: URL.`};if(/^data:/i.test(o))return p0r[t].test(o)?{status:"dataUrl",dataUrl:o}:{status:"error",message:`${r} is a data: URL that is not base64 ${t} content.`};if(c0r.test(o))return{status:"error",message:`${r} uses an unsupported URL scheme. Pass a Buffer, a file path or a data: URL.`};const i=await Zkn(o,r,n);return i.status==="ok"?{status:"buffer",buffer:i.buffer}:i}async function u0r(e,t,r,n){const o=await a0r(e,t,r,n);return o.status==="buffer"?Ykn(o.buffer,t,r):o.status==="dataUrl"?{status:"ok",dataUrl:o.dataUrl}:o}async function Qkn(e,t,r){const n=await a0r(e,"audio",t,r);if(n.status==="dataUrl"){const o=n.dataUrl.slice(n.dataUrl.indexOf(",")+1);return{status:"ok",buffer:Buffer.from(o,"base64")}}return n.status==="buffer"?{status:"ok",buffer:n.buffer}:n}async function eAn(e,t,r,n){const o=e.images??[];if(o.length===0&&e.video===void 0&&e.audio===void 0)return{status:"prepared",media:void 0};const i=n.length>0?` Use a decision provider that does: ${n.join(", ")}.`:"";if(!t){const c=o.length===0&&e.video===void 0?"audio":"images or video";return{status:"refused",message:`${r} does not accept ${c}.${i}`}}if(e.audio!==void 0&&t.audio===void 0)return{status:"refused",message:`${r} does not accept audio.${i}`};if(o.length>t.maxImages)return{status:"refused",message:`${r} accepts at most ${t.maxImages} images per request; this one has ${o.length}.`};if(e.video!==void 0&&!t.video)return{status:"refused",message:`${r} does not accept video.`};const s=[];for(const[c,d]of o.entries()){const p=await u0r(d,"image",`Image ${c+1}`,t.maxRequestBytes);if(p.status==="error")return{status:"refused",message:p.message};s.push(p.dataUrl)}let a;if(e.video!==void 0){const c=await u0r(e.video,"video","The video",t.maxRequestBytes);if(c.status==="error")return{status:"refused",message:c.message};a=c.dataUrl}let u;if(e.audio!==void 0&&t.audio!==void 0){const c=await Qkn(e.audio,"The audio",t.maxRequestBytes);if(c.status==="error")return{status:"refused",message:c.message};const d=Xkn(c.buffer,t.audio,"The audio");if(d.status==="error")return{status:"refused",message:d.message};u=d.audio}const l=s.reduce((c,d)=>c+d.length,(a?.length??0)+(u?.data.length??0));return{status:"prepared",media:{images:s,...a?{video:a}:{},...u?{audio:u}:{},bytes:l}}}var l0r,c0r,d0r,p0r,m0r,Bhe,dm,tAn=S({"src/lib/utils/decisionMedia.ts"(){"use strict";Hr(),P_(),UN(),l0r=/^https?:\/\//i,c0r=/^[a-z][a-z0-9+.-]*:\/\//i,d0r=200,p0r={image:/^data:image\/[a-z0-9.+-]+;base64,/i,video:/^data:video\/[a-z0-9.+-]+;base64,/i,audio:/^data:audio\/[a-z0-9.+-]+;base64,/i},m0r=[26,69,223,163],Bhe={image:"is not a recognised image format",video:"is not a recognised video format (MP4, MOV or WebM)",audio:"is not a recognised audio format (WAV, FLAC, Ogg or MP3)"},dm=(e,t,r)=>e.subarray(t,r).toString("latin1")}});function h0r(e){return e.filter(zr).map(r=>{const n=Array.isArray(r.loc)?r.loc.filter(i=>typeof i=="string"||typeof i=="number").join("."):"",o=typeof r.msg=="string"?r.msg:"invalid";return n?`${n}: ${o}`:o}).slice(0,5).join("; ")||"unspecified field"}function D_(e,t){return(t?e.split(t).join("[redacted]"):e).replace(/\.?\s*Received API Key\s*=[\s\S]*$/,"").replace(/\.?\s*Received Model Group=[\s\S]*$/,"").replace(/\s*No fallback model group found[\s\S]*$/,"").replace(/input_value=[\s\S]*(?=, input_type=)/g,"input_value=[redacted]").replace(/input_value=(?!\[redacted\])[\s\S]*/g,"input_value=[redacted]").replace(/\bsk-[A-Za-z0-9._-]+/g,"[redacted]").replace(/\b[0-9a-f]{32,}\b/gi,"[redacted]").replace(/data:[a-z]+\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]+/gi,"[media]").trim()}function rAn(e){let t=e;for(let r=0;r<5&&t instanceof Error;r++){if(t.message==="unexpected redirect")return!0;t=t.cause}return!1}var zhe,f0r,Ghe,VI,O_=S({async"src/lib/providers/systemOneDecision.ts"(){"use strict";zu(),Au(),await Oc(),Lr(),lt(),tAn(),z(),zt(),hD(),u3e(),Dk(),Dk(),zhe=5e3,f0r=1,Ghe=(e,t)=>new Promise((r,n)=>{if(t?.aborted){n(t.reason);return}const o=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e);function i(){clearTimeout(o),n(t?.reason)}t?.addEventListener("abort",i,{once:!0})}),VI=class extends Za{proxyFetch;maxRetries;authFailed=!1;constructor(e,t,r){super(e,t,yf(r)?r:void 0),this.proxyFetch=Ft(),this.maxRetries=f0r}missingConfigMessage(){}assertWithinVendorLimits(e,t){}encodeQuestion(e){return this.dialect().encodeQuestion(e)}dialect(){return UH}readRetryAfterMs(e){}defaultTimeoutMs(e,t){const r=this.getDescriptorDecideMs(),n=nr.get(this.providerName)?.timeouts?.decideMsPerKStateTokens;return r===void 0||n===void 0?r:r+Math.floor(t/1e3)*n}readDecisionPayload(e){return e}reportedConfidence(e){return{}}resolveResponseModel(e,t){return typeof e.model=="string"?e.model:t}resolveRequestModel(e){return e.model??this.modelName??this.getDefaultModel()}diagnosticContext(){return{}}getProviderName(){return this.providerName}getDefaultDecisionModel(){return this.getDefaultModel()}supportsTools(){return!1}getAISDKModel(){throw new Xe(`${this.vendorDisplayName()} is a decision-only provider; it generates no text, so chat completions are not available. Use \`decide()\` instead, or pick a different provider for \`generate()\` / \`stream()\`.`,this.providerName)}async executeStream(e,t){throw new Xe(`${this.vendorDisplayName()} is a decision-only provider; streaming is not available. Use \`decide()\`, or pick another provider for \`stream()\`.`,this.providerName)}formatProviderError(e){if(e instanceof Xe)return e;const t=e instanceof Error?e.message:String(e);return new Xe(`${this.vendorLabel()} request failed: ${t}`,this.providerName)}async decide(e){const t=this.vendorLabel();if(!this.decisionApiKey())throw this.decisionError({kind:"authentication",message:this.missingKeyMessage(),retryable:!1});const r=this.missingConfigMessage();if(r)throw this.decisionError({kind:"invalid_request",message:r,retryable:!1});if(this.authFailed)throw this.decisionError({kind:"authentication",message:`${t} rejected this API key earlier; not retrying. Fix the key and construct a new provider.`,retryable:!1});const n=Object.entries(e.questions);if(n.length===0)throw this.decisionError({kind:"invalid_request",message:"At least one question is required.",retryable:!1});const o=this.resolveRequestModel(e);this.assertSupportedQuestions(e,o);const i=this.assertWithinDecisionLimits(e,o,n.length),s=Object.fromEntries(n.map(([p,m])=>[p,this.encodeQuestion(m)])),a=await this.prepareMedia(e),u=this.buildDecisionBody(e.state,s,o,a),l=JSON.stringify(u);this.assertWithinRequestBytes(l),this.assertWithinVendorLimits(u,o);const c=e.timeoutMs??this.defaultTimeoutMs(n.length,i)??this.defaultTimeout??zhe;let d;for(let p=0;p<=this.maxRetries;p++){const m=Date.now();try{const h=AbortSignal.timeout(c),g=e.signal?AbortSignal.any([e.signal,h]):h,y=await this.proxyFetch(this.decisionEndpoint(o),{method:"POST",headers:this.decisionHeaders(),body:l,signal:g,redirect:"error"}),v=Date.now()-m,w=this.readRequestId(y.headers),b=Number(y.headers.get("x-envoy-upstream-service-time"))||void 0,E=await y.json().catch(()=>null);if(!y.ok){if(d=this.parseDecisionError(y.status,E,w),d.kind==="authentication"&&(this.authFailed=!0,f.warn(`${t}: credential not accepted \u2014 disabling this provider instance. ${d.message}`,{status:d.status,...this.diagnosticContext(),requestId:w})),!d.retryable||p===this.maxRetries)throw this.decisionError(d);const C=this.readRetryAfterMs(y.headers);if(C!==void 0&&C>c-(Date.now()-m))throw this.decisionError(d);await Ghe(C??2**p*250+Math.random()*250,e.signal);continue}const k=this.readDecisionPayload(E),A=zr(k)?this.dialect().readAnswers(k,this.reportedConfidence(k),e.questions):void 0;if(!zr(k)||!A)throw this.decisionError({kind:"server",message:`${t} returned a response without an answers map.`,status:y.status,requestId:w,retryable:!1});for(const C of A.dropped)f.warn(`${t}: dropped unparseable answer "${C}"`,{requestId:w});for(const C of A.refused??[])f.warn(`${t}: the model declined to answer "${C}"`,{requestId:w});const x={...A.answers},R=zr(k.usage)?k.usage:{};return{model:this.resolveResponseModel(k,o),provider:this.providerName,answers:x,usage:{inputTokens:Ss(R.input_tokens)??Ss(R.inputTokens)??0,outputTokens:Ss(R.output_tokens)??Ss(R.outputTokens)??0},requestId:w,latencyMs:v,upstreamMs:b,...a?{mediaBytes:a.bytes}:{}}}catch(h){if(h instanceof Xe)throw h;const g=e.signal?.aborted===!0,y=h instanceof Error&&h.name==="TimeoutError",v=rAn(h);if(d={kind:g?"network":y?"timeout":"network",message:v?`${t} answered with a redirect, which is refused so the decision is not sent anywhere else. Point the base URL at the final address.`:D_(xw(h instanceof Error?h.message:String(h)),this.decisionApiKey()),retryable:!g&&!v},!d.retryable||p===this.maxRetries)throw this.decisionError(d);await Ghe(2**p*250+Math.random()*250)}}throw this.decisionError(d??{kind:"network",message:`${t} request failed.`,retryable:!1})}assertSupportedQuestions(e,t){const r=nr.get(this.providerName),n=r?mD(r,t):null;for(const[o,i]of Object.entries(e.questions)){const s=JNe(i,n);if(s!==void 0)throw this.decisionError({kind:"invalid_request",message:`${this.vendorLabel()} cannot answer question "${o}": ${s}.`,retryable:!1})}}async prepareMedia(e){const t=nr.get(this.providerName)?.decisionLimits,r=await eAn(e,t?.media,this.vendorLabel(),Szr({video:e.video!==void 0,audio:e.audio!==void 0}));if(r.status==="refused")throw this.decisionError({kind:"invalid_request",message:r.message,retryable:!1});return r.media}assertWithinRequestBytes(e){const t=nr.get(this.providerName)?.decisionLimits?.media,r=t?.maxRequestBytes;if(r===void 0)return;const n=Buffer.byteLength(e);if(n>r)throw this.decisionError({kind:"invalid_request",message:`The request is ${n} bytes; ${this.vendorLabel()} accepts at most ${r}. Send fewer or smaller images${t?.video?", or a shorter video":""}${t?.audio?", or a shorter audio clip":""}.`,retryable:!1})}assertWithinDecisionLimits(e,t,r){const n=nr.get(this.providerName),o=n?mD(n,t):null;if(!o||!o.enforcedLocally)return 0;const i=this.vendorLabel();if(o.maxQuestions!==void 0&&r>o.maxQuestions)throw this.decisionError({kind:"max_tokens_exceeded",message:`${i} accepts at most ${o.maxQuestions} questions per request; this one has ${r}. Ask fewer, or use a decision provider without this cap.`,retryable:!1});const{maxStateTokens:s}=o,a=WNe(e.state,o);if(a>s)throw this.decisionError({kind:"max_tokens_exceeded",message:`The state is ~${a} tokens; ${i}'s "${t}" model reads at most ${s}. Shorten the state, or use a decision provider with a larger window.`,retryable:!1});return a}decisionError(e){const t=new Xe(e.message,this.providerName);return Object.defineProperty(t,"cause",{value:e,enumerable:!1,writable:!0,configurable:!0}),t}}}}),qhe,nAn=S({async"src/lib/providers/decide/formatters.ts"(){"use strict";await O_(),qhe={"fastapi-validation":e=>`Request failed validation \u2014 ${h0r(Array.isArray(e)?e:[])}`}}});function g0r(e,t){const r=t.split(".");if(r.some(o=>o===""))return;let n=e;for(const o of r){if(typeof n!="object"||n===null||Array.isArray(n))return;const i=Object.getOwnPropertyDescriptor(n,o);if(i===void 0||!("value"in i))return;n=i.value}return n}var y0r=S({"src/lib/providers/decide/paths.ts"(){"use strict"}});function oAn(e){const t=Vhe.get(e);if(t)return t;const r=new RegExp(e,"i");return Vhe.set(e,r),r}function iAn(e,t,r){return((e.status===void 0?[]:typeof e.status=="number"?[e.status]:e.status).includes(t)||e.statusMin!==void 0&&t>=e.statusMin)&&(e.messagePattern===void 0||oAn(e.messagePattern).test(r.slice(0,w0r)))}function sAn(e,t){if(e.isArray)return Array.isArray(t)&&e.formatter?qhe[e.formatter](t):void 0;if(!(typeof t!="string"||t.length===0))return e.formatter?qhe[e.formatter](t):t}function aAn(e,t){for(const r of e){const n=sAn(r,g0r(t,r.path));if(n!==void 0)return{shape:r,text:n}}}function uAn(e,t){const{status:r,payload:n,requestId:o,label:i,apiKey:s,apiKeyEnvVar:a}=t,u=D_(`${i} request failed with HTTP ${r}`,s),l=aAn(e.bodyShapes,n),c=l?.text&&D_(l.text,s)||u,d=e.rules.find(y=>iAn(y,r,c)),p=d?.kind??e.default,m=d?.retryable??jhe(p),h=d?.hint?`${c} \u2014 ${D_(d.hint.split("{apiKeyEnvVar}").join(a??"the API key variable"),s)}`:c,g=(y,v)=>({kind:y,message:h,status:r,requestId:o,retryable:v});if(l){const{shape:y}=l;return g(y.kind??p,y.retryable??(y.kind===void 0?m:jhe(y.kind)))}return g(p,m)}var v0r,jhe,w0r,Vhe,lAn=S({async"src/lib/providers/decide/errors.ts"(){"use strict";await O_(),await nAn(),y0r(),v0r=new Set(["rate_limit","overloaded","server"]),jhe=e=>v0r.has(e),w0r=2e3,Vhe=new Map}});function cAn(e,t){if(/[{}]/.test(e.replace(Hhe,"")))throw new Error(`Decide endpoint template "${e}" has an unmatched brace; write placeholders as {baseURL}.`);return e.replace(Hhe,(r,n)=>{if(n!=="baseURL")throw new Error(`Decide endpoint template "${e}" uses an unknown placeholder {${n}}; the only one supported is {baseURL}.`);return t.baseURL})}var Hhe,dAn=S({"src/lib/providers/decide/template.ts"(){"use strict";Hhe=/\{([^{}]*)\}/g}}),b0r={};ue(b0r,{ConfiguredDecisionProvider:()=>_0r});var By,T0r,_0r,pAn=S({async"src/lib/providers/configuredDecision.ts"(){"use strict";hD(),z(),zt(),li(),nh(),LH(),T7r(),await lAn(),Dk(),y0r(),dAn(),await O_(),By=e=>typeof e=="string"?e.trim():"",T0r=e=>typeof e=="string"?e:JSON.stringify(e),_0r=class extends VI{entry;apiKey;baseURL;endpoint;constructor(e,t,r,n){super(t||rs(ho(e,"model"),e.models.default),e.id,r),this.entry=e,this.apiKey=By(n?.apiKey)||By(process.env[ho(e,"apiKey")]),this.baseURL=c7r(By(n?.baseURL)||By(process.env[ho(e,"baseURL")])||By(e.wire.baseURL),e.decide.baseURLNormalize??[]),this.endpoint=cAn(e.decide.endpoint,{baseURL:this.baseURL}),f.debug(`${e.displayName} Provider initialized (decide only)`,{modelName:this.modelName,baseURL:this.baseURL?sr(this.baseURL):"(not set)"})}getDefaultModel(){return rs(ho(this.entry,"model"),this.entry.models.default)}vendorLabel(){return this.entry.displayName}vendorDisplayName(){return this.entry.displayName}decisionApiKey(){return this.apiKey}missingKeyMessage(){return`${this.entry.displayName} requires an API key. Set ${ho(this.entry,"apiKey")} or pass credentials.${Cw(this.entry)}.apiKey.`}missingConfigMessage(){const{baseURLRequired:e,baseURLShape:t}=this.entry.decide;return this.baseURL?t?p7r(t,this.baseURL,this.entry.displayName,`Set ${ho(this.entry,"baseURL")} or pass credentials.${Cw(this.entry)}.baseURL to the origin, and give the key through ${ho(this.entry,"apiKey")} or credentials.${Cw(this.entry)}.apiKey.`):void 0:e?`${this.entry.displayName} requires a base URL. Set ${ho(this.entry,"baseURL")} or pass credentials.${Cw(this.entry)}.baseURL.`:void 0}decisionEndpoint(){return this.endpoint}resolveRequestModel(e){const t=super.resolveRequestModel(e),r=this.entry.decide.capableModel;if(r===void 0||e.model!==void 0||t!==this.entry.models.default||By(process.env[ho(this.entry,"model")])!=="")return t;const n=(e.images?.length??0)>0||e.video!==void 0||e.audio!==void 0,o=Object.values(e.questions).some(i=>r.questionTypes.includes(KNe(i)));return n||o?r.model:t}decisionHeaders(){return{...this.entry.decide.authHeader==="x-api-key"?{"x-api-key":this.apiKey}:{Authorization:`Bearer ${this.apiKey}`},"Content-Type":"application/json"}}encodeState(e){if(this.entry.decide.stateEncoding!=="text")return e;const t=T0r(e);if(t===void 0||t.trim()==="")throw this.decisionError({kind:"invalid_request",message:`${this.vendorLabel()} needs non-blank state text; the state was empty or only whitespace.`,retryable:!1});return t}buildDecisionBody(e,t,r,n){const{placement:o,alias:i}=this.entry.decide.model;return this.dialect().buildBody({state:this.encodeState(e),questions:t,model:o==="body-unless-alias"&&r===i?void 0:r,media:n,mediaKeys:this.entry.decide.media})}parseDecisionError(e,t,r){return uAn(this.entry.decide.errors,{status:e,payload:t,requestId:r,label:this.entry.displayName,apiKey:this.apiKey,apiKeyEnvVar:ho(this.entry,"apiKey")})}readRequestId(e){for(const t of this.entry.decide.requestIdHeaders??[]){const r=e.get(t);if(r!==null)return r}}resolveResponseModel(e,t){if(!zr(e))return t;for(const r of this.entry.decide.response?.modelPaths??[]){const n=g0r(e,r);if(typeof n=="string")return n}return super.resolveResponseModel(e,t)}dialect(){return c3e(this.entry.decide.dialect)}}}});async function zy(e,t){try{await e}catch(r){f.debug(`[${t}] detached stream pump rejected; reason absorbed because the turn's own error is authoritative`,r)}}var Whe=S({"src/lib/utils/drainDetachedPump.ts"(){"use strict";z()}});function Gy(e,t,r){return async(n,o)=>{const i=()=>Promise.resolve(t(n,o));r.onProgress?.();try{const s=r.abortSignal?oc(i(),r.abortSignal):i();return await(r.toolTimeoutMs===void 0||r.toolTimeoutMs===null?s:kt(s,r.toolTimeoutMs,`Tool "${e}" execution timed out after ${r.toolTimeoutMs}ms`))}finally{r.onProgress?.()}}}var U5=S({"src/lib/core/toolExecutionGuards.ts"(){"use strict";j0()}});function mAn(e,t){const r=S0r[e];return Math.round(t.min+r*(t.max-t.min))}function Khe(e,t){if(!e?.enabled&&!e?.thinkingLevel)return;const r=e.thinkingLevel??E0r;if(t&&!Qan(t)){const n=eun(t);if(n)return{includeThoughts:!0,thinkingBudget:mAn(r,n)};Jhe.has(t)||(Jhe.add(t),f.warn(`[thinkingConfig] "${t}" has no verified Gemini thinkingBudget range; omitting thinkingConfig \u2014 requested thinkingLevel is silently disabled.`));return}return{includeThoughts:!0,thinkingLevel:r}}var E0r,S0r,Jhe,k0r=S({"src/lib/utils/thinkingConfig.ts"(){"use strict";iL(),z(),E0r="high",S0r={minimal:0,low:.25,medium:.55,high:1},Jhe=new Set}});function hAn(e){return JSON.stringify(e,(t,r)=>r&&typeof r=="object"&&!Array.isArray(r)?Object.keys(r).sort().reduce((n,o)=>(n[o]=r[o],n),{}):r)}function fAn(e){if(F0r.test(e))return e;let t=e.replace(/[^A-Za-z0-9_.:-]/g,"_");return/^[A-Za-z_]/.test(t)||(t=`_${t}`),t.length>q5&&(t=t.slice(0,q5)),t}function gAn(e,t){if(!t(e))return e;let r=2;for(;;){const n=`_${r}`,i=`${e.slice(0,q5-n.length)}${n}`;if(!t(i))return i;r++}}function vf(e){if(Array.isArray(e.anyOf)||Array.isArray(e.oneOf)){const n=e.anyOf?"anyOf":"oneOf",o=e[n],i=o.filter(l=>l.type!=="null"&&l.type!=="undefined");if(i.length===1){const l=vf({...i[0]});return l.nullable=!0,e.description&&(l.description=e.description),l}const s=i.map(l=>l.type||"unknown").join(" | "),a={type:"string"},u=e.description?`${e.description} (accepts: ${s})`:`Value as string (accepts: ${s})`;return a.description=u,o.some(l=>l.type==="null")&&(a.nullable=!0),a}const t={};for(const[n,o]of Object.entries(e))if(!(n==="$schema"||n==="additionalProperties"||n==="default"))if(n==="properties"&&o&&typeof o=="object"){const i={};for(const[s,a]of Object.entries(o))a&&typeof a=="object"?i[s]=vf(a):i[s]=a;t[n]=i}else n==="items"&&o&&typeof o=="object"?Array.isArray(o)?t[n]=o.map(i=>i&&typeof i=="object"?vf(i):i):t[n]=vf(o):t[n]=o;Array.isArray(t.allOf)&&(t.allOf=t.allOf.map(n=>vf(n))),t.not&&typeof t.not=="object"&&(t.not=vf(t.not));for(const n of["if","then","else"])t[n]&&typeof t[n]=="object"&&(t[n]=vf(t[n]));typeof t.exclusiveMinimum=="boolean"&&(t.exclusiveMinimum===!0&&typeof t.minimum=="number"?(t.exclusiveMinimum=t.minimum,delete t.minimum):delete t.exclusiveMinimum),typeof t.exclusiveMaximum=="boolean"&&(t.exclusiveMaximum===!0&&typeof t.maximum=="number"?(t.exclusiveMaximum=t.maximum,delete t.maximum):delete t.exclusiveMaximum);const r=2147483647;return typeof t.maximum=="number"&&t.maximum>r&&delete t.maximum,typeof t.minimum=="number"&&t.minimum<-r&&delete t.minimum,t}function A0r(e,t){const r=[],n=new F_,o=[],i=[],s=new Set(t??[]),a=new Map;for(const[u,l]of Object.entries(e))try{const c=fAn(u),d=gAn(c,h=>s.has(h));a.set(d,u),d!==u&&i.push({from:u,to:d});const p={name:d,description:l.description||`Tool: ${d}`},m=l;if(m.parameters||l.inputSchema){let h;const g=m.parameters||l.inputSchema;KQ(g)?h=Ti(g,"openApi3"):typeof g=="object"?h=g:h={type:"object",properties:{}},h.jsonSchema&&typeof h.jsonSchema=="object"&&!h.type&&(h=h.jsonSchema),p.parametersJsonSchema=vf(io(h))}r.push(p),s.add(d),l.execute&&n.set(p.name,l.execute)}catch(c){o.push(u),f.error(`[buildNativeToolDeclarations] Failed to convert tool "${u}":`,c)}return o.length>0&&f.warn(`[buildNativeToolDeclarations] ${o.length} tool(s) skipped due to schema errors: ${o.join(", ")}`),i.length>0&&f.warn(`[buildNativeToolDeclarations] ${i.length} tool name(s) sanitized for Google's function-name regex: ${i.map(u=>`"${u.from}" -> "${u.to}"`).join(", ")}`),{toolsConfig:[{functionDeclarations:r}],executeMap:n,originalNameMap:a}}function B5(e,t,r){const n={},o=(i,s)=>r?Gy(i,s,r):async(a,u)=>s(a,u);if(e){for(const[i,s]of e.originalNameMap){const a=e.executeMap.get(i);a&&(n[s]={execute:o(s,a)})}return n}for(const[i,s]of Object.entries(t??{})){const a=s?.execute;a&&(n[i]={execute:o(i,a)})}return n}function yAn(e,t){if(!e)return[];const r=new Set(t.originalNameMap.values()),n=Object.entries(e).filter(([i])=>!r.has(i));if(n.length===0)return[];const o=A0r(Object.fromEntries(n),new Set(t.originalNameMap.keys()));t.toolsConfig[0].functionDeclarations.push(...o.toolsConfig[0].functionDeclarations);for(const[i,s]of o.originalNameMap)t.originalNameMap.set(i,s);for(const[i,s]of o.executeMap)t.executeMap.set(i,s);return f.info(`[buildNativeToolDeclarations] ${n.length} tool(s) hydrated mid-turn via discovery: ${n.map(([i])=>i).join(", ")}`),n.map(([i])=>i)}function x0r(e,t){const r=sc("google-ai",e.model,{temperature:e.temperature??1,topP:e.topP},"googleAiStudio.buildNativeConfig"),n={...r.temperature!==void 0&&{temperature:r.temperature},...r.topP!==void 0&&{topP:r.topP},maxOutputTokens:e.maxTokens};t&&(n.tools=t),e.systemPrompt&&(n.systemInstruction=e.systemPrompt);const o=Khe(e.thinkingConfig,e.model);return o&&(n.thinkingConfig=o),t||((e.responseSchema||e.wantsJsonOutput)&&(n.responseMimeType="application/json"),e.responseSchema&&(n.responseSchema=e.responseSchema)),n}function C0r(e){const t=e||_s;return Number.isFinite(t)&&t>0?Math.min(Math.floor(t),tfe):Math.min(_s,tfe)}function qy(e){switch(e){case"MAX_TOKENS":case"CONTINUATION":return"length";case"TOO_MANY_TOOL_CALLS":return"tool-calls";case"MALFORMED_FUNCTION_CALL":case"UNEXPECTED_TOOL_CALL":return"error";case"SAFETY":case"RECITATION":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":case"LANGUAGE":case"IMAGE_SAFETY":case"IMAGE_PROHIBITED_CONTENT":case"IMAGE_RECITATION":return"content-filter";default:return"stop"}}function vAn(e,t){return t?e?`${e}
|
|
2010
|
+
IMPORTANT: You have a tool called "${u.toolName}" that searches through`,`${u.filesLoaded} loaded document(s) containing ${u.chunksIndexed} indexed chunks.`,`ALWAYS use the "${u.toolName}" tool FIRST to answer the user's question before using any other tools.`,"This tool searches your local knowledge base of pre-loaded documents and is the primary source of truth.","Do NOT use websearchGrounding or any web search tools when the answer can be found in the loaded documents."].join(" ");t.systemPrompt=(t.systemPrompt||"")+l,f.info("[RAG] Tool injected into stream()",{toolName:u.toolName,filesLoaded:u.filesLoaded,chunksIndexed:u.chunksIndexed})}catch(a){f.warn("[RAG] Failed to prepare RAG tool, continuing without RAG",{error:a instanceof Error?a.message:String(a)})}const i=zyn(t),s=Gyn(t);if(t.input?.text){const{toolResults:a,enhancedPrompt:u}=await this.detectAndExecuteTools(t.input.text,void 0);u!==t.input.text&&(s.input.text=u)}return{enhancedOptions:s,factoryResult:i}}async autoDisableOllamaStreamTools(t){if((t.provider==="ollama"||t.provider?.toLowerCase().includes("ollama"))&&!t.disableTools){const{ModelConfigurationManager:r}=await Promise.resolve().then(()=>(TC(),GHt)),i=r.getInstance().getProviderConfiguration("ollama")?.modelBehavior?.toolCapableModels||[],s=t.model;i.length>0&&s&&(i.some(u=>s.toLowerCase().includes(u.toLowerCase()))||(t.disableTools=!0,f.debug("Auto-disabled tools for Ollama model that doesn't support them (stream)",{model:t.model,toolCapableModels:i.slice(0,3)})))}}setupStreamEventListeners(){const t=[];let r=0;const n=this.conversationEventContext.getStore(),o=new Set,i=g=>{if(!(!g||typeof g!="object"||!("payload"in g)||!g.payload||typeof g.payload!="object"||!("confirmationId"in g.payload)||typeof g.payload.confirmationId!="string"))return g.payload.confirmationId},s=(g,y,v)=>{const w=n!==void 0&&this.conversationEventContext.getStore()===n,b=v!==void 0&&o.has(v);!w&&!b||t.push({type:g,seq:r++,timestamp:Date.now(),...y&&typeof y=="object"?y:{data:y}})},a=(...g)=>{const y=g[0];s("response:chunk",{content:y})},u=(...g)=>{const y=g[0];s("tool:start",{...y,toolName:y.toolName??y.tool})},l=(...g)=>{const y=g[0],v=y.toolName??y.tool,w=y.responseTime??y.duration,b=y.success??(y.error!==void 0?!1:void 0),E={...y,toolName:v,...w!==void 0?{responseTime:w}:{},...b!==void 0?{success:b}:{},...y.error!==void 0?{error:y.error}:{}};s("tool:end",E),E.result&&E.result.uiComponent===!0&&s("ui-component",{toolName:v,componentData:E.result,timestamp:Date.now(),...b!==void 0?{success:b}:{},...w!==void 0?{responseTime:w}:{}})},c=(...g)=>{const y=g[0];y&&typeof y=="object"&&"type"in y&&typeof y.type=="string"&&"data"in y&&y.data&&typeof y.data=="object"&&!Array.isArray(y.data)&&s(y.type,{data:y.data})},d=(...g)=>{s("ui-component",g[0])},p=(...g)=>{if(n!==void 0&&this.conversationEventContext.getStore()===n){const y=i(g[0]);y!==void 0&&o.add(y),s("hitl:confirmation-request",g[0])}},m=(...g)=>{const y=i(g[0]);y!==void 0&&o.has(y)&&(s("hitl:confirmation-response",g[0],y),o.delete(y))};return this.emitter.on("response:chunk",a),this.emitter.on("tool:start",u),this.emitter.on("tool:end",l),this.emitter.on("ui-component",d),this.emitter.on("host:conversation-event",c),this.emitter.on("hitl:confirmation-request",p),this.emitter.on("hitl:confirmation-response",m),{eventSequence:t,cleanup:()=>{this.emitter.off("response:chunk",a),this.emitter.off("tool:start",u),this.emitter.off("tool:end",l),this.emitter.off("ui-component",d),this.emitter.off("host:conversation-event",c),this.emitter.off("hitl:confirmation-request",p),this.emitter.off("hitl:confirmation-response",m)}}}async*handleStreamFallback(t,r,n,o,i,s){t.fallbackAttempted=!0;const a="Stream completed with 0 chunks (possible guardrails block)";t.error=a;try{const h=this._metricsTraceContext;let g=Ce.createGenerationSpan({provider:i,model:o.model||"unknown",name:`gen_ai.${i}.stream.failed`,traceId:h?.traceId,parentSpanId:h?.parentSpanId});g=Ce.endSpan(g,2),g.statusMessage=a,g.durationMs=0,this.metricsAggregator.recordSpan(g),nt().recordSpan(g)}catch{}const u=o.fallbackProvider?.trim()||void 0,l=o.fallbackModel?.trim()||void 0,c=process.env.FALLBACK_PROVIDER?.trim()||void 0,d=process.env.FALLBACK_MODEL?.trim()||void 0,p=k$.getFallbackRoute(n||o.input.text||"",{provider:i,model:o.model||"gpt-4o",reasoning:"primary failed",confidence:.5},{fallbackStrategy:"auto"}),m={...p,provider:u??c??p.provider,model:l??d??p.model};f.warn("Retrying with fallback provider",{originalProvider:i,fallbackProvider:m.provider,fallbackModel:m.model,fallbackSource:u||l?"options":c||d?"env":"model_config",reason:a});try{const h=await ao.createProvider(m.provider,m.model,!0,void 0,void 0,this.resolveCredentials(o.credentials));h.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(x,R)=>this.executeTool(x,R,{disableToolCache:o.disableToolCache})},"NeuroLink.fallbackStream");const g=o.conversationMessages!==void 0?o.conversationMessages:await zh(this.conversationMemory,{prompt:o.input.text,context:o.context});h.setFileToolRootPolicy?.(this.fileToolRootsFor(o));const y=await h.stream({...this.deferProviderStreamTTS(o),model:m.model,conversationMessages:g}),v=y.toolCalls??[],w=y.toolResults??[];(v.length>0||w.length>0)&&(r.toolCalls=v,r.toolResults=w,r.finishReason=y.finishReason??r.finishReason);let b=0,E=0;for await(const x of y.stream){b++;const R=x!==null&&typeof x=="object"&&"metadata"in x&&x.metadata?.noOutput===!0,C=x&&"content"in x&&typeof x.content=="string"&&x.content.length>0,P=x!==null&&typeof x=="object"&&"type"in x&&(x.type==="audio"||x.type==="tts_audio"||x.type==="image");!R&&(C||P)&&E++,x&&"content"in x&&typeof x.content=="string"&&(s(x.content),this.emitter.emit("response:chunk",x.content)),yield x}const k=y.toolCalls??[],A=y.toolResults??[];if(E===0&&k.length===0&&A.length===0)throw new Error(`Fallback provider ${m.provider} also returned 0 real output chunks (chunkCount=${b}, sentinel-only or empty)`);r.toolCalls=k,r.toolResults=A,r.finishReason=y.finishReason??r.finishReason,t.fallbackProvider=m.provider,t.fallbackModel=m.model,t.guardrailsBlocked=!0}catch(h){const g=h instanceof Error?h.message:String(h);throw t.error=`${a}; Fallback failed: ${g}`,f.error("Fallback provider failed",{fallbackProvider:m.provider,error:g}),h}}async storeStreamConversationMemory(t){const{enhancedOptions:r,providerName:n,originalPrompt:o,accumulatedContent:i,startTime:s,eventSequence:a,resultToolsUsed:u}=t;f.shouldLog("debug")&&f.debug("[NeuroLink.stream] Preparing to store conversation turn in memory",{options:rD(nD(r)),sessionId:r.context?.sessionId});const l=a.some(c=>c.type==="tool:start"||c.type==="tool:end");if(!i.trim()&&!l){f.warn("[NeuroLink.stream] Skipping conversation turn storage \u2014 no text content or tool activity",{sessionId:r.context?.sessionId});return}if(f.shouldLog("debug")&&f.debug("[NeuroLink.stream] Storing conversation turn in memory",{options:rD(nD(r)),sessionId:r.context?.sessionId,conversationMemoryExists:!!this.conversationMemory}),this.conversationMemory&&r.context?.sessionId){const c=r.context?.sessionId,d=r.context?.userId;let p;r.model&&(p={provider:n,model:r.model});const m=Date.now();try{const h=this.drainPendingSkillMessages(c);await this.conversationMemory.storeConversationTurn({sessionId:c,userId:d,userMessage:o??"",aiResponse:i,startTimeStamp:new Date(s),providerDetails:p,enableSummarization:r.enableSummarization,events:a.length>0?a:void 0,requestId:r.context?.requestId,...h.length>0?{skillMessages:h}:{},...r.modality?{modality:r.modality}:{}}),this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,1),f.debug("[NeuroLink.stream] Stored conversation turn with events",{sessionId:c,eventCount:a.length,eventTypes:[...new Set(a.map(g=>g.type))]})}catch(h){this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,2,h instanceof Error?h.message:String(h)),f.warn("Failed to store stream conversation turn",{error:h instanceof Error?h.message:String(h)})}}if(this.shouldWriteMemory(r.memory,r.context?.userId,i)){const c=r.context?.sessionId,d=[...new Set(u??[])];this.storeMemoryInBackground({prompt:o??"",response:i.trim(),userId:r.context?.userId,...typeof c=="string"?{sessionId:c}:{},provider:n,model:r.model,...d.length>0?{toolsUsed:d}:{}},r.memory,r.context)}}async validateStreamInput(t){const r=process.hrtime.bigint();f.debug("[NeuroLink] \u{1F3AF} LOG_POINT_003_VALIDATION_START",{logPoint:"003_VALIDATION_START",validationStartTimeNs:r.toString(),message:"Starting comprehensive input validation process"});const n=typeof t?.input?.text=="string"&&t.input.text.trim().length>0,o=!!(t?.input?.audio&&t.input.audio.frames&&typeof t.input.audio.frames[Symbol.asyncIterator]=="function"),i=!!(t?.stt?.enabled&&t?.stt?.audio);if(!n&&!o&&!i)throw new Error("Stream options must include either input.text, input.audio, or stt.audio")}emitStreamStartEvents(t,r){this.emitter.emit("stream:start",{provider:t.provider||"auto",timestamp:r}),this.emitter.emit("response:start"),this.emitter.emit("message",`Starting ${t.provider||"auto"} stream...`)}async createMCPStream(t){const r=t.provider&&t.provider!=="auto"?t.provider:this.getOrchestratedPreferredProvider(t),n=await r_(r),o=await ao.createProvider(n,t.model,!t.disableTools,this,t.region,this.resolveCredentials(t.credentials));await o.ensureModelLimits?.(),o.setTraceContext(this._metricsTraceContext),o.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(g,y)=>this.executeTool(g,y,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream");let i=await this.getAllAvailableTools();i=this.applyToolInfoFiltering(i,t),Sr.getDescriptor(n)?.toolSupport==="none"&&(i=[]);const s=t.skipToolPromptInjection?t.systemPrompt||"":this.createToolAwareSystemPrompt(t.systemPrompt,i,o.supportsTools?.()??!0),a=t.conversationMessages!==void 0,u=a?t.conversationMessages:await zh(this.conversationMemory,{...t,prompt:t.input.text,context:t.context});t.conversationMessages=u;let l=u;const c=Ea({provider:n,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,toolReplayMode:this.resolveToolReplayModeForBudget(t),conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:i,compactionThreshold:t.compactionThreshold}),d=l?.length||0,p=this.getCompactionSessionId(t),m=d>0;if(!c.withinBudget&&!m){try{this.emitter.emit("compaction.insufficient",{stagesAttempted:["pre-dispatch hard cap"],finalTokens:c.estimatedInputTokens,budget:c.availableInputTokens,provider:n,model:t.model,phase:"pre-dispatch-no-recovery",timestamp:Date.now()})}catch{}throw new Qa(`Stream context exceeds model budget and no compaction is possible (no conversationMemory, no inline conversationMessages \u2014 only prompt + tools). Estimated: ${c.estimatedInputTokens} tokens, budget: ${c.availableInputTokens} tokens. Reduce prompt or tool-definition size, or trim the request.`,{estimatedTokens:c.estimatedInputTokens,availableTokens:c.availableInputTokens,stagesUsed:[],breakdown:c.breakdown})}if(c.shouldCompact&&(a||this.conversationMemory)&&d>(this.lastCompactionMessageCount.get(p)??0)){const y=await new aT({provider:n,summarizationProvider:this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:this.conversationMemoryConfig?.conversationMemory?.summarizationModel},this.contextCompactorDeps(this.decisionSiteContext(t,p))).compact(l,fL(c,t.compactionThreshold),this.conversationMemoryConfig?.conversationMemory,t.context?.requestId,{currentRequest:t.input.text});y.compacted&&(l=Hb(y.messages).messages,t.conversationMessages=l,this.lastCompactionMessageCount.set(p,l.length));const v=Ea({provider:n,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,toolReplayMode:this.resolveToolReplayModeForBudget(t),conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:i});if(!v.withinBudget){f.warn("[NeuroLink] Stream: post-compaction still over budget, emergency truncation",{estimatedTokens:v.estimatedInputTokens,availableTokens:v.availableInputTokens,overagePercent:Math.round((v.usageRatio-1)*100)});try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:v.estimatedInputTokens,budget:v.availableInputTokens,provider:n,model:t.model,phase:"mid-compaction",willEmergencyTruncate:!0,timestamp:Date.now()})}catch{}l=aie(l,v.availableInputTokens,v.breakdown,n),t.conversationMessages=l;const w=Ea({provider:n,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,toolReplayMode:this.resolveToolReplayModeForBudget(t),conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:i});if(!w.withinBudget){this.lastCompactionMessageCount.delete(p);try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:w.estimatedInputTokens,budget:w.availableInputTokens,provider:n,model:t.model,phase:"post-emergency-truncation",timestamp:Date.now()})}catch{}throw new Qa(`Stream context exceeds model budget after all compaction stages. Estimated: ${w.estimatedInputTokens} tokens, Budget: ${w.availableInputTokens} tokens.`,{estimatedTokens:w.estimatedInputTokens,availableTokens:w.availableInputTokens,stagesUsed:y.stagesUsed,breakdown:w.breakdown})}}}if(this.modelPool){const g=this.modelPool,y=g.maxAttempts,v=new Set;let w=null;for(let b=0;b<y;b++){if(t.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError");const E=g.selectNext(v);if(!E)break;v.add(g.memberKey(E));const k=E.provider,A=E.model??void 0,x=E.region??void 0;f.debug(`[createMCPStream] ModelPool: attempting member ${k}`,{model:A,attempt:b});try{const R=await ao.createProvider(k,A,!t.disableTools,this,x,this.resolveCredentials(t.credentials));R.setTraceContext(this._metricsTraceContext),R.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(L,O)=>this.executeTool(L,O,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream"),R.setFileToolRootPolicy?.(this.fileToolRootsFor(t));const C=await R.stream({...this.deferProviderStreamTTS(t),provider:k,model:A,region:x,systemPrompt:s,conversationMessages:l});f.debug("[createMCPStream] ModelPool stream handle obtained",{provider:k});const P=E,D=(async function*(){try{yield*C.stream,g.recordSuccess(P)}catch(L){throw g.recordFailure(P,n_(L)),L}})();return Zb(C,{...C,stream:D,provider:k,model:C.model||A,toolCalls:C.toolCalls??[],toolResults:C.toolResults??[]})}catch(R){if(cr(R))throw R;if($he(R)){const C=R instanceof Error?R.message:String(R);throw g.recordFailure(E,n_(R)),new Error(`[ModelPool] non-retryable: ${C}`,{cause:R})}g.recordFailure(E,n_(R)),w=R instanceof Error?R:new Error(String(R)),f.warn(`[createMCPStream] ModelPool: member ${k} failed`,{error:w.message})}}throw new Error(`[ModelPool] all stream members failed: ${w?.message??"no stream members available"}`)}o.setFileToolRootPolicy?.(this.fileToolRootsFor(t));const h=await o.stream({...this.deferProviderStreamTTS(t),systemPrompt:s,conversationMessages:l});return f.debug("[createMCPStream] Stream created successfully",{provider:n,systemPromptPassedLength:s.length}),Zb(h,{...h,provider:n,model:h.model||t.model,toolCalls:h.toolCalls??[],toolResults:h.toolResults??[]})}async processStreamResult(t,r,n){return{content:"",usage:void 0,finishReason:"stop",toolCalls:[],toolResults:[],analytics:void 0,evaluation:void 0}}emitStreamEndEvents(t){this.emitter.emit("stream:end",{responseTime:Date.now(),timestamp:Date.now()}),this.emitter.emit("response:end",t.content||"")}createStreamResponse(t,r,n){const o=n.sourceResult,i={streamId:n.streamId,startTime:n.startTime,responseTime:n.responseTime,fallback:n.fallback||!1,guardrailsBlocked:n.guardrailsBlocked,error:n.error},s={...o??{},stream:r,provider:o?.provider??n.providerName,model:o?.model??n.options.model,usage:t.usage,finishReason:t.finishReason,analytics:t.analytics,evaluation:t.evaluation,events:n.events&&n.events.length>0?n.events:void 0,metadata:o?void 0:Object.assign({},i)},a=Object.getOwnPropertyDescriptor(t,"toolCalls");a&&Object.defineProperty(s,"toolCalls",a);const u=Object.getOwnPropertyDescriptor(t,"toolResults");u&&Object.defineProperty(s,"toolResults",u);const l=Object.getOwnPropertyDescriptor(t,"finishReason");if(l&&Object.defineProperty(s,"finishReason",l),!o)return s;const c=new Set(["finishReason","stopReason","rawFinishReason","toolCalls","toolResults"]);for(const d of Object.getOwnPropertyNames(o)){const p=Object.getOwnPropertyDescriptor(o,d);!c.has(d)&&p&&typeof p.get=="function"&&Object.defineProperty(s,d,p)}return Object.defineProperty(s,"metadata",{enumerable:!0,configurable:!0,get:()=>(o.metadata===void 0&&(o.metadata={}),Object.assign(o.metadata,i)),set:d=>{o.metadata=d}}),s}async handleStreamError(t,r,n,o,i,s){if(t instanceof Qa)throw t;f.error("Stream generation failed, attempting fallback",{error:t instanceof Error?t.message:String(t)});try{this.emitter.emit("stream:error",{content:t instanceof Error?t.message:String(t),metadata:{errorName:t instanceof Error?t.name:"UnknownError",durationMs:Date.now()-n,chunkCount:0},provider:r.provider||"unknown",model:r.model||"unknown"})}catch{}const a=r.input.text,u=Date.now()-n,l=await r_(r.provider),c=await ao.createProvider(l,r.model,!0,void 0,void 0,this.resolveCredentials(r.credentials));c.setFileToolRootPolicy?.(this.fileToolRootsFor(r));const d=await c.stream({input:{text:r.input.text},model:r.model,temperature:r.temperature,maxTokens:r.maxTokens,conversationMessages:r.conversationMessages});let p="";return{stream:(async function*(h){try{for await(const g of d.stream)g&&"content"in g&&typeof g.content=="string"&&(p+=g.content,h.emitter.emit("response:chunk",g.content)),yield g}finally{if(p.trim()){f.info("[NeuroLink.handleStreamError] stream() - COMPLETE SUCCESS (fallback)",{provider:l,model:r.model,responseTimeMs:Date.now()-n,contentLength:p.length});try{const g=r.model||"unknown",y=Date.now()-n;h.emitter.emit("stream:complete",{content:p,provider:l,model:g,finishReason:"stop",metadata:{durationMs:y,chunkCount:0,totalLength:p.length,isFallback:!0,finishReason:"stop"}}),h.emitter.emit("generation:end",{provider:l,model:g,responseTime:y,timestamp:Date.now(),result:{content:p,usage:{input:0,output:0,total:0},model:g,provider:l,finishReason:"stop"},success:!0,streamed:!0})}catch{}}if(h.conversationMemory&&i?.context?.sessionId&&p.trim()){const g=i?.context?.sessionId,y=i?.context?.userId;let v;r.model&&(v={provider:l,model:r.model});const w=Date.now();try{const b=g||r.context?.sessionId,E=h.drainPendingSkillMessages(b);await h.conversationMemory.storeConversationTurn({sessionId:b,userId:y||r.context?.userId,userMessage:a??"",aiResponse:p,startTimeStamp:new Date(n),providerDetails:v,enableSummarization:i?.enableSummarization,requestId:i?.context?.requestId||r.context?.requestId,...E.length>0?{skillMessages:E}:{}}),h.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-w,1)}catch(b){h.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-w,2,b instanceof Error?b.message:String(b)),f.warn("Failed to store fallback stream conversation turn",{error:b instanceof Error?b.message:String(b)})}}}})(this),provider:l,model:r.model,usage:d.usage,finishReason:d.finishReason||"stop",toolCalls:d.toolCalls||[],toolResults:d.toolResults||[],analytics:d.analytics,evaluation:d.evaluation,metadata:{streamId:o,startTime:n,responseTime:u,fallback:!0}}}getEventEmitter(){return this.emitter}hasPendingHITLConfirmation(t){return this.hitlManager?.hasPendingConfirmation(t)??!1}getToolDedupConfig(){return this.toolDedupConfig}fileToolRootsFor(t){return WX(t)??this.resolveFileToolRoots(t.toolRoots)}workerToolsConfig(t){const r=this.toolsConfig?.fileRoots;if(t?.fileRoots===void 0)return r===void 0?t:{...t,fileRoots:r};const n=lO({perCall:t.fileRoots,instance:r}).roots;return{...t,fileRoots:n?[...n]:[]}}resolveFileToolRoots(t){return lO({perCall:t,instance:this.toolsConfig?.fileRoots})}getToolsConfig(){return this.toolsConfig}getDiscoveryPins(t){const r=this.discoveryPins.get(t);return r?(this.discoveryPins.delete(t),this.discoveryPins.set(t,r),r):new Set}pinDiscoveredTools(t,r){let n=this.discoveryPins.get(t);n?this.discoveryPins.delete(t):n=new Set,this.discoveryPins.set(t,n);for(const o of r)n.add(o);if(this.discoveryPins.size>1e3){const o=this.discoveryPins.keys().next().value;o!==void 0&&this.discoveryPins.delete(o)}}async checkCredentials(t){const{provider:r,model:n}=t,o="ping";try{return await this.generate({provider:r,...n&&{model:n},input:{text:o},maxTokens:16,disableTools:!0}),{provider:r,status:"ok",detail:"credentials valid"}}catch(i){const s=i instanceof Error?i.message:String(i),a=s.toLowerCase();return i instanceof ww?{provider:r,status:"denied",detail:s}:a.includes("authentication")||a.includes("401")||a.includes("invalid api key")||a.includes("incorrect api key")||a.includes("api_key_invalid")||a.includes("token has expired")||a.includes("expired credentials")?{provider:r,status:"expired",detail:s}:a.includes("not configured")||a.includes("missing api")||a.includes("api key is required")||a.includes("no api key")||a.includes("application default credentials")||a.includes("google_application_credentials")||a.includes("project_id")||a.includes("default credentials")||a.includes("service account")?{provider:r,status:"missing",detail:s}:a.includes("econnrefused")||a.includes("enotfound")||a.includes("could not resolve")||a.includes("timeout")||a.includes("network")||a.includes("cannot connect")?{provider:r,status:"network",detail:s}:{provider:r,status:"unknown",detail:s}}}emitToolStart(t,r,n=Date.now()){const o=eWt(t,n),i={executionId:o,tool:t,startTime:n,metadata:{inputType:typeof r,hasInput:r!=null}};return this.activeToolExecutions.set(o,i),this.currentStreamToolExecutions.push(i),this.emitter.emit("tool:start",_C(t,{input:r,timestamp:n,executionId:o})),f.debug(`tool:start emitted for ${t}`,{toolName:t,executionId:o,timestamp:n,inputProvided:r!==void 0}),o}emitToolEnd(t,r,n,o,i=Date.now(),s){const a=o||i-1e3,u=i-a,l=!n;let c;s?c=this.activeToolExecutions.get(s):c=Array.from(this.activeToolExecutions.values()).find(m=>m.tool===t&&!m.endTime);const d=s||c?.executionId||`${t}-${a}-fallback-${Math.random().toString(36).substr(2,9)}`;c&&(c.endTime=i,c.result=r,c.error=n,this.activeToolExecutions.delete(c.executionId));const p={tool:t,startTime:a,endTime:i,duration:u,success:l,result:r,error:n,executionId:d,metadata:{toolCategory:"custom"}};this.toolExecutionHistory.push(p),this.emitter.emit("tool:end",_C(t,{result:r,error:n,success:l,responseTime:u,timestamp:i,duration:u,executionId:d})),f.debug(`tool:end emitted for ${t}`,{toolName:t,executionId:d,duration:u,success:l,hasResult:r!==void 0,hasError:!!n})}getCurrentToolExecutions(){return[...this.currentStreamToolExecutions]}getToolExecutionHistory(){return[...this.toolExecutionHistory]}clearCurrentStreamExecutions(){this.currentStreamToolExecutions=[]}registerTool(t,r,n){this.invalidateToolCache(),this.emitter.emit("tools-register:start",{toolName:t,timestamp:Date.now()});try{if(!t||typeof t!="string")throw new Error("Invalid tool name");if(!r||typeof r!="object")throw new Error(`Invalid tool object provided for tool: ${t}`);if(typeof r.execute!="function")throw new Error(`Tool '${t}' must have an execute method.`);if(t.trim()==="")throw new Error("Tool name cannot be empty");if(t.length>100)throw new Error("Tool name is too long (maximum 100 characters)");if(/[\x00-\x1F\x7F]/.test(t))throw new Error("Tool name contains invalid control characters");const o={name:r.name||t,description:r.description||t,execute:r.execute,inputSchema:"parameters"in r&&r.parameters&&(KQ(r.parameters)||typeof r.parameters=="object")?r.parameters:r.inputSchema||{}};if(n?.timeout!==void 0&&n.timeout>0&&Number.isFinite(n.timeout)&&typeof o.execute=="function"){const s=o.execute,a=n.timeout,u=t;o.execute=async(...l)=>{const c=AbortSignal.timeout(a),d=l[1],p=d?.abortSignal,m=p?AbortSignal.any([p,c]):c,h={...d,abortSignal:m};return Promise.race([s(l[0],h),new Promise((g,y)=>{m.addEventListener("abort",()=>{c.aborted?y(ve.toolTimeout(u,a)):y(new DOMException("The operation was aborted","AbortError"))},{once:!0})})])}}const i=Ahn(t,o,n?.timeout,n?.maxRetries,n?.totalTimeoutMs);this.toolRegistry.registerServer(i),n?.cacheable===!1?this.uncacheableTools.add(t):this.uncacheableTools.delete(t),this.emitter.emit("tools-register:end",{toolName:t,success:!0,timestamp:Date.now(),timeoutMs:n?.timeout})}catch(o){throw f.error(`Failed to register tool ${t}:`,o),o}}setToolContext(t){this.toolExecutionContext={...t},f.debug("Tool execution context updated",{sessionId:t.sessionId,contextKeys:Object.keys(t),hasJuspayToken:!!t.juspayToken,hasShopId:!!t.shopId})}getToolContext(){return this.toolExecutionContext?{...this.toolExecutionContext}:void 0}clearToolContext(){this.toolExecutionContext=void 0,f.debug("Tool execution context cleared")}registerTools(t){if(Array.isArray(t))for(const{name:r,tool:n}of t)this.registerTool(r,n);else for(const[r,n]of Object.entries(t))this.registerTool(r,n)}unregisterTool(t){this.invalidateToolCache();const r=`custom-tool-${t}`,n=this.toolRegistry.unregisterServer(r);return n&&(this.uncacheableTools.delete(t),f.info(`Unregistered custom tool: ${t}`)),n}useToolMiddleware(t){return this.mcpToolMiddlewares.push(t),f.debug(`[NeuroLink] Registered tool middleware (total: ${this.mcpToolMiddlewares.length})`),this}getToolMiddlewares(){return[...this.mcpToolMiddlewares]}async flushToolBatch(){this.mcpToolBatcher&&await this.mcpToolBatcher.flush()}getMCPEnhancementsConfig(){return this.mcpEnhancementsConfig}async updateAgenticLoopReport(t,r,n){if(!this.conversationMemory)throw new Eu("Conversation memory is not initialized. Enable conversationMemory in NeuroLink options.","CONFIG_ERROR");if(!("updateAgenticLoopReport"in this.conversationMemory)||typeof this.conversationMemory.updateAgenticLoopReport!="function")throw new Eu("updateAgenticLoopReport is only supported with Redis conversation memory.","CONFIG_ERROR");await Ge(this.conversationMemory.updateAgenticLoopReport(t,n,r),5e3)}getCustomTools(){const t=this.toolRegistry.getToolsByCategory(Sa({isCustomTool:!0})),r=new Map;for(const o of t){const i=o.inputSchema||o.parameters;f.debug("Processing tool schema for Claude",{toolName:o.name,hasDescription:!!o.description,description:o.description,hasParameters:!!o.parameters,parametersType:typeof o.parameters,parametersKeys:o.parameters&&typeof o.parameters=="object"?Object.keys(o.parameters):"NOT_OBJECT",hasInputSchema:!!o.inputSchema,inputSchemaType:typeof o.inputSchema,inputSchemaKeys:o.inputSchema&&typeof o.inputSchema=="object"?Object.keys(o.inputSchema):"NOT_OBJECT",hasEffectiveSchema:!!i,effectiveSchemaType:typeof i,effectiveSchemaHasProperties:!!i?.properties,effectiveSchemaHasRequired:!!i?.required,originalInputSchema:o.inputSchema,phase:"AFTER_SCHEMA_FIX",timestamp:Date.now()}),r.set(o.name,{name:o.name,description:o.description||"",inputSchema:typeof o.inputSchema=="object"&&o.inputSchema!==null?o.inputSchema:typeof o.parameters=="object"&&o.parameters!==null?o.parameters:{},execute:async(s,a)=>{const u=this.toolExecutionContext||{},l=a&&ar(a)?a:{},c={...u,...l,sessionId:l.sessionId||u.sessionId||`fallback-${Date.now()}`};return f.debug("Tool execution context merged",{toolName:o.name,storedContextKeys:Object.keys(u),runtimeContextKeys:Object.keys(l),finalContextKeys:Object.keys(c),hasJuspayToken:!!c.juspayToken,hasShopId:!!c.shopId,sessionId:c.sessionId}),await this.toolRegistry.executeTool(o.name,s,c)}})}this.cachedFileTools||(this.cachedFileTools=yXt(this.fileRegistry));const n=this.cachedFileTools;for(const[o,i]of Object.entries(n))if(!r.has(o)){const s=i,a=s.inputSchema??s.parameters;r.set(o,{name:o,description:i.description||`File tool: ${o}`,inputSchema:typeof a=="object"&&a!==null?a:{type:"object",properties:{}},execute:async u=>await i.execute(u,{toolCallId:`file-tool-${Date.now()}`,messages:[]})})}return r}async addInMemoryMCPServer(t,r){this.invalidateToolCache();try{le.debug(`[NeuroLink] Registering in-memory MCP server: ${t}`),r.tools||(r.tools=[]),await this.toolRegistry.registerServer(r),le.info(`[NeuroLink] Successfully registered in-memory server: ${t}`,{category:r.metadata?.category,provider:r.metadata?.provider,version:r.metadata?.version})}catch(n){throw le.error(`[NeuroLink] Failed to register in-memory server ${t}:`,n),n}}getInMemoryServers(){const t=this.getInMemoryServerInfos(),r=new Map;for(const n of t)r.set(n.id,n);return r}getInMemoryServerInfos(){return this.toolRegistry.getBuiltInServerInfos().filter(r=>Sa({existingCategory:r.metadata?.category,serverId:r.id})==="in-memory")}getAutoDiscoveredServerInfos(){return this.autoDiscoveredServerInfos}async executeTool(t,r={},n){if(this.mcpToolBatcher&&!n?.bypassBatcher)return this.mcpToolBatcher.execute(t,r);const o=this.createToolExecutionContext(t,r,n);return Be.mcp.startActiveSpan(t,{attributes:{"tool.name":t,"tool.type":o.toolType,"tool.input_size":o.inputSize}},i=>(no(i,"tool",{input:r}),this.executeToolWithSpan(t,r,n,o,i)))}createToolExecutionContext(t,r,n){const o=this.externalServerManager.getAllTools().find(l=>l.name===t),i=o?"mcp":this.getCustomTools().has(t)?"custom":"external",s=r?Aw(r):"",a=Date.now(),u=`${t}-${a}-${Math.random().toString(36).slice(2,11)}`;return{functionTag:"NeuroLink.executeTool",executionStartTime:a,executionId:u,externalTool:o,toolType:i,inputSize:s.length,options:n,hitlState:{triggered:!1}}}async executeToolWithSpan(t,r,n,o,i){try{const s=await this.prepareToolExecutionState(t,r,n,o),a=await this.runPreparedToolExecution(t,r,s,o,i),u=ar(a)&&"isError"in a&&a.isError===!0;return no(i,"tool",{output:a,...u&&{level:"ERROR",statusMessage:C6(a)}}),a}catch(s){const a=s instanceof Error?s.message:String(s);throw no(i,"tool",{level:"ERROR",statusMessage:a}),s instanceof Me||(i.recordException(s instanceof Error?s:new Error(a)),i.setStatus({code:qe.ERROR,message:a})),s}finally{i.end()}}async prepareToolExecutionState(t,r,n,o){f.debug(`[${o.functionTag}] Tool execution requested:`,{toolName:t,params:ar(r)?cct(r):r,hasExternalManager:!!this.externalServerManager}),f.debug("Tool execution detailed analysis",{toolName:t,executionStartTime:o.executionStartTime,paramsAnalysis:{type:typeof r,isNull:r===null,isUndefined:r===void 0,isEmpty:r&&typeof r=="object"&&Object.keys(r).length===0,keys:r&&typeof r=="object"?Object.keys(r):"NOT_OBJECT",keysLength:r&&typeof r=="object"?Object.keys(r).length:0},isTargetTool:t==="juspay-analytics_SuccessRateSRByTime",options:n,hasExternalManager:!!this.externalServerManager}),this.emitter.emit("tool:start",_C(t,{timestamp:o.executionStartTime,input:r,executionId:o.executionId}));const i=this.toolRegistry.getToolInfo(t),s=n?.timeout??i?.tool?.timeoutMs??dl.EXECUTION_BATCH_MS,a=n?.maxRetries??i?.tool?.maxRetries??Ci.DEFAULT,u=n?.retryDelayMs||lo.BASE_MS,l={timeout:s,maxRetries:a,totalTimeout:n?.totalTimeoutMs??i?.tool?.totalTimeoutMs??s*(a+1)+u*a,retryDelayMs:u,authContext:n?.authContext,disableToolCache:n?.disableToolCache},{MemoryManager:c}=await Promise.resolve().then(()=>(yI(),s_)),d=c.getMemoryUsageMB(),m=`${o.externalTool?.serverId||i?.tool?.serverId||"unknown"}.${t}`;let h=this.toolCircuitBreakers.get(m);h||(h=new Z2(N2.FAILURE_THRESHOLD,vV),this.toolCircuitBreakers.set(m,h));let g=this.toolExecutionMetrics.get(t);return g||(g={totalExecutions:0,successfulExecutions:0,failedExecutions:0,averageExecutionTime:0,lastExecutionTime:0,errorCategories:{}},this.toolExecutionMetrics.set(t,g)),g.totalExecutions++,{finalOptions:l,startMemory:d,circuitBreaker:h,breakerKey:m,metrics:g}}async runPreparedToolExecution(t,r,n,o,i){let s=0;try{le.debug(`[${o.functionTag}] Executing tool: ${t}`,{toolName:t,params:r,options:n.finalOptions,circuitBreakerState:n.circuitBreaker.getState()});const a=n.finalOptions.maxRetries+1,u=n.finalOptions.totalTimeout,l=Date.now(),c=l+u;let d=0;const p=await n.circuitBreaker.execute(async()=>u4e(async()=>{d++;const m=c-Date.now();if(m<=0)throw ve.toolTimeout(t,u,void 0,{attempt:d,maxAttempts:a,attemptTimeoutMs:n.finalOptions.timeout,totalTimeoutMs:u,elapsedMs:Date.now()-l,exhausted:!0});const h=Math.min(n.finalOptions.timeout,m);return Ge(this.executeToolInternal(t,r,n.finalOptions,o.hitlState),h,ve.toolTimeout(t,h,void 0,{attempt:d,maxAttempts:a,attemptTimeoutMs:n.finalOptions.timeout,totalTimeoutMs:u,elapsedMs:Date.now()-l}))},{maxAttempts:a,delayMs:n.finalOptions.retryDelayMs,isRetriable:m=>Date.now()+n.finalOptions.retryDelayMs<c&&UV(m),onRetry:(m,h)=>{s=m,le.warn(`[${o.functionTag}] Retrying tool execution (attempt ${m})`,{toolName:t,error:h.message,attempt:m})}}));return i.setAttribute("tool.retry_count",s),await this.handleSuccessfulToolExecution(t,p,n,o,i)}catch(a){return i.setAttribute("tool.retry_count",s),this.handleFailedToolExecution(t,r,a,n,o,i)}}async handleSuccessfulToolExecution(t,r,n,o,i){const s=Date.now()-o.executionStartTime;n.metrics.successfulExecutions++,n.metrics.lastExecutionTime=s,n.metrics.averageExecutionTime=(n.metrics.averageExecutionTime*(n.metrics.successfulExecutions-1)+s)/n.metrics.successfulExecutions;const{MemoryManager:a}=await Promise.resolve().then(()=>(yI(),s_)),l=a.getMemoryUsageMB().heapUsed-n.startMemory.heapUsed;l>20&&le.warn(`Tool '${t}' used excessive memory: ${l}MB`,{toolName:t,memoryDelta:l,executionTime:s}),le.debug(`[${o.functionTag}] Tool executed successfully`,{toolName:t,executionTime:s,memoryDelta:l,circuitBreakerState:n.circuitBreaker.getState()});const c=r&&typeof r=="object"?r:void 0,d=c&&"isError"in c&&c.isError===!0||c&&"success"in c&&c.success===!1,p=d?c?.content:void 0,m=d?p?.filter(h=>h.type==="text"&&h.text).map(h=>h.text).join(" ")||(typeof c?.error=="string"?c.error:"Unknown error"):void 0;if(d){try{await n.circuitBreaker.execute(async()=>{throw new Error(`Tool ${t} returned isError:true`)})}catch{}le.debug(`[${o.functionTag}] Circuit breaker failure recorded for isError result`,{toolName:t,circuitBreakerState:n.circuitBreaker.getState(),circuitBreakerFailures:n.circuitBreaker.getFailureCount()});const h=$kn(m??"Unknown error"),g=`[TOOL_ERROR: ${t} failed (${h})] `;if(c&&Array.isArray(p)){const w=p.map(b=>({...b}));for(const b of w)if(b.type==="text"&&b.text){b.text=g+b.text;break}c.content=w}i.setAttribute("tool.error.message",(m??"Unknown error").substring(0,500)),i.setAttribute("tool.error.category",h),i.setStatus({code:qe.ERROR,message:`MCP tool returned isError: ${(m??"Unknown error").substring(0,200)}`}),n.metrics.failedExecutions++;const y=n.metrics.successfulExecutions;n.metrics.successfulExecutions=Math.max(0,n.metrics.successfulExecutions-1),n.metrics.averageExecutionTime=y>1?(n.metrics.averageExecutionTime*y-s)/(y-1):0;const v=Fkn(h);n.metrics.errorCategories[v]=(n.metrics.errorCategories[v]||0)+1}return this.emitToolEndEvent(t,o.executionStartTime,!d,r,d&&m?new Error(m):void 0,o.executionId),i.setAttribute("tool.result.status",d?"error":"success"),i.setAttribute("tool.duration_ms",s),r}async handleFailedToolExecution(t,r,n,o,i,s){o.metrics.failedExecutions++;const a=Date.now()-i.executionStartTime;if(n instanceof Km)return le.warn(`[${i.functionTag}] Tool blocked by circuit breaker: ${t}`,{toolName:t,breakerState:n.breakerState,retryAfter:n.retryAfter,retryAfterMs:n.retryAfterMs,failureCount:n.failureCount,executionTime:a}),o.metrics.errorCategories.execution=(o.metrics.errorCategories.execution||0)+1,this.emitToolEndEvent(t,i.executionStartTime,!1,void 0,new Error(`Circuit breaker open for ${t} (state=${n.breakerState}, failures=${n.failureCount})`),i.executionId),s.setAttribute("tool.result.status","circuit_breaker_open"),s.setAttribute("tool.duration_ms",a),s.setAttribute("tool.circuit_breaker.state",n.breakerState),s.setAttribute("tool.circuit_breaker.retry_after_ms",n.retryAfterMs),s.setAttribute("tool.circuit_breaker.failure_count",n.failureCount),s.setStatus({code:qe.ERROR,message:`Circuit breaker open for ${t}: ${n.message}`}),{isError:!0,content:[{type:"text",text:`TOOL TEMPORARILY UNAVAILABLE: "${t}" has been disabled after ${n.failureCount} failures. This is a circuit breaker protection \u2014 do NOT retry this tool. It will become available again after ${Math.ceil(n.retryAfterMs/1e3)} seconds (at ${n.retryAfter}). Instead, inform the user that the operation failed and suggest trying again later.`}]};let u;if(n instanceof Me)u=n;else if(n instanceof Error)if(n.message.includes("timeout"))u=ve.toolTimeout(t,o.finalOptions.timeout);else if(n.message.includes("not found")){const c=await this.getAllAvailableTools();u=ve.toolNotFound(t,lnn(c.map(d=>({name:d.name}))))}else n.message.includes("validation")||n.message.includes("parameter")?u=ve.invalidParameters(t,n,r):n.message.includes("network")||n.message.includes("connection")?u=ve.networkError(t,n):u=ve.toolExecutionFailed(t,n);else u=ve.toolExecutionFailed(t,new Error(String(n)));const l=u.category||"execution";throw o.metrics.errorCategories[l]=(o.metrics.errorCategories[l]||0)+1,this.emitToolEndEvent(t,i.executionStartTime,!1,void 0,u,i.executionId),this.emitter.listenerCount("error")>0&&this.emitter.emit("error",u),u=new Me({...u,context:{...u.context,executionTime:a,params:r,options:o.finalOptions,circuitBreakerState:o.circuitBreaker.getState(),circuitBreakerFailures:o.circuitBreaker.getFailureCount(),metrics:{...o.metrics}}}),l4e(u),s.setAttribute("tool.result.status","error"),s.setAttribute("tool.duration_ms",a),s.recordException(u),s.setStatus({code:qe.ERROR,message:u.message}),u}toolCacheRepeatKey(t,r){try{return`${t}:${JSON.stringify(r)??""}`}catch{return}}async executeToolInternal(t,r,n,o){const i="NeuroLink.executeToolInternal",s=this.getToolAnnotationsForExecution(t),a=this.mcpToolResultCache&&!n.disableToolCache&&!this._disableToolCacheForCurrentRequest&&!this.uncacheableTools.has(t)&&!s?.destructiveHint,u=this.mcpToolResultCache,l=n.authContext||this.toolExecutionContext?{__args:r,__ctx:n.authContext??this.toolExecutionContext}:r,c=this._generationTurnActive?this.toolCacheRepeatKey(t,l):void 0,d=c!==void 0&&this._toolCacheKeysServedThisRequest.has(c);if(c!==void 0&&this._toolCacheKeysServedThisRequest.add(c),a&&u&&!d){const h=u.getCachedResult(t,l);if(h!==void 0)return f.debug(`[${i}] Cache HIT for tool: ${t}`),h}else d&&f.debug(`[${i}] Repeat call within this request \u2014 bypassing tool cache for: ${t}`);const p=async h=>{if(this.mcpToolMiddlewares.length===0)return h();let g=0;const y=async()=>{if(g<this.mcpToolMiddlewares.length){const v=this.mcpToolMiddlewares[g++];return v({name:t,description:"",inputSchema:{},annotations:s,execute:async()=>({})},r,{toolMeta:{name:t,annotations:s}},y)}return h()};return await y()},m=async()=>{const h=this.externalServerManager.getAllTools(),g=h.filter(v=>v.name===t&&v.isAvailable);let y;if(g.length>1&&this.mcpToolRouter)try{const v={name:t,description:g[0].description??"",serverId:g[0].serverId,inputSchema:{}},w=this.mcpToolRouter.route(v);y=g.find(b=>b.serverId===w.serverId)||g[0],f.debug(`[${i}] Router selected server: ${w.serverId}`,{strategy:w.strategy,confidence:w.confidence})}catch(v){f.warn(`[${i}] Router failed, falling back to first match`,{error:v}),y=g[0]}else y=g[0];if(f.debug(`[${i}] External MCP tool search:`,{toolName:t,externalToolsCount:h.length,foundTool:!!y,isAvailable:y?.isAvailable,serverId:y?.serverId}),y&&y.isAvailable)try{le.debug(`[${i}] Executing external MCP tool: ${t} from ${y.serverId}`);const v=await this.externalServerManager.executeTool(y.serverId,t,r,{timeout:n.timeout});return f.debug(`[${i}] External MCP tool execution successful:`,{toolName:t,serverId:y.serverId,resultType:typeof v}),v}catch(v){throw f.error(`[${i}] External MCP tool execution failed:`,{toolName:t,serverId:y.serverId,error:v instanceof Error?v.message:String(v)}),ve.toolExecutionFailed(t,v instanceof Error?v:new Error(String(v)),y.serverId)}try{const v=this.toolExecutionContext||{},w=n.authContext||{},b=gA({...v,...w,hitlState:o},this.resolveFileToolRoots(void 0));f.debug("[Using merged context for unified registry tool:",{toolName:t,storedContextKeys:Object.keys(v),finalContextKeys:Object.keys(b)});const E=await this.toolRegistry.executeTool(t,r,b);if(E&&typeof E=="object"&&"success"in E&&E.success===!1){const k=E.error||"Tool execution failed",A=new Error(k);this.emitter.listenerCount("error")>0&&this.emitter.emit("error",A)}return E}catch(v){const w=v instanceof Error?v:new Error(String(v));if(this.emitter.listenerCount("error")>0&&this.emitter.emit("error",w),v instanceof Error&&v.message.includes("not found")){const b=await this.getAllAvailableTools();throw ve.toolNotFound(t,b.map(E=>E.name))}throw ve.toolExecutionFailed(t,v instanceof Error?v:new Error(String(v)))}};try{const h=await p(m);return a&&u&&h!==void 0&&(u.cacheResult(t,l,h),f.debug(`[${i}] Cached result for tool: ${t}`)),h}catch(h){const g=s?{name:t,description:"",annotations:s,execute:async()=>({})}:void 0;if(g&&tse(g)&&h instanceof Error&&UV(h)){f.debug(`[${i}] Tool ${t} is safe to retry, attempting once more`);try{const y=await p(m);return a&&u&&y!==void 0&&u.cacheResult(t,l,y),y}catch{}}throw h}}getToolAnnotationsForExecution(t){if(this.toolCache?.tools){const r=this.toolCache.tools.find(n=>n.name===t);if(r?.annotations)return r.annotations}if(this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)return Vp({name:t,description:""})}invalidateToolCache(){this.toolCache=null,f.debug("Tool cache invalidated")}async getAllAvailableTools(){if(this.toolCache&&Date.now()-this.toolCache.timestamp<this.toolCacheDuration)return f.debug("Returning available tools from cache"),this.toolCache.tools;const t=`get-all-tools-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,r=Date.now(),n=process.hrtime.bigint();f.debug("[NeuroLink] \u{1F6E0}\uFE0F LOG_POINT_A001_GET_ALL_TOOLS_START",{logPoint:"A001_GET_ALL_TOOLS_START",getAllToolsId:t,timestamp:new Date().toISOString(),getAllToolsStartTime:r,getAllToolsHrTimeStart:n.toString(),toolRegistryState:{hasToolRegistry:!!this.toolRegistry,toolRegistrySize:0,toolRegistryType:this.toolRegistry?.constructor?.name||"NOT_SET",hasExternalServerManager:!!this.externalServerManager,externalServerManagerType:this.externalServerManager?.constructor?.name||"NOT_SET"},mcpState:{mcpInitialized:this.mcpInitialized,hasProviderRegistry:!!ao,providerRegistrySize:0},message:"Starting comprehensive tool discovery across all sources"});const{MemoryManager:o}=await Promise.resolve().then(()=>(yI(),s_)),i=o.getMemoryUsageMB();try{const s=new Map,a=await this.toolRegistry.listTools();for(const g of a)if(!s.has(g.name)){const y=_N(g,{serverId:g.serverId==="direct"?"neurolink-direct":g.serverId});s.set(g.name,y)}const u=this.toolRegistry.getToolsByCategory(Sa({isCustomTool:!0}));for(const g of u)if(!s.has(g.name)){const y=_N(g,{description:"Custom tool",serverId:`custom-tool-${g.name}`,category:Sa({isCustomTool:!0,serverId:g.serverId}),inputSchema:{}});s.set(g.name,y)}const l=this.toolRegistry.getToolsByCategory("in-memory");for(const g of l)if(!s.has(g.name)){const y=_N(g,{description:"In-memory MCP tool",serverId:"unknown",category:"in-memory",inputSchema:{}});s.set(g.name,y)}const c=this.externalServerManager.getAllTools();for(const g of c)if(!s.has(g.name)){const y=_N(g,{category:Sa({existingCategory:typeof g.metadata?.category=="string"?g.metadata.category:void 0,isExternal:!0,serverId:g.serverId}),inputSchema:{}});s.set(g.name,y)}const d=Array.from(s.values());le.debug("Tool discovery results",{mcpTools:a.length,customTools:u.length,inMemoryTools:l.length,externalMCPTools:c.length,total:d.length});const m=o.getMemoryUsageMB().heapUsed-i.heapUsed;if(m>Xm.LOW_USAGE_MB&&(le.debug(`\u{1F50D} Tool listing used ${m}MB memory (large tool registry detected)`),d.length>xRe.LARGE_TOOL_COLLECTION&&le.debug("\u{1F4A1} Tool collection optimized for large sets. Memory usage reduced through efficient object reuse.")),this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)for(const g of d)g.annotations||(g.annotations=Vp({name:g.name,description:g.description||""}));const h=d.sort((g,y)=>g.name<y.name?-1:g.name>y.name?1:0);return this.toolCache={tools:h,timestamp:Date.now()},h}catch(s){return le.error("Failed to list available tools",{error:s}),[]}}async getProviderStatus(t){const{MemoryManager:r}=await Promise.resolve().then(()=>(yI(),s_)),n=r.getMemoryUsageMB();t?.quiet||le.debug("\u{1F50D} DEBUG: Initializing MCP for provider status..."),await this.initializeMCP(),t?.quiet||le.debug("\u{1F50D} DEBUG: MCP initialized:",this.mcpInitialized);const{AIProviderFactory:o}=await Promise.resolve().then(()=>(lu(),fR)),{hasProviderEnvVars:i}=await Promise.resolve().then(()=>(lf(),hI)),s=Sr.getAllDescriptors().map(p=>p.name),a=y0(ja.DEFAULT_CONCURRENCY_LIMIT),u=s.map(p=>a(async()=>{const m=Date.now();try{if(!await this.hasProviderEnvVars(p)&&p!=="ollama")return{provider:p,status:"not-configured",configured:!1,authenticated:!1,error:"Missing required environment variables",responseTime:Date.now()-m};if(p==="bedrock"||p==="sagemaker")return{provider:p,status:"not-configured",configured:!0,authenticated:!1,error:`Live status check is skipped for ${p}`,responseTime:Date.now()-m};if(p==="ollama"){let E,k="not-run";try{const A=CC(),x=IC(A);if(x.kind==="suppressed")throw new Error(x.reason);E=x,k="transport-failure";const R=await fetch(A.url,{method:"GET",signal:AbortSignal.timeout(pl.AUTH_MS)});if(!R.ok)throw new Error("Ollama service not responding");k="protocol-failure";const C=await R.json(),P=C?.models;if(!Array.isArray(P))throw f.warn("Ollama API returned invalid models format in testProvider",{responseData:C,modelsType:typeof P}),new Error("Invalid models format from Ollama API");k="success";const D=P.filter(L=>L&&typeof L=="object"&&typeof L.name=="string");return D.length>0?{provider:p,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-m,model:D[0].name}:{provider:p,status:"failed",configured:!0,authenticated:!1,error:"Ollama service running but no models installed",responseTime:Date.now()-m}}catch(A){return{provider:p,status:"failed",configured:!1,authenticated:!1,error:A instanceof Error?rT(A):"Ollama service not running",responseTime:Date.now()-m}}finally{E&&nT(E,k)}}const g=5e3,y=new AbortController,v=this.testProviderConnection(p,y.signal);let w;const b=new Promise((E,k)=>{w=setTimeout(()=>{k(new Error("Provider test timeout (5s)"))},g)});try{await Promise.race([v,b])}finally{clearTimeout(w),v.catch(()=>{}),y.abort()}return{provider:p,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-m}}catch(h){const g=h instanceof Error?h.message:String(h);return{provider:p,status:"failed",configured:!0,authenticated:!1,error:g,responseTime:Date.now()-m}}})),l=await Promise.all(u),d=r.getMemoryUsageMB().heapUsed-n.heapUsed;return!t?.quiet&&d>20&&le.debug(`\u{1F50D} Memory usage: +${d}MB (consider cleanup for large operations)`),d>50&&r.forceGC(),l}async testProvider(t){try{return await this.testProviderConnection(t),!0}catch{return!1}}async testProviderConnection(t,r){const{AIProviderFactory:n}=await Promise.resolve().then(()=>(lu(),fR));await(await n.createProvider(t,null)).generate({prompt:"test",maxTokens:1,disableTools:!0,abortSignal:r})}async getBestProvider(t){const{getBestProvider:r}=await Promise.resolve().then(()=>(lf(),hI));return r(t)}async getAvailableProviders(){const{getAvailableProviders:t}=await Promise.resolve().then(()=>(lf(),hI));return t()}async isValidProvider(t){const{isValidProvider:r}=await Promise.resolve().then(()=>(lf(),hI));return r(t)}async getMCPStatus(){try{await this.initializeMCP();const t=await this.toolRegistry.listTools(),r=this.externalServerManager.getStatistics(),n=this.externalServerManager.listServers(),o=this.getInMemoryServerInfos(),i=this.toolRegistry.getBuiltInServerInfos(),s=this.getAutoDiscoveredServerInfos(),a=n.length+o.length+i.length+s.length,u=r.connectedServers+o.length+i.length,l=t.length+r.totalTools;return{mcpInitialized:this.mcpInitialized,totalServers:a,availableServers:u,autoDiscoveredCount:s.length,totalTools:l,autoDiscoveredServers:s,customToolsCount:this.toolRegistry.getToolsByCategory(Sa({isCustomTool:!0})).length,inMemoryServersCount:o.length,externalMCPServersCount:n.length,externalMCPConnectedCount:r.connectedServers,externalMCPFailedCount:r.failedServers,externalMCPServers:n}}catch(t){return{mcpInitialized:!1,totalServers:0,availableServers:0,autoDiscoveredCount:0,totalTools:0,autoDiscoveredServers:[],customToolsCount:this.toolRegistry.getToolsByCategory(Sa({isCustomTool:!0})).length,inMemoryServersCount:0,externalMCPServersCount:0,externalMCPConnectedCount:0,externalMCPFailedCount:0,externalMCPServers:[],error:t instanceof Error?t.message:String(t)}}}async listMCPServers(){return[...this.externalServerManager.listServers(),...this.getInMemoryServerInfos(),...this.toolRegistry.getBuiltInServerInfos(),...this.getAutoDiscoveredServerInfos()]}async testMCPServer(t){try{if(t==="neurolink-direct")return(await this.toolRegistry.listTools()).length>0;const r=this.getInMemoryServers();if(r.has(t)){const o=r.get(t);return!!(o?.tools&&o.tools.length>0)}const n=this.externalServerManager.getServer(t);return n?n.status==="connected"&&n.client!==null:!1}catch(r){return le.error(`[NeuroLink] Error testing MCP server ${t}:`,r),!1}}async hasProviderEnvVars(t){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(Py(),e_));try{const n=await r.checkProviderHealth(t,{includeConnectivityTest:!1,cacheResults:!1});return n.isConfigured&&n.hasApiKey}catch(n){return f.warn(`Provider env var check failed for ${t}`,{error:n instanceof Error?n.message:String(n)}),!1}}async checkProviderHealth(t,r={}){const{ProviderHealthChecker:n}=await Promise.resolve().then(()=>(Py(),e_)),o=await n.checkProviderHealth(t,r);return{provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}}async checkAllProvidersHealth(t={}){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(Py(),e_));return(await r.checkAllProvidersHealth(t)).map(o=>({provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}))}async getProviderHealthSummary(){const{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(Py(),e_)),r=await t.checkAllProvidersHealth({cacheResults:!0,includeConnectivityTest:!1}),n=t.getHealthSummary(r),o=[];return n.healthy===0?o.push("No providers are healthy. Check your environment configuration."):n.healthy<2&&o.push("Consider configuring additional providers for better reliability."),n.hasIssues>0&&o.push("Some providers have configuration issues. Run checkAllProvidersHealth() for details."),{...n,recommendations:o}}async clearProviderHealthCache(t){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(Py(),e_));r.clearHealthCache(t)}getToolExecutionMetrics(){const t={};for(const[r,n]of this.toolExecutionMetrics.entries())t[r]={...n,errorCategories:{...n.errorCategories},successRate:n.totalExecutions>0?n.successfulExecutions/n.totalExecutions:0};return t}setModelAliasConfig(t){this.modelAliasConfig=t,f.info(`[ModelAlias] Configured ${Object.keys(t.aliases).length} model aliases`)}getToolCircuitBreakerStatus(){const t={};for(const[r,n]of this.toolCircuitBreakers.entries())t[r]={state:n.getState(),failureCount:n.getFailureCount(),isHealthy:n.getState()==="closed"};return t}resetToolCircuitBreaker(t){this.toolCircuitBreakers.has(t)&&(this.toolCircuitBreakers.set(t,new Z2(N2.FAILURE_THRESHOLD,vV)),le.info(`Circuit breaker reset for tool: ${t}`))}clearToolExecutionMetrics(){this.toolExecutionMetrics.clear(),le.info("All tool execution metrics cleared")}async getToolHealthReport(){const t={};let r=0;const n=await this.toolRegistry.listTools(),o=new Set(n.map(s=>s.name)),i=new Map;for(const s of n)i.has(s.name)||i.set(s.name,s.serverId||"unknown");for(const s of o){const a=this.toolExecutionMetrics.get(s),u=`${i.get(s)||"unknown"}.${s}`,l=this.toolCircuitBreakers.get(u),c=a&&a.totalExecutions>0?a.successfulExecutions/a.totalExecutions:0,d=(!l||l.getState()==="closed")&&c>=.8;d&&r++;const p=[],m=[];if(l&&l.getState()==="open"&&(p.push("Circuit breaker is open due to repeated failures"),m.push("Check tool implementation and fix underlying issues")),c<.8&&a&&a.totalExecutions>0&&(p.push(`Low success rate: ${(c*100).toFixed(1)}%`),m.push("Review error logs and improve tool reliability")),a&&a.averageExecutionTime>1e4&&(p.push("High average execution time"),m.push("Optimize tool performance or increase timeout")),a&&a.errorCategories){const h=a.errorCategories;h.timeout>0&&(p.push(`Timeout errors: ${h.timeout}`),m.push("Consider increasing the tool timeout configuration")),h.validation>0&&(p.push(`Validation errors: ${h.validation}`),m.push("Review input schemas and parameter validation")),h.network>0&&(p.push(`Network errors: ${h.network}`),m.push("Check network connectivity and endpoint availability"))}t[s]={name:s,isHealthy:d,metrics:{totalExecutions:a?.totalExecutions||0,successRate:c,averageExecutionTime:a?.averageExecutionTime||0,lastExecutionTime:a?.lastExecutionTime||0,errorCategories:a?.errorCategories?{...a.errorCategories}:{}},circuitBreaker:{state:l?.getState()||"closed",failureCount:l?.getFailureCount()||0},issues:p,recommendations:m}}return{totalTools:o.size,healthyTools:r,unhealthyTools:o.size-r,tools:t}}async ensureConversationMemoryInitialized(){try{const t=`manual-init-${Date.now()}`;return await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!!this.conversationMemory}catch(t){return f.error("Failed to initialize conversation memory",{error:t instanceof Error?t.message:String(t)}),!1}}async getConversationStats(){const t=`stats-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:He.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return await this.conversationMemory.getStats()}async getConversationHistory(t){const r=`history-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:He.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Me({code:He.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});try{const n=await this.conversationMemory.buildContextMessages(t);return f.debug("Retrieved conversation history",{sessionId:t,messageCount:n.length,turnCount:n.length/2}),n}catch(n){return f.error("Failed to retrieve conversation history",{sessionId:t,error:n instanceof Error?n.message:String(n)}),[]}}async clearConversationSession(t){const r=`clear-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:He.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return this.lastCompactionMessageCount.delete(t),await this.conversationMemory.clearSession(t)}async clearAllConversations(){const t=`clear-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:He.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});this.lastCompactionMessageCount.clear(),await this.conversationMemory.clearAllSessions()}async listSessions(t){const r=`list-sessions-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");if(!this.conversationMemory.listSessions)return f.warn("listSessions not available on current memory manager"),[];const n=3e4;try{const o=await Ge(this.conversationMemory.listSessions(t),n,new Error("listSessions operation timed out after 30s"));return f.debug("Listed conversation sessions",{userId:t,sessionCount:o.length}),o}catch(o){return f.error("Failed to list conversation sessions",{userId:t,error:o instanceof Error?o.message:String(o)}),[]}}async exportSession(t,r={}){const n=`export-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");if(!t||typeof t!="string")throw new Error("Session ID must be a non-empty string");const o=3e4;try{const i=await Ge(this.conversationMemory.buildContextMessages(t),o,new Error("buildContextMessages operation timed out after 30s"));if(i.length===0)return f.debug("No messages found for session export",{sessionId:t}),null;const s=this.conversationMemory.getSession(t),a=await Ge(s instanceof Promise?s:Promise.resolve(s),o,new Error("getSession operation timed out after 30s")),u=new Date().toISOString(),l={sessionId:t,title:t,userId:a?.userId,createdAt:a?.createdAt?new Date(a.createdAt).toISOString():u,updatedAt:a?.lastActivity?new Date(a.lastActivity).toISOString():u,messages:i};return r.includeMetadata&&(l.exportMetadata={exportedAt:u,exportFormat:r.format||"json"}),f.debug("Exported conversation session",{sessionId:t,messageCount:i.length}),l}catch(i){return f.error("Failed to export conversation session",{sessionId:t,error:i instanceof Error?i.message:String(i)}),null}}async exportAllSessions(t,r={}){const n=`export-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");const o=3e4,i=6e4;try{const s=await Ge(this.listSessions(t),o,new Error("listSessions operation timed out after 30s")),a=[];for(const u of s){const l=await Ge(this.exportSession(u.id,r),i,new Error(`exportSession operation timed out after 60s for session ${u.id}`));l&&a.push(l)}return f.debug("Exported all conversation sessions",{userId:t,sessionCount:a.length}),a}catch(s){return f.error("Failed to export all conversation sessions",{userId:t,error:s instanceof Error?s.message:String(s)}),[]}}async storeToolExecutions(t,r,n,o,i){const s=n&&n.length>0||o&&o.length>0;if(!s){f.debug("Tool execution storage skipped",{hasToolData:s,toolCallsCount:n?.length||0,toolResultsCount:o?.length||0});return}const a=this.conversationMemory;if(!a?.storeToolExecution){f.debug("Tool execution storage not supported by this memory backend");return}try{await a.storeToolExecution(t,r,n,o,i)}catch(u){f.warn("Failed to store tool executions",{sessionId:t,userId:r,error:u instanceof Error?u.message:String(u)})}}isToolExecutionStorageAvailable(){return typeof this.conversationMemory?.storeToolExecution=="function"}async getSessionMessages(t,r){const n=`get-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:He.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Me({code:He.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});return await this.conversationMemory.getSessionMessages(t,r)}async recordConversationTurn(t){const{sessionId:r,userId:n,turnId:o}=t;qf.assertConversationIdentity(r,n);const i={sessionId:r,userId:n,...o?{turnId:o}:{}};if(!t.userMessage.trim())return{recorded:!1,reason:"empty-user-message",...i};const s=(t.events??[]).some(u=>u.type==="tool:start"||u.type==="tool:end");if(!t.aiResponse.trim()&&!s)return{recorded:!1,reason:"empty-response",...i};if(await this.initializeConversationMemoryForGeneration(t.requestId??`record-turn-${Date.now()}`,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:He.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(await this.isOwnedByAnotherUser(r,n))throw new Me({code:He.INVALID_PARAMETERS,message:"The conversation belongs to another user",category:"validation",severity:"medium",retriable:!1});const a=Date.now();try{await this.conversationMemory.storeConversationTurn({sessionId:r,userId:n,userMessage:t.userMessage,aiResponse:t.aiResponse,startTimeStamp:t.startTime,...t.provider&&t.model?{providerDetails:{provider:t.provider,model:t.model}}:{},enableSummarization:t.enableSummarization,events:t.events?.length?t.events:void 0,requestId:t.requestId,...t.modality?{modality:t.modality}:{},...o?{turnId:o}:{},...t.interrupted?{interrupted:!0}:{},...t.callEnded?{callEnded:!0}:{}}),this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"record"},Date.now()-a,1)}catch(u){throw this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"record"},Date.now()-a,2,u instanceof Error?u.message:String(u)),u}return this.shouldWriteMemory(t.memory,n,t.aiResponse)&&this.storeMemoryInBackground({prompt:t.userMessage,response:t.aiResponse.trim(),userId:n,sessionId:r,provider:t.provider??"",model:t.model},t.memory,{sessionId:r}),{recorded:!0,...i}}async getConversationSeed(t){const{sessionId:r,userId:n}=t,o=Math.max(0,Math.floor(t.maxTurns??10)),i=Math.max(0,Math.floor(t.maxChars??6e3));try{qf.assertConversationIdentity(r,n);const s=await this.getSessionMessages(r,n),a=[];for(const d of s)d.role!=="user"&&d.role!=="assistant"||d.metadata?.isSummary||d.metadata?.isSkill||typeof d.content!="string"||!d.content.trim()||a.push({role:d.role,content:d.content,...d.metadata?.modality?{modality:d.metadata.modality}:{}});const u=a.slice(-(o*2));let l=0,c=u.length;for(let d=u.length-1;d>=0&&(l+=u[d].content.length,!(l>i));d-=1)c=d;return u.slice(c)}catch(s){return f.warn("[NeuroLink] getConversationSeed failed, starting unseeded",{error:s instanceof Error?s.message:String(s)}),[]}}async conversationExists(t){return qf.assertConversationIdentity(t.sessionId,t.userId),(await this.getSessionMessages(t.sessionId,t.userId)).length===0?!1:!await this.isOwnedByAnotherUser(t.sessionId,t.userId)}async isOwnedByAnotherUser(t,r){const n=this.conversationMemory;if(!n||n.isRedisConfigured)return!1;const o=await n.getSession(t);return o!==void 0&&o.userId!==r}static assertConversationIdentity(t,r){const n=typeof t!="string"||!t.trim()?"sessionId must be a non-empty string":t.includes(":")?'sessionId must not contain ":"':typeof r!="string"||!r.trim()?"userId must be a non-empty string":void 0;if(n)throw new Me({code:He.INVALID_PARAMETERS,message:n,category:"validation",severity:"medium",retriable:!1})}async setSessionMessages(t,r,n){const o=`set-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(o,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:He.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Me({code:He.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});await this.conversationMemory.setSessionMessages(t,r,n)}async modifyLastAssistantMessage(t,r,n){const o=await this.getSessionMessages(t,n);for(let i=o.length-1;i>=0;i--)if(o[i].role==="assistant")return o[i]={...o[i],content:r(o[i].content)},await this.setSessionMessages(t,o,n),!0;return!1}async addExternalMCPServer(t,r){this.invalidateToolCache();try{le.info(`[NeuroLink] Adding external MCP server: ${t}`,{command:r.command,transport:r.transport});const n=await this.externalServerManager.addServer(t,r);if(n.success){if(le.info(`[NeuroLink] External MCP server added successfully: ${t}`,{toolsDiscovered:n.metadata?.toolsDiscovered||0,duration:n.duration}),this.mcpEnhancementsConfig?.router?.enabled!==!1){const o=this.externalServerManager.listServers();if(o.length>=2&&!this.mcpToolRouter){this.mcpToolRouter=new W6({strategy:this.mcpEnhancementsConfig?.router?.strategy??"least-loaded",enableAffinity:this.mcpEnhancementsConfig?.router?.enableAffinity??!1});for(const i of o)this.mcpToolRouter.registerServer(i.id||t);f.debug("[NeuroLink] ToolRouter auto-initialized (2+ external servers)")}else this.mcpToolRouter&&this.mcpToolRouter.registerServer(t)}this.emitter.emit("externalMCP:serverAdded",{serverId:t,serverName:r.name||t,config:r,toolCount:n.metadata?.toolsDiscovered||0,timestamp:Date.now()})}else le.error(`[NeuroLink] Failed to add external MCP server: ${t}`,{error:n.error,transport:r.transport,command:r.command,url:r.url?ui(r.url):void 0});return n}catch(n){throw le.error(`[NeuroLink] Error adding external MCP server: ${t}`,n),n}}async removeExternalMCPServer(t){this.invalidateToolCache();try{le.info(`[NeuroLink] Removing external MCP server: ${t}`);const r=this.externalServerManager.getServerName(t),n=await this.externalServerManager.removeServer(t);return n.success?(le.info(`[NeuroLink] External MCP server removed successfully: ${t}`),this.emitter.emit("externalMCP:serverRemoved",{serverId:t,serverName:r,timestamp:Date.now()})):n.error?.includes("not found")?le.debug(`[NeuroLink] Remove skipped \u2014 external MCP server not registered: ${t}`):le.error(`[NeuroLink] Failed to remove external MCP server: ${t}`,{error:n.error}),n}catch(r){throw le.error(`[NeuroLink] Error removing external MCP server: ${t}`,r),r}}getExternalMCPServerHealth(){return this.externalServerManager.getServerStatuses()}listExternalMCPServers(){const t=this.externalServerManager.getServerStatuses(),r=this.externalServerManager.listServers();return t.map(n=>{const o=r.find(i=>i.id===n.serverId);return{serverId:n.serverId,status:n.status,toolCount:n.toolCount,uptime:n.performance.uptime,isHealthy:n.isHealthy,config:o||{}}})}getExternalMCPServer(t){return this.externalServerManager.getServer(t)}async executeExternalMCPTool(t,r,n,o){let i=r;try{i=this.resolveDirectMcpToolName(t,r),le.debug(`[NeuroLink] Executing external MCP tool: ${i} on ${t}`);const s=this.getToolAnnotationsForExecution(i),a=!!this.mcpToolResultCache&&!this._disableToolCacheForCurrentRequest&&!s?.destructiveHint,u={__serverId:t,__args:n,...this.toolExecutionContext?{__ctx:this.toolExecutionContext}:{}},l=this._generationTurnActive?this.toolCacheRepeatKey(i,u):void 0,c=l!==void 0&&this._toolCacheKeysServedThisRequest.has(l);if(l!==void 0&&this._toolCacheKeysServedThisRequest.add(l),a&&this.mcpToolResultCache&&!c){const h=this.mcpToolResultCache.getCachedResult(i,u);if(h!==void 0)return le.debug(`[NeuroLink] Tool result cache HIT: ${i} on ${t}`),h}const d=await this.externalServerManager.executeTool(t,i,n,o),p=d&&typeof d=="object"?d:void 0,m=!!(p&&"isError"in p&&p.isError===!0||p&&"success"in p&&p.success===!1);return a&&this.mcpToolResultCache&&!m&&d!==void 0&&this.mcpToolResultCache.cacheResult(i,u,d),le.debug(`[NeuroLink] External MCP tool ${m?"returned error":"executed successfully"}: ${i}`),d}catch(s){throw le.error(`[NeuroLink] External MCP tool execution failed: ${i}`,s),s}}resolveDirectMcpToolName(t,r){const n=this.getExternalMCPServer(t);if(!n||n.status!=="connected"||!n.client)return r;const o=this.getExternalMCPServerTools(t).map(s=>s.name);if(o.includes(r))return r;const i=zoe(r,o);if(!i)throw new qoe(r,t,VWt(r,o));return Be.mcp.startActiveSpan("mcp.toolNameRepair",{attributes:{"mcp.server_id":t,"mcp.tool_name.requested":r,"mcp.tool_name.resolved":i.name,"mcp.tool_name.repair_strategy":i.strategy,...i.score!==void 0?{"mcp.tool_name.repair_score":i.score}:{}}},s=>s.end()),le.info(`[NeuroLink] Repaired external MCP tool name at direct execution boundary: "${r}" \u2192 "${i.name}" (${i.strategy}) on server '${t}'`),i.name}getExternalMCPTools(){return this.externalServerManager.getAllTools()}getExternalMCPServerTools(t){return this.externalServerManager.getServerTools(t)}async testExternalMCPConnection(t){try{const{MCPClientFactory:r}=await Ge(Promise.resolve().then(()=>(Sae(),Per)),1e4),n=await r.testConnection(t,1e4);return{success:n.success,error:n.error,toolCount:n.capabilities?1:0}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r)}}}getExternalMCPStatistics(){return this.externalServerManager.getStatistics()}async shutdownExternalMCPServers(){try{le.info("[NeuroLink] Shutting down all external MCP servers..."),this.unregisterAllExternalMCPToolsFromRegistry(),await this.externalServerManager.shutdown(),le.info("[NeuroLink] All external MCP servers shut down successfully")}catch(t){throw le.error("[NeuroLink] Error shutting down external MCP servers:",t),t}}async getElicitationManager(){return(await Ge(Promise.resolve().then(()=>(Xmr(),Jmr)),1e4)).globalElicitationManager}async registerElicitationHandler(t){(await this.getElicitationManager()).registerHandler(t)}async getMultiServerManager(){return(await Ge(Promise.resolve().then(()=>(nse(),DXt)),1e4)).globalMultiServerManager}async getEnhancedToolDiscovery(){const t=await Ge(Promise.resolve().then(()=>(ose(),OXt)),1e4);return new t.EnhancedToolDiscovery(this.toolRegistry)}async getMCPRegistryClient(){return(await Ge(Promise.resolve().then(()=>(mhr(),ahr)),1e4)).globalMCPRegistryClient}async exposeAgentAsTool(t,r){return(await Ge(Promise.resolve().then(()=>($me(),Nme)),1e4)).exposeAgentAsTool(t,r)}async exposeWorkflowAsTool(t,r){return(await Ge(Promise.resolve().then(()=>($me(),Nme)),1e4)).exposeWorkflowAsTool(t,r)}async getToolIntegrationManager(){return(await Ge(Promise.resolve().then(()=>(bhr(),ghr)),1e4)).globalToolIntegrationManager}async convertToolsToMCPFormat(t,r={}){const n=await Ge(Promise.resolve().then(()=>(m5(),qme)),1e4),o=t.map(i=>({...i,execute:i.execute??(async()=>({success:!1,error:"No execute function provided"}))}));return n.batchConvertToMCP(o,r)}async convertToolsFromMCPFormat(t,r={}){return(await Ge(Promise.resolve().then(()=>(m5(),qme)),1e4)).batchConvertToNeuroLink(t,r)}async getToolAnnotations(t){const{inferAnnotations:r,mergeAnnotations:n,getAnnotationSummary:o}=await Ge(Promise.resolve().then(()=>($C(),AXt)),1e4),i=this.toolRegistry.getToolInfo(t);if(!i)return null;const s=i.tool.annotations,a=r({name:i.tool.name,description:i.tool.description??""}),u=n(a,s);return{annotations:u,summary:o(u)}}convertExternalMCPToolsToAISDKFormat(){const t=this.externalServerManager.getAllTools(),r={};for(const n of t)if(n.isAvailable){const o={description:n.description,execute:async i=>{try{le.debug(`[NeuroLink] Executing external MCP tool via AI SDK: ${n.name}`,{params:i});const s=await this.externalServerManager.executeTool(n.serverId,n.name,i,{timeout:3e4});return le.debug(`[NeuroLink] External MCP tool execution result: ${n.name}`,{success:!!s,hasData:!!(s&&typeof s=="object"&&"content"in s)}),s}catch(s){throw le.error(`[NeuroLink] External MCP tool execution failed: ${n.name}`,s),s}}};r[n.name]=o,le.debug(`[NeuroLink] Converted external MCP tool to AI SDK format: ${n.name} from server ${n.serverId}`)}return le.info(`[NeuroLink] Converted ${Object.keys(r).length} external MCP tools to AI SDK format`),r}convertJSONSchemaToAISDKFormat(t){}unregisterExternalMCPToolsFromRegistry(t){try{const r=this.externalServerManager.getServerTools(t);for(const n of r)this.toolRegistry.removeTool(n.name),le.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${n.name}`)}catch(r){le.error(`[NeuroLink] Failed to unregister external MCP tools from registry for server ${t}:`,r)}}unregisterExternalMCPToolFromRegistry(t){try{this.toolRegistry.removeTool(t),le.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${t}`)}catch(r){le.error(`[NeuroLink] Failed to unregister external MCP tool ${t} from registry:`,r)}}async lazyInitializeConversationMemory(t,r,n){try{const{initializeConversationMemory:o}=await uSn().then(()=>Ihr),i=await o(this.conversationMemoryConfig,this.emitter);this.conversationMemory=i,this.conversationMemoryNeedsInit=!1}catch(o){throw f.error("[NeuroLink] \u274C LOG_POINT_G005_MEMORY_LAZY_INIT_ERROR",{logPoint:"G005_MEMORY_LAZY_INIT_ERROR",generateInternalId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-r,elapsedNs:(process.hrtime.bigint()-n).toString(),error:o instanceof Error?o.message:String(o),errorName:o instanceof Error?o.name:"UnknownError",errorStack:o instanceof Error?o.stack:void 0,message:"Lazy conversation memory initialization failed"}),o}}unregisterAllExternalMCPToolsFromRegistry(){try{const t=this.externalServerManager.getAllTools();for(const r of t)this.toolRegistry.removeTool(r.name);le.debug(`[NeuroLink] Unregistered ${t.length} external MCP tools from main registry`)}catch(t){le.error("[NeuroLink] Failed to unregister all external MCP tools from registry:",t)}}async createEvaluationPipeline(t){const{EvaluationPipeline:r,getPreset:n}=await Ge(Promise.resolve().then(()=>(ax(),sx)),1e4,ve.evaluationTimeout("evaluation module load",1e4));let o;typeof t=="string"?o=n(t):o=t;const i=new r(o);return await Ge(i.initialize(),3e4,ve.evaluationTimeout("pipeline initialization",3e4)),f.debug(`[NeuroLink] Created evaluation pipeline: ${o.name??"custom"}`),i}async decide(t){const{sessionId:r,requestId:n}=t;return this.holdTelemetry(),xA({...t.context,sessionId:r??t.context?.sessionId,requestId:n??t.context?.requestId},()=>this.runDecide(t))}resolveDecisionProviderName(t,r){return t??iD(this.resolveCredentials(r))}registeredDecisionModel(t){const r=Sr.getProviderInfo(t.name)?.defaultModel;return r||(t.envVars.model?process.env[t.envVars.model]:void 0)||t.defaultModel}decisionLimits(t){const r=this.resolveDecisionProviderName(t?.provider,t?.credentials);if(!r)return null;const n=fl.get(r.toLowerCase())??r,o=nr.get(n);if(!o)return null;const i=t?.model??this.registeredDecisionModel(o);return mD(o,i)}decisionHookTimeout(){if(this.decisionHookTimeoutMs!==void 0)return this.decisionHookTimeoutMs;const t=this.decisionHooks?.hookTimeoutMs;let r=V2;return t!==void 0&&(typeof t=="number"&&Number.isFinite(t)&&t>0&&t<=H2?r=t:f.warn(`[Decision] decisionHooks.hookTimeoutMs must be a finite number from 1 to ${H2} ms; using the default ${V2} ms`,{configured:String(t)})),this.decisionHookTimeoutMs=r,r}emitDecisionEvent(t,r){try{this.emitter.emit(t,r)}catch(n){f.warn(`[Decision] a ${t} listener threw`,{error:n instanceof Error?n.message:String(n)})}}async siteDecide(t,r){const n={...t,credentials:r?.credentials??t.credentials,signal:r?.signal&&t.signal?AbortSignal.any([r.signal,t.signal]):r?.signal??t.signal,sessionId:r?.sessionId??t.sessionId,requestId:r?.requestId??t.requestId},o=n.site;if(!o)return this.tryRunDecide(n);if(!this.resolveDecisionProviderName(n.provider,n.credentials))return this.tryRunDecide(n);const i=new Map;let s;try{const a=n.questions,u=Object.keys(a).length,l=this.decisionHooks,c=this.decisionHookTimeout();let d;const p=()=>(d??={state:structuredClone(n.state),questions:structuredClone(a)},d),m=()=>({site:o,...p(),sessionId:n.sessionId,requestId:n.requestId});let h=a;if(l?.extendQuestions){let A;try{A=await Ge(Promise.resolve(l.extendQuestions(m())),c,new Error(`extendQuestions exceeded ${c}ms`))??void 0}catch(R){f.warn(`[Decision] extendQuestions hook failed for site "${o}" \u2014 proceeding with NeuroLink's own questions`,{error:R instanceof Error?R.message:String(R)})}const x=A?Object.entries(A):[];if(x.length>0){const R=this.decisionLimits({provider:n.provider,model:n.model,credentials:n.credentials}),C=R?.maxQuestions!==void 0?Math.max(0,R.maxQuestions-u):Number.POSITIVE_INFINITY,P={...a};let D=0,L=0,O=0;for(const[N,$]of x){const U=hln($);if(U===void 0){D+=1;continue}if(JNe(U,R)!==void 0){L+=1;continue}if(i.size>=C){O+=1;continue}const q=qh(bL,i.size);P[q]=U,i.set(q,N)}D>0&&f.warn(`[Decision] dropped ${D} malformed host question(s) for site "${o}"`),L>0&&f.warn(`[Decision] dropped ${L} host question(s) for site "${o}" that ${R?.provider??"the decision provider"} cannot answer`),O>0&&R&&f.warn(`[Decision] dropped ${O} host question(s) for site "${o}": ${R.provider} accepts ${R.maxQuestions} per request and NeuroLink asks ${u}`),h=P}}const g=i.size;if(this.emitter.listenerCount("decision:before")>0){const A={site:o,state:p().state,questions:g===0?p().questions:structuredClone(h),hostQuestionCount:g,sessionId:n.sessionId,requestId:n.requestId};this.emitDecisionEvent("decision:before",A)}const y=Date.now(),v=await this.tryRunDecide({...n,questions:h});s=v;const w=Object.create(null),b=Object.create(null);if(v)for(const[A,x]of Object.entries(v.answers)){const R=i.get(A);R===void 0?w[A]=x:b[R]=x}const E=v?structuredClone(v):null,k={site:o,answers:structuredClone(w),hostAnswers:structuredClone(b),latencyMs:v?.latencyMs??Date.now()-y,provider:v?.provider??this.resolveDecisionProviderName(n.provider,n.credentials),model:v?.model,result:E,sessionId:n.sessionId,requestId:n.requestId};if(this.emitDecisionEvent("decision:after",k),!v||!E)return null;if(l?.onAnswers)try{await Ge(Promise.resolve(l.onAnswers({...m(),answers:structuredClone(b),result:E})),c,new Error(`onAnswers exceeded ${c}ms`))}catch(A){f.warn(`[Decision] onAnswers hook failed for site "${o}"`,{error:A instanceof Error?A.message:String(A)})}return g===0?v:{...v,answers:w}}catch(a){return f.warn(`[Decision] site "${o}" hook or event handling threw \u2014 ${s===void 0?"deciding with NeuroLink's own questions":"handing the consumer the answers already obtained"}`,{error:a instanceof Error?a.message:String(a)}),s===void 0?this.tryRunDecide(n):s?fln(s,i):null}}async runDecide(t){const r=this.resolveDecisionProviderName(t.provider,t.credentials),n=Object.keys(t.questions),o=n.length,i=r?nr.get(fl.get(r.toLowerCase())??r):void 0,s=t.model??(i&&this.registeredDecisionModel(i)),a=t,u=n.filter(mln).length,l=a.site?{"decision.site":a.site,"decision.host_question_count":u}:{};return pt({name:"decide",tracer:Be.decision,expectedFailure:()=>!r,attributes:{"gen_ai.system":r,"gen_ai.operation.name":"decide","ai.provider":r,"decision.question_count":o,"decision.images.count":t.images?.length??0,"decision.audio.count":t.audio===void 0?0:1,...l}},async c=>{if(no(c,"generation",{model:s,input:{state:t.state,questions:t.questions},metadata:{provider:r,...a.site&&{site:a.site,host_question_count:u}}}),!r){const g=`No decision provider is configured. Set ${kzr()} (in the environment or in \`credentials\`), or pass \`provider\` explicitly.`;throw no(c,"generation",{level:"WARNING",statusMessage:g}),new Error(g)}const{traceId:d,parentSpanId:p}=t0(),m=Date.now();let h=Ce.createSpan("model.decision",`decision.${r}`,{"ai.provider":r,"ai.model":t.model??"","decision.question_count":o,"decision.images.count":t.images?.length??0,"decision.audio.count":t.audio===void 0?0:1,...l},p,d);try{const g=await ao.createProvider(r,t.model,!1,this,void 0,this.resolveCredentials(t.credentials));if(typeof g.decide!="function")throw new Error(`Provider "${r}" does not serve the decide inference type.`);const y=await g.decide({state:t.state,questions:t.questions,images:t.images,video:t.video,audio:t.audio,model:t.model,signal:t.signal,timeoutMs:t.timeoutMs}),v=Object.keys(y.answers).length,w=fl.get(r.toLowerCase())??r,b=bl(w,y.model,{input:y.usage.inputTokens,output:y.usage.outputTokens,total:y.usage.inputTokens+y.usage.outputTokens});c.setAttribute("gen_ai.response.model",y.model),c.setAttribute("gen_ai.usage.input_tokens",y.usage.inputTokens),c.setAttribute("gen_ai.usage.output_tokens",y.usage.outputTokens),c.setAttribute("decision.answer_count",v),c.setAttribute("decision.media.bytes",y.mediaBytes??0),c.setAttribute("ai.cost.total",b),y.upstreamMs!==void 0&&c.setAttribute("decision.upstream_ms",y.upstreamMs),y.requestId&&c.setAttribute("gen_ai.response.id",y.requestId),no(c,"generation",{model:y.model,output:y.answers,usageDetails:TZ({input:y.usage.inputTokens,output:y.usage.outputTokens}),costDetails:{total:b}}),h.durationMs=Date.now()-m,h=Ce.updateAttributes(h,{"ai.model":y.model,"ai.tokens.input":y.usage.inputTokens,"ai.tokens.output":y.usage.outputTokens,"ai.cost.input":b,"ai.cost.output":0,"ai.cost.total":b,"decision.answer_count":v,"decision.media.bytes":y.mediaBytes??0,"decision.latency_ms":y.latencyMs,...y.upstreamMs!==void 0?{"decision.upstream_ms":y.upstreamMs}:{}});const E=Ce.endSpan(h,1);return this.metricsAggregator.recordSpan(E),nt().recordSpan(E),y}catch(g){h.durationMs=Date.now()-m;const y=Ce.endSpan(h,2,g instanceof Error?g.message:String(g));throw this.metricsAggregator.recordSpan(y),nt().recordSpan(y),g}})}async tryDecide(t){return this.holdTelemetry(),this.siteDecide(t)}async transcribe(t){const[r,{runTranscribe:n}]=await Promise.all([this.buildTranscribeDeps(t.credentials?.stt),Promise.resolve().then(()=>(qgr(),She))]);return n(t,r)}async*transcribeStream(t){const[r,{runTranscribeStream:n}]=await Promise.all([this.buildTranscribeDeps(t.credentials?.stt),Promise.resolve().then(()=>(Sgr(),bgr))]);yield*n(t,r)}resolveSTTCredentials(t){const r=this.credentials?.stt;if(!r||!t)return t??r;const n={...r};for(const[o,i]of Object.entries(t)){const s=n[o];n[o]=s&&typeof s=="object"&&i&&typeof i=="object"?{...s,...i}:i??s}return n}resolveSTTProvider(t,r){const n=t?.trim();return n?Rw(n)??n:Rk(r)}async buildTranscribeDeps(t){await Jd.registerAllProviders();const[{STTProcessor:r},{createSTTHandler:n},{STTError:o}]=await Promise.all([Promise.resolve().then(()=>(Dh(),a3)),Promise.resolve().then(()=>(Ph(),Mh)),Promise.resolve().then(()=>(Fi(),f1t))]),i=this.resolveSTTCredentials(t),s=u=>{const l=this.resolveSTTProvider(u,i);if(Rw(l)===void 0&&!r.supports(l)&&!Ik(i)[l.trim().toLowerCase()])throw o.unknownProvider(l,NNe(i),$Ne());return l},a=u=>{if(Ik(i)[u.trim().toLowerCase()])return n(u,i);const l=ih(u);return l?i?.[l.credentialsKey]!==void 0?n(l.name,i):r.getHandler(l.name)??n(l.name):r.getHandler(u)};return{...this.buildSTTCorrectionDeps(),transcribe:(u,l,c)=>r.transcribe(u,l,c,i),resolveProvider:s,getHandler:a}}buildSTTCorrectionDeps(){return{decide:async t=>{const r=await this.tryDecide({state:t.state,questions:t.questions,...t.timeoutMs!==void 0?{timeoutMs:t.timeoutMs}:{}});return r?{answers:r.answers}:null},rewrite:async t=>{const r=new AbortController,n=setTimeout(()=>r.abort(),t.timeoutMs),o=t.provider??process.env.NEUROLINK_STT_REWRITE_PROVIDER?.trim(),i=t.model??process.env.NEUROLINK_STT_REWRITE_MODEL?.trim(),s={input:{text:t.user},systemPrompt:t.system,...o?{provider:o}:{},...i?{model:i}:{},maxTokens:t.maxTokens,temperature:0,disableTools:!0,memory:{enabled:!1},abortSignal:r.signal};try{const u=(await this.generate(s)).content??"";return t.onPartial&&u&&t.onPartial(u),u}finally{clearTimeout(n)}},render:async t=>{const r=new AbortController,n=setTimeout(()=>r.abort(),t.timeoutMs),o=t.provider??(process.env.NEUROLINK_STT_OUTPUT_PROVIDER?.trim()||process.env.NEUROLINK_STT_REWRITE_PROVIDER?.trim()),i=t.model??(process.env.NEUROLINK_STT_OUTPUT_MODEL?.trim()||process.env.NEUROLINK_STT_REWRITE_MODEL?.trim());try{const s=await this.generate({input:{text:t.user},systemPrompt:t.system,schema:t.schema,...o?{provider:o}:{},...i?{model:i}:{},maxTokens:t.maxTokens,temperature:0,disableTools:!0,memory:{enabled:!1},abortSignal:r.signal});return s.structuredData??s.content??""}finally{clearTimeout(n)}}}}async tryRunDecide(t){try{const r=await this.decideInBatches(t);return f.shouldLog("debug")&&f.debug(`decide: ${Object.keys(r.answers).length} answers in ${r.latencyMs}ms`+(r.upstreamMs?` (upstream ${r.upstreamMs}ms)`:""),{provider:r.provider,model:r.model,requestId:r.requestId,usage:r.usage}),r}catch(r){return f.debug(`decide unavailable: ${r instanceof Error?r.message:String(r)} \u2014 falling back`),null}}async decideInBatches(t){const r=t.provider??iD(this.resolveCredentials(t.credentials)),n=r?fl.get(r.toLowerCase()):void 0,o=n?nr.get(n)?.decisionLimits?.maxQuestions:void 0,i=Pln(t,o);if(i.length===1)return this.decide(t);const s=[];let a;for(let c=0;c<i.length;c+=Wie){const d=await Promise.allSettled(i.slice(c,c+Wie).map(p=>this.decide(p)));for(const p of d)p.status==="fulfilled"?s.push(p.value):a??=p.reason}const[u,...l]=s;if(u===void 0)throw a instanceof Error?a:new Error(String(a));return l.length+1<i.length&&f.debug(`decide: ${i.length-s.length} of ${i.length} batches failed; using the answers of the rest`),Dln([u,...l])}async evaluate(t,r){const{EvaluationPipeline:n,getPreset:o}=await Ge(Promise.resolve().then(()=>(ax(),sx)),1e4,ve.evaluationTimeout("evaluation module load",1e4));let i;if(r?.pipeline&&r?.scorers)throw new Error("Cannot specify both 'pipeline' and 'scorers' options. Use one or the other.");if(r?.scorers&&r.scorers.length===0)throw new Error("The 'scorers' array must not be empty. Provide at least one scorer ID or omit the option to use the default 'quality' preset.");r?.pipeline?i={...o(r.pipeline)}:r?.scorers&&r.scorers.length>0?i={name:"SDK Evaluation",description:"Evaluation from NeuroLink SDK",scorers:r.scorers.map(l=>({id:l})),executionMode:r.executionMode??"parallel",passThreshold:r.passThreshold??.7}:i=o("quality"),r?.passThreshold!==void 0&&(i.passThreshold=r.passThreshold),r?.executionMode!==void 0&&(i.executionMode=r.executionMode);const s=new n(i);await Ge(s.initialize(),3e4,ve.evaluationTimeout("pipeline initialization",3e4));const a=r?.timeoutMs??6e4,u=await Ge(s.execute(t,{correlationId:r?.correlationId}),a,ve.evaluationTimeout("pipeline execution",a));return f.debug("[NeuroLink] Evaluation completed",{pipeline:i.name,overallScore:u.overallScore,passed:u.passed,scorerCount:u.scores.length}),u}async score(t,r,n){const{ScorerRegistry:o}=await Ge(Promise.resolve().then(()=>(nQ(),rQ)),1e4,ve.evaluationTimeout("scorer module load",1e4));await Ge(o.registerBuiltInScorers(),3e4,ve.evaluationTimeout("scorer bootstrap",3e4));const i=await Ge(o.getScorer(t,n),3e4,ve.evaluationTimeout(`scorer load: ${t}`,3e4));if(!i)throw ve.scorerNotFound(t);const s=i.validateInput(r);if(!s.valid)throw ve.evaluationValidationFailed(t,s.errors);const a=await Ge(i.score(r),6e4,ve.evaluationTimeout("scorer execution",6e4));return f.debug("[NeuroLink] Scoring completed",{scorerId:t,score:a.score,passed:a.passed,computeTime:a.computeTime}),a}async getAvailableScorers(t){const{ScorerRegistry:r}=await Ge(Promise.resolve().then(()=>(nQ(),rQ)),1e4,ve.evaluationTimeout("scorer module load",1e4));await Ge(r.registerBuiltInScorers(),3e4,ve.evaluationTimeout("scorer bootstrap",3e4));let n=r.list();return t?.category&&(n=n.filter(o=>o.category===t.category)),t?.type&&(n=n.filter(o=>o.type===t.type)),n}async getEvaluationPresets(){const{getPresetNames:t}=await Ge(Promise.resolve().then(()=>(ax(),sx)),1e4,ve.evaluationTimeout("evaluation module load",1e4));return t()}async getEvaluationPreset(t){const{getPreset:r}=await Ge(Promise.resolve().then(()=>(ax(),sx)),1e4,ve.evaluationTimeout("evaluation module load",1e4));return r(t)}async createAgent(t){const{Agent:r}=await Promise.resolve().then(()=>(xhe(),jgr));return f.debug("[NeuroLink] Creating agent",{id:t.id,name:t.name,tools:t.tools?.length||0}),new r(t,this)}async createNetwork(t){const{AgentNetwork:r}=await Promise.resolve().then(()=>(Hgr(),Vgr));return f.debug("[NeuroLink] Creating agent network",{name:t.name,agentCount:t.agents.length,workflowCount:t.workflows?.length||0,toolCount:t.tools?.length||0}),new r(t,this)}createWorkerInstance(t){const r=t?.logTag??"worker",n=this.emitter,o=t?.config??{},i={...this.credentials?{credentials:this.credentials}:{},...o,conversationMemory:{enabled:!1},enableOrchestration:!1,observability:this.observabilityConfig,...t?.shareToolRegistry!==!1&&{toolRegistry:this.toolRegistry}},s=this.workerToolsConfig(o.tools),a=new qf(s?{...i,tools:s}:i);if(t?.shareToolRegistry!==!1)for(const u of this.uncacheableTools)a.uncacheableTools.add(u);if(f.setEventEmitter(n),t?.onLog){const u=t.onLog,l=h=>{try{const g=h??{};u({tag:r,level:String(g.level??"info"),message:String(g.message??""),timestamp:typeof g.timestamp=="number"?g.timestamp:Date.now(),data:g.data})}catch{}},c={emit:(h,...g)=>(h==="log-event"&&l(g[0]),!0)},d=a.logInstanceId;f.addScopedEventEmitter(d,c);const p=()=>{f.removeScopedEventEmitter(d,c),this.ownedWorkerLogBridgeDetachers.delete(p)};this.ownedWorkerLogBridgeDetachers.add(p);const m=a.dispose.bind(a);a.dispose=async()=>{p(),await m()}}return f.debug("[NeuroLink] Created worker instance",{tag:r,sharedToolRegistry:t?.shareToolRegistry!==!1}),a}async runIsolatedAgent(t,r,n){const{runIsolatedAgent:o}=await Promise.resolve().then(()=>(w1(),Q6));return o(this,t,r,n)}async continueAgent(t,r){const{continueIsolatedAgent:n}=await Promise.resolve().then(()=>(w1(),Q6));return n(this,t,r)}async stopAgent(t){const{stopIsolatedAgent:r}=await Promise.resolve().then(()=>(w1(),Q6));return r(this,t)}async registerAgentTool(t,r){const{registerAgentTool:n}=await Promise.resolve().then(()=>(T1(),n$)),o=n(this,t,r);return this.hasAgentTools=!0,o}registerTaskTools(){if(this.hasTaskChecklistTools)return;const t=ngn(this);for(const[r,n]of Object.entries(t))this.registerTool(r,n,{cacheable:!1});this.hasTaskChecklistTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(t).length} task checklist tools`)}getTaskState(t){return Qfn(t??Si(this))}clearTaskState(t){return egn(t??Si(this))}registerDelegationTools(t){if(_gn(this,t),this.hasBackgroundDelegationTools)return;const r=Pgn(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundDelegationTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(r).length} background delegation tools`)}async spawnDelegate(t){return For(this,t)}async collectDelegates(t){return Bor(this,t)}async cancelDelegates(t){return Ele(this,t)}getArtifactStore(){return this.mcpArtifactStore||(this.mcpArtifactStore=this.createConfiguredArtifactStore()),this.registerMemoryRetrievalTools(),this.mcpArtifactStore}setArtifactStore(t){const r=this.mcpArtifactStore;r!==t&&(r&&(f.warn("[NeuroLink] Artifact store replaced \u2014 artifacts already written to the previous store will not resolve through this instance"),this.ownsArtifactStore&&r.close&&r.close().catch(n=>{f.warn("[NeuroLink] Previous artifact store close failed",{error:n instanceof Error?n.message:String(n)})})),this.mcpArtifactStore=t,this.ownsArtifactStore=!1,this.installOutputNormalizer(t),this.registerMemoryRetrievalTools())}createConfiguredArtifactStore(){const t=this.artifactsConfig?.store!==void 0,r=krr(this.artifactsConfig,this.conversationMemoryConfig?.conversationMemory?.redisConfig);return this.ownsArtifactStore=!t,f.debug("[NeuroLink] Artifact store initialized",{backend:t?"custom":sue(this.artifactsConfig)}),r}installOutputNormalizer(t){this.mcpOutputNormalizerConfig&&(this.externalServerManager.setOutputNormalizer(new ltr(this.mcpOutputNormalizerConfig,t)),f.debug("[NeuroLink] MCP output normalizer initialized",{...this.mcpOutputNormalizerConfig,hasArtifactStore:t!==void 0}))}async bankArtifact(t,r){return Khn(this,t,r)}async readArtifact(t,r){return Jhn(this,t,r)}registerBackgroundCommandTools(t){if(Hor(this,t),this.hasBackgroundCommandTools)return;const r=zgn(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundCommandTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(r).length} background command tools`)}setBackgroundCommandPolicy(t){Hor(this,t)}async startBackgroundCommand(t,r){return eir(this,t,r)}getBackgroundCommandStatus(t){return tir(this,t)}async awaitBackgroundCommand(t,r){return Lle(this,t,r)}async killBackgroundCommand(t,r){return rir(this,t,r)}async readBackgroundCommandOutput(t,r){return p$(this,t,r)}registerGitTools(t){if(Ggn(this,t),this.hasGitTools)return;const r=Jgn(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasGitTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(r).length} read-only git tools`)}async runGitCommand(t,r){return fir(this,t,r)}async executeNetwork(t,r,n){return f.debug("[NeuroLink] Executing agent network",{networkId:t.id,networkName:t.name,hasContext:!!r.context}),t.execute(r,n)}async*streamNetwork(t,r,n){f.debug("[NeuroLink] Streaming agent network",{networkId:t.id,networkName:t.name,hasContext:!!r.context}),yield*t.stream(r,n)}async createOrchestrator(t){const{NetworkOrchestrator:r}=await Promise.resolve().then(()=>(Xgr(),Jgr));return f.debug("[NeuroLink] Creating network orchestrator",{maxConcurrentExecutions:t?.maxConcurrentExecutions,defaultMode:t?.defaultMode}),new r(this,t)}async createCoordinator(t){const{AgentCoordinator:r}=await Promise.resolve().then(()=>(Zgr(),Ygr));return f.debug("[NeuroLink] Creating agent coordinator",{strategy:t?.strategy,maxConcurrency:t?.maxConcurrency}),new r(t)}async createMessageBus(t){const{MessageBus:r}=await Promise.resolve().then(()=>(e0r(),Qgr));return f.debug("[NeuroLink] Creating message bus",{maxHistorySize:t?.maxHistorySize}),new r(t)}async dispose(){f.debug("[NeuroLink] Starting disposal of resources..."),this.lastCompactionMessageCount.clear();const t=[];try{try{await nir(this),await Ele(this)}catch(r){const n=r instanceof Error?r:new Error(`Background work cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error stopping background work:",r)}try{await this.releaseMemoryCondenser()}catch(r){t.push(r instanceof Error?r:new Error(String(r)))}try{f.debug("[NeuroLink] Flushing and shutting down OpenTelemetry..."),await this.releaseTelemetryHold(),f.debug("[NeuroLink] OpenTelemetry shutdown successfully")}catch(r){const n=r instanceof Error?r:new Error(`OpenTelemetry shutdown error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error shutting down OpenTelemetry:",r)}if(this.externalServerManager)try{f.debug("[NeuroLink] Shutting down external MCP servers..."),await this.externalServerManager.shutdown(),f.debug("[NeuroLink] External MCP servers shutdown successfully")}catch(r){const n=r instanceof Error?r:new Error(`External server shutdown error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error shutting down external MCP servers:",r)}if(this.ownsArtifactStore&&this.mcpArtifactStore?.close)try{await this.mcpArtifactStore.close(),f.debug("[NeuroLink] Artifact store closed")}catch(r){const n=r instanceof Error?r:new Error(`Artifact store close error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error closing artifact store:",r)}if(this.emitter)try{f.debug("[NeuroLink] Removing all event listeners..."),this.emitter.removeAllListeners(),f.clearEventEmitter(this.emitter),f.clearScopedEventEmitters(this.logInstanceId),f.debug("[NeuroLink] Event listeners removed successfully")}catch(r){const n=r instanceof Error?r:new Error(`Event emitter cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error removing event listeners:",r)}if(this.ownedWorkerLogBridgeDetachers.size>0)try{const r=this.ownedWorkerLogBridgeDetachers.size;for(const n of[...this.ownedWorkerLogBridgeDetachers])n();f.debug(`[NeuroLink] Detached ${r} undisposed worker log bridge(s)`)}catch(r){const n=r instanceof Error?r:new Error(`Worker log bridge cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error detaching worker log bridges:",r)}if(this.toolCircuitBreakers&&this.toolCircuitBreakers.size>0)try{f.debug(`[NeuroLink] Clearing ${this.toolCircuitBreakers.size} circuit breakers...`),this.toolCircuitBreakers.clear(),f.debug("[NeuroLink] Circuit breakers cleared successfully")}catch(r){const n=r instanceof Error?r:new Error(`Circuit breaker cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error clearing circuit breakers:",r)}try{f.debug("[NeuroLink] Clearing maps and caches..."),this.toolExecutionMetrics&&this.toolExecutionMetrics.clear(),this.activeToolExecutions&&this.activeToolExecutions.clear(),this.currentStreamToolExecutions&&(this.currentStreamToolExecutions.length=0),this.toolExecutionHistory&&(this.toolExecutionHistory.length=0),this.toolCache&&(this.toolCache.tools=[],this.toolCache.timestamp=0),this.mcpToolResultCache?.destroy(),this.mcpToolRouter?.destroy(),this.mcpToolBatcher?.destroy(),this.mcpToolResultCache=void 0,this.mcpToolRouter=void 0,this.mcpToolBatcher=void 0,this.mcpEnhancedDiscovery=void 0,this.mcpToolMiddlewares=[],f.debug("[NeuroLink] Maps and caches cleared successfully")}catch(r){const n=r instanceof Error?r:new Error(`Cache cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error clearing caches:",r)}if(this._taskManager)try{f.debug("[NeuroLink] Shutting down TaskManager..."),await Ge(this._taskManager.shutdown(),5e3,new Error("TaskManager shutdown timed out"))}catch(r){f.warn("[NeuroLink] TaskManager shutdown error:",r)}finally{this._taskManager=void 0}try{f.debug("[NeuroLink] Resetting initialization state..."),this.mcpInitialized=!1,this.mcpInitPromise=null,this.conversationMemoryNeedsInit=!1,this.credentials=void 0,f.debug("[NeuroLink] Initialization state reset successfully")}catch(r){const n=r instanceof Error?r:new Error(`State reset error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error resetting state:",r)}t.length===0?f.debug("[NeuroLink] \u2705 Resource disposal completed successfully"):f.warn(`[NeuroLink] \u26A0\uFE0F Resource disposal completed with ${t.length} errors`,{errors:t.map(r=>r.message)})}catch(r){throw f.error("[NeuroLink] Critical error during disposal:",r),r}}getToolRegistry(){return this.toolRegistry}async compactSession(t,r){if(!this.conversationMemory)return null;const n=await this.conversationMemory.buildContextMessages(t);if(!n||n.length===0)return null;const o=new aT({...r,summarizationProvider:r?.summarizationProvider??this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:r?.summarizationModel??this.conversationMemoryConfig?.conversationMemory?.summarizationModel},this.contextCompactorDeps({sessionId:t})),i=Ea({provider:r?.provider||"openai",conversationMessages:n,toolReplayMode:this.resolveToolReplayModeForBudget({})}),s=Math.floor(i.availableInputTokens*.6),a=await o.compact(n,s,this.conversationMemoryConfig?.conversationMemory);return a.compacted&&Hb(a.messages),a}async getContextStats(t,r,n){if(!this.conversationMemory)return null;const o=await this.conversationMemory.buildContextMessages(t);if(!o||o.length===0)return null;const i=Ea({provider:r||"openai",model:n,conversationMessages:o,toolReplayMode:this.resolveToolReplayModeForBudget({})});return{estimatedInputTokens:i.estimatedInputTokens,availableInputTokens:i.availableInputTokens,usageRatio:i.usageRatio,shouldCompact:i.shouldCompact,messageCount:o.length}}needsCompaction(t,r,n){if(!this.conversationMemory)return!1;const o=this.conversationMemory.getSession?.(t);return o?Ea({provider:r||"openai",model:n,conversationMessages:o.messages,toolReplayMode:this.resolveToolReplayModeForBudget({})}).shouldCompact:!1}async setAuthProvider(t){this.authInitPromise=void 0,await this.initializeAuthProviderFromConfig(t)}async initializeAuthProviderFromConfig(t){let r,n;if("authenticateToken"in t&&typeof t.authenticateToken=="function")r=t,n=r.type;else if("provider"in t)r=t.provider,n=r.type;else{const o=t,{AuthProviderFactory:i}=await Promise.resolve().then(()=>($5(),t0r));r=await i.createProvider(o.type,o.config),n=o.type}this.authProvider=r,f.info(`Auth provider set: ${n}`),this.emitter.emit("auth:provider:set",{type:r.type,timestamp:Date.now()})}getAuthProvider(){return this.authProvider}async ensureAuthProvider(){if(this.authProvider||!this.pendingAuthConfig)return;const t=this.pendingAuthConfig;this.authInitPromise??=(async()=>{try{await this.initializeAuthProviderFromConfig(t),this.pendingAuthConfig=void 0}finally{this.authInitPromise&&(this.pendingAuthConfig===void 0||this.pendingAuthConfig===t)&&(this.authInitPromise=void 0)}})(),await this.authInitPromise}async setAuthContext(t){const{globalAuthContext:r}=await Promise.resolve().then(()=>(r1(),P6));r.set(t),f.debug("Auth context set",{userId:t.user.id,provider:t.provider,sessionId:t.session?.id})}async getAuthContext(){const{getAuthContext:t}=await Promise.resolve().then(()=>(r1(),P6));return t()}async clearAuthContext(){const{globalAuthContext:t}=await Promise.resolve().then(()=>(r1(),P6)),r=t.get()?.user.id;t.clear(),r&&f.debug(`Auth context cleared for user: ${r}`)}getExternalServerManager(){return this.externalServerManager}buildResolutionContext(t,r){return{requestContext:r||{},signal:t}}async resolveDynamicOptions(t){const r=["model","provider","temperature","maxTokens","systemPrompt","timeout","thinkingLevel","disableTools","enableAnalytics","enableEvaluation"];if(!(r.some(i=>typeof t[i]=="function")||typeof t.tools=="function"))return;const o=t.dynamicContext;await this.resolveDynamicFields(t,r,o)}async resolveDynamicFields(t,r,n){const o=this.buildResolutionContext(t.abortSignal,n);if(f.debug("[NeuroLink] Resolving dynamic arguments"),await Promise.all(r.map(async i=>{if(typeof t[i]=="function"){const s=await due(t[i],o);t[i]=s.value,f.debug(`[NeuroLink] Resolved dynamic ${i}: ${s.resolutionType}`)}})),typeof t.tools=="function"){const i=await due(t.tools,o);if(!Array.isArray(i.value))throw new TypeError(`Dynamic tools resolver must return string[] (tool names), got ${typeof i.value=="object"?"object":typeof i.value}`);t.enabledToolNames=i.value,delete t.tools}}},Fhe=new M_,s0r=Fhe}});function qI(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10?"image/png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56&&(e[4]===55||e[4]===57)&&e[5]===97?"image/gif":null}function jI(e){return qI(e)??"image/png"}var P_=S({"src/lib/utils/imageDetection.ts"(){"use strict"}});function Vkn(e){return bb(e)&&FN(e)===null?"video/mp4":m0r.every((t,r)=>e[r]===t)?"video/webm":null}function Hkn(e){return dm(e,0,4)==="RIFF"&&dm(e,8,12)==="WAVE"?"wav":dm(e,0,4)==="fLaC"?"flac":dm(e,0,4)==="OggS"?"ogg":bb(e)?"aac":dm(e,0,3)==="ID3"?"mp3":e.length>=2&&e[0]===255&&(e[1]&224)===224?(e[1]&6)===0?"aac":"mp3":null}function Wkn(e){let t,r=12;for(;r+8<=e.length;){const n=dm(e,r,r+4),o=e.readUInt32LE(r+4),i=r+8;if(n==="fmt "&&i+12<=e.length)t=e.readUInt32LE(i+8);else if(n==="data"){const s=o===0||o===4294967295?e.length-i:Math.min(o,e.length-i);return t?s/t:void 0}r=i+o+o%2}}function Kkn(e){if(e.length<26||(e[4]&127)!==0)return;const t=8,r=e[t+10]<<12|e[t+11]<<4|e[t+12]>>4,n=(e[t+13]&15)*2**32+e.readUInt32BE(t+14);return r>0&&n>0?n/r:void 0}function Jkn(e){const t=e[26];if(e.length<28||t===void 0)return;const r=27+t;let n,o=0;dm(e,r,r+8)==="OpusHead"?(n=48e3,o=e.length>=r+12?e.readUInt16LE(r+10):0):dm(e,r,r+7)==="vorbis"&&(n=e.length>=r+16?e.readUInt32LE(r+12):void 0);const i=e.lastIndexOf("OggS");if(!n||i<0||i+14>e.length||e[i+4]!==0)return;const s=e.readBigInt64LE(i+6);if(!(s<=0n))return Math.max(0,Number(s)-o)/n}function Xkn(e,t,r){const n=Hkn(e);if(n===null)return{status:"error",message:`${r} ${Bhe.audio}.`};if(n==="aac")return{status:"error",message:`${r} is AAC or M4A audio, which the model does not decode. Convert it to WAV, FLAC, Ogg or MP3.`};const o=n==="wav"?Wkn(e):n==="flac"?Kkn(e):n==="ogg"?Jkn(e):void 0;return n==="wav"&&o===void 0?{status:"error",message:`${r} is a WAV file without a complete fmt and data chunk.`}:o!==void 0&&o>t.maxSeconds?{status:"error",message:`${r} runs ${o.toFixed(1)} seconds; the model hears at most ${t.maxSeconds}. Trim it, or split it across requests.`}:{status:"ok",audio:{data:e.toString("base64"),format:n}}}function Ykn(e,t,r){const n=t==="image"?qI(e):Vkn(e);return n===null?{status:"error",message:`${r} ${Bhe[t]}.`}:{status:"ok",dataUrl:`data:${n};base64,${e.toString("base64")}`}}function Uhe(e){return e.length<=d0r?`(${e})`:`(a ${e.length}-character string)`}async function Zkn(e,t,r){try{const n=await SD.stat(e);return n.isFile()?n.size>r?{status:"error",message:`${t} ${Uhe(e)} is ${n.size} bytes; a request may carry at most ${r}.`}:{status:"ok",buffer:await SD.readFile(e)}:{status:"error",message:`${t} ${Uhe(e)} is not a file.`}}catch(n){const o=n instanceof Error&&"code"in n?String(n.code):"unreadable";return{status:"error",message:`Could not read ${t} ${Uhe(e)}: ${o}.`}}}async function a0r(e,t,r,n){if(typeof e!="string")return e.length===0?{status:"error",message:`${r} is an empty Buffer.`}:{status:"buffer",buffer:e};const o=e.trim();if(o==="")return{status:"error",message:`${r} is an empty string.`};if(l0r.test(o))return{status:"error",message:`${r} is a remote URL. Media is not fetched for you; pass a Buffer, a file path or a data: URL.`};if(/^data:/i.test(o))return p0r[t].test(o)?{status:"dataUrl",dataUrl:o}:{status:"error",message:`${r} is a data: URL that is not base64 ${t} content.`};if(c0r.test(o))return{status:"error",message:`${r} uses an unsupported URL scheme. Pass a Buffer, a file path or a data: URL.`};const i=await Zkn(o,r,n);return i.status==="ok"?{status:"buffer",buffer:i.buffer}:i}async function u0r(e,t,r,n){const o=await a0r(e,t,r,n);return o.status==="buffer"?Ykn(o.buffer,t,r):o.status==="dataUrl"?{status:"ok",dataUrl:o.dataUrl}:o}async function Qkn(e,t,r){const n=await a0r(e,"audio",t,r);if(n.status==="dataUrl"){const o=n.dataUrl.slice(n.dataUrl.indexOf(",")+1);return{status:"ok",buffer:Buffer.from(o,"base64")}}return n.status==="buffer"?{status:"ok",buffer:n.buffer}:n}async function eAn(e,t,r,n){const o=e.images??[];if(o.length===0&&e.video===void 0&&e.audio===void 0)return{status:"prepared",media:void 0};const i=n.length>0?` Use a decision provider that does: ${n.join(", ")}.`:"";if(!t){const c=o.length===0&&e.video===void 0?"audio":"images or video";return{status:"refused",message:`${r} does not accept ${c}.${i}`}}if(e.audio!==void 0&&t.audio===void 0)return{status:"refused",message:`${r} does not accept audio.${i}`};if(o.length>t.maxImages)return{status:"refused",message:`${r} accepts at most ${t.maxImages} images per request; this one has ${o.length}.`};if(e.video!==void 0&&!t.video)return{status:"refused",message:`${r} does not accept video.`};const s=[];for(const[c,d]of o.entries()){const p=await u0r(d,"image",`Image ${c+1}`,t.maxRequestBytes);if(p.status==="error")return{status:"refused",message:p.message};s.push(p.dataUrl)}let a;if(e.video!==void 0){const c=await u0r(e.video,"video","The video",t.maxRequestBytes);if(c.status==="error")return{status:"refused",message:c.message};a=c.dataUrl}let u;if(e.audio!==void 0&&t.audio!==void 0){const c=await Qkn(e.audio,"The audio",t.maxRequestBytes);if(c.status==="error")return{status:"refused",message:c.message};const d=Xkn(c.buffer,t.audio,"The audio");if(d.status==="error")return{status:"refused",message:d.message};u=d.audio}const l=s.reduce((c,d)=>c+d.length,(a?.length??0)+(u?.data.length??0));return{status:"prepared",media:{images:s,...a?{video:a}:{},...u?{audio:u}:{},bytes:l}}}var l0r,c0r,d0r,p0r,m0r,Bhe,dm,tAn=S({"src/lib/utils/decisionMedia.ts"(){"use strict";Hr(),P_(),UN(),l0r=/^https?:\/\//i,c0r=/^[a-z][a-z0-9+.-]*:\/\//i,d0r=200,p0r={image:/^data:image\/[a-z0-9.+-]+;base64,/i,video:/^data:video\/[a-z0-9.+-]+;base64,/i,audio:/^data:audio\/[a-z0-9.+-]+;base64,/i},m0r=[26,69,223,163],Bhe={image:"is not a recognised image format",video:"is not a recognised video format (MP4, MOV or WebM)",audio:"is not a recognised audio format (WAV, FLAC, Ogg or MP3)"},dm=(e,t,r)=>e.subarray(t,r).toString("latin1")}});function h0r(e){return e.filter(zr).map(r=>{const n=Array.isArray(r.loc)?r.loc.filter(i=>typeof i=="string"||typeof i=="number").join("."):"",o=typeof r.msg=="string"?r.msg:"invalid";return n?`${n}: ${o}`:o}).slice(0,5).join("; ")||"unspecified field"}function D_(e,t){return(t?e.split(t).join("[redacted]"):e).replace(/\.?\s*Received API Key\s*=[\s\S]*$/,"").replace(/\.?\s*Received Model Group=[\s\S]*$/,"").replace(/\s*No fallback model group found[\s\S]*$/,"").replace(/input_value=[\s\S]*(?=, input_type=)/g,"input_value=[redacted]").replace(/input_value=(?!\[redacted\])[\s\S]*/g,"input_value=[redacted]").replace(/\bsk-[A-Za-z0-9._-]+/g,"[redacted]").replace(/\b[0-9a-f]{32,}\b/gi,"[redacted]").replace(/data:[a-z]+\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]+/gi,"[media]").trim()}function rAn(e){let t=e;for(let r=0;r<5&&t instanceof Error;r++){if(t.message==="unexpected redirect")return!0;t=t.cause}return!1}var zhe,f0r,Ghe,VI,O_=S({async"src/lib/providers/systemOneDecision.ts"(){"use strict";zu(),Au(),await Oc(),Lr(),lt(),tAn(),z(),zt(),hD(),u3e(),Dk(),Dk(),zhe=5e3,f0r=1,Ghe=(e,t)=>new Promise((r,n)=>{if(t?.aborted){n(t.reason);return}const o=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e);function i(){clearTimeout(o),n(t?.reason)}t?.addEventListener("abort",i,{once:!0})}),VI=class extends Za{proxyFetch;maxRetries;authFailed=!1;constructor(e,t,r){super(e,t,yf(r)?r:void 0),this.proxyFetch=Ft(),this.maxRetries=f0r}missingConfigMessage(){}assertWithinVendorLimits(e,t){}encodeQuestion(e){return this.dialect().encodeQuestion(e)}dialect(){return UH}readRetryAfterMs(e){}defaultTimeoutMs(e,t){const r=this.getDescriptorDecideMs(),n=nr.get(this.providerName)?.timeouts?.decideMsPerKStateTokens;return r===void 0||n===void 0?r:r+Math.floor(t/1e3)*n}readDecisionPayload(e){return e}reportedConfidence(e){return{}}resolveResponseModel(e,t){return typeof e.model=="string"?e.model:t}resolveRequestModel(e){return e.model??this.modelName??this.getDefaultModel()}diagnosticContext(){return{}}getProviderName(){return this.providerName}getDefaultDecisionModel(){return this.getDefaultModel()}supportsTools(){return!1}getAISDKModel(){throw new Xe(`${this.vendorDisplayName()} is a decision-only provider; it generates no text, so chat completions are not available. Use \`decide()\` instead, or pick a different provider for \`generate()\` / \`stream()\`.`,this.providerName)}async executeStream(e,t){throw new Xe(`${this.vendorDisplayName()} is a decision-only provider; streaming is not available. Use \`decide()\`, or pick another provider for \`stream()\`.`,this.providerName)}formatProviderError(e){if(e instanceof Xe)return e;const t=e instanceof Error?e.message:String(e);return new Xe(`${this.vendorLabel()} request failed: ${t}`,this.providerName)}async decide(e){const t=this.vendorLabel();if(!this.decisionApiKey())throw this.decisionError({kind:"authentication",message:this.missingKeyMessage(),retryable:!1});const r=this.missingConfigMessage();if(r)throw this.decisionError({kind:"invalid_request",message:r,retryable:!1});if(this.authFailed)throw this.decisionError({kind:"authentication",message:`${t} rejected this API key earlier; not retrying. Fix the key and construct a new provider.`,retryable:!1});const n=Object.entries(e.questions);if(n.length===0)throw this.decisionError({kind:"invalid_request",message:"At least one question is required.",retryable:!1});const o=this.resolveRequestModel(e);this.assertSupportedQuestions(e,o);const i=this.assertWithinDecisionLimits(e,o,n.length),s=Object.fromEntries(n.map(([p,m])=>[p,this.encodeQuestion(m)])),a=await this.prepareMedia(e),u=this.buildDecisionBody(e.state,s,o,a),l=JSON.stringify(u);this.assertWithinRequestBytes(l),this.assertWithinVendorLimits(u,o);const c=e.timeoutMs??this.defaultTimeoutMs(n.length,i)??this.defaultTimeout??zhe;let d;for(let p=0;p<=this.maxRetries;p++){const m=Date.now();try{const h=AbortSignal.timeout(c),g=e.signal?AbortSignal.any([e.signal,h]):h,y=await this.proxyFetch(this.decisionEndpoint(o),{method:"POST",headers:this.decisionHeaders(),body:l,signal:g,redirect:"error"}),v=Date.now()-m,w=this.readRequestId(y.headers),b=Number(y.headers.get("x-envoy-upstream-service-time"))||void 0,E=await y.json().catch(()=>null);if(!y.ok){if(d=this.parseDecisionError(y.status,E,w),d.kind==="authentication"&&(this.authFailed=!0,f.warn(`${t}: credential not accepted \u2014 disabling this provider instance. ${d.message}`,{status:d.status,...this.diagnosticContext(),requestId:w})),!d.retryable||p===this.maxRetries)throw this.decisionError(d);const C=this.readRetryAfterMs(y.headers);if(C!==void 0&&C>c-(Date.now()-m))throw this.decisionError(d);await Ghe(C??2**p*250+Math.random()*250,e.signal);continue}const k=this.readDecisionPayload(E),A=zr(k)?this.dialect().readAnswers(k,this.reportedConfidence(k),e.questions):void 0;if(!zr(k)||!A)throw this.decisionError({kind:"server",message:`${t} returned a response without an answers map.`,status:y.status,requestId:w,retryable:!1});for(const C of A.dropped)f.warn(`${t}: dropped unparseable answer "${C}"`,{requestId:w});for(const C of A.refused??[])f.warn(`${t}: the model declined to answer "${C}"`,{requestId:w});const x={...A.answers},R=zr(k.usage)?k.usage:{};return{model:this.resolveResponseModel(k,o),provider:this.providerName,answers:x,usage:{inputTokens:Ss(R.input_tokens)??Ss(R.inputTokens)??0,outputTokens:Ss(R.output_tokens)??Ss(R.outputTokens)??0},requestId:w,latencyMs:v,upstreamMs:b,...a?{mediaBytes:a.bytes}:{}}}catch(h){if(h instanceof Xe)throw h;const g=e.signal?.aborted===!0,y=h instanceof Error&&h.name==="TimeoutError",v=rAn(h);if(d={kind:g?"network":y?"timeout":"network",message:v?`${t} answered with a redirect, which is refused so the decision is not sent anywhere else. Point the base URL at the final address.`:D_(xw(h instanceof Error?h.message:String(h)),this.decisionApiKey()),retryable:!g&&!v},!d.retryable||p===this.maxRetries)throw this.decisionError(d);await Ghe(2**p*250+Math.random()*250)}}throw this.decisionError(d??{kind:"network",message:`${t} request failed.`,retryable:!1})}assertSupportedQuestions(e,t){const r=nr.get(this.providerName),n=r?mD(r,t):null;for(const[o,i]of Object.entries(e.questions)){const s=JNe(i,n);if(s!==void 0)throw this.decisionError({kind:"invalid_request",message:`${this.vendorLabel()} cannot answer question "${o}": ${s}.`,retryable:!1})}}async prepareMedia(e){const t=nr.get(this.providerName)?.decisionLimits,r=await eAn(e,t?.media,this.vendorLabel(),Szr({video:e.video!==void 0,audio:e.audio!==void 0}));if(r.status==="refused")throw this.decisionError({kind:"invalid_request",message:r.message,retryable:!1});return r.media}assertWithinRequestBytes(e){const t=nr.get(this.providerName)?.decisionLimits?.media,r=t?.maxRequestBytes;if(r===void 0)return;const n=Buffer.byteLength(e);if(n>r)throw this.decisionError({kind:"invalid_request",message:`The request is ${n} bytes; ${this.vendorLabel()} accepts at most ${r}. Send fewer or smaller images${t?.video?", or a shorter video":""}${t?.audio?", or a shorter audio clip":""}.`,retryable:!1})}assertWithinDecisionLimits(e,t,r){const n=nr.get(this.providerName),o=n?mD(n,t):null;if(!o||!o.enforcedLocally)return 0;const i=this.vendorLabel();if(o.maxQuestions!==void 0&&r>o.maxQuestions)throw this.decisionError({kind:"max_tokens_exceeded",message:`${i} accepts at most ${o.maxQuestions} questions per request; this one has ${r}. Ask fewer, or use a decision provider without this cap.`,retryable:!1});const{maxStateTokens:s}=o,a=WNe(e.state,o);if(a>s)throw this.decisionError({kind:"max_tokens_exceeded",message:`The state is ~${a} tokens; ${i}'s "${t}" model reads at most ${s}. Shorten the state, or use a decision provider with a larger window.`,retryable:!1});return a}decisionError(e){const t=new Xe(e.message,this.providerName);return Object.defineProperty(t,"cause",{value:e,enumerable:!1,writable:!0,configurable:!0}),t}}}}),qhe,nAn=S({async"src/lib/providers/decide/formatters.ts"(){"use strict";await O_(),qhe={"fastapi-validation":e=>`Request failed validation \u2014 ${h0r(Array.isArray(e)?e:[])}`}}});function g0r(e,t){const r=t.split(".");if(r.some(o=>o===""))return;let n=e;for(const o of r){if(typeof n!="object"||n===null||Array.isArray(n))return;const i=Object.getOwnPropertyDescriptor(n,o);if(i===void 0||!("value"in i))return;n=i.value}return n}var y0r=S({"src/lib/providers/decide/paths.ts"(){"use strict"}});function oAn(e){const t=Vhe.get(e);if(t)return t;const r=new RegExp(e,"i");return Vhe.set(e,r),r}function iAn(e,t,r){return((e.status===void 0?[]:typeof e.status=="number"?[e.status]:e.status).includes(t)||e.statusMin!==void 0&&t>=e.statusMin)&&(e.messagePattern===void 0||oAn(e.messagePattern).test(r.slice(0,w0r)))}function sAn(e,t){if(e.isArray)return Array.isArray(t)&&e.formatter?qhe[e.formatter](t):void 0;if(!(typeof t!="string"||t.length===0))return e.formatter?qhe[e.formatter](t):t}function aAn(e,t){for(const r of e){const n=sAn(r,g0r(t,r.path));if(n!==void 0)return{shape:r,text:n}}}function uAn(e,t){const{status:r,payload:n,requestId:o,label:i,apiKey:s,apiKeyEnvVar:a}=t,u=D_(`${i} request failed with HTTP ${r}`,s),l=aAn(e.bodyShapes,n),c=l?.text&&D_(l.text,s)||u,d=e.rules.find(y=>iAn(y,r,c)),p=d?.kind??e.default,m=d?.retryable??jhe(p),h=d?.hint?`${c} \u2014 ${D_(d.hint.split("{apiKeyEnvVar}").join(a??"the API key variable"),s)}`:c,g=(y,v)=>({kind:y,message:h,status:r,requestId:o,retryable:v});if(l){const{shape:y}=l;return g(y.kind??p,y.retryable??(y.kind===void 0?m:jhe(y.kind)))}return g(p,m)}var v0r,jhe,w0r,Vhe,lAn=S({async"src/lib/providers/decide/errors.ts"(){"use strict";await O_(),await nAn(),y0r(),v0r=new Set(["rate_limit","overloaded","server"]),jhe=e=>v0r.has(e),w0r=2e3,Vhe=new Map}});function cAn(e,t){if(/[{}]/.test(e.replace(Hhe,"")))throw new Error(`Decide endpoint template "${e}" has an unmatched brace; write placeholders as {baseURL}.`);return e.replace(Hhe,(r,n)=>{if(n!=="baseURL")throw new Error(`Decide endpoint template "${e}" uses an unknown placeholder {${n}}; the only one supported is {baseURL}.`);return t.baseURL})}var Hhe,dAn=S({"src/lib/providers/decide/template.ts"(){"use strict";Hhe=/\{([^{}]*)\}/g}}),b0r={};ue(b0r,{ConfiguredDecisionProvider:()=>_0r});var By,T0r,_0r,pAn=S({async"src/lib/providers/configuredDecision.ts"(){"use strict";hD(),z(),zt(),li(),nh(),LH(),T7r(),await lAn(),Dk(),y0r(),dAn(),await O_(),By=e=>typeof e=="string"?e.trim():"",T0r=e=>typeof e=="string"?e:JSON.stringify(e),_0r=class extends VI{entry;apiKey;baseURL;endpoint;constructor(e,t,r,n){super(t||rs(ho(e,"model"),e.models.default),e.id,r),this.entry=e,this.apiKey=By(n?.apiKey)||By(process.env[ho(e,"apiKey")]),this.baseURL=c7r(By(n?.baseURL)||By(process.env[ho(e,"baseURL")])||By(e.wire.baseURL),e.decide.baseURLNormalize??[]),this.endpoint=cAn(e.decide.endpoint,{baseURL:this.baseURL}),f.debug(`${e.displayName} Provider initialized (decide only)`,{modelName:this.modelName,baseURL:this.baseURL?sr(this.baseURL):"(not set)"})}getDefaultModel(){return rs(ho(this.entry,"model"),this.entry.models.default)}vendorLabel(){return this.entry.displayName}vendorDisplayName(){return this.entry.displayName}decisionApiKey(){return this.apiKey}missingKeyMessage(){return`${this.entry.displayName} requires an API key. Set ${ho(this.entry,"apiKey")} or pass credentials.${Cw(this.entry)}.apiKey.`}missingConfigMessage(){const{baseURLRequired:e,baseURLShape:t}=this.entry.decide;return this.baseURL?t?p7r(t,this.baseURL,this.entry.displayName,`Set ${ho(this.entry,"baseURL")} or pass credentials.${Cw(this.entry)}.baseURL to the origin, and give the key through ${ho(this.entry,"apiKey")} or credentials.${Cw(this.entry)}.apiKey.`):void 0:e?`${this.entry.displayName} requires a base URL. Set ${ho(this.entry,"baseURL")} or pass credentials.${Cw(this.entry)}.baseURL.`:void 0}decisionEndpoint(){return this.endpoint}resolveRequestModel(e){const t=super.resolveRequestModel(e),r=this.entry.decide.capableModel;if(r===void 0||e.model!==void 0||t!==this.entry.models.default||By(process.env[ho(this.entry,"model")])!=="")return t;const n=(e.images?.length??0)>0||e.video!==void 0||e.audio!==void 0,o=Object.values(e.questions).some(i=>r.questionTypes.includes(KNe(i)));return n||o?r.model:t}decisionHeaders(){return{...this.entry.decide.authHeader==="x-api-key"?{"x-api-key":this.apiKey}:{Authorization:`Bearer ${this.apiKey}`},"Content-Type":"application/json"}}encodeState(e){if(this.entry.decide.stateEncoding!=="text")return e;const t=T0r(e);if(t===void 0||t.trim()==="")throw this.decisionError({kind:"invalid_request",message:`${this.vendorLabel()} needs non-blank state text; the state was empty or only whitespace.`,retryable:!1});return t}buildDecisionBody(e,t,r,n){const{placement:o,alias:i}=this.entry.decide.model;return this.dialect().buildBody({state:this.encodeState(e),questions:t,model:o==="body-unless-alias"&&r===i?void 0:r,media:n,mediaKeys:this.entry.decide.media})}parseDecisionError(e,t,r){return uAn(this.entry.decide.errors,{status:e,payload:t,requestId:r,label:this.entry.displayName,apiKey:this.apiKey,apiKeyEnvVar:ho(this.entry,"apiKey")})}readRequestId(e){for(const t of this.entry.decide.requestIdHeaders??[]){const r=e.get(t);if(r!==null)return r}}resolveResponseModel(e,t){if(!zr(e))return t;for(const r of this.entry.decide.response?.modelPaths??[]){const n=g0r(e,r);if(typeof n=="string")return n}return super.resolveResponseModel(e,t)}dialect(){return c3e(this.entry.decide.dialect)}}}});async function zy(e,t){try{await e}catch(r){f.debug(`[${t}] detached stream pump rejected; reason absorbed because the turn's own error is authoritative`,r)}}var Whe=S({"src/lib/utils/drainDetachedPump.ts"(){"use strict";z()}});function Gy(e,t,r){return async(n,o)=>{const i=()=>Promise.resolve(t(n,o));r.onProgress?.();try{const s=r.abortSignal?oc(i(),r.abortSignal):i();return await(r.toolTimeoutMs===void 0||r.toolTimeoutMs===null?s:kt(s,r.toolTimeoutMs,`Tool "${e}" execution timed out after ${r.toolTimeoutMs}ms`))}finally{r.onProgress?.()}}}var U5=S({"src/lib/core/toolExecutionGuards.ts"(){"use strict";j0()}});function mAn(e,t){const r=S0r[e];return Math.round(t.min+r*(t.max-t.min))}function Khe(e,t){if(!e?.enabled&&!e?.thinkingLevel)return;const r=e.thinkingLevel??E0r;if(t&&!Qan(t)){const n=eun(t);if(n)return{includeThoughts:!0,thinkingBudget:mAn(r,n)};Jhe.has(t)||(Jhe.add(t),f.warn(`[thinkingConfig] "${t}" has no verified Gemini thinkingBudget range; omitting thinkingConfig \u2014 requested thinkingLevel is silently disabled.`));return}return{includeThoughts:!0,thinkingLevel:r}}var E0r,S0r,Jhe,k0r=S({"src/lib/utils/thinkingConfig.ts"(){"use strict";iL(),z(),E0r="high",S0r={minimal:0,low:.25,medium:.55,high:1},Jhe=new Set}});function hAn(e){return JSON.stringify(e,(t,r)=>r&&typeof r=="object"&&!Array.isArray(r)?Object.keys(r).sort().reduce((n,o)=>(n[o]=r[o],n),{}):r)}function fAn(e){if(F0r.test(e))return e;let t=e.replace(/[^A-Za-z0-9_.:-]/g,"_");return/^[A-Za-z_]/.test(t)||(t=`_${t}`),t.length>q5&&(t=t.slice(0,q5)),t}function gAn(e,t){if(!t(e))return e;let r=2;for(;;){const n=`_${r}`,i=`${e.slice(0,q5-n.length)}${n}`;if(!t(i))return i;r++}}function vf(e){if(Array.isArray(e.anyOf)||Array.isArray(e.oneOf)){const n=e.anyOf?"anyOf":"oneOf",o=e[n],i=o.filter(l=>l.type!=="null"&&l.type!=="undefined");if(i.length===1){const l=vf({...i[0]});return l.nullable=!0,e.description&&(l.description=e.description),l}const s=i.map(l=>l.type||"unknown").join(" | "),a={type:"string"},u=e.description?`${e.description} (accepts: ${s})`:`Value as string (accepts: ${s})`;return a.description=u,o.some(l=>l.type==="null")&&(a.nullable=!0),a}const t={};for(const[n,o]of Object.entries(e))if(!(n==="$schema"||n==="additionalProperties"||n==="default"))if(n==="properties"&&o&&typeof o=="object"){const i={};for(const[s,a]of Object.entries(o))a&&typeof a=="object"?i[s]=vf(a):i[s]=a;t[n]=i}else n==="items"&&o&&typeof o=="object"?Array.isArray(o)?t[n]=o.map(i=>i&&typeof i=="object"?vf(i):i):t[n]=vf(o):t[n]=o;Array.isArray(t.allOf)&&(t.allOf=t.allOf.map(n=>vf(n))),t.not&&typeof t.not=="object"&&(t.not=vf(t.not));for(const n of["if","then","else"])t[n]&&typeof t[n]=="object"&&(t[n]=vf(t[n]));typeof t.exclusiveMinimum=="boolean"&&(t.exclusiveMinimum===!0&&typeof t.minimum=="number"?(t.exclusiveMinimum=t.minimum,delete t.minimum):delete t.exclusiveMinimum),typeof t.exclusiveMaximum=="boolean"&&(t.exclusiveMaximum===!0&&typeof t.maximum=="number"?(t.exclusiveMaximum=t.maximum,delete t.maximum):delete t.exclusiveMaximum);const r=2147483647;return typeof t.maximum=="number"&&t.maximum>r&&delete t.maximum,typeof t.minimum=="number"&&t.minimum<-r&&delete t.minimum,t}function A0r(e,t){const r=[],n=new F_,o=[],i=[],s=new Set(t??[]),a=new Map;for(const[u,l]of Object.entries(e))try{const c=fAn(u),d=gAn(c,h=>s.has(h));a.set(d,u),d!==u&&i.push({from:u,to:d});const p={name:d,description:l.description||`Tool: ${d}`},m=l;if(m.parameters||l.inputSchema){let h;const g=m.parameters||l.inputSchema;KQ(g)?h=Ti(g,"openApi3"):typeof g=="object"?h=g:h={type:"object",properties:{}},h.jsonSchema&&typeof h.jsonSchema=="object"&&!h.type&&(h=h.jsonSchema),p.parametersJsonSchema=vf(io(h))}r.push(p),s.add(d),l.execute&&n.set(p.name,l.execute)}catch(c){o.push(u),f.error(`[buildNativeToolDeclarations] Failed to convert tool "${u}":`,c)}return o.length>0&&f.warn(`[buildNativeToolDeclarations] ${o.length} tool(s) skipped due to schema errors: ${o.join(", ")}`),i.length>0&&f.warn(`[buildNativeToolDeclarations] ${i.length} tool name(s) sanitized for Google's function-name regex: ${i.map(u=>`"${u.from}" -> "${u.to}"`).join(", ")}`),{toolsConfig:[{functionDeclarations:r}],executeMap:n,originalNameMap:a}}function B5(e,t,r){const n={},o=(i,s)=>r?Gy(i,s,r):async(a,u)=>s(a,u);if(e){for(const[i,s]of e.originalNameMap){const a=e.executeMap.get(i);a&&(n[s]={execute:o(s,a)})}return n}for(const[i,s]of Object.entries(t??{})){const a=s?.execute;a&&(n[i]={execute:o(i,a)})}return n}function yAn(e,t){if(!e)return[];const r=new Set(t.originalNameMap.values()),n=Object.entries(e).filter(([i])=>!r.has(i));if(n.length===0)return[];const o=A0r(Object.fromEntries(n),new Set(t.originalNameMap.keys()));t.toolsConfig[0].functionDeclarations.push(...o.toolsConfig[0].functionDeclarations);for(const[i,s]of o.originalNameMap)t.originalNameMap.set(i,s);for(const[i,s]of o.executeMap)t.executeMap.set(i,s);return f.info(`[buildNativeToolDeclarations] ${n.length} tool(s) hydrated mid-turn via discovery: ${n.map(([i])=>i).join(", ")}`),n.map(([i])=>i)}function x0r(e,t){const r=sc("google-ai",e.model,{temperature:e.temperature??1,topP:e.topP},"googleAiStudio.buildNativeConfig"),n={...r.temperature!==void 0&&{temperature:r.temperature},...r.topP!==void 0&&{topP:r.topP},maxOutputTokens:e.maxTokens};t&&(n.tools=t),e.systemPrompt&&(n.systemInstruction=e.systemPrompt);const o=Khe(e.thinkingConfig,e.model);return o&&(n.thinkingConfig=o),t||((e.responseSchema||e.wantsJsonOutput)&&(n.responseMimeType="application/json"),e.responseSchema&&(n.responseSchema=e.responseSchema)),n}function C0r(e){const t=e||_s;return Number.isFinite(t)&&t>0?Math.min(Math.floor(t),tfe):Math.min(_s,tfe)}function qy(e){switch(e){case"MAX_TOKENS":case"CONTINUATION":return"length";case"TOO_MANY_TOOL_CALLS":return"tool-calls";case"MALFORMED_FUNCTION_CALL":case"UNEXPECTED_TOOL_CALL":return"error";case"SAFETY":case"RECITATION":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":case"LANGUAGE":case"IMAGE_SAFETY":case"IMAGE_PROHIBITED_CONTENT":case"IMAGE_RECITATION":return"content-filter";default:return"stop"}}function vAn(e,t){return t?e?`${e}
|
|
2011
2011
|
${t}`:t:e}async function wAn(e,t){const r=[],n=[];let o=0,i=0,s=0,a=0,u;for await(const l of e){const c=l,p=c.candidates?.[0],m=p?.finishReason;typeof m=="string"&&(u=m);const h=p?.content;if(h&&Array.isArray(h.parts))for(const y of h.parts)r.push(y),typeof y.text=="string"&&y.text.length>0&&t.push({content:y.text});l.functionCalls&&n.push(...l.functionCalls);const g=c.usageMetadata;g&&(o=Math.max(o,g.promptTokenCount||0),i=Math.max(i,g.candidatesTokenCount||0),s=Math.max(s,g.cachedContentTokenCount||0),a=Math.max(a,g.thoughtsTokenCount||0))}return{rawResponseParts:r,stepFunctionCalls:n,finishReason:u,inputTokens:o,outputTokens:i,cacheReadTokens:s,reasoningTokens:a}}function z5(e){for(let t=e.length-1;t>=0;t--){const r=e[t];if(r!=null&&typeof r=="object"&&"thoughtSignature"in r&&typeof r.thoughtSignature=="string")return r.thoughtSignature}}function bAn(e){return e.filter(t=>typeof t.text=="string").map(t=>t.text).join("")}function I0r(e,t,r,n,o){return t>=r&&!n?(f.warn(`${e} Tool call loop terminated after reaching maxSteps (${r}). Model was still calling tools. Using accumulated text from last step.`),o||bf(r,0)):n}function wf(e){if(!e)return!1;const t=e;return t.name==="AbortError"||typeof t.message=="string"&&/abort/i.test(t.message)||typeof DOMException<"u"&&e instanceof DOMException&&t.code===20}function bf(e,t){return`${t>0?`I gathered information across ${t} tool call${t===1?"":"s"} but `:"I "}reached the ${e}-step limit for a single turn before I could finish. Please narrow the request or break it into smaller asks and I'll continue.`}function Bl(e){return`${e>0?`I gathered information across ${e} tool call${e===1?"":"s"} but `:"I "}had to stop because the gathered material filled this turn's context window before I could finish. Please narrow the request or break it into smaller asks and I'll continue.`}function R0r(e){const t=Math.max(0,Math.round(e/1e3)),r=Math.floor(t/60),n=t%60;return r>0?`${r}m ${n}s`:`${n}s`}function TAn(e,t){const r=t>0?` I completed ${t} tool call${t===1?"":"s"} before stopping;`:"";return`I had to stop after ${R0r(e)} \u2014 this turn hit its processing time limit.${r} ask me to continue and I'll pick up from there.`}function _An(e,t){const r=t>0?` I completed ${t} tool call${t===1?"":"s"} before stopping;`:"";return`I had to stop because this turn made no progress for ${R0r(e)} \u2014 a tool or model call appears to be stuck.${r} ask me to continue and I'll pick up from there.`}function EAn(e){return`This turn was stopped before I could finish.${e>0?` I completed ${e} tool call${e===1?"":"s"} before stopping.`:""}`}function Xhe(e){return e.timedOut?TAn(e.elapsedMs,e.toolCallCount):e.stalled?_An(e.stallTimeoutMs??0,e.toolCallCount):e.wasAborted?EAn(e.toolCallCount):bf(e.maxSteps,e.toolCallCount)}function N_(e){return"NOTE: processing time for this turn is nearly up. Consolidate what you have and "+(e?"call final_result with your best answer now.":"provide your final answer now.")}function pm(e){return e.timedOut?"time-limit":e.stalled?"stalled":e.wasAborted?"aborted":e.contextCappedWithoutAnswer?"context-cap":e.cappedWithoutAnswer?"step-cap":e.finishReason==="error"?"provider-error":"completed"}function L_(e){const t=Date.now(),r=c=>c!==void 0&&Number.isFinite(c)&&c>0,n=r(e.turnTimeoutMs)?e.turnTimeoutMs:r(e.defaultTurnTimeoutMs)?e.defaultTurnTimeoutMs:void 0,o=r(e.turnTimeoutMs)?e.wrapupTimeLeadMs??KOe:void 0;let i=!1,s=!1,a=t,u,l;if(n!==void 0&&(u=setTimeout(()=>{i=!0,e.onDeadline("timeout")},n),u.unref?.()),r(e.stallTimeoutMs)){const c=e.stallTimeoutMs,d=Math.min(Math.max(1e3,Math.floor(c/4)),15e3);l=setInterval(()=>{!s&&!i&&Date.now()-a>=c&&(s=!0,e.onDeadline("stall"))},d),l.unref?.()}return{get timedOut(){return i},get stalled(){return s},get expired(){return i||s},get turnTimeoutMs(){return n},elapsedMs(){return Date.now()-t},noteProgress(){a=Date.now()},shouldNudgeWrapup(){if(n===void 0||o===void 0)return!1;const c=n-(Date.now()-t);return c>0&&c<=o},dispose(){u&&clearTimeout(u),l&&clearInterval(l)}}}function $_(e,t=aD){const r=Math.floor(e*t);let n=0,o=0;return{get thresholdTokens(){return r},get projectedNextPromptTokens(){return n+o},noteUsage(i,s){i>0&&(n=i,o=Math.max(0,s))},noteAppendedChars(i){i>0&&(o+=Math.ceil(i/4))},resetAfterReclaim(){n=0,o=0},shouldStop(){return n>0&&n+o>=r}}}function SAn(e,t,r){e.push({role:"model",parts:t.length>0?t:r.map(n=>({functionCall:n}))})}function M0r(e){const t=Ti(e,"openApi3"),r=io(t);return r.$schema&&delete r.$schema,ba(r)}function G5(e,t){if(!t||t.length===0)return;const r=new Map,n=[];let o=0;const i=a=>`${o}:${a??"undefined"}`,s=a=>{const u=i(a),l=r.get(u);if(l)return l;const c={type:"tool_step",callParts:[],resultParts:[]};return r.set(u,c),n.push(c),c};for(const a of t){if(a.role==="tool_call"){const c=s(a.metadata?.stepIndex),d={functionCall:{name:a.tool||"unknown",args:a.args||{}}};a.metadata?.thoughtSignature&&(d.thoughtSignature=a.metadata.thoughtSignature),c.callParts.push(d);continue}if(a.role==="tool_result"){const c=s(a.metadata?.stepIndex);let d;try{d=a.content!==void 0&&a.content!==null?{result:JSON.parse(a.content)}:{result:"success"}}catch{d={result:a.content??"success"}}c.resultParts.push({functionResponse:{name:a.tool||"unknown",response:d}});continue}const u=a.role==="assistant"?"model":a.role;if(u!=="user"&&u!=="model"||!a.content||a.content.trim().length===0)continue;o++;const l={text:a.content};a.metadata?.thoughtSignature&&(l.thoughtSignature=a.metadata.thoughtSignature),n.push({type:"regular",role:u,parts:[l]})}for(const a of n){if(a.type==="regular"){e.push({role:a.role,parts:a.parts});continue}if(a.callParts.length===0){a.resultParts.length>0&&f.debug("[GoogleNativeGemini3] Dropping orphan tool_result segment with no matching tool_call rows",{resultCount:a.resultParts.length});continue}e.push({role:"model",parts:a.callParts}),a.resultParts.length>0&&e.push({role:"user",parts:a.resultParts})}}function P0r(e){return typeof e!="object"||e===null||!("text"in e)?!1:typeof e.text=="string"}function kAn(e){if(typeof e!="object"||e===null||!("inlineData"in e))return!1;const t=e.inlineData;return typeof t=="object"&&t!==null&&"mimeType"in t&&"data"in t}function AAn(e){return typeof e=="object"&&e!==null&&"functionCall"in e}function D0r(e){return typeof e=="object"&&e!==null&&"functionResponse"in e}function O0r(e){if(!(typeof e!="object"||e===null||!("thoughtSignature"in e)))return typeof e.thoughtSignature=="string"?e.thoughtSignature:void 0}function Yhe(e,t){return t?{...e,providerOptions:{...e.providerOptions,googleAiStudio:{...e.providerOptions?.googleAiStudio,thoughtSignature:t}}}:e}function Zhe(e){if(typeof e!="object"||e===null)return;const t=e.googleAiStudio;if(typeof t!="object"||t===null)return;const r=t.thoughtSignature;return typeof r=="string"?r:void 0}function xAn(e){return e.length>0&&e.every(D0r)}function CAn(e){if(D0r(e))return{type:"tool-result",toolCallId:`gemini-tool-${Wr()}`,toolName:e.functionResponse.name,output:e.functionResponse.response}}function IAn(e){if(P0r(e))return Yhe({type:"text",text:e.text},O0r(e));if(kAn(e))return{type:"file",data:e.inlineData.data,mediaType:e.inlineData.mimeType}}function RAn(e){if(P0r(e))return Yhe({type:"text",text:e.text},O0r(e));if(AAn(e))return Yhe({type:"tool-call",toolCallId:`gemini-tool-${Wr()}`,toolName:e.functionCall.name,input:e.functionCall.args??{}},e.thoughtSignature)}function MAn(e){const t=[];for(const r of e){const n=Array.isArray(r.parts)?r.parts:[];if(r.role==="user"&&xAn(n)){const o=n.map(CAn).filter(i=>i!==void 0);o.length>0&&t.push({role:"tool",content:o});continue}if(r.role==="user"){const o=n.map(IAn).filter(i=>i!==void 0);o.length>0&&t.push({role:"user",content:o});continue}if(r.role==="model"){const o=n.map(RAn).filter(i=>i!==void 0);o.length>0&&t.push({role:"assistant",content:o})}}return t}function N0r(e){return typeof e=="string"?e:Buffer.isBuffer(e)?e.toString("base64"):e instanceof ArrayBuffer?Buffer.from(e).toString("base64"):Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64")}function PAn(e){if(typeof e=="string")return e.length>0?[{text:e}]:[];const t=[];for(const r of e)if(r.type==="text"){if(r.text.length>0){const n=Zhe(r.providerOptions);t.push(n?{text:r.text,thoughtSignature:n}:{text:r.text})}}else r.type==="image"&&!(r.image instanceof URL)?t.push({inlineData:{mimeType:r.mediaType??"application/octet-stream",data:N0r(r.image)}}):r.type==="file"&&!(r.data instanceof URL)&&t.push({inlineData:{mimeType:r.mediaType,data:N0r(r.data)}});return t}function DAn(e){if(typeof e=="string")return e.length>0?[{text:e}]:[];const t=[];for(const r of e)if(r.type==="text"){if(r.text.length>0){const n=Zhe(r.providerOptions);t.push(n?{text:r.text,thoughtSignature:n}:{text:r.text})}}else if(r.type==="tool-call"){const n=Zhe(r.providerOptions),o={functionCall:{name:r.toolName,args:r.input??{}}};n&&(o.thoughtSignature=n),t.push(o)}return t}function OAn(e){const t=[];for(const r of e)r.type==="tool-result"&&t.push({functionResponse:{name:r.toolName,response:r.output&&typeof r.output=="object"?r.output:{result:r.output}}});return t}function L0r(e){const t=[],r=[];for(const n of e){if(n.role==="system"){n.content.length>0&&r.push(n.content);continue}if(n.role==="user"){const i=PAn(n.content);i.length>0&&t.push({role:"user",parts:i});continue}if(n.role==="assistant"){const i=DAn(n.content);i.length>0&&t.push({role:"model",parts:i});continue}const o=OAn(n.content);o.length>0&&t.push({role:"user",parts:o})}return r.length>0?{contents:t,systemText:r.join(`
|
|
2012
2012
|
|
|
2013
2013
|
`)}:{contents:t}}async function Qhe(e,t,r="[GeminiNative]"){if(!(!t||t.length===0))for(const n of t){const o=n.filename.split(/[\\/]/).pop()??n.filename,i=o.lastIndexOf("."),s=i>0?o.slice(i):".bin",a=await CVt(n.buffer,n.mimeType,s);if(Une(a.mimeType)){f.warn(`${r} Skipping native audio for ${o}: ${a.mimeType} is not accepted and could not be converted. The metadata summary was still included.`);continue}e.push({inlineData:{mimeType:a.mimeType,data:a.buffer.toString("base64")}}),f.debug(`${r} Added native audio part for ${o} (${a.mimeType})`)}}async function efe(e,t,r,n,o="[GeminiNative]"){if(!t||t.length===0)return;let i=e.reduce((s,a)=>"inlineData"in a?s+Math.floor(a.inlineData.data.length*3/4):s,0);for(const s of t){const a=s.filename.split(/[\\/]/).pop()??s.filename,u=LVt(r,s,i,n);if(!u.deliver){f.warn(`${o} Sending keyframes instead of the clip for ${a}: ${u.reason}.`);continue}i+=s.buffer.length,e.push({inlineData:{mimeType:s.mimeType,data:s.buffer.toString("base64")}}),f.debug(`${o} Added native video part for ${a} (${s.mimeType})`)}}async function $0r(e,t,r="[GeminiNative]",n){const i=[{text:typeof t=="string"?t:e?.text??""}];if(e?.pdfFiles&&e.pdfFiles.length>0){f.debug(`${r} Processing ${e.pdfFiles.length} PDF(s)`);for(const s of e.pdfFiles){let a;typeof s=="string"?wi(s)?a=As(s):a=Buffer.from(s,"base64"):a=s,i.push({inlineData:{mimeType:"application/pdf",data:a.toString("base64")}})}}if(e?.images&&e.images.length>0){f.debug(`${r} Processing ${e.images.length} image(s)`);for(const s of e.images){const a=s&&typeof s=="object"&&!Buffer.isBuffer(s)?s.data:s;let u,l="image/jpeg";if(typeof a=="string")if(wi(a)){u=As(a);const c=Lw(a).toLowerCase();c===".png"?l="image/png":c===".gif"?l="image/gif":c===".webp"&&(l="image/webp")}else if(a.startsWith("data:")){const c=a.match(/^data:([^;]+);base64,(.+)$/);if(c)l=c[1],u=Buffer.from(c[2],"base64");else continue}else if(a.startsWith("http://")||a.startsWith("https://"))try{const c=await fetch(a);if(!c.ok){f.warn(`${r} Image fetch failed: ${c.status} ${c.statusText}, skipping`,{url:a});continue}const d=await c.arrayBuffer();u=Buffer.from(d);const p=c.headers.get("content-type");p&&p.startsWith("image/")&&(l=p.split(";")[0])}catch(c){f.warn(`${r} Image URL fetch threw, skipping: ${c instanceof Error?c.message:String(c)}`,{url:a});continue}else u=Buffer.from(a,"base64");else u=a;u&&i.push({inlineData:{mimeType:l,data:u.toString("base64")}})}}return await Qhe(i,e?.nativeAudioFiles,r),await efe(i,e?.nativeVideoFiles,"google-ai-studio",n,r),i}var F_,F0r,q5,tfe,j5=S({"src/lib/providers/googleNativeGemini3/utils.ts"(){"use strict";Pr(),Hr(),Lt(),ci(),PVt(),zne(),z(),U5(),uc(),ls(),k0r(),F_=class extends Map{resultCache=new Map;get(e){const t=super.get(e);if(!t)return t;const r=this.resultCache;return async(o,i)=>{const s=`${e}::${hAn(o)}`;if(r.has(s))return f.warn(`[DedupExecuteMap] Tool "${e}" re-requested with identical arguments in the same turn \u2014 reusing the previous result instead of re-executing.`),r.get(s);const a=await t(o,i);return r.set(s,a),a}}},F0r=/^[A-Za-z_][A-Za-z0-9_.:-]{0,127}$/,q5=128,tfe=100}});function U0r(e,t){const r=t.config??{},n=r.thinkingConfig;return{provider:e,model:t.model,modelParameters:{temperature:r.temperature,maxTokens:r.maxOutputTokens,topP:r.topP,thinkingLevel:n?.thinkingLevel,thinkingBudget:n?.thinkingBudget},input:{system:r.systemInstruction,messages:t.contents}}}function V5(e){const t=o=>e.declarations?.originalNameMap?.get(o)??o,r=o=>{const i=e.declarations?.originalNameMap;if(!i)return o;for(const[s,a]of i)if(a===o)return s;return o};let n=0;return{providerLabel:e.providerLabel,maxSteps:e.maxSteps,...e.toolFailureBreaker?{toolFailureBreaker:e.toolFailureBreaker}:{},buildStepRequest(o,i){const s=e.declarations?yAn(e.liveTools,e.declarations):[],a=e.buildRequest(o,i);return{raw:a,generation:U0r(e.provider,a),...s.length>0?{hydratedToolNames:s}:{}}},...e.planReclaim?{planReclaim:(o,i)=>e.planReclaim?.(o,i)}:{},...e.enableMalformedRetry&&e.buildMalformedRetryNote?{isMalformedStep:o=>o.toolCalls.length===0&&!o.text&&o.rawStopReason==="MALFORMED_FUNCTION_CALL",buildMalformedRetryNote:e.buildMalformedRetryNote}:{},resolveToolOnMiss:o=>{const s=yee(e.liveTools,o)?.execute;if(!s)return;const a=e.declarations?.executeMap;let u=s;return a&&(a.set(o,s),u=a.get(o)??s),{execute:e.toolGuards?Gy(o,u,e.toolGuards):(async(c,d)=>u(c,d))}},async executeStep(o,i,s){const a=await e.sendStep(o.raw,s),u=e.collectStep?await e.collectStep(a,i):await wAn(a,{push:h=>i.push(h)});e.noteUsage?.(u.inputTokens,u.outputTokens);const l=bAn(u.rawResponseParts),c=u.stepFunctionCalls.map(h=>({id:`${e.providerLabel}_${n++}_${h.name}`,name:t(h.name),args:h.args})),d=e.finalResultToolName?c.find(h=>h.name===e.finalResultToolName):void 0,p=d?[]:c,m=d?JSON.stringify(d.args):l;return d&&e.onTerminalResult?.(m),{text:m,toolCalls:p,usage:{inputTokens:u.inputTokens,outputTokens:u.outputTokens,...u.cacheReadTokens?{cacheReadTokens:u.cacheReadTokens}:{},...u.reasoningTokens?{reasoningTokens:u.reasoningTokens}:{}},rawStopReason:u.finishReason,raw:{rawResponseParts:u.rawResponseParts,stepFunctionCalls:u.stepFunctionCalls}}},buildToolResultMessages(o,i,s,a){const u=[...o];return SAn(u,i.raw.rawResponseParts,i.raw.stepFunctionCalls),u.push({role:"user",parts:s.map(l=>({functionResponse:{name:r(l.name),response:l.error?l.output:{result:l.output}}}))}),u},observedUsage(o){const i=o.cacheReadTokens===void 0?void 0:Math.min(o.cacheReadTokens,o.inputTokens);return{...o,inputTokens:Math.max(0,o.inputTokens-(i??0)),outputTokens:o.outputTokens+(o.reasoningTokens??0),...i!==void 0&&{cacheReadTokens:i}}},mapFinishReason(o,i){const s=qy(o);return s==="stop"||s==="tool-calls"?i?"tool-calls":"stop":s}}}var B0r=S({"src/lib/core/geminiLoopAdapter.ts"(){"use strict";U5(),vb(),j5()}});function U_(){const e=[];let t=!1,r,n=!1,o=null;function i(){if(o){const d=o;o=null,d()}}function s(d){t||(e.push(d),i())}function a(){t=!0,i()}function u(d){t=!0,r=d,n=!0,i()}let l=0;async function*c(){try{for(;;)if(l<e.length)yield e[l++],l>1024&&l*2>=e.length&&(e.splice(0,l),l=0);else if(t){if(n)throw r instanceof Error?r:new Error(String(r));return}else await new Promise(d=>{o=d})}finally{t=!0,e.length=0,o?.()}}return{push:s,close:a,error:u,iterable:c()}}var B_=S({"src/lib/core/streamChannel.ts"(){"use strict"}});function NAn(e,t){return{inputTokens:e.inputTokens+t.inputTokens,outputTokens:e.outputTokens+t.outputTokens,cacheReadTokens:(e.cacheReadTokens??0)+(t.cacheReadTokens??0)||void 0,cacheWriteTokens:(e.cacheWriteTokens??0)+(t.cacheWriteTokens??0)||void 0,reasoningTokens:(e.reasoningTokens??0)+(t.reasoningTokens??0)||void 0,cacheWrite5mTokens:(e.cacheWrite5mTokens??0)+(t.cacheWrite5mTokens??0)||void 0,cacheWrite1hTokens:(e.cacheWrite1hTokens??0)+(t.cacheWrite1hTokens??0)||void 0}}async function LAn(e){const{name:t,execute:r,args:n,toolCallId:o,turnSignal:i,toolTimeoutMs:s}=e;if(s===null)return r(n,{toolCallId:o,abortSignal:i});const a=new AbortController,u=()=>a.abort(i.reason);i.aborted?a.abort(i.reason):i.addEventListener("abort",u,{once:!0});let l;const c=new Promise((d,p)=>{l=setTimeout(()=>{const m=new Error(`Tool "${t}" execution timed out after ${s}ms`);a.abort(m),p(m)},s)});try{return await Promise.race([Promise.resolve(r(n,{toolCallId:o,abortSignal:a.signal})),c])}finally{clearTimeout(l),i.removeEventListener("abort",u)}}async function $An(e){const{calls:t,adapter:r,tools:n,failedTools:o,abortSignal:i,toolTimeoutMs:s}=e,a=[],u=[],l=[];let c=!1;for(const d of t){if(i.aborted){c=!0;break}l.push(d);const p=r.toolFailureBreaker,m=p?o.get(d.name):void 0;if(p&&m&&m.count>=p.maxRetries){const y={error:`TOOL_PERMANENTLY_FAILED: "${d.name}" has failed ${m.count} times. Last error: ${m.lastError}.`,status:"permanently_failed",do_not_retry:!0};a.push({...d,output:y,error:y.error,permanentlyFailed:!0}),u.push({id:d.id,name:d.name,input:d.args,output:y,error:y.error});continue}const h=n?.[d.name];let g=h;if(!h?.execute){const y=r.resolveToolOnMiss?.(d.name);y&&(g=y,o.delete(d.name))}if(!g?.execute){const y=p?{error:`TOOL_NOT_FOUND: "${d.name}" does not exist.`,status:"permanently_failed",do_not_retry:!0}:{error:`Tool not found: ${d.name}`};a.push({...d,output:y,error:y.error,permanentlyFailed:!!p}),u.push({id:d.id,name:d.name,input:d.args,output:y,error:y.error});continue}try{const y=await LAn({name:d.name,execute:g.execute,args:d.args,toolCallId:d.id,turnSignal:i,toolTimeoutMs:s}),v=p?.classifyResultFailure?.(y);if(p)if(v){const w=o.get(d.name)??{count:0,lastError:""};w.count++,w.lastError=v,o.set(d.name,w)}else p.consecutive&&o.delete(d.name);a.push({...d,output:y}),u.push({id:d.id,name:d.name,input:d.args,output:y})}catch(y){const v=y instanceof Error?y.message:String(y);if(p){const b=o.get(d.name)??{count:0,lastError:""};b.count++,b.lastError=v,o.set(d.name,b)}const w={error:v,status:"failed"};a.push({...d,output:w,error:v}),u.push({id:d.id,name:d.name,input:d.args,output:w,error:v})}}return{toolResults:a,executions:u,dispatched:l,abortedMidBatch:c}}async function FAn(e,t,r,n,o){let i=!1,s;const a={push:u=>{i=!0,s??=new Date,r.push(u)}};return yh(t.generation??{},async u=>{let l;try{l=await kw(async()=>{i=!1;try{return await e.executeStep(t,a,n)}catch(d){throw i?new rfe(d):d}},o,`${e.providerLabel}.step`,void 0,n)}catch(d){throw d instanceof rfe?d.cause:d}const c=e.observedUsage?.(l.usage)??l.usage;return Tl(u,{provider:t.generation?.provider,model:t.generation?.model,responseModel:l.model,output:{text:l.text,...l.reasoning?{reasoning:l.reasoning}:{},...l.toolCalls.length>0?{toolCalls:l.toolCalls}:{}},usage:{inputTokens:c.inputTokens,outputTokens:c.outputTokens,cacheReadTokens:c.cacheReadTokens,cacheCreationTokens:c.cacheWriteTokens,reasoningTokens:c.reasoningTokens},finishReason:l.rawStopReason??(n.aborted?"other":void 0),aborted:n.aborted,completionStartTime:s}),l})}function mm(e,t,r){const n=U_(),o=new AbortController,i=()=>o.abort();r.abortSignal?.addEventListener("abort",i),r.abortSignal?.aborted&&o.abort();const s=new Map;let a=!1;const u=(async()=>{let l=t,c={inputTokens:0,outputTokens:0},d="",p="",m;const h=[],g=[];let y=!1,v=e.maxSteps;const w=Date.now(),b=new zO(r.operation);try{for(let A=0;A<v&&!o.signal.aborted;A++){if(b.begin(A+1),e.planReclaim){const L=e.planReclaim(l,A);if(L?.conversation!==void 0&&(l=L.conversation),L?.stop)break}const x=await e.buildStepRequest(l,A);for(const L of x.hydratedToolNames??[])s.delete(L);const R=await b.run(()=>FAn(e,x,n,o.signal,r.span));if(c=NAn(c,R.usage),m=R.rawStopReason,p=R.text||p,e.isMalformedStep?.(R)&&!a&&!o.signal.aborted){a=!0,f.warn(`[${e.providerLabel}] Malformed function call at step ${A+1}/${v}; retrying once.`),l=e.buildMalformedRetryNote?.(l,A)??l;continue}if(R.toolCalls.length===0){d=R.text||d;break}A===v-1&&(y=!0);const C=await b.run(()=>$An({calls:R.toolCalls,adapter:e,tools:r.tools,failedTools:s,abortSignal:o.signal,toolTimeoutMs:_g(r.toolTimeoutMs)})),P=C.toolResults;if(h.push(...C.dispatched),g.push(...C.executions),C.abortedMidBatch)break;if(l=e.buildToolResultMessages(l,R,P,A),r.beforeStep&&!o.signal.aborted){const L=await r.beforeStep({stepIndex:A,stepsCompleted:A+1,maxSteps:v,elapsedMs:Date.now()-w,toolNames:C.dispatched.map(N=>N.name),signal:o.signal}),O=typeof L?.maxSteps=="number"&&Number.isFinite(L.maxSteps)?Math.floor(L.maxSteps):void 0;O!==void 0&&O>v&&(v=O,y=!1),L?.nudge&&e.appendPlanningNudge&&(l=e.appendPlanningNudge(l,L.nudge))}}const E=o.signal.aborted,k=e.mapFinishReason(m,y);return{text:d||(y?p:""),toolCalls:h,toolExecutions:g,usage:c,finishReason:E&&m===void 0?"other":k,rawStopReason:m,stopReason:E?"aborted":y?"step-cap":void 0,conversation:l,aborted:E}}catch(E){throw n.error(E),E}finally{b.end(),n.close(),r.abortSignal?.removeEventListener("abort",i)}})();return{stream:n.iterable,resultPromise:u}}var rfe,H5=S({"src/lib/core/loopEngine.ts"(){"use strict";B_(),Du(),Rr(),z(),Tp(),ci(),rfe=class extends Error{constructor(e){super(e instanceof Error?e.message:String(e)),this.cause=e}cause}}});function UAn(e,t){return e==="google-ai"?!0:e==="vertex"?!(t?.startsWith("claude-")??!1):!1}function BAn(e){return e==="anthropic"||e==="bedrock"}function nfe(e,t,r,n){return(UAn(e,t)||BAn(e))&&r&&n>0}function zAn(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"";return/cannot be combined with (a )?(tool|function)/i.test(t)||/json[\s_-]?(mode|schema|object|output)[^.]{0,60}(tool|function)/i.test(t)||/(tool|function)[\s-]?call[^.]{0,60}json[\s_-]?(mode|schema)/i.test(t)||/response_format[^.]{0,60}(tool|function)/i.test(t)}function z0r(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"";return/too many states/i.test(t)}function GAn(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"";return/does not support[^.]{0,80}response[\s_-]?format/i.test(t)||/response[\s_-]?format[^.]{0,60}(?:is )?not support/i.test(t)||/unsupported response[\s_-]?format/i.test(t)}var ofe=S({"src/lib/core/modules/structuredOutputPolicy.ts"(){"use strict"}});function qAn(e){return e?.kind==="toolCall"||e?.kind==="toolResult"}function jAn(e,t,r){const n=[];let o=t;for(;o<r;){if(!qAn(e[o])){o++;continue}const i=o;for(;o<e.length&&e[o].kind==="toolCall";)o++;for(;o<e.length&&e[o].kind==="toolResult";)o++;if(o>r)break;n.push({start:i,end:o})}return n}function W5(e,t){const{availableInputTokens:r,fixedOverheadTokens:n,thresholdRatio:o=aD,lowWaterRatio:i=G0r,protectedTailCount:s=q0r,calibration:a=1}=t,u=a>0?a:1,l=Math.floor(r*o/u),c=Math.floor(r*i/u);let d=n;for(const v of e)d+=v.tokens;if(d<=l)return{fire:!1,truncate:[],drop:[],projectedTokens:d};const p=1,m=Math.max(p,e.length-s),h=[],g=new Set;for(let v=p;v<m&&d>c;v++){const w=e[v];if(w.kind!=="toolResult"||w.previewTokens===void 0)continue;const b=w.tokens-w.previewTokens;b<=0||(h.push(v),d-=b)}if(d>c){const v=jAn(e,p,m);for(const w of v){if(d<=c)break;for(let b=w.start;b<w.end;b++){const E=e[b],k=h.includes(b)?E.previewTokens??E.tokens:E.tokens;d-=k,g.add(b)}}}const y=h.filter(v=>!g.has(v));return{fire:y.length>0||g.size>0,truncate:y,drop:[...g].sort((v,w)=>v-w),projectedTokens:d}}var G0r,q0r,K5=S({"src/lib/context/loopGuardCore.ts"(){"use strict";ci(),G0r=.6,q0r=4}});function j0r(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)??""}catch{return"x".repeat(2e5)}}function V0r(e,t){return Array.isArray(e.parts)&&e.parts.some(r=>r&&typeof r=="object"&&t in r)}function VAn(e){return V0r(e,"functionResponse")}function ife(e){const{preview:t}=Bu(e,{maxBytes:sfe,maxLines:W0r});return t}function HAn(e,t){return Xt(j0r(e.parts),t)+xu}function WAn(e,t){return e.map(r=>{const n=HAn(r,t);if(VAn(r)){const o=j0r(r.parts),i=o.length>sfe?Xt(ife(o),t)+xu:n;return{kind:"toolResult",tokens:n,...i<n?{previewTokens:i}:{}}}return V0r(r,"functionCall")?{kind:"toolCall",tokens:n}:{kind:"other",tokens:n}})}function H0r(e){const{contents:t,availableInputTokens:r,fixedOverheadTokens:n=0,provider:o,observedPromptTokens:i}=e,s=WAn(t,o);let a=1;if(i&&i>0){const l=n+s.reduce((c,d)=>c+d.tokens,0);l>0&&(a=Math.min(3,Math.max(1,i/l)))}const u=W5(s,{availableInputTokens:r,fixedOverheadTokens:n,calibration:a});if(u.fire)return f.info("[GeminiLoopGuard] Reclaiming agent-loop context",{provider:o,contents:t.length,toolResponsesTruncated:u.truncate.length,contentsDropped:u.drop.length,projectedTokens:u.projectedTokens,calibration:a}),u}var sfe,W0r,afe,K0r=S({"src/lib/context/geminiLoopGuard.ts"(){"use strict";vi(),G0(),K5(),z(),sfe=2048,W0r=60,afe="[Earlier tool exchanges were removed to fit the context window.]"}}),J0r=S({"src/lib/providers/googleNativeGemini3/index.ts"(){"use strict";j5()}}),ufe,hm,X0r=S({"src/lib/providers/anthropic/cacheControl.ts"(){"use strict";ufe=e=>{if(!e||e.length===0)return e;if(e.some(r=>r.cache_control!==void 0))return[...e];const t=e[e.length-1];return[...e.slice(0,-1),{...t,cache_control:{type:"ephemeral"}}]},hm=e=>e?.providerOptions?.anthropic?.cacheControl?.type==="ephemeral"?{type:"ephemeral"}:void 0}});function z_(e,t){if(t==="functionDeclarations")return A0r(e);const r=Object.entries(e??{});if(r.length!==0)return r.map(([n,o])=>{const i=o,s=i.inputSchema??i.parameters,a=s?Ti(s):{type:"object",properties:{}},u=hm(o);return{name:n,...i.description?{description:i.description}:{},input_schema:a,...u?{cache_control:u}:{}}})}var lfe=S({"src/lib/core/nativeToolFormat.ts"(){"use strict";j5(),X0r(),ls()}});function KAn(e,t,r){const n=e[Symbol.asyncIterator]();return new ReadableStream({async pull(o){try{const i=await n.next();i.done?(o.enqueue(await t),o.close()):o.enqueue({type:"text-delta",delta:i.value.content})}catch(i){o.error(i)}},async cancel(){r(),await n.return?.()}})}async function*JAn(e,t,r){const n=e.getReader();let o=!1,i=!1;try{for(;;){const s=await n.read();if(s.done){o=!0;return}const a=s.value;if(a.type==="text-delta")yield{content:a.delta};else if(a.type==="finish")i=!0,t(a);else if(a.type==="error")throw a.error}}finally{try{o||await n.cancel()}finally{n.releaseLock(),i||r?.()}}}function Y0r(e,t){const r=e.systemInstruction;return[...typeof r=="string"&&r.length>0?[{role:"system",content:r}]:[],...MAn(t)]}async function G_(e,t){const n=(await Promise.resolve().then(()=>(dA(),$w))).GoogleGenAI;if(!n)throw new Me({code:He.INVALID_CONFIGURATION,message:"@google/genai does not export GoogleGenAI",category:"configuration",severity:"critical",retriable:!1,context:{module:"@google/genai",expectedExport:"GoogleGenAI"}});const o=n;return new o({apiKey:e,httpOptions:{...t?{baseUrl:t}:{},...hA()}})}function Z0r(e,t,r){const n=H0r({contents:e,availableInputTokens:Al("googleAiStudio",t),provider:"googleAiStudio",...r?{observedPromptTokens:r}:{}});if(!n)return!1;const o=new Set(n.drop),i=new Set(n.truncate),s=[];for(let a=0;a<e.length;a++){if(o.has(a))continue;const u=e[a];if(i.has(a)&&Array.isArray(u.parts)){s.push({...u,parts:u.parts.map(l=>{const c=l;if(!c.functionResponse)return l;const d=JSON.stringify(c.functionResponse.response)??"";return d.length<=2048?l:{functionResponse:{name:c.functionResponse.name,response:{result:ife(d)}}}})});continue}s.push(u)}if(o.size>0){let a=s.findIndex(u=>Array.isArray(u.parts)&&u.parts.some(l=>!!l.functionCall||!!l.functionResponse));a<0&&(a=Math.min(1,s.length)),s.splice(a,0,{role:"user",parts:[{text:afe}]})}return e.length=0,e.push(...s),!0}var Q0r,XAn=S({"src/lib/providers/googleAiStudio/client.ts"(){"use strict";zu(),ci(),G3(),El(),lt(),et(),z(),Whe(),m0(),Du(),Rr(),B0r(),Th(),H5(),ci(),ofe(),K0r(),gc(),ga(),j0(),vi(),Sl(),Pd(),J0r(),B_(),lfe(),Lr(),Q0r=class extends Za{credentials;constructor(e,t,r){super(e,"google-ai",t),this.credentials=r,f.debug("GoogleAIStudioProvider initialized",{model:this.modelName,provider:this.providerName,sdkProvided:!!t})}getProviderName(){return"google-ai"}getDefaultModel(){return process.env.GOOGLE_AI_MODEL||"gemini-2.5-flash"}getAISDKModel(){throw new Me({code:He.INVALID_CONFIGURATION,message:"GoogleAIStudioProvider no longer uses @ai-sdk/google. All models use native @google/genai SDK.",category:"configuration",severity:"critical",retriable:!1,context:{provider:this.providerName,model:this.modelName}})}formatProviderError(e){if(e instanceof za)return new yi(e.message,this.providerName);const t=e,r=typeof t?.message=="string"?t.message:"Unknown error",n=typeof t?.status=="number"?t.status:typeof t?.statusCode=="number"?t.statusCode:void 0;return r.includes("API_KEY_INVALID")||r.includes("Invalid API key")||n===401?new an("Invalid Google AI API key. Please check your GOOGLE_AI_API_KEY environment variable.",this.providerName):r.includes("RATE_LIMIT_EXCEEDED")||r.includes("rate limit")||r.includes("429")||n===429?new Ts("Google AI rate limit exceeded. Please try again later.",this.providerName):n===404||n===void 0&&(r.includes("model not found")||r.includes("Model not found"))?new si(`Model '${this.modelName}' not found. Please check the model name and ensure it is available.`,this.providerName):r.includes("ECONNRESET")||r.includes("ENOTFOUND")||r.includes("ETIMEDOUT")||r.includes("ECONNREFUSED")||r.includes("network")||r.includes("connection")?new yi(`Connection error: ${r}`,this.providerName):r.includes("500")||r.includes("502")||r.includes("503")||r.includes("504")||r.includes("server error")||r.includes("Internal Server Error")||n&&n>=500&&n<600?new Xe(`Google AI server error: ${r}. Please try again later.`,this.providerName):new Xe(`Google AI error: ${r}`,this.providerName)}async executeImageGeneration(e){return yh({provider:this.providerName,model:e.model||this.modelName,input:{prompt:e.prompt||e.input?.text||""}},t=>this.generateImage(e,t))}async generateImage(e,t){await yC(e.input);const r=e.prompt||e.input?.text||"",n=e.model||this.modelName,o=Date.now(),i=this.getApiKey();f.info("\u{1F3A8} Starting Google AI Studio image generation",{model:n,prompt:r.substring(0,100),provider:this.providerName});let s;try{s=await G_(i,this.getBaseURL())}catch{throw new an("Missing '@google/genai'. Install with: npm install @google/genai",this.providerName)}try{const a=await Promise.all((e.input?.images||[]).map(async p=>{if(typeof p=="object"&&"url"in p){const g=p.url;if(g.startsWith("http")){const w=await fetch(g);if(!w.ok)throw new Error(`Failed to fetch image from ${g}: ${w.status} ${w.statusText}`);const b=await w.arrayBuffer(),E=Buffer.from(b),k=this.detectImageType(E);return f.debug(`Downloaded and detected image MIME type: ${k}`),{inlineData:{mimeType:k,data:E.toString("base64")}}}const y=Buffer.from(g,"base64");return{inlineData:{mimeType:this.detectImageType(y),data:y.toString("base64")}}}if(typeof p=="string"&&p.startsWith("http")){const g=await fetch(p);if(!g.ok)throw new Error(`Failed to fetch image from ${p}: ${g.status} ${g.statusText}`);const y=await g.arrayBuffer(),v=Buffer.from(y),w=this.detectImageType(v);return f.debug(`Downloaded and detected image MIME type: ${w}`),{inlineData:{mimeType:w,data:v.toString("base64")}}}const m=Buffer.isBuffer(p)?p:typeof p=="string"?Buffer.from(p,"base64"):Buffer.from(""),h=this.detectImageType(m);return f.debug(`Detected image MIME type: ${h}`),{inlineData:{mimeType:h,data:m.toString("base64")}}})),u=[{role:"user",parts:[{text:r},...a]}],l={responseModalities:["IMAGE","TEXT"]};f.debug("Starting image generation request",{model:n,contentParts:u[0].parts.length,responseModalities:l.responseModalities});let c=null,d="";try{const p=await s.models.generateContentStream({model:n,contents:u,config:l});for await(const m of p){f.debug("Received chunk",{hasCandidate:!!m.candidates?.[0],hasContent:!!m.candidates?.[0]?.content,hasParts:!!m.candidates?.[0]?.content?.parts});const h=m.candidates?.[0];if(h?.content?.parts)for(const g of h.content.parts){if("inlineData"in g&&g.inlineData?.data){const y=g.inlineData.data;c=y;const v=g.inlineData.mimeType,w=v||"image/png";f.info("Image generation successful",{model:n,mimeType:w,dataLength:y.length,responseTime:Date.now()-o});const b={content:`Generated image using ${n} (${w})`,imageOutput:{base64:y,...v?{mimeType:v}:{}},provider:this.providerName,model:n,usage:{input:this.estimateTokenCount(r),output:0,total:this.estimateTokenCount(r)}};return Tl(t,{responseModel:n,output:b.content,usage:b.usage,finishReason:"stop"}),await this.enhanceResult(b,e,o)}"text"in g&&g.text&&(d+=g.text,f.debug("Received text content",{text:g.text.substring(0,100)}))}}}catch(p){f.debug("Streaming failed, trying non-streaming approach",{error:p instanceof Error?p.message:String(p)})}if(!c){f.debug("Trying non-streaming approach");const m=(await s.models.generateContent({model:n,contents:u,config:l})).candidates?.[0];if(m?.content?.parts)for(const h of m.content.parts){if("inlineData"in h&&h.inlineData?.data){const g=h.inlineData.data;c=g;const y=h.inlineData.mimeType,v=y||"image/png";f.info("Image generation successful (non-streaming)",{model:n,mimeType:v,dataLength:g.length,responseTime:Date.now()-o});const w={content:`Generated image using ${n} (${v})`,imageOutput:{base64:g,...y?{mimeType:y}:{}},provider:this.providerName,model:n,usage:{input:this.estimateTokenCount(r),output:0,total:this.estimateTokenCount(r)}};return Tl(t,{responseModel:n,output:w.content,usage:w.usage,finishReason:"stop"}),await this.enhanceResult(w,e,o)}"text"in h&&h.text&&(d+=h.text)}}throw f.warn("No image data found in response",{model:n,prompt:r.substring(0,100),hasTextContent:!!d,textContent:d.substring(0,200)}),new Xe(d||`Image generation completed but no image data was returned. This may indicate an issue with the model "${n}" or the prompt: "${r}". Please try again or use a different model.`,this.providerName)}catch(a){throw f.error("Image generation failed",{error:a instanceof Error?a.message:String(a),model:n,prompt:r.substring(0,100)}),this.handleProviderError(a)}}detectImageType(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71?"image/png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70?"image/gif":"image/png"}estimateTokenCount(e){return Xt(e,"google-ai")}async preprocessNativeFileInput(e){if(e.input&&Xne(e.input),e.input?.files&&e.input.files.length>0)try{await Yne(e,100*1024*1024,this.providerName)}catch(t){f.warn(`[GoogleAIStudio] processUnifiedFilesArray threw, continuing without file content: ${t instanceof Error?t.message:String(t)}`)}await yC(e.input)}async executeStream(e,t){const r=e.model||this.modelName;if(e.input?.audio)return await this.executeAudioStreamViaGeminiLive(e);await this.preprocessNativeFileInput(e);const n=!!(t||e.output?.format==="json"||e.schema),o=!e.disableTools&&this.supportsTools()&&!n,i=e.tools||{};let s={...e,tools:i};const a=e.output?.format==="json"||e.schema,u=nfe(this.providerName,r,!s.disableTools,Object.keys(s.tools??{}).length);return a&&u&&(f.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request."),s={...s,disableTools:!0,tools:{}}),o&&!s.disableTools&&s.tools&&Object.keys(s.tools).length>0&&f.info("[GoogleAIStudio] Routing to native @google/genai SDK for tool calling",{model:r,totalToolCount:Object.keys(s.tools??{}).length}),this.executeNativeGemini3Stream(s)}async executeNativeGemini3Stream(e){const t=e.model||this.modelName;return dot({name:"provider.stream",tracer:Be.provider,detached:!0,rootWhenOrphaned:!0,attributes:{[Ne.NL_MODEL]:t,[Ne.NL_PROVIDER]:this.providerName}},async r=>{const n=Date.now(),o=this.getTimeout(e),i=Ba(o,this.providerName,"stream");{const s=this.getApiKey(),a=await G_(s,this.getBaseURL());f.debug("[GoogleAIStudio] Using native @google/genai for Gemini 3",{model:t,hasTools:!!e.tools&&Object.keys(e.tools).length>0});const u=[];G5(u,e.conversationMessages);const l=await $0r(e.input,e.input.text,"[GoogleAIStudio:stream]",t);u.push({role:"user",parts:l});let c,d;if(e.tools&&Object.keys(e.tools).length>0&&!e.disableTools){const oe=z_(e.tools,"functionDeclarations");d=oe,c=oe.toolsConfig,f.debug("[GoogleAIStudio] Converted tools for native SDK",{toolCount:c[0].functionDeclarations.length,toolNames:c[0].functionDeclarations.map(xe=>xe.name)})}const p=!c&&(e.output?.format==="json"||!!e.schema),m=p&&e.schema?M0r(e.schema):void 0,h=x0r({...e,model:t,wantsJsonOutput:p,responseSchema:m},c),g=C0r(e.maxSteps),y=bw(e.abortSignal,i?.controller.signal),v=new AbortController,w=()=>v.abort();y?.addEventListener("abort",w),y?.aborted&&v.abort();const b=_g(e.toolTimeoutMs),E=L_({...e.turnTimeoutMs!==void 0?{turnTimeoutMs:e.turnTimeoutMs}:{},...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},...e.wrapupTimeLeadMs!==void 0?{wrapupTimeLeadMs:e.wrapupTimeLeadMs}:{},onDeadline:oe=>{f.warn(oe==="timeout"?`[GoogleAIStudio] Native Gemini turn exceeded its ${e.turnTimeoutMs}ms time budget \u2014 aborting`:`[GoogleAIStudio] Native Gemini turn made no progress for ${e.stallTimeoutMs}ms \u2014 aborting`),v.abort()}}),k=v.signal,A=()=>E.timedOut||i?.controller.signal.aborted===!0,x=U_(),R=[],C=[];let P,D;const L=new Promise((oe,xe)=>{P=oe,D=xe}),O={streamId:`native-${Date.now()}`,startTime:n,responseTime:0,totalToolExecutions:0},N=async(oe,xe)=>{let Z="",we=0,de=0,Te=0,Pe=0,_e=0,ke=0,be=!1,ye;const Le=$_(Od("googleAiStudio",t));try{const je=V5({providerLabel:"GoogleAIStudio",provider:this.providerName,maxSteps:g,toolFailureBreaker:{maxRetries:Eg},liveTools:e.tools??{},toolGuards:{toolTimeoutMs:b,abortSignal:k,onProgress:()=>E.noteProgress()},...d?{declarations:d}:{},buildRequest:ce=>({model:t,contents:ce,config:xe}),sendStep:async(ce,I)=>{E.noteProgress();const j=ce;return a.models.generateContentStream({...j,config:{...j.config??{},abortSignal:I}})},noteUsage:(ce,I)=>{Le.noteUsage(ce,I)},planReclaim:(ce,I)=>{if(I!==0&&!Le.shouldStop())return;const j=[...ce];if(Z0r(j,t,Le.projectedNextPromptTokens))return Le.resetAfterReclaim(),{conversation:j}}}),$e={...je,buildStepRequest:(ce,I)=>(ke=I+1,E.noteProgress(),je.buildStepRequest(ce,I)),buildToolResultMessages:(ce,I,j,ge)=>{_e=ge+1;for(const te of I.toolCalls)r.addEvent("gen_ai.tool_call",{"tool.name":te.name,"tool.step":_e});Z=I.text||Z;for(const te of I.toolCalls)R.push({toolName:te.name,args:te.args});for(const te of j)C.push({name:te.name,input:te.args,output:te.output});if(j.length>0){const te=z5(I.raw.rawResponseParts);kt(this.handleToolExecutionStorage(I.toolCalls.map((F,re)=>({toolName:F.name,args:F.args,...re===0&&te?{thoughtSignature:te}:{},stepIndex:_e})),j.map(F=>({toolName:F.name,output:F.output,stepIndex:_e})),e,new Date),Sg,"tool storage write timed out").catch(F=>{f.warn("[GoogleAIStudio] Failed to store native tool executions",{error:F instanceof Error?F.message:String(F)})})}const Q=je.buildToolResultMessages(ce,I,j,ge);if(E.shouldNudgeWrapup()){const te=Q[Q.length-1];te&&Array.isArray(te.parts)&&te.parts.push({text:N_(!1)})}try{const te=Q[Q.length-1];Le.noteAppendedChars(JSON.stringify(te?.parts??[]).length)}catch{}return Q}},Ae=B5(d,e.tools,{toolTimeoutMs:b,abortSignal:k,onProgress:()=>E.noteProgress()}),{stream:he,resultPromise:V}=mm($e,oe,{tools:Ae,abortSignal:k,toolTimeoutMs:b}),K=(async()=>{for await(const ce of he)E.noteProgress(),x.push(ce)})();let ee,W;try{ee=await V}catch(ce){W=ce}if(await zy(K,"GoogleAIStudio"),W!==void 0)if(E.expired||e.abortSignal?.aborted)be=!0;else throw f.error("[GoogleAIStudio] Native SDK error",W),this.handleProviderError(W);ee&&(we+=ee.usage.inputTokens,de+=ee.usage.outputTokens,Te+=ee.usage.cacheReadTokens??0,Pe+=ee.usage.reasoningTokens??0,ye=ee.rawStopReason??ye,ee.aborted&&(be=!0)),k.aborted&&(be=!0);const J=ee!==void 0&&(ee.toolCalls.length===0||ee.finishReason!=="tool-calls"),ae=!be&&_e>=g&&!J;if(ae){const ce=I0r("[GoogleAIStudio]",_e,g,"",Z);ce&&x.push({content:ce})}else be&&!J&&(f.warn(`[GoogleAIStudio] Tool call loop ended mid-turn (${A()?"turn time limit":E.stalled?"stall watchdog":"caller abort"}); returning an honest terminal message.`),x.push({content:Xhe({timedOut:A(),stalled:E.stalled,elapsedMs:E.elapsedMs(),wasAborted:be,...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},maxSteps:g,toolCallCount:R.length})}));const ie=Date.now()-n,Ee=pm({timedOut:A(),stalled:E.stalled,wasAborted:be,cappedWithoutAnswer:ae,finishReason:qy(ye)});Ee!=="completed"&&this.emitTurnEvent({phase:Ee,step:ke,maxSteps:g,toolCallCount:R.length,elapsedMs:E.elapsedMs()}),O.responseTime=ie,O.totalToolExecutions=R.length,O.stopReason=Ee,O.stepsUsed=ke,ye!==void 0&&(O.rawFinishReason=ye);const pe=Math.max(0,we-Te);P({provider:this.providerName,model:t,tokenUsage:{input:pe,output:de+Pe,total:pe+Te+de+Pe,...Te>0?{cacheReadTokens:Te}:{},...Pe>0?{reasoning:Pe}:{}},requestDuration:ie,timestamp:new Date().toISOString(),stepsUsed:ke,toolCallCount:R.length,stopReason:Ee,elapsedMs:E.elapsedMs(),...ye!==void 0?{rawFinishReason:ye}:{}}),x.close()}catch(je){x.error(je),D(je)}finally{E.dispose(),y?.removeEventListener("abort",w),i?.cleanup()}};let $;const U={prompt:Y0r(h,u),...typeof h.maxOutputTokens=="number"?{maxOutputTokens:h.maxOutputTokens}:{},...typeof h.temperature=="number"?{temperature:h.temperature}:{},...typeof h.topP=="number"?{topP:h.topP}:{},abortSignal:k},q={specificationVersion:"v3",provider:this.providerName,modelId:t,supportedUrls:{},doGenerate:()=>{throw new Error("GoogleAIStudio: doGenerate is not implemented on the native stream model \u2014 NeuroLink streams through executeStream/doStream for this provider.")},doStream:async oe=>{const{contents:xe,systemText:Z}=L0r(oe.prompt),we={...h,...typeof oe.temperature=="number"?{temperature:oe.temperature}:{},...typeof oe.maxOutputTokens=="number"?{maxOutputTokens:oe.maxOutputTokens}:{},...typeof oe.topP=="number"?{topP:oe.topP}:{}};Z?we.systemInstruction=Z:delete we.systemInstruction,$=N(xe,we),$.catch(()=>{});const de=L.then(Te=>({type:"finish",finishReason:{unified:qy(O.rawFinishReason)},usage:{inputTokens:{total:Te.tokenUsage.input},outputTokens:{total:Te.tokenUsage.output}}}));return de.catch(()=>{}),{stream:KAn(x.iterable,de,()=>v.abort())}}};let B;try{const oe=await this.applyMiddlewareToModel(q,e);if(typeof oe=="string")throw new Error("GoogleAIStudio: native stream middleware resolved to a bare model id string, expected a LanguageModelV3 handle.");({stream:B}=await oe.doStream(U))}catch(oe){throw v.abort(),x.close(),E.dispose(),y?.removeEventListener("abort",w),i?.cleanup(),this.handleProviderError(oe)}let X=!1;const H=oe=>{if($||X)return;X=!0;const xe=Date.now()-n,Z=pm({timedOut:!1,stalled:!1,wasAborted:!oe,cappedWithoutAnswer:!1,...oe?{finishReason:oe.finishReason.unified}:{}});O.responseTime=xe,O.stopReason=Z,O.stepsUsed=0,P({provider:this.providerName,model:t,tokenUsage:{input:oe?.usage.inputTokens.total??0,output:oe?.usage.outputTokens.total??0,total:(oe?.usage.inputTokens.total??0)+(oe?.usage.outputTokens.total??0)},requestDuration:xe,timestamp:new Date().toISOString(),stepsUsed:0,toolCallCount:0,stopReason:Z,elapsedMs:xe}),E.dispose(),y?.removeEventListener("abort",w),i?.cleanup()},Y={stream:JAn(B,oe=>H(oe),()=>H()),provider:this.providerName,model:t,toolCalls:R,analytics:L,metadata:O};return Object.defineProperty(Y,"toolsUsed",{enumerable:!0,configurable:!0,get:()=>R.map(oe=>oe.toolName)}),Object.defineProperty(Y,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>Md(C)}),Y}},r=>r.stream,(r,n)=>({...r,stream:n}))}async executeNativeGemini3Generate(e){const t=e.model||this.modelName;return BA({name:"provider.generate",tracer:Be.provider,detached:!0,rootWhenOrphaned:!0,attributes:{[Ne.NL_MODEL]:t,[Ne.NL_PROVIDER]:this.providerName}},async r=>{const n=Date.now(),o=this.getTimeout(e),i=Ba(o,this.providerName,"generate");let s=()=>{};try{const a=this.getApiKey(),u=await G_(a,this.getBaseURL());f.debug("[GoogleAIStudio] Using native @google/genai for Gemini 3 generate",{model:t,hasTools:!!e.tools&&Object.keys(e.tools).length>0});const l=e.input?.text||e.prompt||"",c=[];G5(c,e.conversationMessages);const d=await $0r(e.input,l,"[GoogleAIStudio:generate]",t);c.push({role:"user",parts:d});let p,m;const h=!e.disableTools,g=!!(e.output?.format==="json"||e.schema),y=nfe(this.providerName,t,h,Object.keys(e.tools||{}).length);if(g&&y&&f.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request (generate())."),h&&!(g&&y)){const Y=e.tools||{};if(Object.keys(Y).length>0){const oe=z_(Y,"functionDeclarations");m=oe,p=oe.toolsConfig,f.debug("[GoogleAIStudio] Converted tools for native SDK generate",{toolCount:p[0].functionDeclarations.length,toolNames:p[0].functionDeclarations.map(xe=>xe.name)})}}const v=!p&&g,w=v&&e.schema?M0r(e.schema):void 0,b=x0r({...e,model:t,wantsJsonOutput:v,responseSchema:w},p),E=bw(e.abortSignal,i?.controller.signal),k=new AbortController,A=()=>k.abort();E?.addEventListener("abort",A),E?.aborted&&k.abort();const x=_g(e.toolTimeoutMs),R=L_({...e.turnTimeoutMs!==void 0?{turnTimeoutMs:e.turnTimeoutMs}:{},...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},...e.wrapupTimeLeadMs!==void 0?{wrapupTimeLeadMs:e.wrapupTimeLeadMs}:{},onDeadline:Y=>{f.warn(Y==="timeout"?`[GoogleAIStudio] Native Gemini generate turn exceeded its ${e.turnTimeoutMs}ms time budget \u2014 aborting`:`[GoogleAIStudio] Native Gemini generate turn made no progress for ${e.stallTimeoutMs}ms \u2014 aborting`),k.abort()}}),C=k.signal;s=()=>{R.dispose(),E?.removeEventListener("abort",A)};const P=()=>R.timedOut||i?.controller.signal.aborted===!0,D=C0r(e.maxSteps),L=async(Y,oe)=>{let xe="",Z="",we=0,de=0,Te=0,Pe=0;const _e=[],ke=[];let be=0,ye=0,Le=!1,je;const $e=$_(Od("googleAiStudio",t)),Ae=V5({providerLabel:"GoogleAIStudio",provider:this.providerName,maxSteps:D,toolFailureBreaker:{maxRetries:Eg},liveTools:e.tools??{},toolGuards:{toolTimeoutMs:x,abortSignal:C,onProgress:()=>R.noteProgress()},...m?{declarations:m}:{},buildRequest:j=>({model:t,contents:j,config:oe}),sendStep:async(j,ge)=>{R.noteProgress();const Q=j;return u.models.generateContentStream({...Q,config:{...Q.config??{},abortSignal:ge}})},noteUsage:(j,ge)=>{$e.noteUsage(j,ge)},planReclaim:(j,ge)=>{if(ge!==0&&!$e.shouldStop())return;const Q=[...j];if(Z0r(Q,t,$e.projectedNextPromptTokens))return $e.resetAfterReclaim(),{conversation:Q}}}),he={...Ae,buildStepRequest:(j,ge)=>(ye=ge+1,R.noteProgress(),Ae.buildStepRequest(j,ge)),buildToolResultMessages:(j,ge,Q,te)=>{be=te+1;for(const re of ge.toolCalls)r.addEvent("gen_ai.tool_call",{"tool.name":re.name,"tool.step":be}),_e.push({toolName:re.name,args:re.args});Z=ge.text||Z;for(const re of Q)ke.push({name:re.name,input:re.args,output:re.output});if(Q.length>0){const re=z5(ge.raw.rawResponseParts);kt(this.handleToolExecutionStorage(ge.toolCalls.map((me,Re)=>({toolName:me.name,args:me.args,...Re===0&&re?{thoughtSignature:re}:{},stepIndex:be})),Q.map(me=>({toolName:me.name,output:me.output,stepIndex:be})),e,new Date),Sg,"tool storage write timed out").catch(me=>{f.warn("[GoogleAIStudio] Failed to store native tool executions",{error:me instanceof Error?me.message:String(me)})})}const F=Ae.buildToolResultMessages(j,ge,Q,te);if(R.shouldNudgeWrapup()){const re=F[F.length-1];re&&Array.isArray(re.parts)&&re.parts.push({text:N_(!1)})}try{const re=F[F.length-1];$e.noteAppendedChars(JSON.stringify(re?.parts??[]).length)}catch{}return F}},V=B5(m,e.tools,{toolTimeoutMs:x,abortSignal:C,onProgress:()=>R.noteProgress()}),{stream:K,resultPromise:ee}=mm(he,Y,{tools:V,abortSignal:C,toolTimeoutMs:x}),W=(async()=>{for await(const j of K)R.noteProgress()})();let J,ae;try{J=await ee}catch(j){ae=j}if(await zy(W,"GoogleAIStudio"),ae!==void 0)if(R.expired||e.abortSignal?.aborted)Le=!0;else throw f.error("[GoogleAIStudio] Native SDK generate error",ae),this.handleProviderError(ae);J&&(we+=J.usage.inputTokens,de+=J.usage.outputTokens,Te+=J.usage.cacheReadTokens??0,Pe+=J.usage.reasoningTokens??0,je=J.rawStopReason??je,xe=J.text,J.aborted&&(Le=!0)),C.aborted&&(Le=!0);const ie=!Le&&be>=D&&!xe;Le&&!xe?(f.warn(`[GoogleAIStudio] Generate tool call loop ended mid-turn (${P()?"turn time limit":R.stalled?"stall watchdog":"caller abort"}); returning gathered text or an honest terminal message.`),xe=Z||Xhe({timedOut:P(),stalled:R.stalled,elapsedMs:R.elapsedMs(),wasAborted:Le,...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},maxSteps:D,toolCallCount:_e.length})):xe=I0r("[GoogleAIStudio]",be,D,xe,Z);const Ee=Date.now()-n,pe=pm({timedOut:P(),stalled:R.stalled,wasAborted:Le,cappedWithoutAnswer:ie,finishReason:qy(je)});pe!=="completed"&&this.emitTurnEvent({phase:pe,step:ye,maxSteps:D,toolCallCount:_e.length,elapsedMs:R.elapsedMs()});const ce=Math.max(0,we-Te);return{content:xe,provider:this.providerName,model:t,stopReason:pe,stepsUsed:ye,...je!==void 0?{rawFinishReason:je}:{},usage:{input:ce,output:de+Pe,total:ce+Te+de+Pe,...Te>0?{cacheReadTokens:Te}:{},...Pe>0?{reasoning:Pe}:{}},...Pe>0&&{reasoningTokens:Pe},responseTime:Ee,toolsUsed:_e.map(j=>j.toolName),toolExecutions:Eh(e,ke),enhancedWithTools:_e.length>0}};let O;const N={prompt:Y0r(b,c),...typeof b.maxOutputTokens=="number"?{maxOutputTokens:b.maxOutputTokens}:{},...typeof b.temperature=="number"?{temperature:b.temperature}:{},...typeof b.topP=="number"?{topP:b.topP}:{},abortSignal:C},$={specificationVersion:"v3",provider:this.providerName,modelId:t,supportedUrls:{},doStream:()=>{throw new Error("GoogleAIStudio: doStream is not implemented on the native generate model \u2014 NeuroLink runs this provider's turn synchronously through doGenerate.")},doGenerate:async Y=>{const{contents:oe,systemText:xe}=L0r(Y.prompt),Z={...b,...typeof Y.temperature=="number"?{temperature:Y.temperature}:{},...typeof Y.maxOutputTokens=="number"?{maxOutputTokens:Y.maxOutputTokens}:{},...typeof Y.topP=="number"?{topP:Y.topP}:{}};xe?Z.systemInstruction=xe:delete Z.systemInstruction;const we=await L(oe,Z);return O=we,{content:we.content?[{type:"text",text:we.content}]:[],finishReason:{unified:qy(we.rawFinishReason)},usage:{inputTokens:{total:we.usage?.input??0},outputTokens:{total:we.usage?.output??0}}}}};let U;try{const Y=await this.applyMiddlewareToModel($,e);if(typeof Y=="string")throw new Error("GoogleAIStudio: native generate middleware resolved to a bare model id string, expected a LanguageModelV3 handle.");U=await Y.doGenerate(N)}catch(Y){throw this.handleProviderError(Y)}let q="";for(const Y of U.content)Y.type==="text"&&(q+=Y.text);const B=O?.usage,X=U.usage.inputTokens.total??0,H=U.usage.outputTokens.total??0,ne={...O??{provider:this.providerName,model:t,stopReason:pm({timedOut:!1,stalled:!1,wasAborted:!1,cappedWithoutAnswer:!1,finishReason:U.finishReason.unified}),stepsUsed:0,responseTime:Date.now()-n,toolsUsed:[],toolExecutions:[],enhancedWithTools:!1},content:q,usage:{...B,input:X,output:H,total:X+H+(B?.cacheReadTokens??0)}};return this.enhanceResult(ne,e,n)}finally{s(),i?.cleanup()}})}async generate(e){const t=typeof e=="string"?{prompt:e}:e,r=t.model||this.modelName;if(kk.some(d=>r.toLowerCase().startsWith(d.toLowerCase())))return f.info("[GoogleAIStudio] Routing image generation model to executeImageGeneration",{model:r}),this.executeImageGeneration(t);if(pQ(t.tts))return f.info("[GoogleAIStudio] Routing TTS direct-synthesis to handleDirectTTSSynthesis",{model:r}),this.handleDirectTTSSynthesis(t,Date.now());await this.preprocessNativeFileInput(t);const o=t.disableTools?{}:await this.getToolsForStream(t);let i={...t,tools:o};const s=t.output?.format==="json"||t.schema,a=nfe(this.providerName,r,!i.disableTools,Object.keys(i.tools??{}).length);s&&a&&(f.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request."),i={...i,disableTools:!0,tools:{}}),!i.disableTools&&i.tools&&Object.keys(i.tools).length>0&&f.info("[GoogleAIStudio] Routing generate to native @google/genai SDK for tool calling",{model:r,totalToolCount:Object.keys(i.tools??{}).length});const l=Date.now(),c=i.input?.text||i.prompt||"";try{let d=await pt({name:"executeGeneration",tracer:Be.provider,detached:!0,attributes:{[Ne.NL_MODEL]:r,path:"native.google-genai"}},async()=>this.executeNativeGemini3Generate(i));return d=await this.synthesizeAIResponseIfNeeded(d,t),this.emitGenerationEnd(r,d,l,!0,void 0,c),d}catch(d){throw this.emitGenerationEnd(r,null,l,!1,d,c),d}}emitGenerationEnd(e,t,r,n,o,i){const s=this.neurolink?.getEventEmitter();if(!s)return;const a=t?.usage&&typeof t.usage=="object"?t.usage:{input:0,output:0,total:0};t&&typeof t=="object"&&(t._generationEndEmitted=!0),!n&&o&&typeof o=="object"&&(o._generationEndEmitted=!0),s.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),prompt:i||"",result:{content:t?.content||"",usage:a,model:e,provider:this.providerName,finishReason:n?"stop":"error"},success:n,...o?{error:o instanceof Error?o.message:String(o)}:{}})}async executeAudioStreamViaGeminiLive(e){const t=Date.now(),r=this.getApiKey();let n;try{n=await G_(r,this.getBaseURL())}catch{throw new an("Missing '@google/genai'. Install with: pnpm add @google/genai",this.providerName)}const o=this.modelName||process.env.GOOGLE_VOICE_AI_MODEL||"gemini-2.5-flash-preview-native-audio-dialog",i=[];let s=null,a=!1,u=!1,l=!1,c,d=!1,p,m=()=>{};const h=()=>{const C=s;s=null,C?.()},g=()=>{if(l||(l=!0,m(),p0(e.input?.audio?.frames),p&&(db(p),p=void 0)),c&&!d){d=!0;try{Promise.resolve(c.close?.()).catch(()=>{})}catch{}}},y=C=>{a||u||(i.push(C),C.type!=="audio"&&(u=!0,g()),h())},v=()=>{a=!0,i.length=0,g(),h()};let w=!1,b=()=>{};const E=new Promise((C,P)=>{b=P}),k=n.live.connect({model:o,callbacks:{onopen:()=>{},onmessage:async C=>{if(!(a||u))try{const P=C?.serverContent?.modelTurn?.parts?.[0]?.inlineData;if(P?.data){const L={data:Buffer.from(String(P.data),"base64"),sampleRateHz:24e3,channels:1,encoding:"PCM16LE"};y({type:"audio",audio:L})}C?.serverContent?.interrupted}catch(P){y({type:"error",error:P})}},onerror:C=>{w||b(new Error("Gemini Live connection failed before setup completed")),y({type:"error",error:C})},onclose:C=>{w||b(new Error("Gemini Live connection closed before setup completed")),y({type:"end"})}},config:{responseModalities:["AUDIO"],speechConfig:{voiceConfig:{prebuiltVoiceConfig:{voiceName:"Orus"}}}}}),A=await Promise.race([k,E]);c=A,w=!0,l&&g();const x=e.abortSignal;if(x&&!l){const C=()=>{y({type:"error",error:x.reason instanceof Error?x.reason:new DOMException("The operation was aborted","AbortError")})};x.addEventListener("abort",C,{once:!0}),m=()=>x.removeEventListener("abort",C),x.aborted&&C()}(async()=>{try{if(l)return;const C=e.input?.audio;if(!C){f.debug("[GeminiLive] No audio spec found on input; skipping upstream send");return}const P=C.frames[Symbol.asyncIterator]();for(p=P;!l;){const D=await P.next();if(l)return;if(D.done){p=void 0;break}const L=D.value;if(!L||L.byteLength===0){try{A.sendInput?await A.sendInput({event:"flush"}):A.sendRealtimeInput&&await A.sendRealtimeInput({event:"flush"})}catch($){f.debug("[GeminiLive] flush control failed (non-fatal)",{error:$ instanceof Error?$.message:String($)})}continue}const O=L.toString("base64"),N=`audio/pcm;rate=${C.sampleRateHz||16e3}`;await A.sendRealtimeInput?.({media:{data:O,mimeType:N}})}if(l)return;try{A.sendInput?await A.sendInput({event:"flush"}):A.sendRealtimeInput&&await A.sendRealtimeInput({event:"flush"})}catch(D){f.debug("[GeminiLive] final flush failed (non-fatal)",{error:D instanceof Error?D.message:String(D)})}}catch(C){y({type:"error",error:C})}})().catch(()=>{});const R={[Symbol.asyncIterator](){return{async next(){for(;;){const C=i.shift();if(C?.type==="audio")return{value:{type:"audio",audio:C.audio},done:!1};if(C?.type==="end")return a=!0,{value:void 0,done:!0};if(C?.type==="error")throw a=!0,C.error instanceof Error?C.error:new Error(String(C.error));if(a)return{value:void 0,done:!0};await new Promise(P=>{s=P})}},async return(){return v(),{value:void 0,done:!0}}}}};return cb(R,v),{stream:R,provider:this.providerName,model:o,metadata:{startTime:t,streamId:`google-ai-audio-${Date.now()}`}}}getDefaultEmbeddingModel(){return process.env.GOOGLE_AI_EMBEDDING_MODEL||process.env.GOOGLE_EMBEDDING_MODEL||"gemini-embedding-001"}async embed(e,t){if(typeof e!="string"&&e.image)throw new Xe(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=t||this.getDefaultEmbeddingModel()||"gemini-embedding-001";f.debug("Generating embedding",{provider:this.providerName,model:n,textLength:r.length});try{const o=this.getApiKey(),a=(await(await G_(o,this.getBaseURL())).models.embedContent({model:n,contents:[r]})).embeddings?.[0]?.values;if(!a||a.length===0)throw new Xe("No embedding returned from Google AI",this.providerName);return f.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:a.length}),a}catch(o){throw f.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:r.length}),this.handleProviderError(o)}}async embedMany(e,t){const r=t||this.getDefaultEmbeddingModel()||"gemini-embedding-001";f.debug("Generating batch embeddings",{provider:this.providerName,model:r,count:e.length});let n;try{const i=this.getApiKey(),s=await G_(i,this.getBaseURL());if(n=[],r.includes("gemini-embedding-2"))for(let u=0;u<e.length;u+=8){const l=e.slice(u,u+8),c=await Promise.all(l.map(d=>s.models.embedContent({model:r,contents:[d]})));for(const d of c)n.push(d.embeddings?.[0]?.values)}else{const a=await s.models.embedContent({model:r,contents:e});n.push(...(a.embeddings||[]).map(u=>u.values))}if(n.length!==e.length)throw new Error(`Embedding response held ${n.length} vectors for ${e.length} texts`)}catch(i){throw f.error("Batch embedding generation failed",{error:i instanceof Error?i.message:String(i),model:r,count:e.length}),this.handleProviderError(i)}const o=n.map((i,s)=>{if(!i||i.length===0)throw f.error("Batch embedding returned no values",{model:r,index:s}),new Xe(`Embedding for the text at index ${s} came back without values`,this.providerName);return i});return f.debug("Batch embeddings generated successfully",{provider:this.providerName,model:r,count:o.length,embeddingDimension:o[0]?.length}),o}getApiKey(){const e=this.credentials?.apiKey||process.env.GOOGLE_AI_API_KEY||process.env.GOOGLE_GENERATIVE_AI_API_KEY;if(!e)throw new an("GOOGLE_AI_API_KEY or GOOGLE_GENERATIVE_AI_API_KEY environment variable is not set",this.providerName);return e}getBaseURL(){const e=this.credentials?.baseURL?.trim()||process.env.GOOGLE_AI_BASE_URL?.trim();return e&&e.length>0?e:void 0}}}}),eyr={};ue(eyr,{GoogleAIStudioProvider:()=>Q0r});var YAn=S({"src/lib/providers/googleAiStudio/index.ts"(){"use strict";XAn()}});function ZAn(e){const t=e?.error?.message;if(typeof t=="string"&&t.trim().length>0)return t;if(Array.isArray(t)){const r=t.map(n=>n.msg?.trim()).filter(n=>n!==void 0&&n.length>0);if(r.length>0)return r.join("; ")}return typeof e?.detail=="string"&&e.detail.trim().length>0?e.detail:void 0}var au,cfe,J5,dfe,Nc,HI,pfe,mfe,tyr,hfe,ffe,ryr,nyr,gfe,yfe,oyr,iyr,q_,WI,syr,X5,vfe,ayr,uyr,wfe,lyr,bfe,Tfe,KI,_fe,cyr,Tf=S({"src/lib/providers/openaiChatCompletionsClient.ts"(){"use strict";Yse(),m5(),uc(),ls(),vi(),au=e=>e.replace(/\/+$/,""),cfe=/^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$/,J5=(e,t)=>{if(e.every(o=>cfe.test(o)&&!t?.has(o)))return;const r=new Map,n=new Map;for(const o of e){let i=cfe.test(o)?o:Hme(o);if(n.has(i)||t?.has(i)){let s=2,a;do{const u=`_${s}`;a=`${i.slice(0,64-u.length)}${u}`,s++}while(n.has(a)||t?.has(a));i=a}r.set(o,i),n.set(i,o)}return{toWire:r,fromWire:n}},dfe=(e,t,r)=>{let n=0;for(const o of e){if(Array.isArray(o.content)){for(const a of o.content)n+=a.type==="image_url"?Pk:Xt(a.text,r);n+=xu}else{const a=typeof o.content=="string"?o.content:Nc(o.content);n+=Xt(a,r)+xu}const i=o.tool_calls;i&&(n+=Xt(Nc(i),r));const s=o.reasoning_content;s&&(n+=Xt(s,r))}return t&&t.length>0&&(n+=Xt(Nc(t),r)),n},Nc=e=>{try{return JSON.stringify(e??"")}catch{return String(e??"")}},HI=e=>{if(typeof e=="string")return e;try{return JSON.stringify(e??{})}catch{return"{}"}},pfe=e=>{if(e==null)return"";if(typeof e=="string")return e;if(typeof e!="object")return String(e);const t=e;switch(t.type){case"text":return typeof t.value=="string"?t.value:Nc(t.value);case"json":return Nc(t.value);case"execution-denied":return`Tool execution denied${t.reason?`: ${t.reason}`:""}`;case"error-text":return typeof t.value=="string"?t.value:Nc(t.value);case"error-json":return Nc(t.value);case"content":return Array.isArray(t.value)?t.value.map(r=>r&&typeof r=="object"&&r.type==="text"?String(r.text??""):"").filter(r=>r.length>0).join(`
|