Files
StudyDiary/.obsidian/plugins/copilot/main.js
T

3431 lines
3.3 MiB
JavaScript
Raw Normal View History

2026-07-23 20:36:13 +08:00
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
// Polyfill for import.meta in CommonJS context
if (typeof import_meta === 'undefined') {
var import_meta = {
url: typeof __filename !== 'undefined' ? 'file://' + __filename : 'file:///obsidian-plugin'
};
}
var swt=Object.create;var nD=Object.defineProperty;var awt=Object.getOwnPropertyDescriptor;var lwt=Object.getOwnPropertyNames;var cwt=Object.getPrototypeOf,uwt=Object.prototype.hasOwnProperty;var oPe=t=>{throw TypeError(t)};var dwt=(t,e,n)=>e in t?nD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var C=(t,e)=>()=>(t&&(e=t(t=0)),e);var Tt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),zn=(t,e)=>{for(var n in e)nD(t,n,{get:e[n],enumerable:!0})},iPe=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of lwt(e))!uwt.call(t,o)&&o!==n&&nD(t,o,{get:()=>e[o],enumerable:!(r=awt(e,o))||r.enumerable});return t};var N=(t,e,n)=>(n=t!=null?swt(cwt(t)):{},iPe(e||!t||!t.__esModule?nD(n,"default",{value:t,enumerable:!0}):n,t)),fwt=t=>iPe(nD({},"__esModule",{value:!0}),t);var I=(t,e,n)=>dwt(t,typeof e!="symbol"?e+"":e,n),pwt=(t,e,n)=>e.has(t)||oPe("Cannot "+n);var GQ=(t,e,n)=>e.has(t)?oPe("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n);var sPe=(t,e,n)=>(pwt(t,e,"access private method"),n);function aPe(t,e=0){return(al[t[e+0]]+al[t[e+1]]+al[t[e+2]]+al[t[e+3]]+"-"+al[t[e+4]]+al[t[e+5]]+"-"+al[t[e+6]]+al[t[e+7]]+"-"+al[t[e+8]]+al[t[e+9]]+"-"+al[t[e+10]]+al[t[e+11]]+al[t[e+12]]+al[t[e+13]]+al[t[e+14]]+al[t[e+15]]).toLowerCase()}var al,lPe=C(()=>{al=[];for(let t=0;t<256;++t)al.push((t+256).toString(16).slice(1))});function ZQ(){if(!YQ){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");YQ=crypto.getRandomValues.bind(crypto)}return YQ(mwt)}var YQ,mwt,cPe=C(()=>{mwt=new Uint8Array(16)});var hwt,JQ,uPe=C(()=>{hwt=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),JQ={randomUUID:hwt}});function gwt(t,e,n){if(JQ.randomUUID&&!e&&!t)return JQ.randomUUID();t=t||{};let r=t.random??t.rng?.()??ZQ();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[n+o]=r[o];return e}return aPe(r)}var si,dPe=C(()=>{uPe();cPe();lPe();si=gwt});var qh=C(()=>{dPe()});var Qi=C(()=>{});var rD=C(()=>{});var XQ,jy,No,uo,Sd,Af,ywt,wwt,vwt,xwt,bwt,Cwt,QQ,pPe,mPe,oD,bu,eee,iD,NS,sD,tee,aD,nee,ree,ZV,oee,lD,JV,XV,iee,QV,_wt,see,eW,Td,Vy,Pc,ZE,Ec,Ex,Gh,um,OS,aee,Cu,tW,hPe,JE,bt,nW,rW,lee,gPe,XE,Hn,kf,It=C(()=>{qh();Qi();rD();XQ="https://api.brevilabs.com/v1",jy="https://models.brevilabs.com/v1",No="copilot-chat-view",uo="user",Sd="ai",Af="copilot",ywt=`${Af}/copilot-conversations`,wwt=`${Af}/copilot-custom-prompts`,vwt=`${Af}/memory`,xwt=`${Af}/system-prompts`,bwt=`${Af}/projects`,Cwt="",QQ=Af,pPe=`You are Obsidian Copilot, a helpful assistant that integrates AI to Obsidian note-taking.
1. Never mention that you do not have access to something. Always rely on the user provided context.
2. Always answer to the best of your knowledge. If you are unsure about something, say so and ask the user to provide more context.
3. If the user mentions "note", it most likely means an Obsidian note in the vault, not the generic meaning of a note.
4. If the user mentions "@vault", it means the user wants you to search the Obsidian vault for information relevant to the query. The search results will be provided to you in the context along with the user query, read it carefully and answer the question based on the information provided. If there's no relevant information in the vault, just say so.
5. If the user mentions any other tool with the @ symbol, check the context for their results. If nothing is found, just ignore the @ symbol in the query.
6. Always use $'s instead of \\[ etc. for LaTeX equations.
7. When showing note titles, use [[title]] format and do not wrap them in \` \`.
8. When showing **Obsidian internal** image links, use ![[link]] format and do not wrap them in \` \`.
9. When showing **web** image links, use ![link](url) format and do not wrap them in \` \`.
10. When generating a table, format as github markdown tables, however, for table headings, immediately add ' |' after the table heading.
11. Always respond in the language of the user's query.
12. Do NOT mention the additional context provided such as getCurrentTime and getTimeRangeMs if it's irrelevant to the user message.
13. If the user mentions "tags", it most likely means tags in Obsidian note properties.
14. YouTube URLs: If the user provides YouTube URLs in their message, transcriptions will be automatically fetched and provided to you. You don't need to do anything special - just use the transcription content if available.
15. For markdown lists, always use '- ' (hyphen followed by exactly one space) for bullet points, with no leading spaces before the hyphen. Never use '*' (asterisk) for bullets.`,mPe=`Return the new note content or canvas JSON in <writeFile> tags.
# Steps to find the the target notes
1. Extract the target note information from user message and find out the note path from the context below.
2. If target note is not specified, use the <active_note> as the target note.
3. If still failed to find the target note or the note path, ask the user to specify the target note.
# Examples
Input: Add a new section to note A
Output:
<writeFile>
<path>path/to/file.md</path>
<content>The FULL CONTENT of the note A with added section goes here</content>
</writeFile>
Input: Create a new canvas with "Hello, world!"
Output:
<writeFile>
<path>path/to/file.canvas</path>
<content>
{
"nodes": [
{
"id": "1",
"type": "text",
"text": "Hello, world!",
"x": 0,
"y": 0,
"width": 200,
"height": 50
}
],
"edges": []
}
</content>
</writeFile>
Input: Create a canvas with a file node and a group
Output:
<writeFile>
<path>path/to/file.canvas</path>
<content>
{
"nodes": [
{"id": "1", "type": "file", "file": "note.md", "subpath": "#heading", "x": 100, "y": 100, "width": 300, "height": 200, "color": "2"},
{"id": "2", "type": "group", "label": "My Group", "x": 50, "y": 50, "width": 400, "height": 300, "color": "1"},
{"id": "3", "type": "link", "url": "https://example.com", "x": 500, "y": 100, "width": 200, "height": 100, "color": "#FF5733"}
],
"edges": [
{"id": "e1-2", "fromNode": "1", "toNode": "3", "fromSide": "right", "toSide": "left", "fromEnd": "arrow", "toEnd": "none", "color": "3", "label": "references"}
]
}
</content>
</writeFile>
# Canvas JSON Format (JSON Canvas spec 1.0)
Required node fields: id, type, x, y, width, height
Node types: "text" (needs text), "file" (needs file), "link" (needs url), "group" (optional label)
Optional node fields: color (hex #FF0000 or preset "1"-"6"), subpath (file nodes, starts with #)
Required edge fields: id, fromNode, toNode
Optional edge fields: fromSide/toSide ("top"/"right"/"bottom"/"left"), fromEnd/toEnd ("none"/"arrow"), color, label
All IDs must be unique. Edge nodes must reference existing node IDs.
Position nodes with reasonable spacing and logical visual flow.
`,oD="note_context",bu="selected_text",eee="web_selected_text",iD="variable",NS="variable_note",sD="embedded_pdf",tee="embedded_note",aD="dataview_block",nee="retrieved_document",ree="web_tab_context",ZV="active_web_tab",oee="youtube_video_context",lD="{activeWebTab}",JV=6e3,XV=.4,iee=448e3,QV=3e4,_wt=30,see=5*60*1e3,eW=16,Td={DEFAULT:"",READING_FILES:"Reading files",SEARCHING_WEB:"Searching the web",READING_FILE_TREE:"Reading file tree",COMPACTING:"Compacting"},Vy={SETTINGS:"settings",EXPIRED_MODAL:"expired_modal",CHAT_MODE_SELECT:"chat_mode_select",MODE_SELECT_TOOLTIP:"mode_select_tooltip"},Pc={MAX_TOKENS:6e3,TEMPERATURE:.1,REASONING_EFFORT:"low",VERBOSITY:"medium"},ZE=131072,Ec=(y=>(y.OPENROUTERAI="openrouterai",y.OPENAI="openai",y.OPENAI_FORMAT="3rd party (openai-format)",y.ANTHROPIC="anthropic",y.GOOGLE="google",y.XAI="xai",y.AMAZON_BEDROCK="amazon-bedrock",y.AZURE_OPENAI="azure openai",y.GROQ="groq",y.OLLAMA="ollama",y.LM_STUDIO="lm-studio",y.COPILOT_PLUS="copilot-plus",y.MISTRAL="mistralai",y.DEEPSEEK="deepseek",y.COHEREAI="cohereai",y.SILICONFLOW="siliconflow",y.GITHUB_COPILOT="github-copilot",y))(Ec||{}),Ex={reasoning:"This model supports general reasoning tasks.",vision:"This model supports image inputs.",websearch:"This model can access the internet."},Gh=[{name:"copilot-plus-flash",provider:"copilot-plus",enabled:!0,isBuiltIn:!0,core:!0,plusExclusive:!0,projectEnabled:!1,capabilities:["vision"]},{name:"google/gemini-2.5-flash",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"google/gemini-3.5-flash",provider:"openrouterai",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision","reasoning"]},{name:"gpt-5.5",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"gpt-5.4-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"claude-sonnet-4-6",provider:"anthropic",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-3.5-flash",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision","reasoning"]},{name:"gemini-3.1-flash-lite",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gemini-2.5-flash",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"google/gemini-3.1-pro-preview",provider:"openrouterai",enabled:!1,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"google/gemini-2.5-pro",provider:"openrouterai",enabled:!1,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"openai/gpt-5.5",provider:"openrouterai",enabled:!1,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"openai/gpt-5.4-mini",provider:"openrouterai",enabled:!1,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"grok-4.3",provider:"xai",enabled:!1,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"x-ai/grok-4.3",provider:"openrouterai",enabled:!1,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1",provider:"openai",enabled:!1,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1-mini",provider:"openai",enabled:!1,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"claude-opus-4-7",provider:"anthropic",enabled:!1,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"claude-haiku-4-5",provider:"anthropic",enabled:!1,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-3.1-pro-preview",provider:"google",enabled:!1,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-2.5-pro",provider:"google",enabled:!1,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"deepseek-chat",provider:"deepseek",enabled:!1,isBuiltIn:!0},{name:"deepseek-reasoner",provider:"deepseek",enabled:!1,isBuiltIn:!0,capabilities:["reasoning"]},{name:"deepseek-ai/DeepSeek-V3",provider:"siliconflow",enabled:!1,isBuiltIn:!1,baseUrl:"https://api.siliconflow.com/v1"},{name:"deepseek-ai/DeepSeek-R1",provider:"siliconflow",enabled:!1,isBuiltIn:!1,baseUr
`)}return JSON.stringify(t)??String(t)}catch{return String(t)}}var Wee=C(()=>{});var Gy,hW,gW,yW,dm,lA,Ri,fm,Rx=C(()=>{Gy=class extends Error{},hW=class extends Gy{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},gW=class extends Gy{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},yW=class extends Gy{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},dm=class extends Gy{},lA=class extends Gy{constructor(e){super(`Invalid unit ${e}`)}},Ri=class extends Gy{},fm=class extends Gy{constructor(){super("Zone is an abstract class")}}});var ft,pm,Pd,Lx,hD,Hee,gD,yD,wD,vD,xD,bD,CD,_D,SD,TD,ID,PD,ED,AD,Kee,kD,MD,ND,OD,RD=C(()=>{ft="numeric",pm="short",Pd="long",Lx={year:ft,month:ft,day:ft},hD={year:ft,month:pm,day:ft},Hee={year:ft,month:pm,day:ft,weekday:pm},gD={year:ft,month:Pd,day:ft},yD={year:ft,month:Pd,day:ft,weekday:Pd},wD={hour:ft,minute:ft},vD={hour:ft,minute:ft,second:ft},xD={hour:ft,minute:ft,second:ft,timeZoneName:pm},bD={hour:ft,minute:ft,second:ft,timeZoneName:Pd},CD={hour:ft,minute:ft,hourCycle:"h23"},_D={hour:ft,minute:ft,second:ft,hourCycle:"h23"},SD={hour:ft,minute:ft,second:ft,hourCycle:"h23",timeZoneName:pm},TD={hour:ft,minute:ft,second:ft,hourCycle:"h23",timeZoneName:Pd},ID={year:ft,month:ft,day:ft,hour:ft,minute:ft},PD={year:ft,month:ft,day:ft,hour:ft,minute:ft,second:ft},ED={year:ft,month:pm,day:ft,hour:ft,minute:ft},AD={year:ft,month:pm,day:ft,hour:ft,minute:ft,second:ft},Kee={year:ft,month:pm,day:ft,weekday:pm,hour:ft,minute:ft},kD={year:ft,month:Pd,day:ft,hour:ft,minute:ft,timeZoneName:pm},MD={year:ft,month:Pd,day:ft,hour:ft,minute:ft,second:ft,timeZoneName:pm},ND={year:ft,month:Pd,day:ft,weekday:Pd,hour:ft,minute:ft,timeZoneName:Pd},OD={year:ft,month:Pd,day:ft,weekday:Pd,hour:ft,minute:ft,second:ft,timeZoneName:Pd}});var Tu,$S=C(()=>{Rx();Tu=class{get type(){throw new fm}get name(){throw new fm}get ianaName(){return this.name}get isUniversal(){throw new fm}offsetName(e,n){throw new fm}formatOffset(e,n){throw new fm}offset(e){throw new fm}equals(e){throw new fm}get isValid(){throw new fm}}});var qee,Dx,vW=C(()=>{kc();$S();qee=null,Dx=class t extends Tu{static get instance(){return qee===null&&(qee=new t),qee}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:n,locale:r}){return xW(e,n,r)}formatOffset(e,n){return $x(this.offset(e),n)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}});function zvt(t){return CW[t]||(CW[t]=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"})),CW[t]}function Vvt(t,e){let n=t.format(e).replace(/\u200E/g,""),r=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(n),[,o,i,s,a,l,c,u]=r;return[s,o,i,a,l,c,u]}function Wvt(t,e){let n=t.formatToParts(e),r=[];for(let o=0;o<n.length;o++){let{type:i,value:s}=n[o],a=jvt[i];i==="era"?r[a]=s:mn(a)||(r[a]=parseInt(s,10))}return r}var CW,jvt,bW,Hl,Fx=C(()=>{kc();$S();CW={};jvt={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};bW={},Hl=class t extends Tu{static create(e){return bW[e]||(bW[e]=new t(e)),bW[e]}static resetCache(){bW={},CW={}}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=t.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:n,locale:r}){return xW(e,n,r,this.name)}formatOffset(e,n){return $x(this.offset(e),n)}offset(e){let n=new Date(e);if(isNaN(n))return NaN;let r=zvt(this.name),[o,i,s,a,l,c,u]=r.formatToParts?Wvt(r,n):Vvt(r,n);a==="BC"&&(o=-Math.abs(o)+1);let f=cA({year:o,month:i,day:s,hour:l===24?0:l,minute:c,second:u,millisecond:0}),p=+n,m=p%1e3;return p-=m>=0?m:1e3+m,(f-p)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}});function Hvt(t,e={}
`)?o.slice(2):o.startsWith(`
`)||o.startsWith("\r")?o.slice(1):o}}return t}function eg(t,e=!0){let n=app.metadataCache.getFileCache(t),r=n?.frontmatter?.tags,o=new Set;if(!e){let i=n?.tags?.map(s=>s.tag);i&&i.forEach(s=>o.add(TA(s)))}return r&&(Array.isArray(r)?r.forEach(i=>{typeof i=="string"&&o.add(TA(i))}):typeof r=="string"&&o.add(TA(r))),Array.from(o)}function $W(t,e,n){if(e.length===0)return[];e=e.map(i=>TA(i));let r=n&&n.length>0?n:JD(t,"/"),o=[];for(let i of r){let s=eg(i);e.some(a=>s.includes(a))&&o.push(i)}return o}async function Fr(t){let e=(0,Kl.normalizePath)(t).replace(/^\/+/,"").replace(/\/+$/,"");if(!e)return;let n=e.split("/").filter(Boolean),r="";for(let o of n){r=r?`${r}/${o}`:o;let i=app.vault.getAbstractFileByPath(r);if(i){if(i instanceof Kl.TFile)throw new Error(`Path conflict: "${r}" exists as a file, expected folder.`);continue}await app.vault.adapter.mkdir(r)}}function FW(t){return t?lee.includes(t.extension):!1}async function IA(t,e){return FW(t)?await e.read(t):null}function UW(t){return t.basename}function tg(t){return t?gPe.includes(t.extension):!1}function Mc(t){return t==="copilot_plus"||t==="project"}function PA(t,e){return t?FW(t)?!0:Mc(e):!1}function kAe(t,e){return!t||!e?!1:t.includes(aee)&&e.includes(aee)||t==="small"&&e==="cohereai"||t==="cohereai"&&e==="small"?!0:t===e}function BW(t){let e=[],n=t.history;for(let r=0;r<n.length;r+=2){let o=n[r]?.content||"",i=n[r+1]?.content||"";e.push({role:"user",content:o},{role:"assistant",content:i})}return e}function MAe(t,e){let n=new Map;return t.forEach(r=>{let o=e.getAbstractFileByPath(r);if(o instanceof Kl.TFile)n.set(o.path,o);else{let s=e.getMarkdownFiles().filter(a=>a.basename===r);s.length>0&&(hbt(r,e)?n.set(s[0].path,s[0]):console.warn(`Found multiple files with title "${r}". Expected a full path for duplicate titles.`))}}),Array.from(n.values())}function Df(t,e){let n=/\[\[(.*?)\]\]/g,r=t.match(n);if(!r)return[];let o=r.map(i=>i.slice(2,-2));return MAe(o,e)}function NAe(t,e){let n=/\{\[\[(.*?)\]\]\}/g,r=t.match(n);if(!r)return[];let o=r.map(i=>i.slice(3,-3));return MAe(o,e)}function hbt(t,e){return e.getMarkdownFiles().filter(r=>r.basename===t).length===1}function OAe(t){return t=t.trim(),t.startsWith("[[")&&t.endsWith("]]")?`${t.slice(2,-2).trim()}.md`:t}function RAe(t){let e=new Set;return t.forEach(n=>{n.metadata?.title&&e.add(n.metadata.title)}),Array.from(e)}function Fte(t){if(!t||typeof t!="string")return{isValid:!1,error:"URL is required"};let e=t.trim();if(!e)return{isValid:!1,error:"URL cannot be empty"};let n=Ute(e);return n?/^[a-zA-Z0-9_-]{11}$/.test(n)?{isValid:!0,videoId:n}:{isValid:!1,error:"Invalid YouTube video ID"}:{isValid:!1,error:"Invalid YouTube URL format"}}function Ute(t){try{let e=[/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/v\/)([a-zA-Z0-9_-]{11})/,/youtube\.com\/shorts\/([a-zA-Z0-9_-]{11})/];for(let n of e){let r=t.match(n);if(r&&r[1])return r[1]}return null}catch{return null}}function LAe(t){return`https://www.youtube.com/watch?v=${t}`}function DAe(t){return Fte(t).isValid}function $Ae(t){if(!t||typeof t!="string")return!1;try{let e=new URL(t.trim());return(e.hostname==="x.com"||e.hostname==="www.x.com"||e.hostname==="twitter.com"||e.hostname==="www.twitter.com")&&e.pathname.includes("/status/")}catch{return!1}}function FAe(t){let e=t.matchAll(new RegExp(gbt,"g"));return Array.from(e,n=>n[0])}async function fo(t,e={}){let{throwOnHttpError:n=!0}=e,r=new Headers(e.headers),o=Object.fromEntries(r.entries());delete o["content-length"],k("safeFetch request");let i=e.method?.toUpperCase()||"POST",a=await(0,Kl.requestUrl)({url:t,contentType:"application/json",headers:o,method:i,...["POST","PUT","PATCH"].includes(i)&&typeof e.body=="string"&&{body:e.body},throw:!1});if(n&&a.status>=400){let l=null;try{l=typeof a.json=="string"?JSON.parse(a.json):a.json}catch{try{l=typeof a.text=="string"?JSON.parse(a.text):a.text}catch{l=null}}let c=new Error($te.REQUEST_FAILED(a.status));c.json=l;let u=l&&typeof l.detail=="object"?l.detail:void 0;if(u?.reason==="Invalid license key"||l?.reason==="Invalid license key")c.message=
`),e=e.trim(),e}async function EA(t,e=!1){let n=app.workspace.getMostRecentLeaf();if(!n){new Kl.Notice("No active leaf found.");return}if(n.view instanceof Kl.MarkdownView||(n=app.workspace.getLeaf(!1),await n.setViewState({type:"markdown",state:n.view.getState()})),!(n.view instanceof Kl.MarkdownView)){new Kl.Notice("Failed to open a markdown view.");return}let r=n.view.editor,o=r.getCursor("from"),i=r.getCursor("to"),s=ng(t),a=s.split(`
`),l=(w,v)=>{let x=v.length-1;return x===0?{line:w.line,ch:w.ch+(v[0]?.length??0)}:{line:w.line+x,ch:v[v.length-1]?.length??0}},c=()=>{let w=e?o:i;r.replaceRange(s,w,i),r.setSelection(w,l(w,a))},u=()=>{r.focus(),new Kl.Notice("Message inserted into the active note.")},d=r.cm;if(!(d?.state?.doc&&typeof d.dispatch=="function")){c(),u();return}let{from:p,to:m}=d.state.selection.main,h=e?p:m,g=d.state.toText(s),y=h+g.length;try{d.dispatch({changes:{from:h,to:m,insert:g},selection:{anchor:h,head:y}})}catch(w){ee("CM6 dispatch failed, falling back to Obsidian API",w),c()}u()}function zW(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let o=0;o<3;o++){if(n[o]>r[o])return!0;if(n[o]<r[o])return!1}return!1}async function UAe(){try{return{version:(await(0,Kl.requestUrl)({url:"https://api.github.com/repos/logancyang/obsidian-copilot/releases/latest",method:"GET"})).json.tag_name.replace("v",""),error:null}}catch(t){return{version:null,error:t instanceof Error?t.message:"Failed to check for updates"}}}function QD(t){if(typeof t=="string")return t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4");let e=t,n=e.modelName||e.model||"";return n.startsWith("o1")||n.startsWith("o3")||n.startsWith("o4")}function wbt(t){if(typeof t=="string")return t.startsWith("gpt-5");let e=t;return(e.modelName||e.model||"").startsWith("gpt-5")}function vbt(t){let e=t;return(typeof t=="string"?t:e.modelName||e.model||"").toLowerCase().includes("codex")}function Bte(t){return t.provider!=="github-copilot"?!1:t.useResponsesApi===!0?!0:vbt(t.name)}function AA(t){let e=t,n=typeof t=="string"?t:e.modelName||e.model||"",r=QD(n),o=wbt(n),i=n.startsWith("claude-3-7-sonnet")||n.startsWith("claude-sonnet-4")||n.startsWith("claude-opus-4"),s=n.match(/^claude-opus-4-(\d{1,2})(?:[-.]|$)/),a=s?parseInt(s[1],10)>=7:!1;return{isOSeries:r,isGPT5:o,isThinkingEnabled:i,usesAdaptiveThinking:a}}function e$(t,e="system"){return QD(t)?"human":e}function zte(){let t=["3rd party (openai-format)","ollama","lm-studio","azure openai","github-copilot","copilot-plus","copilot-plus-jina"];return Object.keys(Cu).filter(e=>!t.includes(e))}function kA(t,e){let n=t.provider;if(n==="amazon-bedrock")return t.apiKey||e.amazonBedrockApiKey?{hasApiKey:!0}:{hasApiKey:!1,errorNotice:"Amazon Bedrock API key is missing. Please add a key in Settings > API Keys or update the model configuration."};if(n==="github-copilot")return!(t.apiKey||e.githubCopilotToken||e.githubCopilotAccessToken)?{hasApiKey:!1,errorNotice:"GitHub Copilot is not authenticated. Please connect it in Settings > Copilot > Basic Tab > Set Keys."}:{hasApiKey:!0};let r=!!zte().find(i=>i===n),o=!Ad(t.provider,t);return r&&o?{hasApiKey:!1,errorNotice:`Please configure API Key for ${t.name} in settings first.
Path: Settings > copilot plugin > Basic Tab > Set Keys`}:{hasApiKey:!0}}function Kx(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>e.text??"").join(""):""}function jte(t){let n=Kx(t).replace(/<think>[\s\S]*?<\/think>/g,"");return n=n.replace(/<think>[\s\S]*$/g,""),n.trim()}function BAe(t){return Kx(t).replace(/<errorChunk>[\s\S]*?<\/errorChunk>/g,"").trim()}function zAe(){return crypto.randomUUID()}async function Nc(t){let e=console.warn;try{return console.warn=function(...n){let r=n[0];typeof r=="string"&&(r.includes("Failed to calculate number of tokens")||r.includes("Unknown model"))||e.apply(console,n)},await t()}finally{console.warn=e}}async function jAe(t,e,n="Operation"){let{TimeoutError:r}=await Promise.resolve().then(()=>(Nf(),zPe)),o=new AbortController,i=window.setTimeout(()=>{o.abort()},e);try{return await Promise.race([t(o.signal),new Promise((s,a)=>{o.signal.addEventListener("abort",()=>{a(new r(n,e))})})])}finally{window.clearTimeout(i)}}function t$(){let t=app.workspace.getActiveViewOfType(Kl.MarkdownView);return t?t.getState().source===!0:!0}function WS(t){return new TextEncoder().encode(t).length}function ZD(t,e){if(e<=0)return"";let n=new TextEncoder;if(n.encode(t).length<=e)return t;let o=0,i=t.length,s="";for(;o<=i;){let a=Math.floor((o+i)/2),l=t.substring(0,a);n.encode(l).length<=e?(s=l,o=a+1):i=a-1}return s}function Vte(t){let e=t.split("/"),n=e[e.length-1];if(WS(n)<=Dte)return t;let r=n.lastIndexOf("."),o=r>=0?n.substring(r):"",i=r>=0?n.substring(0,r):n,s=WS(o),a=Dte-s;return a<=0?e[e.length-1]=ZD(n,Dte):e[e.length-1]=ZD(i,a)+o,e.join("/")}async function VAe(t,e=!0){let n=null;app.workspace.iterateAllLeaves(r=>{if(r.view.getViewType()==="markdown"||r.view.getViewType()==="pdf"||r.view.getViewType()==="canvas"){let o=r.view.file;o&&o.path===t.path&&(n=r)}}),n&&e?app.workspace.setActiveLeaf(n,{focus:!0}):n||await app.workspace.getLeaf("tab").openFile(t)}var PAe,Kl,$te,JD,ll,gbt,Dte,qe=C(()=>{PAe=N(uD());Qi();It();ye();Lte();Kl=require("obsidian");VS();Wee();Hx();$te={INVALID_LICENSE_KEY_USER:"Invalid Copilot Plus license key. Please check your license key in settings.",UNKNOWN_ERROR:"An unknown error occurred",REQUEST_FAILED:t=>`Request failed, status ${t}`};JD=(t,e)=>{let n=t.getMarkdownFiles();if(e==="/")return n;let r=e.toLowerCase().replace(/^\/|\/$/g,"");return n.filter(o=>{let s=o.path.toLowerCase().split("/"),a=r.split("/"),l=0;for(let c of a){for(;l<s.length&&s[l]!==c;)l++;if(l>=s.length)return!1}return!0})};ll=(t,e="local")=>{let n=e==="utc"?hn.fromJSDate(t).toUTC():hn.fromJSDate(t);return{fileName:n.toFormat("yyyyMMdd_HHmmss"),display:n.toFormat("yyyy/MM/dd HH:mm:ss"),epoch:n.toMillis()}};gbt=/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|shorts\/)|youtu\.be\/)([^\s&]+)/;Dte=255});var WAe,Wte,Ds,HS=C(()=>{Wee();WAe=require("obsidian");qe();Se();Su();Wte=class t{constructor(){this.maxLines=500;this.maxLineChars=8e3;this.buffer=[];this.initialized=!1;this.flushing=!1}static getInstance(){return t.instance||(t.instance=new t),t.instance}getLogPath(){return"copilot/copilot-log.md"}async ensureInitialized(){this.initialized||(this.initialized=!0)}hasVault(){try{return typeof app<"u"&&!!app.vault?.adapter}catch{return!1}}sanitizeForSingleLine(e){if(e instanceof Error){let n=Xt(e,!0);return this.escapeAngleBrackets(this.collapseToSingleLine(n))}if(typeof e=="string")return this.escapeAngleBrackets(this.collapseToSingleLine(e));try{let n=JSON.stringify(e);return this.escapeAngleBrackets(this.collapseToSingleLine(n??String(e)))}catch{return this.escapeAngleBrackets(this.collapseToSingleLine(String(e)))}}collapseToSingleLine(e){let n=e.replace(/[\r\n]+/g,"\\n").replace(/\t/g," ");return n.length<=this.maxLineChars?n:n.slice(0,this.maxLineChars)+` \u2026 [truncated ${n.length-this.maxLineChars} chars]`}async append(e,...n){await this.ensureInitialized();let r=new Date().toISOString(),o=n.map(s=>this.sanitizeForSingleLine(s)),i=`${r} ${e} ${o.join(" ")}`.trim();this.buffer.push(i),this.buffer.length>this.maxLines&&this.buffer.splice(0,this.buffer.length-
`)+(this.buffer.length?`
`:"");await app.vault.adapter.write(e,n)}}catch{}finally{this.flushing=!1}}}async clear(){if(this.buffer=[],!!this.hasVault())try{let e=this.getLogPath();await app.vault.adapter.exists(e)&&await app.vault.adapter.remove(e)}catch{}}sanitizeSettingsForLog(){let e=q();return this.removeKeysRecursive(e)}removeKeysRecursive(e){if(e==null)return e;if(Array.isArray(e))return e.map(n=>this.removeKeysRecursive(n));if(typeof e=="object"&&e.constructor===Object){let n={},r=e;for(let[o,i]of Object.entries(r))Mx(o)||/orgId$/i.test(o)||/instanceName$/i.test(o)||/deploymentName$/i.test(o)||/apiVersion$/i.test(o)||(n[o]=this.removeKeysRecursive(i));return n}return e}async openLogFile(){if(!this.hasVault())return;let e=this.getLogPath(),n=[...this.buffer];try{let i=this.sanitizeSettingsForLog(),a=["","## Settings","```json",...JSON.stringify(i,null,2).split(`
`),"```"];n.push(...a)}catch{}try{let i=n.join(`
`)+(n.length?`
`:""),s=e.includes("/")?e.split("/").slice(0,-1).join("/"):"";s&&await Fr(s),await app.vault.adapter.exists(e)?await app.vault.adapter.write(e,i):await app.vault.create(e,i)}catch{}let r=app.vault.getAbstractFileByPath(e),o=r instanceof WAe.TFile?r:null;try{o&&await app.workspace.getLeaf(!0).openFile(o)}catch{}}},Ds=Wte.getInstance()});function k(...t){q().debug&&console.log(...t),Ds.append("INFO",...t)}function z(...t){q().debug&&console.error(...t),Ds.append("ERROR",...t)}function ee(...t){q().debug&&console.warn(...t),Ds.append("WARN",...t)}function jW(t){Ds.appendMarkdownBlock(t)}function HAe(t,e){if(q().debug)try{if(typeof console.table=="function"){Array.isArray(e)&&e.length>0?console.table(t,e):console.table(t);return}}catch{}k("Table:",JSON.stringify(t))}var ye=C(()=>{Se();HS()});function ZAe(t){Kn.set(WW,t)}function Iu(){return Kn.get(WW)}function JAe(t){return Kn.sub(WW,t)}function qx(){return Hy(WW,{store:Kn})}function ym(){return Kn.get(HW)}function XAe(t){Kn.set(HW,t)}function QAe(t){return Kn.sub(HW,t)}function kd(){return Hy(HW,{store:Kn})}function Gx(t){Kn.set(VW,t)}function br(){return Kn.get(VW)}function OA(t){return Kn.sub(VW,()=>{t(Kn.get(VW))})}function rg(t){Kn.set(YAe,t)}function KW(){return Hy(YAe,{store:Kn})}function RA(){return ym()==="project"}function og(t){Kn.set(Hte,t)}function wm(){return Kn.get(Hte)}function eke(t){let e=wm();og(e.filter(n=>n.id!==t))}function tke(){og([])}function nke(){return Hy(Hte,{store:Kn})}function rke(t){Kn.set(n$,t)}function ig(t,e){Kn.set(n$,n=>({...n,[t]:e(n[t])}))}function Yx(){return Hy(n$,{store:Kn})}function LA(){return Kn.get(r$)}function Kte(t){Kn.set(r$,t)}function ul(t){Kn.set(r$,e=>({...e,...t}))}function qte(){Ff!==null&&(window.clearTimeout(Ff),Ff=null),MA=0,NA=0,Kn.set(r$,{isActive:!1,isPaused:!1,isCancelled:!1,indexedCount:0,totalFiles:0,errors:[],completionStatus:"none"})}function oke(t){NA=t;let e=Date.now();e-MA>=GAe?(MA=e,Ff!==null&&(window.clearTimeout(Ff),Ff=null),ul({indexedCount:NA})):Ff===null&&(Ff=window.setTimeout(()=>{MA=Date.now(),Ff=null,ul({indexedCount:NA})},GAe-(e-MA)))}function ike(){Ff!==null&&(window.clearTimeout(Ff),Ff=null),ul({indexedCount:NA}),MA=0,NA=0}function DA(){return Hy(r$,{store:Kn})}var KAe,WW,qAe,HW,VW,YAe,n$,r$,Hte,MA,NA,Ff,GAe,Ir=C(()=>{Qi();Se();Id();KAe=Oo(null),WW=Oo(t=>{let e=t(KAe);return e!==null?e:t(Ox).defaultModelKey},(t,e,n)=>{e(KAe,n)}),qAe=Oo(null),HW=Oo(t=>{let e=t(qAe);return e!==null?e:t(Ox).defaultChainType},(t,e,n)=>{e(qAe,n)}),VW=Oo(null),YAe=Oo(!1),n$=Oo({success:[],failed:[],processingFiles:[],total:[]}),r$=Oo({isActive:!1,isPaused:!1,isCancelled:!1,indexedCount:0,totalFiles:0,errors:[],completionStatus:"none"}),Hte=Oo([]);MA=0,NA=0,Ff=null,GAe=500});function ske(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function ake(...t){return e=>{let n=!1,r=t.map(o=>{let i=ske(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():ske(t[o],null)}}}}var xbt,lke=C(()=>{xbt=N(U(),1)});var uke=Tt(qW=>{"use strict";var bbt=U(),Cbt=Symbol.for("react.element"),_bt=Symbol.for("react.fragment"),Sbt=Object.prototype.hasOwnProperty,Tbt=bbt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,Ibt={key:!0,ref:!0,__self:!0,__source:!0};function cke(t,e,n){var r,o={},i=null,s=null;n!==void 0&&(i=""+n),e.key!==void 0&&(i=""+e.key),e.ref!==void 0&&(s=e.ref);for(r in e)Sbt.call(e,r)&&!Ibt.hasOwnProperty(r)&&(o[r]=e[r]);if(t&&t.defaultProps)for(r in e=t.defaultProps,e)o[r]===void 0&&(o[r]=e[r]);return{$$typeof:Cbt,type:t,key:i,ref:s,props:o,_owner:Tbt.current}}qW.Fragment=_bt;qW.jsx=cke;qW.jsxs=cke});var Ve=Tt((Wan,dke)=>{"use strict";dke.exports=uke()});function Ebt(t){return typeof t=="object"&&t!==null&&"then"in t}function fke(t){return t!=null&&typeof t=="object"&&"$$typeof"in t&&t.$$typeof===Pbt&&"_payload"in t&&Ebt(t._payload)}function Abt(t){let e=kbt(t),n=gs.forwardRef((r,o)=>{let{children:i,...s}=r;fke(i)&&typeof YW=="function"&&(i=YW(i._payload));let a=gs.Children.toArray(i),l=a.find(Nbt);if(l){let c=l.pro
`+lne+t}var cne=!1;function une(t,e){if(!t||cne)return"";cne=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(e)if(e=function(){throw Error()},Object.defineProperty(e.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(e,[])}catch(c){var r=c}Reflect.construct(t,[],e)}else{try{e.call()}catch(c){r=c}t.call(e.prototype)}else{try{throw Error()}catch(c){r=c}t()}}catch(c){if(c&&r&&typeof c.stack=="string"){for(var o=c.stack.split(`
`),i=r.stack.split(`
`),s=o.length-1,a=i.length-1;1<=s&&0<=a&&o[s]!==i[a];)a--;for(;1<=s&&0<=a;s--,a--)if(o[s]!==i[a]){if(s!==1||a!==1)do if(s--,a--,0>a||o[s]!==i[a]){var l=`
`+o[s].replace(" at new "," at ");return t.displayName&&l.includes("<anonymous>")&&(l=l.replace("<anonymous>",t.displayName)),l}while(1<=s&&0<=a);break}}}finally{cne=!1,Error.prepareStackTrace=n}return(t=t?t.displayName||t.name:"")?G$(t):""}function xCt(t){switch(t.tag){case 5:return G$(t.type);case 16:return G$("Lazy");case 13:return G$("Suspense");case 19:return G$("SuspenseList");case 0:case 2:case 15:return t=une(t.type,!1),t;case 11:return t=une(t.type.render,!1),t;case 1:return t=une(t.type,!0),t;default:return""}}function Rne(t){if(t==null)return null;if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case JA:return"Fragment";case ZA:return"Portal";case Mne:return"Profiler";case Tre:return"StrictMode";case Nne:return"Suspense";case One:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case LOe:return(t.displayName||"Context")+".Consumer";case ROe:return(t._context.displayName||"Context")+".Provider";case Ire:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case Pre:return e=t.displayName||null,e!==null?e:Rne(t.type)||"Memo";case sb:e=t._payload,t=t._init;try{return Rne(t(e))}catch{}}return null}function bCt(t){var e=t.type;switch(t.tag){case 24:return"Cache";case 9:return(e.displayName||"Context")+".Consumer";case 10:return(e._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return t=e.render,t=t.displayName||t.name||"",e.displayName||(t!==""?"ForwardRef("+t+")":"ForwardRef");case 7:return"Fragment";case 5:return e;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Rne(e);case 8:return e===Tre?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e}return null}function xb(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function $Oe(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function CCt(t){var e=$Oe(t)?"checked":"value",n=Object.getOwnPropertyDescriptor(t.constructor.prototype,e),r=""+t[e];if(!t.hasOwnProperty(e)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var o=n.get,i=n.set;return Object.defineProperty(t,e,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.call(this,s)}}),Object.defineProperty(t,e,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(s){r=""+s},stopTracking:function(){t._valueTracker=null,delete t[e]}}}}function aH(t){t._valueTracker||(t._valueTracker=CCt(t))}function FOe(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var n=e.getValue(),r="";return t&&(r=$Oe(t)?t.checked?"true":"false":t.value),t=r,t!==n?(e.setValue(t),!0):!1}function LH(t){if(t=t||(typeof document<"u"?document:void 0),typeof t>"u")return null;try{return t.activeElement||t.body}catch{return t.body}}function Lne(t,e){var n=e.checked;return Si({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??t._wrapperState.initialChecked})}function ANe(t,e){var n=e.defaultValue==null?"":e.defaultValue,r=e.checked!=null?e.checked:e.defaultChecked;n=xb(e.value!=null?e.value:n),t._wrapperState={initialChecked:r,initialValue:n,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function UOe(t,e){e=e.checked,e!=null&&Sre(t,"checked",e,!1)}function Dne(t,e){UOe(t,e);var n=xb(e.value),r=e.type;if(n!=null)r==="number"?(n===0&&t.value===""||t.value!=n)&&(t.value=""+n):t.value!==""+n&&(t.value=""+n);else if(r==="submit"||r==="reset"){t.removeAttribute("value");return}e.hasOwnProperty("value")?$ne(t,e.type,n):e.hasOwnProperty("defaultValue")&&$ne(t,e.type,xb(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}function k
`).replace(k_t,"")}function vH(t,e,n){if(e=eOe(e),eOe(t)!==e&&n)throw Error(Be(425))}function VH(){}var Jne=null,Xne=null;function Qne(t,e){return t==="textarea"||t==="noscript"||typeof e.children=="string"||typeof e.children=="number"||typeof e.dangerouslySetInnerHTML=="object"&&e.dangerouslySetInnerHTML!==null&&e.dangerouslySetInnerHTML.__html!=null}var ere=typeof setTimeout=="function"?setTimeout:void 0,M_t=typeof clearTimeout=="function"?clearTimeout:void 0,tOe=typeof Promise=="function"?Promise:void 0,N_t=typeof queueMicrotask=="function"?queueMicrotask:typeof tOe<"u"?function(t){return tOe.resolve(null).then(t).catch(O_t)}:ere;function O_t(t){setTimeout(function(){throw t})}function xne(t,e){var n=e,r=0;do{var o=n.nextSibling;if(t.removeChild(n),o&&o.nodeType===8)if(n=o.data,n==="/$"){if(r===0){t.removeChild(o),fF(e);return}r--}else n!=="$"&&n!=="$?"&&n!=="$!"||r++;n=o}while(n);fF(e)}function hb(t){for(;t!=null;t=t.nextSibling){var e=t.nodeType;if(e===1||e===3)break;if(e===8){if(e=t.data,e==="$"||e==="$!"||e==="$?")break;if(e==="/$")return null}}return t}function nOe(t){t=t.previousSibling;for(var e=0;t;){if(t.nodeType===8){var n=t.data;if(n==="$"||n==="$!"||n==="$?"){if(e===0)return t;e--}else n==="/$"&&e++}t=t.previousSibling}return null}var Ck=Math.random().toString(36).slice(2),mg="__reactFiber$"+Ck,yF="__reactProps$"+Ck,mw="__reactContainer$"+Ck,tre="__reactEvents$"+Ck,R_t="__reactListeners$"+Ck,L_t="__reactHandles$"+Ck;function rT(t){var e=t[mg];if(e)return e;for(var n=t.parentNode;n;){if(e=n[mw]||n[mg]){if(n=e.alternate,e.child!==null||n!==null&&n.child!==null)for(t=nOe(t);t!==null;){if(n=t[mg])return n;t=nOe(t)}return e}t=n,n=t.parentNode}return null}function IF(t){return t=t[mg]||t[mw],!t||t.tag!==5&&t.tag!==6&&t.tag!==13&&t.tag!==3?null:t}function tk(t){if(t.tag===5||t.tag===6)return t.stateNode;throw Error(Be(33))}function c6(t){return t[yF]||null}var nre=[],nk=-1;function _b(t){return{current:t}}function Go(t){0>nk||(t.current=nre[nk],nre[nk]=null,nk--)}function Do(t,e){nk++,nre[nk]=t.current,t.current=e}var bb={},Xl=_b(bb),Nu=_b(!1),lT=bb;function hk(t,e){var n=t.type.contextTypes;if(!n)return bb;var r=t.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===e)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=e[i];return r&&(t=t.stateNode,t.__reactInternalMemoizedUnmaskedChildContext=e,t.__reactInternalMemoizedMaskedChildContext=o),o}function Ou(t){return t=t.childContextTypes,t!=null}function WH(){Go(Nu),Go(Xl)}function rOe(t,e,n){if(Xl.current!==bb)throw Error(Be(168));Do(Xl,e),Do(Nu,n)}function PRe(t,e,n){var r=t.stateNode;if(e=e.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in e))throw Error(Be(108,bCt(t)||"Unknown",o));return Si({},n,r)}function HH(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||bb,lT=Xl.current,Do(Xl,t),Do(Nu,Nu.current),!0}function oOe(t,e,n){var r=t.stateNode;if(!r)throw Error(Be(169));n?(t=PRe(t,e,lT),r.__reactInternalMemoizedMergedChildContext=t,Go(Nu),Go(Xl),Do(Xl,t)):Go(Nu),Do(Nu,n)}var cw=null,u6=!1,bne=!1;function ERe(t){cw===null?cw=[t]:cw.push(t)}function D_t(t){u6=!0,ERe(t)}function Sb(){if(!bne&&cw!==null){bne=!0;var t=0,e=po;try{var n=cw;for(po=1;t<n.length;t++){var r=n[t];do r=r(!0);while(r!==null)}cw=null,u6=!1}catch(o){throw cw!==null&&(cw=cw.slice(t+1)),QOe(Are,Sb),o}finally{po=e,bne=!1}}return null}var rk=[],ok=0,KH=null,qH=0,Vf=[],Wf=0,cT=null,uw=1,dw="";function tT(t,e){rk[ok++]=qH,rk[ok++]=KH,KH=t,qH=e}function ARe(t,e,n){Vf[Wf++]=uw,Vf[Wf++]=dw,Vf[Wf++]=cT,cT=t;var r=uw;t=dw;var o=32-Am(r)-1;r&=~(1<<o),n+=1;var i=32-Am(e)+o;if(30<i){var s=o-o%5;i=(r&(1<<s)-1).toString(32),r>>=s,o-=s,uw=1<<32-Am(e)+o|n<<o|r,dw=i+t}else uw=1<<i|n<<o|r,dw=t}function Fre(t){t.return!==null&&(tT(t,1),ARe(t,1,0))}function Ure(t){for(;t===KH;)KH=rk[--ok],rk[ok]=null,qH=rk[--ok],rk[ok]=null;for(;t===cT;)cT=Vf[--Wf],Vf[Wf]=null,dw=Vf[--Wf],Vf[Wf]=null,uw=Vf[--Wf],Vf[Wf]=null}var Ld=null,Rd=null,li=!1,Em=null;function kRe(t,e){var n=Hf(5,null,null,0);n.elementT
Error generating stack: `+i.message+`
`+i.stack}return{value:t,source:e,stack:o,digest:null}}function Ine(t,e,n){return{value:t,source:null,stack:n??null,digest:e??null}}function lre(t,e){try{console.error(e.value)}catch(n){setTimeout(function(){throw n})}}var H_t=typeof WeakMap=="function"?WeakMap:Map;function oLe(t,e,n){n=fw(-1,n),n.tag=3,n.payload={element:null};var r=e.value;return n.callback=function(){t6||(t6=!0,wre=r),lre(t,e)},n}function iLe(t,e,n){n=fw(-1,n),n.tag=3;var r=t.type.getDerivedStateFromError;if(typeof r=="function"){var o=e.value;n.payload=function(){return r(o)},n.callback=function(){lre(t,e)}}var i=t.stateNode;return i!==null&&typeof i.componentDidCatch=="function"&&(n.callback=function(){lre(t,e),typeof r!="function"&&(yb===null?yb=new Set([this]):yb.add(this));var s=e.stack;this.componentDidCatch(e.value,{componentStack:s!==null?s:""})}),n}function mOe(t,e,n){var r=t.pingCache;if(r===null){r=t.pingCache=new H_t;var o=new Set;r.set(e,o)}else o=r.get(e),o===void 0&&(o=new Set,r.set(e,o));o.has(n)||(o.add(n),t=iSt.bind(null,t,e,n),e.then(t,t))}function hOe(t){do{var e;if((e=t.tag===13)&&(e=t.memoizedState,e=e!==null?e.dehydrated!==null:!0),e)return t;t=t.return}while(t!==null);return null}function gOe(t,e,n,r,o){return(t.mode&1)===0?(t===e?t.flags|=65536:(t.flags|=128,n.flags|=131072,n.flags&=-52805,n.tag===1&&(n.alternate===null?n.tag=17:(e=fw(-1,1),e.tag=2,gb(n,e,1))),n.lanes|=1),t):(t.flags|=65536,t.lanes=o,t)}var K_t=yw.ReactCurrentOwner,Mu=!1;function Dc(t,e,n,r){e.child=t===null?$Re(e,null,n,r):yk(e,t.child,n,r)}function yOe(t,e,n,r,o){n=n.render;var i=e.ref;return fk(e,o),r=Zre(t,e,n,r,i,o),n=Jre(),t!==null&&!Mu?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,gw(t,e,o)):(li&&n&&Fre(e),e.flags|=1,Dc(t,e,r,o),e.child)}function wOe(t,e,n,r,o){if(t===null){var i=n.type;return typeof i=="function"&&!aoe(i)&&i.defaultProps===void 0&&n.compare===null&&n.defaultProps===void 0?(e.tag=15,e.type=i,sLe(t,e,i,r,o)):(t=RH(n.type,null,r,e,e.mode,o),t.ref=e.ref,t.return=e,e.child=t)}if(i=t.child,(t.lanes&o)===0){var s=i.memoizedProps;if(n=n.compare,n=n!==null?n:mF,n(s,r)&&t.ref===e.ref)return gw(t,e,o)}return e.flags|=1,t=vb(i,r),t.ref=e.ref,t.return=e,e.child=t}function sLe(t,e,n,r,o){if(t!==null){var i=t.memoizedProps;if(mF(i,r)&&t.ref===e.ref)if(Mu=!1,e.pendingProps=r=i,(t.lanes&o)!==0)(t.flags&131072)!==0&&(Mu=!0);else return e.lanes=t.lanes,gw(t,e,o)}return cre(t,e,n,r,o)}function aLe(t,e,n){var r=e.pendingProps,o=r.children,i=t!==null?t.memoizedState:null;if(r.mode==="hidden")if((e.mode&1)===0)e.memoizedState={baseLanes:0,cachePool:null,transitions:null},Do(ak,Od),Od|=n;else{if((n&1073741824)===0)return t=i!==null?i.baseLanes|n:n,e.lanes=e.childLanes=1073741824,e.memoizedState={baseLanes:t,cachePool:null,transitions:null},e.updateQueue=null,Do(ak,Od),Od|=t,null;e.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=i!==null?i.baseLanes:n,Do(ak,Od),Od|=r}else i!==null?(r=i.baseLanes|n,e.memoizedState=null):r=n,Do(ak,Od),Od|=r;return Dc(t,e,o,n),e.child}function lLe(t,e){var n=e.ref;(t===null&&n!==null||t!==null&&t.ref!==n)&&(e.flags|=512,e.flags|=2097152)}function cre(t,e,n,r,o){var i=Ou(n)?lT:Xl.current;return i=hk(e,i),fk(e,o),n=Zre(t,e,n,r,i,o),r=Jre(),t!==null&&!Mu?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,gw(t,e,o)):(li&&r&&Fre(e),e.flags|=1,Dc(t,e,n,o),e.child)}function vOe(t,e,n,r,o){if(Ou(n)){var i=!0;HH(e)}else i=!1;if(fk(e,o),e.stateNode===null)MH(t,e),LRe(e,n,r),are(e,n,r,o),r=!0;else if(t===null){var s=e.stateNode,a=e.memoizedProps;s.props=a;var l=s.context,c=n.contextType;typeof c=="object"&&c!==null?c=qf(c):(c=Ou(n)?lT:Xl.current,c=hk(e,c));var u=n.getDerivedStateFromProps,d=typeof u=="function"||typeof s.getSnapshotBeforeUpdate=="function";d||typeof s.UNSAFE_componentWillReceiveProps!="function"&&typeof s.componentWillReceiveProps!="function"||(a!==r||l!==c)&&uOe(e,s,r,c),ab=!1;var f=e.memoizedState;s.state=f,ZH(e,r,s,o),l=e.memoizedState,a!==r||f!==l||Nu.current||ab?(typeof u=="function"&&(sre(e,n,u,r),l=e.memoizedState),(a=ab||cOe(e,n,a,r,f,l,c))?(d||typeof s.UNSAFE_componentWillMount!="funct
`)}var zLe,DF,Ik,Aoe=C(()=>{_k();An();zLe=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,woe,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},DF=ce("$ZodError",zLe),Ik=ce("$ZodError",zLe,{Parent:Error})});var C6,wT,_6,vT,S6,koe,T6,Moe,I6=C(()=>{_k();Aoe();An();C6=t=>(e,n,r,o)=>{let i=r?Object.assign(r,{async:!1}):{async:!1},s=e._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new wg;if(s.issues.length){let a=new(o?.Err??t)(s.issues.map(l=>Ud(l,i,vs())));throw b6(a,o?.callee),a}return s.value},wT=C6(Ik),_6=t=>async(e,n,r,o)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},s=e._zod.run({value:n,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(o?.Err??t)(s.issues.map(l=>Ud(l,i,vs())));throw b6(a,o?.callee),a}return s.value},vT=_6(Ik),S6=t=>(e,n,r)=>{let o=r?{...r,async:!1}:{async:!1},i=e._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new wg;return i.issues.length?{success:!1,error:new(t??DF)(i.issues.map(s=>Ud(s,o,vs())))}:{success:!0,data:i.value}},koe=S6(Ik),T6=t=>async(e,n,r)=>{let o=r?Object.assign(r,{async:!0}):{async:!0},i=e._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new t(i.issues.map(s=>Ud(s,o,vs())))}:{success:!0,data:i.value}},Moe=T6(Ik)});var bT={};zn(bT,{_emoji:()=>VLe,base64:()=>Koe,base64url:()=>P6,bigint:()=>Qoe,boolean:()=>nie,browserEmail:()=>VSt,cidrv4:()=>Woe,cidrv6:()=>Hoe,cuid:()=>Noe,cuid2:()=>Ooe,date:()=>Yoe,datetime:()=>Joe,domain:()=>WSt,duration:()=>Foe,e164:()=>Goe,email:()=>Boe,emoji:()=>zoe,extendedDuration:()=>DSt,guid:()=>Uoe,hostname:()=>qoe,html5Email:()=>BSt,integer:()=>eie,ipv4:()=>joe,ipv6:()=>Voe,ksuid:()=>Doe,lowercase:()=>iie,nanoid:()=>$oe,null:()=>rie,number:()=>tie,rfc5322Email:()=>zSt,string:()=>Xoe,time:()=>Zoe,ulid:()=>Roe,undefined:()=>oie,unicodeEmail:()=>jSt,uppercase:()=>sie,uuid:()=>xT,uuid4:()=>$St,uuid6:()=>FSt,uuid7:()=>USt,xid:()=>Loe});function zoe(){return new RegExp(VLe,"u")}function HLe(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Zoe(t){return new RegExp(`^${HLe(t)}$`)}function Joe(t){let e=HLe({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-]\\d{2}:\\d{2})");let r=`${e}(?:${n.join("|")})`;return new RegExp(`^${WLe}T(?:${r})$`)}var Noe,Ooe,Roe,Loe,Doe,$oe,Foe,DSt,Uoe,xT,$St,FSt,USt,Boe,BSt,zSt,jSt,VSt,VLe,joe,Voe,Woe,Hoe,Koe,P6,qoe,WSt,Goe,WLe,Yoe,Xoe,Qoe,eie,tie,nie,rie,oie,iie,sie,E6=C(()=>{Noe=/^[cC][^\s-]{8,}$/,Ooe=/^[0-9a-z]+$/,Roe=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Loe=/^[0-9a-vA-V]{20}$/,Doe=/^[A-Za-z0-9]{27}$/,$oe=/^[a-zA-Z0-9_-]{21}$/,Foe=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,DSt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Uoe=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,xT=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,$St=xT(4),FSt=xT(6),USt=xT(7),Boe=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,BSt=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,zSt=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}]
`).filter(s=>s),o=Math.min(...r.map(s=>s.length-s.trimStart().length)),i=r.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(let s of i)this.content.push(s)}compile(){let e=Function,n=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new e(...n,o.join(`
`))}}});var Iie,Pie=C(()=>{Iie={major:4,minor:0,patch:0}});function Gie(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function s1e(t){if(!P6.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return Gie(n)}function a1e(t,e=null){try{let n=t.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function YLe(t,e,n){t.issues.length&&e.issues.push(...Lu(n,t.issues)),e.value[n]=t.value}function N6(t,e,n){t.issues.length&&e.issues.push(...Lu(n,t.issues)),e.value[n]=t.value}function ZLe(t,e,n,r){t.issues.length?r[n]===void 0?n in r?e.value[n]=void 0:e.value[n]=t.value:e.issues.push(...Lu(n,t.issues)):t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function JLe(t,e,n,r){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(o=>o.issues.map(i=>Ud(i,r,vs())))}),e}function Eie(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Tk(t)&&Tk(e)){let n=Object.keys(e),r=Object.keys(t).filter(i=>n.indexOf(i)!==-1),o={...t,...e};for(let i of r){let s=Eie(t[i],e[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<t.length;r++){let o=t[r],i=e[r],s=Eie(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function XLe(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),yT(t))return t;let r=Eie(e.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return t.value=r.data,t}function O6(t,e,n){t.issues.length&&e.issues.push(...Lu(n,t.issues)),e.value[n]=t.value}function QLe(t,e,n,r,o,i,s){t.issues.length&&(OF.has(typeof r)?n.issues.push(...Lu(r,t.issues)):n.issues.push({origin:"map",code:"invalid_key",input:o,inst:i,issues:t.issues.map(a=>Ud(a,s,vs()))})),e.issues.length&&(OF.has(typeof r)?n.issues.push(...Lu(r,e.issues)):n.issues.push({origin:"map",code:"invalid_element",input:o,inst:i,key:r,issues:e.issues.map(a=>Ud(a,s,vs()))})),n.value.set(t.value,e.value)}function e1e(t,e){t.issues.length&&e.issues.push(...t.issues),e.value.add(t.value)}function t1e(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function n1e(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function r1e(t,e,n){return yT(t)?t:e.out._zod.run({value:t.value,issues:t.issues},n)}function o1e(t){return t.value=Object.freeze(t.value),t}function i1e(t,e,n,r){if(!t){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),e.issues.push(Ioe(o))}}var jn,CT,_o,Aie,kie,Mie,Nie,Oie,Rie,Lie,Die,$ie,Fie,Uie,Bie,zie,jie,Vie,Wie,Hie,Kie,qie,Yie,Zie,Jie,Xie,Qie,R6,ese,BF,L6,tse,nse,rse,ose,ise,_T,zF,sse,ase,jF,lse,D6,cse,use,ST,dse,fse,pse,mse,hse,gse,VF,$6,yse,wse,vse,xse,bse,Cse,_se,WF,Sse,Tse,Ise,Pse,Ese,HF=C(()=>{M6();_k();Tie();I6();E6();An();Pie();An();jn=ce("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Iie;let r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(let o of r)for(let i of o._zod.onattach)i(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(i,s,a)=>{let l=yT(i),c;for(let u of s){if(u._zod.def.when){if(!u._zod.def.when(i))continue}else if(l)continue;let d=i.issues.length,f=u._zod.check(i);if(f instanceof Promise&&a?.async===!1)throw new wg;if(c||f instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await f,i.issues.leng
if (${v}.issues.length) {
if (input[${x}] === undefined) {
if (${x} in input) {
newResult[${x}] = undefined;
}
} else {
payload.issues = payload.issues.concat(
${v}.issues.map((iss) => ({
...iss,
path: iss.path ? [${x}, ...iss.path] : [${x}],
}))
);
}
} else if (${v}.value === undefined) {
if (${x} in input) newResult[${x}] = undefined;
} else {
newResult[${x}] = ${v}.value;
}
`)}else{let v=h[w];f.write(`const ${v} = ${m(w)};`),f.write(`
if (${v}.issues.length) payload.issues = payload.issues.concat(${v}.issues.map(iss => ({
...iss,
path: iss.path ? [${gT(w)}, ...iss.path] : [${gT(w)}]
})));`),f.write(`newResult[${gT(w)}] = ${v}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let y=f.compile();return(w,v)=>y(d,w,v)},o,i=Sk,s=!EF.jitless,l=s&&boe.value,c=e.catchall,u;t._zod.parse=(d,f)=>{u??(u=n.value);let p=d.value;if(!i(p))return d.issues.push({expected:"object",code:"invalid_type",input:p,inst:t}),d;let m=[];if(s&&l&&f?.async===!1&&f.jitless!==!0)o||(o=r(e.shape)),d=o(d,f);else{d.value={};let v=u.shape;for(let x of u.keys){let b=v[x],_=b._zod.run({value:p[x],issues:[]},f),T=b._zod.optin==="optional"&&b._zod.optout==="optional";_ instanceof Promise?m.push(_.then(S=>T?ZLe(S,d,x,p):N6(S,d,x))):T?ZLe(_,d,x,p):N6(_,d,x)}}if(!c)return m.length?Promise.all(m).then(()=>d):d;let h=[],g=u.keySet,y=c._zod,w=y.def.type;for(let v of Object.keys(p)){if(g.has(v))continue;if(w==="never"){h.push(v);continue}let x=y.run({value:p[v],issues:[]},f);x instanceof Promise?m.push(x.then(b=>N6(b,d,v))):N6(x,d,v)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:p,inst:t}),m.length?Promise.all(m).then(()=>d):d}});D6=ce("$ZodUnion",(t,e)=>{jn.init(t,e),Zr(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),Zr(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),Zr(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),Zr(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>NF(r.source)).join("|")})$`)}}),t._zod.parse=(n,r)=>{let o=!1,i=[];for(let s of e.options){let a=s._zod.run({value:n.value,issues:[]},r);if(a instanceof Promise)i.push(a),o=!0;else{if(a.issues.length===0)return a;i.push(a)}}return o?Promise.all(i).then(s=>JLe(s,n,t,r)):JLe(i,n,t,r)}}),cse=ce("$ZodDiscriminatedUnion",(t,e)=>{D6.init(t,e);let n=t._zod.parse;Zr(t._zod,"propValues",()=>{let o={};for(let i of e.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let[a,l]of Object.entries(s)){o[a]||(o[a]=new Set);for(let c of l)o[a].add(c)}}return o});let r=MF(()=>{let o=e.options,i=new Map;for(let s of o){let a=s._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let l of a){if(i.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);i.set(l,s)}}return i});t._zod.parse=(o,i)=>{let s=o.value;if(!Sk(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:t}),o;let a=r.value.get(s?.[e.discriminator]);return a?a._zod.run(o,i):e.unionFallback?n(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:s,path:[e.discriminator],inst:t}),o)}}),use=ce("$ZodIntersection",(t,e)=>{jn.init(t,e),t._zod.parse=(n,r)=>{let o=n.value,i=e.left._zod.run({value:o,issues:[]},r),s=e.right._zod.run({value:o,issues:[]},r);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([l,c])=>XLe(n,l,c)):XLe(n,i,s)}});ST=ce("$ZodTuple",(t,e)=>{jn.init(t,e);let n=e.items,r=n.length-[...n].reverse().findIndex(o=>o._zod.optin!=="optional");t._zod.parse=(o,i)=>{let s=o.value;if(!Array.isArray(s))return o.issues.push({input:s,inst:t,expected:"tuple",code:"invalid_type"}),o;o.value=[];let a=[];if(!e.rest){let c=s.length>n.length,u=s.length<r-1;if(c||u)return o.issues.push({input:s,inst:t,origin:"array",...c?{code:"too_big",maximum:n.length}:{code:"too_small",minimum:n.length}}),o}let l=-1;for(let c of n){if(l++,l>=s.length&&l>=r)continue;let u=c._zod.run({value:s[l],issues:[]},i);u instanceof Promise?a.push(u.then(d=>O6(d,o,l))):O6(u,o,l)}if(e.rest){let c=s.slice(n.length);for(let u of c){l++;let d=e.rest._zod.run({value:u,issues:[]},i);d instanceof Promise?a.push(d.then(f=>O6(f,o,l))):O6(d,o,l)}}return a.length?Promise.all(a).then(()=>o):o}});dse=ce("$ZodRecord",(t,e)=>{jn.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Tk(o))return n.issues.push({expected
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let u of this.seen.entries()){let d=u[1];if(e===u[0]){s(u);continue}if(r.external){let p=r.external.registry.get(u[0])?.id;if(e!==u[0]&&p){s(u);continue}}if(this.metadataRegistry.get(u[0])?.id){s(u);continue}if(d.cycle){s(u);continue}if(d.count>1&&r.reused==="ref"){s(u);continue}}let a=(u,d)=>{let f=this.seen.get(u),p=f.def??f.schema,m={...p};if(f.ref===null)return;let h=f.ref;if(f.ref=null,h){a(h,d);let g=this.seen.get(h).schema;g.$ref&&d.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(g)):(Object.assign(p,g),Object.assign(p,m))}f.isParent||this.override({zodSchema:u,jsonSchema:p,path:f.path??[]})};for(let u of[...this.seen.entries()].reverse())a(u[0],{target:this.target});let l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){let u=r.external.registry.get(e)?.id;if(!u)throw new Error("Schema is missing an `id` property");l.$id=r.external.uri(u)}Object.assign(l,o.def);let c=r.external?.defs??{};for(let u of this.seen.entries()){let d=u[1];d.def&&d.defId&&(c[d.defId]=d.def)}r.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}}});var LDe={};var DDe=C(()=>{});var Cw={};zn(Cw,{$ZodAny:()=>ise,$ZodArray:()=>jF,$ZodAsyncError:()=>wg,$ZodBase64:()=>Yie,$ZodBase64URL:()=>Zie,$ZodBigInt:()=>L6,$ZodBigIntFormat:()=>tse,$ZodBoolean:()=>BF,$ZodCIDRv4:()=>Kie,$ZodCIDRv6:()=>qie,$ZodCUID:()=>Lie,$ZodCUID2:()=>Die,$ZodCatch:()=>Cse,$ZodCheck:()=>Ti,$ZodCheckBigIntFormat:()=>cie,$ZodCheckEndsWith:()=>bie,$ZodCheckGreaterThan:()=>k6,$ZodCheckIncludes:()=>vie,$ZodCheckLengthEquals:()=>hie,$ZodCheckLessThan:()=>A6,$ZodCheckLowerCase:()=>yie,$ZodCheckMaxLength:()=>pie,$ZodCheckMaxSize:()=>uie,$ZodCheckMimeType:()=>_ie,$ZodCheckMinLength:()=>mie,$ZodCheckMinSize:()=>die,$ZodCheckMultipleOf:()=>aie,$ZodCheckNumberFormat:()=>lie,$ZodCheckOverwrite:()=>Sie,$ZodCheckProperty:()=>Cie,$ZodCheckRegex:()=>gie,$ZodCheckSizeEquals:()=>fie,$ZodCheckStartsWith:()=>xie,$ZodCheckStringFormat:()=>Pk,$ZodCheckUpperCase:()=>wie,$ZodCustom:()=>Ese,$ZodCustomStringFormat:()=>Qie,$ZodDate:()=>ase,$ZodDefault:()=>wse,$ZodDiscriminatedUnion:()=>cse,$ZodE164:()=>Jie,$ZodEmail:()=>Mie,$ZodEmoji:()=>Oie,$ZodEnum:()=>mse,$ZodError:()=>DF,$ZodFile:()=>gse,$ZodFunction:()=>a3,$ZodGUID:()=>Aie,$ZodIPv4:()=>Wie,$ZodIPv6:()=>Hie,$ZodISODate:()=>zie,$ZodISODateTime:()=>Bie,$ZodISODuration:()=>Vie,$ZodISOTime:()=>jie,$ZodIntersection:()=>use,$ZodJWT:()=>Xie,$ZodKSUID:()=>Uie,$ZodLazy:()=>Pse,$ZodLiteral:()=>hse,$ZodMap:()=>fse,$ZodNaN:()=>_se,$ZodNanoID:()=>Rie,$ZodNever:()=>zF,$ZodNonOptional:()=>xse,$ZodNull:()=>ose,$ZodNullable:()=>yse,$ZodNumber:()=>R6,$ZodNumberFormat:()=>ese,$ZodObject:()=>lse,$ZodOptional:()=>$6,$ZodPipe:()=>WF,$ZodPrefault:()=>vse,$ZodPromise:()=>Ise,$ZodReadonly:()=>Sse,$ZodRealError:()=>Ik,$ZodRecord:()=>dse,$ZodRegistry:()=>Ek,$ZodSet:()=>pse,$ZodString:()=>CT,$ZodStringFormat:()=>_o,$ZodSuccess:()=>bse,$ZodSymbol:()=>nse,$ZodTemplateLiteral:()=>Tse,$ZodTransform:()=>VF,$ZodTuple:()=>ST,$ZodType:()=>jn,$ZodULID:()=>$ie,$ZodURL:()=>Nie,$ZodUUID:()=>kie,$ZodUndefined:()=>rse,$ZodUnion:()=>D6,$ZodUnknown:()=>_T,$ZodVoid:()=>sse,$ZodXID:()=>Fie,$brand:()=>hoe,$constructor:()=>ce,$input:()=>Nse,$output:()=>Mse,Doc:()=>UF,JSONSchema:()=>LDe,JSONSchemaGenerator:()=>l2,NEVER:()=>moe,TimePrecision:()=>Dse,_any:()=>rae,_array:()=>a2,_base64:()=>r3,_base64url:()=>o3,_bigint:()=>Zse,_boolean:()=>Gse,_catch:()=>GTt,_cidrv4:()=>t3,_cidrv6:()=>n3,_coercedBigint:()=>Jse,_coercedBoolean:()=>Yse,_coercedDate:()=>sae,_coercedNumber:()=>jse,_coercedString:()=>Lse,_cuid:()=>G6,_cuid2:()=>Y6,_custom:()=>hae,_date:()=>iae,_default:()=>HTt,_discriminatedUnion:()=>RTt,_e164:()=>i3,_email:()=>B6,_emoji:()=>K6,_endsWith:()=>t2,_enum:()=>UTt,_file:()=>mae,_floa
]))`;continue}else if(r[l]==="$"){o+=`($|(?=[\r
]))`;continue}}if(n.s&&r[l]==="."){o+=s?`${r[l]}\r
`:`[${r[l]}\r
]`;continue}o+=r[l],r[l]==="\\"?i=!0:s&&r[l]==="]"?s=!1:!s&&r[l]==="["&&(s=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var jae,Om,m0t,b3=C(()=>{Eb();Om={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(jae===void 0&&(jae=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),jae),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};m0t=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function C3(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===he.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,o)=>({...r,[o]:Tn(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??ci(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:Tn(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===he.ZodString&&t.keyType._def.checks?.length){let{type:r,...o}=x3(t.keyType._def,e);return{...n,propertyNames:o}}else{if(t.keyType?._def.typeName===he.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===he.ZodBranded&&t.keyType._def.type._def.typeName===he.ZodString&&t.keyType._def.type._def.checks?.length){let{type:r,...o}=w3(t.keyType._def,e);return{...n,propertyNames:o}}}return n}var _3=C(()=>{Jf();v3();b3();bs();_g()});function m$e(t,e){return e.mapStrategy==="record"?C3(t,e):{type:"array",maxItems:125,items:{type:"array",items:[Tn(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ci(e),Tn(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ci(e)],minItems:2,maxItems:2}}}var Wae=C(()=>{Jf();_3();bs()});function h$e(t){let e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),r=Array.from(new Set(n.map(o=>typeof o)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:n}}va
Known schemas:
- ${Object.keys(r).join(`
- `)}`,new Error(Ue)}let dt=`${a}/$ref`,Me=Yo(t,Ie,n,r,o,i,s,dt,l);if(Me.valid||ke.push({instanceLocation:s,keyword:"$ref",keywordLocation:dt,error:"A subschema had errors."},...Me.errors),n==="4"||n==="7")return{valid:ke.length===0,errors:ke}}if(Array.isArray(m)){let He=m.length,Ie=!1;for(let dt=0;dt<He;dt++)if(u===m[dt]||m[dt]==="integer"&&u==="number"&&t%1===0&&t===t){Ie=!0;break}Ie||ke.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join('", "')}".`})}else m==="integer"?(u!=="number"||t%1||t!==t)&&ke.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&ke.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u==="object"||u==="array"?Pw(t,h)||ke.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):t!==h&&ke.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),g!==void 0&&(u==="object"||u==="array"?g.some(He=>Pw(t,He))||ke.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(He=>t===He)||ke.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),w!==void 0){let He=`${a}/not`;Yo(t,w,n,r,o,i,s,He).valid&&ke.push({instanceLocation:s,keyword:"not",keywordLocation:He,error:'Instance matched "not" schema.'})}let Ln=[];if(v!==void 0){let He=`${a}/anyOf`,Ie=ke.length,dt=!1;for(let Me=0;Me<v.length;Me++){let Ue=v[Me],it=Object.create(l),St=Yo(t,Ue,n,r,o,p===!0?i:null,s,`${He}/${Me}`,it);ke.push(...St.errors),dt=dt||St.valid,St.valid&&Ln.push(it)}dt?ke.length=Ie:ke.splice(Ie,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:He,error:"Instance does not match any subschemas."})}if(x!==void 0){let He=`${a}/allOf`,Ie=ke.length,dt=!0;for(let Me=0;Me<x.length;Me++){let Ue=x[Me],it=Object.create(l),St=Yo(t,Ue,n,r,o,p===!0?i:null,s,`${He}/${Me}`,it);ke.push(...St.errors),dt=dt&&St.valid,St.valid&&Ln.push(it)}dt?ke.length=Ie:ke.splice(Ie,0,{instanceLocation:s,keyword:"allOf",keywordLocation:He,error:"Instance does not match every subschema."})}if(b!==void 0){let He=`${a}/oneOf`,Ie=ke.length,dt=b.filter((Me,Ue)=>{let it=Object.create(l),St=Yo(t,Me,n,r,o,p===!0?i:null,s,`${He}/${Ue}`,it);return ke.push(...St.errors),St.valid&&Ln.push(it),St.valid}).length;dt===1?ke.length=Ie:ke.splice(Ie,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:He,error:`Instance does not match exactly one subschema (${dt} matches).`})}if((u==="object"||u==="array")&&Object.assign(l,...Ln),_!==void 0){let He=`${a}/if`;if(Yo(t,_,n,r,o,i,s,He,l).valid){if(T!==void 0){let dt=Yo(t,T,n,r,o,i,s,`${a}/then`,l);dt.valid||ke.push({instanceLocation:s,keyword:"if",keywordLocation:He,error:'Instance does not match "then" schema.'},...dt.errors)}}else if(S!==void 0){let dt=Yo(t,S,n,r,o,i,s,`${a}/else`,l);dt.valid||ke.push({instanceLocation:s,keyword:"if",keywordLocation:He,error:'Instance does not match "else" schema.'},...dt.errors)}}if(u==="object"){if(y!==void 0)for(let Me of y)Me in t||ke.push({instanceLocation:s,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${Me}".`});let He=Object.keys(t);if(B!==void 0&&He.length<B&&ke.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${B} properties.`}),W!==void 0&&He.length>W&&ke.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${W} properties.`}),F!==void 0){let Me=`${a}/propertyNames`;for(let Ue in t){let it=`${s}/${zd(Ue)}`,St=Yo(Ue,F,n,r,o,i,it,Me);St.valid||ke.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:Me,error:`Property name "${Ue}" does not
`)}var iFe=C(()=>{});function sFe(t){return Array.isArray(t)?t:typeof t=="string"?t===""?[]:[{type:"text",text:t}]:t==null?[]:[t]}function zc(t,e){if(typeof t=="string")return t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.length===0?t:Array.isArray(e)&&e.some(n=>tc(n))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e];if(Array.isArray(e)){let n=sFe(t);return ZT(n,e)??[...n,...e]}else return e===""?t:Array.isArray(t)&&t.some(n=>tc(n))?[...t,{type:"file",source_type:"text",text:e}]:[...sFe(t),{type:"text",text:e}]}function _le(t,e){return t==="error"||e==="error"?"error":"success"}function wPt(t,e){function n(r,o){if(typeof r!="object"||r===null||r===void 0)return r;if(o>=e)return Array.isArray(r)?"[Array]":"[Object]";if(Array.isArray(r))return r.map(s=>n(s,o+1));let i={};for(let s of Object.keys(r))i[s]=n(r[s],o+1);return i}return JSON.stringify(n(t,0),null,2)}function Ii(t,e,n){let r=n?.ignoreKeys??dFe;if(t==null&&e==null)return;if(t==null||e==null)return t??e;let o={...t};for(let[i,s]of Object.entries(e))if(o[i]==null)o[i]=s;else{if(s==null)continue;if(typeof o[i]!=typeof s||Array.isArray(o[i])!==Array.isArray(s))throw new Error(`field[${i}] already exists in the message chunk, but with a different type.`);if(typeof o[i]=="string"){if(i==="type")continue;if(["id","name","output_version","model_provider"].includes(i))s&&(o[i]=s);else{if(r.includes(i))continue;o[i]+=s}}else if(typeof o[i]=="number"){if(r.includes(i))continue;o[i]=o[i]+s}else if(typeof o[i]=="object"&&!Array.isArray(o[i]))o[i]=Ii(o[i],s,n);else if(Array.isArray(o[i]))o[i]=ZT(o[i],s,n);else{if(o[i]===s)continue;console.warn(`field[${i}] already exists in this message chunk and value has unsupported type.`)}}return o}function vPt(t){return typeof t=="number"||typeof t=="string"}function aFe(t){return typeof t!="object"||t===null||!("index"in t)?!1:vPt(t.index)}function lFe(t){if(typeof t!="object"||t===null||!("id"in t))return!1;let e=t.id;return e!=null&&e!==""}function cFe(t){return t.endsWith("_delta")?t.slice(0,-6):t}function xPt(t,e){return typeof t!="object"||t===null||typeof e!="object"||e===null||!("type"in t)||!("type"in e)?!1:typeof t.type=="string"&&typeof e.type=="string"&&cFe(t.type)!==cFe(e.type)}function bPt(t,e){let n=aFe(e),r=lFe(e);return!n&&!r?-1:t.findIndex(o=>{let i=aFe(o),s=lFe(o);return n&&i?o.index!==e.index||xPt(o,e)?!1:s&&r?o.id===e.id:!0:!n&&!i&&r&&s?o.id===e.id:!1})}function ZT(t,e,n){if(!(t==null&&e==null)){if(t==null||e==null)return t||e;{let r=[...t];for(let o of e){let i=bPt(r,o);if(i!==-1)r[i]=Ii(r[i],o,n);else{if(typeof o=="object"&&o!==null&&"text"in o&&o.text==="")continue;r.push(o)}}return r}}}function Sle(t,e,n){if(!(t==null&&e==null)){if(t==null||e==null)return t??e;if(typeof t!=typeof e)throw new Error(`Cannot merge objects of different types.
Left ${typeof t}
Right ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return ZT(t,e,n);if(typeof t=="object"&&typeof e=="object")return Ii(t,e,n);if(t===e)return t;throw new Error(`Can not merge objects of different types.
Left ${t}
Right ${e}`)}}function Tle(t){return typeof t.role=="string"}function np(t){return typeof t?._getType=="function"}function O3(t){return ju.isInstance(t)}var Cle,uFe,Vs,dFe,ju,nc=C(()=>{Rb();C2();vle();xle();ble();gle();iFe();Cle=Symbol.for("langchain.message");Vs=class extends zu{constructor(e){let n=typeof e=="string"||Array.isArray(e)?{content:e}:e;n.additional_kwargs||(n.additional_kwargs={}),n.response_metadata||(n.response_metadata={});super(n);I(this,"lc_namespace",["langchain_core","messages"]);I(this,"lc_serializable",!0);I(this,uFe,!0);I(this,"id");I(this,"name");I(this,"content");I(this,"additional_kwargs");I(this,"response_metadata");this.name=n.name,n.content===void 0&&n.contentBlocks!==void 0?(this.content=n.contentBlocks,this.response_metadata={output_version:"v1",...n.response_metadata}):n.content!==void 0?(this.content=n.content??[],this.response_metadata=n.response_metadata):(this.content=[],this.response_metadata=n.response_metadata),this.additional_kwargs=n.additional_kwargs,this.id=n.id}get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}_getType(){return this.type}getType(){return this._getType()}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e=="string"?e:e.type==="text"?e.text:"").join(""):""}get contentBlocks(){let e=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[Q$e,N3,J$e].reduce((n,r)=>r(n),e)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(e){return typeof e=="object"&&e!==null&&Cle in e&&e[Cle]===!0&&hle(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[(uFe=Cle,Symbol.toStringTag)](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;let n=wPt(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${n}`}toFormattedString(e="pretty"){return oFe(this,e)}},dFe=["index","created","timestamp"];ju=class fFe extends Vs{static isInstance(e){if(!super.isInstance(e))return!1;let n=Object.getPrototypeOf(e);for(;n!==null;){if(n===fFe.prototype)return!0;n=Object.getPrototypeOf(n)}return!1}}});function Ile(t,e){return Ii(t,e)??{}}function pFe(t,e){let n={};return(t?.audio!==void 0||e?.audio!==void 0)&&(n.audio=(t?.audio??0)+(e?.audio??0)),(t?.image!==void 0||e?.image!==void 0)&&(n.image=(t?.image??0)+(e?.image??0)),(t?.video!==void 0||e?.video!==void 0)&&(n.video=(t?.video??0)+(e?.video??0)),(t?.document!==void 0||e?.document!==void 0)&&(n.document=(t?.document??0)+(e?.document??0)),(t?.text!==void 0||e?.text!==void 0)&&(n.text=(t?.text??0)+(e?.text??0)),n}function CPt(t,e){let n={...pFe(t,e)};return(t?.cache_read!==void 0||e?.cache_read!==void 0)&&(n.cache_read=(t?.cache_read??0)+(e?.cache_read??0)),(t?.cache_creation!==void 0||e?.cache_creation!==void 0)&&(n.cache_creation=(t?.cache_creation??0)+(e?.cache_creation??0)),n}function _Pt(t,e){let n={...pFe(t,e)};return(t?.reasoning!==void 0||e?.reasoning!==void 0)&&(n.reasoning=(t?.reasoning??0)+(e?.reasoning??0)),n}function _2(t,e){return{input_tokens:(t?.input_tokens??0)+(e?.input_tokens??0),output_tokens:(t?.output_tokens??0)+(e?.output_tokens??0),total_tokens:(t?.total_tokens??0)+(e?.total_tokens??0),input_token_details:CPt(t?.input_token_details,e?.input_token_details),output_token_details:_Pt(t?.output_token_details,e?.output_token_details)}}var R3=C(()=>{nc()});function Ple(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}function Ele(t){let e=[],n=[];for(let r of t)if(r.function){let o=r.function.name;try{let i=JSON.parse(r.function.arguments);e.push({name:o||"",args:i||{},id:r.id})}catch{n.push({name:o,args:r.function.arguments,id:r.id,error:"Malformed args."})}}else continue;return[e,n]}function Ale(t){return typeof t=="object"&&t!==null&&"getType"in
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
`,t}var Nle,jFe,Ole,VFe,JT=C(()=>{$n();zFe();Nle=BFe.sub("error"),jFe=class extends Nle.brand(Error){constructor(e){super(e);I(this,"name","LangChainError");Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},Ole=class extends Nle.brand(jFe,"model-abort"){constructor(e,n){super(e);I(this,"name","ModelAbortError");I(this,"partialOutput");this.partialOutput=n}},VFe=class WFe extends Nle.brand(jFe,"context-overflow"){constructor(n){super(n??"Input exceeded the model's context window.");I(this,"name","ContextOverflowError");I(this,"cause")}static fromError(n){let r=new WFe(n.message);return r.cause=n,r}}});function Db(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="tool_call")}function HFe(t){return!!(t&&typeof t=="object"&&"toolCall"in t&&t.toolCall!=null&&typeof t.toolCall=="object"&&"id"in t.toolCall&&typeof t.toolCall.id=="string")}var S2,L3=C(()=>{S2=class extends Error{constructor(e,n){super(e);I(this,"output");this.output=n}}});function jk(t,e=Vk){t=t.trim();let n=t.indexOf("```");if(n===-1)return e(t);let r=t.substring(n+3);r.startsWith(`json
`)?r=r.substring(5):r.startsWith("json")?r=r.substring(4):r.startsWith(`
`)&&(r=r.substring(1));let o=r.indexOf("```"),i=r;return o!==-1&&(i=r.substring(0,o)),e(i.trim())}function PPt(t){try{return JSON.parse(t)}catch{}let e=t.trim();if(e.length===0)throw new Error("Unexpected end of JSON input");let n=0;function r(){for(;n<e.length&&/\s/.test(e[n]);)n+=1}function o(){if(e[n]!=='"')throw new Error(`Expected '"' at position ${n}, got '${e[n]}'`);n+=1;let u="",d=!1;for(;n<e.length;){let f=e[n];if(d){if(f==="n")u+=`
`;else if(f==="t")u+=" ";else if(f==="r")u+="\r";else if(f==="\\")u+="\\";else if(f==='"')u+='"';else if(f==="b")u+="\b";else if(f==="f")u+="\f";else if(f==="/")u+="/";else if(f==="u"){let p=e.substring(n+1,n+5);if(/^[0-9A-Fa-f]{0,4}$/.test(p))p.length===4?u+=String.fromCharCode(Number.parseInt(p,16)):u+=`u${p}`,n+=p.length;else throw new Error(`Invalid unicode escape sequence '\\u${p}' at position ${n}`)}else throw new Error(`Invalid escape sequence '\\${f}' at position ${n}`);d=!1}else if(f==="\\")d=!0;else{if(f==='"')return n+=1,u;u+=f}n+=1}return d&&(u+="\\"),u}function i(){let u=n,d="";if(e[n]==="-"&&(d+="-",n+=1),n<e.length&&e[n]==="0"&&(d+="0",n+=1,e[n]>="0"&&e[n]<="9"))throw new Error(`Invalid number at position ${u}`);if(n<e.length&&e[n]>="1"&&e[n]<="9")for(;n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(n<e.length&&e[n]===".")for(d+=".",n+=1;n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(n<e.length&&(e[n]==="e"||e[n]==="E"))for(d+=e[n],n+=1,n<e.length&&(e[n]==="+"||e[n]==="-")&&(d+=e[n],n+=1);n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(d==="-")return-0;let f=Number.parseFloat(d);if(Number.isNaN(f))throw n=u,new Error(`Invalid number '${d}' at position ${u}`);return f}function s(){if(r(),n>=e.length)throw new Error(`Unexpected end of input at position ${n}`);let u=e[n];if(u==="{")return l();if(u==="[")return a();if(u==='"')return o();if("null".startsWith(e.substring(n,n+4)))return n+=Math.min(4,e.length-n),null;if("true".startsWith(e.substring(n,n+4)))return n+=Math.min(4,e.length-n),!0;if("false".startsWith(e.substring(n,n+5)))return n+=Math.min(5,e.length-n),!1;if(u==="-"||u>="0"&&u<="9")return i();throw new Error(`Unexpected character '${u}' at position ${n}`)}function a(){if(e[n]!=="[")throw new Error(`Expected '[' at position ${n}, got '${e[n]}'`);let u=[];if(n+=1,r(),n>=e.length)return u;if(e[n]==="]")return n+=1,u;for(;n<e.length;){if(r(),n>=e.length||(u.push(s()),r(),n>=e.length))return u;if(e[n]==="]")return n+=1,u;if(e[n]===","){n+=1;continue}throw new Error(`Expected ',' or ']' at position ${n}, got '${e[n]}'`)}return u}function l(){if(e[n]!=="{")throw new Error(`Expected '{' at position ${n}, got '${e[n]}'`);let u={};if(n+=1,r(),n>=e.length)return u;if(e[n]==="}")return n+=1,u;for(;n<e.length;){if(r(),n>=e.length)return u;let d=o();if(r(),n>=e.length)return u;if(e[n]!==":")throw new Error(`Expected ':' at position ${n}, got '${e[n]}'`);if(n+=1,r(),n>=e.length||(u[d]=s(),r(),n>=e.length))return u;if(e[n]==="}")return n+=1,u;if(e[n]===","){n+=1;continue}throw new Error(`Expected ',' or '}' at position ${n}, got '${e[n]}'`)}return u}let c=s();if(r(),n<e.length)throw new Error(`Unexpected character '${e[n]}' at position ${n}`);return c}function Vk(t){try{return typeof t>"u"?null:PPt(t)}catch{return null}}var Wk=C(()=>{});var rc,$b,T2=C(()=>{nc();rc=class KFe extends Vs{constructor(n,r){(typeof n=="string"||Array.isArray(n))&&(n={content:n,role:r});super(n);I(this,"type","generic");I(this,"role");this.role=n.role}static lc_name(){return"ChatMessage"}static _chatMessageClass(){return KFe}static isInstance(n){return super.isInstance(n)&&n.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},$b=class extends ju{constructor(e,n){(typeof e=="string"||Array.isArray(e))&&(e={content:e,role:n});super(e);I(this,"type","generic");I(this,"role");this.role=e.role}static lc_name(){return"ChatMessageChunk"}concat(e){let n=this.constructor;return new n({content:zc(this.content,e.content),additional_kwargs:Ii(this.additional_kwargs,e.additional_kwargs),response_metadata:Ii(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}}});var Fb,D3=C(()=>{nc();Fb=class extends ju{constructor(){super(...arguments);I(this,"type","function")}static lc_name(){return"FunctionMessageChunk"}concat(e){let n=this.constructor;return new n({content:zc(this.content,e.content),additional_kwargs:Ii(this.additional_kwargs,e.additiona
Received: ${JSON.stringify(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Lm(t){if(typeof t=="string")return new Zo(t);if(np(t))return t;if(Array.isArray(t)){let[e,n]=t;return Rle({type:e,content:n})}else if(Tle(t)){let{role:e,...n}=t;return Rle({...n,type:e})}else return Rle(t)}function kPt(t){if(typeof t=="string")return t;switch(t.type){case"text":return t.text??"";case"text-plain":return t.text??"[text-plain file]";case"image":case"image_url":return"[image]";case"audio":case"input_audio":return"[audio]";case"video":return"[video]";case"file":return"[file]";case"reasoning":case"tool_call":case"tool_call_chunk":case"invalid_tool_call":case"server_tool_call":case"server_tool_call_chunk":case"server_tool_call_result":case"non_standard":return"";default:return t.type?`[${t.type}]`:""}}function ui(t,e="Human",n="AI"){let r=[];for(let o of t){let i;if(o.type==="human")i=e;else if(o.type==="ai")i=n;else if(o.type==="system")i="System";else if(o.type==="tool")i="Tool";else if(o.type==="generic")i=o.role;else throw new Error(`Got unsupported message type: ${o.type}`);let s=o.name?`${o.name}, `:"",a=typeof o.content=="string"?o.content:Array.isArray(o.content)?o.content.map(kPt).filter(Boolean).join(""):"",l=`${i}: ${s}${a}`;if(o.type==="ai"){let c=o;c.tool_calls&&c.tool_calls.length>0?l+=JSON.stringify(c.tool_calls):c.additional_kwargs&&"function_call"in c.additional_kwargs&&(l+=JSON.stringify(c.additional_kwargs.function_call))}r.push(l)}return r.join(`
`)}function B3(t){let e=t._getType();if(e==="human")return new Ub({...t});if(e==="ai"){let n={...t};return"tool_calls"in n&&(n={...n,tool_call_chunks:n.tool_calls?.map(r=>({...r,type:"tool_call_chunk",index:void 0,args:JSON.stringify(r.args)}))}),new Yt({...n})}else{if(e==="system")return new Sg({...t});if(e==="function")return new Fb({...t});if(rc.isInstance(t))return new $b({...t});throw new Error("Unknown message type.")}}function Dle(t){let e=t.reduce((o,i)=>{let s=o.findIndex(([a])=>"id"in i&&i.id&&"index"in i&&i.index!==void 0?i.id===a.id&&i.index===a.index:"id"in i&&i.id?i.id===a.id:"index"in i&&i.index!==void 0?i.index===a.index:!1);return s!==-1?o[s].push(i):o.push([i]),o},[]),n=[],r=[];for(let o of e){let i=null,s=o[0]?.name??"",a=o.map(u=>u.args||"").join("").trim(),l=a.length?a:"{}",c=o[0]?.id;try{if(i=Vk(l),!c||i===null||typeof i!="object"||Array.isArray(i))throw new Error("Malformed tool call chunk args.");n.push({name:s,args:i,id:c,type:"tool_call"})}catch{r.push({name:s,args:l,id:c,error:"Malformed args.",type:"invalid_tool_call"})}}return{tool_call_chunks:t,tool_calls:n,invalid_tool_calls:r}}var Lle,Dm=C(()=>{JT();L3();Wk();nc();zk();Wu();T2();D3();Bb();F3();I2();Lle=t=>t()});function rp(t){return t._getType()==="ai"}function z3(t){return t._getType()==="ai"}var kn,Yt,Wu=C(()=>{nc();FFe();R3();zk();Dm();kn=class extends Vs{constructor(e){let n;if(typeof e=="string"||Array.isArray(e))n={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{n=e;let r=n.additional_kwargs?.tool_calls,o=n.tool_calls;r!=null&&r.length>0&&(o===void 0||o.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(r!=null&&o===void 0){let[i,s]=Ele(r);n.tool_calls=i??[],n.invalid_tool_calls=s??[]}else n.tool_calls=n.tool_calls??[],n.invalid_tool_calls=n.invalid_tool_calls??[]}catch{n.tool_calls=[],n.invalid_tool_calls=[]}if(n.response_metadata!==void 0&&"output_version"in n.response_metadata&&n.response_metadata.output_version==="v1"&&(n.contentBlocks=n.content,n.content=void 0),n.contentBlocks!==void 0){if(n.tool_calls){let s=n.tool_calls.filter(a=>!n.contentBlocks?.some(l=>l.type==="tool_call"&&l.id===a.id&&l.name===a.name));n.contentBlocks.push(...s.map(a=>({type:"tool_call",id:a.id,name:a.name,args:a.args})))}let i=n.contentBlocks.filter(s=>s.type==="tool_call").filter(s=>!n.tool_calls?.some(a=>a.id===s.id&&a.name===s.name));i.length>0&&(n.tool_calls=[...n.tool_calls??[],...i.map(s=>({type:"tool_call",id:s.id,name:s.name,args:s.args}))])}}super(n);I(this,"type","ai");I(this,"tool_calls",[]);I(this,"invalid_tool_calls",[]);I(this,"usage_metadata");typeof n!="string"&&(this.tool_calls=n.tool_calls??this.tool_calls,this.invalid_tool_calls=n.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=n.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",usage_metadata:"usage_metadata"}}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let n=Mle(this.response_metadata.model_provider);if(n)return n.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls){let n=this.tool_calls.filter(r=>!e.some(o=>o.id===r.id&&o.name===r.name));e.push(...n.map(r=>({type:"tool_call",id:r.id,name:r.name,args:r.args})))}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}};Yt=class extends ju{constructor(e){let n;if(typeof e=="string"||Array.isArray(e))n={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0||e.tool_call_chunks.length===0)n={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0};else{let r=Dle(e.tool_call_chunks??[]);n={...e,tool_call_chunks:r.tool_call_chunks,tool_calls:r.tool_calls,invalid_tool_calls:r.invalid_tool_calls,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(n);I(this,"type","ai");I(this,"tool_calls",[]);I(this,"invalid_tool_calls",[]);I(this,"tool_call_chunks",[]);I(this,"usage_metadata");this.tool_call_chunks=n.tool_call_chunks??this.tool_call_chunks,this.tool_calls=n.tool_calls??this.tool_calls,this.invalid_tool_calls=n.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=n.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks",usage_metadata:"usage_metadata"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let n=Mle(this.response_metadata.model_provider);if(n)return n.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){let n=this.content.filter(r=>r.type==="tool_call").map(r=>r.id);for(let r of this.tool_calls)r.id&&!n.includes(r.id)&&e.push({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})}return e}get _printableFields(){return{...s
Context: ${e}`:""}`),AK("[Unserializable]");rs("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
Context: ${e}`:""}`),typeof o>"u"&&(o=JMt()),lue(t,"",0,[],void 0,0,o);let s;try{eM.length===0?s=JSON.stringify(t,n,r):s=JSON.stringify(t,QMt(n),r)}catch{return AK("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;kK.length!==0;){let a=kK.pop();a.length===4?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return AK(s)}}function aue(t,e,n,r){var o=Object.getOwnPropertyDescriptor(r,n);o.get!==void 0?o.configurable?(Object.defineProperty(r,n,{value:t}),kK.push([r,n,e,o])):eM.push([e,n,t]):(r[n]=t,kK.push([r,n,e]))}function lue(t,e,n,r,o,i,s){i+=1;var a;if(typeof t=="object"&&t!==null){for(a=0;a<r.length;a++)if(r[a]===t){aue(YMt,t,e,o);return}if(typeof s.depthLimit<"u"&&i>s.depthLimit){aue(Dze,t,e,o);return}if(typeof s.edgesLimit<"u"&&n+1>s.edgesLimit){aue(Dze,t,e,o);return}if(r.push(t),Array.isArray(t))for(a=0;a<t.length;a++)lue(t[a],a,a,r,t,i,s);else{t=$ze(t);var l=Object.keys(t);for(a=0;a<l.length;a++){var c=l[a];lue(t[c],c,a,r,t,i,s)}}r.pop()}}function QMt(t){return t=typeof t<"u"?t:function(e,n){return n},function(e,n){if(eM.length>0)for(var r=0;r<eM.length;r++){var o=eM[r];if(o[1]===e&&o[0]===n){n=o[2],eM.splice(r,1);break}}return t.call(this,e,n)}}var Dze,YMt,kK,eM,ZMt,Fze=C(()=>{Mw();Dze="[...]",YMt={result:"[Circular]"},kK=[],eM=[],ZMt=new TextEncoder});function Uze(t,e,n){if(n)return t;let r=sK(),o=e??gce(),i=t.extra??{},s=i.metadata;return t.extra={...i,runtime:{...r,...i?.runtime},metadata:{...o,...o.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??o.revision_id}:{},...s}},t}async function nNt(t){let e=[];for await(let n of t)e.push(n);return e}function MK(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}function Bze(t){return typeof t=="number"?Number(t.toFixed(4)):t}function jze(t){return"dataset_id"in t||"dataset_name"in t}var eNt,tNt,rNt,oNt,Vze,iNt,sNt,zze,cue,rI,dce=C(()=>{q3();EUe();Sce();jUe();VUe();Mw();iK();tK();G3();Oze();sue();uce();oce();Fze();eNt=t=>{let e=t?.toString()??rs("TRACING_SAMPLING_RATE");if(e===void 0)return;let n=parseFloat(e);if(n<0||n>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${n}`);return n},tNt=t=>{let n=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return n==="localhost"||n==="127.0.0.1"||n==="::1"};rNt=async t=>{if(t?.status===429){let e=parseInt(t.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(n=>setTimeout(n,e)),!0}return!1};oNt=24*1024*1024,Vze=1024*1024*1024,iNt=1e4,sNt=100,zze="https://api.smith.langchain.com",cue=class{constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??Vze}peek(){return this.items[0]}push(e){let n,r=new Promise(i=>{n=i}),o=Hu(e.item,`Serializing run with id: ${e.item.id}`).length;return this.sizeBytes+o>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${o} bytes.`),n(),r):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:n,itemPromise:r,size:o}),this.sizeBytes+=o,r)}pop({upToSizeBytes:e,upToSize:n}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");let r=[],o=0;for(;o+(this.peek()?.size??0)<e&&this.items.length>0&&r.length<n;){let i=this.items.shift();i&&(r.push(i),o+=i.size,this.sizeBytes-=i.size)}if(r.length===0&&this.items.length>0){let i=this.items.shift();r.push(i),o+=i.size,this.sizeBytes-=i.size}return[r.map(i=>({action:i.action,item:i.payload,otelContext:i.otelContext,apiKey:i.apiKey,apiUrl:i.apiUrl,size:i.size})),()=>r.forEach(i=>i.itemPromiseResolve())]}},rI=class t{get _fetch(){return this.fetch
=== LangSmith Server Configuration ===
`+JSON.stringify(n,null,2)+`
`),n}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let e=await this._getBatchSizeLimitBytes(),n=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:n})}_cloneCurrentOTELContext(){let e=lK(),n=IUe();if(this.langSmithToOTELTranslator!==void 0){let r=e.getActiveSpan();if(r)return e.setSpan(n.active(),r)}}async createRun(e,n){if(!this._filterForSampling([e]).length)return;let r={...this.headers,"Content-Type":"application/json"},o=e.project_name;delete e.project_name;let i=await this.prepareRunCreateOrUpdateInputs({session_name:o,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){let l=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:i,otelContext:l,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}let s=Uze(i,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);n?.apiKey!==void 0&&(r["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(r["x-tenant-id"]=n.workspaceId);let a=Hu(s,`Creating run with id: ${s.id}`);await this.caller.call(async()=>{let l=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await zt(l,"create run",!0),l})}async batchIngestRuns({runCreates:e,runUpdates:n},r){if(e===void 0&&n===void 0)return;let o=await Promise.all(e?.map(l=>this.prepareRunCreateOrUpdateInputs(l))??[]),i=await Promise.all(n?.map(l=>this.prepareRunCreateOrUpdateInputs(l))??[]);if(o.length>0&&i.length>0){let l=o.reduce((u,d)=>(d.id&&(u[d.id]=d),u),{}),c=[];for(let u of i)u.id!==void 0&&l[u.id]?l[u.id]={...l[u.id],...u}:c.push(u);o=Object.values(l),i=c}let s={post:o,patch:i};if(!s.post.length&&!s.patch.length)return;let a={post:[],patch:[]};for(let l of["post","patch"]){let c=l,u=s[c].reverse(),d=u.pop();for(;d!==void 0;)a[c].push(d),d=u.pop()}if(a.post.length>0||a.patch.length>0){let l=a.post.map(c=>c.id).concat(a.patch.map(c=>c.id)).join(",");await this._postBatchIngestRuns(Hu(a,`Ingesting runs with ids: ${l}`),r)}}async _postBatchIngestRuns(e,n){let r={...this.headers,"Content-Type":"application/json",Accept:"application/json"};n?.apiKey!==void 0&&(r["x-api-key"]=n.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{let o=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await zt(o,"batch create run",!0),o})}async multipartIngestRuns({runCreates:e,runUpdates:n},r){if(e===void 0&&n===void 0)return;let o={},i=[];for(let d of e??[]){let f=await this.prepareRunCreateOrUpdateInputs(d);f.id!==void 0&&f.attachments!==void 0&&(o[f.id]=f.attachments),delete f.attachments,i.push(f)}let s=[];for(let d of n??[])s.push(await this.prepareRunCreateOrUpdateInputs(d));if(i.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(s.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(i.length>0&&s.length>0){let d=i.reduce((p,m)=>(m.id&&(p[m.id]=m),p),{}),f=[];for(let p of s)p.id!==void 0&&d[p.id]?d[p.id]={...d[p.id],...p}:f.push(p);i=Object.values(d),s=f}if(i.length===0&&s.length===0)return;let c=[],u=[];for(let[d,f]of[["post",i],["patch",s
`])),r.push(new Blob([`Content-Disposition: form-data; name="${s.name}"\r
`,`Content-Type: ${s.payload.type}\r
\r
`])),r.push(s.payload),r.push(new Blob([`\r
`]));return r.push(new Blob([`--${n}--\r
`])),await new Blob(r).arrayBuffer()}async _createMultipartStream(e,n){let r=new TextEncoder;return new ReadableStream({async start(i){let s=async a=>{typeof a=="string"?i.enqueue(r.encode(a)):i.enqueue(a)};for(let a of e){await s(`--${n}\r
`),await s(`Content-Disposition: form-data; name="${a.name}"\r
`),await s(`Content-Type: ${a.payload.type}\r
\r
`);let c=a.payload.stream().getReader();try{let u;for(;!(u=await c.read()).done;)i.enqueue(u.value)}finally{c.releaseLock()}await s(`\r
`)}await s(`--${n}--\r
`),i.close()}})}async _sendMultipartRequest(e,n,r){let o="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),i=()=>this._createNodeFetchBody(e,o),s=()=>this._createMultipartStream(e,o),a=async l=>this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{let c=await l(),u={...this.headers,"Content-Type":`multipart/form-data; boundary=${o}`};r?.apiKey!==void 0&&(u["x-api-key"]=r.apiKey);let d=c;r?.useGzip&&typeof c=="object"&&"pipeThrough"in c&&(d=c.pipeThrough(new CompressionStream("gzip")),u["Content-Encoding"]="gzip");let f=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:u,body:d,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(f,"Failed to send multipart request",!0),f});try{let l,c=!1;oUe()&&!this.multipartStreamingDisabled&&hce()!=="bun"?(c=!0,l=await a(s)):l=await a(i),(!this.multipartStreamingDisabled||c)&&l.status===422&&(r?.apiUrl??this.apiUrl)!==zze&&(console.warn(`Streaming multipart upload to ${r?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${n}".`),this.multipartStreamingDisabled=!0,l=await a(i))}catch(l){if(iue(l))throw l;console.warn(`${l.message.trim()}
Context: ${n}`)}}async updateRun(e,n,r){qn(e),n.inputs&&(n.inputs=await this.processInputs(n.inputs)),n.outputs&&(n.outputs=await this.processOutputs(n.outputs));let o={...n,id:e};if(!this._filterForSampling([o],!0).length)return;if(this.autoBatchTracing&&o.trace_id!==void 0&&o.dotted_order!==void 0){let a=this._cloneCurrentOTELContext();if(n.end_time!==void 0&&o.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:o,otelContext:a,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:o,otelContext:a,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}let i={...this.headers,"Content-Type":"application/json"};r?.apiKey!==void 0&&(i["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(i["x-tenant-id"]=r.workspaceId);let s=Hu(n,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{let a=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await zt(a,"update run",!0),a})}async readRun(e,{loadChildRuns:n}={loadChildRuns:!1}){qn(e);let r=await this._get(`/runs/${e}`);return n&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:n,projectOpts:r}){if(n!==void 0){let o;n.session_id?o=n.session_id:r?.projectName?o=(await this.readProject({projectName:r?.projectName})).id:r?.projectId?o=r?.projectId:o=(await this.readProject({projectName:rs("PROJECT")||"default"})).id;let i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${o}/r/${n.id}?poll=true`}else if(e!==void 0){let o=await this.readRun(e);if(!o.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${o.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){let n=await nNt(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),r={},o={};n.sort((i,s)=>(i?.dotted_order??"").localeCompare(s?.dotted_order??""));for(let i of n){if(i.parent_run_id===null||i.parent_run_id===void 0)throw new Error(`Child run ${i.id} has no parent`);i.dotted_order?.startsWith(e.dotted_order??"")&&i.id!==e.id&&(i.parent_run_id in r||(r[i.parent_run_id]=[]),r[i.parent_run_id].push(i),o[i.id]=i)}e.child_runs=r[e.id]||[];for(let i in r)i!==e.id&&(o[i].child_runs=r[i]);return e}async*listRuns(e){let{projectId:n,projectName:r,parentRunId:o,traceId:i,referenceExampleId:s,startTime:a,executionOrder:l,isRoot:c,runType:u,error:d,id:f,query:p,filter:m,traceFilter:h,treeFilter:g,limit:y,select:w,order:v}=e,x=[];if(n&&(x=Array.isArray(n)?n:[n]),r){let S=Array.isArray(r)?r:[r],P=await Promise.all(S.map(A=>this.readProject({projectName:A}).then(O=>O.id)));x.push(...P)}let b=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],_={session:x.length?x:null,run_type:u,reference_example:s,query:p,filter:m,trace_filter:h,tree_filter:g,execution_order:l,parent_run:o,start_time:a?a.toISOString():null,error:d,id:f,limit:y,trace:i,select:w||b,is_root:c,order:v};_.select.includes("child_run_ids")&&tI("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let T=0;for await(let S of this._getCursorPaginatedList("/runs/query",_))if(y){if(T>=y)break;if(S.length+T>y){yield*S.slice(0,y-T);break}T+=S.length,yield*S}else yield*S}async*listGroupRuns(e){let{projectId:n,projectName:r,groupBy:o,filter:i,startTime:s,endTime:a,limit:l,offset:c}=e,d={session_id:n||(await this.readProject({projectName:r})).id,group_by:o,filter:i,start_time:s?s.toISOString():null,end_time:a?a.toISOString():null,limit:Number(l)||100},f=Number(c)||0,p="/runs/group",m=`${this.apiUrl}${p}`;for(;;){let h={...d,offset:f},g
Status: ${i.status}
Message: ${Array.isArray(s.detail)?s.detail.join(`
`):"Unspecified error"}`):new Error(`Failed to list shared examples: ${i.status} ${i.statusText}`);return s.map(a=>({...a,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:n=null,metadata:r=null,upsert:o=!1,projectExtra:i=null,referenceDatasetId:s=null}){let a=o?"?upsert=true":"",l=`${this.apiUrl}/sessions${a}`,c=i||{};r&&(c.metadata=r);let u={name:e,extra:c,description:n};s!==null&&(u.reference_dataset_id=s);let d=JSON.stringify(u);return await(await this.caller.call(async()=>{let m=await this._fetch(l,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:d});return await zt(m,"create project"),m})).json()}async updateProject(e,{name:n=null,description:r=null,metadata:o=null,projectExtra:i=null,endTime:s=null}){let a=`${this.apiUrl}/sessions/${e}`,l=i;o&&(l={...l||{},metadata:o});let c=JSON.stringify({name:n,extra:l,description:r,end_time:s?new Date(s).toISOString():null});return await(await this.caller.call(async()=>{let f=await this._fetch(a,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await zt(f,"update project"),f})).json()}async hasProject({projectId:e,projectName:n}){let r="/sessions",o=new URLSearchParams;if(e!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)qn(e),r+=`/${e}`;else if(n!==void 0)o.append("name",n);else throw new Error("Must provide projectName or projectId");let i=await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${r}?${o}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(s,"has project"),s});try{let s=await i.json();return i.ok?Array.isArray(s)?s.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:n,includeStats:r}){let o="/sessions",i=new URLSearchParams;if(e!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)qn(e),o+=`/${e}`;else if(n!==void 0)i.append("name",n);else throw new Error("Must provide projectName or projectId");r!==void 0&&i.append("include_stats",r.toString());let s=await this._get(o,i),a;if(Array.isArray(s)){if(s.length===0)throw new Error(`Project[id=${e}, name=${n}] not found`);a=s[0]}else a=s;return a}async getProjectUrl({projectId:e,projectName:n}){if(e===void 0&&n===void 0)throw new Error("Must provide either projectName or projectId");let r=await this.readProject({projectId:e,projectName:n}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/projects/p/${r.id}`}async getDatasetUrl({datasetId:e,datasetName:n}){if(e===void 0&&n===void 0)throw new Error("Must provide either datasetName or datasetId");let r=await this.readDataset({datasetId:e,datasetName:n}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/datasets/${r.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let n of this._getPaginated("/sessions",e))return this._tenantId=n[0].tenant_id,n[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:n,nameContains:r,referenceDatasetId:o,referenceDatasetName:i,includeStats:s,datasetVersion:a,referenceFree:l,metadata:c}={}){let u=new URLSearchParams;if(e!==void 0)for(let d of e)u.append("id",d);if(n!==void 0&&u.append("name",n),r!==void 0&&u.append("name_contains",r),o!==void 0)u.append("reference_dataset",o);else if(i!==void 0){let d=await this.readDataset({datasetName:i});u.append("reference_dataset",d.id)}s!==void 0&&u.append("include_stats",s.toString()),a!==void 0&&u.append("dataset_version",a),l!==void 0&&u.append("reference_free",l.toString()),c!==void 0&&u.append("metadata",JSON.stringify(c));for await(let d of this._getPaginated("/sessions",u))yield*d}async deleteProject({projectId:e,projectName:n}){let r;if(e===void 0&&n===void 0)throw new Error("Must provide projectNa
`).map(a=>JSON.parse(a))}async*listDatasets({limit:e=100,offset:n=0,datasetIds:r,datasetName:o,datasetNameContains:i,metadata:s}={}){let a="/datasets",l=new URLSearchParams({limit:e.toString(),offset:n.toString()});if(r!==void 0)for(let c of r)l.append("id",c);o!==void 0&&l.append("name",o),i!==void 0&&l.append("name_contains",i),s!==void 0&&l.append("metadata",JSON.stringify(s));for await(let c of this._getPaginated(a,l))yield*c}async updateDataset(e){let{datasetId:n,datasetName:r,...o}=e;if(!n&&!r)throw new Error("Must provide either datasetName or datasetId");let i=n??(await this.readDataset({datasetName:r})).id;qn(i);let s=JSON.stringify(o);return await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await zt(l,"update dataset"),l})).json()}async updateDatasetTag(e){let{datasetId:n,datasetName:r,asOf:o,tag:i}=e;if(!n&&!r)throw new Error("Must provide either datasetName or datasetId");let s=n??(await this.readDataset({datasetName:r})).id;qn(s);let a=JSON.stringify({as_of:typeof o=="string"?o:o.toISOString(),tag:i});await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${s}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await zt(l,"update dataset tags",!0),l})}async deleteDataset({datasetId:e,datasetName:n}){let r="/datasets",o=e;if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(n!==void 0&&(o=(await this.readDataset({datasetName:n})).id),o!==void 0)qn(o),r+=`/${o}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{let i=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(i,`delete ${r}`,!0),i})}async indexDataset({datasetId:e,datasetName:n,tag:r}){let o=e;if(!o&&!n)throw new Error("Must provide either datasetName or datasetId");if(o&&n)throw new Error("Must provide either datasetName or datasetId, not both");o||(o=(await this.readDataset({datasetName:n})).id),qn(o);let s=JSON.stringify({tag:r});await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${o}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await zt(l,"index dataset"),l})).json()}async similarExamples(e,n,r,{filter:o}={}){let i={limit:r,inputs:e};o!==void 0&&(i.filter=o),qn(n);let s=JSON.stringify(i);return(await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${n}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:s});return await zt(c,"fetch similar examples"),c})).json()).examples}async createExample(e,n,r){if(jze(e)&&(n!==void 0||r!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let o=n?r?.datasetId:e.dataset_id,i=n?r?.datasetName:e.dataset_name;if(o===void 0&&i===void 0)throw new Error("Must provide either datasetName or datasetId");if(o!==void 0&&i!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");o===void 0&&(o=(await this.readDataset({datasetName:i})).id);let s=(n?r?.createdAt:e.created_at)||new Date,a;jze(e)?a=e:a={inputs:e,outputs:n,created_at:s?.toISOString(),id:r?.exampleId,metadata:r?.metadata,split:r?.split,source_run_id:r?.sourceRunId,use_source_run_io:r?.useSourceRunIO,use_source_run_attachments:r?.useSourceRunAttachments,attachments:r?.attachments};let l=await this._uploadExamplesMultipart(o,[a]);return await this.readExample(l.example_ids?.[0]??eI())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let w=e,v=w[0].dataset_id,x=w[0].dat
Current tenant: ${r.tenant_handle}
Requested tenant: ${n}`)}async _getLatestCommitHash(e){let r=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(o,"get latest commit hash"),o})).json();if(r.commits.length!==0)return r.commits[0].commit_hash}async _likeOrUnlikePrompt(e,n){let[r,o,i]=Ow(e),s=JSON.stringify({like:n});return(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/likes/${r}/${o}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await zt(l,`${n?"like":"unlike"} prompt`),l})).json()}async _getPromptUrl(e){let[n,r,o]=Ow(e);if(await this._currentTenantIsOwner(n)){let i=await this._getSettings();return o!=="latest"?`${this.getHostUrl()}/prompts/${r}/${o.substring(0,8)}?organizationId=${i.id}`:`${this.getHostUrl()}/prompts/${r}?organizationId=${i.id}`}else return o!=="latest"?`${this.getHostUrl()}/hub/${n}/${r}/${o.substring(0,8)}`:`${this.getHostUrl()}/hub/${n}/${r}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){for await(let n of this._getPaginated(`/commits/${e}/`,new URLSearchParams,r=>r.commits))yield*n}async*listPrompts(e){let n=new URLSearchParams;n.append("sort_field",e?.sortField??"updated_at"),n.append("sort_direction","desc"),n.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&n.append("is_public",e.isPublic.toString()),e?.query&&n.append("query",e.query);for await(let r of this._getPaginated("/repos",n,o=>o.repos))yield*r}async getPrompt(e){let[n,r,o]=Ow(e),s=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/repos/${n}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return a?.status===404?null:(await zt(a,"get prompt"),a)}))?.json();return s?.repo?s.repo:null}async createPrompt(e,n){let r=await this._getSettings();if(n?.isPublic&&!r.tenant_handle)throw new Error(`Cannot create a public prompt without first
creating a LangChain Hub handle.
You can add a handle by creating a public prompt at:
https://smith.langchain.com/prompts`);let[o,i,s]=Ow(e);if(!await this._currentTenantIsOwner(o))throw await this._ownerConflictError("create a prompt",o);let a={repo_handle:i,...n?.description&&{description:n.description},...n?.readme&&{readme:n.readme},...n?.tags&&{tags:n.tags},is_public:!!n?.isPublic},l=JSON.stringify(a),c=await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await zt(d,"create prompt"),d}),{repo:u}=await c.json();return u}async createCommit(e,n,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[o,i,s]=Ow(e),a=r?.parentCommitHash==="latest"||!r?.parentCommitHash?await this._getLatestCommitHash(`${o}/${i}`):r?.parentCommitHash,l={manifest:JSON.parse(JSON.stringify(n)),parent_commit:a},c=JSON.stringify(l),d=await(await this.caller.call(async()=>{let f=await this._fetch(`${this.apiUrl}/commits/${o}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await zt(f,"create commit"),f})).json();return this._getPromptUrl(`${o}/${i}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(e,n=[]){return this._updateExamplesMultipart(e,n)}async _updateExamplesMultipart(e,n=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let r=new FormData;for(let s of n){let a=s.id,l={...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split}},c=Hu(l,`Serializing body for example with id: ${a}`),u=new Blob([c],{type:"application/json"});if(r.append(a,u),s.inputs){let d=Hu(s.inputs,`Serializing inputs for example with id: ${a}`),f=new Blob([d],{type:"application/json"});r.append(`${a}.inputs`,f)}if(s.outputs){let d=Hu(s.outputs,`Serializing outputs whle updating example with id: ${a}`),f=new Blob([d],{type:"application/json"});r.append(`${a}.outputs`,f)}if(s.attachments)for(let[d,f]of Object.entries(s.attachments)){let p,m;Array.isArray(f)?[p,m]=f:(p=f.mimeType,m=f.data);let h=new Blob([m],{type:`${p}; length=${m.byteLength}`});r.append(`${a}.attachment.${d}`,h)}if(s.attachments_operations){let d=Hu(s.attachments_operations,`Serializing attachments while updating example with id: ${a}`),f=new Blob([d],{type:"application/json"});r.append(`${a}.attachments_operations`,f)}}let o=e??n[0]?.dataset_id;return(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${o}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await zt(s,"update examples"),s})).json()}async uploadExamplesMultipart(e,n=[]){return this._uploadExamplesMultipart(e,n)}async _uploadExamplesMultipart(e,n=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let r=new FormData;for(let i of n){let s=(i.id??eI()).toString(),a={created_at:i.created_at,...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split},...i.source_run_id&&{source_run_id:i.source_run_id},...i.use_source_run_io&&{use_source_run_io:i.use_source_run_io},...i.use_source_run_attachments&&{use_source_run_attachments:i.use_source_run_attachments}},l=Hu(a,`Serializing body for uploaded example with id: ${s}`),c=new Blob([l],{type:"application/json"});if(r.append(s,c),i.inputs){let u=Hu(i.inputs,`Serializing inputs for uploaded example with id: ${s}`),d=new Blob([u],{type:"application/json"});r.append(`${s}.inputs`,d)}if(i.outputs){let u=Hu(i.outputs,`Serializing outputs for uploaded example with id: ${s}`),d=new Blob([u],{type:"application/json"});r.append(`${s}.outputs`,d)}if(i.attachme
${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,n){e.child_runs.push(n)}_addRunToRunMap(e){let{dottedOrder:n,microsecondPrecisionDatestring:r}=fue(new Date(e.start_time).getTime(),e.id,e.execution_order),o={...e},i=this.getRunById(o.parent_run_id);if(o.parent_run_id!==void 0?i?(this._addChildRun(i,o),i.child_execution_order=Math.max(i.child_execution_order,o.child_execution_order),o.trace_id=i.trace_id,i.dotted_order!==void 0&&(o.dotted_order=[i.dotted_order,n].join("."),o._serialized_start_time=r)):o.parent_run_id=void 0:(o.trace_id=o.id,o.dotted_order=n,o._serialized_start_time=r),this.usesRunTreeMap){let s=mue(o,i);s!==void 0&&this.runTreeMap.set(o.id,s)}else this.runMap.set(o.id,o);return o}async _endTrace(e){let n=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);n?n.child_execution_order=Math.max(n.child_execution_order,e.child_execution_order):await this.persistRun(e),await this.onRunUpdate?.(e),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){let n=e!==void 0&&this.getRunById(e);return n?n.child_execution_order+1:1}_createRunForLLMStart(e,n,r,o,i,s,a,l){let c=this._getExecutionOrder(o),u=Date.now(),d=a?{...i,metadata:a}:i,f={id:r,name:l??e.id[e.id.length-1],parent_run_id:o,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:n},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:s||[]};return this._addRunToRunMap(f)}async handleLLMStart(e,n,r,o,i,s,a,l){let c=this.getRunById(r)??this._createRunForLLMStart(e,n,r,o,i,s,a,l);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(e,n,r,o,i,s,a,l){let c=this._getExecutionOrder(o),u=Date.now(),d=a?{...i,metadata:a}:i,f={id:r,name:l??e.id[e.id.length-1],parent_run_id:o,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:n},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:s||[]};return this._addRunToRunMap(f)}async handleChatModelStart(e,n,r,o,i,s,a,l){let c=this.getRunById(r)??this._createRunForChatModelStart(e,n,r,o,i,s,a,l);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(e,n,r,o,i){let s=this.getRunById(n);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.outputs=e,s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...i},await this.onLLMEnd?.(s),await this._endTrace(s),s}async handleLLMError(e,n,r,o,i){let s=this.getRunById(n);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(e),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...i},await this.onLLMError?.(s),await this._endTrace(s),s}_createRunForChainStart(e,n,r,o,i,s,a,l,c){let u=this._getExecutionOrder(o),d=Date.now(),f={id:r,name:l??e.id[e.id.length-1],parent_run_id:o,start_time:d,serialized:e,events:[{name:"start",time:new Date(d).toISOString()}],inputs:n,execution_order:u,child_execution_order:u,run_type:a??"chain",child_runs:[],extra:s?{...c,metadata:s}:{...c},tags:i||[]};return this._addRunToRunMap(f)}async handleChainStart(e,n,r,o,i,s,a,l){let c=this.getRunById(r)??this._createRunForChainStart(e,n,r,o,i,s,a,l);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(e,n,r,o,i){let s=this.getRunById(n);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.outputs=pue(e,"output"),s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),i?.inputs!==void 0&&(s.inputs=pue(i.inputs,"input")),await this.onChainEnd?.(s),await this._endTrace(s),s}async handleChainError(e,n,r,o,i){let s=this.getRunById(n);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(e),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),i?.inputs!==void 0&&(s.inputs=pue(i.inputs,"input")),await this.onChainError?.(s),await
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function DK(t){return typeof t=="function"&&"langsmith:traceable"in t}var xue,vue,yNt,bue,wNt,fIn,rje=C(()=>{xue=class{getStore(){}run(e,n){return n()}},vue=Symbol.for("ls:tracing_async_local_storage"),yNt=new xue,bue=class{getInstance(){return globalThis[vue]??yNt}initializeGlobalInstance(e){globalThis[vue]===void 0&&(globalThis[vue]=e)}},wNt=new bue;fIn=Symbol.for("langsmith:traceable:root")});var Cue=C(()=>{rje()});function vNt(t){let e;for(let n of t)for(let r of n)kn.isInstance(r.message)&&r.message.usage_metadata!==void 0&&(e=_2(e,r.message.usage_metadata));return e}function oje(t,e){if(t.tracingMetadata){e.extra??(e.extra={});let n=e.extra.metadata??{},r=!1;for(let[o,i]of Object.entries(t.tracingMetadata))(!Object.prototype.hasOwnProperty.call(n,o)||ije.has(o))&&n[o]!==i&&(n[o]=i,r=!0);r&&(e.extra.metadata=n)}t.tracingTags.length>0&&(e.tags=Array.from(new Set([...e.tags??[],...t.tracingTags])))}var ije,W2,sje=C(()=>{$n();R3();Wu();iI();wue();RK();LK();Cue();ije=new Set(["ls_agent_type"]);W2=class _ue extends Mg{constructor(n={}){super(n);I(this,"name","langchain_tracer");I(this,"projectName");I(this,"exampleId");I(this,"client");I(this,"replicas");I(this,"usesRunTreeMap",!0);I(this,"tracingMetadata");I(this,"tracingTags",[]);this.fields=n;let{exampleId:r,projectName:o,client:i,replicas:s,metadata:a,tags:l}=n;this.projectName=o??N2(),this.replicas=s,this.exampleId=r,this.client=i??yue(),this.tracingMetadata=a?{...a}:void 0,this.tracingTags=l??[];let c=_ue.getTraceableRunTree();c&&this.updateFromRunTree(c)}async persistRun(n){}async onRunCreate(n){oje(this,n),n.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(n.id)?.postRun()}async onRunUpdate(n){oje(this,n);let r=this.getRunTreeWithTracingConfig(n.id);n.extra?.lc_defers_inputs?await r?.postRun():await r?.patchRun()}onLLMEnd(n){let r=n.outputs;if(r?.generations){let o=vNt(r.generations);if(o!==void 0){n.extra=n.extra??{};let i=n.extra.metadata??{};i.usage_metadata=o,n.extra.metadata=i}}}copyWithTracingConfig({metadata:n,tags:r}){let o;if(n===void 0)o=this.tracingMetadata?{...this.tracingMetadata}:void 0;else if(this.tracingMetadata===void 0)o={...n};else{o={...this.tracingMetadata};for(let[a,l]of Object.entries(n))(!Object.prototype.hasOwnProperty.call(o,a)||ije.has(a))&&(o[a]=l)}let i=r?Array.from(new Set([...this.tracingTags,...r])):[...this.tracingTags],s=new _ue({...this.fields,metadata:o,tags:i});return s.runMap=this.runMap,s.runTreeMap=this.runTreeMap,s}getRun(n){return this.runTreeMap.get(n)}updateFromRunTree(n){this.runTreeMap.set(n.id,n);let r=n,o=new Set;for(;r.parent_run&&!(o.has(r.id)||(o.add(r.id),!r.parent_run));)r=r.parent_run;o.clear();let i=[r];for(;i.length>0;){let s=i.shift();!s||o.has(s.id)||(o.add(s.id),this.runTreeMap.set(s.id,s),s.child_runs&&i.push(...s.child_runs))}this.client=n.client??this.client,this.replicas=n.replicas??this.replicas,this.projectName=n.project_name??this.projectName,this.exampleId=n.reference_example_id??this.exampleId,this.fields={...this.fields,client:this.client,replicas:this.replicas,projectName:this.projectName,exampleId:this.exampleId}}getRunTreeWithTracingConfig(n){let r=this.runTreeMap.get(n);if(r)return new Fm({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return nje(!0)}catch{return}}static[Symbol.hasInstance](n){if(typeof n!="object"||n===null)return!1;let r=n;return"name"in r&&r.name==="langchain_tracer"&&"copyWithTracingConfig"in r&&typeof r.copyWithTracingConfig=="function"&&"getRunTreeWithTracingConfig"in r&&typeof r.getRunTreeWithTracingConfig=="function"}}});var lje=Tt((IIn,FK)=>{"use strict";var xNt=kce(),$K=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},aje=(t,e,n)=>new Promise((r,o)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){r(t);return}let i=setTimeout(()=>{if(type
`)}var FNt,_je,KK=C(()=>{FNt=Object.prototype.hasOwnProperty;_je=class extends Error{constructor(t,e,n,r,o){super(bje(t,{name:e,index:n,operation:r,tree:o})),this.name=e,this.index=n,this.operation=r,this.tree=o,Object.setPrototypeOf(this,new.target.prototype),this.message=bje(t,{name:e,index:n,operation:r,tree:o})}}});function qK(t,e){if(e=="")return t;var n={op:"_get",path:e};return uI(t,n),n.value}function uI(t,e,n=!1,r=!0,o=!0,i=0){if(n&&(typeof n=="function"?n(e,0,t,e.path):GK(e,0)),e.path===""){let s={newDocument:t};if(e.op==="add")return s.newDocument=e.value,s;if(e.op==="replace")return s.newDocument=e.value,s.removed=t,s;if(e.op==="move"||e.op==="copy")return s.newDocument=qK(t,e.from),e.op==="move"&&(s.removed=t),s;if(e.op==="test"){if(s.test=G2(t,e.value),s.test===!1)throw new Ui("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return s.newDocument=t,s}else{if(e.op==="remove")return s.removed=t,s.newDocument=null,s;if(e.op==="_get")return e.value=t,s;if(n)throw new Ui("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return s}}else{r||(t=Kd(t));let s=(e.path||"").split("/"),a=t,l=1,c=s.length,u,d,f;for(typeof n=="function"?f=n:f=GK;;){if(d=s[l],d&&d.indexOf("~")!=-1&&(d=Cje(d)),o&&(d=="__proto__"||d=="prototype"&&l>0&&s[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&u===void 0&&(a[d]===void 0?u=s.slice(0,l).join("/"):l==c-1&&(u=e.path),u!==void 0&&f(e,0,t,u)),l++,Array.isArray(a)){if(d==="-")d=a.length;else{if(n&&!HK(d))throw new Ui("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,t);HK(d)&&(d=~~d)}if(l>=c){if(n&&e.op==="add"&&d>a.length)throw new Ui("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);let p=BNt[e.op].call(e,a,d,t);if(p.test===!1)throw new Ui("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return p}}else if(l>=c){let p=oM[e.op].call(e,a,d,t);if(p.test===!1)throw new Ui("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return p}if(a=a[d],n&&l<c&&(!a||typeof a!="object"))throw new Ui("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function dI(t,e,n,r=!0,o=!0){if(n&&!Array.isArray(e))throw new Ui("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(t=Kd(t));let i=new Array(e.length);for(let s=0,a=e.length;s<a;s++)i[s]=uI(t,e[s],n,!0,o,s),t=i[s].newDocument;return i.newDocument=t,i}function zNt(t,e,n){let r=uI(t,e);if(r.test===!1)throw new Ui("Test operation failed","TEST_OPERATION_FAILED",n,e,t);return r.newDocument}function GK(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t))throw new Ui("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,n);if(oM[t.op]){if(typeof t.path!="string")throw new Ui("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,n);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new Ui('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,n);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new Ui("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new Ui("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&jK(t.value))throw new Ui("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,n);if(n){if(t.op=="add"){var o=t.path.split("/").length,i=r.split("/").length;if(o!==i+1&&o!==i)throw new Ui("Cannot perform an
`;return e}function jje(t,e,n){let{firstNode:r,lastNode:o,nodeColors:i,withStyles:s=!0,curveStyle:a="linear",wrapLabelNWords:l=9}=n??{},c=s?`%%{init: {'flowchart': {'curve': '${a}'}}}%%
graph TD;
`:`graph TD;
`;if(s){let m="default",h={[m]:"{0}({1})"};r!==void 0&&(h[r]="{0}([{1}]):::first"),o!==void 0&&(h[o]="{0}([{1}]):::last");for(let[g,y]of Object.entries(t)){let w=y.name.split(":").pop()??"",v=XNt.some(b=>w.startsWith(b)&&w.endsWith(b))?`<p>${w}</p>`:w;Object.keys(y.metadata??{}).length&&(v+=`<hr/><small><em>${Object.entries(y.metadata??{}).map(([b,_])=>`${b} = ${_}`).join(`
`)}</em></small>`);let x=(h[g]??h[m]).replace("{0}",Bue(g)).replace("{1}",v);c+=` ${x}
`}}let u={};for(let m of e){let h=m.source.split(":"),g=m.target.split(":"),y=h.filter((w,v)=>w===g[v]).join(":");u[y]||(u[y]=[]),u[y].push(m)}let d=new Set;function f(m){return[...m].sort((h,g)=>h.split(":").length-g.split(":").length)}function p(m,h){let g=m.length===1&&m[0].source===m[0].target;if(h&&!g){let w=h.split(":").pop();if(d.has(h))throw new Error(`Found duplicate subgraph '${w}' at '${h} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(h),c+=` subgraph ${w}
`}let y=f(Object.keys(u).filter(w=>w.startsWith(`${h}:`)&&w!==h&&w.split(":").length===h.split(":").length+1));for(let w of y)p(u[w],w);for(let w of m){let{source:v,target:x,data:b,conditional:_}=w,T="";if(b!==void 0){let S=b,P=S.split(" ");P.length>l&&(S=Array.from({length:Math.ceil(P.length/l)},(A,O)=>P.slice(O*l,(O+1)*l).join(" ")).join("&nbsp;<br>&nbsp;")),T=_?` -. &nbsp;${S}&nbsp; .-> `:` -- &nbsp;${S}&nbsp; --> `}else T=_?" -.-> ":" --> ";c+=` ${Bue(v)}${T}${Bue(x)};
`}h&&!g&&(c+=` end
`)}p(u[""]??[],"");for(let m in u)!m.includes(":")&&m!==""&&p(u[m],m);return s&&(c+=QNt(i??{})),c}async function Vje(t,e){let n=e?.backgroundColor??"white",r=e?.imageType??"png",o=zje(t);n!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(n)||(n=`!${n}`));let i=`https://mermaid.ink/img/${o}?bgColor=${n}&type=${r}`,s=await fetch(i);if(!s.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${s.status}`,`Status text: ${s.statusText}`].join(`
`));return await s.blob()}var XNt,Wje=C(()=>{QK();XNt=["*","_","`"]});function eOt(t,e){if(t!==void 0&&!Tg(t))return t;if(Q2(e))try{let n=e.getName();return n=n.startsWith("Runnable")?n.slice(8):n,n}catch{return e.getName()}else return e.name??"UnknownSchema"}function tOt(t){return Q2(t.data)?{type:"runnable",data:{id:t.data.lc_id,name:t.data.getName()}}:{type:"schema",data:{...Hr(t.data.schema),title:t.data.name}}}function Hje(t,e=[]){let n=new Set(t.edges.filter(o=>!e.includes(o.source)).map(o=>o.target)),r=[];for(let o of Object.values(t.nodes))!e.includes(o.id)&&!n.has(o.id)&&r.push(o);return r.length===1?r[0]:void 0}function Kje(t,e=[]){let n=new Set(t.edges.filter(o=>!e.includes(o.target)).map(o=>o.source)),r=[];for(let o of Object.values(t.nodes))!e.includes(o.id)&&!n.has(o.id)&&r.push(o);return r.length===1?r[0]:void 0}var zue,Gje=C(()=>{$n();Hk();Ble();E2();QK();Wje();Bu();zue=class qje{constructor(e){I(this,"nodes",{});I(this,"edges",[]);this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){let e={};return Object.values(this.nodes).forEach((n,r)=>{e[n.id]=Tg(n.id)?r:n.id}),{nodes:Object.values(this.nodes).map(n=>({id:e[n.id],...tOt(n)})),edges:this.edges.map(n=>{let r={source:e[n.source],target:e[n.target]};return typeof n.data<"u"&&(r.data=n.data),typeof n.conditional<"u"&&(r.conditional=n.conditional),r})}}addNode(e,n,r){if(n!==void 0&&this.nodes[n]!==void 0)throw new Error(`Node with id ${n} already exists`);let o=n??Ule(),i={id:o,data:e,name:eOt(n,e),metadata:r};return this.nodes[o]=i,i}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(n=>n.source!==e.id&&n.target!==e.id)}addEdge(e,n,r,o){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[n.id]===void 0)throw new Error(`Target node ${n.id} not in graph`);let i={source:e.id,target:n.id,data:r,conditional:o};return this.edges.push(i),i}firstNode(){return Hje(this)}lastNode(){return Kje(this)}extend(e,n=""){let r=n;Object.values(e.nodes).map(l=>l.id).every(Tg)&&(r="");let o=l=>r?`${r}:${l}`:l;Object.entries(e.nodes).forEach(([l,c])=>{this.nodes[o(l)]={...c,id:o(l)}});let i=e.edges.map(l=>({...l,source:o(l.source),target:o(l.target)}));this.edges=[...this.edges,...i];let s=e.firstNode(),a=e.lastNode();return[s?{id:o(s.id),data:s.data}:void 0,a?{id:o(a.id),data:a.data}:void 0]}trimFirstNode(){let e=this.firstNode();e&&Hje(this,[e.id])&&this.removeNode(e)}trimLastNode(){let e=this.lastNode();e&&Kje(this,[e.id])&&this.removeNode(e)}reid(){let e=Object.fromEntries(Object.values(this.nodes).map(o=>[o.id,o.name])),n=new Map;Object.values(e).forEach(o=>{n.set(o,(n.get(o)||0)+1)});let r=o=>{let i=e[o];return Tg(o)&&n.get(i)===1?i:o};return new qje({nodes:Object.fromEntries(Object.entries(this.nodes).map(([o,i])=>[r(o),{...i,id:r(o)}])),edges:this.edges.map(o=>({...o,source:r(o.source),target:r(o.target)}))})}drawMermaid(e){let{withStyles:n,curveStyle:r,nodeColors:o={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:i}=e??{},s=this.reid(),a=s.firstNode(),l=s.lastNode();return jje(s.nodes,s.edges,{firstNode:a?.id,lastNode:l?.id,withStyles:n,curveStyle:r,nodeColors:o,wrapLabelNWords:i})}async drawMermaidPng(e){return Vje(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}}});function Yje(t){let e=new TextEncoder,n=new ReadableStream({async start(r){for await(let o of t)r.enqueue(e.encode(`event: data
data: ${JSON.stringify(o)}
`));r.enqueue(e.encode(`event: end
`)),r.close()}});return Yu.fromReadableStream(n)}var Zje=C(()=>{Og()});function jue(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}function e5(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function Vue(t){return t!=null&&typeof t=="object"&&typeof t.next=="function"}async function Xje(t,e){try{let n=await t.next();for(;!n.done;)await e?.(n.value),n=await t.next();return n.value}finally{await t.return?.(void 0)}}function*Wue(t,e){for(;;){let{value:n,done:r}=vl.runWithConfig(Gu(t),e.next.bind(e),!0);if(r)break;yield n}}async function*t5(t,e){let n=e[Symbol.asyncIterator]();for(;;){let{value:r,done:o}=await vl.runWithConfig(Gu(t),n.next.bind(e),!0);if(o)break;yield r}}var Jje,Hue=C(()=>{sI();aI();Ng();Jje=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function"});function Hs(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function rOt(t){if(DK(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}function Dw(t){if(typeof t=="function")return new $w({func:t});if(gr.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=Dw(r);return new sM({steps:e})}else throw new Error(`Expected a Runnable, function or object.
Instead got an unsupported type.`)}function oOt(t,e){let n=e.name??t.getName(),r=e.description??NT(e.schema);return u2(e.schema)?new Kue({name:n,description:r,schema:we.object({input:we.string()}).transform(o=>o.input),bound:t}):new Kue({name:n,description:r,schema:e.schema,bound:t})}var gr,fI,que,Kc,sM,nOt,$w,r4e,n5,o4e,Kue,Ra=C(()=>{L3();Rb();P2();E2();sI();aI();Ng();rM();Og();kje();Lje();Fue();X2();Uje();QK();vg();Gje();Zje();Hue();Cue();_g();gr=class extends zu{constructor(){super(...arguments);I(this,"lc_runnable",!0);I(this,"name")}getName(e){let n=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${n}${e}`:n}withRetry(e){return new que({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new fI({bound:this,config:e,kwargs:{}})}withFallbacks(e){let n=Array.isArray(e)?e:e.fallbacks;return new r4e({runnable:this,fallbacks:n})}_getOptionsList(e,n=0){if(Array.isArray(e)&&e.length!==n)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${n} inputs`);if(Array.isArray(e))return e.map(fr);if(n>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");let r=Object.fromEntries(Object.entries(e).filter(([o])=>o!=="runId"));return Array.from({length:n},(o,i)=>fr(i===0?e:r))}return Array.from({length:n},()=>fr(e))}async batch(e,n,r){let o=this._getOptionsList(n??{},e.length),i=new qb({maxConcurrency:o[0]?.maxConcurrency??r?.maxConcurrency,onFailedAttempt:a=>{throw a}}),s=e.map((a,l)=>i.call(async()=>{try{return await this.invoke(a,o[l])}catch(c){if(r?.returnExceptions)return c;throw c}}));return Promise.all(s)}async*_streamIterator(e,n){yield this.invoke(e,n)}async stream(e,n){let r=fr(n),o=new lI({generator:this._streamIterator(e,r),config:r});return await o.setup,Yu.fromAsyncGenerator(o)}_separateRunnableConfigFromCallOptions(e){let n;e===void 0?n=fr(e):n=fr({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});let r={...e};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[n,r]}async _callWithConfig(e,n,r){let o=fr(r),i=await(await qu(o))?.handleChainStart(this.toJSON(),Hs(n,"input"),o.runId,o?.runType,void 0,void 0,o?.runName??this.getName());delete o.runId;let s;try{s=await lp(e.call(this,n,o,i),o.signal)}catch(a){throw await i?.handleChainError(a),a}return await i?.handleChainEnd(Hs(s,"output")),s}async _batchWithConfig(e,n,r,o){let i=this._getOptionsList(r??{},n.length),s=await Promise.all(i.map(qu)),a=await Promise.all(s.map(async(c,u)=>{let d=await c?.handleChainStart(this.toJSON(),Hs(n[u],"input"),i[u].runId,i[u].runType,void 0,void 0,i[u].runName??this.getName());return delete i[u].runId,d})),l;try{l=await lp(e.call(this,n,i,a,o),i?.[0]?.signal)}catch(c){throw await Promise.all(a.map(u=>u?.handleChainError(c))),c}return await Promise.all(a.map(c=>c?.handleChainEnd(Hs(l,"output")))),l}_concatOutputChunks(e,n){return Um(e,n)}async*_transformStreamWithConfig(e,n,r){let o,i=!0,s,a=!0,l=fr(r),c=await qu(l),u=this;async function*d(){for await(let p of e){if(i)if(o===void 0)o=p;else try{o=u._concatOutputChunks(o,p)}catch{o=void 0,i=!1}yield p}}let f;try{let p=await xje(n.bind(this),d(),async()=>c?.handleChainStart(this.toJSON(),{input:""},l.runId,l.runType,void 0,void 0,l.runName??this.getName(),void 0,{lc_defers_inputs:!0}),l.signal,l);delete l.runId,f=p.setup;let m=f?.handlers.find(Oje),h=p.output;m!==void 0&&f!==void 0&&(h=m.tapOutputIterable(f.runId,h));let g=f?.handlers.find(Aje);g!==void 0&&f!==void 0&&(h=g.tapOutputIterable(f.runId,h));for await(let y of h)if(yield y,a)if(s===void 0)s=y;else try{s=this._concatOutputChunks(s,y)}catch{s=void 0,a=!1}}catch(p){throw await f?.handleChainError(p,void 0,void 0,void 0,{inputs:Hs(o,"input")
`).filter(Boolean).reduce((r,o)=>{let[i,s,...a]=o.split(" "),l=Number.parseInt(s,10);return a.forEach((c,u)=>r[c]=l+u),r},{});for(let[r,o]of Object.entries(n)){let i=g4e.default.toByteArray(r);this.rankMap.set(i.join(","),o),this.textMap.set(o,i)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((r,[o,i])=>(r[i]=this.textEncoder.encode(o),r),{})}encode(t,e=[],n="all"){let r=new RegExp(this.patStr,"ug"),o=tde.specialTokenRegex(Object.keys(this.specialTokens)),i=[],s=new Set(e==="all"?Object.keys(this.specialTokens):e),a=new Set(n==="all"?Object.keys(this.specialTokens).filter(c=>!s.has(c)):n);if(a.size>0){let c=tde.specialTokenRegex([...a]),u=t.match(c);if(u!=null)throw new Error(`The text contains a special token that is not allowed: ${u[0]}`)}let l=0;for(;;){let c=null,u=l;for(;o.lastIndex=u,c=o.exec(t),!(c==null||s.has(c[0]));)u=c.index+1;let d=c?.index??t.length;for(let p of t.substring(l,d).matchAll(r)){let m=this.textEncoder.encode(p[0]),h=this.rankMap.get(m.join(","));if(h!=null){i.push(h);continue}i.push(...gOt(m,this.rankMap))}if(c==null)break;let f=this.specialTokens[c[0]];i.push(f),l=c.index+c[0].length}return i}decode(t){let e=[],n=0;for(let i=0;i<t.length;++i){let s=t[i],a=this.textMap.get(s)??this.inverseSpecialTokens[s];a!=null&&(e.push(a),n+=a.length)}let r=new Uint8Array(n),o=0;for(let i of e)r.set(i,o),o+=i.length;return this.textDecoder.decode(r)}},s5=tde;mOt(s5,"specialTokenRegex",t=>new RegExp(t.map(e=>yOt(e)).join("|"),"g"))});var w4e=C(()=>{y4e()});async function v4e(t){return t in a5||(a5[t]=wOt.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new s5(e)).catch(e=>{throw delete a5[t],e})),await a5[t]}async function x4e(t){return v4e(nde(t))}var a5,wOt,rde=C(()=>{$n();X2();w4e();a5={},wOt=new qb({})});function Rg(t){return typeof t!="object"||!t?!1:!!("type"in t&&t.type==="function"&&"function"in t&&typeof t.function=="object"&&t.function&&"name"in t.function&&"parameters"in t.function)}var vOt,xOt,nU,mI,qd=C(()=>{$n();Dm();m4e();X2();Ra();tU();rde();vOt=t=>t.startsWith("gpt-5")?"gpt-5":t.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":t.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":t.startsWith("gpt-4-32k")?"gpt-4-32k":t.startsWith("gpt-4-")?"gpt-4":t.startsWith("gpt-4o")?"gpt-4o":t;xOt=()=>!1,nU=class extends gr{constructor(e){super(e);I(this,"verbose");I(this,"callbacks");I(this,"tags");I(this,"metadata");this.verbose=e.verbose??xOt(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{},this._addVersion("@langchain/core","1.1.46")}get lc_attributes(){return{callbacks:void 0,verbose:void 0}}_addVersion(e,n){let r=this.metadata?.versions;this.metadata={...this.metadata,versions:{...typeof r=="object"&&r!==null?r:{},[e]:n}}}},mI=class extends nU{constructor({callbacks:e,callbackManager:n,...r}){let{cache:o,...i}=r;super({callbacks:e??n,...i});I(this,"caller");I(this,"cache");I(this,"_encoding");typeof o=="object"?this.cache=o:o?this.cache=f4e.global():this.cache=void 0,this.caller=new qb(r??{})}get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}async getNumTokens(e){let n;typeof e=="string"?n=e:n=e.map(o=>typeof o=="string"?o:o.type==="text"&&"text"in o?o.text:"").join("");let r=Math.ceil(n.length/4);if(!this._encoding)try{this._encoding=await x4e("modelName"in this?vOt(this.modelName):"gpt2")}catch(o){console.warn("Failed to calculate number of tokens, falling back to approximate count",o)}if(this._encoding)try{r=this._encoding.encode(n).length}catch(o){console.warn("Failed to calculate number of tokens, falling back to approximate count",o)}return r}static _convertInputToPromptValue(e){return typeof e=="string"?new o5(e):Array.isArray(e)?new i5(e.map(Lm)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...n}){let r={...this._identifyingParams(),...n,_type:this._llmType(),_model:this._modelType()};return Object.entries(r).filter(([o,i])=>i!==void 0).map(([o,i])=>`${o}:${JSON.stringify(i)}`).sort().join(",")}serialize(){ret
"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
\`\`\`json
${JSON.stringify(Hr(this.schema))}
\`\`\`
`}async parse(e){try{let n=e.trim(),r=(n.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||n.match(/```json\s*([\s\S]*?)```/)?.[1]||n).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(o,i)=>`"${i.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await MT(this.schema,JSON.parse(r))}catch(n){throw new lc(`Failed to parse. Text: "${e}". Error: ${n}`,e)}}_baseMessageToString(e){return e.text}}});var AOt,kOt,M4e=C(()=>{AOt=function(){let t={};t.parser=function(M,E){return new n(M,E)},t.SAXParser=n,t.SAXStream=c,t.createStream=l,t.MAX_BUFFER_LENGTH=65536;let e=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];t.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function n(M,E){if(!(this instanceof n))return new n(M,E);var R=this;o(R),R.q=R.c="",R.bufferCheckPosition=t.MAX_BUFFER_LENGTH,R.opt=E||{},R.opt.lowercase=R.opt.lowercase||R.opt.lowercasetags,R.looseCase=R.opt.lowercase?"toLowerCase":"toUpperCase",R.tags=[],R.closed=R.closedRoot=R.sawRoot=!1,R.tag=R.error=null,R.strict=!!M,R.noscript=!!(M||R.opt.noscript),R.state=S.BEGIN,R.strictEntities=R.opt.strictEntities,R.ENTITIES=R.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),R.attribList=[],R.opt.xmlns&&(R.ns=Object.create(m)),R.trackPosition=R.opt.position!==!1,R.trackPosition&&(R.position=R.line=R.column=0),A(R,"onready")}Object.create||(Object.create=function(M){function E(){}return E.prototype=M,new E}),Object.keys||(Object.keys=function(M){var E=[];for(var R in M)M.hasOwnProperty(R)&&E.push(R);return E});function r(M){for(var E=Math.max(t.MAX_BUFFER_LENGTH,10),R=0,L=0,K=e.length;L<K;L++){var Y=M[e[L]].length;if(Y>E)switch(e[L]){case"textNode":D(M);break;case"cdata":O(M,"oncdata",M.cdata),M.cdata="";break;case"script":O(M,"onscript",M.script),M.script="";break;default:B(M,"Max buffer length exceeded: "+e[L])}R=Math.max(R,Y)}M.bufferCheckPosition=t.MAX_BUFFER_LENGTH-R+M.position}function o(M){for(var E=0,R=e.length;E<R;E++)M[e[E]]=""}function i(M){D(M),M.cdata!==""&&(O(M,"oncdata",M.cdata),M.cdata=""),M.script!==""&&(O(M,"onscript",M.script),M.script="")}n.prototype={end:function(){W(this)},write:J,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){i(this)}};var s=ReadableStream;s||(s=function(){});var a=t.EVENTS.filter(function(M){return M!=="error"&&M!=="end"});function l(M,E){return new c(M,E)}function c(M,E){if(!(this instanceof c))return new c(M,E);s.apply(this),this._parser=new n(M,E),this.writable=!0,this.readable=!0;var R=this;this._parser.onend=function(){R.emit("end")},this._parser.onerror=function(L){R.emit("error",L),R._parser.error=null},this._decoder=null,a.forEach(function(L){Object.defineProperty(R,"on"+L,{get:function(){return R._parser["on"+L]},set:function(K){if(!K)return R.removeAllListeners(L),R._parser["on"+L]=K,K;R.on(L,K)},enumerable:!0,configurable:!1})})}c.prototype=Object.create(s.prototype,{constructor:{value:c}}),c.prototype.write=function(M){return this._parser.write(M.toString()),this.emit("data",M),!0},c.prototype.end=function(M){return M&&M.length&&this.write(M),this._parser.end(),!0},c.prototype.on=function(M,E){var R=this;return!R._parser["on"+M]&&a.indexOf(M)!==-1&&(R._parser["on"+M]=function(){var L=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);L.splice(0,0,M),R.emit.apply(R,L)}),s.prototype.on.call(R,M,E)};var u="[CDATA[",d="DOCTYPE",f="http://www.w3.org/XML/1998/namespace",p="http://www.w3.org/2000/xmlns/",m={xml:f,xmlns:p},h=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,g=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,y=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\
`||M==="\r"||M===" "}function x(M){return M==='"'||M==="'"}function b(M){return M===">"||v(M)}function _(M,E){return M.test(E)}function T(M,E){return!_(M,E)}var S=0;t.STATE={BEGIN:S++,BEGIN_WHITESPACE:S++,TEXT:S++,TEXT_ENTITY:S++,OPEN_WAKA:S++,SGML_DECL:S++,SGML_DECL_QUOTED:S++,DOCTYPE:S++,DOCTYPE_QUOTED:S++,DOCTYPE_DTD:S++,DOCTYPE_DTD_QUOTED:S++,COMMENT_STARTING:S++,COMMENT:S++,COMMENT_ENDING:S++,COMMENT_ENDED:S++,CDATA:S++,CDATA_ENDING:S++,CDATA_ENDING_2:S++,PROC_INST:S++,PROC_INST_BODY:S++,PROC_INST_ENDING:S++,OPEN_TAG:S++,OPEN_TAG_SLASH:S++,ATTRIB:S++,ATTRIB_NAME:S++,ATTRIB_NAME_SAW_WHITE:S++,ATTRIB_VALUE:S++,ATTRIB_VALUE_QUOTED:S++,ATTRIB_VALUE_CLOSED:S++,ATTRIB_VALUE_UNQUOTED:S++,ATTRIB_VALUE_ENTITY_Q:S++,ATTRIB_VALUE_ENTITY_U:S++,CLOSE_TAG:S++,CLOSE_TAG_SAW_WHITE:S++,SCRIPT:S++,SCRIPT_ENDING:S++},t.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},t.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(t.ENTITIES).forEach(function(M){var E=t.ENTITIES[M],R=typeof E=="number"?String.fromCharCode(E):E;t.ENTITIES[M]=R});for(var P in t.STATE)t.STATE[t.STATE[P]]=P;S=t.STATE;function A(M,E,R){M[E]&&M[E](R)}function O(M,E,R){M.textNode&&D(M),A(M,E,R)}function D(M){M.textNode=$(M.opt,M.textNode),M.textNode&&A(M,"ontext",M.textNode),M.textNode=""}function $(M,E){return M.trim&&(E=E.trim()),M.normalize&&(E=E.replace(/\s+/g," ")),E}function B(M,E){return D(M),M.trackPosition&&(E+=`
Line: `+M.line+`
Column: `+M.column+`
Char: `+M.c),E=new Error(E),M.error=E,A(M,"onerror",E),M}function W(M){return M.sawRoot&&!M.closedRoot&&F(M,"Unclosed root tag"),M.state!==S.BEGIN&&M.state!==S.BEGIN_WHITESPACE&&M.state!==S.TEXT&&B(M,"Unexpected end"),D(M),M.c="",M.closed=!0,A(M,"onend"),n.call(M,M.strict,M.opt),M}function F(M,E){if(typeof M!="object"||!(M instanceof n))throw new Error("bad call to strictFail");M.strict&&B(M,E)}function Z(M){M.strict||(M.tagName=M.tagName[M.looseCase]());var E=M.tags[M.tags.length-1]||M,R=M.tag={name:M.tagName,attributes:{}};M.opt.xmlns&&(R.ns=E.ns),M.attribList.length=0,O(M,"onopentagstart",R)}function V(M,E){var R=M.indexOf(":")<0?["",M]:M.split(":"),L=R[0],K=R[1];return E&&M==="xmlns"&&(L="xmlns",K=""),{prefix:L,local:K}}function H(M){if(M.strict||(M.attribName=M.attribName[M.looseCase]()),M.attribList.indexOf(M.attribName)!==-1||M.tag.attributes.hasOwnProperty(M.attribName)){M.attribName=M.attribValue="";return}if(M.opt.xmlns){var E=V(M.attribName,!0),R=E.prefix,L=E.local;if(R==="xmlns")if(L==="xml"&&M.attribValue!==f)F(M,"xml: prefix must be bound to "+f+`
Actual: `+M.attribValue);else if(L==="xmlns"&&M.attribValue!==p)F(M,"xmlns: prefix must be bound to "+p+`
Actual: `+M.attribValue);else{var K=M.tag,Y=M.tags[M.tags.length-1]||M;K.ns===Y.ns&&(K.ns=Object.create(Y.ns)),K.ns[L]=M.attribValue}M.attribList.push([M.attribName,M.attribValue])}else M.tag.attributes[M.attribName]=M.attribValue,O(M,"onattribute",{name:M.attribName,value:M.attribValue});M.attribName=M.attribValue=""}function te(M,E){if(M.opt.xmlns){var R=M.tag,L=V(M.tagName);R.prefix=L.prefix,R.local=L.local,R.uri=R.ns[L.prefix]||"",R.prefix&&!R.uri&&(F(M,"Unbound namespace prefix: "+JSON.stringify(M.tagName)),R.uri=L.prefix);var K=M.tags[M.tags.length-1]||M;R.ns&&K.ns!==R.ns&&Object.keys(R.ns).forEach(function(Ln){O(M,"onopennamespace",{prefix:Ln,uri:R.ns[Ln]})});for(var Y=0,re=M.attribList.length;Y<re;Y++){var ae=M.attribList[Y],ve=ae[0],Te=ae[1],Ee=V(ve,!0),nt=Ee.prefix,rt=Ee.local,Jt=nt===""?"":R.ns[nt]||"",ke={name:ve,value:Te,prefix:nt,local:rt,uri:Jt};nt&&nt!=="xmlns"&&!Jt&&(F(M,"Unbound namespace prefix: "+JSON.stringify(nt)),ke.uri=nt),M.tag.attributes[ve]=ke,O(M,"onattribute",ke)}M.attribList.length=0}M.tag.isSelfClosing=!!E,M.sawRoot=!0,M.tags.push(M.tag),O(M,"onopentag",M.tag),E||(!M.noscript&&M.tagName.toLowerCase()==="script"?M.state=S.SCRIPT:M.state=S.TEXT,M.tag=null,M.tagName=""),M.attribName=M.attribValue="",M.attribList.length=0}function fe(M){if(!M.tagName){F(M,"Weird empty close tag."),M.textNode+="</>",M.state=S.TEXT;return}if(M.script){if(M.tagName!=="script"){M.script+="</"+M.tagName+">",M.tagName="",M.state=S.SCRIPT;return}O(M,"onscript",M.script),M.script=""}var E=M.tags.length,R=M.tagName;M.strict||(R=R[M.looseCase]());for(var L=R;E--&&M.tags[E].name!==L;)F(M,"Unexpected close tag");if(E<0){F(M,"Unmatched closing tag: "+M.tagName),M.textNode+="</"+M.tagName+">",M.state=S.TEXT;return}M.tagName=R;for(var K=M.tags.length;K-- >E;){var Y=M.tag=M.tags.pop();M.tagName=M.tag.name,O(M,"onclosetag",M.tagName);var re={};for(var ae in Y.ns)re[ae]=Y.ns[ae];var ve=M.tags[M.tags.length-1]||M;M.opt.xmlns&&Y.ns!==ve.ns&&Object.keys(Y.ns).forEach(function(Te){var Ee=Y.ns[Te];O(M,"onclosenamespace",{prefix:Te,uri:Ee})})}E===0&&(M.closedRoot=!0),M.tagName=M.attribValue=M.attribName="",M.attribList.length=0,M.state=S.TEXT}function me(M){var E=M.entity,R=E.toLowerCase(),L,K="";return M.ENTITIES[E]?M.ENTITIES[E]:M.ENTITIES[R]?M.ENTITIES[R]:(E=R,E.charAt(0)==="#"&&(E.charAt(1)==="x"?(E=E.slice(2),L=parseInt(E,16),K=L.toString(16)):(E=E.slice(1),L=parseInt(E,10),K=L.toString(10))),E=E.replace(/^0+/,""),isNaN(L)||K.toLowerCase()!==E?(F(M,"Invalid character entity"),"&"+M.entity+";"):String.fromCodePoint(L))}function j(M,E){E==="<"?(M.state=S.OPEN_WAKA,M.startTagPosition=M.position):v(E)||(F(M,"Non-whitespace before first tag."),M.textNode=E,M.state=S.TEXT)}function G(M,E){var R="";return E<M.length&&(R=M.charAt(E)),R}function J(M){var E=this;if(this.error)throw this.error;if(E.closed)return B(E,"Cannot write after close. Assign an onready handler.");if(M===null)return W(E);typeof M=="object"&&(M=M.toString());for(var R=0,L="";L=G(M,R++),E.c=L,!!L;)switch(E.trackPosition&&(E.position++,L===`
`?(E.line++,E.column=0):E.column++),E.state){case S.BEGIN:if(E.state=S.BEGIN_WHITESPACE,L==="\uFEFF")continue;j(E,L);continue;case S.BEGIN_WHITESPACE:j(E,L);continue;case S.TEXT:if(E.sawRoot&&!E.closedRoot){for(var K=R-1;L&&L!=="<"&&L!=="&";)L=G(M,R++),L&&E.trackPosition&&(E.position++,L===`
`?(E.line++,E.column=0):E.column++);E.textNode+=M.substring(K,R-1)}L==="<"&&!(E.sawRoot&&E.closedRoot&&!E.strict)?(E.state=S.OPEN_WAKA,E.startTagPosition=E.position):(!v(L)&&(!E.sawRoot||E.closedRoot)&&F(E,"Text data outside of root node."),L==="&"?E.state=S.TEXT_ENTITY:E.textNode+=L);continue;case S.SCRIPT:L==="<"?E.state=S.SCRIPT_ENDING:E.script+=L;continue;case S.SCRIPT_ENDING:L==="/"?E.state=S.CLOSE_TAG:(E.script+="<"+L,E.state=S.SCRIPT);continue;case S.OPEN_WAKA:if(L==="!")E.state=S.SGML_DECL,E.sgmlDecl="";else if(!v(L))if(_(h,L))E.state=S.OPEN_TAG,E.tagName=L;else if(L==="/")E.state=S.CLOSE_TAG,E.tagName="";else if(L==="?")E.state=S.PROC_INST,E.procInstName=E.procInstBody="";else{if(F(E,"Unencoded <"),E.startTagPosition+1<E.position){var Y=E.position-E.startTagPosition;L=new Array(Y).join(" ")+L}E.textNode+="<"+L,E.state=S.TEXT}continue;case S.SGML_DECL:(E.sgmlDecl+L).toUpperCase()===u?(O(E,"onopencdata"),E.state=S.CDATA,E.sgmlDecl="",E.cdata=""):E.sgmlDecl+L==="--"?(E.state=S.COMMENT,E.comment="",E.sgmlDecl=""):(E.sgmlDecl+L).toUpperCase()===d?(E.state=S.DOCTYPE,(E.doctype||E.sawRoot)&&F(E,"Inappropriately located doctype declaration"),E.doctype="",E.sgmlDecl=""):L===">"?(O(E,"onsgmldeclaration",E.sgmlDecl),E.sgmlDecl="",E.state=S.TEXT):(x(L)&&(E.state=S.SGML_DECL_QUOTED),E.sgmlDecl+=L);continue;case S.SGML_DECL_QUOTED:L===E.q&&(E.state=S.SGML_DECL,E.q=""),E.sgmlDecl+=L;continue;case S.DOCTYPE:L===">"?(E.state=S.TEXT,O(E,"ondoctype",E.doctype),E.doctype=!0):(E.doctype+=L,L==="["?E.state=S.DOCTYPE_DTD:x(L)&&(E.state=S.DOCTYPE_QUOTED,E.q=L));continue;case S.DOCTYPE_QUOTED:E.doctype+=L,L===E.q&&(E.q="",E.state=S.DOCTYPE);continue;case S.DOCTYPE_DTD:E.doctype+=L,L==="]"?E.state=S.DOCTYPE:x(L)&&(E.state=S.DOCTYPE_DTD_QUOTED,E.q=L);continue;case S.DOCTYPE_DTD_QUOTED:E.doctype+=L,L===E.q&&(E.state=S.DOCTYPE_DTD,E.q="");continue;case S.COMMENT:L==="-"?E.state=S.COMMENT_ENDING:E.comment+=L;continue;case S.COMMENT_ENDING:L==="-"?(E.state=S.COMMENT_ENDED,E.comment=$(E.opt,E.comment),E.comment&&O(E,"oncomment",E.comment),E.comment=""):(E.comment+="-"+L,E.state=S.COMMENT);continue;case S.COMMENT_ENDED:L!==">"?(F(E,"Malformed comment"),E.comment+="--"+L,E.state=S.COMMENT):E.state=S.TEXT;continue;case S.CDATA:L==="]"?E.state=S.CDATA_ENDING:E.cdata+=L;continue;case S.CDATA_ENDING:L==="]"?E.state=S.CDATA_ENDING_2:(E.cdata+="]"+L,E.state=S.CDATA);continue;case S.CDATA_ENDING_2:L===">"?(E.cdata&&O(E,"oncdata",E.cdata),O(E,"onclosecdata"),E.cdata="",E.state=S.TEXT):L==="]"?E.cdata+="]":(E.cdata+="]]"+L,E.state=S.CDATA);continue;case S.PROC_INST:L==="?"?E.state=S.PROC_INST_ENDING:v(L)?E.state=S.PROC_INST_BODY:E.procInstName+=L;continue;case S.PROC_INST_BODY:if(!E.procInstBody&&v(L))continue;L==="?"?E.state=S.PROC_INST_ENDING:E.procInstBody+=L;continue;case S.PROC_INST_ENDING:L===">"?(O(E,"onprocessinginstruction",{name:E.procInstName,body:E.procInstBody}),E.procInstName=E.procInstBody="",E.state=S.TEXT):(E.procInstBody+="?"+L,E.state=S.PROC_INST_BODY);continue;case S.OPEN_TAG:_(g,L)?E.tagName+=L:(Z(E),L===">"?te(E):L==="/"?E.state=S.OPEN_TAG_SLASH:(v(L)||F(E,"Invalid character in tag name"),E.state=S.ATTRIB));continue;case S.OPEN_TAG_SLASH:L===">"?(te(E,!0),fe(E)):(F(E,"Forward-slash in opening tag not followed by >"),E.state=S.ATTRIB);continue;case S.ATTRIB:if(v(L))continue;L===">"?te(E):L==="/"?E.state=S.OPEN_TAG_SLASH:_(h,L)?(E.attribName=L,E.attribValue="",E.state=S.ATTRIB_NAME):F(E,"Invalid attribute name");continue;case S.ATTRIB_NAME:L==="="?E.state=S.ATTRIB_VALUE:L===">"?(F(E,"Attribute without value"),E.attribValue=E.attribName,H(E),te(E)):v(L)?E.state=S.ATTRIB_NAME_SAW_WHITE:_(g,L)?E.attribName+=L:F(E,"Invalid attribute name");continue;case S.ATTRIB_NAME_SAW_WHITE:if(L==="=")E.state=S.ATTRIB_VALUE;else{if(v(L))continue;F(E,"Attribute without value"),E.tag.attributes[E.attribName]="",E.attribValue="",O(E,"onattribute",{name:E.attribName,value:""}),E.attribName="",L===">"?te(E):_(h,L)?(E.attribName=L,E.state=S.ATTRIB_NAME):(F(E,"Invalid attribute name"),E.state=S.ATTRIB)}continue;case S.ATTRIB_VALUE:if(v(L))continue;x(L)?(E.q=
`+s.executableCode.code+"\n```\n"),s.codeExecutionResult&&i.push("\n```\n"+s.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function W4e(t){var e,n,r,o;let i=[];if(!((n=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||n===void 0)&&n.parts)for(let s of(o=(r=t.candidates)===null||r===void 0?void 0:r[0].content)===null||o===void 0?void 0:o.parts)s.functionCall&&i.push(s.functionCall);if(i.length>0)return i}function c5(t){return!!t.finishReason&&VOt.includes(t.finishReason)}function Jb(t){var e,n,r;let o="";if((!t.candidates||t.candidates.length===0)&&t.promptFeedback)o+="Response was blocked",!((e=t.promptFeedback)===null||e===void 0)&&e.blockReason&&(o+=` due to ${t.promptFeedback.blockReason}`),!((n=t.promptFeedback)===null||n===void 0)&&n.blockReasonMessage&&(o+=`: ${t.promptFeedback.blockReasonMessage}`);else if(!((r=t.candidates)===null||r===void 0)&&r[0]){let i=t.candidates[0];c5(i)&&(o+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(o+=`: ${i.finishMessage}`))}return o}function sU(t){return this instanceof sU?(this.v=t,this):new sU(t)}function WOt(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),o,i=[];return o={},s("next"),s("throw"),s("return"),o[Symbol.asyncIterator]=function(){return this},o;function s(f){r[f]&&(o[f]=function(p){return new Promise(function(m,h){i.push([f,p,m,h])>1||a(f,p)})})}function a(f,p){try{l(r[f](p))}catch(m){d(i[0][3],m)}}function l(f){f.value instanceof sU?Promise.resolve(f.value.v).then(c,u):d(i[0][2],f)}function c(f){a("next",f)}function u(f){a("throw",f)}function d(f,p){f(p),i.shift(),i.length&&a(i[0][0],i[0][1])}}function HOt(t){let e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),n=GOt(e),[r,o]=n.tee();return{stream:qOt(r),response:KOt(o)}}async function KOt(t){let e=[],n=t.getReader();for(;;){let{done:r,value:o}=await n.read();if(r)return hde(YOt(e));e.push(o)}}function qOt(t){return WOt(this,arguments,function*(){let n=t.getReader();for(;;){let{value:r,done:o}=yield sU(n.read());if(o)break;yield yield sU(hde(r))}})}function GOt(t){let e=t.getReader();return new ReadableStream({start(r){let o="";return i();function i(){return e.read().then(({value:s,done:a})=>{if(a){if(o.trim()){r.error(new Da("Failed to parse stream"));return}r.close();return}o+=s;let l=o.match(H4e),c;for(;l;){try{c=JSON.parse(l[1])}catch{r.error(new Da(`Error parsing JSON response: "${l[1]}"`));return}r.enqueue(c),o=o.substring(l[0].length),l=o.match(H4e)}return i()}).catch(s=>{let a=s;throw a.stack=s.stack,a.name==="AbortError"?a=new d5("Request aborted when reading from the stream"):a=new Da("Error reading from the stream"),a})}}})}function YOt(t){let e=t[t.length-1],n={promptFeedback:e?.promptFeedback};for(let r of t){if(r.candidates){let o=0;for(let i of r.candidates)if(n.candidates||(n.candidates=[]),n.candidates[o]||(n.candidates[o]={index:o}),n.candidates[o].citationMetadata=i.citationMetadata,n.candidates[o].groundingMetadata=i.groundingMetadata,n.candidates[o].finishReason=i.finishReason,n.candidates[o].finishMessage=i.finishMessage,n.candidates[o].safetyRatings=i.safetyRatings,i.content&&i.content.parts){n.candidates[o].content||(n.candidates[o].content={role:i.content.role||"user",parts:[]});let s={};for(let a of i.content.parts)a.text&&(s.text=a.text),a.functionCall&&(s.functionCall=a.functionCall),a.executableCode&&(s.executableCode=a.executableCode),a.codeExecutionResult&&(s.codeExecutionResult=a.codeExecutionResult),Object.keys(s).length===0&&(s.text=""),n.candidates[o].content.parts.push(s)}o++}r.usageMetadata&&(n.usageMetadata=r.usageMetadata)}return n}async function Z4e(t,e,n,r){let o=await lU(e,yI.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(n),r);return HOt(o)}async function J4e(t,e,n,r){let i=await(await lU(e,yI.GENERATE_CONTENT,t,!1,JSON.stringify(n),r)).json();return{response:hde(i)}}function X4e(t){if(t!=null){if(typeof t=="string")return{role:"system",parts:[{text:t}]};if(t.text)return{role:"system",parts:[t]};if(t.parts)return t.role?t:{role:"system",p
`))}let r={name:t.function.name,args:n,type:"tool_call"};return e?.returnId&&(r.id=t.id),r}function cU(t){if(t.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:t.id,type:"function",function:{name:t.name,arguments:JSON.stringify(t.args)}}}function Bw(t,e){return{name:t.function?.name,args:t.function?.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var oVe,up,yde=C(()=>{Wk();Wu();vg();hI();Yb();oU();oVe=class extends lM{constructor(e){super(e);I(this,"returnId",!1);I(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);I(this,"lc_serializable",!0);this.returnId=e?.returnId??this.returnId}static lc_name(){return"JsonOutputToolsParser"}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,n=!0){let r=e[0].message,o;if(rp(r)&&r.tool_calls?.length?o=r.tool_calls.map(s=>{let{id:a,...l}=s;return this.returnId?{id:a,...l}:l}):r.additional_kwargs.tool_calls!==void 0&&(o=JSON.parse(JSON.stringify(r.additional_kwargs.tool_calls)).map(s=>Xb(s,{returnId:this.returnId,partial:n}))),!o)return[];let i=[];for(let s of o)if(s!==void 0){let a={type:s.name,args:s.args,id:s.id};i.push(a)}return i}},up=class extends oVe{constructor(e){super(e);I(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);I(this,"lc_serializable",!0);I(this,"returnId",!1);I(this,"keyName");I(this,"returnSingle",!1);I(this,"zodSchema");I(this,"serializableSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,"zodSchema"in e&&(this.zodSchema=e.zodSchema),"serializableSchema"in e&&(this.serializableSchema=e.serializableSchema)}static lc_name(){return"JsonOutputKeyToolsParser"}async _validateResult(e){if(this.serializableSchema!==void 0){let r=await this.serializableSchema["~standard"].validate(e);if(r.issues)throw new lc(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.issues)}`,JSON.stringify(e,null,2));return r.value}if(this.zodSchema===void 0)return e;let n=await kT(this.zodSchema,e);if(n.success)return n.data;throw new lc(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error?.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){let n=(await super.parsePartialResult(e)).filter(o=>o.type===this.keyName),r=n;if(n.length)return this.returnId||(r=n.map(o=>o.args)),this.returnSingle?r[0]:r}async parseResult(e){let n=(await super.parsePartialResult(e,!1)).filter(o=>o.type===this.keyName),r=n;if(n.length)return this.returnId||(r=n.map(o=>o.args)),this.returnSingle?this._validateResult(r[0]):await Promise.all(r.map(o=>this._validateResult(o)))}}});function iVe(t){return jr(t)?Vm.fromZodSchema(t):Ob(t)?cde.fromSerializableSchema(t):new Gd}function sVe(t,e,n){let r=n??up;return jr(t)?new r({returnSingle:!0,keyName:e,zodSchema:t}):Ob(t)?new r({returnSingle:!0,keyName:e,serializableSchema:t}):new r({returnSingle:!0,keyName:e})}function h5(t,e,n,r){if(!n){let l=t.pipe(e);return r?l.withConfig({runName:r}):l}let o=xl.assign({parsed:(l,c)=>e.invoke(l.raw,c)}),i=xl.assign({parsed:()=>null}),s=o.withFallbacks({fallbacks:[i]}),a=Kc.from([{raw:t},s]);return r?a.withConfig({runName:r}):a}var wde=C(()=>{$n();vg();y2();Ra();l5();jm();oU();ude();dde();Uw();yde();Bd()});function lRt(t,e){switch(e.type){case"text-delta":return t.type==="text"?{...t,text:(t.text??"")+e.text}:t;case"reasoning-delta":return t.type==="thinking"?{...t,thinking:(t.thinking??"")+e.reasoning}:t.type==="reasoning"?{...t,reasoning:(t.reasoning??"")+e.reasoning}:t;case"data-delta":return{...t,data:(t.data??"")+e.data};case"block-delta":return{...t,...e.fields};default:throw new Error(`Unknown delta type: ${JSON.stringify(e)}`)}}function uU(t){if(t.event!=="content-block-delta")return;if("delta"in t&&t.delta)return t.delta;let e=t.content;if(e==null||typeof e!="object")return;let n=e;if(n.type==="text"&&typeof n.text=="string")return{type:"text-delta",text:n.text};if(n.type==="reasoning"&&typeof n.reasoning=="string")re
`)===0?r.substr(1,r.length):r}).forEach(function(r){var o=r.split(":"),i=o.shift().trim();if(i){var s=o.join(":").trim();try{e.append(i,s)}catch(a){console.warn("Response "+a.message)}}}),e}function $g(t,e){if(!(this instanceof $g))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(e||(e={}),this.type="default",this.status=e.status===void 0?200:e.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=e.statusText===void 0?"":""+e.statusText,this.headers=new Ks(e.headers),this.url=e.url||"",this._initBody(t)}function kVe(t,e){return new Promise(function(n,r){var o=new CI(t,e);if(o.signal&&o.signal.aborted)return r(new bI("Aborted","AbortError"));var i=new XMLHttpRequest;function s(){i.abort()}i.onload=function(){var c={statusText:i.statusText,headers:DRt(i.getAllResponseHeaders()||"")};o.url.indexOf("file://")===0&&(i.status<200||i.status>599)?c.status=200:c.status=i.status,c.url="responseURL"in i?i.responseURL:c.headers.get("X-Request-URL");var u="response"in i?i.response:i.responseText;setTimeout(function(){n(new $g(u,c))},0)},i.onerror=function(){setTimeout(function(){r(new TypeError("Network request failed"))},0)},i.ontimeout=function(){setTimeout(function(){r(new TypeError("Network request timed out"))},0)},i.onabort=function(){setTimeout(function(){r(new bI("Aborted","AbortError"))},0)};function a(c){try{return c===""&&Cl.location.href?Cl.location.href:c}catch{return c}}if(i.open(o.method,a(o.url),!0),o.credentials==="include"?i.withCredentials=!0:o.credentials==="omit"&&(i.withCredentials=!1),"responseType"in i&&(qc.blob?i.responseType="blob":qc.arrayBuffer&&(i.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof Ks||Cl.Headers&&e.headers instanceof Cl.Headers)){var l=[];Object.getOwnPropertyNames(e.headers).forEach(function(c){l.push(uM(c)),i.setRequestHeader(c,Ede(e.headers[c]))}),o.headers.forEach(function(c,u){l.indexOf(u)===-1&&i.setRequestHeader(u,c)})}else o.headers.forEach(function(c,u){i.setRequestHeader(u,c)});o.signal&&(o.signal.addEventListener("abort",s),i.onreadystatechange=function(){i.readyState===4&&o.signal.removeEventListener("abort",s)}),i.send(typeof o._bodyInit>"u"?null:o._bodyInit)})}var Cl,qc,TVe,PVe,ORt,$Rt,bI,MVe=C(()=>{Cl=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof window<"u"&&window||{},qc={searchParams:"URLSearchParams"in Cl,iterable:"Symbol"in Cl&&"iterator"in Symbol,blob:"FileReader"in Cl&&"Blob"in Cl&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in Cl,arrayBuffer:"ArrayBuffer"in Cl};qc.arrayBuffer&&(TVe=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],PVe=ArrayBuffer.isView||function(t){return t&&TVe.indexOf(Object.prototype.toString.call(t))>-1});Ks.prototype.append=function(t,e){t=uM(t),e=Ede(e);var n=this.map[t];this.map[t]=n?n+", "+e:e};Ks.prototype.delete=function(t){delete this.map[uM(t)]};Ks.prototype.get=function(t){return t=uM(t),this.has(t)?this.map[t]:null};Ks.prototype.has=function(t){return this.map.hasOwnProperty(uM(t))};Ks.prototype.set=function(t,e){this.map[uM(t)]=Ede(e)};Ks.prototype.forEach=function(t,e){for(var n in this.map)this.map.hasOwnProperty(n)&&t.call(e,this.map[n],n,this)};Ks.prototype.keys=function(){var t=[];return this.forEach(function(e,n){t.push(n)}),Ade(t)};Ks.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),Ade(t)};Ks.prototype.entries=function(){var t=[];return this.forEach(function(e,n){t.push([n,e])}),Ade(t)};qc.iterable&&(Ks.prototype[Symbol.iterator]=Ks.prototype.entries);ORt=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];CI.prototype.clone=function(){return new CI(this,{body:this._bodyInit})};AVe.call(CI.prototype);AVe.call($g.pro
`);n=s.pop()??"";for(let a of s)try{yield JSON.parse(a)}catch{console.warn("invalid json: ",a)}}n+=e.decode();for(let o of n.split(`
`).filter(i=>i!==""))try{yield JSON.parse(o)}catch{console.warn("invalid json: ",o)}},KRt=t=>{if(!t)return OVe;let e=t.includes("://");t.startsWith(":")&&(t=`http://127.0.0.1${t}`,e=!0),e||(t=`http://${t}`);let n=new URL(t),r=n.port;r||(e?r=n.protocol==="https:"?"443":"80":r=NVe);let o="";n.username&&(o=n.username,n.password&&(o+=`:${n.password}`),o+="@");let i=`${n.protocol}//${o}${n.hostname}:${r}${n.pathname}`;return i.endsWith("/")&&(i=i.slice(0,-1)),i},qRt=Object.defineProperty,GRt=(t,e,n)=>e in t?qRt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Nde=(t,e,n)=>(GRt(t,typeof e!="symbol"?e+"":e,n),n),dM=class{constructor(e){Nde(this,"config"),Nde(this,"fetch"),Nde(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e?.headers},e?.proxy||(this.config.host=KRt(e?.host??OVe)),this.fetch=e?.fetch??fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,n){n.stream=n.stream??!1;let r=`${this.config.host}/api/${e}`;if(n.stream){let i=new AbortController,s=await eC(this.fetch,r,n,{signal:i.signal,headers:this.config.headers});if(!s.body)throw new Error("Missing body");let a=HRt(s.body),l=new Rde(i,a,()=>{let c=this.ongoingStreamedRequests.indexOf(l);c>-1&&this.ongoingStreamedRequests.splice(c,1)});return this.ongoingStreamedRequests.push(l),l}return await(await eC(this.fetch,r,n,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!="string"){let n=new Uint8Array(e),r="",o=n.byteLength;for(let i=0;i<o;i++)r+=String.fromCharCode(n[i]);return btoa(r)}return e}async generate(e){return e.images&&(e.images=await Promise.all(e.images.map(this.encodeImage.bind(this)))),this.processStreamableRequest("generate",e)}async chat(e){if(e.messages)for(let n of e.messages)n.images&&(n.images=await Promise.all(n.images.map(this.encodeImage.bind(this))));return this.processStreamableRequest("chat",e)}async create(e){return this.processStreamableRequest("create",{...e})}async pull(e){return this.processStreamableRequest("pull",{name:e.model,stream:e.stream,insecure:e.insecure})}async push(e){return this.processStreamableRequest("push",{name:e.model,stream:e.stream,insecure:e.insecure})}async delete(e){return await WRt(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await eC(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await Mde(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await eC(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await eC(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await eC(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await Mde(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await Mde(this.fetch,`${this.config.host}/api/version`,{headers:this.config.headers})).json()}async webSearch(e){if(!e.query||e.query.length===0)throw new Error("Query is required");return await(await eC(this.fetch,"https://ollama.com/api/web_search",{...e},{headers:this.config.headers})).json()}async webFetch(e){if(!e.url||e.url.length===0)throw new Error("URL is required");return await(await eC(this.fetch,"https://ollama.com/api/web_fetch",{...e},{headers:this.config.headers})).json()}},FRn=new dM});var fM=C(()=>{$n();yde()});var $de,RVe=C(()=>{SVe();Kr();vI();v5();ac();jm();pI();Og();Uw();fM();Jo();Bd();Bu();$de=class extends dp{constructor(e){super(e??{});I(this,"model","llama3");I(this,"numa");I(this,"numCtx");I(this,"numBatch");I(this,"numGpu");I(this,"mainGpu");I(this,"lowVram");I(this,"f16Kv");I(this,"logitsAll");I(this,"vocabOnly");I(this,"useMmap");I(this,"useMlock");I(this,"embeddingOnly");I(this,"numThread");I(this,"numKeep")
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
`,t}var $Ve=C(()=>{});function Zt(t,e,n,r,o){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?o.call(t,n):o?o.value=n:e.set(t,n),n}function de(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)}var fp=C(()=>{});var zde,jde=C(()=>{zde=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return zde=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))}});function mU(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var hU,x5=C(()=>{hU=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)}});var st,Bi,zi,tC,Fg,pM,mM,hM,gM,yM,wM,vM,xM,bM,CM,Ug,_I,gU,pp=C(()=>{x5();st=class extends Error{},Bi=class t extends st{constructor(e,n,r,o){super(`${t.makeMessage(e,n,r)}`),this.status=e,this.headers=o,this.requestID=o?.get("x-request-id"),this.error=n;let i=n;this.code=i?.code,this.param=i?.param,this.type=i?.type}static makeMessage(e,n,r){let o=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,n,r,o){if(!e||!o)return new tC({message:r,cause:hU(n)});let i=n?.error;return e===400?new pM(e,i,r,o):e===401?new mM(e,i,r,o):e===403?new hM(e,i,r,o):e===404?new gM(e,i,r,o):e===409?new yM(e,i,r,o):e===422?new wM(e,i,r,o):e===429?new vM(e,i,r,o):e>=500?new xM(e,i,r,o):new t(e,i,r,o)}},zi=class extends Bi{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},tC=class extends Bi{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}},Fg=class extends tC{constructor({message:e}={}){super({message:e??"Request timed out."})}},pM=class extends Bi{},mM=class extends Bi{},hM=class extends Bi{},gM=class extends Bi{},yM=class extends Bi{},wM=class extends Bi{},vM=class extends Bi{},xM=class extends Bi{},bM=class extends st{constructor(){super("Could not parse response content as the length limit was reached")}},CM=class extends st{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Ug=class extends Error{constructor(e){super(e)}},_I=class extends Bi{constructor(e,n,r){let o="OAuth2 authentication error",i;if(n&&typeof n=="object"){let s=n;i=s.error;let a=s.error_description;a&&typeof a=="string"?o=a:i&&(o=i)}super(e,n,o,r),this.error_code=i}},gU=class extends st{constructor(e,n,r){super(e),this.provider=n,this.cause=r}}});function b5(t){return typeof t!="object"?{}:t??{}}function Wde(t){if(!t)return!0;for(let e in t)return!1;return!0}function UVe(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function _M(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var ZRt,FVe,cc,Vde,BVe,zVe,zw=C(()=>{pp();ZRt=/^[a-z][a-z0-9+.-]*:/i,FVe=t=>ZRt.test(t),cc=t=>(cc=Array.isArray,cc(t)),Vde=cc;BVe=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new st(`${t} must be an integer`);if(e<0)throw new st(`${t} must be a positive integer`);return e},zVe=t=>{try{return JSON.parse(t)}catch{return}}});var Bg,SM=C(()=>{Bg=t=>new Promise(e=>setTim
`):[]}};Yd=new WeakMap,Zd=new WeakMap;SI.NEWLINE_CHARS=new Set([`
`,"\r"]);SI.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function yU(){}function I5(t,e,n){return!e||P5[t]>P5[n]?yU:e[t].bind(e)}function os(t){let e=t.logger,n=t.logLevel??"off";if(!e)return iLt;let r=fWe.get(e);if(r&&r[0]===n)return r[1];let o={error:I5("error",e,n),warn:I5("warn",e,n),info:I5("info",e,n),debug:I5("debug",e,n)};return fWe.set(e,[n,o]),o}var P5,ife,iLt,fWe,jw,wU=C(()=>{zw();P5={off:0,error:200,warn:300,info:400,debug:500},ife=(t,e,n)=>{if(t){if(UVe(P5,t))return t;os(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(P5))}`)}};iLt={error:yU,warn:yU,info:yU,debug:yU},fWe=new WeakMap;jw=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t)});async function*sLt(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new st("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new st("Attempted to iterate over a response with no body");let n=new sfe,r=new SI,o=Gde(t.body);for await(let i of aLt(o))for(let s of r.decode(i)){let a=n.decode(s);a&&(yield a)}for(let i of r.flush()){let s=n.decode(i);s&&(yield s)}}async function*aLt(t){let e=new Uint8Array;for await(let n of t){if(n==null)continue;let r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?IM(n):n,o=new Uint8Array(e.length+r.length);o.set(e),o.set(r,e.length),e=o;let i;for(;(i=uWe(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function lLt(t,e){let n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}var vU,jg,sfe,afe=C(()=>{fp();pp();TM();dWe();TM();x5();T5();wU();pp();jg=class t{constructor(e,n,r){this.iterator=e,vU.set(this,void 0),this.controller=n,Zt(this,vU,r,"f")}static fromSSEResponse(e,n,r,o){let i=!1,s=r?os(r):console;async function*a(){if(i)throw new st("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let l=!1;try{for await(let c of sLt(e,n))if(!l){if(c.data.startsWith("[DONE]")){l=!0;continue}if(c.event===null||!c.event.startsWith("thread.")){let u;try{u=JSON.parse(c.data)}catch(d){throw s.error("Could not parse message into JSON:",c.data),s.error("From chunk:",c.raw),d}if(u&&u.error)throw new Bi(void 0,u.error,void 0,e.headers);yield o?{event:c.event,data:u}:u}else{let u;try{u=JSON.parse(c.data)}catch(d){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),d}if(c.event=="error")throw new Bi(void 0,u.error,u.message,void 0);yield{event:c.event,data:u}}}l=!0}catch(c){if(mU(c))return;throw c}finally{l||n.abort()}}return new t(a,n,r)}static fromReadableStream(e,n,r){let o=!1;async function*i(){let a=new SI,l=Gde(e);for await(let c of l)for(let u of a.decode(c))yield u;for(let c of a.flush())yield c}async function*s(){if(o)throw new st("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let l of i())a||l&&(yield JSON.parse(l));a=!0}catch(l){if(mU(l))return;throw l}finally{a||n.abort()}}return new t(s,n,r)}[(vU=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],n=[],r=this.iterator(),o=i=>({next:()=>{if(i.length===0){let s=r.next();e.push(s),n.push(s)}return i.shift()}});return[new t(()=>o(e),this.controller,de(this,vU,"f")),new t(()=>o(n),this.controller,de(this,vU,"f"))]}toReadableStream(){let e=this,n;return qde({async start(){n=e[Symbol.asyncIterator]()},async pull(r){try{let{value:o,done:i}=await n.next();if(i)return r.close();let s=IM(JSON.stringify(o)+`
`);r.enqueue(s)}catch(o){r.error(o)}},async cancel(){await n.return?.()}})}};sfe=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,o]=lLt(e,":");return o.startsWith(" ")&&(o=o.substring(1)),n==="event"?this.event=o:n==="data"&&this.data.push(o),null}}});async function E5(t,e){let{response:n,requestLogID:r,retryOfRequestLogID:o,startTime:i}=e,s=await(async()=>{if(e.options.stream)return os(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller,t,e.options.__synthesizeEventData):jg.fromSSEResponse(n,e.controller,t,e.options.__synthesizeEventData);if(n.status===204)return null;if(e.options.__binaryResponse)return n;let l=n.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){if(n.headers.get("content-length")==="0")return;let f=await n.json();return lfe(f,n)}return await n.text()})();return os(t).debug(`[${r}] response parsed`,jw({retryOfRequestLogID:o,url:n.url,status:n.status,body:s,durationMs:Date.now()-i})),s}function lfe(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var cfe=C(()=>{afe();wU()});var xU,TI,A5=C(()=>{fp();cfe();TI=class t extends Promise{constructor(e,n,r=E5){super(o=>{o(null)}),this.responsePromise=n,this.parseResponse=r,xU.set(this,void 0),Zt(this,xU,e,"f")}_thenUnwrap(e){return new t(de(this,xU,"f"),this.responsePromise,async(n,r)=>lfe(e(await this.parseResponse(n,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n,request_id:n.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(de(this,xU,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};xU=new WeakMap});var k5,PM,bU,uc,Fn,Xr,Cs,Pn=C(()=>{fp();pp();cfe();A5();zw();PM=class{constructor(e,n,r,o){k5.set(this,void 0),Zt(this,k5,e,"f"),this.options=o,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new st("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await de(this,k5,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(k5=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let n of e.getPaginatedItems())yield n}},bU=class extends TI{constructor(e,n,r){super(e,n,async(o,i)=>new r(o,i.response,await E5(o,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let n of e)yield n}},uc=class extends PM{constructor(e,n,r,o){super(e,n,r,o),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},Fn=class extends PM{constructor(e,n,r,o){super(e,n,r,o),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),n=e[e.length-1]?.id;return n?{...this.options,query:{...b5(this.options.query),after:n}}:null}},Xr=class extends PM{constructor(e,n,r,o){super(e,n,r,o),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...b5(this.options.query),after:e}}:null}},Cs=class extends PM{constructor(e,n,r,o){super(e,n,r,o),this.data=r.data||[],this.has_more=r.has_more||!1,this.next=r.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptio
${i.map(f=>f.error).join(`
`)}
${s}
${d}`)}return s},Q=wLt(xWe)});var II,O5=C(()=>{Ge();Pn();Qt();II=class extends le{list(e,n={},r){return this._client.getAPIList(Q`/chat/completions/${e}/messages`,Fn,{query:n,...r,__security:{bearerAuth:!0}})}}});var Wm=C(()=>{pp()});function SU(t){return t!==void 0&&"function"in t&&t.function!==void 0}function bWe(t,e){let n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function TU(t){return t?.$brand==="auto-parseable-response-format"}function PI(t){return t?.$brand==="auto-parseable-tool"}function CWe(t,e){return!e||!hfe(e)?{...t,choices:t.choices.map(n=>(SWe(n.message.tool_calls),{...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:IU(t,e)}function IU(t,e){let n=t.choices.map(r=>{if(r.finish_reason==="length")throw new bM;if(r.finish_reason==="content_filter")throw new CM;return SWe(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(o=>CLt(e,o))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?bLt(e,r.message.content):null}}});return{...t,choices:n}}function bLt(t,e){return t.response_format?.type!=="json_schema"?null:t.response_format?.type==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function CLt(t,e){let n=t.tools?.find(r=>SU(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:PI(n)?n.$parseRaw(e.function.arguments):n?.function.strict?JSON.parse(e.function.arguments):null}}}function _We(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let n=t.tools?.find(r=>SU(r)&&r.function?.name===e.function.name);return SU(n)&&(PI(n)||n?.function.strict||!1)}function hfe(t){return TU(t.response_format)?!0:t.tools?.some(e=>PI(e)||e.type==="function"&&e.function.strict===!0)??!1}function SWe(t){for(let e of t||[])if(e.type!=="function")throw new st(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function TWe(t){for(let e of t??[]){if(e.type!=="function")throw new st(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new st(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var AM=C(()=>{Wm()});var kM,gfe,yfe=C(()=>{kM=t=>t?.role==="assistant",gfe=t=>t?.role==="tool"});var wfe,R5,L5,PU,EU,D5,AU,Vw,kU,$5,F5,MM,IWe,oC,U5=C(()=>{fp();Wm();oC=class{constructor(){wfe.add(this),this.controller=new AbortController,R5.set(this,void 0),L5.set(this,()=>{}),PU.set(this,()=>{}),EU.set(this,void 0),D5.set(this,()=>{}),AU.set(this,()=>{}),Vw.set(this,{}),kU.set(this,!1),$5.set(this,!1),F5.set(this,!1),MM.set(this,!1),Zt(this,R5,new Promise((e,n)=>{Zt(this,L5,e,"f"),Zt(this,PU,n,"f")}),"f"),Zt(this,EU,new Promise((e,n)=>{Zt(this,D5,e,"f"),Zt(this,AU,n,"f")}),"f"),de(this,R5,"f").catch(()=>{}),de(this,EU,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},de(this,wfe,"m",IWe).bind(this))},0)}_connected(){this.ended||(de(this,L5,"f").call(this),this._emit("connect"))}get ended(){return de(this,kU,"f")}get errored(){return de(this,$5,"f")}get aborted(){return de(this,F5,"f")}abort(){this.controller.abort()}on(e,n){return(de(this,Vw,"f")[e]||(de(this,Vw,"f")[e]=[])).push({listener:n}),this}off(e,n){let r=de(this,Vw,"f")[e];if(!r)return this;let o=r.findIndex(i=>i.listener===n);return o>=0&&r.splice(o,1),this}once(e,n){return(de(this,Vw,"f")[e]||(de(this,Vw,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,r)=>{Zt(this,MM,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,n)})}async done(){Zt(this,MM,!0,"f"),await de(this,EU,"f")}_emit(e,...n){if(de(this,kU,"f"))return;e==="end"&&(Zt(this,kU,!0,"f"),de(this,D5,"f").call(this));let r=de(this,Vw,"f")[e];if(r&&(de(this,Vw,"f")[e]=r.filter(o=>!o.once),r.forEach(({listener:o})=>o(...n))),e==="abort"){let o=n[0];!de(this,MM,"f")&&!r?.length&&Promise.reject(o)
\r `.includes(t[r]);)r++};return s()},Efe=t=>SLt(t,$a.ALL^$a.NUM)});var Afe=C(()=>{afe()});function ILt(t,e){let{id:n,choices:r,created:o,model:i,system_fingerprint:s,...a}=t,l={...a,id:n,choices:r.map(({message:c,finish_reason:u,index:d,logprobs:f,...p})=>{if(!u)throw new st(`missing finish_reason for choice ${d}`);let{content:m=null,function_call:h,tool_calls:g,...y}=c,w=c.role;if(!w)throw new st(`missing role for choice ${d}`);if(h){let{arguments:v,name:x}=h;if(v==null)throw new st(`missing function_call.arguments for choice ${d}`);if(!x)throw new st(`missing function_call.name for choice ${d}`);return{...p,message:{content:m,function_call:{arguments:v,name:x},role:w,refusal:c.refusal??null},finish_reason:u,index:d,logprobs:f}}return g?{...p,index:d,finish_reason:u,logprobs:f,message:{...y,role:w,content:m,refusal:c.refusal??null,tool_calls:g.map((v,x)=>{let{function:b,type:_,id:T,...S}=v,{arguments:P,name:A,...O}=b||{};if(T==null)throw new st(`missing choices[${d}].tool_calls[${x}].id
${V5(t)}`);if(_==null)throw new st(`missing choices[${d}].tool_calls[${x}].type
${V5(t)}`);if(A==null)throw new st(`missing choices[${d}].tool_calls[${x}].function.name
${V5(t)}`);if(P==null)throw new st(`missing choices[${d}].tool_calls[${x}].function.arguments
${V5(t)}`);return{...S,id:T,type:_,function:{...O,name:A,arguments:P}}})}}:{...p,message:{...y,content:m,role:w,refusal:c.refusal??null},finish_reason:u,index:d,logprobs:f}}),created:o,model:i,object:"chat.completion",...s?{system_fingerprint:s}:{}};return CWe(l,e)}function V5(t){return JSON.stringify(t)}var Gs,Ww,OM,iC,kfe,z5,Mfe,Nfe,Ofe,j5,Rfe,MWe,EI,W5=C(()=>{fp();kWe();Wm();AM();Afe();Sfe();EI=class t extends NM{constructor(e){super(),Gs.add(this),Ww.set(this,void 0),OM.set(this,void 0),iC.set(this,void 0),Zt(this,Ww,e,"f"),Zt(this,OM,[],"f")}get currentChatCompletionSnapshot(){return de(this,iC,"f")}static fromReadableStream(e){let n=new t(null);return n._run(()=>n._fromReadableStream(e)),n}static createChatCompletion(e,n,r){let o=new t(n);return o._run(()=>o._runChatCompletion(e,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createChatCompletion(e,n,r){super._createChatCompletion;let o=r?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),de(this,Gs,"m",kfe).call(this);let i=await e.chat.completions.create({...n,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let s of i)de(this,Gs,"m",Mfe).call(this,s);if(i.controller.signal?.aborted)throw new zi;return this._addChatCompletion(de(this,Gs,"m",j5).call(this))}async _fromReadableStream(e,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),de(this,Gs,"m",kfe).call(this),this._connected();let o=jg.fromReadableStream(e,this.controller),i;for await(let s of o)i&&i!==s.id&&this._addChatCompletion(de(this,Gs,"m",j5).call(this)),de(this,Gs,"m",Mfe).call(this,s),i=s.id;if(o.controller.signal?.aborted)throw new zi;return this._addChatCompletion(de(this,Gs,"m",j5).call(this))}[(Ww=new WeakMap,OM=new WeakMap,iC=new WeakMap,Gs=new WeakSet,kfe=function(){this.ended||Zt(this,iC,void 0,"f")},z5=function(n){let r=de(this,OM,"f")[n.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},de(this,OM,"f")[n.index]=r,r)},Mfe=function(n){if(this.ended)return;let r=de(this,Gs,"m",MWe).call(this,n);this._emit("chunk",n,r);for(let o of n.choices){let i=r.choices[o.index];o.delta.content!=null&&i.message?.role==="assistant"&&i.message?.content&&(this._emit("content",o.delta.content,i.message.content),this._emit("content.delta",{delta:o.delta.content,snapshot:i.message.content,parsed:i.message.parsed})),o.delta.refusal!=null&&i.message?.role==="assistant"&&i.message?.refusal&&this._emit("refusal.delta",{delta:o.delta.refusal,snapshot:i.message.refusal}),o.logprobs?.content!=null&&i.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:o.logprobs?.content,snapshot:i.logprobs?.content??[]}),o.logprobs?.refusal!=null&&i.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:o.logprobs?.refusal,snapshot:i.logprobs?.refusal??[]});let s=de(this,Gs,"m",z5).call(this,i);i.finish_reason&&(de(this,Gs,"m",Ofe).call(this,i),s.current_tool_call_index!=null&&de(this,Gs,"m",Nfe).call(this,i,s.current_tool_call_index));for(let a of o.delta.tool_calls??[])s.current_tool_call_index!==a.index&&(de(this,Gs,"m",Ofe).call(this,i),s.current_tool_call_index!=null&&de(this,Gs,"m",Nfe).call(this,i,s.current_tool_call_index)),s.current_tool_call_index=a.index;for(let a of o.delta.tool_calls??[]){let l=i.message.tool_calls?.[a.index];l?.type&&(l?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:l.function?.name,index:a.index,arguments:l.function.arguments,parsed_arguments:l.function.parsed_arguments,arguments_delta:a.function?.arguments??""}):(l?.type,void 0))}}},Nfe=function(n,r){if(de(this,Gs,"m",z5).call(this,n).done_tool_calls.has(r))return;let i=n.message.tool_calls?.[r];if(!i)throw new Error("no tool call snapshot");if(!i.type)throw new Error("tool call snapshot missing `type`");if(i.type==="function"){let s=de(this,Ww,"f")?.tools?.find(a=>SU(a)&&a.function.name===
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
`);this.baseURL=c.baseURL,this.timeout=c.timeout??hme.DEFAULT_TIMEOUT,this.logger=c.logger??console;let u="warn";this.logLevel=u,this.logLevel=ife(c.logLevel,"ClientOptions.logLevel",this)??ife(Xd("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=c.fetchOptions,this.maxRetries=c.maxRetries??2,this.fetch=c.fetch??C5(),Zt(this,tq,GVe,"f");let d=Xd("OPENAI_CUSTOM_HEADERS");if(d){let f={};for(let p of d.split(`
`)){let m=p.indexOf(":");m>=0&&(f[p.substring(0,m).trim()]=p.substring(m+1).trim())}c.defaultHeaders=Fe([f,c.defaultHeaders])}this._options=c,a&&(this._workloadIdentityAuth=new M5(a,this.fetch)),this.apiKey=typeof n=="string"?n:null,this.adminAPIKey=r,this.organization=o,this.project=i,this.webhookSecret=s}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n},r={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(n.has("authorization")||n.has("api-key"))&&!(this._workloadIdentityAuth&&r.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,n={bearerAuth:!0,adminAPIKeyAuth:!0}){return Fe([n.bearerAuth?await this.bearerAuth(e):null,n.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return Fe([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return Fe([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return Fe([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return sWe(e)}getUserAgent(){return`${this.constructor.name}/JS ${nC}`}defaultIdempotencyKey(){return`stainless-node-retry-${zde()}`}makeStatusError(e,n,r,o){return Bi.generate(e,n,r,o)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let n;try{n=await e()}catch(r){throw r instanceof st?r:new st(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof n!="string"||!n)throw new st(`Expected 'apiKey' function argument to return a string but it returned ${n}`);return this.apiKey=n,!0}buildURL(e,n,r){let o=!de(this,mme,"m",rHe).call(this)&&r||this.baseURL,i=FVe(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery(),a=Object.fromEntries(i.searchParams);return(!Wde(s)||!Wde(a))&&(n={...a,...s,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(i.search=this.stringifyQuery(n)),i.toString()}async prepareOptions(e){(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:n,options:r}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,r){return this.request(Promise.resolve(r).then(o=>({method:e,path:n,...o})))}request(e,n=null){return new TI(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,r){let o=await e,i=o.maxRetries??this.maxRetries;n==null&&(n=i),await this.prepareOptions(o);let{req:s,url:a,timeout:l}=await this.buildRequest(o,{retryCount:i-n});await this.prepareRequest(s,{url:a,options:o});let c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(os(this).debug(`[${c}] sending request`,jw({retryOfRequestLogID:r,method:o.method,url:a,options:o,headers:s.headers})),o.signal?.aborted)throw new zi;let f=o.__security??{bearerAuth:!0},p=new AbortController,m=await this.fetchWithAuth(a,s,l,p,f).catch(hU),h=Date.now();if(m instanceof globalThis.Error){let w=`retrying, ${n} attempts remaining`;if(o.signal?.aborted)throw new zi;let v=mU(m)||/timed? ?out/i.test(String(m)+("cause"in m?String(m.cause):""));if(n)return os(this).info(`[${c}] connection ${v?"timed out":"failed"} - ${w}`),os(this).debug(`[${c}] connection ${v?"timed out":"failed"} (${w})`,jw({retryOfRequestLogID:r,url:a,dura
`)}function uHe(t,e){let n=[];for(let[r,o]of Object.entries(t.properties??{}))o.description&&e<2&&n.push(`// ${o.description}`),t.required?.includes(r)?n.push(`${r}: ${rq(o,e)},`):n.push(`${r}?: ${rq(o,e)},`);return n.map(r=>" ".repeat(e)+r).join(`
`)}function rq(t,e){if(W1t(t))return t.anyOf.map(n=>rq(n,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(n=>`"${n}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",uHe(t,e+2),"}"].join(`
`);case"array":return t.items?`${rq(t.items,e)}[]`:"any[]";default:return""}}function oq(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}function PN(t){return"type"in t&&t.type!=="function"}function dHe(t){return typeof t=="object"&&t!==null&&"extras"in t&&typeof t.extras=="object"&&t.extras!==null&&"providerToolDefinition"in t.extras&&typeof t.extras.providerToolDefinition=="object"&&t.extras.providerToolDefinition!==null}function fHe(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function XI(t){return typeof t=="object"&&t!==null&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null&&"customTool"in t.metadata&&typeof t.metadata.customTool=="object"&&t.metadata.customTool!==null}function iq(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function pHe(t){if(t.type==="custom_tool_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:t.name,isCustomTool:!0,args:{input:t.input}}}function mHe(t){if(t.type==="computer_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:"computer_use",isComputerTool:!0,args:{action:t.action}}}function hHe(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function gHe(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isCustomTool"in t&&t.isCustomTool===!0}function yHe(t){let e=()=>{if(t.custom.format){if(t.custom.format.type==="grammar")return{type:"grammar",definition:t.custom.format.grammar.definition,syntax:t.custom.format.grammar.syntax};if(t.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:t.custom.name,description:t.custom.description,format:e()}}function wHe(t){let e=()=>{if(t.format){if(t.format.type==="grammar")return{type:"grammar",grammar:{definition:t.format.definition,syntax:t.format.syntax}};if(t.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:t.name,description:t.description,format:e()}}}var EN=C(()=>{pI();Bd();Bu()});var yme=C(()=>{Ql()});var uq={};zn(uq,{ZodISODate:()=>aq,ZodISODateTime:()=>sq,ZodISODuration:()=>cq,ZodISOTime:()=>lq,date:()=>vme,datetime:()=>wme,duration:()=>bme,time:()=>xme});function wme(t){return $se(sq,t)}function vme(t){return Fse(aq,t)}function xme(t){return Use(lq,t)}function bme(t){return Bse(cq,t)}var sq,aq,lq,cq,dq=C(()=>{Ql();fq();sq=ce("ZodISODateTime",(t,e)=>{Bie.init(t,e),Uo.init(t,e)});aq=ce("ZodISODate",(t,e)=>{zie.init(t,e),Uo.init(t,e)});lq=ce("ZodISOTime",(t,e)=>{jie.init(t,e),Uo.init(t,e)});cq=ce("ZodISODuration",(t,e)=>{Vie.init(t,e),Uo.init(t,e)})});var xHe,K1t,AN,Cme=C(()=>{Ql();Ql();xHe=(t,e)=>{DF.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>FF(t,n)},flatten:{value:n=>$F(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},K1t=ce("ZodError",xHe),AN=ce("ZodError",xHe,{Parent:Error})});var _me,Sme,Tme,Ime,Pme=C(()=>{Ql();Cme();_me=C6(AN),Sme=_6(AN),Tme=S6(AN),Ime=T6(AN)});function Eme(t){return Rse(UU,t)}function G1t(t){return B6(Mme,t)}function Y1t(t){return qF(pq,t)}function Z1t(t){return z6(ev,t)}function J1t(t){return j6(ev,t)}function X1t(t){return V6(ev,t)}function Q1t(t){return W6(ev,t)}function eDt(t){return H6(Nme,t)}function tDt(t){return K6(Ome,t)}function nDt(t){return q6(Rme,t)}function rDt(t){return G6(Lme,t)}function oDt(t){return Y6(Dme,t)}function iDt(t){return Z6($me,t)}function sDt(t){return J6(Fme,t)}function aDt(t){return X6(Ume,t)}function lDt(t){return Q6(Bme,t)}function cDt(t){return e3(zme,t)}function uDt(t){return t3(jme,t)}function dDt(t){return n3(Vme,t)}function fDt(t){return r3(Wme,t)}function pDt(t){return o3(Hme,t)}function mDt(t){return i3(Kme,t)}function hDt(t){return s3(qme,t)}function gDt(t,e,n={}){return wae(bHe,t,e,n)}function CHe(t){return zse(BU,t)}function Ame(t){return Vse(kN,t)}function yDt(t){return Wse(kN,t)}function wDt(t){return Hse(kN,t)}fu
]))`;continue}else if(o[c]==="$"){i+=`($|(?=[\r
]))`;continue}}if(r.s&&o[c]==="."){i+=a?`${o[c]}\r
`:`[${o[c]}\r
]`;continue}i+=o[c],o[c]==="\\"?s=!0:a&&o[c]==="]"?a=!1:!a&&o[c]==="["&&(a=!0)}try{let c=new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return i}});function Iq(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===he.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,o)=>({...r,[o]:_n(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let n={type:"object",additionalProperties:_n(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===he.ZodString&&t.keyType._def.checks?.length){let r=Object.entries(Sq(t.keyType._def,e)).reduce((o,[i,s])=>i==="type"?o:{...o,[i]:s},{});return{...n,propertyNames:r}}else if(t.keyType?._def.typeName===he.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};return n}var Pq=C(()=>{_g();_s();Tq()});function A6e(t,e){if(e.mapStrategy==="record")return Iq(t,e);let n=_n(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=_n(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}var _he=C(()=>{_s();Pq()});function k6e(t){let e=t.values,r=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(r.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}var She=C(()=>{});function M6e(){return{not:{}}}var The=C(()=>{});function N6e(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ihe=C(()=>{});function R6e(t,e){if(e.target==="openApi3")return O6e(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in WU&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((o,i)=>{let s=WU[i._def.typeName];return s&&!o.includes(s)?[...o,s]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.reduce((o,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...o,s];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(r.length===n.length){let o=r.filter((i,s,a)=>a.indexOf(i)===s);return{type:o.length>1?o:o[0],enum:n.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(i=>!r.includes(i))],[])};return O6e(t,e)}var WU,O6e,Eq=C(()=>{_s();WU={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};O6e=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,o)=>_n(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0}});function L6e(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:WU[t.innerType._def.typeName],nullable:!0}:{type:[WU[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=_n(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=_n(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}var Phe=C(()=>{_s();Eq()});function D6e(t,e){let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",lhe(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?Ar(n,"minimum"
Details: ${m.message}`),_ae(m)&&(h=`${h}
${se.prettifyError(m)}`),new S2(h,JSON.stringify(e))}else{let m=Yo(o,this.schema);if(!m.valid){let h="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(h=`${h}
Details: ${m.errors.map(g=>`${g.keywordLocation}: ${g.error}`).join(`
`)}`),new S2(h,JSON.stringify(e))}i=o}let s=Wb(n),a=Ws.configure(s.callbacks,this.callbacks,s.tags||r,this.tags,s.metadata,this.metadata,{verbose:this.verbose}),l;Db(e)&&(l=e.id),!l&&HFe(s)&&(l=s.toolCall.id);let c=await a?.handleToolStart(this.toJSON(),typeof e=="string"?e:JSON.stringify(e),s.runId,void 0,void 0,void 0,s.runName,l);delete s.runId;let u;try{let m=await this._call(i,c,s);u=Vue(m)?await Xje(m,async h=>{try{await c?.handleToolEvent(h)}catch(g){await c?.handleToolError(g)}}):m}catch(m){throw await c?.handleToolError(m),m}let d,f;if(this.responseFormat==="content_and_artifact")if(Array.isArray(u)&&u.length===2)[d,f]=u;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
Result: ${JSON.stringify(u)}`);else d=u;let p=C$t({content:d,artifact:f,toolCallId:l,name:this.name,metadata:this.metadata});return await c?.handleToolEnd(p),p}},y3e=class extends g3e{constructor(e){super(e);I(this,"schema",we.object({input:we.string().optional()}).transform(e=>e.input))}call(e,n){let r=typeof e=="string"||e==null?{input:e}:e;return super.call(r,n)}},w3e=class extends y3e{constructor(e){super(e);I(this,"name");I(this,"description");I(this,"func");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}static lc_name(){return"DynamicTool"}async call(e,n){let r=Wb(n);return r.runName===void 0&&(r.runName=this.name),super.call(e,r)}_call(e,n,r){return this.func(e,n,r)}},b$t=class extends g3e{constructor(e){super(e);I(this,"description");I(this,"func");I(this,"schema");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}static lc_name(){return"DynamicStructuredTool"}async call(e,n,r){let o=Wb(n);return o.runName===void 0&&(o.runName=this.name),super.call(e,o,r)}_call(e,n,r){return this.func(e,n,r)}}});var Xhe=C(()=>{Gm();Jo();gp()});var v3e=C(()=>{});var x3e=C(()=>{});var b3e=C(()=>{});var C3e=C(()=>{});var _3e=C(()=>{});var S$t,T$t,I$t,P$t,E$t,A$t,k$t,M$t,N$t,O$t,vKn,S3e=C(()=>{Kr();gp();tv();S$t=se.object({type:se.literal("screenshot")}),T$t=se.object({type:se.literal("click"),x:se.number(),y:se.number(),button:se.enum(["left","right","wheel","back","forward"]).default("left")}),I$t=se.object({type:se.literal("double_click"),x:se.number(),y:se.number(),button:se.enum(["left","right","wheel","back","forward"]).default("left")}),P$t=se.object({type:se.literal("drag"),path:se.array(se.object({x:se.number(),y:se.number()}))}),E$t=se.object({type:se.literal("keypress"),keys:se.array(se.string())}),A$t=se.object({type:se.literal("move"),x:se.number(),y:se.number()}),k$t=se.object({type:se.literal("scroll"),x:se.number(),y:se.number(),scroll_x:se.number(),scroll_y:se.number()}),M$t=se.object({type:se.literal("type"),text:se.string()}),N$t=se.object({type:se.literal("wait"),duration:se.number().optional()}),O$t=se.discriminatedUnion("type",[S$t,T$t,I$t,P$t,E$t,A$t,k$t,M$t,N$t]),vKn=se.object({action:O$t})});var R$t,_Kn,T3e=C(()=>{gp();tv();R$t=se.object({type:se.literal("exec"),command:se.array(se.string()),env:se.record(se.string(),se.string()).optional(),working_directory:se.string().optional(),timeout_ms:se.number().optional(),user:se.string().optional()}),_Kn=se.discriminatedUnion("type",[R$t])});var PKn,I3e=C(()=>{gp();tv();PKn=se.object({commands:se.array(se.string()).describe("Array of shell commands to execute"),timeout_ms:se.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:se.number().optional().describe("Optional maximum number of characters to return from each command")})});var L$t,D$t,$$t,MKn,P3e=C(()=>{gp();tv();L$t=se.object({type:se.literal("create_file"),path:se.string(),diff:se.string()}),D$t=se.object({type:se.literal("update_file"),path:se.string(),diff:se.string()}),$$t=se.object({type:se.literal("delete_file"),path:se.string()}),MKn=se.discriminatedUnion("type",[L$t,D$t,$$t])});var E3e=C(()=>{Xhe();v3e();x3e();b3e();C3e();_3e();S3e();T3e();I3e();P3e()});var A3e=C(()=>{jm();gp();aI()});var k3e=C(()=>{NN()});var M3e=C(()=>{NN();Rq()});var Yg=C(()=>{wC();vC();xC();HU();NN();kq();Whe();Rq();Dq();qhe();Ghe();p3e();Yhe();m3e();Zhe();h3e();Xhe();E3e();A3e();k3e();M3e();Gm()});var $q,N3e=C(()=>{dU();fU();Jo();$q=class extends Qb{constructor(n){let r={maxConcurrency:2,...n};super(r);this.model="jina-clip-v2";this.batchSize=24;this.baseUrl="https://api.jina.ai/v1/embeddings";this.stripNewLines=!0;this.dimensions=1024;this.normalized=!0;let o=r?.apiKey||In("JINA_API_KEY")||In("JINA_AUTH_TOKEN");if(!o)throw new Error("Jina API key not found");this.apiKey=o,this.model=r?.model??r?.modelName??this.model,this.baseUrl=r?.baseUrl??this.baseUrl,this.dimensions=r?.dimensions??this.dimensions,this.batchSize=r?.batchSi
without CORS Error: `+Xt(r)+`
with CORS Error: `+Xt(o);throw new Error(i)}}}}});function L3e(t){return t.replace(/\\/g,"/").replace(/\/+$/,"")}function Jm(t){return(t.miyoServerUrl||"").trim()}function Fa(t){return!t.enableMiyo||!Qhe()?!1:!R3e.Platform.isMobile||!!Jm(t)}function Jg(t){return t.vault.getName()}function Uq(t,e){let n=L3e(e).replace(/^\/+/,""),r=Jg(t);return r?`${r}/${n}`:n}function i0(t,e){let n=L3e(e),r=Jg(t);if(!r)return n;let o=`${r}/`;return n.startsWith(o)?n.slice(o.length):n}var R3e,yp=C(()=>{ns();R3e=require("obsidian")});var D3e,Bq,$3e=C(()=>{ye();Se();qe();D3e=require("obsidian"),Bq=class t{constructor(){this.cachedBaseUrl=null}static getInstance(){return t.instance||(t.instance=new t),t.instance}async resolveBaseUrl(e={}){let n=(e.overrideUrl||"").trim();if(n.length>0)return this.normalizeBaseUrl(n);if(this.cachedBaseUrl&&!e.forceRefresh)return this.cachedBaseUrl;if(!D3e.Platform.isDesktopApp)return null;let r=await this.readServiceConfig();if(r==="missing"){let i=this.getDefaultBaseUrl();return this.cachedBaseUrl=null,q().debug&&k(`Miyo service discovery file missing; using fallback ${i}`),i}if(!r)return this.cachedBaseUrl=null,null;let o=this.normalizeBaseUrl(`http://${r.host}:${r.port}`);return this.cachedBaseUrl=o,o}normalizeBaseUrl(e){return e.trim().replace(/\/+$/,"")}getDefaultBaseUrl(){return this.normalizeBaseUrl("http://127.0.0.1:8742")}getServiceFilePaths(){let e=this.getNodeRequire();if(!e)return[];let n=e("os"),r=e("process"),o=e("path"),i=n.homedir(),s=n.platform(),a=r.env||{};if(s==="win32"){let l=(a.LOCALAPPDATA||"").trim(),c=(a.APPDATA||"").trim();return[l,o.join(i,"AppData","Local"),c,o.join(i,"AppData","Roaming")].filter((d,f,p)=>d.length>0&&p.indexOf(d)===f).map(d=>o.join(d,"Miyo","service.json"))}return s==="linux"?[o.join(i,".config","Miyo","service.json")]:s==="darwin"?[o.join(i,"Library","Application Support","Miyo","service.json")]:(ee(`Miyo service discovery unsupported platform: ${s}`),[])}async readServiceConfig(){let e=this.getServiceFilePaths();if(e.length===0)return null;let n=this.getNodeRequire();if(!n)return null;let r=n("fs"),o=!1;for(let i of e)try{let s=await r.promises.readFile(i,"utf8"),a=JSON.parse(s);return!a.host||typeof a.host!="string"?(ee("Miyo service discovery missing host"),null):typeof a.port!="number"||Number.isNaN(a.port)?(ee("Miyo service discovery missing port"),null):(q().debug&&k(`Miyo service discovery resolved host=${a.host} port=${a.port}`),a)}catch(s){if(this.isMissingFileError(s)){o=!0;continue}return q().debug&&ee(`Miyo service discovery failed: ${Xt(s)}`),null}return o?"missing":null}isMissingFileError(e){return e?.code==="ENOENT"}getNodeRequire(){let e=window?.require;return typeof e=="function"?e:null}}});var F3e,wp,RN=C(()=>{Su();ye();$3e();Se();qe();F3e=require("obsidian"),wp=class{constructor(){this.discovery=Bq.getInstance()}async resolveBaseUrl(e){let n=await this.discovery.resolveBaseUrl({overrideUrl:e});if(!n)throw new Error("Miyo base URL not available");return n}async isBackendAvailable(e){try{let n=await this.resolveBaseUrl(e),r=await this.requestJson(n,"/v0/health",{method:"GET"});return r?.status!=="ok"?(ee(`Miyo health check failed: status="${r?.status??"unknown"}"`),!1):!0}catch(n){return ee(`Miyo backend availability check failed: ${Xt(n)}`),!1}}async getFolder(e,n){return this.requestJson(e,"/v0/folder",{method:"GET",query:{path:n}})}async scanFolder(e,n,r=!1){return this.requestJson(e,"/v0/scan",{method:"POST",body:{path:n,force:r}})}async listFolderFiles(e,n){return this.requestJson(e,"/v0/folder/files",{method:"GET",query:{folder_name:n.folderName,title:n.title,file_path:n.filePath,mtime_after:n.mtimeAfter,mtime_before:n.mtimeBefore,offset:n.offset,limit:n.limit,order_by:n.orderBy}})}async getDocumentsByPath(e,n,r){return this.requestJson(e,"/v0/folder/documents",{method:"GET",query:{path:r,folder_name:n}})}async search(e,n,r,o,i){let s={query:r,...n?{folder_name:n}:{},limit:o,...i&&i.length>0?{filters:i}:{}};return q().debug&&k("Miyo search request:",{baseUrl:e,payload:s}),this.requestJson(e,"/v0/search",{method:"POST",body:s})}async searchRe
- `),H$t={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported.
Supported languages are:
- ${W$t}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.oramasearch.com/open-source/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.oramasearch for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead.
Input vectors must be of the size declared in the schema, as calculating similarity between vectors of different sizes can lead to unexpected results.`,WRONG_SEARCH_PROPERTY_TYPE:'Property "%s" is not searchable. Only "string" properties are searchable.',FACET_NOT_SUPPORTED:`Facet doens't support the type "%s".`,INVALID_DISTANCE_SUFFIX:'Invalid distance suffix "%s". Valid suffixes are: cm, m, km, mi, yd, ft.',INVALID_SEARCH_MODE:'Invalid search mode "%s". Valid modes are: "fulltext", "vector", "hybrid".',MISSING_VECTOR_AND_SECURE_PROXY:"No vector was provided and no secure proxy was configured. Please provide a vector or configure an Orama Secure Proxy to perform hybrid search.",MISSING_TERM:'"term" is a required parameter when performing hybrid search. Please provide a search term.',INVALID_VECTOR_INPUT:'Invalid "vector" property. Expected an object with "value" and "property" properties, but got "%s" instead.',PLUGIN_CRASHED:"A plugin crashed during initialization. Please check the error message for more information:",PLUGIN_SECURE_PROXY_NOT_FOUND:`Could not find '@orama/secure-proxy-plugin' installed in your Orama instance.
Please install it before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL:`Could not find a chat model defined in the secure proxy plugin configuration.
Please provide a chat model before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages."}});function Z3e(t){return{raw:Number(t),formatted:s0(t)}}function J3e(t){if(t.id){if(typeof t.id!="string")throw qt("DOCUMENT_ID_MUST_BE_STRING",typeof t.id);return t.id}return GU()}function nge(t,e){for(let[n,r]of Object.entries(e)){let o=t[n];if(!(typeof o>"u")&&!(r==="geopoint"&&typeof o=="object"&&typeof o.lon=="number"&&typeof o.lat=="number")&&!(r==="enum"&&(typeof o=="string"||typeof o=="number"))){if(r==="enum[]"&&Array.isArray(o)){let i=o.length;for(let s=0;s<i;s++)if(typeof o[s]!="string"&&typeof o[s]!="number")return n+"."+s;continue}if(ov(r)){let i=oge(r);if(!Array.isArray(o)||o.length!==i)throw qt("INVALID_INPUT_VECTOR",n,i,o.length);continue}if(FN(r)){if(!Array.isArray(o))return n;let i=rge(r),s=o.length;for(let a=0;a<s;a++)if(typeof o[a]!==i)return n+"."+a;continue}if(typeof r=="object"){if(!o||typeof o!="object")return n;let i=nge(o,r);if(i)return n+"."+i;continue}if(typeof o!==r)return n}}}function X3e(t){return t==="geopoint"}function ov(t){return typeof t=="string"&&/^vector\[\d+\]$/.test(t)}function FN(t){return typeof t=="string"&&K$t[t]}function rge(t){return q$t[t]}function oge(t){let e=Number(t.slice(7,-1));switch(!0){case isNaN(e):throw qt("INVALID_VECTOR_VALUE",t);case e<=0:throw qt("INVALID_VECTOR_SIZE",t);default:return e}}var K$t,q$t,YU=C(()=>{Ua();ss();ss();K$t={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},q$t={"string[]":"string","number[]":"number","boolean[]":"boolean","enum[]":"enum"}});function Q3e(){return{idToInternalId:new Map,internalIdToId:[],save:G$t,load:Y$t}}function G$t(t){return{internalIdToId:t.internalIdToId}}function Y$t(t,e){let{internalIdToId:n}=e;t.internalDocumentIDStore.idToInternalId.clear(),t.internalDocumentIDStore.internalIdToId=[];let r=n.length;for(let o=0;o<r;o++){let i=n[o];t.internalDocumentIDStore.idToInternalId.set(i,o+1),t.internalDocumentIDStore.internalIdToId.push(i)}}function mo(t,e){if(typeof e=="string"){let n=t.idToInternalId.get(e);if(n)return n;let r=t.idToInternalId.size+1;return t.idToInternalId.set(e,r),t.internalIdToId.push(e),r}return e>t.internalIdToId.length?mo(t,e.toString()):e}function vp(t,e){if(t.internalIdToId.length<e)throw new Error(`Invalid internalId ${e}`);return t.internalIdToId[e-1]}var xp=C(()=>{});function J$t(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}function X$t(t,e){let n=mo(t.sharedInternalDocumentStore,e);return t.docs[n]}function Q$t(t,e){let n=e.length,r=Array.from({length:n});for(let o=0;o<n;o++){let i=mo(t.sharedInternalDocumentStore,e[o]);r[o]=t.docs[i]}return r}function eFt(t){return t.docs}function tFt(t,e,n){let r=mo(t.sharedInternalDocumentStore,e);return typeof t.docs[r]<"u"?!1:(t.docs[r]=n,t.count++,!0)}function nFt(t,e){let n=mo(t.sharedInternalDocumentStore,e);return typeof t.docs[n]>"u"?!1:(delete t.docs[n],t.count--,!0)}function rFt(t){return t.count}function oFt(t,e){let n=e;return{docs:n.docs,count:n.count,sharedInternalDocumentStore:t}}function iFt(t){return{docs:t.docs,count:t.count}}function eKe(){return{create:J$t,get:X$t,getMultiple:Q$t,getAll:eFt,store:tFt,remove:nFt,count:rFt,load:oFt,save:iFt}}var ige=C(()=>{xp()});function nKe(t,e){let n=[],r=t.plugins?.length;if(!r)return n;for(let o=0;o<r;o++)try{let i=t.plugins[o];typeof i[e]=="function"&&n.push(i[e])}catch(i){throw console.error("Caught error in getAllPluginsByHook:",i),qt("PLUGIN_CRASHED")}return n}var tKe,rKe=C(()=>{Ua();tKe=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeLoad","afterLoad","afterCreate"]});function Qm(t,e,n,r){if(t.some(Ss))return(async()=>{for(let i of t)await i(e,n,r)})();for(let i of t)i(e,n,r)}function a0(t,e,n){if(t.some(Ss))return(async()=>{for(let o of t)await o(e,n)})();for(let o of
which is longer than the specified ${this.chunkSize}`),o.length>0)){let c=this.joinDocs(o,n);for(c!==null&&r.push(c);i>this.chunkOverlap||i+l+o.length*n.length>this.chunkSize&&i>0;)i-=await this.lengthFunction(o[0]),o.shift()}o.push(a),i+=l}let s=this.joinDocs(o,n);return s!==null&&r.push(s),r}},Xge=class Jge extends _5e{constructor(n){super(n);I(this,"separators",[`
`,`
`," ",""]);this.separators=n?.separators??this.separators,this.keepSeparator=n?.keepSeparator??!0}static lc_name(){return"RecursiveCharacterTextSplitter"}async _splitText(n,r){let o=[],i=r[r.length-1],s;for(let u=0;u<r.length;u+=1){let d=r[u];if(d===""){i=d;break}if(n.includes(d)){i=d,s=r.slice(u+1);break}}let a=this.splitOnSeparator(n,i),l=[],c=this.keepSeparator?"":i;for(let u of a)if(await this.lengthFunction(u)<this.chunkSize)l.push(u);else{if(l.length){let d=await this.mergeSplits(l,c);o.push(...d),l=[]}if(!s)o.push(u);else{let d=await this._splitText(u,s);o.push(...d)}}if(l.length){let u=await this.mergeSplits(l,c);o.push(...u)}return o}async splitText(n){return this._splitText(n,this.separators)}static fromLanguage(n,r){return new Jge({...r,separators:Jge.getSeparatorsForLanguage(n)})}static getSeparatorsForLanguage(n){if(n==="cpp")return[`
class `,`
void `,`
int `,`
float `,`
double `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
`,`
`," ",""];if(n==="go")return[`
func `,`
var `,`
const `,`
type `,`
if `,`
for `,`
switch `,`
case `,`
`,`
`," ",""];if(n==="java")return[`
class `,`
public `,`
protected `,`
private `,`
static `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
`,`
`," ",""];if(n==="js")return[`
function `,`
const `,`
let `,`
var `,`
class `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
default `,`
`,`
`," ",""];if(n==="php")return[`
function `,`
class `,`
if `,`
foreach `,`
while `,`
do `,`
switch `,`
case `,`
`,`
`," ",""];if(n==="proto")return[`
message `,`
service `,`
enum `,`
option `,`
import `,`
syntax `,`
`,`
`," ",""];if(n==="python")return[`
class `,`
def `,`
def `,`
`,`
`," ",""];if(n==="rst")return[`
===
`,`
---
`,`
***
`,`
.. `,`
`,`
`," ",""];if(n==="ruby")return[`
def `,`
class `,`
if `,`
unless `,`
while `,`
for `,`
do `,`
begin `,`
rescue `,`
`,`
`," ",""];if(n==="rust")return[`
fn `,`
const `,`
let `,`
if `,`
while `,`
for `,`
loop `,`
match `,`
const `,`
`,`
`," ",""];if(n==="scala")return[`
class `,`
object `,`
def `,`
val `,`
var `,`
if `,`
for `,`
while `,`
match `,`
case `,`
`,`
`," ",""];if(n==="swift")return[`
func `,`
class `,`
struct `,`
enum `,`
if `,`
for `,`
while `,`
do `,`
switch `,`
case `,`
`,`
`," ",""];if(n==="markdown")return[`
## `,`
### `,`
#### `,`
##### `,`
###### `,"```\n\n",`
***
`,`
---
`,`
___
`,`
`,`
`," ",""];if(n==="latex")return[`
\\chapter{`,`
\\section{`,`
\\subsection{`,`
\\subsubsection{`,`
\\begin{enumerate}`,`
\\begin{itemize}`,`
\\begin{description}`,`
\\begin{list}`,`
\\begin{quote}`,`
\\begin{quotation}`,`
\\begin{verse}`,`
\\begin{verbatim}`,`
\\begin{align}`,"$$","$",`
`,`
`," ",""];if(n==="html")return["<body>","<div>","<p>","<br>","<li>","<h1>","<h2>","<h3>","<h4>","<h5>","<h6>","<span>","<table>","<tr>","<td>","<th>","<ul>","<ol>","<header>","<footer>","<nav>","<head>","<style>","<script>","<meta>","<title>"," ",""];if(n==="sol")return[`
pragma `,`
using `,`
contract `,`
interface `,`
library `,`
constructor `,`
type `,`
function `,`
event `,`
modifier `,`
error `,`
struct `,`
enum `,`
if `,`
for `,`
while `,`
do while `,`
assembly `,`
`,`
`," ",""];throw new Error(`Language ${n} is not supported.`)}}});var T5e=C(()=>{S5e()});var GN,p0,Qge=C(()=>{ye();Se();GN=class GN{constructor(){this.bytesUsed=0;let e=q(),n=Math.min(1e3,Math.max(20,e.lexicalSearchRamLimit||100));this.maxBytes=n*GN.MB_TO_BYTES,this.candidateLimit=Math.min(GN.DEFAULT_CANDIDATE_LIMIT,Math.floor(n*5))}getMaxBytes(){return this.maxBytes}getCandidateLimit(){return this.candidateLimit}getBytesUsed(){return this.bytesUsed}canAddContent(e){return this.bytesUsed+e<=this.maxBytes}addBytes(e){this.bytesUsed+=e}reset(){let e=this.bytesUsed;this.bytesUsed=0,k(`MemoryManager: Reset memory tracking (was using ${e} bytes, max: ${this.maxBytes} bytes)`)}getUsagePercent(){return Math.round(this.bytesUsed/this.maxBytes*100)}static getByteSize(e){return new TextEncoder().encode(e).length}};GN.DEFAULT_CANDIDATE_LIMIT=500,GN.MB_TO_BYTES=1024*1024;p0=GN});function PC(t){return eye||(eye=new tye(t)),eye}var dG,uG,tye,eye,iB=C(()=>{ye();It();dG=require("obsidian");T5e();Qge();uG={maxChars:JV,overlap:0,maxBytesTotal:10*1024*1024},tye=class{constructor(e){this.app=e;this.cache=new Map;this.memoryUsage=0}getCacheKey(e,n){return`${e}:${n.maxChars}:${n.overlap}`}createSplitter(e){return Xge.fromLanguage("markdown",{chunkSize:e.maxChars,chunkOverlap:e.overlap,separators:[`
`,`
`,". "," ",""],keepSeparator:!1})}async getChunks(e,n={}){try{if(!Array.isArray(e))return ee("ChunkManager: Invalid notePaths provided"),[];if(e.length===0)return[];e.length>1e3&&(ee("ChunkManager: Too many note paths, limiting to 1000"),e=e.slice(0,1e3));let r=e.filter(l=>!(!l||typeof l!="string"||l.startsWith("/")||l.startsWith("../")||l.includes("/../")||l.endsWith("/..")));if(r.length===0)return ee("ChunkManager: No valid note paths provided"),[];let o={...uG,...n},i=[],s=0,a=0;for(let l of r){let c=this.getCacheKey(l,o),u=this.cache.get(c);if(u&&u.length>0){let d=this.app.vault.getAbstractFileByPath(l);if(d&&d instanceof dG.TFile&&d.stat.mtime>u[0].mtime){let f=this.calculateChunkBytes(u);this.cache.delete(c),this.memoryUsage-=f,u=void 0}}if(!u&&(u=await this.generateChunksForNote(l,o),u.length>0)){let d=this.calculateChunkBytes(u);this.memoryUsage+d<=o.maxBytesTotal?(this.cache.set(c,u),this.memoryUsage+=d):(s+=1,a+=d)}i.push(...u)}if(s>0){let l=(a/1024/1024).toFixed(1);k(`ChunkManager: Cache budget reached, skipped caching ${s} notes (${l}MB total)`)}return k(`ChunkManager: Retrieved ${i.length} chunks from ${r.length} notes (${this.formatMemoryUsage()})`),i}catch(r){return ee("ChunkManager: Failed to get chunks",r),[]}}async getChunkText(e){return(await this.ensureChunkExists(e))?.content||""}async ensureChunkExists(e){let[n]=e.split("#"),o=(await this.getValidatedChunks(n)).find(i=>i.id===e);return o||ee(`ChunkManager: Chunk ${e} not found after regeneration`),o||null}async getValidatedChunks(e){let n;for(let[o,i]of this.cache.entries())if(o.startsWith(e+":")){n=i;break}if(!n&&(k(`ChunkManager: Cache miss for ${e}, regenerating...`),n=await this.regenerateChunks(e),!n||n.length===0))return ee(`ChunkManager: Failed to regenerate chunks for ${e}`),[];let r=this.app.vault.getAbstractFileByPath(e);return r&&r instanceof dG.TFile&&n.length>0&&r.stat.mtime>n[0].mtime&&(k(`ChunkManager: File ${e} modified, regenerating chunks`),n=await this.regenerateChunks(e),!n||n.length===0)?(ee(`ChunkManager: Failed to regenerate chunks after modification for ${e}`),[]):n}getChunkTextSync(e){let[n]=e.split("#");for(let[r,o]of this.cache.entries())if(r.startsWith(n+":")){let i=o.find(s=>s.id===e);if(i)return i.content}return ee(`ChunkManager: Chunk not in cache: ${e} (use async getChunkText for auto-regeneration)`),""}async regenerateChunks(e){try{let n=await this.generateChunksForNote(e,uG),r=this.getCacheKey(e,uG);if(n.length>0){let o=this.calculateChunkBytes(n);if(this.memoryUsage+o<=uG.maxBytesTotal){let i=this.cache.get(r);i&&(this.memoryUsage-=this.calculateChunkBytes(i)),this.cache.set(r,n),this.memoryUsage+=o}else k(`ChunkManager: Cannot cache regenerated chunks for ${e}, would exceed memory budget`)}return n}catch(n){return ee(`ChunkManager: Failed to regenerate chunks for ${e}`,n),[]}}clearCache(){this.cache.clear(),this.memoryUsage=0,k("ChunkManager: Cache cleared")}async generateChunksForNote(e,n){try{let r=this.app.vault.getAbstractFileByPath(e);if(!r||!(r instanceof dG.TFile))return[];let o=await this.safeReadFile(r);if(!o?.trim())return[];let i=this.app.metadataCache.getFileCache(r),s=(i?.headings||[]).slice().sort((p,m)=>p.position.start.offset-m.position.start.offset),a=[],l=0,c=this.findFrontmatterEnd(o,i?.frontmatter),u=o.substring(c),d=s.length>0?s[0].heading:"";if(`
NOTE TITLE: [[${r.basename}]]
NOTE BLOCK CONTENT:
`.length+u.length<=n.maxChars){let p=await this.processContentSection(u,d,r,l,n);return a.push(...p),a}if(s.length===0){let p=await this.processContentSection(u,"",r,l,n);return a.push(...p),a}for(let p=0;p<s.length;p++){let m=s[p],h=s[p+1],g=p===0?c:m.position.start.offset,y=h?.position.start.offset||o.length,w=o.substring(g,y),v=await this.processContentSection(w,m.heading,r,l,n);a.push(...v),l+=v.length}return a}catch(r){return ee(`ChunkManager: Failed to chunk note ${e}`,r),[]}}async processContentSection(e,n,r,o,i){let s=r.basename,a=[],l=`
NOTE TITLE: [[${s}]]
NOTE BLOCK CONTENT:
`,c=l+e;if(c.length<=i.maxChars){let u=this.generateChunkId(r.path,o),d=this.calculateContentHash(c);a.push({id:u,notePath:r.path,chunkIndex:o,content:c,contentHash:d,title:s,heading:n,mtime:r.stat.mtime})}else try{let d=await this.createSplitter(i).createDocuments([e],[],{chunkHeader:l,appendChunkOverlapHeader:i.overlap>0});this.coalesceTinySplitChunks(d.map(p=>p.pageContent),l,i.maxChars).forEach((p,m)=>{let h=o+m,g=this.generateChunkId(r.path,h),y=this.calculateContentHash(p);a.push({id:g,notePath:r.path,chunkIndex:h,content:p,contentHash:y,title:s,heading:n,mtime:r.stat.mtime})})}catch(u){ee(`ChunkManager: Failed to split section in ${r.path}`,u);let d=this.generateChunkId(r.path,o),f=this.calculateContentHash(c);a.push({id:d,notePath:r.path,chunkIndex:o,content:c,contentHash:f,title:s,heading:n,mtime:r.stat.mtime})}return a}coalesceTinySplitChunks(e,n,r){if(e.length<=1)return e;let o=[...e],i=0;for(;i<o.length-1;){if(this.isTinyStructuralChunk(o[i],n)){let s=this.mergeChunkContents(o[i],o[i+1],n);if(s.length<=r){o.splice(i,2,s);continue}}i++}if(o.length>1){let s=o.length-1;if(this.isTinyStructuralChunk(o[s],n)){let a=this.mergeChunkContents(o[s-1],o[s],n);a.length<=r&&o.splice(s-1,2,a)}}return o}isTinyStructuralChunk(e,n){let r=this.stripChunkHeader(e,n).trim();if(!r)return!0;let o=r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);return o.length===1&&/^#{1,6}\s+\S+/.test(o[0])}mergeChunkContents(e,n,r){let o=this.stripChunkHeader(e,r).replace(/\s+$/,""),i=this.stripChunkHeader(n,r).replace(/^\s+/,"");return`${r}${o}${o&&i?`
`:""}${i}`}stripChunkHeader(e,n){return e.startsWith(n)?e.slice(n.length):e}calculateChunkBytes(e){return e.reduce((n,r)=>n+p0.getByteSize(r.content),0)}async safeReadFile(e){try{return(await this.app.vault.cachedRead(e))?.trim()||""}catch(n){return ee(`ChunkManager: Failed to read ${e.path}`,n),""}}generateChunkId(e,n){return`${e}#${n}`}calculateContentHash(e){let n=e.length.toString(16),r=e.slice(0,32).replace(/\s/g,"").substring(0,8);return n+r}formatMemoryUsage(){return`${(this.memoryUsage/1024/1024).toFixed(1)}MB`}findFrontmatterEnd(e,n){if(!n||!e.startsWith("---"))return 0;let r=e.match(/\n---(\r?\n|$)/);return r&&r.index!==void 0?r.index+r[0].length:0}},eye=null});var fG,sB,I5e=C(()=>{Ir();o0();ye();b5e();iB();Se();qe();TC();fG=require("obsidian");fc();sB=class{constructor(e,n,r){this.app=e;this.indexBackend=n;this.embeddingsManager=r;this.state={isIndexingPaused:!1,isIndexingCancelled:!1,indexedCount:0,totalFilesToIndex:0,processedFiles:new Set};this.refreshRuntimeIndexingConfig(),this.chunkManager=PC(e),Ho(()=>{this.refreshRuntimeIndexingConfig()})}refreshRuntimeIndexingConfig(){let e=q();this.rateLimiter=new cG(e.embeddingRequestsPerMin),this.embeddingBatchSize=Math.max(1,e.embeddingBatchSize),this.checkpointInterval=8*this.embeddingBatchSize}async indexVaultToVectorStore(e,n){if(!q().enableSemanticSearchV3)return ee("indexVaultToVectorStore called with semantic search disabled, skipping."),0;let r=[];qte();try{let o=this.indexBackend.requiresEmbeddings(),i=o?await this.embeddingsManager.getEmbeddingsAPI():void 0;if(o&&!i)return z("Embedding instance not found."),Kte({isActive:!1,isPaused:!1,isCancelled:!1,indexedCount:0,totalFiles:0,errors:["Embedding model not available. Please check your Copilot settings to make sure you have a working embedding model."],completionStatus:"error"}),0;(o?await this.indexBackend.checkAndHandleEmbeddingModelChange(i):!1)&&(e=!0),e?(await this.indexBackend.clearIndex(i),this.indexBackend.clearFilesMissingEmbeddings()):await this.indexBackend.garbageCollect();let a=await this.getFilesToIndex(e);if(a.length===0)return n?.userInitiated&&ul({completionStatus:"success"}),0;this.initializeIndexingState(a.length),this.indexBackend.clearFilesMissingEmbeddings();let l=o&&i?is.getModelName(i):"",c=await this.prepareAllChunks(a,l);if(c.length===0)return qte(),0;if(this.state.isIndexingCancelled||LA().isCancelled)return ul({isActive:!1,completionStatus:"cancelled"}),0;let u=new Set(c.map(f=>f.fileInfo.path)).size;this.state.totalFilesToIndex=u,ul({totalFiles:u});let d=0;for(;d<c.length&&!(this.state.isIndexingCancelled||LA().isCancelled);){await this.handlePause();let f=c.slice(d,d+this.embeddingBatchSize);try{let p=[];if(o&&i){await this.rateLimiter.wait();let g=await i.embedDocuments(f.map(y=>y.content));if(!g||g.length!==f.length)throw new Error(`Embedding model returned ${g?.length??0} embeddings for ${f.length} documents`);for(let y=0;y<f.length;y++){let w=f[y],v=g[y];if(!v||!Array.isArray(v)||v.length===0){z(`Invalid embedding for document ${String(w.fileInfo.path)}: ${JSON.stringify(v)}`),this.indexBackend.markFileMissingEmbeddings(w.fileInfo.path);continue}p.push({doc:{...w.fileInfo,id:this.getDocHash(w.content),content:w.content,embedding:v,created_at:Date.now(),nchars:w.content.length},filePath:w.fileInfo.path})}}else for(let g of f)p.push({doc:{...g.fileInfo,id:this.getDocHash(g.content),content:g.content,embedding:[],created_at:Date.now(),nchars:g.content.length},filePath:g.fileInfo.path});if(p.length>0)try{await this.indexBackend.upsertBatch(p.map(g=>g.doc)),p.forEach(g=>this.state.processedFiles.add(g.filePath))}catch(g){z("Batch upsert failed; falling back to per-document upserts.",g);for(let y of p)try{await this.indexBackend.upsert(y.doc),this.state.processedFiles.add(y.filePath)}catch(w){this.handleError(w,{filePath:y.filePath,errors:r}),o&&this.indexBackend.markFileMissingEmbeddings(y.filePath)}}this.state.indexedCount=this.state.processedFiles.size,oke(this.state.indexedCount);let m=Math.floor((this.state.indexedCount-f.length)/this.checkpointInterval);Math.floor(this.st
`,m=c.content.indexOf("NOTE BLOCK CONTENT:"),h=m>0?c.content.slice(0,m)+p+c.content.slice(m):c.content;r.push({content:h,chunkId:c.id,fileInfo:f})}}}return r}getDocHash(e){return Jc(e)}async getFilesToIndex(e){let{inclusions:n,exclusions:r}=Bo(),o=this.app.vault.getMarkdownFiles();if(e)return o.filter(u=>Qr(u,n,r));let i=new Set(await this.indexBackend.getIndexedFiles()),s=await this.indexBackend.getLatestFileMtime(),a=new Set(this.indexBackend.getFilesMissingEmbeddings()),l=new Set,c=new Set;for(let u of o){if(!Qr(u,n,r))continue;let d=await this.app.vault.cachedRead(u);if(!d||d.trim().length===0){c.add(u.path);continue}let f=i.has(u.path),p=a.has(u.path);(!f||p||u.stat.mtime>s)&&l.add(u)}return k([`Files to index: ${l.size}`,`Previously indexed: ${i.size}`,`Empty files skipped: ${c.size}`,`Files missing embeddings: ${a.size}`].join(`
`)),Array.from(l)}initializeIndexingState(e){this.state={isIndexingPaused:!1,isIndexingCancelled:!1,indexedCount:0,totalFilesToIndex:e,processedFiles:new Set},Kte({isActive:!0,isPaused:!1,isCancelled:!1,indexedCount:0,totalFiles:e,errors:[],completionStatus:"none"})}async handlePause(){let e=LA();if(this.state.isIndexingPaused=e.isPaused,this.state.isIndexingCancelled=e.isCancelled,this.state.isIndexingPaused){for(;this.state.isIndexingPaused&&!this.state.isIndexingCancelled;){await new Promise(r=>window.setTimeout(r,100));let n=LA();this.state.isIndexingPaused=n.isPaused,this.state.isIndexingCancelled=n.isCancelled}if(!this.state.isIndexingCancelled){this.refreshRuntimeIndexingConfig();let n=await this.getFilesToIndex();if(n.length===0){k("No files to index after filter change, stopping indexing"),await this.cancelIndexing();return}let r=Math.max(this.state.indexedCount+n.length,1);this.state.totalFilesToIndex=r,ul({totalFiles:r})}}}isStringLengthError(e){if(!e)return!1;if(e instanceof RangeError&&e.message.toLowerCase().includes("string length"))return!0;let r=(e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)??"").toLowerCase();return r.includes("string length")||r.includes("rangeerror")}handleError(e,n){let r=n?.filePath;if(r?(n.batch?console.error("Batch processing error:",{error:e,batchSize:n.batch.length||0,firstChunk:n.batch[0]?{path:n.batch[0].fileInfo?.path,contentLength:n.batch[0].content?.length,hasFileInfo:!!n.batch[0].fileInfo}:"No chunks in batch",errorType:e instanceof Error?e.constructor?.name:typeof e,errorMessage:e instanceof Error?e.message:String(e)}):console.error(`Error indexing file ${r}:`,e),n.errors?.push(r)):console.error("Fatal error during indexing:",e),this.isStringLengthError(e)){new fG.Notice("Vault is too large for 1 partition, please increase the number of partitions in your Copilot QA settings!",1e4);return}}isRateLimitError(e){return e instanceof Error&&e.message.toLowerCase().includes("rate limit")||!1}finalizeIndexing(e){if(ike(),this.state.isIndexingCancelled||LA().isCancelled){ul({isActive:!1,completionStatus:"cancelled",errors:e});return}ul({isActive:!1,completionStatus:e.length>0?"error":"success",errors:e,indexedCount:this.state.indexedCount})}async reindexFile(e){try{let n=this.indexBackend.requiresEmbeddings(),r=n?await this.embeddingsManager.getEmbeddingsAPI():void 0;if(n&&!r)return;if(await this.indexBackend.removeByPath(e.path),n&&r&&await this.indexBackend.checkAndHandleEmbeddingModelChange(r)){await this.indexVaultToVectorStore(!0);return}let o=n&&r?is.getModelName(r):"",i=await this.prepareAllChunks([e],o);if(i.length===0)return;if(n&&r){let s=await r.embedDocuments(i.map(a=>a.content));for(let a=0;a<i.length;a++){let l=i[a];await this.indexBackend.upsert({...l.fileInfo,id:this.getDocHash(l.content),content:l.content,embedding:s[a],created_at:Date.now(),nchars:l.content.length})}}else for(let s of i)await this.indexBackend.upsert({...s.fileInfo,id:this.getDocHash(s.content),content:s.content,embedding:[],created_at:Date.now(),nchars:s.content.length});this.indexBackend.markUnsavedChanges(),q().debug&&k(`Reindexed file: ${e.path}`)}catch(n){this.handleError(n,{filePath:e.path})}}async cancelIndexing(){k("Indexing cancelled by user"),this.state.isIndexingCancelled=!0,ul({isCancelled:!0,isActive:!1,completionStatus:"cancelled"}),await new Promise(e=>window.setTimeout(e,100))}}});var ji={};zn(ji,{default:()=>Cp});var aB,Cp,ei=C(()=>{Ir();Nf();ye();o0();yp();Se();aB=require("obsidian");B3e();v5e();x5e();Gge();I5e();Cp=class t{constructor(){this.embeddingsManager=is.getInstance(),this.oramaBackend=new lG(app),this.miyoBackend=new zq(app),this.activeBackendKey=this.getBackendKey(q()),this.indexBackend=this.activeBackendKey==="miyo"?this.miyoBackend:this.oramaBackend,this.indexOps=new sB(app,this.indexBackend,this.embeddingsManager),this.eventHandler=new rB(app,this.indexOps,this.indexBackend),this.initializationPromise=this.initialize(),this.setupSettingsSubscription()}static getInstance(){return t.instance||(t.instance=new t),t.instance}setupSettingsSubscrip
`)),l instanceof Blob){let c=l instanceof File?l.name:"blob",u=l.type||"application/octet-stream";r.push(n.encode(`Content-Disposition: form-data; name="${a}"; filename="${c}"\r
Content-Type: ${u}\r
\r
`));let d=await l.arrayBuffer();r.push(new Uint8Array(d)),r.push(n.encode(`\r
`))}else r.push(n.encode(`Content-Disposition: form-data; name="${a}"\r
\r
`)),r.push(n.encode(String(l))),r.push(n.encode(`\r
`));r.push(n.encode(`--${e}--\r
`));let o=r.reduce((a,l)=>a+l.byteLength,0),i=new Uint8Array(o),s=0;for(let a of r)i.set(a,s),s+=a.byteLength;return{body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),contentType:`multipart/form-data; boundary=${e}`}}function R5e(t,e){let n=t.json;if(typeof n=="string")try{n=JSON.parse(n)}catch{}if(t.status<200||t.status>=300){let r=n?.detail;if(r?.reason){let o=new Error(r.reason);return r.error&&(o.name=r.error),{data:null,error:o}}return{data:null,error:new Error(`HTTP error: ${t.status}`)}}return k(`[API ${e} request]:`,n),{data:n}}var cye,di,Zg=C(()=>{It();Su();Nf();ye();ns();Se();pG();cye=require("obsidian");di=class t{constructor(){this.pluginVersion="Unknown"}static getInstance(){return t.instance||(t.instance=new t),t.instance}checkLicenseKey(){if(!q().plusLicenseKey)throw new DS("Copilot Plus license key not found. Please enter your license key in the settings.")}setPluginVersion(e){this.pluginVersion=e}async makeRequest(e,n,r="POST",o=!1,i=!1){i||this.checkLicenseKey(),n.user_id=q().userId;let s=new URL(`${XQ}${e}`);r==="GET"&&Object.entries(n).forEach(([c,u])=>{s.searchParams.append(c,u)});let a={"Content-Type":"application/json","X-Client-Version":this.pluginVersion};o||(a.Authorization=`Bearer ${await pn(q().plusLicenseKey)}`);let l=await(0,cye.requestUrl)({url:s.toString(),method:r,headers:a,...r==="POST"&&{body:JSON.stringify(n)},throw:!1});return R5e(l,e)}async makeFormDataRequest(e,n,r=!1){r||this.checkLicenseKey(),n.append("user_id",q().userId);let o=new URL(`${XQ}${e}`);try{let{body:i,contentType:s}=await W2t(n),a=await(0,cye.requestUrl)({url:o.toString(),method:"POST",headers:{"Content-Type":s,Authorization:`Bearer ${await pn(q().plusLicenseKey)}`,"X-Client-Version":this.pluginVersion},body:i,throw:!1});return R5e(a,`${e} form-data`)}catch(i){return{data:null,error:i instanceof Error?i:new Error(String(i))}}}async validateLicenseKey(e){let n={license_key:await pn(q().plusLicenseKey)};if(e&&typeof e=="object"){let i=Object.fromEntries(Object.entries(e).filter(([a,l])=>l!=null)),s=new Set(["license_key","user_id"]);for(let a of s)a in i&&delete i[a];Object.assign(n,i)}let{data:r,error:o}=await this.makeRequest("/license",n,"POST",!0,!0);return o?o.message==="Invalid license key"?(lye(),{isValid:!1}):{isValid:void 0}:(N5e(),{isValid:!0,plan:r?.plan})}async rerank(e,n){let{data:r,error:o}=await this.makeRequest("/rerank",{query:e,documents:n,model:"rerank-2"});if(o)throw o;if(!r)throw new Error("No data returned from rerank");return r}async url4llm(e){let{data:n,error:r}=await this.makeRequest("/url4llm",{url:e});if(r)throw r;if(!n)throw new Error("No data returned from url4llm");return n}async pdf4llm(e){let n=EC(e),{data:r,error:o}=await this.makeRequest("/pdf4llm",{pdf:n});if(o)throw o;if(!r)throw new Error("No data returned from pdf4llm");return r}async docs4llm(e,n){let r=new FormData,o=this.getMimeTypeFromExtension(n),i=new Blob([e],{type:o}),s=`file.${n}`,a=new File([i],s,{type:o});r.append("files",a),r.append("file_type",n);let{data:l,error:c}=await this.makeFormDataRequest("/docs4llm",r);if(c)throw c;if(!l)throw new Error("No data returned from docs4llm");return l}getMimeTypeFromExtension(e){return{pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",epub:"application/epub+zip",txt:"text/plain",rtf:"application/rtf",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",bmp:"image/bmp",svg:"image/svg+xml",tiff:"image/tiff",webp:"image/webp",html:"text/html",htm:"text/html",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xls:"application/vnd.ms-excel",csv:"text/csv",mp3:"audio/mpeg",mp4:"video/mp4",wav:"audio/wav",webm:"video/webm"}[e.toLowerCase()]||"application/octet-stream"}async webSearch(e){let{data:n,error:r}=await this.makeRequest("/websearch",{query:e});if(r)throw r;if(!n)throw new Error("No data returned from websearch");return n}async youtube4llm(e){let
`)?`\r
`:`
`,s=o.replace(/^(\uFEFF?---\r?\n[\s\S]*?\r?\n)(---)/,(a,l,c)=>{let u=l;for(let[d,f]of Object.entries(n)){let p=typeof f=="string"?`"${f.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:String(f),m=new RegExp(`^${d}:\\s*.+`,"m");m.test(u)?u=u.replace(m,`${d}: ${p}`):u+=`${d}: ${p}${i}`}return u+c});s!==o&&await t.vault.adapter.write(e,s)}async function oy(t,e){let o=(await t.vault.adapter.read(e)).replace(/^\uFEFF/,"").match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1];if(!o)return null;let i={};for(let s of o.split(/\r?\n/)){let a=s.match(/^([\w-]+):\s*(.+)/);a&&(i[a[1]]=a[2].trim().replace(/^["']|["']$/g,""))}return i}async function H5e(t,e){let n=await t.vault.adapter.stat(e),r=e.split("/").pop()??"",o=Object.create(nO.TFile.prototype);return Object.assign(o,{path:e,name:r,basename:r.replace(/\.md$/,""),extension:"md",stat:n??{ctime:Date.now(),mtime:Date.now(),size:0},vault:t.vault,parent:null}),o}var nO,av=C(()=>{nO=require("obsidian")});var uqe={};zn(uqe,{createToolCallMarker:()=>sUt,parseToolCallMarkers:()=>gye,updateToolCallMarker:()=>aUt});function cqe(t){try{return`ENC:${encodeURIComponent(t)}`}catch{return t}}function oUt(t){if(typeof t!="string"||!t.startsWith("ENC:"))return t;try{return decodeURIComponent(t.slice(4))}catch{return t}}function iUt(t){return`Tool '${t}' ${rUt}`}function hye(t,e=0,n=""){let r=[],o=/<errorChunk>([\s\S]*?)<\/errorChunk>/g,i=0,s;for(;(s=o.exec(t))!==null;){s.index>i&&r.push({type:"text",content:t.slice(i,s.index)});let[a,l]=s,c=e+s.index,u=n?`${n}-error-${c}`:`error-${c}`;r.push({type:"error",content:l,error:{id:u,errorContent:l,startIndex:c,endIndex:e+s.index+a.length}}),i=s.index+a.length}return i<t.length&&r.push({type:"text",content:t.slice(i)}),r.length===0&&r.push({type:"text",content:t}),r}function gye(t,e){let n=[],r=/<!--TOOL_CALL_START:([^:]+):([^:]+):([^:]+):([^:]+):([^:]*):([^:]+)-->([\s\S]*?)<!--TOOL_CALL_END:\1:([\s\S]*?)-->/g,o=0,i;for(;(i=r.exec(t))!==null;){if(i.index>o){let v=t.slice(o,i.index);hye(v,o,e).forEach(b=>{b.type==="text"&&b.content.trim()?n.push({type:"text",content:b.content}):b.type==="error"&&b.error&&n.push({type:"error",content:b.content,error:b.error})})}let[s,a,l,c,u,d,f,p,m]=i,g=oUt(typeof m=="string"?m:""),w=(typeof g=="string"?g.length:0)>5e3?iUt(l):g??void 0;n.push({type:"toolCall",content:p,toolCall:{id:a,toolName:l,displayName:c,emoji:u,confirmationMessage:d||void 0,isExecuting:f==="true",result:w,startIndex:i.index,endIndex:i.index+s.length}}),o=i.index+s.length}if(o<t.length){let s=t.slice(o);hye(s,o,e).forEach(l=>{l.type==="text"&&l.content.trim()?n.push({type:"text",content:l.content}):l.type==="error"&&l.error&&n.push({type:"error",content:l.content,error:l.error})})}return n.length===0&&hye(t,0,e).forEach(a=>{a.type==="text"?n.push({type:"text",content:a.content}):a.type==="error"&&a.error&&n.push({type:"error",content:a.content,error:a.error})}),{segments:n}}function sUt(t,e,n,r,o="",i=!0,s="",a=""){let l=a&&cqe(a);return`<!--TOOL_CALL_START:${t}:${e}:${n}:${r}:${o}:${i}-->${s}<!--TOOL_CALL_END:${t}:${l}-->`}function aUt(t,e,n){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`(<!--TOOL_CALL_START:${r}:[^:]+:[^:]+:[^:]+:[^:]*:)true(-->[\\s\\S]*?<!--TOOL_CALL_END:${r}:)[\\s\\S]*?-->`,"g"),i=cqe(n);return t.replace(o,`$1false$2${i}-->`)}var rUt,yye=C(()=>{rUt=`Result omitted to keep the UI responsive (payload exceeded ${5e3.toLocaleString()} characters).`});var ay,lO=C(()=>{$n();Hb();Ng();Ra();ay=class extends gr{constructor(e){super(e);I(this,"callbacks");I(this,"tags");I(this,"metadata");I(this,"verbose");this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,n){throw new Error("Not implemented!")}async invoke(e,n){let r=fr(Wb(n)),o=await(await Ws.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,r.runId,void 0,void 0,void 0,r.runName);try{let i=await this._getRelevantDocuments(e,o);return await o?.handleRetrieverEnd(i),i}catch(i){throw await o?.handleRetrieve
1. SALIENT TERMS from the original query (for ranking)
2. Alternative queries and related terms (for finding more results)
Query: "{query}"
Instructions:
SALIENT TERMS (for ranking - ONLY from original query):
- Extract meaningful words FROM THE ORIGINAL QUERY ONLY
- Include: nouns, proper nouns, technical terms, domain concepts
- Exclude: action verbs (find, search, get), pronouns (my, your), articles (the, a), prepositions (in, on, for), conjunctions (and, or)
- These terms determine search ranking - must be from original query
ALTERNATIVE QUERIES (for recall - specific alternative phrasings):
- Alternative phrasings of the query (specific enough to be useful for search)
Example: "find my piano notes"
- Salient (from original): piano, notes
- Queries: "piano lesson notes", "piano practice sheets"
Example: "\u67E5\u627E\u6211\u7684\u5B66\u4E60\u7B14\u8BB0"
- Salient (from original): \u5B66\u4E60, \u7B14\u8BB0
- Queries: "\u4E2A\u4EBA\u7B14\u8BB0\u6587\u6863"
Format:
<salient>
<term>word_from_original_query</term>
</salient>
<queries>
<query>alternative query</query>
</queries>`;DG=$G});var dO,FG,kqe=C(()=>{ye();fc();dO=class dO{constructor(e){this.app=e}async batchCachedReadGrep(e,n){let{inclusions:r,exclusions:o}=Bo(),s=this.app.vault.getMarkdownFiles().filter(h=>Qr(h,r,o)),a=dO.CONFIG.BATCH_SIZE,l=e.map(h=>h.toLowerCase()).filter(h=>this.isGrepWorthy(h)),c=[],u=dO.CONFIG.YIELD_INTERVAL;for(let h=0;h<s.length;h++){let g=s[h],y=g.path.toLowerCase(),w=0;for(let v of l)y.includes(v)&&w++;w>0&&c.push({path:g.path,matchCount:w}),h>0&&h%u===0&&await new Promise(v=>window.setTimeout(v,0))}c.sort((h,g)=>g.matchCount-h.matchCount);let d=new Set(c.map(h=>h.path)),f=Math.max(0,n-d.size),p=new Set;if(f>0)for(let h=0;h<s.length&&p.size<f;h+=a){let g=s.slice(h,h+a);await Promise.all(g.map(async y=>{if(!(p.size>=f)&&!d.has(y.path))try{let v=(await this.app.vault.cachedRead(y)).toLowerCase();for(let x of l)if(v.includes(x)){p.add(y.path);break}}catch(w){k(`GrepScanner: Skipping file ${y.path}: ${w}`)}})),h%dO.CONFIG.YIELD_INTERVAL===0&&await new Promise(y=>window.setTimeout(y,0))}let m=[...d,...p].slice(0,n);if(m.length>0){let h=Math.min(d.size,n),g=m.length-h;k(` Grep: ${m.length} files match (${h} path, ${g} content) [${e.slice(0,3).join(", ")}${e.length>3?"...":""}]`)}return m}async grep(e,n=200){return this.batchCachedReadGrep([e],n)}isGrepWorthy(e){return!(!e||e.length<=1)}async fileContainsAny(e,n){try{let r=e.path.toLowerCase(),o=0;for(let a of n)r.includes(a.toLowerCase())&&o++;if(o>0)return!0;let s=(await this.app.vault.cachedRead(e)).toLowerCase();return n.some(a=>s.includes(a.toLowerCase()))}catch{return!1}}};dO.CONFIG={BATCH_SIZE:30,YIELD_INTERVAL:100};FG=dO});function oh(t){let e=t.lastIndexOf("#");return e===-1?t:t.substring(0,e)}var UG=C(()=>{});var IUt,BG,Mqe=C(()=>{ye();UG();IUt={enabled:!0,minDocsForBoost:2,maxBoostFactor:1.15,minRelevanceRatio:.4},BG=class{constructor(e){this.config=IUt;this.app=e||null}setConfig(e){this.config={...this.config,...e}}applyBoosts(e){if(!this.config.enabled||e.length===0)return e;let n=this.calculateFolderStats(e);return this.logBoostedFolders(n),e.map(r=>{let o=oh(r.id),i=this.extractFolder(o),s=n.get(i);if(s){let a=r.score*s.boostFactor;return{...r,score:a,explanation:r.explanation?{...r.explanation,folderBoost:{folder:s.folderPath,documentCount:s.documentCount,totalDocsInFolder:s.totalDocsInFolder,relevanceRatio:s.relevanceRatio,boostFactor:s.boostFactor},finalScore:a}:void 0}}return r})}calculateFolderStats(e){let n=new Map;for(let s of e){let a=oh(s.id),l=this.extractFolder(a);n.has(l)||n.set(l,new Set),n.get(l).add(a)}let r=new Map;for(let[s,a]of n.entries())r.set(s,a.size);let o=this.getTotalDocsPerFolder(),i=new Map;for(let[s,a]of r.entries()){let l=o.get(s)||a,c=a/l;if(a>=this.config.minDocsForBoost&&c>=this.config.minRelevanceRatio){let d=1+(1+Math.log2(a+1)-1)*Math.sqrt(c),f=Math.min(d,this.config.maxBoostFactor);i.set(s,{folderPath:s,documentCount:a,totalDocsInFolder:l,relevanceRatio:c,boostFactor:f})}}return i}getTotalDocsPerFolder(){let e=new Map;if(!this.app)return e;let n=this.app.vault.getMarkdownFiles();for(let r of n){let o=this.extractFolder(r.path);e.set(o,(e.get(o)||0)+1)}return e}extractFolder(e){return e.substring(0,e.lastIndexOf("/"))||""}logBoostedFolders(e){let n=Array.from(e.values()).sort((r,o)=>o.relevanceRatio-r.relevanceRatio);n.length>0&&(k(`Folder boost: Boosting ${n.length} folders with significant relevance`),n.slice(0,5).forEach(r=>{let o=(r.relevanceRatio*100).toFixed(1);k(` ${r.folderPath||"(root)"}: ${r.documentCount}/${r.totalDocsInFolder} docs (${o}% relevant, ${r.boostFactor.toFixed(2)}x boost)`)}))}getFolderBoosts(e){return this.config.enabled?this.calculateFolderStats(e):new Map}}});var Nqe,PUt,zG,Oqe=C(()=>{ye();Nqe=require("obsidian");UG();PUt={enabled:!0,maxCandidates:10,backlinkWeight:1,coCitationWeight:.5,sharedTagWeight:.3,boostStrength:.1,maxBoostMultiplier:1.2},zG=class{constructor(e,n={}){this.metadataCache=e.metadataCache,this.config={...PUt,...n}}applyBoost(e){if(!this.config.enabled||e.length===0)return e;let n=this.filterCandidates(e);if(n.length<2)return e;let r=new Set(n.map(a=>oh(a.id)
Explicit Chunks: `,s),k("Orama Chunks: ",a),k("Combined Chunks: ",l),k("Max Orama Score: ",u),f?k("Reranked Chunks: ",c):k("No reranking applied.")),c})}async getExplicitChunks(n){let r=[];for(let o of n){let i=await Cp.getInstance().getDocumentsByPath(o.path);if(i.length===0)continue;let s=i.map(a=>new fi({pageContent:a.content,metadata:{...a.metadata,score:1,path:a.path,mtime:a.mtime,ctime:a.ctime,title:a.title,id:a.id,embeddingModel:a.embeddingModel,tags:a.tags,extension:a.extension,created_at:a.created_at,nchars:a.nchars,chunkId:a.metadata?.chunkId}}));r.push(...s)}return r}async getOramaChunks(n,r,o){let i;try{i=await this.convertQueryToVector(n)}catch(c){throw console.error("Error in convertQueryToVector, please ensure your embedding model is working and has an adequate context length:",c,`
Query:`,n),c}let s=await Cp.getInstance().getDb(),a={similarity:this.options.minSimilarityScore,limit:this.options.maxK,includeVectors:!0};if(r.length>0){let c;o||(o=.5),c=1-o;let u=!0;for(let d of r)if(!d.startsWith("#")){u=!1;break}u&&(q().debug&&k("Tag only query detected, setting textWeight to 1 and vectorWeight to 0."),o=1,c=0),a.mode="hybrid",a.term=r.join(" "),a.vector={value:i,property:"embedding"},a.hybridWeights={text:o,vector:c}}else a.mode="vector",a.vector={value:i,property:"embedding"};if(this.options.timeRange){let{startTime:c,endTime:u}=this.options.timeRange,d=this.generateDailyNoteDateRange(c,u);k("Daily note date range:",d[0],d[d.length-1]);let f=Df(d.join(", "),app.vault),m=(await this.getExplicitChunks(f)).map(v=>({...v,metadata:{...v.metadata,includeInContext:!0}}));k("Modified time range:",c,u),a.where={mtime:{between:[c,u]}};let g=(await Zu(s,a)).hits.map(v=>new fi({pageContent:v.document.content,metadata:{...v.document.metadata,score:v.score,path:v.document.path,mtime:v.document.mtime,ctime:v.document.ctime,title:v.document.title,id:v.document.id,embeddingModel:v.document.embeddingModel,tags:v.document.tags,extension:v.document.extension,created_at:v.document.created_at,nchars:v.document.nchars,chunkId:v.document.metadata?.chunkId}})),y=[...m,...g];return Array.from(new Set(y.map(v=>v.metadata.id))).map(v=>y.find(x=>x.metadata.id===v)).filter(v=>v!==void 0)}k(`Orama search params:
`,a);let l=await Zu(s,a);return!l||!l.hits?(console.warn("Search results or hits are undefined"),[]):l.hits.map(c=>!c||!c.document?(console.warn("Invalid hit or document in search results"),null):((typeof c.score!="number"||isNaN(c.score))&&console.warn("NaN/invalid score detected:",{score:c.score,path:c.document.path,title:c.document.title}),new fi({pageContent:c.document.content||"",metadata:{...c.document.metadata||{},score:c.score,path:c.document.path||"",mtime:c.document.mtime,ctime:c.document.ctime,title:c.document.title||"",id:c.document.id,embeddingModel:c.document.embeddingModel,tags:c.document.tags||[],extension:c.document.extension,created_at:c.document.created_at,nchars:c.document.nchars,chunkId:c.document.metadata?.chunkId}}))).filter(c=>c!==null)}async convertQueryToVector(n){let o=await(await is.getInstance().getEmbeddingsAPI()).embedQuery(n);if(o.length===0)throw new Error("Query embedding returned an empty vector");return o}generateDailyNoteDateRange(n,r){let o=[],i=new Date(n),s=new Date(r),a=new Date(i);for(;a<=s;)o.push(`[[${a.toLocaleDateString("en-CA")}]]`),a.setDate(a.getDate()+1);return o}filterAndFormatChunks(n,r){let o=this.options.minSimilarityScore,i=n.filter(l=>{let c=l.metadata.score;return typeof c!="number"||isNaN(c)?!0:c>=o}),s=new Set(r.map(l=>l.pageContent)),a=[...r];for(let l of i){let c=l.pageContent;s.has(c)||(s.add(c),a.push(l))}return a.map(l=>({...l,metadata:{...l.metadata,includeInContext:!0}}))}}});function Oye(t){let e=[];for(let n of t)n.type==="tool_use"&&e.push({name:n.name,args:n.input,id:n.id,type:"tool_call"});return e}var Fqe,Rye=C(()=>{Bd();Uw();Fqe=class extends aM{constructor(e){super(e);I(this,"lc_namespace",["langchain","anthropic","output_parsers"]);I(this,"returnId",!1);I(this,"keyName");I(this,"returnSingle",!1);I(this,"zodSchema");I(this,"serializableSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema,this.serializableSchema=e.serializableSchema}static lc_name(){return"AnthropicToolsOutputParser"}async _validateResult(e){let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch(o){throw new lc(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(o.message)}`,e)}else n=e;if(this.serializableSchema!==void 0){let o=await this.serializableSchema["~standard"].validate(n);if(o.issues)throw new lc(`Failed to parse. Text: "${JSON.stringify(n,null,2)}". Error: ${JSON.stringify(o.issues)}`,JSON.stringify(n,null,2));return o.value}if(this.zodSchema===void 0)return n;let r=await kT(this.zodSchema,n);if(r.success)return r.data;throw new lc(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.error.issues)}`,JSON.stringify(n,null,2))}async parseResult(e){let n=e.flatMap(o=>{let{message:i}=o;return Array.isArray(i.content)?Oye(i.content)[0]:[]});if(n[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");let[r]=n;return await this._validateResult(r.args)}}});function Uqe(t){if(t)return t==="any"||t==="required"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}var Bqe,Lye,zqe=C(()=>{tv();Bqe=Yme({cache_control:rhe().optional().nullable(),defer_loading:yq().optional(),input_examples:MN(QI()).optional(),allowed_callers:MN(QI()).optional()}),Lye={tool_search_tool_regex_20251119:"advanced-tool-use-2025-11-20",tool_search_tool_bm25_20251119:"advanced-tool-use-2025-11-20",memory_20250818:"context-management-2025-06-27",web_fetch_20250910:"web-fetch-2025-09-10",code_execution_20250825:"code-execution-2025-08-25",computer_20251124:"computer-use-2025-11-24",computer_20250124:"computer-use-2025-01-24",mcp_toolset:"mcp-client-2025-11-20"}});function jqe(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function Vqe(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function HG(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="compaction"}function Wqe(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_res
`))}if(n.protocol==="http:"||n.protocol==="https:")return{type:"url",url:t};throw new Error([`Invalid image URL protocol: ${JSON.stringify(n.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
`))}function LUt(t){let e=[];for(let n of t)if(n._getType()==="tool")if(typeof n.content=="string"){let r=e[e.length-1];r?._getType()==="human"&&Array.isArray(r.content)&&"type"in r.content[0]&&r.content[0].type==="tool_result"?r.content.push({type:"tool_result",content:n.content,tool_use_id:n.tool_call_id}):e.push(new Zo({content:[{type:"tool_result",content:n.content,tool_use_id:n.tool_call_id}]}))}else e.push(new Zo({content:[{type:"tool_result",...n.content!=null?{content:zye(n)}:{},tool_use_id:n.tool_call_id}]}));else e.push(n);return e}function Bye(t){if(t.id===void 0)throw new Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:t.id,name:t.name,input:t.args}}function*DUt(t,e){let n=["bash_code_execution_tool_result","input_json_delta","server_tool_use","text_editor_code_execution_tool_result","tool_result","tool_use","web_search_result","web_search_tool_result"],r=["text","text_delta"];for(let o of t){tc(o)&&(yield kw(o,Kqe));let i="cache_control"in o?o.cache_control:void 0;if(o.type==="image_url"){let s;typeof o.image_url=="string"?s=Uye(o.image_url):typeof o.image_url=="object"&&o.image_url!==null&&"url"in o.image_url&&typeof o.image_url.url=="string"&&(s=Uye(o.image_url.url)),s&&(yield{type:"image",source:s,...i?{cache_control:i}:{}})}else if(Hqe(o))yield o;else if(o.type==="image"){let s;"url"in o&&typeof o.url=="string"?s=Uye(o.url):"data"in o&&(typeof o.data=="string"||o.data instanceof Uint8Array)?s={type:"base64",media_type:"mimeType"in o&&typeof o.mimeType=="string"?o.mimeType:"image/jpeg",data:typeof o.data=="string"?o.data:Buffer.from(o.data).toString("base64")}:"fileId"in o&&typeof o.fileId=="string"&&(s={type:"file",file_id:o.fileId}),s&&(yield{type:"image",source:s,...i?{cache_control:i}:{}})}else if(o.type==="file"){let s;"url"in o&&typeof o.url=="string"?s={type:"url",url:o.url}:"data"in o&&(typeof o.data=="string"||o.data instanceof Uint8Array)?s={type:"base64",media_type:"mimeType"in o&&typeof o.mimeType=="string"?o.mimeType:"application/pdf",data:typeof o.data=="string"?o.data:Buffer.from(o.data).toString("base64")}:"fileId"in o&&typeof o.fileId=="string"&&(s={type:"file",file_id:o.fileId}),s&&(yield{type:"document",source:s,...i?{cache_control:i}:{}})}else if(o.type==="document")yield{...o,...i?{cache_control:i}:{}};else if(jqe(o))yield{type:"thinking",thinking:o.thinking,signature:o.signature,...i?{cache_control:i}:{}};else if(Vqe(o))yield{type:"redacted_thinking",data:o.data,...i?{cache_control:i}:{}};else if(HG(o))yield{type:"compaction",content:o.content,...i?{cache_control:i}:{}};else if(Wqe(o))yield{type:"search_result",title:o.title,source:o.source,..."cache_control"in o&&o.cache_control?{cache_control:o.cache_control}:{},..."citations"in o&&o.citations?{citations:o.citations}:{},content:o.content};else if(r.find(s=>s===o.type)&&"text"in o)yield{type:"text",text:o.text,...i?{cache_control:i}:{},..."citations"in o&&o.citations?{citations:o.citations}:{}};else if(n.find(s=>s===o.type)){let s={...o};if(s.type==="input_json_delta")continue;if(s.type==="tool_use"&&typeof s.input=="string"){let a=e?.find(l=>l.id===s.id);a?s.input=a.args:s.input=t.filter(l=>l.index===s.index&&l.type==="input_json_delta"&&typeof l.input=="string").reduce((l,c)=>l+c.input,s.input)}if("index"in s&&delete s.index,"input"in s&&typeof s.input=="string")try{s.input=JSON.parse(s.input)}catch{s.input={}}yield{...s,...i?{cache_control:i}:{}}}else o.type==="container_upload"&&(yield{...o,...i?{cache_control:i}:{}})}}function zye(t,e){let{content:n}=t;return typeof n=="string"?n:Array.from(DUt(n,e))}function CB(t){let e=LUt(t),n;return e.length>0&&e[0]._getType()==="system"&&(n=t[0].content),{messages:$Ut((n!==void 0?e.slice(1):e).map(r=>{let o;if(r._getType()==="human")o="user";else if(r._getType()==="ai")o="assistant";else if(r._getType()==="tool")o="user";else throw r._getType()==="system"?new Error("System messages are only permitted as the first passed message."):new Error(`Message type "${r.type}" is not supported.`);if(kn.isInstance(r)&&r.response_metadata?.output_version==="v1")re
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
`,t}function Wye(t){let e;return t.status===400&&typeof t.message=="string"&&t.message.includes("prompt is too long")?e=_B(VFe.fromError(t),"CONTEXT_OVERFLOW"):t.status===400&&t.message.includes("tool")?e=_B(t,"INVALID_TOOL_RESULTS"):t.status===401?e=_B(t,"MODEL_AUTHENTICATION"):t.status===404?e=_B(t,"MODEL_NOT_FOUND"):t.status===429?e=_B(t,"MODEL_RATE_LIMIT"):e=t,e}var aGe=C(()=>{JT()});var lGe,cGe=C(()=>{lGe={"claude-3-sonnet-20240229":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-haiku-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-5-20251101":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-opus-20240229":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-haiku-20241022":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-sonnet-20241022":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-6":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-0":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-7":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-haiku-20240307":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-5-20250929":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-haiku-latest":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-1":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-
`):[]}};sf=new WeakMap,af=new WeakMap;pv.NEWLINE_CHARS=new Set([`
`,"\r"]);pv.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function IB(){}function ZG(t,e,n){return!e||JG[t]>JG[n]?IB:e[t].bind(e)}function Wa(t){let e=t.logger,n=t.logLevel??"off";if(!e)return JUt;let r=kGe.get(e);if(r&&r[0]===n)return r[1];let o={error:ZG("error",e,n),warn:ZG("warn",e,n),info:ZG("info",e,n),debug:ZG("debug",e,n)};return kGe.set(e,[n,o]),o}var JG,rwe,JUt,kGe,mv,PB=C(()=>{zC();JG={off:0,error:200,warn:300,info:400,debug:500},rwe=(t,e,n)=>{if(t){if(pGe(JG,t))return t;Wa(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(JG))}`)}};JUt={error:IB,warn:IB,info:IB,debug:IB},kGe=new WeakMap;mv=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t)});async function*XUt(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Ut("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new Ut("Attempted to iterate over a response with no body");let n=new owe,r=new pv,o=TB(t.body);for await(let i of QUt(o))for(let s of r.decode(i)){let a=n.decode(s);a&&(yield a)}for(let i of r.flush()){let s=n.decode(i);s&&(yield s)}}async function*QUt(t){let e=new Uint8Array;for await(let n of t){if(n==null)continue;let r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?SO(n):n,o=new Uint8Array(e.length+r.length);o.set(e),o.set(r,e.length),e=o;let i;for(;(i=AGe(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function eBt(t,e){let n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}var EB,ly,owe,iwe=C(()=>{dv();tu();_O();nwe();_O();pO();zC();YG();PB();tu();ly=class t{constructor(e,n,r){this.iterator=e,EB.set(this,void 0),this.controller=n,at(this,EB,r,"f")}static fromSSEResponse(e,n,r){let o=!1,i=r?Wa(r):console;async function*s(){if(o)throw new Ut("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let l of XUt(e,n)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(c){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),c}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop"||l.event==="message"||l.event==="user.message"||l.event==="user.interrupt"||l.event==="user.tool_confirmation"||l.event==="user.custom_tool_result"||l.event==="agent.message"||l.event==="agent.thinking"||l.event==="agent.tool_use"||l.event==="agent.tool_result"||l.event==="agent.mcp_tool_use"||l.event==="agent.mcp_tool_result"||l.event==="agent.custom_tool_use"||l.event==="agent.thread_context_compacted"||l.event==="session.status_running"||l.event==="session.status_idle"||l.event==="session.status_rescheduled"||l.event==="session.status_terminated"||l.event==="session.error"||l.event==="session.deleted"||l.event==="span.model_request_start"||l.event==="span.model_request_end")try{yield JSON.parse(l.data)}catch(c){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),c}if(l.event!=="ping"&&l.event==="error"){let c=qG(l.data)??l.data,u=c?.error?.type;throw new Va(void 0,c,void 0,e.headers,u)}}a=!0}catch(l){if(fv(l))return;throw l}finally{a||n.abort()}}return new t(s,n,r)}static fromReadableStream(e,n,r){let o=!1;async function*i(){let a=new pv,l=TB(e);for await(let c of l)for(let u of a.decode(c))yield u;for(let c of a.flush())yield c}async function*s(){if(o)throw new Ut("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(
`);r.enqueue(s)}catch(o){r.error(o)}},async cancel(){await n.return?.()}})}};owe=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,o]=eBt(e,":");return o.startsWith(" ")&&(o=o.substring(1)),n==="event"?this.event=o:n==="data"&&this.data.push(o),null}}});async function XG(t,e){let{response:n,requestLogID:r,retryOfRequestLogID:o,startTime:i}=e,s=await(async()=>{if(e.options.stream)return Wa(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller):ly.fromSSEResponse(n,e.controller);if(n.status===204)return null;if(e.options.__binaryResponse)return n;let l=n.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){if(n.headers.get("content-length")==="0")return;let f=await n.json();return swe(f,n)}return await n.text()})();return Wa(t).debug(`[${r}] response parsed`,mv({retryOfRequestLogID:o,url:n.url,status:n.status,body:s,durationMs:Date.now()-i})),s}function swe(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var awe=C(()=>{iwe();PB()});var AB,O0,QG=C(()=>{dv();awe();O0=class t extends Promise{constructor(e,n,r=XG){super(o=>{o(null)}),this.responsePromise=n,this.parseResponse=r,AB.set(this,void 0),at(this,AB,e,"f")}_thenUnwrap(e){return new t(ue(this,AB,"f"),this.responsePromise,async(n,r)=>swe(e(await this.parseResponse(n,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n,request_id:n.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(ue(this,AB,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};AB=new WeakMap});var e8,t8,kB,Pp,io,Hi=C(()=>{dv();tu();awe();QG();zC();t8=class{constructor(e,n,r,o){e8.set(this,void 0),at(this,e8,e,"f"),this.options=o,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new Ut("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await ue(this,e8,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(e8=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let n of e.getPaginatedItems())yield n}},kB=class extends O0{constructor(e,n,r){super(e,n,async(o,i)=>new r(o,i.response,await XG(o,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let n of e)yield n}},Pp=class extends t8{constructor(e,n,r,o){super(e,n,r,o),this.data=r.data||[],this.has_more=r.has_more||!1,this.first_id=r.first_id||null,this.last_id=r.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let n=this.first_id;return n?{...this.options,query:{...KG(this.options.query),before_id:n}}:null}let e=this.last_id;return e?{...this.options,query:{...KG(this.options.query),after_id:e}}:null}},io=class extends t8{constructor(e,n,r,o){super(e,n,r,o),this.data=r.data||[],this.next_page=r.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{...KG(this.options.query),page:e}}:null}}});function R0(t,e,n){return cwe(),new File(t,e??"unknown_file",n)}function MB(t,e){let n=typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"";return e?n.split(/[\\/]/).pop()||void 0:n}function nBt(t){let e=typeof t=="function"?t:t.fetch,n=MGe.get(e);if(n)return n;let r=(async()=>{try{let o="Resp
${i.map(f=>f.error).join(`
`)}
${s}
${d}`)}return s},et=uBt($Ge)});var PO,pwe=C(()=>{pi();Hi();ri();Ts();PO=class extends Mn{create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/environments?beta=true",{body:o,...n,headers:_e([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(et`/v1/environments/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(et`/v1/environments/${e}?beta=true`,{body:i,...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/environments?beta=true",io,{query:o,...n,headers:_e([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(et`/v1/environments/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,n={},r){let{betas:o}=n??{};return this._client.post(et`/v1/environments/${e}/archive?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}});function r8(t){return typeof t=="object"&&t!==null&&NB in t}function mwe(t,e){let n=new Set;if(t)for(let r of t)r8(r)&&n.add(r[NB]);if(e){for(let r of e)if(r8(r)&&n.add(r[NB]),Array.isArray(r.content))for(let o of r.content)r8(o)&&n.add(o[NB])}return Array.from(n)}function o8(t,e){let n=mwe(t,e);return n.length===0?{}:{"x-stainless-helper":n.join(", ")}}function FGe(t){return r8(t)?{"x-stainless-helper":t[NB]}:{}}var NB,OB=C(()=>{NB=Symbol("anthropic.sdk.stainlessHelper")});var EO,hwe=C(()=>{pi();Hi();ri();OB();IO();Ts();EO=class extends Mn{list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/files?beta=true",Pp,{query:o,...n,headers:_e([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(et`/v1/files/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString()},r?.headers])})}download(e,n={},r){let{betas:o}=n??{};return this._client.get(et`/v1/files/${e}/content?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}retrieveMetadata(e,n={},r){let{betas:o}=n??{};return this._client.get(et`/v1/files/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString()},r?.headers])})}upload(e,n){let{betas:r,...o}=e;return this._client.post("/v1/files?beta=true",TO({body:o,...n,headers:_e([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},FGe(o.file),n?.headers])},this._client))}}});var AO,gwe=C(()=>{pi();Hi();ri();Ts();AO=class extends Mn{retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(et`/v1/models/${e}?beta=true`,{...r,headers:_e([{...o?.toString()!=null?{"anthropic-beta":o?.toString()}:void 0},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/models?beta=true",Pp,{query:o,...n,headers:_e([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}}});var kO,ywe=C(()=>{pi();Hi();ri();Ts();kO=class extends Mn{create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/user_profiles?beta=true",{body:o,...n,headers:_e([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(et`/v1/user_profiles/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(et`/v1/user_profiles/${e}?beta=true`,{body:i,...r,headers:_e([{"anthropic-beta":[...o??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/user_profile
1. Task Overview
The user's core request and success criteria
Any clarifications or constraints they specified
2. Current State
What has been completed so far
Files created, modified, or analyzed (with paths if relevant)
Key outputs or artifacts produced
3. Important Discoveries
Technical constraints or requirements uncovered
Decisions made and their rationale
Errors encountered and how they were resolved
What approaches were tried that didn't work (and why)
4. Next Steps
Specific actions needed to complete the task
Any blockers or open questions to resolve
Priority order if multiple steps remain
5. Context to Preserve
User preferences or style requirements
Domain-specific details that aren't obvious
Any promises made to the user
Be concise but complete\u2014err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
Wrap your summary in <summary></summary> tags.`});function GGe(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function TBt(t,e=t.messages.at(-1),n){if(!e||e.role!=="assistant"||!e.content||typeof e.content=="string")return null;let r=e.content.filter(i=>i.type==="tool_use");return r.length===0?null:{role:"user",content:await Promise.all(r.map(async i=>{let s=t.tools.find(a=>("name"in a?a.name:a.mcp_server_name)===i.name);if(!s||!("run"in s))return{type:"tool_result",tool_use_id:i.id,content:`Error: Tool '${i.name}' not found`,is_error:!0};try{let a=i.input;"parse"in s&&s.parse&&(a=s.parse(a));let l=await s.run(a,{toolUseBlock:i,signal:n?.signal});return{type:"tool_result",tool_use_id:i.id,content:l}}catch(a){return{type:"tool_result",tool_use_id:i.id,content:a instanceof $0?a.content:`Error: ${a instanceof Error?a.message:String(a)}`,is_error:!0}}}))}}var BB,$O,F0,Ys,Qu,lf,gv,HC,zB,qGe,Owe,FO,Rwe=C(()=>{dv();h8();tu();ri();KGe();OB();FO=class{constructor(e,n,r){BB.add(this),this.client=e,$O.set(this,!1),F0.set(this,!1),Ys.set(this,void 0),Qu.set(this,void 0),lf.set(this,void 0),gv.set(this,void 0),HC.set(this,void 0),zB.set(this,0),at(this,Ys,{params:{...n,messages:structuredClone(n.messages)}},"f");let i=["BetaToolRunner",...mwe(n.tools,n.messages)].join(", ");at(this,Qu,{...r,headers:_e([{"x-stainless-helper":i},r?.headers])},"f"),at(this,HC,GGe(),"f"),n.compactionControl?.enabled&&console.warn('Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction')}async*[($O=new WeakMap,F0=new WeakMap,Ys=new WeakMap,Qu=new WeakMap,lf=new WeakMap,gv=new WeakMap,HC=new WeakMap,zB=new WeakMap,BB=new WeakSet,qGe=async function(){let n=ue(this,Ys,"f").params.compactionControl;if(!n||!n.enabled)return!1;let r=0;if(ue(this,lf,"f")!==void 0)try{let c=await ue(this,lf,"f");r=c.usage.input_tokens+(c.usage.cache_creation_input_tokens??0)+(c.usage.cache_read_input_tokens??0)+c.usage.output_tokens}catch{return!1}let o=n.contextTokenThreshold??1e5;if(r<o)return!1;let i=n.model??ue(this,Ys,"f").params.model,s=n.summaryPrompt??HGe,a=ue(this,Ys,"f").params.messages;if(a[a.length-1].role==="assistant"){let c=a[a.length-1];if(Array.isArray(c.content)){let u=c.content.filter(d=>d.type!=="tool_use");u.length===0?a.pop():c.content=u}}let l=await this.client.beta.messages.create({model:i,messages:[...a,{role:"user",content:[{type:"text",text:s}]}],max_tokens:ue(this,Ys,"f").params.max_tokens},{signal:ue(this,Qu,"f").signal,headers:_e([ue(this,Qu,"f").headers,{"x-stainless-helper":"compaction"}])});if(l.content[0]?.type!=="text")throw new Ut("Expected text response for compaction");return ue(this,Ys,"f").params.messages=[{role:"user",content:l.content}],!0},Symbol.asyncIterator)](){var e;if(ue(this,$O,"f"))throw new Ut("Cannot iterate over a consumed stream");at(this,$O,!0,"f"),at(this,F0,!0,"f"),at(this,gv,void 0,"f");try{for(;;){let n;try{if(ue(this,Ys,"f").params.max_iterations&&ue(this,zB,"f")>=ue(this,Ys,"f").params.max_iterations)break;at(this,F0,!1,"f"),at(this,gv,void 0,"f"),at(this,zB,(e=ue(this,zB,"f"),e++,e),"f"),at(this,lf,void 0,"f");let{max_iterations:r,compactionControl:o,...i}=ue(this,Ys,"f").params;if(i.stream?(n=this.client.beta.messages.stream({...i},ue(this,Qu,"f")),at(this,lf,n.finalMessage(),"f"),ue(this,lf,"f").catch(()=>{}),yield n):(at(this,lf,this.client.beta.messages.create({...i,stream:!1},ue(this,Qu,"f")),"f"),yield ue(this,lf,"f")),!await ue(this,BB,"m",qGe).call(this)){if(!ue(this,F0,"f")){let{role:l,content:c}=await ue(this,lf,"f");ue(this,Ys,"f").params.messages.push({role:l,content:c})}let a=await ue(this,BB,"m",Owe).call(this,ue(this,Ys,"f").params.messages.at(-1));if(a)ue(this,Ys,"f").params.messages.push(a);else if(!ue(this,F0,"f"))break}}finally{n&&n.abort()}}if(!ue(this,lf,"f"))throw new Ut("ToolRunner concluded without a message from the server")
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),PBt.includes(i.model)&&i.thinking&&i.thinking.type==="enabled"&&console.warn(`Using Claude with ${i.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let s=this._client._options.timeout;if(!i.stream&&s==null){let l=i8[i.model]??void 0;s=this._client.calculateNonstreamingTimeout(i.max_tokens,l)}let a=o8(i.tools,i.messages);return this._client.post("/v1/messages?beta=true",{body:i,timeout:s??6e5,...n,headers:_e([{...o?.toString()!=null?{"anthropic-beta":o?.toString()}:void 0},a,n?.headers]),stream:r.stream??!1})}parse(e,n){return n={...n,headers:_e([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},n?.headers])},this.create(e,n).then(r=>Twe(r,e,{logger:this._client.logger??console}))}stream(e,n){return m8.createMessage(this,e,n)}countTokens(e,n){let r=ZGe(e),{betas:o,...i}=r;return this._client.post("/v1/messages/count_tokens?beta=true",{body:i,...n,headers:_e([{"anthropic-beta":[...o??[],"token-counting-2024-11-01"].toString()},n?.headers])})}toolRunner(e,n){return new FO(this._client,e,n)}};yv.Batches=BO;yv.BetaToolRunner=FO;yv.ToolError=$0});var zO,Fwe=C(()=>{pi();Hi();ri();Ts();zO=class extends Mn{list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(et`/v1/sessions/${e}/events?beta=true`,io,{query:i,...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}send(e,n,r){let{betas:o,...i}=n;return this._client.post(et`/v1/sessions/${e}/events?beta=true`,{body:i,...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}stream(e,n={},r){let{betas:o}=n??{};return this._client.get(et`/v1/sessions/${e}/events/stream?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers]),stream:!0})}}});var jO,Uwe=C(()=>{pi();Hi();ri();Ts();jO=class extends Mn{retrieve(e,n,r){let{session_id:o,betas:i}=n;return this._client.get(et`/v1/sessions/${o}/resources/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{session_id:o,betas:i,...s}=n;return this._client.post(et`/v1/sessions/${o}/resources/${e}?beta=true`,{body:s,...r,headers:_e([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(et`/v1/sessions/${e}/resources?beta=true`,io,{query:i,...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,n,r){let{session_id:o,betas:i}=n;return this._client.delete(et`/v1/sessions/${o}/resources/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}add(e,n,r){let{betas:o,...i}=n;return this._client.post(et`/v1/sessions/${e}/resources?beta=true`,{body:i,...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}});var KC,Bwe=C(()=>{pi();Fwe();Fwe();Uwe();Uwe();Hi();ri();Ts();KC=class extends Mn{constructor(){super(...arguments),this.events=new zO(this._client),this.resources=new jO(this._client)}create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/sessions?beta=true",{body:o,...n,headers:_e([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(et`/v1/sessions/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(et`/v1/sessions/${e}?beta=true`,{body:i,...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/se
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),FBt.includes(e.model)&&e.thinking&&e.thinking.type==="enabled"&&console.warn(`Using Claude with ${e.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let r=this._client._options.timeout;if(!e.stream&&r==null){let i=i8[e.model]??void 0;r=this._client.calculateNonstreamingTimeout(e.max_tokens,i)}let o=o8(e.tools,e.messages);return this._client.post("/v1/messages",{body:e,timeout:r??6e5,...n,headers:_e([o,n?.headers]),stream:e.stream??!1})}parse(e,n){return this.create(e,n).then(r=>Gwe(r,e,{logger:this._client.logger??console}))}stream(e,n){return C8.createMessage(this,e,n,{logger:this._client.logger??console})}countTokens(e,n){return this._client.post("/v1/messages/count_tokens",{body:e,...n})}},r8e={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026","claude-3-5-haiku-latest":"February 19th, 2026","claude-3-5-haiku-20241022":"February 19th, 2026","claude-opus-4-0":"June 15th, 2026","claude-opus-4-20250514":"June 15th, 2026","claude-sonnet-4-0":"June 15th, 2026","claude-sonnet-4-20250514":"June 15th, 2026"},FBt=["claude-mythos-preview","claude-opus-4-6"];GC.Batches=KO});var V0,rve=C(()=>{pi();Hi();ri();Ts();V0=class extends Mn{retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(et`/v1/models/${e}`,{...r,headers:_e([{...o?.toString()!=null?{"anthropic-beta":o?.toString()}:void 0},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/models",Pp,{query:o,...n,headers:_e([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}}});var o8e=C(()=>{RGe();Hwe();Kwe();nve();rve()});var GB,ove=C(()=>{GB=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0}});var ive,sve,_8,i8e,s8e,a8e,Ei,cy,ave=C(()=>{dv();Kye();zC();Zye();pO();Xye();_O();SGe();ewe();Jye();tu();Hi();fwe();o8e();QG();Kwe();rve();Hwe();nve();Xye();ri();ove();PB();zC();s8e="\\n\\nHuman:",a8e="\\n\\nAssistant:",Ei=class{constructor({baseURL:e=GB("ANTHROPIC_BASE_URL"),apiKey:n=GB("ANTHROPIC_API_KEY")??null,authToken:r=GB("ANTHROPIC_AUTH_TOKEN")??null,...o}={}){ive.add(this),_8.set(this,void 0);let i={apiKey:n,authToken:r,...o,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&vGe())throw new Ut(`It looks like you're running in a browser-like environment.
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
`);this.baseURL=i.baseURL,this.timeout=i.timeout??sve.DEFAULT_TIMEOUT,this.logger=i.logger??console;let s="warn";this.logLevel=s,this.logLevel=rwe(i.logLevel,"ClientOptions.logLevel",this)??rwe(GB("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??s,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??bGe(),at(this,_8,_Ge,"f"),this._options=i,this.apiKey=typeof n=="string"?n:null,this.authToken=r}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){if(!(e.get("x-api-key")||e.get("authorization"))&&!(this.apiKey&&e.get("x-api-key"))&&!n.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!n.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return _e([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return _e([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return _e([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return TGe(e)}getUserAgent(){return`${this.constructor.name}/JS ${jC}`}defaultIdempotencyKey(){return`stainless-node-retry-${Hye()}`}makeStatusError(e,n,r,o){return Va.generate(e,n,r,o)}buildURL(e,n,r){let o=!ue(this,ive,"m",i8e).call(this)&&r||this.baseURL,i=fGe(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery(),a=Object.fromEntries(i.searchParams);return(!Yye(s)||!Yye(a))&&(n={...a,...s,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(i.search=this.stringifyQuery(n)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new Ut("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:n,options:r}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,r){return this.request(Promise.resolve(r).then(o=>({method:e,path:n,...o})))}request(e,n=null){return new O0(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,r){let o=await e,i=o.maxRetries??this.maxRetries;n==null&&(n=i),await this.prepareOptions(o);let{req:s,url:a,timeout:l}=await this.buildRequest(o,{retryCount:i-n});await this.prepareRequest(s,{url:a,options:o});let c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(Wa(this).debug(`[${c}] sending request`,mv({retryOfRequestLogID:r,method:o.method,url:a,options:o,headers:s.headers})),o.signal?.aborted)throw new Il;let f=new AbortController,p=await this.fetchWithTimeout(a,s,l,f).catch(SB),m=Date.now();if(p instanceof globalThis.Error){let y=`retrying, ${n} attempts remaining`;if(o.signal?.aborted)throw new Il;let w=fv(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(n)return Wa(this).info(`[${c}] connection ${w?"timed out":"failed"} - ${y}`),Wa(this).debug(`[${c}] connection ${w?"timed out":"failed"} (${y})`,mv({retryOfRequestLogID:r,url:a,durationMs:m-d,message:p.message})),this.retryRequest(o,n,r??c);throw Wa(this).info(`[${c}] connection ${w?"timed out":"failed"} - error; no more retries left`),Wa(this).debug(`[${c}] connection ${w?"timed out":"failed"} (error; no more retries left)`,mv({retryOfRequestLogID:r,url:a,durationMs:m-d,message:p.message})),w?new mO:new BC({cause:p})}let h=[...p.headers.entries()].filter(([y])=>y==="request-id").map(([y,w])=>", "+y+": "+JSON.s
`:"")+"{"+Object.entries(t).map(([d,f])=>`${d}: ${JSON.stringify(f)}`).join(", ")+"}"}return e}var BBt,f8e=C(()=>{u8e();BBt=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"])});function VBt(t){return t?Object.entries(jBt).find(([e])=>t.startsWith(e))?.[1]??p8e:p8e}function WBt(t){return!!(t.tools&&t.tools.length>0)}function HBt(t){for(let e of t.messages??[])if(typeof e.content!="string"){for(let n of e.content??[])if(typeof n=="object"&&n!=null&&n.type==="document"&&typeof n.citations=="object"&&n.citations?.enabled)return!0}return!1}function KBt(t){return!!(t.thinking&&(t.thinking.type==="enabled"||t.thinking.type==="adaptive"))}function qBt(t){return!!t.context_management?.edits?.some(e=>e.type==="compact_20260112")}function GBt(t){return"input_schema"in t}function YBt(t){return typeof t=="object"&&t!==null&&"type"in t&&("name"in t||"mcp_server_name"in t)&&typeof t.type=="string"&&["text_editor_","computer_","bash_","web_search_","web_fetch_","str_replace_editor_","str_replace_based_edit_tool_","code_execution_","memory_","tool_search_","mcp_toolset"].some(e=>typeof t.type=="string"&&t.type.startsWith(e))}function ZBt(t,e,...n){return Array.from(new Set([...t??[],...e??[],...n.flatMap(r=>Array.from(r))]))}function JBt(t){if(typeof t.content=="string")return t.content;if(Array.isArray(t.content)&&t.content.length>=1&&"input"in t.content[0])return typeof t.content[0].input=="string"?t.content[0].input:JSON.stringify(t.content[0].input);if(Array.isArray(t.content)&&t.content.length>=1&&"text"in t.content[0]&&typeof t.content[0].text=="string")return t.content[0].text}var jBt,p8e,m8e,lve,h8e=C(()=>{Rye();zqe();jye();nGe();sGe();aGe();cGe();dGe();l8e();f8e();Kr();ac();Jo();vI();qd();Bu();Bd();pI();y2();wde();jBt={"claude-opus-4-7":16384,"claude-opus-4-6":16384,"claude-sonnet-4-6":16384,"claude-opus-4-5":16384,"claude-sonnet-4-5":16384,"claude-haiku-4-5":16384,"claude-opus-4-1":16384,"claude-sonnet-4":16384,"claude-opus-4":16384,"claude-3-7-sonnet":8192,"claude-3-5-sonnet":8192,"claude-3-5-haiku":8192,"claude-3-opus":4096,"claude-3-sonnet":4096,"claude-3-haiku":4096},p8e=4096;m8e=class extends dp{constructor(e,n){let r=typeof e=="string"?{...n??{},model:e}:e??{};super(r??{});I(this,"lc_serializable",!0);I(this,"anthropicApiKey");I(this,"apiKey");I(this,"apiUrl");I(this,"temperature");I(this,"topK");I(this,"topP");I(this,"maxTokens");I(this,"modelName","claude-sonnet-4-5-20250929");I(this,"model","claude-sonnet-4-5-20250929");I(this,"invocationKwargs");I(this,"stopSequences");I(this,"streaming",!1);I(this,"clientOptions");I(this,"thinking",{type:"disabled"});I(this,"contextManagement");I(this,"outputConfig");I(this,"inferenceGeo");I(this,"batchClient");I(this,"streamingClient");I(this,"streamUsage",!0);I(this,"betas");I(this,"createClient");if(this._addVersion("@langchain/anthropic","1.3.29"),this.anthropicApiKey=r?.apiKey??r?.anthropicApiKey??In("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!r?.createClient)throw new Error("Anthropic API key not found");this.clientOptions=r?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=r?.anthropicApiUrl,this.modelName=r?.model??r?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=r?.invocationKwargs??{},this.topP=r?.topP??this.topP,this.temperature=r?.temperature??this.temperature,this.topK=r?.topK??this.topK,this.maxTokens=r?.maxTokens??VBt(this.model),this.stopSequences=r?.stopSequences??this.stopSequences,this.streaming=r?.streaming??!1,this.streamUsage=r?.streamUsage??this.streamUsage,this.thinking=r?.thinking??this.thinking,this.contextManagement=r?.contextManagement??this.contextManagement,this.outputConfig=r?.outputConfig??this.outputConfig,this.inferenceGeo=r?.inferenceGeo??this.inferenceGeo,this.betas=r?.betas??this.betas,this.createClient=r?.createClient??(o=>new cy(o))}static lc_name(){return"ChatAnthropic"}get lc_secrets(){return{anthropicApiKey:"ANTHROPIC_API_KEY",apiKey:"ANTHROPIC_API_KEY"}}get lc_aliases(){return{modelName:"model"}}getLsParams(e){let n=this.invocationParams(e);return{ls_provider:
`);o.enqueue(a)}catch(i){o.error(i)}},async cancel(){await n.return?.()}})}},wve=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,o]=_zt(e,":");return o.startsWith(" ")&&(o=o.substring(1)),n==="event"?this.event=o:n==="data"&&this.data.push(o),null}},YO=class t{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){let n=this.decodeText(e);if(this.trailingCR&&(n="\r"+n,this.trailingCR=!1),n.endsWith("\r")&&(this.trailingCR=!0,n=n.slice(0,-1)),!n)return[];let r=t.NEWLINE_CHARS.has(n[n.length-1]||""),o=n.split(t.NEWLINE_REGEXP);return o.length===1&&!r?(this.buffer.push(o[0]),[]):(this.buffer.length>0&&(o=[this.buffer.join("")+o[0],...o.slice(1)],this.buffer=[]),r||(this.buffer=[o.pop()||""]),o)}decodeText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new El(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new El(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new El("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}};YO.NEWLINE_CHARS=new Set([`
`,"\r","\v","\f","","","","\x85","\u2028","\u2029"]);YO.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g});async function bve(t,e,n){if(t=await t,t9e(t))return t;if(e9e(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=sz(o)?[await o.arrayBuffer()]:[o];return new S8(i,e,n)}let r=await Tzt(t);if(e||(e=Pzt(t)??"unknown_file"),!n?.type){let o=r[0]?.type;typeof o=="string"&&(n={...n,type:o})}return new S8(r,e,n)}async function Tzt(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(sz(t))e.push(await t.arrayBuffer());else if(Ezt(t))for await(let n of t)e.push(n);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${Izt(t)}`);return e}function Izt(t){return`[${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}function Pzt(t){return vve(t.name)||vve(t.filename)||vve(t.path)?.split(/[\\/]/).pop()}var e9e,t9e,sz,Szt,vve,Ezt,Cve,G0,n9e,xve,A8=C(()=>{ZB();ZB();e9e=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",t9e=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&sz(t),sz=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",Szt=t=>t9e(t)||e9e(t)||hve(t);vve=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},Ezt=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Cve=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody",G0=async t=>{let e=await n9e(t.body);return pve(e,t)},n9e=async t=>{let e=new dve;return await Promise.all(Object.entries(t||{}).map(([n,r])=>xve(e,n,r))),e},xve=async(t,e,n)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(Szt(n)){let r=await bve(n);t.append(e,r)}else if(Array.isArray(n))await Promise.all(n.map(r=>xve(t,e+"[]",r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([r,o])=>xve(t,`${e}[${r}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}}});async function l9e(t){let{response:e}=t;if(t.options.stream)return ZO("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):E8.fromSSEResponse(e,t.controller);if(e.status===204)return null;if(t.options.__binaryResponse)return e;let r=e.headers.get("content-type")?.split(";")[0]?.trim();if(r?.includes("application/json")||r?.endsWith("+json")){let s=await e.json();return ZO("response",e.status,e.url,e.headers,s),s}let i=await e.text();return ZO("response",e.status,e.url,e.headers,i),i}function Rzt(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:n}of t){let r=n.exec(navigator.userAgent);if(r){let o=r[1]||0,i=r[2]||0,s=r[3]||0;return{browser:e,version:`${o}.${i}.${s}`}}}return null}function Bzt(t){if(!t)return!0;for(let e in t)return!1;return!0}function zzt(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function a9e(t,e){for(let n in e){if(!zzt(e,n))continue;let r=n.toLowerCase();if(!r)continue;let o=e[n];o===null?delete t[r]:o!==void 0&&(t[r]=o)}}function ZO(t,...e){typeof process<"u"&&process?.env?.DEBUG==="true"&&console.log(`Groq:DEBUG:${t}`,...e)}var kzt,Mzt,k8,N8,O8,r9e,Sve,Nzt,Ozt,o9e,i9e,s9e,Lzt,Dzt,$zt,Fzt,Uzt,_ve
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
new Groq({ apiKey, dangerouslyAllowBrowser: true })`);super({baseURL:o.baseURL,timeout:o.timeout??6e4,httpAgent:o.httpAgent,maxRetries:o.maxRetries,fetch:o.fetch}),this.completions=new Z0(this),this.chat=new ZC(this),this.embeddings=new J0(this),this.audio=new uy(this),this.models=new Q0(this),this.batches=new Y0(this),this.files=new X0(this),this._options=o,this.apiKey=n}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}};f9e=wo;wo.Groq=f9e;wo.DEFAULT_TIMEOUT=6e4;wo.GroqError=El;wo.APIError=Ha;wo.APIConnectionError=YC;wo.APIConnectionTimeoutError=qO;wo.APIUserAbortError=q0;wo.NotFoundError=ez;wo.ConflictError=tz;wo.RateLimitError=rz;wo.BadRequestError=JB;wo.AuthenticationError=XB;wo.InternalServerError=oz;wo.PermissionDeniedError=QB;wo.UnprocessableEntityError=nz;wo.toFile=bve;wo.fileFromPath=T8;wo.Completions=Z0;wo.Chat=ZC;wo.Embeddings=J0;wo.Audio=uy;wo.Models=Q0;wo.Batches=Y0;wo.Files=X0;p9e=wo});function Xzt(t){if(t.role!=="system"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function")throw new Error(`Unsupported message role: ${t.role}. Expected "system", "assistant", "user", or "function"`);return t.role}function g9e(t){switch(t.type){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!rc.isInstance(t))throw new Error("Invalid generic chat message");return Xzt(t);default:throw new Error(`Unknown message type: ${t.type}`)}}function h9e(t){return t.map(e=>{let n={role:g9e(e),content:e.content,name:e.name,function_call:e.additional_kwargs.function_call,tool_calls:e.additional_kwargs.tool_calls,tool_call_id:e.tool_call_id};return rp(e)&&e.tool_calls?.length?n.tool_calls=e.tool_calls.map(cU):(e.additional_kwargs.tool_calls!=null&&(n.tool_calls=e.additional_kwargs.tool_calls),e.tool_call_id!=null&&(n.tool_call_id=e.tool_call_id)),n})}function Qzt(t,e,n){let r=t.tool_calls;switch(t.role){case"assistant":{let o=[],i=[];for(let s of r??[])try{o.push(Xb(s,{returnId:!0}))}catch(a){i.push(Bw(s,a.message))}return new kn({content:t.content||"",additional_kwargs:{tool_calls:r},tool_calls:o,invalid_tool_calls:i,usage_metadata:e,response_metadata:n})}default:return new rc(t.content||"",t.role??"unknown")}}function ejt(t,e,n,r){let o=t.role??e,i=t.content??"",s;t.function_call?s={function_call:t.function_call}:t.tool_calls?s={tool_calls:t.tool_calls}:s={},t.audio&&(s.audio={...t.audio,index:n.choices[0].index});let a,l=r,c,u=n.x_groq;u?.usage&&(a={input_tokens:u.usage.prompt_tokens,output_tokens:u.usage.completion_tokens,total_tokens:u.usage.total_tokens},c={completion_time:u.usage.completion_time,prompt_time:u.usage.prompt_time,queue_time:u.usage.queue_time,total_time:u.usage.total_time}),u?.id&&(l=u.id);let d={usage:a,timing:c};if(o==="user")return new Ub({content:i,response_metadata:d});if(o==="assistant"){let f=[];if(Array.isArray(t.tool_calls))for(let p of t.tool_calls)f.push({name:p.function?.name,args:p.function?.arguments,id:p.id,index:p.index,type:"tool_call_chunk"});return new Yt({content:i,tool_call_chunks:f,additional_kwargs:s,id:l,response_metadata:d})}else return o==="system"?new Sg({content:i,response_metadata:d}):o==="developer"?new Sg({content:i,response_metadata:d,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new Fb({content:i,additional_kwargs:s,name:t.name,response_metadata:d}):o==="tool"?new Bk({content:i,additional_kwargs:s,tool_call_id:t.tool_call_id,response_metadata:d}):new $b({content:i,role:o,response_metadata:d})}function tjt(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}var Yzt,Zzt,Jzt,$ve,y9e=C(()=>{Bu();vI();Kr();ac();Jo();Bd();m9e();jm();Uw();fM();pI();Yzt=["frequency_penalty","function_call","functions","logit_bias","logprobs","max_completion_tokens","max_tokens","n","parallel_tool_calls","presence_penalty","reasoning_format","respons
`).map(n=>n.trim()).filter(n=>n.length>0):[]}parseEventStreamBuffer(e){let n=[];if(e.length<12)return{messages:n,remainingBytes:e};let r=new DataView(e.buffer,e.byteOffset,e.byteLength),o=0;for(;o+12<=e.length;){let s=r.getUint32(o,!1),a=r.getUint32(o+4,!1);if(o+s>e.length)break;if(s<=0||a<0||a+12>s){ee(`parseEventStreamBuffer: Invalid message structure at offset ${o}: totalLength=${s}, headersLength=${a}`);break}let l=o+12+a,c=o+s-4;if(l>c||c>e.length){ee(`parseEventStreamBuffer: Invalid payload bounds at offset ${o}`);break}if(l<e.length){let u=e.subarray(l,c),d=this.decodeUtf8(u).trim();d.length>0&&n.push(d)}if(o+=s,s===0)break}let i=o<e.length?e.subarray(o):new Uint8Array(0);return{messages:n,remainingBytes:i}}decodeEventStreamMessages(e){let{messages:n}=this.parseEventStreamBuffer(e);return n}buildChunkMetadata(e){let n={provider:"amazon-bedrock"};typeof e?.type=="string"&&(n.event_type=e.type),e?.index!==void 0&&(n.event_index=e.index);let r=this.extractStopReason(e);r&&(n.stop_reason=r);let o=this.extractUsage(e);return o&&(n.usage=o),n}extractStreamText(e){if(!e||typeof e!="object")return null;let n=e.delta,r=e.content_block_delta,o=e.contentBlockDelta,i=r?.delta,s=o?.delta,a=[n?.thinking,i?.thinking,s?.thinking,n?.reasoning_content,e.reasoning_content];for(let h of a)if(typeof h=="string"&&h.length>0)return h;let l=[e.text,e.outputText,e.completion,e.resultText,e.delta];for(let h of l)if(typeof h=="string"&&h.length>0)return h;let c=e.message,u=e.messageStop,d=e.message_stop,f=u?.message,p=d?.message,m=[n?.text,n?.output_text,n?.content,s?.text,s?.output_text,s?.content,i?.text,i?.output_text,i?.content,c?.content,f?.content,p?.content,e.content];for(let h of m){let g=this.extractTextFromCandidate(h);if(g)return g}return null}extractTextFromCandidate(e){if(!e)return null;if(typeof e=="string")return e.length>0?e:null;if(Array.isArray(e)){let n=e.map(r=>{if(typeof r=="string")return r;if(r&&typeof r=="object"){let o=r;if(typeof o.text=="string")return o.text;if(typeof o.value=="string")return o.value;if(Array.isArray(o.content))return o.content.map(i=>{let s=i;return typeof s?.text=="string"?s.text:""}).join("")}return""}).join("");return n.length>0?n:null}if(typeof e=="object"){let n=e;if(typeof n.text=="string")return n.text.length>0?n.text:null;if(n.text&&typeof n.text=="object"){let r=this.extractTextFromCandidate(n.text);if(r)return r}if(typeof n.value=="string")return n.value.length>0?n.value:null;if(Array.isArray(n.content))return this.extractTextFromCandidate(n.content);if(n.delta){let r=this.extractTextFromCandidate(n.delta);if(r)return r}if(n.message&&typeof n.message=="object"){let r=this.extractTextFromCandidate(n.message);if(r)return r}}return null}extractUsage(e){if(!(!e||typeof e!="object")){if(e.usage&&typeof e.usage=="object")return e.usage;if(e.metrics&&typeof e.metrics=="object")return e.metrics;if(e["amazon-bedrock-invocationMetrics"]&&typeof e["amazon-bedrock-invocationMetrics"]=="object")return e["amazon-bedrock-invocationMetrics"];if(e.messageStop&&typeof e.messageStop=="object")return this.extractUsage(e.messageStop);if(e.message_stop&&typeof e.message_stop=="object")return this.extractUsage(e.message_stop)}}extractStopReason(e){if(!e||typeof e!="object")return;let n=e.messageStop,r=e.message_stop,o=e.stop_reason||e.stopReason||e.completionReason||e.completion_reason||e.reason||n?.stopReason||r?.stop_reason||(e.type==="message_stop"?e.reason:void 0);return typeof o=="string"?o:void 0}buildTerminalMetadataChunk(e,n){let r=n?this.normaliseUsageMetadata(n):void 0,o={provider:"amazon-bedrock"};e&&(o.stop_reason=e),n&&(o.usage=n);let i=new Yt({content:"",response_metadata:o,usage_metadata:r});return new Jr({message:i,text:"",generationInfo:o})}normaliseUsageMetadata(e){let n=this.coerceNumber(e.inputTokens)??this.coerceNumber(e.input_tokens)??this.coerceNumber(e.inputTokenCount)??this.coerceNumber(e.promptTokens)??this.coerceNumber(e.prompt_tokens)??0,r=this.coerceNumber(e.outputTokens)??this.coerceNumber(e.output_tokens)??this.coerceNumber(e.outputTokenCount)??this.coerceNumber(e.completionTo
`)),i!==void 0&&(l.max_tokens=i),this.anthropicVersion&&(l.anthropic_version=this.anthropicVersion),this.enableThinking){let c=this.modelName.match(/claude-opus-4-(\d{1,2})(?:[-.]|$)/),u=c?parseInt(c[1],10)>=7:!1;l.thinking=u?{type:"adaptive",display:"summarized"}:{type:"enabled",budget_tokens:2048},l.temperature=1,k("[BedrockChatModel] Enabled thinking mode for Claude model with temperature=1")}else s!==void 0&&(l.temperature=s);return a!==void 0&&(l.top_p=a),l}normaliseMessageContent(e){let{content:n}=e;return typeof n=="string"?n:Array.isArray(n)?n.some(o=>typeof o=="object"&&o!==null&&(o.type==="image_url"||o.type==="image"))?n.map(o=>{if(typeof o=="string")return{type:"text",text:o};if(typeof o=="object"&&o!==null){if(o.type==="text"||o.type==="image_url"||o.type==="image")return o;if("text"in o&&typeof o.text=="string")return{type:"text",text:o.text};if("content"in o&&typeof o.content=="string")return{type:"text",text:o.content}}return null}).filter(o=>o!==null):n.map(o=>{if(typeof o=="string")return o;if(typeof o=="object"&&o!==null){if("text"in o&&typeof o.text=="string")return o.text;if("content"in o&&typeof o.content=="string")return o.content}return""}).join(""):typeof n=="object"&&n!==null&&"text"in n?n.text??"":""}extractText(e){return typeof e?.outputText=="string"?e.outputText:Array.isArray(e?.content)?e.content.map(n=>{if(!n)return"";if(typeof n=="string")return n;if(typeof n=="object"){let r=n;if(typeof r.text=="string")return r.text;if(r.text&&typeof r.text=="object"&&"text"in r.text)return r.text.text??""}return""}).join(""):typeof e?.completion=="string"?e.completion:typeof e?.resultText=="string"?e.resultText:""}}});function Uve(t){return t instanceof Mp||t instanceof Error&&t.name==="AuthCancelledError"}var Mp,Bve=C(()=>{Mp=class t extends Error{constructor(n="Authentication cancelled by user."){super(n);this.name="AuthCancelledError";Object.setPrototypeOf(this,t.prototype)}}});var lz,T9e,rjt,ojt,ijt,cz,sjt,ajt,I9e,ljt,sh,uz=C(()=>{Se();Su();lz=require("obsidian");Bve();T9e="Iv1.b507a08c87ecfe98",rjt="https://github.com/login/device/code",ojt="https://github.com/login/oauth/access_token",ijt="https://api.github.com/copilot_internal/v2/token",cz="https://api.githubcopilot.com",sjt=`${cz}/models`,ajt=60*1e3,I9e=60*60*1e3,ljt=3,sh=class t{constructor(){this.abortController=null;this.refreshPromise=null;this.refreshAttempts=0;this.modelPolicyTermsCache=new Map;this.authGeneration=0}static getInstance(){return t.instance||(t.instance=new t),t.instance}getAuthState(){let e=q(),n=!!e.githubCopilotAccessToken,r=!!e.githubCopilotToken,o=e.githubCopilotTokenExpiresAt,s=!(typeof o=="number"&&o>0)||o<Date.now();return r&&!s||r&&n?{status:"authenticated"}:n?{status:"pending"}:{status:"idle"}}isAuthenticated(){return this.getAuthState().status==="authenticated"}async startDeviceCodeFlow(){let e=new URLSearchParams({client_id:T9e,scope:"read:user"}).toString(),n=await(0,lz.requestUrl)({url:rjt,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:e,throw:!1}),r=this.getRequestUrlJson(n);if(n.status!==200){let i=typeof r.error_description=="string"?r.error_description:typeof r.error=="string"?r.error:"";throw new Error(i?`Failed to get device code: ${i}`:`Failed to get device code: ${n.status}`)}if(typeof r.device_code!="string"||typeof r.user_code!="string"||typeof r.expires_in!="number")throw new Error("Invalid device code response from GitHub");let o=typeof r.verification_uri=="string"?r.verification_uri:typeof r.verification_uri_complete=="string"?r.verification_uri_complete:null;if(!o)throw new Error("Invalid device code response from GitHub: missing verification URI");return{deviceCode:r.device_code,userCode:r.user_code,verificationUri:o,expiresIn:r.expires_in,interval:typeof r.interval=="number"&&r.interval>0?r.interval:5}}async pollForAccessToken(e,n,r,o){let i=this.authGeneration;this.abortPolling();let s=new AbortController;this.abortController=s;let a=Date.now()+r*1e3,l=0;try{for(;Date.now()<a;){if(s.signal.aborted||this.authGeneration!==i)throw new Mp
without CORS Error: `+Xt(r)+`
with CORS Error: `+Xt(o);throw new Error(i)}}}findModelByName(e){return q().activeModels.find(r=>r.name===e)}};as.ANTHROPIC_THINKING_BUDGET_TOKENS=2048,as.REASONING_MODEL_TEMPERATURE=1;Np=as});var k9e={};zn(k9e,{TieredLexicalRetriever:()=>ah});async function pjt(){try{if(!Wve){let e=await Promise.resolve().then(()=>(eP(),Vve));Wve=()=>e.default.getInstance()}return Wve().getChatModel()}catch{return null}}var Hve,Wve,ah,fz=C(()=>{ye();Se();qe();iv();lO();Hve=require("obsidian");iB();N0();Wve=null;ah=class extends ay{constructor(n,r){super();this.app=n;this.options=r;this.lc_namespace=["tiered_lexical_retriever"];this.lastQueryExpansion=null;this.searchCore=new VG(n,pjt),this.chunkManager=PC(n)}getLastQueryExpansion(){return this.lastQueryExpansion}async getRelevantDocuments(n,r){try{let i=Df(n,this.app.vault).map(f=>f.basename),s=[...new Set([...this.options.salientTerms,...i])];q().debug&&k("TieredLexicalRetriever: Starting search",{query:n,salientTerms:s,maxK:this.options.maxK});let a=q(),l=await this.searchCore.retrieve(n,{maxResults:this.options.maxK,salientTerms:s,enableLexicalBoosts:a.enableLexicalBoosts,preExpandedQuery:this.options.preExpandedQuery}),c=l.results;this.lastQueryExpansion=l.queryExpansion;let u=await this.convertToDocuments(c),d=this.sortResults(u);return q().debug&&k("TieredLexicalRetriever: Search complete",{totalResults:d.length,searchResults:c.length}),d}catch(o){return ee("TieredLexicalRetriever: Error during search",o),[]}}async convertToDocuments(n){let r=[];for(let o of n)try{if(o.id.includes("#")){let[s]=o.id.split("#"),a=this.app.vault.getAbstractFileByPath(s);if(!a||!(a instanceof Hve.TFile))continue;let l="",c=this.chunkManager;if(typeof c.getChunkText=="function"?l=await c.getChunkText(o.id):typeof c.getChunkTextSync=="function"&&(l=c.getChunkTextSync(o.id)||""),!l)continue;let u=this.app.metadataCache.getFileCache(a);r.push(new fi({pageContent:l,metadata:{path:s,chunkId:o.id,title:a.basename,mtime:a.stat.mtime,ctime:a.stat.ctime,tags:u?.tags?.map(d=>d.tag)||[],score:o.score,rerank_score:o.score,engine:o.engine||"chunk-v3",includeInContext:o.score>(this.options.minSimilarityScore||.1),explanation:o.explanation,isChunk:!0}}))}else{let s=this.app.vault.getAbstractFileByPath(o.id);if(!s||!(s instanceof Hve.TFile))continue;let a=await this.app.vault.cachedRead(s);if(!a)continue;let l=this.app.metadataCache.getFileCache(s);r.push(new fi({pageContent:a,metadata:{path:o.id,title:s.basename,mtime:s.stat.mtime,ctime:s.stat.ctime,tags:l?.tags?.map(c=>c.tag)||[],score:o.score,rerank_score:o.score,engine:o.engine||"v3",includeInContext:o.score>(this.options.minSimilarityScore||.1),explanation:o.explanation,isChunk:!1}}))}}catch(i){ee(`TieredLexicalRetriever: Failed to convert result ${o.id}`,i)}return k(`TieredLexicalRetriever: Converted ${r.length} results to Documents`),r}sortResults(n){return n.sort((r,o)=>{let i=r.metadata.score||0,a=(o.metadata.score||0)-i;if(Math.abs(a)>.01)return a;if(r.metadata.isChunk&&o.metadata.isChunk&&r.metadata.path===o.metadata.path){let l=parseInt(r.metadata.chunkId?.split("#")[1]||"0"),c=parseInt(o.metadata.chunkId?.split("#")[1]||"0");return l-c}return a})}}});var M9e={};zn(M9e,{MergedSemanticRetriever:()=>tP});var JC,tP,Kve=C(()=>{Nye();N0();fz();iv();lO();JC=class JC extends ay{constructor(n,r,o){super();this.app=n;this.options=r;this.lc_namespace=["merged_semantic_retriever"];this.originalMaxK=Math.max(1,r.maxK),this.returnAll=!!r.returnAll;let i=this.returnAll?ni:Math.min(this.originalMaxK*2,ni),s={...r,maxK:i,returnAll:this.returnAll};this.lexicalRetriever=new ah(n,s);let a=this.returnAll?ni:Math.min(this.originalMaxK*2,ni);this.semanticRetriever=o||new vB({minSimilarityScore:r.minSimilarityScore??.1,maxK:a,salientTerms:r.salientTerms,timeRange:r.timeRange,textWeight:r.textWeight,returnAll:this.returnAll,useRerankerThreshold:r.useRerankerThreshold})}async getRelevantDocuments(n){let[r,o]=await Promise.all([this.lexicalRetriever.getRelevantDocuments(n),this.semanticRetriever.getRelevantDocuments(n)]),i=new Map;for(let l of r)this.insertResult(i,l,"lexical");fo
`&&(u(),l="",c=0,n=!1);if(!h.scan(d))break;if(s=!0,y=h.scan(NWt)||"name",h.scan(AWt),y==="="?(w=h.scanUntil(r7e),h.scan(r7e),h.scanUntil(f)):y==="{"?(w=h.scanUntil(p),h.scan(MWt),h.scanUntil(f),y="&"):w=h.scanUntil(f),!h.scan(f))throw new Error("Unclosed tag at "+h.pos);if(y==">"?x=[y,w,g,h.pos,l,c,n]:x=[y,w,g,h.pos],c++,o.push(x),y==="#"||y==="^")r.push(x);else if(y==="/"){if(b=r.pop(),!b)throw new Error('Unopened section "'+w+'" at '+g);if(b[1]!==w)throw new Error('Unclosed section "'+b[1]+'" at '+g)}else y==="name"||y==="{"||y==="&"?a=!0:y==="="&&m(w)}if(u(),b=r.pop(),b)throw new Error('Unclosed section "'+b[1]+'" at '+h.pos);return LWt(RWt(o))}function RWt(t){for(var e=[],n,r,o=0,i=t.length;o<i;++o)n=t[o],n&&(n[0]==="text"&&r&&r[0]==="text"?(r[1]+=n[1],r[3]=n[3]):(e.push(n),r=n));return e}function LWt(t){for(var e=[],n=e,r=[],o,i,s=0,a=t.length;s<a;++s)switch(o=t[s],o[0]){case"#":case"^":n.push(o),r.push(o),n=o[4]=[];break;case"/":i=r.pop(),i[5]=o[2],n=r.length>0?r[r.length-1][4]:e;break;default:n.push(o)}return e}function ij(t){this.string=t,this.tail=t,this.pos=0}function vR(t,e){this.view=t,this.cache={".":this.view},this.parent=e}function ru(){this.templateCache={_cache:{},set:function(e,n){this._cache[e]=n},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}var xWt,xR,_Wt,TWt,PWt,AWt,kWt,r7e,MWt,NWt,Dp,oj,w9,o7e=C(()=>{xWt=Object.prototype.toString,xR=Array.isArray||function(e){return xWt.call(e)==="[object Array]"};_Wt=RegExp.prototype.test;TWt=/\S/;PWt={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};AWt=/\s*/,kWt=/\s+/,r7e=/\s*=/,MWt=/\s*\}/,NWt=/#|\^|\/|>|\{|&|=|!/;ij.prototype.eos=function(){return this.tail===""};ij.prototype.scan=function(e){var n=this.tail.match(e);if(!n||n.index!==0)return"";var r=n[0];return this.tail=this.tail.substring(r.length),this.pos+=r.length,r};ij.prototype.scanUntil=function(e){var n=this.tail.search(e),r;switch(n){case-1:r=this.tail,this.tail="";break;case 0:r="";break;default:r=this.tail.substring(0,n),this.tail=this.tail.substring(n)}return this.pos+=r.length,r};vR.prototype.push=function(e){return new vR(e,this)};vR.prototype.lookup=function(e){var n=this.cache,r;if(n.hasOwnProperty(e))r=n[e];else{for(var o=this,i,s,a,l=!1;o;){if(e.indexOf(".")>0)for(i=o.view,s=e.split("."),a=0;i!=null&&a<s.length;)a===s.length-1&&(l=n7e(i,s[a])||CWt(i,s[a])),i=i[s[a++]];else i=o.view[e],l=n7e(o.view,e);if(l){r=i;break}o=o.parent}n[e]=r}return zxe(r)&&(r=r.call(this.view)),r};ru.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};ru.prototype.parse=function(e,n){var r=this.templateCache,o=e+":"+(n||Dp.tags).join(":"),i=typeof r<"u",s=i?r.get(o):void 0;return s==null&&(s=OWt(e,n),i&&r.set(o,s)),s};ru.prototype.render=function(e,n,r,o){var i=this.getConfigTags(o),s=this.parse(e,i),a=n instanceof vR?n:new vR(n,void 0);return this.renderTokens(s,a,r,e,o)};ru.prototype.renderTokens=function(e,n,r,o,i){for(var s="",a,l,c,u=0,d=e.length;u<d;++u)c=void 0,a=e[u],l=a[0],l==="#"?c=this.renderSection(a,n,r,o,i):l==="^"?c=this.renderInverted(a,n,r,o,i):l===">"?c=this.renderPartial(a,n,r,i):l==="&"?c=this.unescapedValue(a,n):l==="name"?c=this.escapedValue(a,n,i):l==="text"&&(c=this.rawValue(a)),c!==void 0&&(s+=c);return s};ru.prototype.renderSection=function(e,n,r,o,i){var s=this,a="",l=n.lookup(e[1]);function c(f){return s.render(f,n,r,i)}if(l){if(xR(l))for(var u=0,d=l.length;u<d;++u)a+=this.renderTokens(e[4],n.push(l[u]),r,o,i);else if(typeof l=="object"||typeof l=="string"||typeof l=="number")a+=this.renderTokens(e[4],n.push(l),r,o,i);else if(zxe(l)){if(typeof o!="string")throw new Error("Cannot use higher-order sections without the original template");l=l.call(n.view,o.slice(e[3],e[5]),c),l!=null&&(a+=l)}else a+=this.renderTokens(e[4],n,r,o,i);return a}};ru.prototype.renderInverted=function(e,n,r,o,i){var s=n.lookup(e[1]);if(!s||xR(s)&&s.length===0)return this.renderTokens(e[4],n,r,o,i)};ru.prototype.indentPartial=function(e,n,r){for(var o=n.replace(/[^ \t]/g,""),i=e.split(`
`),s=0;s<i.length;s++)i[s].length&&(s>0||!r)&&(i[s]=o+i[s]);return i.join(`
`)};ru.prototype.renderPartial=function(e,n,r,o){if(r){var i=this.getConfigTags(o),s=zxe(r)?r(e[1]):r[e[1]];if(s!=null){var a=e[6],l=e[5],c=e[4],u=s;l==0&&c&&(u=this.indentPartial(s,c,a));var d=this.parse(u,i);return this.renderTokens(d,n,r,u,o)}}};ru.prototype.unescapedValue=function(e,n){var r=n.lookup(e[1]);if(r!=null)return r};ru.prototype.escapedValue=function(e,n,r){var o=this.getConfigEscape(r)||Dp.escape,i=n.lookup(e[1]);if(i!=null)return typeof i=="number"&&o===Dp.escape?String(i):o(i)};ru.prototype.rawValue=function(e){return e[1]};ru.prototype.getConfigTags=function(e){return xR(e)?e:e&&typeof e=="object"?e.tags:void 0};ru.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!xR(e))return e.escape};Dp={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(t){oj.templateCache=t},get templateCache(){return oj.templateCache}},oj=new ru;Dp.clearCache=function(){return oj.clearCache()};Dp.parse=function(e,n){return oj.parse(e,n)};Dp.render=function(e,n,r,o){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+bWt(e)+'" was given as the first argument for mustache#render(template, view, partials)');return oj.render(e,n,r,o)};Dp.escape=EWt;Dp.Scanner=ij;Dp.Context=vR;Dp.Writer=ru;w9=Dp});function i7e(){w9.escape=t=>t}var bR,s7e,sj,a7e,l7e,v9,c7e,df,CR,_R,uP=C(()=>{JT();o7e();bR=t=>{let e=t.split(""),n=[],r=(i,s)=>{for(let a=s;a<e.length;a+=1)if(i.includes(e[a]))return a;return-1},o=0;for(;o<e.length;)if(e[o]==="{"&&o+1<e.length&&e[o+1]==="{")n.push({type:"literal",text:"{"}),o+=2;else if(e[o]==="}"&&o+1<e.length&&e[o+1]==="}")n.push({type:"literal",text:"}"}),o+=2;else if(e[o]==="{"){let i=r("}",o);if(i<0)throw new Error("Unclosed '{' in template.");n.push({type:"variable",name:e.slice(o+1,i).join("")}),o=i+1}else{if(e[o]==="}")throw new Error("Single '}' in template.");{let i=r("{}",o),s=(i<0?e.slice(o):e.slice(o,i)).join("");n.push({type:"literal",text:s}),o=i<0?e.length:i}}return n},s7e=(t,e=[])=>{let n=[];for(let r of t)if(r[0]==="name"){let o=r[1].includes(".")?r[1].split(".")[0]:r[1];n.push({type:"variable",name:o})}else if(["#","&","^",">"].includes(r[0])){if(n.push({type:"variable",name:r[1]}),r[0]==="#"&&r.length>4&&Array.isArray(r[4])){let o=[...e,r[1]],i=s7e(r[4],o);n.push(...i)}}else n.push({type:"literal",text:r[1]});return n},sj=t=>(i7e(),s7e(w9.parse(t))),a7e=(t,e)=>bR(t).reduce((n,r)=>{if(r.type==="variable"){if(r.name in e)return n+(typeof e[r.name]=="string"?e[r.name]:JSON.stringify(e[r.name]));throw new Error(`(f-string) Missing value for input ${r.name}`)}return n+r.text},""),l7e=(t,e)=>(i7e(),w9.render(t,e)),v9={"f-string":a7e,mustache:l7e},c7e={"f-string":bR,mustache:sj},df=(t,e,n)=>{try{return v9[e](t,n)}catch(r){throw Lb(r,"INVALID_PROMPT_INPUT")}},CR=(t,e)=>c7e[e](t),_R=(t,e,n)=>{if(!(e in v9))throw new Error(`Invalid template format. Got \`${e}\`;
should be one of ${Object.keys(v9)}`);try{let r=Object.fromEntries(n.map(o=>[o,"foo"]));Array.isArray(t)?t.forEach(o=>{if(o.type==="text"&&"text"in o&&typeof o.text=="string")df(o.text,e,r);else if(o.type==="image_url"){if(typeof o.image_url=="string")df(o.image_url,e,r);else if(typeof o.image_url=="object"&&o.image_url!==null&&"url"in o.image_url&&typeof o.image_url.url=="string"){let i=o.image_url.url;df(i,e,r)}}else throw new Error(`Invalid message template received. ${JSON.stringify(o,null,2)}`)}):df(t,e,r)}catch(r){throw new Error(`Invalid prompt schema: ${r.message}`)}}});var ki,x9=C(()=>{rj();uP();ki=class aj extends cP{constructor(n){super(n);I(this,"template");I(this,"templateFormat","f-string");I(this,"validateTemplate",!0);I(this,"additionalContentFields");if(n.templateFormat==="mustache"&&n.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,n),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),_R(this.template,this.templateFormat,r)}}static lc_name(){return"PromptTemplate"}_getPromptType(){return"prompt"}async format(n){let r=await this.mergePartialAndUserVariables(n);return df(this.template,this.templateFormat,r)}static fromExamples(n,r,o,i=`
`,s=""){return new aj({inputVariables:o,template:[s,...n,r].join(i)})}static fromTemplate(n,r){let{templateFormat:o="f-string",...i}=r??{},s=new Set;return CR(n,o).forEach(a=>{a.type==="variable"&&s.add(a.name)}),new aj({inputVariables:[...s],templateFormat:o,template:n,...i})}async partial(n){let r=this.inputVariables.filter(i=>!(i in n)),o={...this.partialVariables??{},...n};return new aj({...this,inputVariables:r,partialVariables:o})}serialize(){if(this.outputParser!==void 0)throw new Error("Cannot serialize a prompt template with an output parser");return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}static async deserialize(n){if(!n.template)throw new Error("Prompt template must have a template");return new aj({inputVariables:n.input_variables,template:n.template,templateFormat:n.template_format})}}});var lj,jxe=C(()=>{tU();wR();uP();lj=class u7e extends fy{constructor(n){super(n);I(this,"lc_namespace",["langchain_core","prompts","image"]);I(this,"template");I(this,"templateFormat","f-string");I(this,"validateTemplate",!0);I(this,"additionalContentFields");if(this.template=n.template,this.templateFormat=n.templateFormat??this.templateFormat,this.validateTemplate=n.validateTemplate??this.validateTemplate,this.additionalContentFields=n.additionalContentFields,this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),_R([{type:"image_url",image_url:this.template}],this.templateFormat,r)}}static lc_name(){return"ImagePromptTemplate"}_getPromptType(){return"prompt"}async partial(n){let r=this.inputVariables.filter(i=>!(i in n)),o={...this.partialVariables??{},...n};return new u7e({...this,inputVariables:r,partialVariables:o})}async format(n){let r={};for(let[a,l]of Object.entries(this.template))typeof l=="string"?r[a]=df(l,this.templateFormat,n):r[a]=l;let o=n.url||r.url,i=n.detail||r.detail;if(!o)throw new Error("Must provide either an image URL.");if(typeof o!="string")throw new Error("url must be a string.");let s={url:o};return i&&(s.detail=i),s}async formatPromptValue(n){return new h4e(await this.format(n))}}});function Vxe(t,e){let n=[];for(let r of Object.values(t))if(typeof r=="string")CR(r,e).forEach(o=>{o.type==="variable"&&n.push(o.name)});else if(Array.isArray(r))for(let o of r)typeof o=="string"?CR(o,e).forEach(i=>{i.type==="variable"&&n.push(i.name)}):typeof o=="object"&&n.push(...Vxe(o,e));else typeof r=="object"&&r!==null&&n.push(...Vxe(r,e));return Array.from(new Set(n))}function Wxe(t,e,n){let r={};for(let[o,i]of Object.entries(t))if(typeof i=="string")r[o]=df(i,n,e);else if(Array.isArray(i)){let s=[];for(let a of i)typeof a=="string"?s.push(df(a,n,e)):typeof a=="object"&&s.push(Wxe(a,e,n));r[o]=s}else typeof i=="object"&&i!==null?r[o]=Wxe(i,e,n):r[o]=i;return r}var b9,Hxe=C(()=>{Ra();uP();b9=class extends gr{constructor(e){let n=e.templateFormat??"f-string",r=Vxe(e.template,n);super({inputVariables:r,...e});I(this,"lc_namespace",["langchain_core","prompts","dict"]);I(this,"lc_serializable",!0);I(this,"template");I(this,"templateFormat");I(this,"inputVariables");this.template=e.template,this.templateFormat=n,this.inputVariables=r}static lc_name(){return"DictPromptTemplate"}async format(e){return Wxe(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}}});function DWt(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function $Wt(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:"image_url"in t&&(typeof t.image_url=="string"||typeof t.image_url=="object"&&t.image_url!==null&&"url"in t.image_url&&typeof t.image_url.url=="string")}function FWt(t){return typeof t.formatMessages=="function"}function UWt(t,e){if(FWt(t)||np(t))return t;if(Array.isArray(t)&&t[0]==="placeholder"){let o=t[1];if(e?.templateFormat==="mustache"&&typeof o=="string"&&o.slice(0,2)==="{{"&&o.slice(-2)==="}}")return new Pv({variableName:o
`));throw s.name="InputFormatError",s.lc_error_code=o.lc_error_code,s}return r}},d7e=class extends _9{constructor(e){"prompt"in e||(e={prompt:e});super(e);I(this,"prompt");this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},Kxe=class extends fy{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){return new i5(await this.formatMessages(t))}},f7e=class extends d7e{constructor(e,n){"prompt"in e||(e={prompt:e,role:n});super(e);I(this,"role");this.role=e.role}static lc_name(){return"ChatMessagePromptTemplate"}async format(e){return new rc(await this.prompt.format(e),this.role)}static fromTemplate(e,n,r){return new this(ki.fromTemplate(e,{templateFormat:r?.templateFormat}),n)}};qxe=class extends _9{constructor(e,n){"prompt"in e||(e={prompt:e});super(e);I(this,"lc_namespace",["langchain_core","prompts","chat"]);I(this,"lc_serializable",!0);I(this,"inputVariables",[]);I(this,"additionalOptions",{});I(this,"prompt");I(this,"messageClass");I(this,"chatMessageClass");if(this.prompt=e.prompt,Array.isArray(this.prompt)){let r=[];this.prompt.forEach(o=>{"inputVariables"in o&&(r=r.concat(o.inputVariables))}),this.inputVariables=r}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=n??this.additionalOptions}static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}createMessage(e){let n=this.constructor;if(n._messageClass())return new(n._messageClass())({content:e});if(n.chatMessageClass){let r=n.chatMessageClass();return new r({content:e,role:this.getRoleFromMessageClass(r.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(e){switch(e){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw new Error("Invalid message class name")}}static fromTemplate(e,n){if(typeof e=="string")return new this(ki.fromTemplate(e,n));let r=[];for(let o of e)if(typeof o=="string")r.push(ki.fromTemplate(o,n));else if(o!==null)if(DWt(o)){let i="";typeof o.text=="string"&&(i=o.text??"");let s={...n,additionalContentFields:o};r.push(ki.fromTemplate(i,s))}else if($Wt(o)){let i=o.image_url??"",s,a=[];if(typeof i=="string"){let l;n?.templateFormat==="mustache"?l=sj(i):l=bR(i);let c=l.flatMap(u=>u.type==="variable"?[u.name]:[]);if((c?.length??0)>0){if(c.length>1)throw new Error(`Only one format variable allowed per image template.
Got: ${c}
From: ${i}`);a=[c[0]]}else a=[];i={url:i},s=new lj({template:i,inputVariables:a,templateFormat:n?.templateFormat,additionalContentFields:o})}else if(typeof i=="object"){if("url"in i){let l;n?.templateFormat==="mustache"?l=sj(i.url):l=bR(i.url),a=l.flatMap(c=>c.type==="variable"?[c.name]:[])}else a=[];s=new lj({template:i,inputVariables:a,templateFormat:n?.templateFormat,additionalContentFields:o})}else throw new Error("Invalid image template");r.push(s)}else typeof o=="object"&&r.push(new b9({template:o,templateFormat:n?.templateFormat}));return new this({prompt:r,additionalOptions:n})}async format(e){if(this.prompt instanceof cP){let n=await this.prompt.format(e);return this.createMessage(n)}else{let n=[];for(let r of this.prompt){let o={};if(!("inputVariables"in r))throw new Error(`Prompt ${r} does not have inputVariables defined.`);for(let i of r.inputVariables)o||(o={[i]:e[i]}),o={...o,[i]:e[i]};if(r instanceof cP){let i=await r.format(o),s;"additionalContentFields"in r&&(s=r.additionalContentFields),i!==""&&n.push({...s,type:"text",text:i})}else if(r instanceof lj){let i=await r.format(o),s;"additionalContentFields"in r&&(s=r.additionalContentFields),n.push({...s,type:"image_url",image_url:i})}else if(r instanceof b9){let i=await r.format(o),s;"additionalContentFields"in r&&(s=r.additionalContentFields),n.push({...s,...i})}}return this.createMessage(n)}}async formatMessages(e){return[await this.format(e)]}},ff=class extends qxe{static _messageClass(){return Zo}static lc_name(){return"HumanMessagePromptTemplate"}},Gxe=class extends qxe{static _messageClass(){return kn}static lc_name(){return"AIMessagePromptTemplate"}},fh=class extends qxe{static _messageClass(){return Vu}static lc_name(){return"SystemMessagePromptTemplate"}};ou=class C9 extends Kxe{constructor(n){super(n);I(this,"promptMessages");I(this,"validateTemplate",!0);I(this,"templateFormat","f-string");if(n.templateFormat==="mustache"&&n.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,n),this.validateTemplate){let r=new Set;for(let l of this.promptMessages)if(!(l instanceof Vs))for(let c of l.inputVariables)r.add(c);let o=this.inputVariables,i=new Set(this.partialVariables?o.concat(Object.keys(this.partialVariables)):o),s=new Set([...i].filter(l=>!r.has(l)));if(s.size>0)throw new Error(`Input variables \`${[...s]}\` are not used in any of the prompt messages.`);let a=new Set([...r].filter(l=>!i.has(l)));if(a.size>0)throw new Error(`Input variables \`${[...a]}\` are used in prompt messages but not in the prompt template.`)}}static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}_getPromptType(){return"chat"}async _parseImagePrompts(n,r){return typeof n.content=="string"||(n.content=await Promise.all(n.content.map(async o=>{if(o.type!=="image_url")return o;let i="";typeof o.image_url=="string"?i=o.image_url:typeof o.image_url=="object"&&o.image_url!==null&&"url"in o.image_url&&typeof o.image_url.url=="string"&&(i=o.image_url.url);let s=await ki.fromTemplate(i,{templateFormat:this.templateFormat}).format(r);return typeof o.image_url=="object"&&o.image_url!==null&&"url"in o.image_url?o.image_url.url=s:o.image_url=s,o}))),n}async formatMessages(n){let r=await this.mergePartialAndUserVariables(n),o=[];for(let i of this.promptMessages)if(i instanceof Vs)o.push(await this._parseImagePrompts(i,r));else{let s;this.templateFormat==="mustache"?s={...r}:s=i.inputVariables.reduce((l,c)=>{if(!(c in r)&&!(BWt(i)&&i.optional))throw Lb(new Error(`Missing value for input variable \`${c.toString()}\``),"INVALID_PROMPT_INPUT");return l[c]=r[c],l},{});let a=await i.formatMessages(s);o=o.concat(a)}return o}async partial(n){let r=this.inputVariables.filter(i=>!(i in n)),o={...this.partialVariables??{},...n};return new C9({...this,inputVariables:r,partialVariables:o})}static fromTemplate(n,r){let o=new ff({prompt:ki.fromTemplate(n,r)});return this.fromMessages([o])}static fromMessages(n,r){let o=n.reduce((a,l)=>a.concat(l instanceof C9?l.promptMessages:[UWt(l,r)]),[]),i=n.reduce((a,l)=>l instanceof C9?Object.assign(a,
`);return{...o,[this.documentVariableName]:s}}async _call(n,r){return await this.llmChain.call(this._prepInputs(n),r?.getChild("combine_documents"))}_chainType(){return"stuff_documents_chain"}static async deserialize(n){if(!n.llm_chain)throw new Error("Missing llm_chain");return new I7e({llmChain:await Ka.deserialize(n.llm_chain)})}serialize(){return{_type:this._chainType(),llm_chain:this.llmChain.serialize()}}},P7e=class E7e extends mc{constructor(n){super(n);I(this,"llmChain");I(this,"inputKey","input_documents");I(this,"documentVariableName","context");I(this,"returnIntermediateSteps",!1);I(this,"maxTokens",3e3);I(this,"maxIterations",10);I(this,"ensureMapStep",!1);I(this,"combineDocumentChain");this.llmChain=n.llmChain,this.combineDocumentChain=n.combineDocumentChain,this.documentVariableName=n.documentVariableName??this.documentVariableName,this.ensureMapStep=n.ensureMapStep??this.ensureMapStep,this.inputKey=n.inputKey??this.inputKey,this.maxTokens=n.maxTokens??this.maxTokens,this.maxIterations=n.maxIterations??this.maxIterations,this.returnIntermediateSteps=n.returnIntermediateSteps??!1}static lc_name(){return"MapReduceDocumentsChain"}get inputKeys(){return[this.inputKey,...this.combineDocumentChain.inputKeys]}get outputKeys(){return this.combineDocumentChain.outputKeys}async _call(n,r){if(!(this.inputKey in n))throw new Error(`Document key ${this.inputKey} not found.`);let{[this.inputKey]:o,...i}=n,s=o,a=[];for(let u=0;u<this.maxIterations;u+=1){let d=s.map(h=>({[this.documentVariableName]:h.pageContent,...i}));if(u!==0||!this.ensureMapStep){let h=await this.combineDocumentChain.llmChain.prompt.format(this.combineDocumentChain._prepInputs({[this.combineDocumentChain.inputKey]:s,...i}));if(await this.combineDocumentChain.llmChain._getNumTokens(h)<this.maxTokens)break}let p=await this.llmChain.apply(d,r?Array.from({length:d.length},(h,g)=>r.getChild(`map_${g+1}`)):void 0),{outputKey:m}=this.llmChain;this.returnIntermediateSteps&&(a=a.concat(p.map(h=>h[m]))),s=p.map(h=>({pageContent:h[m],metadata:{}}))}let l={[this.combineDocumentChain.inputKey]:s,...i},c=await this.combineDocumentChain.call(l,r?.getChild("combine_documents"));return this.returnIntermediateSteps?{...c,intermediateSteps:a}:c}_chainType(){return"map_reduce_documents_chain"}static async deserialize(n){if(!n.llm_chain)throw new Error("Missing llm_chain");if(!n.combine_document_chain)throw new Error("Missing combine_document_chain");return new E7e({llmChain:await Ka.deserialize(n.llm_chain),combineDocumentChain:await A9.deserialize(n.combine_document_chain)})}serialize(){return{_type:this._chainType(),llm_chain:this.llmChain.serialize(),combine_document_chain:this.combineDocumentChain.serialize()}}},A7e=class k7e extends mc{constructor(n){super(n);I(this,"llmChain");I(this,"inputKey","input_documents");I(this,"outputKey","output_text");I(this,"documentVariableName","context");I(this,"initialResponseName","existing_answer");I(this,"refineLLMChain");I(this,"documentPrompt",this.defaultDocumentPrompt);this.llmChain=n.llmChain,this.refineLLMChain=n.refineLLMChain,this.documentVariableName=n.documentVariableName??this.documentVariableName,this.inputKey=n.inputKey??this.inputKey,this.outputKey=n.outputKey??this.outputKey,this.documentPrompt=n.documentPrompt??this.documentPrompt,this.initialResponseName=n.initialResponseName??this.initialResponseName}static lc_name(){return"RefineDocumentsChain"}get defaultDocumentPrompt(){return new ki({inputVariables:["page_content"],template:"{page_content}"})}get inputKeys(){return[...new Set([this.inputKey,...this.llmChain.inputKeys,...this.refineLLMChain.inputKeys])].filter(n=>n!==this.documentVariableName&&n!==this.initialResponseName)}get outputKeys(){return[this.outputKey]}async _constructInitialInputs(n,r){let o={page_content:n.pageContent,...n.metadata},i={};return this.documentPrompt.inputVariables.forEach(l=>{i[l]=o[l]}),{...{[this.documentVariableName]:await this.documentPrompt.format({...i})},...r}}async _constructRefineInputs(n,r){let o={page_content:n.pageContent,...n.metadata},i={};this.documentPrompt.inputVar
{context}
Question: {question}
Helpful Answer:`,inputVariables:["context","question"]}),oHt=`Use the following pieces of context to answer the users question.
If you don't know the answer, just say that you don't know, don't try to make up an answer.
----------------
{context}`,iHt=[fh.fromTemplate(oHt),ff.fromTemplate("{question}")],sHt=ou.fromMessages(iHt),D7e=new mj(rHt,[[hj,sHt]])});var F7e=C(()=>{ph();N9()});var U7e=C(()=>{ph();N9()});function B7e(t,e={}){let{prompt:n=D7e.getPrompt(t),verbose:r}=e,o=new Ka({prompt:n,llm:t,verbose:r});return new A9({llmChain:o,verbose:r})}var z7e=C(()=>{pP();pj();$7e();F7e();U7e()});var V7e={};zn(V7e,{VectorDBQAChain:()=>aHt});var aHt,W7e=C(()=>{MR();z7e();aHt=class j7e extends mc{constructor(n){super(n);I(this,"k",4);I(this,"inputKey","query");I(this,"vectorstore");I(this,"combineDocumentsChain");I(this,"returnSourceDocuments",!1);this.vectorstore=n.vectorstore,this.combineDocumentsChain=n.combineDocumentsChain,this.inputKey=n.inputKey??this.inputKey,this.k=n.k??this.k,this.returnSourceDocuments=n.returnSourceDocuments??this.returnSourceDocuments}static lc_name(){return"VectorDBQAChain"}get inputKeys(){return[this.inputKey]}get outputKeys(){return this.combineDocumentsChain.outputKeys.concat(this.returnSourceDocuments?["sourceDocuments"]:[])}async _call(n,r){if(!(this.inputKey in n))throw new Error(`Question key ${this.inputKey} not found.`);let o=n[this.inputKey],i=await this.vectorstore.similaritySearch(o,this.k,n.filter,r?.getChild("vectorstore")),s={question:o,input_documents:i},a=await this.combineDocumentsChain.call(s,r?.getChild("combine_documents"));return this.returnSourceDocuments?{...a,sourceDocuments:i}:a}_chainType(){return"vector_db_qa"}static async deserialize(n,r){if(!("vectorstore"in r))throw new Error("Need to pass in a vectorstore to deserialize VectorDBQAChain");let{vectorstore:o}=r;if(!n.combine_documents_chain)throw new Error("VectorDBQAChain must have combine_documents_chain in serialized data");return new j7e({combineDocumentsChain:await mc.deserialize(n.combine_documents_chain),k:n.k,vectorstore:o})}serialize(){return{_type:this._chainType(),combine_documents_chain:this.combineDocumentsChain.serialize(),k:this.k}}static fromLLM(n,r,o){let i=B7e(n);return new this({vectorstore:r,combineDocumentsChain:i,...o})}}});var H7e,K7e,lHt,q7e,G7e=C(()=>{ph();H7e=`You are given the below API Documentation:
{api_docs}
Using this documentation, generate the full API url to call for answering the user question.
You should build the API url in order to get a response that is as short as possible, while still getting the necessary information to answer the question. Pay attention to deliberately exclude any unnecessary pieces of data in the API call.
Question:{question}
API url:`,K7e=new ki({inputVariables:["api_docs","question"],template:H7e}),lHt=`${H7e} {api_url}
Here is the response from the API:
{api_response}
Summarize this response to answer the original question.
Summary:`,q7e=new ki({inputVariables:["api_docs","question","api_url","api_response"],template:lHt})});var Z7e={};zn(Z7e,{APIChain:()=>cHt});var cHt,J7e=C(()=>{MR();pP();G7e();cHt=class Y7e extends mc{constructor(n){super(n);I(this,"apiAnswerChain");I(this,"apiRequestChain");I(this,"apiDocs");I(this,"headers",{});I(this,"inputKey","question");I(this,"outputKey","output");this.apiRequestChain=n.apiRequestChain,this.apiAnswerChain=n.apiAnswerChain,this.apiDocs=n.apiDocs,this.inputKey=n.inputKey??this.inputKey,this.outputKey=n.outputKey??this.outputKey,this.headers=n.headers??this.headers}get inputKeys(){return[this.inputKey]}get outputKeys(){return[this.outputKey]}async _call(n,r){let o=n[this.inputKey],i=await this.apiRequestChain.predict({question:o,api_docs:this.apiDocs},r?.getChild("request")),a=await(await fetch(i,{headers:this.headers})).text(),l=await this.apiAnswerChain.predict({question:o,api_docs:this.apiDocs,api_url:i,api_response:a},r?.getChild("response"));return{[this.outputKey]:l}}_chainType(){return"api_chain"}static async deserialize(n){let{api_request_chain:r,api_answer_chain:o,api_docs:i}=n;if(!r)throw new Error("LLMChain must have api_request_chain");if(!o)throw new Error("LLMChain must have api_answer_chain");if(!i)throw new Error("LLMChain must have api_docs");return new Y7e({apiAnswerChain:await Ka.deserialize(o),apiRequestChain:await Ka.deserialize(r),apiDocs:i})}serialize(){return{_type:this._chainType(),api_answer_chain:this.apiAnswerChain.serialize(),api_request_chain:this.apiRequestChain.serialize(),api_docs:this.apiDocs}}static fromLLMAndAPIDocs(n,r,o={}){let{apiUrlPrompt:i=K7e,apiResponsePrompt:s=q7e}=o,a=new Ka({prompt:i,llm:n}),l=new Ka({prompt:s,llm:n});return new this({apiAnswerChain:l,apiRequestChain:a,apiDocs:r,...o})}}});var mc,MR=C(()=>{jm();qd();ac();Hb();mc=class extends nU{get lc_namespace(){return["langchain","chains",this._chainType()]}constructor(t,e,n){if(arguments.length===1&&typeof t=="object"&&!("saveContext"in t)){let{memory:r,callbackManager:o,...i}=t;super({...i,callbacks:o??i.callbacks}),this.memory=r}else super({verbose:e,callbacks:n}),this.memory=t}_selectMemoryInputs(t){let e={...t};return"signal"in e&&delete e.signal,"timeout"in e&&delete e.timeout,e}async invoke(t,e){let n=fr(e),r=await this._formatValues(t),i=await(await Ws.configure(n?.callbacks,this.callbacks,n?.tags,this.tags,n?.metadata,this.metadata,{verbose:this.verbose}))?.handleChainStart(this.toJSON(),r,void 0,void 0,void 0,void 0,n?.runName),s;try{if(r.signal){let a;s=await Promise.race([this._call(r,i,n),new Promise((l,c)=>{a=()=>{c(new Error("AbortError"))},r.signal?.addEventListener("abort",a)})]).finally(()=>{r.signal&&a&&r.signal.removeEventListener("abort",a)})}else s=await this._call(r,i,n)}catch(a){throw await i?.handleChainError(a),a}return this.memory!=null&&await this.memory.saveContext(this._selectMemoryInputs(t),s),await i?.handleChainEnd(s),Object.defineProperty(s,iM,{value:i?{runId:i?.runId}:void 0,configurable:!0}),s}_validateOutputs(t){let e=this.outputKeys.filter(n=>!(n in t));if(e.length)throw new Error(`Missing output keys: ${e.join(", ")} from chain ${this._chainType()}`)}async prepOutputs(t,e,n=!1){return this._validateOutputs(e),this.memory&&await this.memory.saveContext(t,e),n?e:{...t,...e}}serialize(){throw new Error("Method not implemented.")}async run(t,e){let n=this.inputKeys.filter(a=>!this.memory?.memoryKeys.includes(a));if(!(n.length<=1))throw new Error(`Chain ${this._chainType()} expects multiple inputs, cannot use 'run' `);let o=n.length?{[n[0]]:t}:{},i=await this.call(o,e),s=Object.keys(i);if(s.length===1)return i[s[0]];throw new Error("return values have multiple keys, `run` only supported when one key currently")}async _formatValues(t){let e={...t};if(e.timeout&&!e.signal&&(e.signal=AbortSignal.timeout(e.timeout),delete e.timeout),this.memory!=null){let n=await this.memory.loadMemoryVariables(this._selectMemoryInputs(t));for(let[r,o]of Object.entries(n))e[r]=o}return e}async call(t,e,n){let r={tags:n,...Wb(e)};return this.invoke(t,r)}async apply(t,e){return Promise.all(
`;)e--;return t.substring(0,e)}function _rt(t){return Crt(brt(t))}function GCe(t){return YCe(t,hGt)}function Trt(t){return YCe(t,Srt)}function gGt(t){return Prt(t,Srt)}function yGt(t){return YCe(t,Irt)}function wGt(t){return Prt(t,Irt)}function YCe(t,e){return e.indexOf(t.nodeName)>=0}function Prt(t,e){return t.getElementsByTagName&&e.some(function(n){return t.getElementsByTagName(n).length})}function hZ(t){return t?t.replace(/(\n+\s*)+/g,`
`):""}function Ert(t){this.options=t,this._keep=[],this._remove=[],this.blankRule={replacement:t.blankReplacement},this.keepReplacement=t.keepReplacement,this.defaultRule={replacement:t.defaultReplacement},this.array=[];for(var e in t.rules)this.array.push(t.rules[e])}function WCe(t,e,n){for(var r=0;r<t.length;r++){var o=t[r];if(vGt(o,e,n))return o}}function vGt(t,e,n){var r=t.filter;if(typeof r=="string"){if(r===e.nodeName.toLowerCase())return!0}else if(Array.isArray(r)){if(r.indexOf(e.nodeName.toLowerCase())>-1)return!0}else if(typeof r=="function"){if(r.call(t,e,n))return!0}else throw new TypeError("`filter` needs to be a string, array, or function")}function xGt(t){var e=t.element,n=t.isBlock,r=t.isVoid,o=t.isPre||function(d){return d.nodeName==="PRE"};if(!(!e.firstChild||o(e))){for(var i=null,s=!1,a=null,l=vrt(a,e,o);l!==e;){if(l.nodeType===3||l.nodeType===4){var c=l.data.replace(/[ \r\n\t]+/g," ");if((!i||/ $/.test(i.data))&&!s&&c[0]===" "&&(c=c.substr(1)),!c){l=HCe(l);continue}l.data=c,i=l}else if(l.nodeType===1)n(l)||l.nodeName==="BR"?(i&&(i.data=i.data.replace(/ $/,"")),i=null,s=!1):r(l)||o(l)?(i=null,s=!0):i&&(s=!1);else{l=HCe(l);continue}var u=vrt(a,l,o);a=l,l=u}i&&(i.data=i.data.replace(/ $/,""),i.data||HCe(i))}}function HCe(t){var e=t.nextSibling||t.parentNode;return t.parentNode.removeChild(t),e}function vrt(t,e,n){return t&&t.parentNode===e||n(e)?e.nextSibling||e.parentNode:e.firstChild||e.nextSibling||e.parentNode}function bGt(){var t=ZCe.DOMParser,e=!1;try{new t().parseFromString("","text/html")&&(e=!0)}catch{}return e}function CGt(){var t=function(){};return _Gt()?t.prototype.parseFromString=function(e){var n=new window.ActiveXObject("htmlfile");return n.designMode="on",n.open(),n.write(e),n.close(),n}:t.prototype.parseFromString=function(e){var n=document.implementation.createHTMLDocument("");return n.open(),n.write(e),n.close(),n},t}function _Gt(){var t=!1;try{document.implementation.createHTMLDocument("").open()}catch{ZCe.ActiveXObject&&(t=!0)}return t}function TGt(t,e){var n;if(typeof t=="string"){var r=IGt().parseFromString('<x-turndown id="turndown-root">'+t+"</x-turndown>","text/html");n=r.getElementById("turndown-root")}else n=t.cloneNode(!0);return xGt({element:n,isBlock:GCe,isVoid:Trt,isPre:e.preformattedCode?PGt:null}),n}function IGt(){return KCe=KCe||new SGt,KCe}function PGt(t){return t.nodeName==="PRE"||t.nodeName==="CODE"}function EGt(t,e){return t.isBlock=GCe(t),t.isCode=t.nodeName==="CODE"||t.parentNode.isCode,t.isBlank=AGt(t),t.flankingWhitespace=kGt(t,e),t}function AGt(t){return!Trt(t)&&!yGt(t)&&/^\s*$/i.test(t.textContent)&&!gGt(t)&&!wGt(t)}function kGt(t,e){if(t.isBlock||e.preformattedCode&&t.isCode)return{leading:"",trailing:""};var n=MGt(t.textContent);return n.leadingAscii&&xrt("left",t,e)&&(n.leading=n.leadingNonAscii),n.trailingAscii&&xrt("right",t,e)&&(n.trailing=n.trailingNonAscii),{leading:n.leading,trailing:n.trailing}}function MGt(t){var e=t.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/);return{leading:e[1],leadingAscii:e[2],leadingNonAscii:e[3],trailing:e[4],trailingNonAscii:e[5],trailingAscii:e[6]}}function xrt(t,e,n){var r,o,i;return t==="left"?(r=e.previousSibling,o=/ $/):(r=e.nextSibling,o=/^ /),r&&(r.nodeType===3?i=o.test(r.nodeValue):n.preformattedCode&&r.nodeName==="CODE"?i=!1:r.nodeType===1&&!GCe(r)&&(i=o.test(r.textContent))),i}function gZ(t){if(!(this instanceof gZ))return new gZ(t);var e={rules:yc,headingStyle:"setext",hr:"* * *",bulletListMarker:"*",codeBlockStyle:"indented",fence:"```",emDelimiter:"_",strongDelimiter:"**",linkStyle:"inlined",linkReferenceStyle:"full",br:" ",preformattedCode:!1,blankReplacement:function(n,r){return r.isBlock?`
`:""},keepReplacement:function(n,r){return r.isBlock?`
`+r.outerHTML+`
`:r.outerHTML},defaultReplacement:function(n,r){return r.isBlock?`
`+n+`
`:n}};this.options=mGt({},e,t),this.rules=new Ert(this.options)}function Art(t){var e=this;return NGt.call(t.childNodes,function(n,r){r=new EGt(r,e.options);var o="";return r.nodeType===3?o=r.isCode?r.nodeValue:e.escape(r.nodeValue):r.nodeType===1&&(o=LGt.call(e,r)),krt(n,o)},"")}function RGt(t){var e=this;return this.rules.forEach(function(n){typeof n.append=="function"&&(t=krt(t,n.append(e.options)))}),t.replace(/^[\t\r\n]+/,"").replace(/[\t\r\n\s]+$/,"")}function LGt(t){var e=this.rules.forNode(t),n=Art.call(this,t),r=t.flankingWhitespace;return(r.leading||r.trailing)&&(n=n.trim()),r.leading+e.replacement(n,t,this.options)+r.trailing}function krt(t,e){var n=Crt(t),r=brt(e),o=Math.max(t.length-n.length,e.length-r.length),i=`
`.substring(0,o);return n+i+r}function DGt(t){return t!=null&&(typeof t=="string"||t.nodeType&&(t.nodeType===1||t.nodeType===9||t.nodeType===11))}var hGt,Srt,Irt,yc,ZCe,SGt,KCe,NGt,OGt,Mrt,Nrt=C(()=>{hGt=["ADDRESS","ARTICLE","ASIDE","AUDIO","BLOCKQUOTE","BODY","CANVAS","CENTER","DD","DIR","DIV","DL","DT","FIELDSET","FIGCAPTION","FIGURE","FOOTER","FORM","FRAMESET","H1","H2","H3","H4","H5","H6","HEADER","HGROUP","HR","HTML","ISINDEX","LI","MAIN","MENU","NAV","NOFRAMES","NOSCRIPT","OL","OUTPUT","P","PRE","SECTION","TABLE","TBODY","TD","TFOOT","TH","THEAD","TR","UL"];Srt=["AREA","BASE","BR","COL","COMMAND","EMBED","HR","IMG","INPUT","KEYGEN","LINK","META","PARAM","SOURCE","TRACK","WBR"];Irt=["A","TABLE","THEAD","TBODY","TFOOT","TH","TD","IFRAME","SCRIPT","AUDIO","VIDEO"];yc={};yc.paragraph={filter:"p",replacement:function(t){return`
`+t+`
`}};yc.lineBreak={filter:"br",replacement:function(t,e,n){return n.br+`
`}};yc.heading={filter:["h1","h2","h3","h4","h5","h6"],replacement:function(t,e,n){var r=Number(e.nodeName.charAt(1));if(n.headingStyle==="setext"&&r<3){var o=qCe(r===1?"=":"-",t.length);return`
`+t+`
`+o+`
`}else return`
`+qCe("#",r)+" "+t+`
`}};yc.blockquote={filter:"blockquote",replacement:function(t){return t=_rt(t).replace(/^/gm,"> "),`
`+t+`
`}};yc.list={filter:["ul","ol"],replacement:function(t,e){var n=e.parentNode;return n.nodeName==="LI"&&n.lastElementChild===e?`
`+t:`
`+t+`
`}};yc.listItem={filter:"li",replacement:function(t,e,n){var r=n.bulletListMarker+" ",o=e.parentNode;if(o.nodeName==="OL"){var i=o.getAttribute("start"),s=Array.prototype.indexOf.call(o.children,e);r=(i?Number(i)+s:s+1)+". "}var a=/\n$/.test(t);return t=_rt(t)+(a?`
`:""),t=t.replace(/\n/gm,`
`+" ".repeat(r.length)),r+t+(e.nextSibling?`
`:"")}};yc.indentedCodeBlock={filter:function(t,e){return e.codeBlockStyle==="indented"&&t.nodeName==="PRE"&&t.firstChild&&t.firstChild.nodeName==="CODE"},replacement:function(t,e,n){return`
`+e.firstChild.textContent.replace(/\n/g,`
`)+`
`}};yc.fencedCodeBlock={filter:function(t,e){return e.codeBlockStyle==="fenced"&&t.nodeName==="PRE"&&t.firstChild&&t.firstChild.nodeName==="CODE"},replacement:function(t,e,n){for(var r=e.firstChild.getAttribute("class")||"",o=(r.match(/language-(\S+)/)||[null,""])[1],i=e.firstChild.textContent,s=n.fence.charAt(0),a=3,l=new RegExp("^"+s+"{3,}","gm"),c;c=l.exec(i);)c[0].length>=a&&(a=c[0].length+1);var u=qCe(s,a);return`
`+u+o+`
`+i.replace(/\n$/,"")+`
`+u+`
`}};yc.horizontalRule={filter:"hr",replacement:function(t,e,n){return`
`+n.hr+`
`}};yc.inlineLink={filter:function(t,e){return e.linkStyle==="inlined"&&t.nodeName==="A"&&t.getAttribute("href")},replacement:function(t,e){var n=e.getAttribute("href");n&&(n=n.replace(/([()])/g,"\\$1"));var r=hZ(e.getAttribute("title"));return r&&(r=' "'+r.replace(/"/g,'\\"')+'"'),"["+t+"]("+n+r+")"}};yc.referenceLink={filter:function(t,e){return e.linkStyle==="referenced"&&t.nodeName==="A"&&t.getAttribute("href")},replacement:function(t,e,n){var r=e.getAttribute("href"),o=hZ(e.getAttribute("title"));o&&(o=' "'+o+'"');var i,s;switch(n.linkReferenceStyle){case"collapsed":i="["+t+"][]",s="["+t+"]: "+r+o;break;case"shortcut":i="["+t+"]",s="["+t+"]: "+r+o;break;default:var a=this.references.length+1;i="["+t+"]["+a+"]",s="["+a+"]: "+r+o}return this.references.push(s),i},references:[],append:function(t){var e="";return this.references.length&&(e=`
`+this.references.join(`
`)+`
`,this.references=[]),e}};yc.emphasis={filter:["em","i"],replacement:function(t,e,n){return t.trim()?n.emDelimiter+t+n.emDelimiter:""}};yc.strong={filter:["strong","b"],replacement:function(t,e,n){return t.trim()?n.strongDelimiter+t+n.strongDelimiter:""}};yc.code={filter:function(t){var e=t.previousSibling||t.nextSibling,n=t.parentNode.nodeName==="PRE"&&!e;return t.nodeName==="CODE"&&!n},replacement:function(t){if(!t)return"";t=t.replace(/\r?\n|\r/g," ");for(var e=/^`|^ .*?[^ ].* $|`$/.test(t)?" ":"",n="`",r=t.match(/`+/gm)||[];r.indexOf(n)!==-1;)n=n+"`";return n+e+t+e+n}};yc.image={filter:"img",replacement:function(t,e){var n=hZ(e.getAttribute("alt")),r=e.getAttribute("src")||"",o=hZ(e.getAttribute("title")),i=o?' "'+o+'"':"";return r?"!["+n+"]("+r+i+")":""}};Ert.prototype={add:function(t,e){this.array.unshift(e)},keep:function(t){this._keep.unshift({filter:t,replacement:this.keepReplacement})},remove:function(t){this._remove.unshift({filter:t,replacement:function(){return""}})},forNode:function(t){if(t.isBlank)return this.blankRule;var e;return(e=WCe(this.array,t,this.options))||(e=WCe(this._keep,t,this.options))||(e=WCe(this._remove,t,this.options))?e:this.defaultRule},forEach:function(t){for(var e=0;e<this.array.length;e++)t(this.array[e],e)}};ZCe=typeof window<"u"?window:{};SGt=bGt()?ZCe.DOMParser:CGt();NGt=Array.prototype.reduce,OGt=[[/\\/g,"\\\\"],[/\*/g,"\\*"],[/^-/g,"\\-"],[/^\+ /g,"\\+ "],[/^(=+)/g,"\\$1"],[/^(#{1,6}) /g,"\\$1 "],[/`/g,"\\`"],[/^~~~/g,"\\~~~"],[/\[/g,"\\["],[/\]/g,"\\]"],[/^>/g,"\\>"],[/_/g,"\\_"],[/^(\d+)\. /g,"$1\\. "]];gZ.prototype={turndown:function(t){if(!DGt(t))throw new TypeError(t+" is not a string, or an element/document/fragment node.");if(t==="")return"";var e=Art.call(this,new TGt(t,this.options));return RGt.call(this,e)},use:function(t){if(Array.isArray(t))for(var e=0;e<t.length;e++)this.use(t[e]);else if(typeof t=="function")t(this);else throw new TypeError("plugin must be a Function or an Array of Functions");return this},addRule:function(t,e){return this.rules.add(t,e),this},keep:function(t){return this.rules.keep(t),this},remove:function(t){return this.rules.remove(t),this},escape:function(t){return OGt.reduce(function(e,n){return e.replace(n[0],n[1])},t)}};Mrt=gZ});function lL(t){return typeof t=="object"&&t!==null}function cL(t){if(typeof t=="string")return t;if(t==null)return"";try{return typeof t=="object"?JSON.stringify(t):typeof t=="function"||typeof t=="symbol"||typeof t=="bigint"?t.toString():typeof t=="number"||typeof t=="boolean"?String(t):""}catch{return""}}function Drt(t){return t instanceof Error?t.message:cL(t)}async function $Gt(t){await new Promise(e=>window.setTimeout(e,t))}async function $rt(t,e,n,r){let o=Date.now();for(;;){if(t())return;if(Date.now()-o>=e)throw new gf(`${r} timed out after ${e}ms`);await $Gt(n)}}function Ort(t,e){let n=(t??"").trim();if(!n)return"";if(!e)return n;try{return new URL(n,e).href}catch{return n}}function Rrt(t){let e=(t??"").trim();return e?/[\s)]/.test(e)?`<${e}>`:e:""}function FGt(t){let e=new Mrt({headingStyle:"atx",hr:"---",bulletListMarker:"-",codeBlockStyle:"fenced",fence:"```",emDelimiter:"*",strongDelimiter:"**",linkStyle:"inlined"});return e.remove(["script","style","noscript"]),e.addRule("webviewer-link",{filter:"a",replacement:(n,r)=>{let o=r,i=o.getAttribute("href")??"",s=Rrt(Ort(i,t)),a=n?.trim()||o.textContent||s;return s?`[${a}](${s})`:a}}),e.addRule("webviewer-image",{filter:"img",replacement:(n,r)=>{let o=r,i=o.getAttribute("alt")??"",s=o.getAttribute("src")??"",a=Rrt(Ort(s,t));return a?`![${i}](${a})`:""}}),e}function JCe(t,e){if(!t.trim())return"";let n=FGt(e),i=new DOMParser().parseFromString(`<div>${t}</div>`,"text/html").body.firstElementChild;return i?n.turndown(i).replace(/\n{3,}/g,`
`).trim():""}function XCe(t){let e=t.commands;return!e||!lL(e)||typeof e.executeCommandById!="function"?null:e}function Frt(t,e){let n=XCe(t);if(!n)return!1;if(n.commands){if(n.commands instanceof Map)return n.commands.has(e);if(typeof n.commands=="object")return e in n.commands}return typeof n.listCommands=="function"?n.listCommands().some(o=>o.id===e):!1}function Urt(t,e){return t.workspace.getLeavesOfType(DP).includes(e)}function Lrt(t){if(!lL(t)||t.enabled!==!0)return null;let e=t.instance;if(!e||!lL(e))return null;let n=e;return typeof n.openUrl=="function"||typeof n.handleOpenUrl=="function"?n:null}function Brt(t,e){let n=t.internalPlugins;if(!n||!lL(n))return null;let r=n.plugins;if(!r)return null;let o=r instanceof Map?r.get(DP):lL(r)?r[DP]:null;if(o){let s=Lrt(o);if(s)return s}let i;if(r instanceof Map)i=Array.from(r.values());else if(lL(r))i=Object.values(r);else return e&&e(),null;for(let s of i){let a=Lrt(s);if(a)return a}return null}var yZ=C(()=>{Nrt();aL()});function uL(t){return{url:typeof t.view?.url=="string"?t.view.url:"",title:typeof t.view?.title=="string"?t.view.title:"",faviconUrl:typeof t.view?.faviconUrl=="string"?t.view.faviconUrl:"",mode:t.view?.mode==="reader"?"reader":"webview"}}async function zrt(t,e={}){let{signal:n}=e;if(n?.aborted)throw new M_("Operation was aborted");try{let r=Promise.resolve(t.view.getReaderModeContent());if(!n){let i=await r;return typeof i?.md=="string"?i.md:""}let o=await new Promise((i,s)=>{let a=()=>{s(new M_("Operation was aborted"))};n.addEventListener("abort",a,{once:!0}),r.then(l=>{n.removeEventListener("abort",a),i(l)}).catch(l=>{n.removeEventListener("abort",a),s(l instanceof Error?l:new Error(String(l)))})});return typeof o?.md=="string"?o.md:""}catch(r){throw r instanceof M_||z("Failed to get reader mode content:",r),r}}async function wZ(t,e=!0){let n=sL(t),r='(() => { try { return window.getSelection?.()?.toString?.() ?? ""; } catch { return ""; } })()';try{let o=await n.executeJavaScript(r),i=cL(o);return e?i.trim():i}catch(o){throw z("Failed to get selected text:",o),o}}async function vZ(t){let e=sL(t),n="";try{n=typeof e.getURL=="function"?e.getURL():""}catch{n=t.view?.url??""}let r=`(() => {
const sel = window.getSelection();
if (!sel || sel.rangeCount === 0 || sel.isCollapsed) return "";
const div = document.createElement("div");
for (let i = 0; i < sel.rangeCount; i++) div.appendChild(sel.getRangeAt(i).cloneContents());
return div.innerHTML;
})()`,o="";try{let i=await e.executeJavaScript(r);o=cL(i)}catch(i){throw z("Failed to get selection HTML:",i),i}try{return JCe(o,n)}catch(i){throw z("Failed to convert HTML to Markdown:",i),i}}async function jrt(t){let e=sL(t),n="";try{n=typeof e.getURL=="function"?e.getURL():""}catch{n=t.view?.url??""}let r=`(() => {
const clone = document.body.cloneNode(true);
clone.querySelectorAll('script, style, noscript').forEach(el => el.remove());
return clone.innerHTML;
})()`,o="";try{let i=await e.executeJavaScript(r);o=cL(i)}catch(i){throw z("Failed to get page HTML:",i),i}try{return JCe(o,n)}catch(i){throw z("Failed to convert page HTML to Markdown:",i),i}}async function Vrt(t,e=!0){let n=sL(t),r=e?'(() => { try { return document.documentElement?.outerHTML ?? ""; } catch { return ""; } })()':'(() => { try { return document.body?.outerHTML ?? ""; } catch { return ""; } })()';try{let o=await n.executeJavaScript(r);return cL(o)}catch(o){throw z("Failed to get HTML:",o),o}}function UGt(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.videoId=="string"&&typeof e.title=="string"&&typeof e.channel=="string"&&(e.description===void 0||typeof e.description=="string")&&(e.uploadDate===void 0||typeof e.uploadDate=="string")&&(e.duration===void 0||typeof e.duration=="string")&&(e.genre===void 0||typeof e.genre=="string")&&Array.isArray(e.transcript)&&e.transcript.every(n=>typeof n=="object"&&n!==null&&typeof n.timestamp=="string"&&typeof n.text=="string")}async function Wrt(t,e={}){let n=sL(t),{timeoutMs:r=1e4}=e,o=Math.ceil(r/500),i="";try{i=typeof n.getURL=="function"?n.getURL():""}catch{i=""}i||(i=t.view?.url??"");let s=k_(i);if(!s)throw new Error("Not a YouTube video page");let a=`(async () => {
const videoId = ${JSON.stringify(s)};
// =========================================================================
// Step 1: Extract video metadata from JSON-LD (structured data)
// JSON-LD is more reliable than DOM selectors as it's machine-readable
// =========================================================================
let title = '';
let channel = '';
let description = '';
let uploadDate = '';
let duration = '';
let genre = '';
// Helper to extract fields from a VideoObject schema
const extractVideoObject = (data) => {
if (!data || data['@type'] !== 'VideoObject') return;
if (!title && data.name && typeof data.name === 'string') {
title = data.name;
}
if (!description && data.description && typeof data.description === 'string') {
description = data.description;
}
if (!uploadDate && data.uploadDate && typeof data.uploadDate === 'string') {
uploadDate = data.uploadDate;
}
// JSON-LD duration is ISO 8601 format (e.g., "PT12M34S"), convert to readable format
if (!duration && data.duration && typeof data.duration === 'string') {
const match = data.duration.match(/PT(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?/);
if (match) {
const h = match[1] ? match[1] + ':' : '';
const m = match[2] || '0';
const s = match[3] || '0';
duration = h + (h ? m.padStart(2, '0') : m) + ':' + s.padStart(2, '0');
}
}
if (!genre && data.genre) {
genre = Array.isArray(data.genre) ? data.genre.join(', ') : String(data.genre);
}
// author can be string, object {name}, or array [{name}]
if (!channel && data.author) {
const author = data.author;
if (typeof author === 'string') {
channel = author;
} else if (Array.isArray(author) && author[0]?.name) {
channel = String(author[0].name);
} else if (author?.name) {
channel = String(author.name);
}
}
};
// Parse all JSON-LD scripts, handling various formats (@graph, array, single object)
const ldJsonEls = document.querySelectorAll('script[type="application/ld+json"]');
for (const el of ldJsonEls) {
try {
const data = JSON.parse(el.textContent || '');
if (Array.isArray(data)) {
for (const item of data) {
extractVideoObject(item);
}
} else if (data['@graph'] && Array.isArray(data['@graph'])) {
for (const item of data['@graph']) {
extractVideoObject(item);
}
} else {
extractVideoObject(data);
}
// Stop if we have all essential fields
if (title && channel && description) break;
} catch {}
}
// =========================================================================
// Step 2: Fallback to DOM selectors for missing metadata
// =========================================================================
if (!title) {
title = document.querySelector('h1.ytd-watch-metadata yt-formatted-string')?.textContent?.trim()
|| document.querySelector('#title h1')?.textContent?.trim() || '';
}
if (!channel) {
channel = document.querySelector('#owner #channel-name a')?.textContent?.trim()
|| document.querySelector('#channel-name a')?.textContent?.trim()
|| document.querySelector('#channel-name')?.textContent?.trim() || '';
}
if (!duration) {
duration = document.querySelector('#ytd-player .ytp-time-duration')?.textContent?.trim() || '';
}
// =========================================================================
// Step 3: Find or open the transcript panel
// Reason: YouTube has two coexisting transcript panel DOM structures:
// - Classic ("In this video"): ytd-transcript-segment-renderer
// - Modern ("Transcript"): transcript-segment-view-model
// YouTube selects the panel type server-side per video. We must support both.
// All segment queries are scoped to the panel to avoid false matches.
// =========================================================================
// Reason: Find panel by checking for transcript segment elements inside it,
// rather than relying on fragile target-id strings that YouTube changes.
// Prefer visible panels to avoid picking up hidden/stale panels YouTube
// leaves in the DOM during page transitions.
const findTranscriptPanel = () => {
const panels = document.querySelectorAll('ytd-engagement-panel-section-list-renderer');
for (const panel of panels) {
const hasSegments = panel.querySelector('ytd-transcript-segment-renderer')
|| panel.querySelector('transcript-segment-view-model');
if (!hasSegments) continue;
const style = window.getComputedStyle(panel);
if (style.display !== 'none' && style.visibility !== 'hidden') return panel;
}
return null;
};
// Reason: Auto-detect classic vs modern layout and use the correct selectors
// for each. Queries are scoped to the panel to prevent matching unrelated UI.
const extractFromPanel = (panel) => {
const classicSegs = panel.querySelectorAll('ytd-transcript-segment-renderer');
if (classicSegs.length > 0) {
return [...classicSegs].map(seg => ({
timestamp: seg.querySelector('.segment-timestamp')?.textContent?.trim() || '',
text: seg.querySelector('yt-formatted-string.segment-text, .segment-text')?.textContent?.trim() || ''
})).filter(t => t.timestamp && t.text);
}
const modernSegs = panel.querySelectorAll('transcript-segment-view-model');
if (modernSegs.length > 0) {
return [...modernSegs].map(seg => ({
timestamp: seg.querySelector('.ytwTranscriptSegmentViewModelTimestamp')?.textContent?.trim() || '',
text: [...seg.querySelectorAll('span.yt-core-attributed-string')].map(s => s.textContent || '').join('').trim() || ''
})).filter(t => t.timestamp && t.text);
}
return null;
};
let panel = findTranscriptPanel();
let needClose = false;
if (!panel) {
const btn = document.querySelector('ytd-video-description-transcript-section-renderer button')
|| document.querySelector('ytd-video-description-transcript-section-renderer [role="button"]');
if (btn) {
btn.click();
needClose = true;
// Poll for the panel container to appear (not individual segments)
for (let i = 0; i < ${o}; i++) {
await new Promise(r => setTimeout(r, 500));
panel = findTranscriptPanel();
if (panel) break;
}
}
}
// =========================================================================
// Step 4: Extract transcript segments from the panel
// =========================================================================
// Reason: Close via captured panel element rather than hardcoded target-id.
// This is resilient to YouTube changing the target-id string.
const closePanel = () => {
if (!needClose || !panel) return;
const closeBtn = panel.querySelector('#visibility-button button')
|| panel.querySelector('#visibility-button [role="button"]');
if (closeBtn) closeBtn.click();
};
try {
const transcript = panel ? (extractFromPanel(panel) || []) : [];
return { videoId, title, channel, description, uploadDate, duration, genre, transcript };
} finally {
closePanel();
}
})()`,l=await n.executeJavaScript(a);if(!UGt(l))throw new Error("Invalid transcript data structure");return l}async function Hrt(t,e,n={}){let{preferCommand:r=!0,focusLeafBeforeCommand:o=!0}=n;if(r)try{return await e(mZ.SAVE_TO_VAULT,{leaf:t,focusLeaf:o}),k("Saved via webviewer:save-to-vault command"),{method:"command"}}catch(i){ee("save-to-vault command failed, falling back:",i)}try{return await Promise.resolve(t.view.saveAsMarkdown()),k("Saved via view.saveAsMarkdown()"),{method:"view.saveAsMarkdown"}}catch(i){throw z("Failed to save Web Viewer page:",i),i}}var QCe=C(()=>{ye();dZ();aL();yZ();dZ()});function wc(t){if(typeof t!="string")return null;let e=t.trim();return e||null}function dL(t){if(typeof t!="string")return null;let e=t.trim();if(!e)return null;try{let n=new URL(e);n.hash="",(n.protocol==="http:"&&n.port==="80"||n.protocol==="https:"&&n.port==="443")&&(n.port=""),n.pathname!=="/"&&(n.pathname=n.pathname.replace(/\/+$/,""));let r=Array.from(n.searchParams.entries());return r.length>0?(r.sort(([o,i],[s,a])=>o!==s?o.localeCompare(s):i.localeCompare(a)),n.search=`?${new URLSearchParams(r).toString()}`):n.search="",n.toString()}catch{return e}}function qrt(t){return wc(t)??void 0}function e_e(t){let e=wc(t.url);if(!e)return null;let n=qrt(t.title),r=qrt(t.faviconUrl);return{url:e,title:n,faviconUrl:r,isLoaded:t.isLoaded,isActive:t.isActive?!0:void 0}}function $P(t){let e=new Map;for(let n of t){let r=e_e(n);if(!r)continue;let o=e.get(r.url);if(!o){e.set(r.url,r);continue}e.set(r.url,{...o,title:r.title??o.title,faviconUrl:r.faviconUrl??o.faviconUrl,isLoaded:r.isLoaded??o.isLoaded,isActive:o.isActive||r.isActive?!0:void 0})}return Array.from(e.values())}function Grt(t){let e=$P(t),n=!1;return e.map(r=>{if(!r.isActive)return r;if(!n)return n=!0,r;let{isActive:o,...i}=r;return i})}var fL=C(()=>{});var BGt,xZ,Yrt=C(()=>{ye();yZ();aL();fL();BGt=["did-finish-load","page-favicon-updated","page-title-updated"],xZ=class t{constructor(e){this.lastActiveLeaf=null;this.activeWebTabState={activeWebTabForMentions:null,activeOrLastWebTab:null};this.activeWebTabLeaf=null;this.activeWebTabListeners=new Set;this.activeWebTabTrackingRefs=null;this.activeWebTabTrackingPreserveViewTypes=[];this.webviewLoadListeners=new Map;this.webviewLoadCallbacks=new Set;this.cancelScheduledWebviewLoadNotify=null;this.app=e.app,this.isSupportedPlatform=e.isSupportedPlatform,this.getActiveLeaf=e.getActiveLeaf,this.getLeaves=e.getLeaves,this.getPageInfo=e.getPageInfo}getLastActiveLeaf(){let e=this.lastActiveLeaf;return!e||!t4(e)?(this.lastActiveLeaf=null,null):Urt(this.app,e)?e:(this.lastActiveLeaf=null,null)}findLeafByUrl(e,n={}){let r=e.trim();if(!r)return null;let o=this.getLeaves();for(let u of o)if(u?.view?.url===r)return u;let i=dL(r);if(!i)return null;let s=[];for(let u of o){let d=u?.view?.url;if(!d)continue;dL(d)===i&&s.push(u)}if(s.length===0)return null;if(s.length===1)return s[0];let a=(n.title??"").trim();if(a){let u=a.toLowerCase(),d=[];for(let f of s)try{let m=(this.getPageInfo(f).title||"").trim();m&&m.toLowerCase()===u&&d.push(f)}catch{}if(d.length===1)return d[0];if(d.length>1){let f=this.getActiveLeaf();if(f&&d.includes(f))return f;let p=this.getLastActiveLeaf();return p&&d.includes(p)?p:(ee("[WebViewerStateManager] Multiple leaves matched URL + title; returning first match.",{url:r,title:a,matches:d.length}),d[0])}}let l=this.getActiveLeaf();if(l&&s.includes(l))return l;let c=this.getLastActiveLeaf();return c&&s.includes(c)?c:(ee("[WebViewerStateManager] Multiple leaves matched URL; returning first match as fallback.",{url:r,matches:s.length}),s[0])}getActiveWebTabState(){return this.activeWebTabState}subscribeActiveWebTabState(e){return this.activeWebTabListeners.add(e),()=>{this.activeWebTabListeners.delete(e)}}subscribeToWebviewLoad(e){return this.webviewLoadCallbacks.add(e),()=>{this.webviewLoadCallbacks.delete(e)}}startActiveWebTabTracking(e={}){this.activeWebTabTrackingRefs&&this.stopActiveWebTabTracking(),this.activeWebTabTrackingPreserveViewTypes=[...e.preserveOnViewTypes??[]];let n=this.app.workspace.on("active-leaf-c
- Key concepts and main ideas
- Important facts, names, and dates
- Technical details relevant for Q&A
Keep the summary concise but information-dense. Output only the summary.
Title: {title}
Path: {path}
Content:
{content}
Summary:`;this.URL_BASED_TYPES=["url_content","web_tab_context","active_web_tab","youtube_video_context"];this.chatModelManager=Np.getInstance()}static getInstance(){return t.instance||(t.instance=new t),t.instance}async compact(e){let n=e.length;k(`[ContextCompactor] Starting compaction of ${n} chars`);let r=this.parseItems(e);if(r.length===0)return this.noOpResult(e);let o=await this.summarizeItems(r);if(o.size===0)return this.noOpResult(e);let i=this.rebuild(e,r,o);return k(`[ContextCompactor] Done: ${n} -> ${i.length} chars (${((1-i.length/n)*100).toFixed(0)}% reduction)`),{content:i,wasCompacted:!0,originalCharCount:n,compactedCharCount:i.length,itemsProcessed:r.length,itemsSummarized:o.size}}noOpResult(e){return{content:e,wasCompacted:!1,originalCharCount:e.length,compactedCharCount:e.length,itemsProcessed:0,itemsSummarized:0}}parseItems(e){let n=[];for(let r of this.BLOCK_TYPES){let o=new RegExp(`<${r}>[\\s\\S]*?<\\/${r}>`,"g"),i;for(;(i=o.exec(e))!==null;){let s=this.parseBlock(i[0],r,i.index);s&&n.push(s)}}return n.sort((r,o)=>r.startIndex-o.startIndex),n.filter((r,o)=>!n.some((i,s)=>o!==s&&i.startIndex<=r.startIndex&&i.endIndex>=r.endIndex))}parseBlock(e,n,r){let o=c=>new RegExp(`<${c}>([^<]*)</${c}>`).exec(e)?.[1]||"",i=()=>/<content>([\s\S]*?)<\/content>/.exec(e)?.[1]||"",s=o("path")||o("url"),a=o("title")||s.split("/").pop()||"Untitled",l=i();return{type:n,path:s,title:a,content:l,metadata:{ctime:o("ctime"),mtime:o("mtime")},originalXml:e,startIndex:r,endIndex:r+e.length}}async summarizeItems(e){let n=new Map,r=e.map((o,i)=>({index:i,item:o})).filter(({item:o})=>o.content.length>=this.MIN_ITEM_SIZE);if(r.length===0)return n;k(`[ContextCompactor] Summarizing ${r.length} items`);for(let o=0;o<r.length;o+=this.MAX_CONCURRENCY){let i=r.slice(o,o+this.MAX_CONCURRENCY);(await Promise.all(i.map(async({index:a,item:l})=>{try{return{index:a,summary:await this.summarize(l)}}catch(c){return k(`[ContextCompactor] Failed to summarize item ${a}:`,c),{index:a,summary:null}}}))).forEach(({index:a,summary:l})=>{l&&n.set(a,l)})}return n.size<r.length*.5?(k("[ContextCompactor] High failure rate, aborting compaction"),new Map):n}async summarize(e){let n=e.content;n.length>this.MAX_ITEM_SIZE&&(n=n.slice(0,this.MAX_ITEM_SIZE)+`
[TRUNCATED]`);let r=this.PROMPT.replace("{title}",e.title).replace("{path}",e.path).replace("{content}",n),i=await(await this.chatModelManager.getChatModelWithTemperature(this.TEMPERATURE)).invoke([new Zo(r)]);return typeof i.content=="string"?i.content.trim():""}rebuild(e,n,r){let o=e;return Array.from(r.keys()).sort((i,s)=>s-i).forEach(i=>{let s=n[i],a=r.get(i),l=this.buildBlock(s,a);o=o.slice(0,s.startIndex)+l+o.slice(s.endIndex)}),o}buildBlock(e,n){let r=[`<${e.type}>`];if(e.title&&r.push(`<title>${e.title}</title>`),e.path){let o=this.URL_BASED_TYPES.includes(e.type)?"url":"path";r.push(`<${o}>${e.path}</${o}>`)}return e.metadata.ctime&&r.push(`<ctime>${e.metadata.ctime}</ctime>`),e.metadata.mtime&&r.push(`<mtime>${e.metadata.mtime}</mtime>`),r.push(`<content>[SUMMARIZED]
${n}</content>`),r.push(`</${e.type}>`),r.join(`
`)}}});var Son={};zn(Son,{default:()=>WQ});module.exports=fwt(Son);Zg();Ir();ye();TC();var JN=class t{constructor(e){this.memoryCache=new Map;this.cacheDir=e}static getInstance(e=".copilot/file-content-cache"){return t.instance||(t.instance=new t(e)),t.instance}async ensureCacheDir(){await app.vault.adapter.exists(this.cacheDir)||(k("Creating file cache directory:",this.cacheDir),await app.vault.adapter.mkdir(this.cacheDir))}getCacheKey(e,n){let r=`${e.path}:${e.stat.size}:${e.stat.mtime}${n?`:${n}`:""}`;return Jc(r)}getCachePath(e){return`${this.cacheDir}/${e}.md`}async get(e){try{let n=this.memoryCache.get(e);if(n)return k("Memory cache hit for file:",e),n.content;let r=this.getCachePath(e);if(await app.vault.adapter.exists(r)){k("File cache hit:",e);let o=await app.vault.adapter.read(r),i,s=o.trim();if(s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]"))try{i=JSON.parse(o)}catch{i=o}else i=o;let a={content:i,timestamp:Date.now()};return this.memoryCache.set(e,a),a.content}return k("Cache miss for file:",e),null}catch(n){return z("Error reading from file cache:",n),null}}async set(e,n){try{await this.ensureCacheDir();let r=this.getCachePath(e),o=Date.now(),i={content:n,timestamp:o};this.memoryCache.set(e,i);let s;typeof n=="string"?s=n:s=JSON.stringify(n,null,2),await app.vault.adapter.write(r,s),k("Cached file content:",e)}catch(r){z("Error writing to file cache:",r)}}async remove(e){try{this.memoryCache.delete(e);let n=this.getCachePath(e);await app.vault.adapter.exists(n)&&(await app.vault.adapter.remove(n),k("Removed file from cache:",e))}catch(n){z("Error removing file from cache:",n)}}async clear(){try{if(this.memoryCache.clear(),await app.vault.adapter.exists(this.cacheDir)){let e=await app.vault.adapter.list(this.cacheDir);k("Clearing file cache, removing files:",e.files.length);for(let n of e.files)await app.vault.adapter.remove(n)}}catch(e){z("Error clearing file cache:",e)}}};ye();fc();Id();Id();var mG=require("obsidian"),Ba=Jh(),za=Oo([]),H2t=Oo(t=>t(za).map(e=>e.project));function L5e(){return Wl(H2t,{store:Ba})}function Sp(){return Ba.get(za)}function QN(){return Ba.get(za).map(t=>t.project)}function ef(t){return Ba.get(za).find(e=>e.project.id===t)}function eO(t){return Ba.get(za).find(e=>e.filePath===t)}function uB(t){Ba.set(za,t)}function uye(t,e){let n=Ba.get(za),r=n.findIndex(o=>o.filePath===t);if(r!==-1){let o=n.filter((s,a)=>a===r||s.project.id!==e.project.id),i=o.findIndex(s=>s.filePath===t);o[i]=e,Ba.set(za,o)}else{let o=n.filter(i=>i.project.id!==e.project.id);Ba.set(za,[...o,e])}}function m0(t){let e=Ba.get(za),n=e.findIndex(r=>r.project.id===t.project.id);if(n!==-1){let r=[...e];r[n]=t,Ba.set(za,r)}else Ba.set(za,[...e,t])}function D5e(t){let e=Ba.get(za);Ba.set(za,e.filter(n=>n.project.id!==t))}function AC(t){let e=Ba.get(za);Ba.set(za,e.filter(n=>n.filePath!==t))}function $5e(t){return Ba.sub(za,()=>{t(Ba.get(za))})}var XN=new Map;function tf(t){let e=(0,mG.normalizePath)(t);XN.set(e,(XN.get(e)??0)+1)}function Ju(t){let e=(0,mG.normalizePath)(t),n=(XN.get(e)??0)-1;n<=0?XN.delete(e):XN.set(e,n)}function th(t){return(XN.get((0,mG.normalizePath)(t))??0)>0}TC();var hG=require("obsidian");Hx();Uge();var K2t=".copilot/file-content-cache";function dye(t,e){let n=t?.fileContexts?.[e];return!n?.cacheKey||typeof n.cacheKey!="string"||!n.cacheKey.trim()?null:{cacheKey:n.cacheKey,cachePath:`${K2t}/${n.cacheKey}.md`}}var kC=class kC{constructor(){this.cacheDir=".copilot/project-context-cache";this.memoryCache=new Map;this.projectMutexMap=new Map;this.mutexCreationMutex=new f0;this.handleFileEvent=e=>{e instanceof hG.TFile&&this.debouncedHandleFileChange(e)};this.handleFileChange=async e=>{try{if(e.extension!=="md")return;let n=QN();for(let r of n){let{inclusions:o,exclusions:i}=Bo({inclusions:r.contextSource.inclusions,exclusions:r.contextSource.exclusions,isProject:!0});Qr(e,o,i,!0)&&(await this.invalidateMarkdownContext(r),k(`Invalidated markdown context for project ${r.name} due to file change: ${e.path}`))}}catch(n){z("Error handling file change for project context cache:",n)}};th
${e.join(`
`)}`)}};Zg();Su();ye();Se();qe();var q2t="https://api.firecrawl.dev/v2/search",G2t="https://api.perplexity.ai/chat/completions",U5e="https://api.supadata.ai/v1/transcript",Y2t=2e3,F5e=6e4;function B5e(){let t=q();switch(t.selfHostSearchProvider){case"perplexity":return!!t.perplexityApiKey;case"firecrawl":default:return!!t.firecrawlApiKey}}async function Z2t(t,e){let n=Date.now(),r=await Qy(q2t,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({query:t,limit:5})});if(!r.ok){let u=await r.text();throw new Error(`Firecrawl search failed (${r.status}): ${u}`)}let i=(await r.json())?.data,s=Array.isArray(i)?i:Array.isArray(i?.web)?i.web:[],a=[],l=[];for(let u of s){let d=u.title||"Untitled",f=u.description||"",p=u.url||"";a.push(`### ${d}
${f}
Source: ${p}`),p&&l.push(p)}let c=Date.now()-n;return k(`[selfHostWebSearch] Firecrawl: ${s.length} results in ${c}ms`),{content:a.join(`
`),citations:l}}async function J2t(t,e){let n=await Qy(G2t,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({model:"sonar",messages:[{role:"user",content:t}]})});if(!n.ok){let s=await n.text();throw new Error(`Perplexity Sonar search failed (${n.status}): ${s}`)}let r=await n.json(),o=r?.choices?.[0]?.message?.content??"",i=Array.isArray(r?.citations)?r.citations:[];return{content:o,citations:i}}async function z5e(t){let e=q();switch(e.selfHostSearchProvider){case"perplexity":return J2t(t,await pn(e.perplexityApiKey));case"firecrawl":default:return Z2t(t,await pn(e.firecrawlApiKey))}}async function gG(t){let e=Date.now(),n=await pn(q().supadataApiKey),r=`${U5e}?url=${encodeURIComponent(t)}&mode=auto&text=true`,o=await Qy(r,{method:"GET",headers:{"x-api-key":n,Accept:"application/json"}});if(o.status===200){let s=await o.json(),a=Date.now()-e;return k(`[selfHostYoutube4llm] transcript received in ${a}ms`),{response:{transcript:s.content||""},elapsed_time_ms:a}}if(o.status===201||o.status===202){let a=(await o.json()).job_id;if(!a)throw new Error("Supadata returned async status but no job_id");return await X2t(a,n,e)}let i=await o.text();throw new Error(`Supadata transcript request failed (${o.status}): ${i}`)}async function X2t(t,e,n){let r=Date.now()+F5e,o=`${U5e}/${t}`;for(;Date.now()<r;){await new Promise(a=>window.setTimeout(a,Y2t));let i=await Qy(o,{method:"GET",headers:{"x-api-key":e,Accept:"application/json"}});if(i.status===200){let a=await i.json(),l=Date.now()-n;return k(`[selfHostYoutube4llm] async transcript completed in ${l}ms`),{response:{transcript:a.content||""},elapsed_time_ms:l}}if(i.status===202)continue;let s=await i.text();throw z(`[selfHostYoutube4llm] poll failed (${i.status}): ${s}`),new Error(`Supadata poll failed (${i.status}): ${s}`)}throw new Error(`Supadata transcript timed out after ${F5e}ms`)}qe();ye();ns();Se();var tO=class t{constructor(){this.mentions=new Map,this.brevilabsClient=di.getInstance()}static getInstance(){return t.instance||(t.instance=new t),t.instance}extractAllUrls(e){let n=/https?:\/\/[^\s"'<>]+/g;return(e.match(n)||[]).map(r=>r.replace(/,+$/,"")).filter((r,o,i)=>i.indexOf(r)===o)}extractUrls(e){let n=/https?:\/\/[^\s"'<>]+/g;return(e.match(n)||[]).map(r=>r.replace(/,+$/,"")).filter((r,o,i)=>i.indexOf(r)===o)}async processUrl(e){try{return await this.brevilabsClient.url4llm(e)}catch(n){let r=Xt(n);return z(`Error processing URL ${e}: ${r}`),{response:e,elapsed_time_ms:0,error:r}}}async processYoutubeUrl(e){try{return{transcript:(pc()&&q().supadataApiKey?await gG(e):await this.brevilabsClient.youtube4llm(e)).response.transcript}}catch(n){let r=Xt(n);return z(`Error processing YouTube URL ${e}: ${r}`),{transcript:"",error:r}}}async processTwitterUrl(e){try{return await this.brevilabsClient.twitter4llm(e)}catch(n){let r=Xt(n);return z(`Error processing Twitter URL ${e}: ${r}`),{response:e,elapsed_time_ms:0,error:r}}}async processUrlList(e){let n="",r=[],o={};if(e.length===0)return{urlContext:n,imageUrls:r,processedErrorUrls:o};let i=e.map(async a=>{if(await ry.isImageUrl(a,app.vault))return r.push(a),{type:"image",url:a};if(DAe(a)){let c=this.mentions.get(a);if(!c||c.error){let u=await this.processYoutubeUrl(a);this.mentions.set(a,{type:"youtube",original:a,processed:u.transcript,error:u.error})}return{type:"youtube",data:this.mentions.get(a)}}if($Ae(a)){let c=this.mentions.get(a);if(!c||c.error){let u=await this.processTwitterUrl(a);this.mentions.set(a,{type:"twitter",original:a,processed:u.response,error:u.error})}return{type:"twitter",data:this.mentions.get(a)}}let l=this.mentions.get(a);if(!l||l.error){let c=await this.processUrl(a);this.mentions.set(a,{type:"url",original:a,processed:c.response,error:c.error})}return{type:"url",data:this.mentions.get(a)}});return(await Promise.all(i)).forEach(a=>{if(a.type==="image")return;let l=a.data;l&&(l.processed&&(a.type==="youtube"?n+=`
<youtube_video_context>
<url>${l.original}</url>
<content>
${l.processed}
</content>
</youtube_video_context>`:a.type==="twitter"?n+=`
<twitter_content>
<url>${l.original}</url>
<content>
${l.processed}
</content>
</twitter_content>`:n+=`
<url_content>
<url>${l.original}</url>
<content>
${l.processed}
</content>
</url_content>`),l.error&&(o[l.original]=l.error))}),{urlContext:n,imageUrls:r,processedErrorUrls:o}}async processUrls(e){let n=this.extractUrls(e);return this.processUrlList(n)}getMentions(){return this.mentions}clearMentions(){this.mentions.clear()}};fc();ye();var j5e={id:"",name:"",description:"",systemPrompt:"",projectModelKey:"",modelConfigs:{},contextSource:{},created:0,UsageTimestamps:0},Tp="copilot-project-id",y0="copilot-project-name",w0="copilot-project-description",v0="copilot-project-model-key",MC="copilot-project-temperature",NC="copilot-project-max-tokens",x0="copilot-project-created",nh="copilot-project-last-used",b0="copilot-project-inclusions",C0="copilot-project-exclusions",_0="copilot-project-web-urls",S0="copilot-project-youtube-urls",sv="project.md",nf="unsupported";Se();var OC=require("obsidian");function ja(){return(0,OC.normalizePath)(q().projectsFolder)}function yG(){return(0,OC.normalizePath)(`${ja()}/${nf}`)}function rf(t){return(0,OC.normalizePath)(`${ja()}/${t}`)}function RC(t,e){let n=e?(0,OC.normalizePath)(e):ja();return(0,OC.normalizePath)(`${n}/${t}/${sv}`)}function T0(t){if(!(t instanceof OC.TFile)||t.extension!=="md")return!1;let e=ja();if(!t.path.startsWith(e+"/"))return!1;let n=t.path.slice(e.length+1);if(n.startsWith(`${nf}/`))return!1;let r=n.split("/");return!(r.length!==2||r[1]!==sv)}function V5e(t){let e=ja();if(!t.startsWith(e+"/"))return null;let r=t.slice(e.length+1).split("/");return r.length!==2||r[1]!==sv?null:r[0]||null}function Xc(t){let n=(t||"").trim().replace(/[<>:"/\\|?*]/g,"_").replace(/[\x00-\x1F]/g,"_");return n=n.replace(/[. ]+$/g,""),(n==="."||n==="..")&&(n=n.replace(/\./g,"_")),/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(n)&&(n=`_${n}`),n||(n="_"),n}function W5e(t,e){let n=(e||"").trim()||t,r=Xc(n);return r.toLowerCase()===nf&&(r=`_${r}`),r}function rh(t){return(t||"").split(`
`).map(e=>e.trim()).filter(Boolean)}async function fye(t,e,n){try{let o=(await t.cachedRead(e)).replace(/^\uFEFF/,"").match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!o)return"";let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=o[1].match(new RegExp(`^${i}:\\s*(.+)$`,"m"));if(!s)return"";let a=s[1].trim();if(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))a=a.slice(1,-1);else{let l=a.indexOf(" #");l>0&&(a=a.slice(0,l).trim())}return a}catch{return""}}qe();ye();var lv=require("obsidian");async function fB(t,e,n,r){let o=rh(e.contextSource?.webUrls||""),i=rh(e.contextSource?.youtubeUrls||"");await app.fileManager.processFrontMatter(t,s=>{s[Tp]=e.id.trim(),s[y0]=(e.name||n).trim(),s[w0]=(e.description||"").trim(),s[v0]=(e.projectModelKey||"").trim(),e.modelConfigs?.temperature!=null?s[MC]=e.modelConfigs.temperature:delete s[MC],e.modelConfigs?.maxTokens!=null?s[NC]=e.modelConfigs.maxTokens:delete s[NC],s[b0]=e.contextSource?.inclusions||"",s[C0]=e.contextSource?.exclusions||"",s[_0]=o,s[S0]=i,s[x0]=r.createdMs,s[nh]=r.lastUsedMs})}function wG(t,e){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let n=Number(t);if(Number.isFinite(n))return n}return e}function rO(t,e){return typeof t=="string"?t:e}function q5e(t){return Array.isArray(t)?t.filter(e=>typeof e=="string").map(e=>e.trim()).filter(Boolean):typeof t=="string"?t.split(`
`).map(e=>e.trim()).filter(Boolean):[]}function G5e(t){return t.replace(/\n\s*/g,"").replace(/\r/g,"")}function Y5e(t){return(t||[]).map(e=>e.trim()).filter(Boolean).join(`
`)}async function E0(t){let e=app.vault.getAbstractFileByPath(t.path),n=e instanceof lv.TFile,r=n?await app.vault.read(e):await app.vault.adapter.read(t.path),o=Qh(r,{trimStart:!1}),i,s=r.replace(/^\uFEFF/,"").match(/^---\r?\n([\s\S]*?)\r?\n---/);if(s)try{let A=(0,lv.parseYaml)(s[1]);A&&typeof A=="object"&&(i=A)}catch{return ee(`[Projects] Failed to parse YAML frontmatter from file: ${t.path}`),null}!i&&n&&(i=app.metadataCache.getFileCache(e)?.frontmatter);let a=V5e(t.path);if(!a)return ee(`[Projects] Cannot extract folder name from path, ignoring file: ${t.path}`),null;let l=i?.[Tp],c=typeof l=="number"&&Number.isFinite(l)?String(l):rO(l,"");if(!c.trim())return ee(`[Projects] Missing ${Tp} in frontmatter, skipping file: ${t.path}`),null;let u=c.trim(),f=rO(i?.[y0],"").trim()||a,p=rO(i?.[w0],"").trim(),m=rO(i?.[v0],"").trim(),h=wG(i?.[MC],NaN),g=wG(i?.[NC],NaN),y=rO(i?.[b0],""),w=rO(i?.[C0],""),v=G5e(y),x=G5e(w),b=q5e(i?.[_0]),_=q5e(i?.[S0]),T=wG(i?.[x0],t.stat?.ctime??0),S=wG(i?.[nh],0),P={};return Number.isFinite(h)&&(P.temperature=h),Number.isFinite(g)&&g>0&&(P.maxTokens=g),{project:{...j5e,id:u,name:f,description:p||"",systemPrompt:o,projectModelKey:m,modelConfigs:P,contextSource:{inclusions:v||"",exclusions:x||"",webUrls:Y5e(b),youtubeUrls:Y5e(_)},created:Number.isFinite(T)&&T>0?T:0,UsageTimestamps:Number.isFinite(S)&&S>0?S:0},filePath:t.path,folderName:a}}async function vG(){let t=ja(),e=app.vault.getAbstractFileByPath(t),n=[];if(e instanceof lv.TFolder)for(let s of e.children){if(!(s instanceof lv.TFolder)||s.name===nf)continue;let a=s.children.find(l=>l instanceof lv.TFile&&l.name===sv);a instanceof lv.TFile&&n.push(a)}else if(await app.vault.adapter.exists(t)){let{resolveFileByPath:s}=await Promise.resolve().then(()=>(av(),K5e)),a=await app.vault.adapter.list(t);for(let l of a.folders){if((l.split("/").pop()??"")===nf)continue;let u=`${l}/${sv}`;if(await app.vault.adapter.exists(u)){let d=await s(app,u);d&&n.push(d)}}}n.sort((s,a)=>s.path.localeCompare(a.path));let r={},o=[],i=[];for(let s of n){let a;try{a=await E0(s)}catch(c){z(`[Projects] Failed to parse project file, skipping: ${s.path}`,c),o.push(s.path);continue}if(!a){o.push(s.path);continue}let l=a.project.id;if(r[l]||(r[l]=[]),r[l].push(s.path),r[l].length>1){ee(`[Projects] Duplicate project id="${l}": ${r[l].join(", ")}; keeping first: ${r[l][0]}`);continue}i.push(a)}return{records:i,diagnostics:{duplicateIdIndex:r,ignoredFiles:o}}}async function cv(){let{records:t}=await vG();return uB(t),t}async function Z5e(){let{records:t}=await vG();return t}async function pB(t,e){let n=th(t.path),r=Date.now(),o=Number.isFinite(e.project.created)&&e.project.created>0?e.project.created:r,i=Number.isFinite(e.project.UsageTimestamps)&&e.project.UsageTimestamps>0?e.project.UsageTimestamps:0,s=rh(e.project.contextSource?.webUrls||""),a=rh(e.project.contextSource?.youtubeUrls||"");try{n||tf(t.path),await app.fileManager.processFrontMatter(t,l=>{l[Tp]==null&&e.project.id&&(l[Tp]=e.project.id),l[y0]==null&&(l[y0]=e.project.name||e.folderName),l[w0]==null&&e.project.description&&(l[w0]=e.project.description),l[v0]==null&&e.project.projectModelKey&&(l[v0]=e.project.projectModelKey),l[MC]==null&&e.project.modelConfigs?.temperature!=null&&(l[MC]=e.project.modelConfigs.temperature),l[NC]==null&&e.project.modelConfigs?.maxTokens!=null&&(l[NC]=e.project.modelConfigs.maxTokens),l[b0]==null&&e.project.contextSource?.inclusions&&(l[b0]=e.project.contextSource.inclusions),l[C0]==null&&e.project.contextSource?.exclusions&&(l[C0]=e.project.contextSource.exclusions),l[_0]==null&&s.length>0&&(l[_0]=s),l[S0]==null&&a.length>0&&(l[S0]=a),l[x0]==null&&(l[x0]=o),l[nh]==null&&(l[nh]=i)})}finally{n||Ju(t.path)}}qe();Ky();av();var Ip=require("obsidian");rn();ye();ws();var J5e=require("obsidian"),A0=N(U());function Q2t({content:t,onConfirm:e,onCancel:n,confirmButtonText:r,cancelButtonText:o}){return A0.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-5"},A0.default.createElement("div",{className:"tw-whitespace-pre-wrap"},t),A0.default.createElement("div",{className:"tw-flex t
`).replace(/\r/g,`
`)}async function k0(t,e,n){try{let r=yG();await Fr(r);let o=Xc(e.id||"unknown")||"unknown",i=`Project Migration Failed - ${o}`,s=`${r}/${i}.md`,a=2;for(;await t.adapter.exists(s);){if(a===2)try{let u=(await t.adapter.read(s)).match(/```json\s*\n([\s\S]*?)\n```/);if(u){let d=JSON.parse(u[1]);if(JSON.stringify(d)===JSON.stringify(e))return!1}}catch{}if(s=`${r}/${i} - ${a}.md`,a++,a>20)return ee(`[Projects] Too many backup collisions for safeId="${o}", giving up`),!1}let l=[`> Projects migration failed: ${n}`,">","> This file is an automatic backup (unsupported/), for manual recovery.","> You can recreate the project from the JSON below, or fix and re-migrate.","","```json",JSON.stringify(e,null,2),"```",""].join(`
`);return await t.create(s,l),!0}catch(r){return z(`[Projects] Failed to save unsupported backup for project id=${e.id||"unknown"}`,r),!1}}async function tqe(t,e,n){let r=t.vault;try{let o=r.getAbstractFileByPath(e);o instanceof eu.TFile?await Qc(t,o):await r.adapter.exists(e)&&await r.adapter.remove(e);let i=r.getAbstractFileByPath(n);if(i instanceof eu.TFolder&&i.children.length===0)await Qc(t,i);else if(await r.adapter.exists(n)){let s=await r.adapter.list(n);s.files.length===0&&s.folders.length===0&&await r.adapter.rmdir(n,!1)}}catch(o){z(`[Projects] Migration rollback failed for ${e}`,o)}}async function eUt(t,e,n){let r=t.vault,o=ja();await Fr(o),await Fr(`${o}/${n}`);let i=RC(n),s=`${o}/${n}`;tf(i);try{let a=await r.create(i,e.systemPrompt||""),l=Date.now(),c=Number.isFinite(e.created)&&e.created>0?e.created:l,u=Number.isFinite(e.UsageTimestamps)&&e.UsageTimestamps>0?e.UsageTimestamps:0;try{await fB(a,e,n,{createdMs:c,lastUsedMs:u})}catch(d){throw await tqe(t,i,s),d}return a}finally{Ju(i)}}async function Q5e(t,e,n){try{let r=e instanceof eu.TFile?await t.read(e):await t.adapter.read(e),o=Qh(r,{trimStart:!1}),i=X5e(o).replace(/^\n+/,""),s=X5e(n||"").replace(/^\n+/,"");return i!==s?(ee(`[Projects] Migration verify failed: content mismatch. Expected ${s.length} chars, got ${i.length} chars`),!1):!0}catch(r){return z("[Projects] Migration verify failed: unable to read back file",r),!1}}function eqe(t,e){return W5e(t,e)}async function tUt(t){let e=t.vault,r=q().projectList||[];if(r.length===0){k("[Projects] No legacy projects to migrate");return}k(`[Projects] Migrating ${r.length} legacy projects to vault files...`);let o=[],i=new Set,s=new Map;for(let f of r){let p=(f.id||"").trim();if(!p){ee("[Projects] Skip migrating project with empty id"),await k0(e,f,"empty project id");continue}if(i.has(p)){ee(`[Projects] Skip migrating duplicate project id: ${p}`),await k0(e,f,`duplicate project id: ${p}`);continue}i.add(p);let m=eqe(p,f.name),h=m.toLowerCase(),g=s.get(h);if(g){ee(`[Projects] Skip migrating project id="${p}": folder name "${m}" collides with id="${g}"`),await k0(e,f,`folder name collision: "${m}" already used by id="${g}"`);continue}s.set(h,p);let y=RC(m),w=e.getAbstractFileByPath(y);if(w instanceof eu.TFile||await e.adapter.exists(y)){let x="";if(w instanceof eu.TFile){let b=t.metadataCache.getFileCache(w);x=String(b?.frontmatter?.[Tp]??"").trim(),x||(x=await fye(e,w,Tp))}else try{let _=(await e.adapter.read(y)).replace(/^\uFEFF/,"").match(/^---\r?\n([\s\S]*?)\r?\n---/);if(_){let T=(0,eu.parseYaml)(_[1]);if(T&&typeof T=="object"){let S=T[Tp];x=(typeof S=="string"?S:"").trim()}}}catch{x=""}if(x===p){if(await Q5e(e,w instanceof eu.TFile?w:y,f.systemPrompt||"")){if(w instanceof eu.TFile)try{let _=eqe(p,f.name);await pB(w,{project:f,filePath:y,folderName:_})}catch(_){ee(`[Projects] Failed to repair frontmatter for id=${p}, continuing`,_)}k(`[Projects] Migration skip: target file already exists for id=${p} at ${y}`),o.push(f);continue}ee(`[Projects] Migration verify failed on existing file for id=${p} at ${y}`),await k0(e,f,`existing file content mismatch at ${y} (delete/rename the file and re-run migration)`);continue}ee(`[Projects] Migration conflict: ${y} exists with id="${x}" but expected "${p}"`),await k0(e,f,`target file exists at ${y} with mismatched id="${x}"`);continue}try{let x=await eUt(t,f,m);if(await Q5e(e,x,f.systemPrompt||""))o.push(f);else{let _=`${ja()}/${m}`;await tqe(t,x.path,_),await k0(e,f,"content verification mismatch")}}catch(x){let b=x instanceof Error?x.message:String(x);z(`[Projects] Failed to migrate project id=${p}`,x),await k0(e,f,b)}}pe("projectList",[]);let a=o.length,l=r.length-a,c=ja(),u=yG(),d=f=>{let p=e.getAbstractFileByPath(f);if(p instanceof eu.TFolder){let m=t.internalPlugins?.getPluginById?.("file-explorer");m?.enabled&&m.instance?.revealInFolder&&m.instance.revealInFolder(p)}else new eu.Notice(`Folder "${f}" is hidden and cannot be revealed in Obsidian's explorer.`)};l===0?(k(`[Projects] Migration succeeded: all ${a} project(s) migrated to vault files`),new Cr(t,()=>d(c),`Y
You can now:
\u2022 Edit project settings directly in the file
\u2022 View and manage project files in the vault
\u2022 All ${a} project(s) were migrated successfully.`,"\u{1F680} Projects Upgraded","Show in Folder","OK").open()):a>0?(ee(`[Projects] Migration partially succeeded: ${a} migrated, ${l} failed`),new Cr(t,()=>d(c),`\u26A0\uFE0F Projects migration partially completed.
\u2705 ${a} project(s) migrated successfully.
\u274C ${l} project(s) failed \u2014 their data has been backed up to:
${u}
You can manually recover failed projects from the unsupported folder.`,"\u26A0\uFE0F Projects Migration: Partial Success","Show in Folder","OK").open()):(ee("[Projects] Migration failed: no projects were migrated"),new Cr(t,()=>d(u),`\u26A0\uFE0F Projects migration could not be completed.
Your project data has been backed up to:
${u}
To recover:
1. Open the files in the unsupported folder
2. Review the content
3. Recreate the projects manually`,"\u26A0\uFE0F Projects Migration Failed","Show in Folder","OK").open())}async function nUt(t){let{records:e}=await vG();if(e.length===0)return;let n=0,r=ja(),o=new Map;for(let i of e)o.set(i.folderName.toLowerCase(),i.project.id);for(let i of e){let s=(i.project.name||"").trim();if(!s)continue;let a=Xc(s),l=a.toLowerCase()===nf?`_${a}`:a;if(l===i.folderName)continue;let c=`${r}/${l}`,u=rf(i.folderName),d=i.filePath,f=RC(l),p=l.toLowerCase(),m=o.get(p);if(m&&m!==i.project.id){ee(`[Projects] Naming migration skip: folder "${l}" collides (case-insensitive) with project id="${m}" for project id="${i.project.id}"`);continue}if(!(c.toLowerCase()===u.toLowerCase())&&await t.adapter.exists(c)){ee(`[Projects] Naming migration skip: target folder "${c}" already exists for project id="${i.project.id}"`);continue}try{tf(d),tf(f);let g=t.getAbstractFileByPath(u);g instanceof eu.TFolder?await t.rename(g,c):await t.adapter.rename(u,c),n++,o.delete(i.folderName.toLowerCase()),o.set(p,i.project.id),k(`[Projects] Naming migration: renamed folder "${i.folderName}" \u2192 "${l}" for project "${s}" (id=${i.project.id})`)}catch(g){z(`[Projects] Naming migration failed for project id="${i.project.id}"`,g)}finally{Ju(d),Ju(f)}}n>0&&k(`[Projects] Naming migration complete: ${n} folder(s) renamed`)}async function nqe(t){(q().projectList||[]).length>0&&await tUt(t),await nUt(t.vault)}var Xu=class t{constructor(e){this.projectLastUsedManager=new sA;this.app=e,this.vault=e.vault}static getInstance(e){if(!t.instance){if(!e)throw new Error("App is required for first initialization");t.instance=new t(e)}return t.instance}async initialize(){k("[Projects] Initializing ProjectFileManager"),await nqe(this.app),await cv()}getProjects(){return Sp().map(e=>e.project)}getProjectRecords(){return Sp()}async reloadProjects(){return await cv()}async fetchProjects(){return await Z5e()}getProjectUsageTimestampsManager(){return this.projectLastUsedManager}sanitizeFolderName(e){let n=Xc(e);return n.toLowerCase()===nf?`_${n}`:n}async rollbackCreatedFile(e,n){try{let r=this.vault.getAbstractFileByPath(e);r instanceof Ip.TFile?await Qc(this.app,r):await this.vault.adapter.exists(e)&&await this.vault.adapter.remove(e);let o=this.vault.getAbstractFileByPath(n);if(o instanceof Ip.TFolder&&o.children.length===0)await Qc(this.app,o);else if(await this.vault.adapter.exists(n)){let i=await this.vault.adapter.list(n);i.files.length===0&&i.folders.length===0&&await this.vault.adapter.rmdir(n,!1)}}catch(r){z(`[Projects] Rollback failed for ${e}`,r)}}getLeadingFrontmatterBlock(e){let r=e.replace(/^\uFEFF/,"").match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return r?r[0]:null}buildProjectFileContent(e,n,r){let o=rh(e.contextSource?.webUrls||""),i=rh(e.contextSource?.youtubeUrls||""),s={[Tp]:e.id.trim(),[y0]:(e.name||n).trim(),[w0]:(e.description||"").trim(),[v0]:(e.projectModelKey||"").trim(),[b0]:e.contextSource?.inclusions||"",[C0]:e.contextSource?.exclusions||"",[_0]:o,[S0]:i,[x0]:r.createdMs,[nh]:r.lastUsedMs};return e.modelConfigs?.temperature!=null&&(s[MC]=e.modelConfigs.temperature),e.modelConfigs?.maxTokens!=null&&(s[NC]=e.modelConfigs.maxTokens),`---
${(0,Ip.stringifyYaml)(s)}---
${e.systemPrompt||""}`}async createProject(e){let n=(e.id||"").trim();if(!n)throw new Error("Project id cannot be empty");if(ef(n))throw new Error(`Project id already exists: ${n}`);let r=(e.name||"").trim();if(r&&Sp().some(d=>d.project.name.trim().toLowerCase()===r.toLowerCase()))throw new Error(`A project with the name "${r}" already exists`);let o=this.sanitizeFolderName(r||n),i=rf(o),s=RC(o),a=o.toLowerCase(),c=Sp().find(u=>u.folderName.toLowerCase()===a&&u.project.id!==n);if(c)throw new Error(`Folder name collision: project id "${n}" sanitizes to folder "${o}" which conflicts with existing project "${c.project.id}"`);try{if(tf(s),await Fr(ja()),await Fr(i),await this.vault.adapter.exists(s))throw new Error(`Project file already exists at "${s}". This may be a folder name collision \u2014 project id "${n}" sanitizes to folder "${o}"`);let u=Date.now(),d=Number.isFinite(e.created)&&e.created>0?e.created:u,f=Number.isFinite(e.UsageTimestamps)&&e.UsageTimestamps>0?e.UsageTimestamps:0,p=await this.vault.create(s,e.systemPrompt||"");try{await fB(p,e,o,{createdMs:d,lastUsedMs:f})}catch(h){throw await this.rollbackCreatedFile(s,i),h}let m={project:{...e,id:n,created:d,UsageTimestamps:f},filePath:s,folderName:o};return m0(m),k(`[Projects] Created project: ${n} -> ${s}`),m}finally{Ju(s)}}async updateProject(e,n){let r=(e||"").trim();if(!r)throw new Error("Project id cannot be empty");if((n.id||"").trim()!==r)throw new Error("Project id mismatch: cannot change id via update");let o=ef(r);if(!o)throw new Error(`Project not found: ${r}`);let i=(n.name||"").trim();if(i&&Sp().some(d=>d.project.id!==r&&d.project.name.trim().toLowerCase()===i.toLowerCase()))throw new Error(`A project with the name "${i}" already exists`);let s=o.filePath,a=o.folderName,l=this.sanitizeFolderName(i||r),c=null;if(l!==o.folderName){let u=rf(l),d=RC(l),f=l.toLowerCase(),p=Sp().find(h=>h.project.id!==r&&h.folderName.toLowerCase()===f);if(p)throw new Error(`Cannot rename project folder: "${l}" conflicts with project "${p.project.name}"`);if(!(u.toLowerCase()===rf(o.folderName).toLowerCase())&&await this.vault.adapter.exists(u))throw new Error(`Cannot rename project folder: "${u}" already exists on disk`);c=s,tf(c),tf(d);try{let h=rf(o.folderName),g=this.vault.getAbstractFileByPath(h);g instanceof Ip.TFolder?await this.vault.rename(g,u):await this.vault.adapter.rename(h,u)}catch(h){throw Ju(c),Ju(d),h}s=d,a=l,k(`[Projects] Renamed project folder: "${o.folderName}" \u2192 "${l}" for project ${r}`)}try{c||tf(s);let u=await I0(app,s),d=!1;if(!u){k(`[Projects] Materializing missing vault file for project: ${r}`);let w=rf(a);await Fr(ja()),await Fr(w),u=await this.vault.create(s,n.systemPrompt||""),d=!0}let f=Number.isFinite(o.project.created)&&o.project.created>0?o.project.created:Date.now(),p=Number.isFinite(o.project.UsageTimestamps)&&o.project.UsageTimestamps>0?o.project.UsageTimestamps:0,m=this.projectLastUsedManager.getLastTouchedAt(r)??0,h=Math.max(p,m),g={...n,created:f,UsageTimestamps:h};if(P0(app,s)){try{await fB(u,g,a,{createdMs:f,lastUsedMs:h})}catch(b){throw d&&await this.rollbackCreatedFile(s,rf(a)),b}let w=await this.vault.read(u),v=this.getLeadingFrontmatterBlock(w);if(!v)throw new Error(`Expected frontmatter block after update: ${u.path}`);let x=v.endsWith(`
`)?"":`
`;await this.vault.modify(u,v+x+(n.systemPrompt||""))}else{let w=this.buildProjectFileContent(g,a,{createdMs:f,lastUsedMs:h});await this.vault.adapter.write(s,w)}let y={project:{...n,created:f,UsageTimestamps:h},filePath:s,folderName:a};return m0(y),k(`[Projects] Updated project: ${r} -> ${s}`),y}catch(u){if(c&&a!==o.folderName)try{let d=rf(o.folderName),f=rf(a),p=this.vault.getAbstractFileByPath(f);p instanceof Ip.TFolder?await this.vault.rename(p,d):await this.vault.adapter.rename(f,d),ee(`[Projects] Rolled back folder rename "${a}" \u2192 "${o.folderName}" after write failure`)}catch(d){z(`[Projects] Failed to rollback folder rename for ${r}`,d)}throw u}finally{Ju(s),c&&Ju(c)}}async deleteProject(e){let n=(e||"").trim(),r=ef(n);if(!r){ee(`[Projects] deleteProject: not found: ${n}`);return}let o=rf(r.folderName);try{tf(r.filePath);let i=this.vault.getAbstractFileByPath(r.filePath);i instanceof Ip.TFile?await Qc(this.app,i):await this.vault.adapter.exists(r.filePath)&&await this.vault.adapter.remove(r.filePath),D5e(n);try{let s=this.vault.getAbstractFileByPath(o);if(s instanceof Ip.TFolder&&s.children.length===0)await Qc(this.app,s);else if(await this.vault.adapter.exists(o)){let a=await this.vault.adapter.list(o);a.files.length===0&&a.folders.length===0&&await this.vault.adapter.rmdir(o,!1)}}catch(s){ee(`[Projects] Failed to clean up empty project folder: ${o}`,s)}await ti.getInstance().clearForProject(r.project).catch(s=>z("[Projects] Failed to clear context cache on delete",s)),k(`[Projects] Deleted project: ${n} -> ${o}`),cv().catch(s=>z("[Projects] Rescan after delete failed",s))}finally{Ju(r.filePath)}}async touchProjectLastUsed(e){let n=(e||"").trim(),r=ef(n);if(r)try{this.projectLastUsedManager.touch(n);let o=this.projectLastUsedManager.shouldPersist(n,r.project.UsageTimestamps);if(o===null)return;let i=(0,Ip.normalizePath)(r.filePath),s=await I0(app,i);if(!s)return;let a=th(i),l=o;try{if(a||tf(i),P0(app,i))await app.fileManager.processFrontMatter(s,u=>{let d=Number(u[nh]),f=Number.isFinite(d)&&d>0?d:0;l=Math.max(f,o),f!==l&&(u[nh]=l)});else{let u=await oy(app,i),d=Number(u?.[nh]),f=Number.isFinite(d)&&d>0?d:0;l=Math.max(f,o),f!==l&&await LC(app,i,{[nh]:l})}}finally{a||Ju(i)}this.projectLastUsedManager.markPersisted(n,l);let c=ef(n);c&&m0({...c,project:{...c.project,UsageTimestamps:l}})}catch(o){z(`[Projects] Failed to touch last-used for projectId=${e}`,o)}}};Se();ye();TC();var xG=class t{constructor(){this.cacheDir=".copilot/pdf-cache"}static getInstance(){return t.instance||(t.instance=new t),t.instance}async ensureCacheDir(){await app.vault.adapter.exists(this.cacheDir)||(k("Creating PDF cache directory:",this.cacheDir),await app.vault.adapter.mkdir(this.cacheDir))}getCacheKey(e){let n=`${e.path}:${e.stat.size}:${e.stat.mtime}`,r=Jc(n);return k("Generated cache key for PDF:",{path:e.path,key:r}),r}getCachePath(e){return`${this.cacheDir}/${e}.json`}async get(e){try{let n=this.getCacheKey(e),r=this.getCachePath(n);if(await app.vault.adapter.exists(r)){k("Cache hit for PDF:",e.path);let o=await app.vault.adapter.read(r);return JSON.parse(o)}return k("Cache miss for PDF:",e.path),null}catch(n){return z("Error reading from PDF cache:",n),null}}async set(e,n){try{await this.ensureCacheDir();let r=this.getCacheKey(e),o=this.getCachePath(r);k("Caching PDF response for:",e.path),await app.vault.adapter.write(o,JSON.stringify(n))}catch(r){z("Error writing to PDF cache:",r)}}async clear(){try{if(await app.vault.adapter.exists(this.cacheDir)){let e=await app.vault.adapter.list(this.cacheDir);k("Clearing PDF cache, removing files:",e.files.length);for(let n of e.files)await app.vault.adapter.remove(n)}}catch(e){z("Error clearing PDF cache:",e)}}};ye();RN();yp();ns();Se();ye();qe();async function rqe(t,e,n,r){let o=r?.trim();if(o&&t.extension!=="md"&&!(!e||e.startsWith("[Error:")))try{await Fr(o);let i=`${o}/${t.basename}.md`;if(await n.adapter.exists(i)){let a=await n.adapter.read(i);if(a&&!a.startsWith(`<!-- source: ${t.path} -->`)){let l=t.path.replace(/\.[^.]+$/,"").replace(/[/\\]/g,"__");if(i=`${o}/${l}.md`,await n.
${e}`;if(await n.adapter.exists(i)&&await n.adapter.read(i)===s)return;await n.adapter.write(i,s),k(`Saved converted doc output: ${i}`)}catch(i){z(`Failed to save converted doc output for ${t.path}:`,i)}}function uv(t){if(!t||typeof t!="object")return!1;let e=t,n=e.message||"";return n.includes("Request rate limit exceeded")||n.includes("RATE_LIMIT_EXCEEDED")||n.includes("429")||e.status===429}function oqe(t){let r=(t?.message||"").match(/Try again in ([\d\w\s]+)/);return r?r[1]:"some time"}var aqe=require("obsidian");var iqe=require("obsidian");var CG,sqe,bG=class{constructor(e){this.vault=e;GQ(this,CG)}async load(e){let n=await this.vault.read(e),{nodes:r=[],edges:o=[]}=JSON.parse(n),i=await Promise.all(r.map(async l=>{if(l.type==="file"&&l.file){let c=this.vault.getAbstractFileByPath(l.file),u=c instanceof iqe.TFile?await this.vault.read(c):"";return{...l,content:u}}return l.type==="text"?{...l,content:l.text??""}:{...l,content:""}})),s=[...o];sPe(this,CG,sqe).call(this,i,s);let a=Object.fromEntries(i.map(l=>[l.id,l]));return{nodes:i,edges:s,byId:a}}buildPrompt(e){let n=new Map,r=e.nodes.filter(a=>a.type==="group");for(let a of r){let l=e.nodes.filter(c=>{if(c.id===a.id)return!1;let u=c.x+c.width/2,d=c.y+c.height/2;return u>=a.x&&d>=a.y&&u<=a.x+a.width&&d<=a.y+a.height});n.set(a.label||a.id,l)}let o=`This canvas contains the following elements:
`,i=a=>{switch(a.type){case"file":return`- File: ${a.file}
Content:
${a.content}
`;case"text":return`- Text: "${a.text}"
`;case"link":return`- Link: ${a.url}
`;default:return""}};r.forEach(a=>{let l=a.label||a.id,c=n.get(l)||[];o+=`Group "${l}" contains:
`,c.forEach(u=>{o+=i(u)}),o+=`
`});let s=e.nodes.filter(a=>a.type==="group"?!1:!Array.from(n.values()).flat().some(l=>l.id===a.id));return s.length>0&&(o+=`Elements outside of groups:
`,s.forEach(a=>{o+=i(a)})),o+=`
When describing this canvas, please:
`,o+=`- Use the actual titles/names of elements instead of their IDs
`,o+=`- Pay attention to the content and relationships between elements
`,o+=`- Describe files by their names, links by their URLs, and text nodes by their content
`,o}};CG=new WeakSet,sqe=function(e,n){let r=e.filter(o=>o.type==="group");for(let o of r)for(let i of e){if(i.id===o.id)continue;let s=i.x+i.width/2,a=i.y+i.height/2;s>=o.x&&a>=o.y&&s<=o.x+o.width&&a<=o.y+o.height&&n.push({id:crypto.randomUUID(),fromNode:o.id,toNode:i.id,label:"contains"})}};async function DC(t,e,n){let r=q().convertedDocOutputFolder??"";await rqe(t,e,n,r)}var _G=class{constructor(){this.miyoClient=new wp}async parsePdf(e,n){let r=q();if(!r.enableMiyo||e.extension.toLowerCase()!=="pdf")return null;try{let o=await this.miyoClient.resolveBaseUrl(Jm(r)),i=n.getName(),s=await this.miyoClient.parseDoc(o,i,e.path);return typeof s.text!="string"||s.text.trim().length===0?{error:"Miyo parse-doc returned empty text"}:(k(`[SelfHostPdfParser] Parsed PDF via Miyo: ${e.path}`),{content:s.text})}catch(o){let i=o instanceof Error?o.message:String(o);return ee(`[SelfHostPdfParser] Failed to parse ${e.path} via Miyo parse-doc: ${i}`),{error:i}}}},pye=class{constructor(){this.supportedExtensions=["md","base"]}async parseFile(e,n){return await n.read(e)}},SG=class{constructor(e){this.supportedExtensions=["pdf"];this.brevilabsClient=e,this.pdfCache=xG.getInstance(),this.selfHostPdfParser=new _G}async parseFile(e,n){try{k("Parsing PDF file:",e.path);let r=await this.pdfCache.get(e);if(r)return k("Using cached PDF content for:",e.path),await DC(e,r.response,n),r.response;let o=q();if(pc()&&o.enableMiyo&&e.extension.toLowerCase()==="pdf"){let a=await this.selfHostPdfParser.parsePdf(e,n);if(a&&"content"in a)return await this.pdfCache.set(e,{response:a.content,elapsed_time_ms:0}),await DC(e,a.content,n),a.content;if(a&&"error"in a)return ee(`[PDFParser] Miyo parse failed for ${e.path}: ${a.error}`),`[Error: Could not extract content from PDF ${e.basename}. ${a.error}]`}let i=await n.readBinary(e);k("Calling pdf4llm API for:",e.path);let s=await this.brevilabsClient.pdf4llm(i);return await this.pdfCache.set(e,s),await DC(e,s.response,n),s.response}catch(r){return z(`Error extracting content from PDF ${e.path}:`,r),`[Error: Could not extract content from PDF ${e.basename}]`}}async clearCache(){k("Clearing PDF cache"),await this.pdfCache.clear()}},mye=class{constructor(){this.supportedExtensions=["canvas"]}async parseFile(e,n){try{k("Parsing Canvas file:",e.path);let r=new bG(n),o=await r.load(e);return r.buildPrompt(o)}catch(r){return z(`Error parsing Canvas file ${e.path}:`,r),`[Error: Could not parse Canvas file ${e.basename}]`}}},lqe=["pdf","602","abw","cgm","cwk","doc","docx","docm","dot","dotm","hwp","key","lwp","mw","mcw","pages","pbd","ppt","pptm","pptx","pot","potm","potx","rtf","sda","sdd","sdp","sdw","sgl","sti","sxi","sxw","stw","sxg","txt","uof","uop","uot","vor","wpd","wps","xml","zabw","epub","jpg","jpeg","png","gif","bmp","svg","tiff","webp","web","htm","html","xlsx","xls","xlsm","xlsb","xlw","csv","dif","sylk","slk","prn","numbers","et","ods","fods","uos1","uos2","dbf","wk1","wk2","wk3","wk4","wks","123","wq1","wq2","wb1","wb2","wb3","qpw","xlr","eth","tsv","mp3","mp4","mpeg","mpga","m4a","wav","webm"],oO=class oO{constructor(e,n=null){this.supportedExtensions=[...lqe];this.brevilabsClient=e,this.projectContextCache=ti.getInstance(),this.selfHostPdfParser=new _G,this.currentProject=n}static resetRateLimitNoticeTimer(){oO.lastRateLimitNoticeTime=0}async parseFile(e,n){try{if(k(`[Docs4LLMParser] Project ${this.currentProject?.name}: Parsing ${e.extension} file: ${e.path}`),!this.currentProject)throw z("[Docs4LLMParser] No project context for parsing file: ",e.path),new Error("No project context provided for file parsing");let r=await this.projectContextCache.getOrReuseFileContext(this.currentProject,e.path);if(r)return k(`[Docs4LLMParser] Project ${this.currentProject.name}: Using cached content for: ${e.path}`),await DC(e,r,n),r;if(k(`[Docs4LLMParser] Project ${this.currentProject.name}: Cache miss for: ${e.path}. Proceeding to API call.`),pc()&&q().enableMiyo&&e.extension.toLowerCase()==="pdf"){let a=await this.selfHostPdfParser.parsePdf(e,n);if(a&&"content"in a)return await this.projectContextCache.setFileContex
`)}else if(typeof i.response=="object"){let a=i.response;a.md?s=a.md:a.text?s=a.text:a.content?s=a.content:s=JSON.stringify(i.response,null,2)}else s=JSON.stringify(i.response);return await this.projectContextCache.setFileContext(this.currentProject,e.path,s),await DC(e,s,n),k(`[Docs4LLMParser] Project ${this.currentProject.name}: Successfully processed and cached: ${e.path}`),s}catch(r){throw z(`[Docs4LLMParser] Project ${this.currentProject?.name}: Error processing file ${e.path}:`,r),uv(r)&&this.showRateLimitNotice(r),r}}showRateLimitNotice(e){let n=Date.now();if(n-oO.lastRateLimitNoticeTime<6e4)return;oO.lastRateLimitNoticeTime=n;let r=oqe(e);new aqe.Notice(`\u26A0\uFE0F Rate limit exceeded for document processing. Please try again in ${r}. Having fewer non-markdown files in the project will help.`,1e4)}async clearCache(){k("Cache clearing is now handled at the project level")}};oO.lastRateLimitNoticeTime=0;var mB=oO,iy=class{constructor(e,n,r=!1,o=null){this.parsers=new Map;this.registerParser(new pye),this.registerParser(new mB(e,o)),r||this.registerParser(new SG(e)),this.registerParser(new mye)}static getProjectSupportedExtensions(){let e=new Set;e.add("md");for(let n of lqe)e.add(n);return e.add("canvas"),e}registerParser(e){for(let n of e.supportedExtensions)this.parsers.set(n,e)}async parseFile(e,n){let r=this.parsers.get(e.extension);if(!r)throw new Error(`No parser found for file type: ${e.extension}`);return await r.parseFile(e,n)}supportsExtension(e){return this.parsers.has(e)}async clearPDFCache(){let e=this.parsers.get("pdf");e instanceof SG&&await e.clearCache()}};qe();var mP=require("obsidian");Zg();Ir();Qi();It();It();ye();var sy=class{static convert(e,n={}){let{includeSystemMessage:r=!0,mergeUserContent:o=!0,debug:i=!1}=n,s=[],a=e.layers.find(f=>f.id==="L1_SYSTEM"),l=e.layers.find(f=>f.id==="L2_PREVIOUS"),c=e.layers.find(f=>f.id==="L3_TURN"),u=e.layers.find(f=>f.id==="L4_STRIP"),d=e.layers.find(f=>f.id==="L5_USER");if(r&&a&&a.text){let f=[a.text];l&&l.text&&(f.push(`
## Context Library
The following notes are available for reference:
`+l.text),i&&k("[LayerToMessagesConverter] Added L2 (cumulative context) to system")),s.push({role:"system",content:f.join(`
`)}),i&&k("[LayerToMessagesConverter] Added L1 (System) + L2 (Cumulative) as stable prefix")}if(u&&u.text&&i&&k("[LayerToMessagesConverter] L4 (Strip) found but skipped (using LangChain memory)"),o){let f=[];if(c&&c.segments.length>0&&l){let p=new Set(l.segments.map(g=>g.id)),m=[],h=[];for(let g of c.segments)p.has(g.id)?m.push(g.id):h.push(g);if(m.length>0||h.length>0){let g=[];m.length>0&&g.push(`Context attached to this message:
`+m.map(y=>`- ${y}`).join(`
`)+`
Find them in the Context Library in the system prompt above.`),h.length>0&&g.push(h.map(y=>y.content).join(`
`)),f.push(g.join(`
`)),i&&k(`[LayerToMessagesConverter] Added L3: ${m.length} references, ${h.length} new items`)}}else c&&c.text&&(f.push(c.text),i&&k("[LayerToMessagesConverter] Added L3 (all new context)"));f.length>0&&d&&d.text&&f.push(`---
[User query]:`),d&&d.text&&(f.push(d.text),i&&k("[LayerToMessagesConverter] Added L5 (user message)")),f.length>0&&s.push({role:"user",content:f.join(`
`)})}else c&&c.text&&s.push({role:"user",content:c.text}),d&&d.text&&s.push({role:"user",content:d.text});return i&&(k(`[LayerToMessagesConverter] Converted envelope to ${s.length} messages`),s.forEach((f,p)=>{let m=f.content.substring(0,100);k(` Message ${p+1} [${f.role}]: ${m}...`)})),s}static extractUserContent(e){let n=e.layers.find(i=>i.id==="L3_TURN"),r=e.layers.find(i=>i.id==="L5_USER"),o=[];return n&&n.text&&o.push(n.text),r&&r.text&&o.push(r.text),o.join(`
`)}static extractFullContext(e){let n=e.layers.find(s=>s.id==="L2_PREVIOUS"),r=e.layers.find(s=>s.id==="L3_TURN"),o=e.layers.find(s=>s.id==="L5_USER"),i=[];return n&&n.text&&i.push(n.text),r&&r.text&&i.push(r.text),o&&o.text&&i.push(o.text),i.join(`
`)}static extractSystemMessage(e){return e.layers.find(r=>r.id==="L1_SYSTEM")?.text||""}static getLayerHashes(e){return e.layerHashes}};ye();Se();qe();It();ye();qe();var $C=class{constructor(e){this.chainManager=e}async handleResponse(e,n,r,o,i,s,a,l){if((e||l?.wasTruncated)&&!(r.signal.aborted&&r.signal.reason==="new-chat")){let p=n.contextEnvelope?.layers.find(y=>y.id==="L5_USER")?.text||n.originalMessage||n.message,m=a||e||"[Response truncated - no content generated]";await this.chainManager.memoryManager.saveContext({input:p},{output:m});let g={message:e||(l?.wasTruncated?"_[The response was truncated before any content could be generated. Try increasing the max tokens limit.]_":""),sender:Sd,isVisible:!0,timestamp:ll(new Date),sources:s,responseMetadata:l};o(g),i("")}else r.signal.reason==="new-chat"&&i("");let u=this.chainManager.memoryManager.getMemory().chatHistory.messages;k(`Chat memory updated:
`,{turns:Array.isArray(u)?u.length:0});let d=2e3;try{let{parseToolCallMarkers:f}=await Promise.resolve().then(()=>(yye(),uqe)),m=f(e).segments.map(g=>g.type==="text"?g.content:"").join("").trim();m||(m=e||"");let h=m.length>d?m.slice(0,d)+"... (truncated)":m;k(`Final AI response (truncated):
`,h)}catch{let f=typeof e=="string"?e:String(e??""),p=f.length>d?f.slice(0,d)+"... (truncated)":f;k(`Final AI response (truncated):
`,p)}return e}async handleError(e,n){let r=Xt(e);z("Error during LLM invocation:",r);let o=e?.response?.data?.error||r,i=o?.code||r,s="";e?.message?.includes("Invalid license key")?s="Invalid Copilot Plus license key. Please check your license key in settings.":i==="model_not_found"?s="You do not have access to this model or the model does not exist, please check with your API provider.":s=`${i}`,z(o),n(this.enhancedErrorMsg(s,r,e))}enhancedErrorMsg(e,n,r){let o=e.search("Troubleshooting URL");return e=o!==-1?e.slice(0,o):e,this.isAuthenticationError(r,n)&&(e=`Something went wrong. Please check if you have set your API key.
Path: Settings > copilot plugin > Basic Tab > Set Keys.
Or check model config
Error Details: `+e),e}isAuthenticationError(e,n){let r=e?.response,o=r?.data?.error??e?.error,i=r?.status??o?.status,s=typeof i=="string"?Number.parseInt(i,10):i,a=typeof o=="object"&&o!==null?o:void 0,l=(typeof a?.message=="string"?a.message:n).toLowerCase(),c=typeof a?.code=="string"?a.code.toLowerCase():"",u=typeof a?.type=="string"?a.type.toLowerCase():"";return s===401?!0:["api key","apikey","unauthorized","authentication","invalid authentication"].some(f=>l.includes(f)||c.includes(f)||u.includes(f))}};ye();function wye(t){let e=[];for(let n of t){if(!n)continue;let r=n;if(typeof r._getType=="function"){let o=r._getType();o==="human"?e.push({role:"user",content:r.content}):o==="ai"&&e.push({role:"assistant",content:r.content})}else if(r.content!==void 0){let o=lUt(r);o&&e.push({role:o,content:r.content})}}return e}function lUt(t){return t.role==="human"||t.role==="user"||t.sender==="user"?"user":t.role==="ai"||t.role==="assistant"||t.sender==="AI"?"assistant":null}function cUt(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null&&n.type==="text").map(n=>n.text||"").join(" ")||"[Image content]":String(t||"")}function dqe(t){return t.map(e=>({role:e.role,content:cUt(e.content)}))}async function FC(t,e){let r=(await t.loadMemoryVariables({})).history||[],o=r.length?wye(r):[];for(let l of o)e.push({role:l.role,content:l.content});let i=0;for(let l of e)typeof l.content=="string"&&l.role==="system"&&(i+=l.content.length);let s=0;for(let l of o)typeof l.content=="string"&&(s+=l.content.length);let a=i+s;return a>2e6&&k("[Token Budget] Large payload detected (excluding user message):",{"L1+L2 (system)":`${Math.round(i/4e3)}k tokens`,"L4 (history)":`${Math.round(s/4e3)}k tokens (${o.length} msgs)`,total:`${Math.round(a/4e3)}k tokens`}),o}ye();var Vi=class t{constructor(){this.tools=new Map}static getInstance(){return t.instance||(t.instance=new t),t.instance}register(e){this.tools.set(e.metadata.id,e)}registerAll(e){e.forEach(n=>this.register(n))}getAllTools(){return Array.from(this.tools.values())}getEnabledTools(e,n){let r=[];for(let[o,i]of this.tools){let{metadata:s,tool:a}=i;if(s.isAlwaysEnabled){(!s.requiresVault||n)&&r.push(a);continue}e.has(o)&&(!s.requiresVault||n)&&r.push(a)}return r}getToolsByCategory(){let e=new Map;for(let n of this.tools.values()){let r=n.metadata.category;e.has(r)||e.set(r,[]),e.get(r).push(n)}return e}getConfigurableTools(){return Array.from(this.tools.values()).filter(e=>!e.metadata.isAlwaysEnabled)}getCopilotCommandMappings(){let e=new Map;for(let n of this.tools.values()){let r=n.metadata.copilotCommands;if(r)for(let o of r){let i=o.toLowerCase();e.has(i)||e.set(i,n)}}return e}getToolMetadata(e){return this.tools.get(e)?.metadata}getToolDefinition(e){return this.tools.get(e)}clear(){this.tools.clear()}};var iO=null;function uUt(t){let e=new WeakSet;return JSON.stringify(t,(n,r)=>{if(typeof r=="object"&&r!==null){if(e.has(r))return"[Circular]";e.add(r)}return typeof r=="bigint"?r.toString():r},2)}function dUt(t,e){let n=[];e&&(n.push(`msg:${e.messageId??"N/A"} | conv:${e.conversationId??"N/A"} | v${e.version}`),n.push(""));let r=Vi.getInstance(),o=new Set(r.getAllTools().map(u=>u.tool.name)),i=u=>{let d=[],f=/<(\w+)>([\s\S]*?)<\/\1>/g,p;for(;(p=f.exec(u))!==null;){let m=p[1],h=p[2];if(o.has(m)){let g=h.length>200?h.substring(0,200).trim()+"...[truncated]":h.trim();d.push({tool:m,preview:g})}}return d},s=u=>typeof u.content=="string"?u.content:Array.isArray(u.content)?u.content.filter(f=>f.type==="text").map(f=>f.text??"").join(`
`):"",a=Array.isArray(t)?t:[],l=0;for(let u=0;u<a.length;u++){let d=a[u],f=s(d);if(d.role==="system"){n.push("\u2501\u2501\u2501 SYSTEM MESSAGE \u2501\u2501\u2501"),n.push("");let p=e?.layers.find(h=>h.id==="L1_SYSTEM"),m=e?.layers.find(h=>h.id==="L2_PREVIOUS");if(p&&f.includes(p.text)){let h=p.hash.substring(0,8);n.push(`\u{1F512} L1_SYSTEM (${h}) [CACHEABLE]`);let g=f.indexOf(p.text)+p.text.length,y=p.text.length>300?p.text.substring(0,300)+"...[truncated]":p.text;if(n.push(y),n.push(""),m&&m.text){let x=m.hash.substring(0,8);n.push(`\u{1F512} L2_PREVIOUS (${x}) [CACHEABLE]`);let b=m.text.length>300?m.text.substring(0,300)+"...[truncated]":m.text;n.push(b),n.push("")}let w=f.substring(g),v=i(w);if(v.length>0){n.push("--- PER-TURN ADDITIONS (not cached) ---"),n.push("");for(let x of v)n.push(`\u{1F4E6} TOOL: ${x.tool} (turn-specific RAG)`),n.push(x.preview),n.push("")}}else{let h=i(f);if(h.length>0){let g=f.match(/<(\w+)>/);if(g){let y=f.substring(0,g.index);if(y.trim()){let w=y.length>300?y.substring(0,300)+"...[truncated]":y;n.push(w),n.push("")}}n.push("--- PER-TURN ADDITIONS (not cached) ---"),n.push("");for(let y of h)n.push(`\u{1F4E6} TOOL: ${y.tool}`),n.push(y.preview),n.push("")}else{let g=f.length>300?f.substring(0,300)+"...[truncated]":f;n.push(g),n.push("")}}}else(d.role==="user"||d.role==="assistant")&&u<a.length-1&&l++}l>0&&(n.push("\u2501\u2501\u2501 CHAT HISTORY (L4) \u2501\u2501\u2501"),n.push(""),n.push(`${l} message(s)`),n.push(""));let c=a[a.length-1];if(c&&c.role==="user"){n.push("\u2501\u2501\u2501 USER MESSAGE \u2501\u2501\u2501"),n.push("");let u=s(c),d=i(u);if(d.length>0){n.push("--- PER-TURN TOOL RESULTS ---"),n.push("");for(let m of d)n.push(`\u{1F4E6} TOOL: ${m.tool}`),n.push(m.preview),n.push("")}let f=e?.layers.find(m=>m.id==="L3_TURN"),p=e?.layers.find(m=>m.id==="L5_USER");if(f&&f.text&&u.includes(f.text)){let m=f.hash.substring(0,8);n.push(`\u26A1 L3_TURN (${m})`);let h=f.text.length>300?f.text.substring(0,300)+"...[truncated]":f.text;n.push(h),n.push("")}if(p&&p.text&&u.includes(p.text)){let m=p.hash.substring(0,8);n.push(`\u26A1 L5_USER (${m})`),n.push(p.text),n.push("")}}return n.join(`
`)}function UC(t){let{messages:e,modelName:n,contextEnvelope:r}=t;try{iO={timestamp:new Date().toISOString(),modelName:n,serializedMessages:uUt(e),messagesArray:e,contextEnvelope:r}}catch{iO={timestamp:new Date().toISOString(),modelName:n,serializedMessages:String(e),messagesArray:e,contextEnvelope:r}}}function sO(){iO=null}async function TG(){if(!iO)return;let{timestamp:t,modelName:e,serializedMessages:n,messagesArray:r,contextEnvelope:o}=iO,i=[`### Prompt \u2014 ${t}${e?` \u2014 ${e}`:""}`,"","**Actual Messages Sent to LLM:**","","```json",n,"```",""],s=dUt(r,o);i.push("**Layered Context Metadata:**"),i.push(""),i.push("```"),i.push(s),i.push("```"),i.push(""),jW(i),iO=null}function fqe(t){let e=t.response_metadata||{};return e.finish_reason==="length"?{wasTruncated:!0,message:"Response truncated due to token limit"}:e.stop_reason==="max_tokens"?{wasTruncated:!0,message:"Response truncated due to max_tokens limit"}:e.finishReason==="MAX_TOKENS"||e.finish_reason==="MAX_TOKENS"?{wasTruncated:!0,message:"Response truncated due to MAX_TOKENS limit"}:{wasTruncated:!1,message:null}}function pqe(t){let e=t.response_metadata||{};if(e.tokenUsage){let n=e.tokenUsage;return{inputTokens:n.promptTokens,outputTokens:n.completionTokens,totalTokens:n.totalTokens}}if(e.usage){let n=e.usage;return{inputTokens:n.input_tokens||n.inputTokens||n.inputTokenCount||n.prompt_tokens,outputTokens:n.output_tokens||n.outputTokens||n.outputTokenCount||n.completion_tokens,totalTokens:n.total_tokens||n.totalTokens||(n.input_tokens||n.inputTokenCount||0)+(n.output_tokens||n.outputTokenCount||0)}}return t.usage_metadata?{inputTokens:t.usage_metadata.input_tokens,outputTokens:t.usage_metadata.output_tokens,totalTokens:t.usage_metadata.total_tokens}:null}function fUt(t){return`<errorChunk>${t}</errorChunk>`}function IG(t,e){let n=fUt(t);return e?`${e}
${n}`:`
${n}`}Kr();ye();function vye(t,e,n){return new Wd({content:n,tool_call_id:t,name:e})}function PG(){let t=Date.now(),e=Math.random().toString(36).substring(2,11);return`call_${t}_${e}`}function mqe(t,e){let n=e.index??0,r=t.get(n)||{name:"",args:""};e.id&&(r.id=e.id);let o=e.name??e.functionCall?.name;o&&(r.name+=o),e.args&&(r.args+=e.args),t.set(n,r)}function EG(t){let e=[];for(let n of t.values()){if(!n.name)continue;let r={};if(n.args)try{r=JSON.parse(n.args)}catch{z(`[ToolCall] Failed to parse args for tool "${n.name}": ${n.args}`),r={}}e.push({id:n.id||PG(),name:n.name,args:r})}return e}function hqe(t,e){return new kn({content:t,tool_calls:e.map(n=>({id:n.id,name:n.name,args:n.args,type:"tool_call"}))})}ye();var pUt=["<|im_end|>","<|im_start|>","<|eot_id|>","<|start_header_id|>","<|end_header_id|>","<end_of_turn>","<start_of_turn>","<|end|>","<|assistant|>","<|user|>","<|system|>","</s>","[INST]","[/INST]","<|endoftext|>","<|end\u2581of\u2581sentence|>","<|END_OF_TURN_TOKEN|>","<|START_OF_TURN_TOKEN|>"],mUt=new RegExp(pUt.map(t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),"g");function xye(t){return t.replace(mUt,"")}var of=class{constructor(e,n=!1){this.updateCurrentAiMessage=e;this.excludeThinking=n;this.hasOpenThinkBlock=!1;this.fullResponse="";this.errorResponse="";this.wasTruncated=!1;this.tokenUsage=null;this.hasHandledTextLevelThinkTag=!1;this.excludedThinkBlockStart=-1;this.toolCallChunks=new Map;this.accumulatedToolCalls=[];k(`[ThinkBlockStreamer] Created with excludeThinking=${n}`)}handleTextLevelThinkTags(){if(this.excludeThinking){this.handleExcludedThinkTags();return}let e=this.fullResponse.includes("</think>"),n=this.fullResponse.includes("<think>");e&&!n&&!this.hasHandledTextLevelThinkTag&&(this.hasHandledTextLevelThinkTag=!0,ee("Detected </think> closing tag without opening <think> tag. This may indicate a misconfigured chat template in LM Studio. Adding opening tag."),this.fullResponse="<think>"+this.fullResponse)}handleExcludedThinkTags(){if(this.excludedThinkBlockStart>=0){let r=this.fullResponse.indexOf("</think>",this.excludedThinkBlockStart);if(r!==-1){let o=this.fullResponse.substring(0,this.excludedThinkBlockStart),i=this.fullResponse.substring(r+8);this.fullResponse=(o+i).trimStart(),this.excludedThinkBlockStart=-1}else this.fullResponse=this.fullResponse.substring(0,this.excludedThinkBlockStart);return}let e=this.fullResponse.indexOf("<think>");if(e!==-1){this.excludedThinkBlockStart=e;let r=this.fullResponse.indexOf("</think>",e);if(r!==-1){let o=this.fullResponse.substring(0,e),i=this.fullResponse.substring(r+8);this.fullResponse=(o+i).trimStart(),this.excludedThinkBlockStart=-1}else this.fullResponse=this.fullResponse.substring(0,e);return}let n=this.fullResponse.indexOf("</think>");n!==-1&&(this.fullResponse=this.fullResponse.substring(n+8).trimStart())}handleClaudeChunk(e){let n="",r=!1;for(let o of e)switch(o.type){case"text":n+=o.text;break;case"thinking":if(r=!0,this.excludeThinking)break;this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),o.thinking!==void 0&&(this.fullResponse+=o.thinking),this.updateCurrentAiMessage(this.fullResponse);break}return n&&this.hasOpenThinkBlock&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),n&&(this.fullResponse+=xye(n)),r}handleDeepseekChunk(e){return typeof e.content=="string"&&(this.fullResponse+=xye(e.content)),e.additional_kwargs?.reasoning_content?(this.excludeThinking||(this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),e.additional_kwargs.reasoning_content!==void 0&&(this.fullResponse+=e.additional_kwargs.reasoning_content)),!0):!1}handleOpenRouterChunk(e){return e.additional_kwargs?.delta?.reasoning?(this.excludeThinking||(this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),this.fullResponse+=e.additional_kwargs.delta.reasoning),!0):(typeof e.content=="string"&&e.content&&this.hasOpenThinkBlock&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),typeof e.content=="string"&&e.content&&(this.fullResponse+=e.content),!1)}handleToolCallChunks(e){let n=e.tool_call_chunks;if(!(!n||!Array.isArray(n)))for(let r of n){let o=r.index??0,i=this.toolCallChunks.get(o)||{name:"",args:""};r.id&&(i.id=r.id),r.name&&(i.name+=r.name),r.args&&(i.args+=r.args),this.toolCallChunks.set(o,i)}}processChunk(e){fqe(e).wasTruncated&&(this.wasTruncated=!0);let r=pqe(e);r&&(this.tokenUsage=r),this.handleToolCallChunks(e);let o=Array.isArray(e.content)||e.additional_kwargs?.delta?.reasoning||e.additional_kwargs?.reasoning_details&&Array.isArray(e.additional_kwargs.reasoning_details)&&e.additional_kwargs.reasoning_details.length>0||e.additional_kwargs?.reasoning_content;this.hasOpenThinkBlock&&!o&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),Array.isArray(e.content)?this.handleClaudeChunk(e.content):e.additional_kwargs?.reasoning_content?this.handleDeepseekChunk(e):o?this.handleOpenRouterChunk(e):this.handleDeepseekChunk(e),this.handleTextLevelThinkTags(),this.updateCurrentAiMessage(this.fullResponse)}processErrorChunk(e){this.errorResponse=IG(e)}getToolCalls(){return this.accumulatedToolCalls.length>0?this.accumulatedToolCalls:EG(this.toolCallChunks)}hasToolCalls(){return this.toolCallChunks.size>0||this.accumulatedToolCalls.length>0}setToolCalls(e){this.accumulatedToolCalls=e}buildAIMessage(){let e=this.getToolCalls();return hqe(this.fullResponse,e)}close(){return this.hasOpenThinkBlock&&(this.fullResponse+="</think>"),this.handleTextLevelThinkTags(),this.errorResponse&&(this.fullResponse+=this.errorResponse),this.updateCurrentAiMessage(this.fullResponse),{content:this.fullResponse,wasTruncated:this.wasTruncated,tokenUsage:this.tokenUsage}}};Ir();var hB=class extends $C{async constructMessages(e){if(!e.contextEnvelope)throw new Error("[LLMChainRunner] Context envelope is required but not available. Cannot proceed with LLM chain.");k("[LLMChainRunner] Using envelope-based context");let n=sy.convert(e.contextEnvelope,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),r=[],o=n.find(a=>a.role==="system");o&&r.push(o);let i=this.chainManager.memoryManager.getMemory();await FC(i,r);let s=n.find(a=>a.role==="user");if(s)if(e.content&&Array.isArray(e.content)){let a=e.content.map(l=>l.type==="text"?{...l,text:s.content}:l);r.push({role:"user",content:a})}else r.push(s);return r}async run(e,n,r,o,i){let s=q(),a=Iu(),l=!1;try{l=!$f(a,s.activeModels).capabilities?.includes("reasoning")}catch(f){k("Could not determine model capabilities, defaulting to include thinking blocks",f)}let c=new of(r,l);try{let f=await this.constructMessages(e),m=this.chainManager.chatModelManager.getChatModel()?.modelName;UC({messages:f,modelName:m,contextEnvelope:e.contextEnvelope}),k(`Final Request to AI:
`,f);let h=await Nc(()=>this.chainManager.chatModelManager.getChatModel().stream(f,{signal:n.signal}));for await(let g of h){if(n.signal.aborted){k("Stream iteration aborted",{reason:n.signal.reason});break}c.processChunk(g)}}catch(f){(f instanceof Error?f.name:"")==="AbortError"||n.signal.aborted?k("Stream aborted by user",{reason:n.signal.reason}):await this.handleError(f,c.processErrorChunk.bind(c))}let u=c.close(),d={wasTruncated:u.wasTruncated,tokenUsage:u.tokenUsage??void 0};return n.signal.aborted&&n.signal.reason==="new-chat"?(r(""),""):(await this.handleResponse(u.content,e,n,o,r,void 0,void 0,d),u.content)}};It();qe();async function AG(t,e){let n=`Given the following conversation and a follow up question,
summarize the conversation as context and keep the follow up question unchanged, in its original language.
If the follow up question is unrelated to its preceding messages, return this follow up question directly.
If it is related, then combine the summary and the follow up question to construct a standalone question.
Make sure to keep any [[]] wrapped note titles in the question unchanged.
If there's nothing in the chat history, just return the follow up question.
Chat History:
{chat_history}
Follow Up Input: {question}
Standalone question:`,r=e.map(({role:o,content:i})=>`${o}: ${i}`).join(`
`);return await Nc(async()=>{let o=await Sl.instance.getCurrentChainManager().chatModelManager.getChatModelWithTemperature(0),i="",s=await o.stream([{role:"user",content:n.replace("{chat_history}",r).replace("{question}",t)}]);for await(let l of s)i+=Kx(l.content);let a=jte(i);return BAe(a)})}ye();ye();ns();yp();Se();ye();qe();iv();lO();var kG=class extends ay{constructor(n,r,o){super();this.lc_namespace=["self_host_retriever"];this.app=n,this.backend=r,this.options={...o,minSimilarityScore:o.minSimilarityScore??.01,salientTerms:o.salientTerms??[],returnAll:o.returnAll??!1}}async getRelevantDocuments(n,r){try{if(!await this.backend.isAvailable())return ee("SelfHostRetriever: Backend is not available"),[];let s=Df(n,this.app.vault).map(f=>f.basename),a=[...new Set([...this.options.salientTerms||[],...s])],l=this.buildFilter(),c=this.options.returnAll?100:this.options.maxK,u=await this.backend.search(n,{limit:c,minScore:this.options.minSimilarityScore,filter:l});k(`SelfHostRetriever: Found ${u.length} results for query "${n.substring(0,50)}..."`);let d=this.convertToDocuments(u);return a.length>0?this.boostBySalientTerms(d,a):d}catch(o){return ee(`SelfHostRetriever: Search failed: ${o}`),[]}}buildFilter(){let n={};return this.options.timeRange&&(n.mtime={gte:this.options.timeRange.startTime,lte:this.options.timeRange.endTime}),this.options.tagTerms&&this.options.tagTerms.length>0&&(n.tags={containsAny:this.options.tagTerms}),Object.keys(n).length>0?n:void 0}convertToDocuments(n){return n.map(r=>new fi({pageContent:r.content,metadata:{...r.metadata,score:r.score,rerank_score:r.score,id:r.id,source:"self_host"}}))}boostBySalientTerms(n,r){return n.map(s=>{let a=s.pageContent.toLowerCase(),l=(s.metadata?.title||"").toLowerCase();if(r.some(u=>a.includes(u.toLowerCase())||l.includes(u.toLowerCase()))){let u=(s.metadata?.score||0)*1.1;return new fi({pageContent:s.pageContent,metadata:{...s.metadata,score:u,rerank_score:u,salientBoost:!0}})}return s}).sort((s,a)=>(a.metadata?.score||0)-(s.metadata?.score||0))}getBackend(){return this.backend}};iv();lO();ye();RN();yp();Se();N0();var WG=class extends ay{constructor(n,r){super();this.app=n;this.options=r;this.lc_namespace=["miyo_semantic_retriever"];this.client=new wp,this.returnAll=!!r.returnAll,this.maxK=Math.max(1,r.maxK),this.minSimilarityScore=r.minSimilarityScore??.1}async getRelevantDocuments(n,r){let o=await this.searchMiyo(n),i=this.deduplicateResults(o);return q().debug&&this.logDebugInfo(n,o,i),i}async searchMiyo(n){try{let r=await this.client.resolveBaseUrl(Jm(q())),o=this.returnAll?ni:this.maxK,i=this.buildSearchFilters();q().debug&&k("MiyoSemanticRetriever: search params:",{baseUrl:r,limit:o,maxK:this.maxK,minSimilarityScore:this.minSimilarityScore,returnAll:this.returnAll,filters:i});let s=q().miyoSearchAll?void 0:Jg(this.app),l=(await this.client.search(r,s,n,o,i)).results||[],c=l.filter(u=>this.isScoreAboveThreshold(u));return q().debug&&k(`MiyoSemanticRetriever: received ${l.length} results, ${c.length} after threshold`),c.map(u=>this.toDocument(u))}catch(r){return ee(`MiyoSemanticRetriever: search failed: ${r}`),[]}}buildSearchFilters(){if(!this.options.timeRange)return;let{startTime:n,endTime:r}=this.options.timeRange;return[{field:"mtime",gte:n,lte:r}]}toDocument(n){let r=i0(this.app,n.path),o=n.metadata??{},i=o.chunkId||(n.chunk_index!==void 0?`${r}#${n.chunk_index}`:void 0),s=typeof n.score=="number"?n.score.toFixed(2):"?";return new fi({pageContent:n.chunk_text??"",metadata:{...o,score:n.score,explanation:`miyo ${s}`,path:r,mtime:n.mtime,ctime:n.ctime,title:n.title??"",id:n.id,embeddingModel:n.embedding_model,tags:n.tags??[],extension:n.extension,created_at:n.created_at,nchars:n.nchars,chunkId:i}})}isScoreAboveThreshold(n){let r=n.score;return typeof r!="number"||Number.isNaN(r)?!0:r>=this.minSimilarityScore}deduplicateResults(n){let r=new Map,o=i=>{let s=this.getDocumentKey(i);r.has(s)||r.set(s,i)};return n.forEach(o),q().debug&&r.size!==n.length&&k(`MiyoSemanticRetriever: deduplicated semantic results from ${n.length} to ${r.size}`),Array.from(r.values())}
1. START with [^1] and increment sequentially ([^1], [^2], [^3], etc.) with NO gaps
2. BE SELECTIVE: ONLY cite when introducing NEW factual claims, specific data, or direct quotes from sources
3. IMPORTANT: Do NOT cite every sentence or bullet point. This creates clutter and poor readability.
4. DO NOT cite for:
- General knowledge or common facts
- Your own analysis or synthesis
- Transitional or concluding statements
- Every single sentence (AVOID CITATION CLUTTER - aim for 1-3 citations per paragraph maximum)
5. Citations are for SOURCE ATTRIBUTION, not for proving every statement
6. GOOD: One citation per key concept. BAD: Citation after every sentence.
7. Place citations immediately after the specific claim: "The study found X [^1]" not "The study found X. [^1]"
8. Do not reuse any bracketed numbers that appear inside the source content itself
9. If multiple source chunks come from the same document, cite each relevant chunk separately (e.g., [^1] and [^2] can both be from the same document title)
10. End with '#### Sources' section containing: [^n]: [[Title]] (one per line, matching citation order)`,mjt=`WEB CITATION RULES:
1. START with [^1] and increment sequentially ([^1], [^2], [^3], etc.) with NO gaps
2. Cite ONLY when introducing new factual claims, statistics, or direct quotes from the search results
3. After every cited claim, place the corresponding footnote immediately after the sentence ("The study found X [^1]")
4. End with '#### Sources' and provide definitions EXACTLY in this format: [^n]: [Short Title](URL)
IMPORTANT: Each source definition must follow this exact pattern:
- Start with [^n]: (where n is the citation number)
- Follow with [Title](URL) where Title is SHORT (2-5 words) and wrapped in square brackets
- Example: [^1]: [Paul Graham Essay](https://paulgraham.com/wealth.html)
- DO NOT write long descriptions - keep titles concise`;function $9e(t,e=!0){return e?`
<guidance>
${D9e}
IMAGE INCLUSION:
When the retrieved documents contain relevant images (in formats like ![alt](image.png) or ![[image.png]]), include them in your response at appropriate locations using their exact original markdown format from the source.
Source Catalog (for reference only):
${t.join(`
`)}
</guidance>`:`
<guidance>
IMAGE INCLUSION:
When the retrieved documents contain relevant images (in formats like ![alt](image.png) or ![[image.png]]), include them in your response at appropriate locations using their exact original markdown format from the source.
Source Catalog (for reference only):
${t.join(`
`)}
</guidance>`}function F9e(t,e=!0){return e?`
${D9e}
Source Catalog (for reference only):
${t}`:""}function U9e(t){return t?"REMINDER: End your response with an '#### Sources' section listing each cited source as [^n]: [[Title]], numbered sequentially from [^1].":null}var hjt=20;function z8(t,e,n=!0){if(!n||!e?.length||!t)return t||"";if(gjt(t))return t;let r=e.slice(0,hjt).map((o,i)=>{let s=(o.title||o.path||"Untitled").replace(/^\[\[|\]\]$/g,"");return`[^${i+1}]: [[${s}]]`}).join(`
`);return`${t}
#### Sources:
${r}`}function rR(t){if(!t)return"";let e=t.replace(/\[\^\d+\]/g,"");return e=e.replace(/\[(\d+(?:\s*,\s*\d+)*)\](?!\()/g,""),e=e.replace(/^\s*\[\^\d+\]:.*$/gm,""),e}function gjt(t){let e=t||"",n=/(^|\n)\s*#{1,6}\s*Sources\b/i.test(e),r=/(^|\n)\s*Sources\s*(?:[:-]\s*)?(\n|$)/i.test(e),o=/<summary[^>]*>\s*Sources\s*<\/summary>/i.test(e),i=/(^|\n)\s*\[\^\d+\]:\s*/.test(e);return n||r||o||i}function B9e(t){let e=t||"";return/\[\^\d+\]/.test(e)}function z9e(t=!0){return t?`
${mjt}`:""}function yjt(t){let e=/([\s\S]*?)\n+(?:####\s*)?Sources\s*:?\s*\n+([\s\S]*)$/i,n=t.match(e);if(n)return{mainContent:n[1],sourcesBlock:(n[2]||"").trim()};let r=t.match(/([\s\S]*?)\n+---+\s*\n+([\s\S]*)$/);if(r){let i=(r[2]||"").trim();if(i.length>0&&i.split(`
`).every(a=>!a.trim()||/^\[\^\d+\]:/.test(a.trim())))return{mainContent:r[1],sourcesBlock:i}}let o=t.match(/([\s\S]*?)\n{2,}(\[\^\d+\]:[\s\S]*)$/);if(o){let i=(o[2]||"").trim();if(i.split(`
`).every(a=>!a.trim()||/^\[\^\d+\]:/.test(a.trim())))return{mainContent:o[1],sourcesBlock:i}}return null}function wjt(t){return t.includes(`
`)||(t=t.replace(/\s*\[(\d+)\]\s*/g,`
[$1] `),t=t.replace(/\s+(\d+)\.\s/g,`
$1. `),t=t.trim()),t}function vjt(t){return t.split(`
`).map(e=>e.trim()).filter(e=>/^\[\^\d+\]:/.test(e))}function xjt(t,e){let n=new Map,r=new Set,o=[],i=/\[\^(\d+)\]/g,s;for(;(s=i.exec(t))!==null;){let a=parseInt(s[1],10);r.has(a)||(r.add(a),o.push(a))}if(o.length>0)o.forEach((a,l)=>n.set(a,l+1));else{let a=1;for(let l of e){let c=l.match(/^\[\^(\d+)\]:/);if(c){let u=parseInt(c[1],10);n.has(u)||n.set(u,a++)}}}return n}function bjt(t,e){let n=t,r;do r=!1,n=n.replace(/\[\^(\d+)\]/g,(o,i)=>{let s=parseInt(i,10),l=`[${e.get(s)??s}]`;return l!==o&&(r=!0),l}),n=n.replace(/\[\^(\d+(?:\s*,\s*\^?\d+)*)\]/g,(o,i)=>{let a=`[${i.split(",").map(l=>{let c=l.trim().replace(/^\^/,""),u=parseInt(c,10);return e.get(u)??u}).sort((l,c)=>l-c).map(l=>l.toString()).join(", ")}]`;return a!==o&&(r=!0),a});while(r);return n=n.replace(/\[(\d+)\]\./g,"[$1]"),n}function Cjt(t,e){let n=[];return t.split(`
`).forEach(r=>{let o=r.match(/^\[\^(\d+)\]:\s*(.*)$/);if(!o)return;let i=parseInt(o[1],10),s=e.get(i)??i,a=o[2].match(/\[([^\]]+)\]\(([^)]+)\)/),l=o[2].match(/\[\[(.*?)\]\]/),c;if(a)c=`<a href="${a[2]}">${a[1]}</a>`;else if(l)c=`[[${l[1]}]]`;else{let u=o[2].match(/^(.*?)\]\s*\(([^)]+)\)\s*$/);if(u){let d=u[1].trim();c=`<a href="${u[2].trim()}">${d}</a>`}else c=o[2].replace(/\s*\([^)]*\)\s*$/,"")}n[s-1]=c}),n}function _jt(t){let e=[],n=new Set,r=new Map;return t.forEach((o,i)=>{if(!o)return;let s=o.match(/\[\[(.*?)\]\]/),a=s?s[1].toLowerCase():o.toLowerCase();if(!n.has(a))n.add(a),e.push(o),r.set(i+1,e.length);else{let l=e.findIndex(c=>{let u=c.match(/\[\[(.*?)\]\]/);return(u?u[1].toLowerCase():c.toLowerCase())===a});l>=0&&r.set(i+1,l+1)}}),{uniqueItems:e,consolidationMap:r}}function Sjt(t,e){return e.size===0?t:t.replace(/\[(\d+(?:\s*,\s*\d+)*)\]/g,(n,r)=>{let o=r.split(/\s*,\s*/),i=new Set,s=[];for(let a of o){let l=e.get(parseInt(a,10))||parseInt(a,10);i.has(l)||(i.add(l),s.push(l))}return`[${s.join(", ")}]`})}function Tjt(t){let e=t,n;do n=e,e=e.replace(/\[(\d+(?:\s*,\s*\d+)*)\](?:\s*(?:and|,)\s*|\s*)\[(\d+(?:\s*,\s*\d+)*)\]/g,(r,o,i)=>{let s=new Set(o.split(/\s*,\s*/).map(l=>l.trim()));return i.split(/\s*,\s*/).map(l=>l.trim()).every(l=>s.has(l))?`[${[...s].join(", ")}]`:r});while(e!==n);return e}function Ijt(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Pjt(t){return t!=null}function Ejt(t){let e=t.split(`
`),n=[];return e.forEach(r=>{let o=r.trim();if(!o)return;let i=o.replace(/^<li>/i,"").replace(/<\/li>$/i,"").replace(/^[-*]\s*/,"").trim();if(!i)return;let s=i.match(/\[([^\]]+)\]\(([^)]+)\)/),a=i.match(/\[\[(.*?)\]\]/),l;s?l=`<a href="${s[2]}">${s[1]}</a>`:a?l=`[[${a[1]}]]`:l=Ijt(i),n.push({index:n.length+1,html:l})}),n}function L9e(t,e){let n=e.filter(o=>o.html.trim().length>0);if(n.length===0)return t;let r=n.map(({index:o,html:i})=>`<li class="copilot-sources__item"><span class="copilot-sources__index">[${o}]</span><span class="copilot-sources__text">${i}</span></li>`).join(`
`);return`${t}
<br/>
<details class="copilot-sources"><summary class="copilot-sources__summary">Sources</summary>
<ul class="copilot-sources__list">
${r}
</ul>
</details>`}function Ajt(t){return t.replace(/\[(\d+(?:\s*,\s*\d+)*)\](?!\()/g,'<span class="copilot-citation-ref">[$1]</span>')}function j9e(t,e=!0){if(!e)return t;let n=yjt(t);if(!n)return t;let{mainContent:r,sourcesBlock:o}=n;o=wjt(o);let i=vjt(o);if(i.length===0){let d=Ejt(o);return L9e(r,d)}let s=xjt(r,i);r=bjt(r,s);let a=Cjt(o,s),{uniqueItems:l,consolidationMap:c}=_jt(a);c.size>0&&(r=Sjt(r,c),r=Tjt(r),a=l),r=Ajt(r);let u=a.map((d,f)=>d?{index:f+1,html:d}:null).filter(Pjt);return L9e(r,u)}function j8(t){return t.map(e=>{let n=e.title||e.path||"Untitled",r=e.path||n;return`- [[${n}]] (${r})`})}Ir();var pz=class extends $C{async run(e,n,r,o,i){let s=q(),a=Iu(),l=!1;try{l=!$f(a,s.activeModels).capabilities?.includes("reasoning")}catch(p){k("Could not determine model capabilities, defaulting to include thinking blocks",p)}let c=new of(r,l);try{let p=e.contextEnvelope;if(!p)throw new Error("[VaultQA] Context envelope is required but not available. Cannot proceed with VaultQA chain.");let h=p.layers.find(K=>K.id==="L5_USER")?.text||e.message,g=this.extractTagTerms(h);k("[VaultQA] Extracted tags before condensing:",g);let y=this.chainManager.memoryManager.getMemory(),w=await y.loadMemoryVariables({}),v=BW(w),x=h;v.length>0&&(k("[VaultQA] Condensing query with chat history for better retrieval"),x=await AG(h,v),k("[VaultQA] Standalone question:",x));let b=q(),_=g.length>0,S=await new XC(app,{salientTerms:_?[...g]:[],maxK:b.maxSourceChunks,returnAll:_}).getRelevantDocuments(x),P=lh.isMiyoActive(),A=await lh.createRetriever(app,{minSimilarityScore:.01,maxK:b.maxSourceChunks,salientTerms:_?[...g]:[],tagTerms:g,returnAll:_},P?{enableMiyo:!1,enableSemanticSearchV3:!1}:{}),O=A.retriever;k(`VaultQA: Using ${A.type} retriever - ${A.reason}`);let D=await O.getRelevantDocuments(x),{filterResults:$,searchResults:B}=nR(S,D),W=[...$,...B],F=W.length>b.maxSourceChunks,Z=W.slice(0,b.maxSourceChunks);this.chainManager.storeRetrieverDocuments(Z);let V=Z.map(K=>{let Y=K.metadata?.title||"Untitled",re=K.metadata?.path||Y;return`<${nee}>
<title>${Y}</title>
<path>${re}</path>
<content>
${rR(K.pageContent??"")}
</content>
</${nee}>`}).join(`
`),H=[],te=this.chainManager.chatModelManager.getChatModel(),fe=Z.slice(0,Math.max(5,Math.min(20,Z.length))).map(K=>({title:K.metadata?.title||K.metadata?.path||"Untitled",path:K.metadata?.path||K.metadata?.title||""})),me=j8(fe).join(`
`),j=F?`
IMPORTANT: The retrieval limit of ${b.maxSourceChunks} documents was reached. ${W.length-b.maxSourceChunks} additional matching documents were omitted. Inform the user: "Note: The retrieval cap was reached \u2014 some matching documents were not included. Upgrade to Copilot Plus for more complete answers."`:"",G=`
Answer the question based only on the following context:
`+V+F9e(me,b.enableInlineCitations)+j;k("[VaultQA] Using envelope-based context construction with LayerToMessagesConverter");let J=sy.convert(p,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),M=J.find(K=>K.role==="system");M&&H.push({role:e$(te),content:M.content}),await FC(y,H);let E=J.find(K=>K.role==="user");if(E){let K=G+`
`+E.content;if(e.content&&Array.isArray(e.content)){let Y=e.content.map(re=>re.type==="text"?{...re,text:K}:{...re});H.push({role:"user",content:Y})}else H.push({role:"user",content:K})}let R=te?.modelName;UC({messages:H,modelName:R,contextEnvelope:e.contextEnvelope}),k(`Final Request to AI:
`,H);let L=await Nc(()=>this.chainManager.chatModelManager.getChatModel().stream(H,{signal:n.signal}));for await(let K of L){if(n.signal.aborted){k("VaultQA stream iteration aborted",{reason:n.signal.reason});break}c.processChunk(K)}}catch(p){p.name==="AbortError"||n.signal.aborted?k("VaultQA stream aborted by user",{reason:n.signal.reason}):await this.handleError(p,c.processErrorChunk.bind(c))}let u=c.close(),d={wasTruncated:u.wasTruncated,tokenUsage:u.tokenUsage??void 0};if(n.signal.aborted&&n.signal.reason==="new-chat")return r(""),"";let f=this.addSourcestoResponse(u.content);return await this.handleResponse(f,e,n,o,r,void 0,void 0,d),f}addSourcestoResponse(e){let n=q();if(!B9e(e))return e;let r=this.chainManager.getRetrievedDocuments(),o=RAe(r).map(i=>({title:i}));return z8(e,o,n.enableInlineCitations)}extractTagTerms(e){return uO(e)}};var oR=["@vault","@websearch","@composer","@memory"];It();ye();ns();Se();Se();It();ye();Id();Id();Se();var cf=Jh(),QC=Oo([]),qve=Oo(""),V9e=Oo(!1);function V8(){return Wl(QC,{store:cf})}function W9e(){return Hy(qve,{store:cf})}function iR(){return cf.get(QC)}function nP(){return cf.get(qve)}function W8(t){cf.set(QC,t)}function rP(t){let e=cf.get(QC),n=e.findIndex(r=>r.title===t.title);if(n!==-1){let r=[...e];r[n]=t,cf.set(QC,r)}else cf.set(QC,[...e,t])}function sR(t){let e=cf.get(QC);cf.set(QC,e.filter(n=>n.title!==t))}function e_(t){cf.set(qve,t)}function mz(t){cf.set(V9e,t)}function hz(){return cf.get(V9e)}var Gve=new Set;function t_(t){Gve.add(t)}function n_(t){Gve.delete(t)}function vv(t){return Gve.has(t)}function H8(){return q().defaultSystemPromptTitle}function H9e(){let t=iR(),e=nP();if(e){let r=t.find(o=>o.title===e);if(r)return r.content}let n=H8();if(n){let r=t.find(o=>o.title===n);if(r)return r.content}return""}function K9e(){let t=H8();e_(t)}function Yve(){mz(!1),e_("")}function K8(){return H9e()||q()?.userSystemPrompt||""}function r_(){let t=K8();if(hz())return t;let n=pPe;return t?`${n}
<user_custom_instructions>
${t}
</user_custom_instructions>`:n}async function xv(t){let e=r_();if(!t)return k("No UserMemoryManager provided to getSystemPromptWithMemory"),e;let n=await t.getUserMemoryPrompt();return n?`${n}
${e}`:e}var aR=require("obsidian");Kt();ye();Se();ws();function ch(){}ch.prototype={diff:function(e,n){var r,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=o.callback;typeof o=="function"&&(i=o,o={});var s=this;function a(x){return x=s.postProcess(x,o),i?(setTimeout(function(){i(x)},0),!0):x}e=this.castInput(e,o),n=this.castInput(n,o),e=this.removeEmpty(this.tokenize(e,o)),n=this.removeEmpty(this.tokenize(n,o));var l=n.length,c=e.length,u=1,d=l+c;o.maxEditLength!=null&&(d=Math.min(d,o.maxEditLength));var f=(r=o.timeout)!==null&&r!==void 0?r:1/0,p=Date.now()+f,m=[{oldPos:-1,lastComponent:void 0}],h=this.extractCommon(m[0],n,e,0,o);if(m[0].oldPos+1>=c&&h+1>=l)return a(q9e(s,m[0].lastComponent,n,e,s.useLongestToken));var g=-1/0,y=1/0;function w(){for(var x=Math.max(g,-u);x<=Math.min(y,u);x+=2){var b=void 0,_=m[x-1],T=m[x+1];_&&(m[x-1]=void 0);var S=!1;if(T){var P=T.oldPos-x;S=T&&0<=P&&P<l}var A=_&&_.oldPos+1<c;if(!S&&!A){m[x]=void 0;continue}if(!A||S&&_.oldPos<T.oldPos?b=s.addToPath(T,!0,!1,0,o):b=s.addToPath(_,!1,!0,1,o),h=s.extractCommon(b,n,e,x,o),b.oldPos+1>=c&&h+1>=l)return a(q9e(s,b.lastComponent,n,e,s.useLongestToken));m[x]=b,b.oldPos+1>=c&&(y=Math.min(y,x-1)),h+1>=l&&(g=Math.max(g,x+1))}u++}if(i)(function x(){setTimeout(function(){if(u>d||Date.now()>p)return i();w()||x()},0)})();else for(;u<=d&&Date.now()<=p;){var v=w();if(v)return v}},addToPath:function(e,n,r,o,i){var s=e.lastComponent;return s&&!i.oneChangePerToken&&s.added===n&&s.removed===r?{oldPos:e.oldPos+o,lastComponent:{count:s.count+1,added:n,removed:r,previousComponent:s.previousComponent}}:{oldPos:e.oldPos+o,lastComponent:{count:1,added:n,removed:r,previousComponent:s}}},extractCommon:function(e,n,r,o,i){for(var s=n.length,a=r.length,l=e.oldPos,c=l-o,u=0;c+1<s&&l+1<a&&this.equals(r[l+1],n[c+1],i);)c++,l++,u++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return u&&!i.oneChangePerToken&&(e.lastComponent={count:u,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=l,c},equals:function(e,n,r){return r.comparator?r.comparator(e,n):e===n||r.ignoreCase&&e.toLowerCase()===n.toLowerCase()},removeEmpty:function(e){for(var n=[],r=0;r<e.length;r++)e[r]&&n.push(e[r]);return n},castInput:function(e){return e},tokenize:function(e){return Array.from(e)},join:function(e){return e.join("")},postProcess:function(e){return e}};function q9e(t,e,n,r,o){for(var i=[],s;e;)i.push(e),s=e.previousComponent,delete e.previousComponent,e=s;i.reverse();for(var a=0,l=i.length,c=0,u=0;a<l;a++){var d=i[a];if(d.removed)d.value=t.join(r.slice(u,u+d.count)),u+=d.count;else{if(!d.added&&o){var f=n.slice(c,c+d.count);f=f.map(function(p,m){var h=r[u+m];return h.length>p.length?h:p}),d.value=t.join(f)}else d.value=t.join(n.slice(c,c+d.count));c+=d.count,d.added||(u+=d.count)}}return i}var Iur=new ch;function G9e(t,e){var n;for(n=0;n<t.length&&n<e.length;n++)if(t[n]!=e[n])return t.slice(0,n);return t.slice(0,n)}function Y9e(t,e){var n;if(!t||!e||t[t.length-1]!=e[e.length-1])return"";for(n=0;n<t.length&&n<e.length;n++)if(t[t.length-(n+1)]!=e[e.length-(n+1)])return t.slice(-n);return t.slice(-n)}function Zve(t,e,n){if(t.slice(0,e.length)!=e)throw Error("string ".concat(JSON.stringify(t)," doesn't start with prefix ").concat(JSON.stringify(e),"; this is a bug"));return n+t.slice(e.length)}function Jve(t,e,n){if(!e)return t+n;if(t.slice(-e.length)!=e)throw Error("string ".concat(JSON.stringify(t)," doesn't end with suffix ").concat(JSON.stringify(e),"; this is a bug"));return t.slice(0,-e.length)+n}function gz(t,e){return Zve(t,e,"")}function q8(t,e){return Jve(t,e,"")}function Z9e(t,e){return e.slice(0,kjt(t,e))}function kjt(t,e){var n=0;t.length>e.length&&(n=t.length-e.length);var r=e.length;t.length<e.length&&(r=t.length);var o=Array(r),i=0;o[0]=0;for(var s=1;s<r;s++){for(e[s]==e[i]?o[s]=o[i]:o[s]=i;i>0&&e[s]!=e[i];)i=o[i];e[s]==e[i]&&i++}i=0;for(var a=n;a<t.length;a++){for(;i>0&&t[a]!=e[i];)i=o[i];t[a]==e[i]&&i++}return i}var G8="a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-
`));var n=[],r=t.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(var o=0;o<r.length;o++){var i=r[o];o%2&&!e.newlineIsToken?n[n.length-1]+=i:n.push(i)}return n};J8.equals=function(t,e,n){return n.ignoreWhitespace?((!n.newlineIsToken||!t.includes(`
`))&&(t=t.trim()),(!n.newlineIsToken||!e.includes(`
`))&&(e=e.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(t.endsWith(`
`)&&(t=t.slice(0,-1)),e.endsWith(`
`)&&(e=e.slice(0,-1))),ch.prototype.equals.call(this,t,e,n)};function X9e(t,e,n){var r=Ojt(n,{ignoreWhitespace:!0});return J8.diff(t,e,r)}var Rjt=new ch;Rjt.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var Ljt=new ch;Ljt.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function Xve(t){"@babel/helpers - typeof";return Xve=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Xve(t)}var yz=new ch;yz.useLongestToken=!0;yz.tokenize=J8.tokenize;yz.castInput=function(t,e){var n=e.undefinedReplacement,r=e.stringifyReplacer,o=r===void 0?function(i,s){return typeof s>"u"?n:s}:r;return typeof t=="string"?t:JSON.stringify(Qve(t,null,null,o),o," ")};yz.equals=function(t,e,n){return ch.prototype.equals.call(yz,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"),n)};function Qve(t,e,n,r,o){e=e||[],n=n||[],r&&(t=r(o,t));var i;for(i=0;i<e.length;i+=1)if(e[i]===t)return n[i];var s;if(Object.prototype.toString.call(t)==="[object Array]"){for(e.push(t),s=new Array(t.length),n.push(s),i=0;i<t.length;i+=1)s[i]=Qve(t[i],e,n,r,o);return e.pop(),n.pop(),s}if(t&&t.toJSON&&(t=t.toJSON()),Xve(t)==="object"&&t!==null){e.push(t),s={},n.push(s);var a=[],l;for(l in t)Object.prototype.hasOwnProperty.call(t,l)&&a.push(l);for(a.sort(),i=0;i<a.length;i+=1)l=a[i],s[l]=Qve(t[l],e,n,r,l);e.pop(),n.pop()}else s=t;return s}var Y8=new ch;Y8.tokenize=function(t){return t.slice()};Y8.join=Y8.removeEmpty=function(t){return t};function Q9e(t,e,n){return Y8.diff(t,e,n)}vt();var bv=require("obsidian"),Xe=N(U());rn();var wz=N(U());Kt();var uh=wz.forwardRef(({checked:t=!1,onCheckedChange:e,disabled:n=!1,className:r,...o},i)=>{let s=()=>{n||e?.(!t)},a=l=>{n||(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),e?.(!t))};return wz.createElement("div",{role:"switch","aria-checked":t,"aria-disabled":n,"data-state":t?"checked":"unchecked","data-disabled":n?"":void 0,ref:i,tabIndex:n?-1:0,className:oe("tw-relative tw-inline-flex tw-h-5.5 tw-w-10 tw-shrink-0 tw-cursor-pointer tw-items-center tw-rounded-full tw-transition-colors","focus-visible:tw-outline-none focus-visible:tw-ring-2 focus-visible:tw-ring-ring focus-visible:tw-ring-offset-2",t?"tw-bg-interactive-accent":"tw-bg-[--background-modifier-border-hover]",n&&"tw-cursor-not-allowed tw-opacity-50",r),onClick:s,onKeyDown:a,...o},wz.createElement("div",{className:oe("tw-pointer-events-none tw-block tw-size-4 tw-rounded-full tw-bg-toggle-thumb tw-shadow-lg tw-ring-0 tw-transition-transform",t?"tw-translate-x-5.5":"tw-translate-x-0.5")}))});uh.displayName="SettingSwitch";function eYe(t){let e=[],n=[];return t.forEach(r=>{r.added||r.removed?n.push(r):(n.length>0&&(e.push(n),n=[]),e.push([r]))}),n.length>0&&e.push(n),e}qe();function Djt(t,e){let n=o=>o.split(/(\s+)/).filter(Boolean);return Q9e(n(t),n(e)).map(o=>({value:o.value.join(""),added:o.added,removed:o.removed}))}function vz(t){let e=t.split(`
`);return e.length>0&&e[e.length-1]===""&&e.pop(),e}function tYe(t){let e=[],n=0;for(;n<t.length;){let r=t[n];if(!r.added&&!r.removed)vz(r.value).forEach(o=>{e.push({original:o,modified:o,isUnchanged:!0})}),n++;else if(r.removed){let o=t[n+1];if(o?.added){let i=vz(r.value),s=vz(o.value),a=Math.max(i.length,s.length);for(let l=0;l<a;l++)e.push({original:i[l]??null,modified:s[l]??null,isUnchanged:!1});n+=2}else vz(r.value).forEach(i=>{e.push({original:i,modified:null,isUnchanged:!1})}),n++}else r.added&&vz(r.value).forEach(o=>{e.push({original:null,modified:o,isUnchanged:!1})}),n++}return e}var nYe=(0,Xe.memo)(({original:t,modified:e,side:n})=>{let r=Djt(t,e);return Xe.default.createElement("span",null,r.map((o,i)=>{if(n==="original"){if(o.removed)return Xe.default.createElement("span",{key:i,className:"tw-bg-error tw-text-error"},o.value);if(o.added)return null}else{if(o.added)return Xe.default.createElement("span",{key:i,className:"tw-bg-success tw-text-success"},o.value);if(o.removed)return null}return Xe.default.createElement("span",{key:i},o.value)}))});nYe.displayName="WordDiffSpan";var xz=(0,Xe.memo)(({row:t,side:e})=>{let n=e==="original"?t.original:t.modified,r=e==="original"?t.modified:t.original;return n===null?Xe.default.createElement("span",{className:"tw-text-muted"},"\xA0"):t.isUnchanged?Xe.default.createElement("span",{className:"tw-text-normal"},n||"\xA0"):r!==null?Xe.default.createElement(nYe,{original:t.original,modified:t.modified,side:e}):Xe.default.createElement("span",{className:e==="original"?"tw-bg-error tw-text-error":"tw-bg-success tw-text-success"},n||"\xA0")});xz.displayName="DiffCell";var bz="obsidian-copilot-apply-view",X8=class extends bv.ItemView{constructor(n){super(n);this.root=null;this.state=null;this.result=null}getViewType(){return bz}getDisplayText(){return"Preview Changes"}async setState(n){this.state=n,this.render()}async onOpen(){this.render()}async onClose(){this.root&&(this.root.unmount(),this.root=null),this.state?.resultCallback?.(this.result?this.result:"aborted")}render(){if(!this.state)return;let n=this.containerEl.children[1];n.empty();let r=n.createDiv();this.root||(this.root=sr(r,this.app)),this.root.render(Xe.default.createElement($jt,{app:this.app,state:this.state,close:o=>{this.result=o,this.leaf.detach()}}))}},rYe=(0,Xe.memo)(({block:t})=>{let e=(0,Xe.useMemo)(()=>tYe(t),[t]);return Xe.default.createElement("div",{className:"tw-grid tw-grid-cols-2 tw-gap-2"},Xe.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},e.map((n,r)=>Xe.default.createElement("div",{key:r,className:"tw-whitespace-pre-wrap tw-font-mono tw-text-sm"},Xe.default.createElement(xz,{row:n,side:"original"})))),Xe.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},e.map((n,r)=>Xe.default.createElement("div",{key:r,className:"tw-whitespace-pre-wrap tw-font-mono tw-text-sm"},Xe.default.createElement(xz,{row:n,side:"modified"})))))});rYe.displayName="SideBySideBlock";var oYe=(0,Xe.memo)(({block:t})=>{let e=t.some(r=>r.added||r.removed),n=(0,Xe.useMemo)(()=>tYe(t),[t]);return e?Xe.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Xe.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},Xe.default.createElement("div",{className:"tw-mb-1 tw-text-xs tw-font-medium tw-text-muted"},"Original"),Xe.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-font-mono tw-text-sm"},n.map((r,o)=>r.original!==null?Xe.default.createElement("div",{key:o},Xe.default.createElement(xz,{row:r,side:"original"})):null))),Xe.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},Xe.default.createElement("div",{className:"tw-mb-1 tw-text-xs tw-font-medium tw-text-muted"},"Modified"),Xe.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-font-mono tw-text-sm"},n.map((r,o)=>r.modified!==null?Xe.default.createElement("div",{k
The path must end with explicit file extension, such as .md or .canvas .
Prefer to create new files in existing folders or root folder unless the user's request specifies otherwise.
The path must be relative to the root of the vault.`),content:we.union([we.string(),we.object({}).passthrough()]).describe(`(Required) The content to write to the file. Can be either a string or an object.
ALWAYS provide the COMPLETE intended content of the file, without any truncation or omissions.
You MUST include ALL parts of the file, even if they haven't been modified.
# For string content
* Use when writing text files like .md, .txt, etc.
# For object content
* Use when writing structured data files like .json, .canvas, etc.
* The object will be automatically converted to JSON string format
# Canvas JSON Format (JSON Canvas spec 1.0)
Required node fields: id, type, x, y, width, height
Node types: "text" (needs text), "file" (needs file), "link" (needs url), "group" (optional label)
Optional node fields: color (hex #FF0000 or preset "1"-"6"), subpath (file nodes, starts with #)
Required edge fields: id, fromNode, toNode
Optional edge fields: fromSide/toSide ("top"/"right"/"bottom"/"left"), fromEnd/toEnd ("none"/"arrow"), color, label
All IDs must be unique. Edge nodes must reference existing node IDs.
Example:
{
"nodes": [
{"id": "1", "type": "text", "text": "Hello", "x": 0, "y": 0, "width": 200, "height": 50},
{"id": "2", "type": "file", "file": "note.md", "subpath": "#heading", "x": 250, "y": 0, "width": 200, "height": 100, "color": "2"},
{"id": "3", "type": "group", "label": "Group", "x": 0, "y": 100, "width": 300, "height": 150}
],
"edges": [
{"id": "e1-2", "fromNode": "1", "toNode": "2", "fromSide": "right", "toSide": "left", "color": "3", "label": "links to"}
]
}`),confirmation:we.preprocess(t=>{if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t},we.boolean()).optional().default(!0).describe("(Optional) Hint for confirmation preference. Note: preview is always shown unless the user has enabled auto-accept in settings.")}),t9=Rr({name:"writeFile",description:`Request to write content to a file at the specified path and show the changes in a Change Preview UI.
# Steps to find the the target path
1. Extract the target file information from user message and find out the file path from the context.
2. If target file is not specified, use the active note as the target file.
3. If still failed to find the target file or the file path, ask the user to specify the target file.
`,schema:Fjt,func:async({path:t,content:e,confirmation:n=!0})=>{let r=Vte(t);r!==t&&(ee(`Filename too long, truncated for filesystem compatibility: "${t}" \u2192 "${r}"`),t=r);let o=typeof e=="string"?e:JSON.stringify(e,null,2);if(q().autoAcceptEdits)try{let l=await sYe(t);return await app.vault.modify(l,o),{result:"accepted",message:"File changes applied without preview. Do not retry or attempt alternative approaches to modify this file in response to the current user request."}}catch(l){return{result:"failed",message:`Error writing to file without preview: ${l instanceof Error?l.message:String(l)}`}}let a=await aYe(t,o);return{result:a,message:`File change result: ${a}. Do not retry or attempt alternative approaches to modify this file in response to the current user request.`}}}),Ujt=we.object({path:we.string().describe("(Required) The path of the file to modify (relative to the root of the vault and include the file extension)."),oldText:we.string().describe(`(Required) The exact text to find and replace. Must match the file content exactly, including whitespace and indentation.
Fuzzy matching handles minor differences like trailing spaces or smart quotes, but the overall structure must be correct.
To make the match unique, include enough surrounding context lines (not just the changed line).`),newText:we.string().describe("(Required) The new text to replace the old text with. Can be empty string to delete the old text.")});function exe(t){return t.replace(/\r\n/g,`
`).replace(/\r/g,`
`)}function e9(t){return t.normalize("NFKC").split(`
`).map(e=>e.trimEnd()).join(`
`).replace(/[\u2018\u2019]/g,"'").replace(/[\u201C\u201D]/g,'"').replace(/[\u2010-\u2015\u2212]/g,"-").replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g," ")}function Q8(t,e){if(!e)return 0;let n=0,r=0;for(;(r=t.indexOf(e,r))!==-1;)n++,r+=1;return n}function Bjt(t){return t.charCodeAt(0)===65279?{content:t.slice(1),hasBOM:!0}:{content:t,hasBOM:!1}}function zjt(t,e,n){let r=Q8(t,e);if(r>0)return{found:!0,occurrences:r,workingContent:t,workingSearch:e,workingReplace:n,usedFuzzyMatch:!1};let o=e9(t),i=e9(e),s=Q8(o,i);if(s>0)return{found:!0,occurrences:s,workingContent:o,workingSearch:i,workingReplace:n,usedFuzzyMatch:!0};if(e.endsWith(`
`)){let a=e.slice(0,-1),l=n.endsWith(`
`)?n.slice(0,-1):n,c=Q8(t,a);if(c>0)return{found:!0,occurrences:c,workingContent:t,workingSearch:a,workingReplace:l,usedFuzzyMatch:!1};let u=e9(a),d=Q8(o,u);if(d>0)return{found:!0,occurrences:d,workingContent:o,workingSearch:u,workingReplace:l,usedFuzzyMatch:!0}}return{found:!1,occurrences:0,workingContent:o,workingSearch:i,workingReplace:n,usedFuzzyMatch:!0}}function iYe(t,e,n){let r=n,o=0;for(let i=0;i<e.length;i++){let s=e[i].length,a=t[i]??"",l=a.length;if(r<=s){if(r===s)return o+l;let c=0,u=0;for(;u<a.length&&c<r;){let d=a[u].normalize("NFKC").length;if(c+d>r)break;c+=d,u++}return o+u}r-=s+1,o+=l+1}return o}function jjt(t,e,n){let{content:r,hasBOM:o}=Bjt(t),i=(r.match(/\r\n/g)||[]).length,s=(r.match(/(?<!\r)\n/g)||[]).length,a=i>s,l=exe(r),c=exe(e),u=exe(n),d=zjt(l,c,u);if(!d.found)return{ok:!1,reason:"NOT_FOUND"};if(d.occurrences>1)return{ok:!1,reason:"AMBIGUOUS",occurrences:d.occurrences};let f,p;if(d.usedFuzzyMatch){let h=l.split(`
`),g=d.workingContent.split(`
`),y=d.workingContent.indexOf(d.workingSearch);if(f=iYe(h,g,y),p=iYe(h,g,y+d.workingSearch.length),f>=p)return{ok:!1,reason:"NOT_FOUND"};if(e9(l.substring(f,p))!==d.workingSearch)return{ok:!1,reason:"NOT_FOUND"}}else f=l.indexOf(d.workingSearch),p=f+d.workingSearch.length;let m=l.substring(0,f)+d.workingReplace+l.substring(p);return a&&(m=m.replace(/\n/g,`\r
`)),o&&(m="\uFEFF"+m),{ok:!0,content:m}}var lYe=Rr({name:"editFile",description:"Request to make a targeted change to an existing file by specifying the exact text to find and its replacement. Use this tool for precise, surgical edits to specific parts of a file.",schema:Ujt,func:async({path:t,oldText:e,newText:n})=>{let r=Vte(t),o=app.vault.getAbstractFileByPath(r);if(!o||!(o instanceof aR.TFile))return{result:"failed",message:`File not found at path: ${r}. Please check the file path and try again.`};try{let i=await app.vault.read(o),s=jjt(i,e,n);if(!s.ok)return s.reason==="NOT_FOUND"?{result:"failed",message:`Could not find the specified text in ${r}. The oldText must match the file content \u2014 try including more surrounding context lines to locate the right spot.`}:{result:"failed",message:`Found ${s.occurrences} occurrences of the search text in ${r}. The text must be unique \u2014 add more surrounding context to make it unambiguous.`};let a=s.content;if(i===a)return{result:"accepted",message:`No changes made to ${r}. The replacement produced identical content. Use writeFile if the file needs a broader rewrite.`};if(q().autoAcceptEdits)return await app.vault.modify(o,a),{result:"accepted",message:"File changes applied without preview. Do not retry or attempt alternative approaches to modify this file in response to the current user request."};let c=await aYe(r,a,!0);return{result:c,message:`File change result: ${c}. Do not retry or attempt alternative approaches to modify this file in response to the current user request.`}}catch(i){return{result:"failed",message:`Error modifying ${r}: ${i}. Please check the file path and try again.`}}}});ye();var txe=t=>{switch(t){case"@vault":return"Search through your vault for relevant information";case"@websearch":return"Search the web for information";case"@composer":return"Edit existing notes or create new notes.";case"@memory":return"Save information to user memory";default:return""}},Cv=class{static async callTool(e,n){if(!e)throw new Error("Tool is undefined");let r=e,o=await r.call(n);return o??(ee(`[ToolCall] Tool "${r.name}" returned null/undefined`),null)}};function cYe(t){let e=t.trim();if(!e)return"note";let n=e.match(/^\[\[([\s\S]+?)\]\]$/),r=n?n[1]:e,[o="",i=""]=r.split("|"),s=i.trim();if(s.length>0)return s;let a=o.trim(),[l]=a.split("#"),c=(l||a).trim()||e,u=c.split("/").filter(Boolean),d=u.length>0?u[u.length-1]:c;return d.replace(/\.[^/.]+$/,"")||d||"note"}var uYe=180;function Vjt(t){let e=t.trim();return e.length<=uYe?e:`${e.slice(0,uYe)}\u2026`}function Wjt(t){if(!t||typeof t!="object")return null;let e=t,n=typeof e.status=="string"?e.status:null,r=typeof e.message=="string"&&e.message.trim().length>0?Vjt(e.message):null,o=typeof e.notePath=="string"?e.notePath:"",s=(typeof e.noteTitle=="string"&&e.noteTitle.trim().length>0?e.noteTitle.trim():cYe(o))||cYe(o);if(n==="invalid_path")return r??`\u26A0\uFE0F Invalid note path "${s}"`;if(n==="not_found")return r??`\u26A0\uFE0F Note "${s}" not found`;if(n==="not_unique"){let d=Array.isArray(e.candidates)?e.candidates.length:0;return r||(d>0?`\u26A0\uFE0F Multiple matches for "${s}" (${d} candidates)`:`\u26A0\uFE0F Multiple matches for "${s}"`)}if(n==="empty")return r??`\u26A0\uFE0F "${s}" contains no readable content`;if(n==="out_of_range"){if(r)return r;let d=typeof e.totalChunks=="number"&&Number.isFinite(e.totalChunks)?e.totalChunks:null,f=typeof e.chunkIndex=="number"&&Number.isFinite(e.chunkIndex)?e.chunkIndex:null;if(f!==null&&d!==null){let p=Math.max(d-1,0);return`\u26A0\uFE0F Chunk ${f} exceeds available range (max index ${p})`}return"\u26A0\uFE0F Requested chunk is out of range"}let a=typeof e.chunkIndex=="number"&&Number.isFinite(e.chunkIndex)?e.chunkIndex:0,l=typeof e.totalChunks=="number"&&Number.isFinite(e.totalChunks)?e.totalChunks:null,c=!!e.hasMore,u=[`\u2705 Read "${s||"note"}"`];return l&&l>0?u.push(`chunk ${a+1} of ${l}`):u.push(`chunk ${a+1}`),c&&u.push("more available"),u.join(" \xB7 ")}var _v=class{static format(e,n){try{let r=n;if(typeof r=="string"&&r.startsWith("ENC:"))try{r=decodeURIComp
No matching notes found.`;let n=e.length,r=e.slice(0,10),o=r.some(a=>{let l=a;return typeof l?.rerank_score=="number"||typeof l?.score=="number"||l?.source}),i=r.map((a,l)=>o?this.formatSearchItem(a,l):this.formatBasicSearchItem(a,l)).join(`
`),s=n>10?`
... and ${n-10} more results`:"";return`\u{1F4DA} Found ${n} relevant notes
Top results:
${i}${s}`}static formatLocalSearch(e){if(typeof e=="string"){let r=e.match(/<localSearch[^>]*>([\s\S]*)<\/localSearch>/);if(r){let o=r[1].trim(),i=o.match(/<document>/g);if((i?i.length:0)===0)return`\u{1F4DA} Found 0 relevant notes
No matching notes found.`;let a=[],l=/<document>([\s\S]*?)<\/document>/g,c;for(;(c=l.exec(o))!==null;){let u=c[1],d=u.match(/<title>([\s\S]*?)<\/title>/),f=u.match(/<path>([\s\S]*?)<\/path>/),p=u.match(/<modified>([\s\S]*?)<\/modified>/),m=(d?.[1]||"Untitled").trim(),h=(f?.[1]||"").trim(),g=(p?.[1]||"").trim();a.push({title:m,path:h,mtime:g||null})}return this.formatLocalSearchDocuments(a)}}let n=this.parseSearchResults(e);return Array.isArray(n)?n.length===0?typeof e=="string"&&!e.includes("<localSearch")&&!e.includes('"type":"local_search"')?e:`\u{1F4DA} Found 0 relevant notes
No matching notes found.`:this.formatLocalSearchDocuments(n):typeof e=="string"?e:JSON.stringify(e,null,2)}static parseSearchResults(e){if(typeof e=="object"&&e!==null){let n=e;return n.type==="local_search"&&Array.isArray(n.documents)?n.documents:[]}if(typeof e=="string"){try{let n=JSON.parse(e);if(n&&typeof n=="object"&&n.type==="local_search"&&Array.isArray(n.documents))return n.documents}catch{}return[]}return[]}static formatSearchItem(e,n){let r=e,o=typeof r.path=="string"?r.path:"",i=typeof r.title=="string"?r.title:"",s=o?o.split("/").pop()?.replace(/\.md$/,"")||i||"Untitled":i||"Untitled",a=r.rerank_score||r.score||0,l=typeof a=="number"?a.toFixed(4):a,c=r.source==="time-filtered"?"Recency":"Relevance",u=[`${n+1}. ${s}`];if(r.source==="time-filtered"){if(r.mtime)try{let f=r.mtime,p=new Date(f),m=isNaN(p.getTime())?typeof f=="string"||typeof f=="number"?String(f):"":p.toISOString();u.push(` \u{1F552} Modified: ${m}${r.includeInContext?" \u2713":""}`)}catch{let f=typeof r.mtime=="string"||typeof r.mtime=="number"?String(r.mtime):"";u.push(` \u{1F552} Modified: ${f}${r.includeInContext?" \u2713":""}`)}}else r.source==="title-match"?u.push(` \u{1F516} Title match${r.includeInContext?" \u2713":""}`):u.push(` \u{1F4CA} ${c}: ${l}${r.includeInContext?" \u2713":""}`);let d=this.extractContentSnippet(r.content);if(d){let f=typeof r.content=="string"?r.content.length:0;u.push(` \u{1F4AC} "${d}${f>150?"...":""}"`)}return o&&!o.endsWith(`/${s}.md`)&&u.push(` \u{1F4C1} ${o}`),u.join(`
`)}static formatBasicSearchItem(e,n){let r=e,o=r.title||r.path||`Result ${n+1}`,i=[`${n+1}. ${o}`],s=r.mtime||r.modified||r.modified_at||r.updated_at;if(s){let a=typeof s=="string"||typeof s=="number"?String(s):"";a&&i.push(` \u{1F552} Modified: ${a}`)}return typeof r.path=="string"&&r.path&&r.path!==o&&i.push(` \u{1F4C1} ${r.path}`),i.join(`
`)}static extractContentSnippet(e,n=150){return e?(e.match(/NOTE BLOCK CONTENT:\s*([\s\S]*)/)?.[1]||e).substring(0,n).replace(/\s+/g," ").trim():""}static formatWebSearch(e){let n=Array.isArray(e)&&e.length>0?e[0]:null;if(n&&n.type==="web_search"){let r=["\u{1F310} Web Search Results"];n.content&&(r.push(""),r.push(typeof n.content=="string"?n.content:""));let o=Array.isArray(n.citations)?n.citations:[];return o.length>0&&(r.push(""),r.push("Sources:"),o.forEach((i,s)=>{r.push(`[${s+1}] ${String(i)}`)})),n.instruction&&(r.push(""),r.push(`Note: ${typeof n.instruction=="string"?n.instruction:""}`)),r.join(`
`)}if(typeof e=="string"){let r=e.split(`
`),o=["\u{1F310} Web Search Results"],i=!1,s=[],a=[];for(let l of r){if(l.includes("Sources:")){i=!0;continue}i?a.push(l):l.includes("Here are the web search results")||s.push(l)}return s.length>0&&(o.push(""),o.push(...s.filter(l=>l.trim()))),a.length>0&&(o.push(""),o.push("Sources:"),a.forEach(l=>{l.trim()&&o.push(l)})),o.join(`
`)}return typeof e=="string"?e:""}static formatYoutubeTranscription(e){let n;if(typeof e=="string")try{n=JSON.parse(e)}catch{return e}else if(typeof e=="object")n=e;else return typeof e=="number"||typeof e=="boolean"?String(e):"";let r=typeof n=="object"&&n!==null?n:null;if(!r)return typeof e=="object"?JSON.stringify(e,null,2):"";if(r.success===!1)return`\u{1F4FA} YouTube Transcription Failed
${typeof r.message=="string"?r.message:""}`;if(r.results&&Array.isArray(r.results)){let o=typeof r.total_urls=="number"?r.total_urls:r.results.length,i=[`\u{1F4FA} YouTube Transcripts (${o} video${o>1?"s":""})`];i.push("");for(let s of r.results){let a=typeof s=="object"&&s!==null?s:null;if(a){if(a.success){i.push(`\u{1F4F9} Video: ${typeof a.url=="string"?a.url:""}`),i.push("");let c=(typeof a.transcript=="string"?a.transcript:"").split(`
`),u=0;for(let d of c)if(d.trim()&&(d.match(/^\[(\d+:\d+)\]/)?(u>0&&i.push(""),i.push(`\u23F0 ${d}`)):i.push(` ${d.trim()}`),u++,u>30)){i.push(""),i.push("... (transcript truncated for display)");break}a.elapsed_time_ms&&(i.push(""),i.push(`Processing time: ${(typeof a.elapsed_time_ms=="number"?a.elapsed_time_ms/1e3:0).toFixed(1)}s`))}else i.push(`\u274C Failed to transcribe: ${typeof a.url=="string"?a.url:""}`),i.push(` ${typeof a.message=="string"?a.message:""}`);i.push(""),i.push("---"),i.push("")}}return i.join(`
`).trimEnd()}if(r.transcript){let o=["\u{1F4FA} YouTube Transcript"];o.push("");let s=(typeof r.transcript=="string"?r.transcript:"").split(`
`),a=0;for(let l of s)if(l.trim()&&(l.match(/^\[(\d+:\d+)\]/)?(a>0&&o.push(""),o.push(`\u23F0 ${l}`)):o.push(` ${l.trim()}`),a++,a>50)){o.push(""),o.push("... (transcript truncated for display)");break}return r.elapsed_time_ms&&(o.push(""),o.push(`Processing time: ${(typeof r.elapsed_time_ms=="number"?r.elapsed_time_ms/1e3:0).toFixed(1)}s`)),o.join(`
`)}return typeof e=="object"?JSON.stringify(e,null,2):""}static formatWriteToFile(e){let n=typeof e=="object"&&e!==null?e:null,r=n?n.result:e,o=(typeof r=="string"?r:typeof r=="number"||typeof r=="boolean"?String(r):"").toLowerCase();return o.includes("accepted")?"\u2705 File change: accepted":o.includes("rejected")?"\u274C File change: rejected":n&&typeof n.message=="string"?n.message:typeof r=="string"?r:""}static formatReplaceInFile(e){let n=typeof e=="object"&&e!==null?e:null,r=n?n.result:void 0,o=n?typeof r=="string"||typeof r=="number"||typeof r=="boolean"?String(r):"":typeof e=="string"?e:"",i=n?n.diff:void 0,s=typeof i=="string"?i:typeof i=="number"?String(i):"";return o.toLowerCase().includes("accepted")&&s?`\u2705 Edit accepted
\`\`\`diff
${s}
\`\`\``:o.toLowerCase().includes("accepted")?"\u2705 Edit accepted":o.toLowerCase().includes("rejected")?"\u274C Edit rejected":n&&typeof n.message=="string"?n.message:o}static formatReadNote(e){let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch{n=null}let r=Wjt(n);return r||(typeof e=="string"?e:JSON.stringify(e,null,2))}};Se();var dYe=require("obsidian"),Hjt="obsidian",Kjt=["/Applications/Obsidian.app/Contents/MacOS/obsidian","/Applications/Obsidian.app/Contents/MacOS/Obsidian"],qjt=15e3,Gjt=1048576;function nxe(){let t=dYe.Platform;return!!(t.isDesktopApp??t.isDesktop)}function Yjt(){let t=window;if(typeof t.require!="function")throw new Error("Node require is unavailable in this runtime. Obsidian CLI commands require the desktop app.");return t.require}function Zjt(){let e=Yjt()("child_process");if(typeof e.execFile!="function")throw new Error("Failed to resolve child_process.execFile");return e.execFile}function Jjt(t){return t.replace(/\n/g,"\\n").replace(/\t/g,"\\t")}function Xjt(){let e=window.process?.env;return e?[e.OBSIDIAN_CLI_BINARY,e.OBSIDIAN_CLI_PATH].map(r=>r?.trim()||"").filter(Boolean):[]}function Qjt(t){let e=t?.trim();if(e)return[e];let n=[...Xjt(),Hjt,...Kjt];return Array.from(new Set(n.map(r=>r.trim()).filter(Boolean)))}function e4t(t){let e=[],n=t.vault?.trim();n&&e.push(`vault=${n}`),e.push(t.command);let r=Object.entries(t.params||{});r.sort(([o],[i])=>o.localeCompare(i));for(let[o,i]of r)if(i!=null){if(typeof i=="boolean"){i&&e.push(o);continue}e.push(`${o}=${Jjt(String(i))}`)}return e}function t4t(t){return typeof t=="number"?t:null}async function n4t(t,e,n,r,o,i,s){let a=Date.now();return await new Promise(l=>{t(n,r,{timeout:o,maxBuffer:i,windowsHide:!0},(c,u,d)=>{let f=Date.now()-a;if(c){l({command:e,args:r,binary:n,attemptedBinaries:[...s],ok:!1,stdout:u||"",stderr:d||"",exitCode:t4t(c.code),errorCode:c.code??null,signal:c.signal??null,durationMs:f});return}l({command:e,args:r,binary:n,attemptedBinaries:[...s],ok:!0,stdout:u||"",stderr:d||"",exitCode:0,errorCode:null,signal:null,durationMs:f})})})}async function Sv(t){let e=t.command?.trim();if(!e)throw new Error("Obsidian CLI command is required");if(!nxe())throw new Error("Obsidian CLI commands are only supported in desktop Obsidian.");let n=e4t({...t,command:e}),r=t.timeoutMs??qjt,o=t.maxBufferBytes??Gjt,i=Zjt(),s=Qjt(t.binary),a=[],l=null;for(let c of s){a.push(c);let u=await n4t(i,e,c,n,r,o,a);if(l=u,u.ok||u.errorCode!=="ENOENT")return u}if(l)return l;throw new Error("Obsidian CLI execution failed before process spawn.")}async function fYe(t){return await Sv({command:"daily:read",vault:t})}async function pYe(t){return await Sv({command:"random:read",vault:t})}fc();function r4t(t){return typeof t=="object"&&t!==null&&"children"in t&&"path"in t}function o4t(t){return typeof t=="object"&&t!==null&&"path"in t&&!("children"in t)}function i4t(t){let e=t.split(".");return e.length>1&&e.pop()?.toLowerCase()||""}function rxe(t,e=!0){let n=[],r={},o={},{inclusions:i,exclusions:s}=Bo();for(let l of t.children)if(o4t(l)){if(Qr(l,i,s)){e&&n.push(l.name);let c=i4t(l.name)||"unknown";c&&(r[c]=(r[c]||0)+1)}}else if(r4t(l)){let c=rxe(l,e);if(Object.keys(c).length>0&&(o[l.name]=c[l.name],c[l.name].extensionCounts))for(let[u,d]of Object.entries(c[l.name].extensionCounts))r[u]=(r[u]||0)+d}let a={};return Object.keys(r).length>0&&(a.extensionCounts=r),e&&n.length>0&&(a.files=n),Object.keys(o).length>0&&(a.subFolders=o),Object.keys(a).length===0?{}:t.name?{[t.name]:a}:{vault:a}}var mYe=t=>Rr({name:"getFileTree",description:"Get the file tree as a nested structure of folders and files",schema:we.object({}),func:async()=>{let e=rxe(t,!0),n=`A JSON represents the file tree as a nested structure:
* The root object has a key "vault" which contains a FileTreeNode object.
* Each FileTreeNode has these properties:
* files: An array of filenames in the current directory (if any files exist)
* subFolders: An object mapping folder names to their FileTreeNode objects (if any subfolders exist)
* extensionCounts: An object with counts of file extensions in this folder and all subfolders
`,r=JSON.stringify(e);if(r.length>5e5){let o=rxe(t,!1);return n+JSON.stringify(o)}return n+r}});var lR=require("obsidian");ye();Se();qe();Kr();var o_=class{constructor(e){this.recentConversationsContent="";this.savedMemoriesContent="";this.isUpdatingMemory=!1;this.app=e}async loadMemory(){try{let e=this.app.vault.getAbstractFileByPath(this.getRecentConversationFilePath());e instanceof lR.TFile?this.recentConversationsContent=await this.app.vault.read(e):(this.recentConversationsContent="",k("[UserMemoryManager] Recent Conversations file not found, skipping memory load"));let n=this.app.vault.getAbstractFileByPath(this.getSavedMemoriesFilePath());n instanceof lR.TFile?this.savedMemoriesContent=await this.app.vault.read(n):(this.savedMemoriesContent="",k("[UserMemoryManager] Saved Memories file not found, skipping saved memory load"))}catch(e){z("[UserMemoryManager] Error reading memory files:",e),this.recentConversationsContent="",this.savedMemoriesContent=""}}addRecentConversation(e,n){if(!q().enableRecentConversations){ee("[UserMemoryManager] Recent history referencing is disabled, skipping analysis");return}if(e.length===0){ee("[UserMemoryManager] No messages to analyze for user memory");return}this.updateMemory(e,n).catch(o=>{z("[UserMemoryManager] Background user memory operation failed:",o)})}async updateSavedMemory(e,n){if(!q().enableSavedMemory)return{error:"Saved memory is disabled, skipping save"};if(!e||e.trim()==="")return{error:"No content provided for saved memory"};if(!n)return{error:"No chat model available, skipping save"};try{return await this.ensureMemoryFolderExists(),await this.updateSavedMemoryFile(this.getSavedMemoriesFilePath(),e,n)}catch(o){return{error:"Error saving memory: "+(o instanceof Error?o.message:String(o))}}}async getUserMemoryPrompt(){await this.loadMemory();try{let e=q(),n="";return e.enableRecentConversations&&this.recentConversationsContent&&(n+=`<recent_conversations>
${this.recentConversationsContent}
</recent_conversations>
The current time is ${this.getTimestamp()}.
<recent_conversations> are the recent conversations between you and the user.
You can use it to provide more context for your responses.
Only use the recent conversations if they are relevant to the current conversation.`),e.enableSavedMemory&&this.savedMemoriesContent&&(n+=`<saved_memories>
${this.savedMemoriesContent}
</saved_memories>
<saved_memories> are important memories that the user explicitly asked you to remember.
Use these memories to provide more personalized and contextually relevant responses.`),n.length>0?n:null}catch(e){return z("[UserMemoryManager] Error reading user memory content:",e),null}}getTimestamp(){let e=new Date,n=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0"),i=String(e.getHours()).padStart(2,"0"),s=String(e.getMinutes()).padStart(2,"0");return`${n}-${r}-${o} ${i}:${s}`}async createConversationSection(e,n){let{title:r,summary:o}=await this.extractTitleAndSummary(e,n),i=this.getTimestamp(),s=`## ${r}
`;return s+=`**Time:** ${i}
`,s+=`**Summary:** ${o}
`,s}async updateMemory(e,n){if(this.isUpdatingMemory){k("[UserMemoryManager] Memory update already in progress, skipping.");return}this.isUpdatingMemory=!0;try{if(await this.ensureMemoryFolderExists(),!n){z("[UserMemoryManager] No chat model available, skipping memory update");return}if(e.length===0){k("[UserMemoryManager] No messages available, skipping memory update");return}let r=await this.createConversationSection(e,n);await this.addToRecentConversationsFile(this.getRecentConversationFilePath(),r)}catch(r){z("[UserMemoryManager] Error analyzing chat messages for user memory:",r)}finally{this.isUpdatingMemory=!1}}async ensureMemoryFolderExists(){let n=q().memoryFolderName;await Fr(n)}getRecentConversationFilePath(){return`${q().memoryFolderName}/Recent Conversations.md`}getSavedMemoriesFilePath(){return`${q().memoryFolderName}/Saved Memories.md`}async updateSavedMemoryFile(e,n,r){let o=this.app.vault.getAbstractFileByPath(e),i=o instanceof lR.TFile?await this.app.vault.read(o):"";if(!r)return{error:"No chat model available, skipping memory update"};let s=`You maintain a user's long-term personal memory list as concise bullet points.
You task is to update the user's memory list with the new statement.
Rules:
- Keep only stable, evergreen facts or preferences that will help future conversations.
- Remove duplicates and near-duplicates by merging them into one concise statement.
- If the new statement conflicts with older ones, keep the most recent truth and remove obsolete/conflicting entries.
- Prefer short, specific, and unambiguous phrasing.
- Preserve the language used in the input memories.
- Output only the memory content with each as a bullet point.
# OUTPUT FORMAT
Return the updated memory list with each as a bullet point.
- memory item 1
- memory item 2
- memory item 3
...
`,a=`<current_memories>
${i.trim()}
</current_memories>
<new_statement>
${n.trim()}
</new_statement>
`,l=[new Vu(s),new Zo(a)],c=null;try{c=(await r.invoke(l)).text??""}catch(u){return{error:"LLM call failed while updating saved memories: "+(u instanceof Error?u.message:String(u))}}return c==null||c.trim()===""?{error:"Empty content returned from LLM"}:(o instanceof lR.TFile?await this.app.vault.modify(o,c):await this.app.vault.create(e,c),{content:c})}async addToRecentConversationsFile(e,n){let r=this.app.vault.getAbstractFileByPath(e);if(r instanceof lR.TFile){let o=await this.app.vault.read(r),i;if(o.trim()==="")i=`${n.trim()}
`;else{let s=this.parseExistingConversations(o);s.push(n);let l=q().maxRecentConversations;s.length>l&&s.splice(0,s.length-l),i=`${s.map(u=>u.trim()).join(`
`)}
`}await this.app.vault.modify(r,i)}else{let o=`${n.trim()}
`;await this.app.vault.create(e,o)}}parseExistingConversations(e){let n=e.split(`
`),r=[],o=[];for(let i of n)i.trim().startsWith("## ")?(o.length>0&&r.push(o.join(`
`).trim()),o=[i]):o.length>0&&o.push(i);return o.length>0&&r.push(o.join(`
`).trim()),r}extractJsonFromResponse(e){let n=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);if(n)return n[1].trim();let r=e.match(/\{[\s\S]*\}/);return r?r[0]:e}async extractTitleAndSummary(e,n){let r=e.map(a=>`${a.sender}: ${a.message}`).join(`
`),o=`Your task is to analyze a conversation and generate both a title and a summary.
# OUTPUT FORMAT
You must return your response in the following JSON format:
{
"title": "Brief 2-8 word title capturing the main user intent",
"summary": "2-3 sentence summary at most including key details (e.g. user facts mentioned entities), and key conclusions if there are any."
}
# RULES
* Use the same language as the conversation`,i=`<conversation_text>
${r}
</conversation_text>
Generate a title and summary for this conversation:`,s=[new Vu(o),new Zo(i)];try{let l=(await n.invoke(s)).text,c=this.extractJsonFromResponse(l);try{let u=JSON.parse(c);return{title:u.title||"Untitled Conversation",summary:u.summary||"No summary available"}}catch(u){return z("[UserMemoryManager] Failed to parse LLM response as JSON:",u),{title:"Untitled Conversation",summary:"Summary generation failed"}}}catch(a){return z("[UserMemoryManager] Failed to extract title and summary:",a),{title:"Untitled Conversation",summary:"Summary generation failed"}}}};ye();eP();var s4t=we.object({statement:we.string().min(1).describe("The user statement for explicitly updating saved memories")}),n9=Rr({name:"updateMemory",description:"Update the user memory when the user explicitly asks to update the memory",schema:s4t,func:async({statement:t})=>{try{let e=new o_(app),n=Np.getInstance().getChatModel(),r=await e.updateSavedMemory(t,n);return r.error?{success:!1,message:r.error}:{success:!0,message:`Memory updated successfully into ${e.getSavedMemoriesFilePath()}: ${r.content}`}}catch(e){return z("[updateMemoryTool] Error updating memory:",e),{success:!1,message:`Failed to save memory: ${e instanceof Error?e.message:String(e)}`}}}});var Cz=require("obsidian");ye();var oxe=200;function r9(t){return t.replace(/\\/g,"/").toLowerCase()}function a4t(t){return t.replace(/\.[^/.]+$/,"")}function l4t(t,e){if(e.length===0)return!1;let r=r9(t).split("/").filter(Boolean);if(r.length<e.length)return!1;let o=r.slice(-e.length);for(let i=0;i<e.length;i+=1){let s=e[i];if(!s)return!1;let a=o[i];if(i===o.length-1){let l=a4t(a);if(!a.includes(s)&&!l.includes(s))return!1}else if(!a.includes(s))return!1}return!0}function ixe(t){return/\.[^/]+$/.test(t)}async function c4t(t){let e=w=>{let v=app.vault.getAbstractFileByPath(w);return v instanceof Cz.TFile?v:null},n=t.trim(),r=n.match(/^\s*\[\[([\s\S]+?)\]\]\s*$/),i=(r?r[1]:n).trim(),[s]=i.split("|"),[a]=s.split("#"),l=a.trim(),c=Array.from(new Set([n,i,l].map(w=>w.trim()).filter(Boolean)));for(let w of c){let v=e(w);if(v)return{type:"resolved",file:v};if(!ixe(w))for(let x of[".md",".canvas"]){let b=e(`${w}${x}`);if(b)return{type:"resolved",file:b}}}let u=app.metadataCache,d=l.trim();if(u&&d){let w=new Set([d]);if(!ixe(d))for(let v of[".md",".canvas"])w.add(`${d}${v}`);for(let v of w){let x=u.getFirstLinkpathDest?.(v,"");if(x instanceof Cz.TFile)return{type:"resolved",file:x}}}if(!d)return{type:"not_found"};let f=app.vault.getMarkdownFiles?.()??[];if(f.length===0)return{type:"not_found"};let p=r9(d),m=new Set([p]);if(!ixe(d))for(let w of[".md",".canvas"])m.add(r9(`${d}${w}`));for(let w of f){let v=r9(w.path);if(m.has(v))return{type:"resolved",file:w}}let h=d.split("/").pop();if(h){let w=h.toLowerCase(),v=f.filter(x=>x.basename.toLowerCase()===w);if(v.length===1)return{type:"resolved",file:v[0]};if(v.length>1)return{type:"not_unique",matches:v}}let g=p.split("/").filter(Boolean);if(g.length===0)return{type:"not_found"};let y=f.filter(w=>l4t(w.path,g));return y.length===1?{type:"resolved",file:y[0]}:y.length>1?{type:"not_unique",matches:y}:{type:"not_found"}}async function u4t(t){try{return await app.vault.read(t)}catch(e){return ee(`readNote: failed to read ${t.path}`,e),""}}function d4t(){let t=new Map,e=app.vault.getMarkdownFiles?.()??[];for(let n of e)if(n instanceof Cz.TFile){let r=t.get(n.basename)??[];r.push(n),t.set(n.basename,r)}return t}function f4t(t,e,n){let r=t.trim();if(!r)return[];let o=new Map,i=app.metadataCache.getFirstLinkpathDest?.(r,e);if(i instanceof Cz.TFile&&o.set(i.path,i),!/\.[^./]+$/.test(r)){let s=r.split("/").pop()??r,a=n.get(s)??[];for(let l of a)o.set(l.path,l)}return Array.from(o.values())}function p4t(t,e){if(!t)return[];let n=/\[\[([^\]]+)\]\]/g,r=new Map,o=null,i;for(;(i=n.exec(t))!==null;){if(i.index>0&&t[i.index-1]==="!")continue;let s=i[1]?.trim();if(!s)continue;let[a,l]=s.split("|"),[c,u]=a.split("#"),d=c?.trim();if(!d)continue;let f=`${d}|${l??""}|${u??""}`;if(r.has(f))continue;o||(o=d4t());let p=f4t(d,e.path,o);r.set(f,{linkText:d,displayText:l?.trim()||d,section:u?.trim(
`).trimEnd(),heading:d})}return i}var h4t=we.object({notePath:we.string().min(1).describe("Full path to the note (relative to the vault root) that needs to be read, such as 'Projects/plan.md'."),chunkIndex:we.preprocess(t=>{if(typeof t=="string"){let e=t.trim();if(e.length===0)return;let n=Number(e);return Number.isFinite(n)?n:t}return t},we.number().int().min(0)).optional().describe("0-based chunk index to read. Omit to read the first chunk.")}),hYe=Rr({name:"readNote",description:"Read a single note in search v3 sized chunks. Use only when you already know the exact note path and need its contents.",schema:h4t,func:async({notePath:t,chunkIndex:e=0})=>{let n=t.trim();if(n.startsWith("/"))return{notePath:n,status:"invalid_path",message:"Provide the note path relative to the vault root without a leading slash."};let r=await c4t(n);if(r.type==="not_found")return ee(`readNote: note not found or not a file (${n})`),{notePath:n,status:"not_found",message:`Note "${n}" was not found or is not a readable file.`};if(r.type==="not_unique")return ee(`readNote: ambiguous note path "${n}" matched multiple files`,r.matches.map(f=>f.path)),{notePath:n,status:"not_unique",message:`Multiple notes match "${n}". Provide a more specific path.`,candidates:r.matches.map(f=>({path:f.path,title:f.basename}))};let o=r.file,i=o.path,s=await u4t(o),a=m4t(o,s),l=a.length;if(l===0)return{notePath:i,status:"empty",message:`No readable content was found in "${i}".`};if(e>=l)return{notePath:i,status:"out_of_range",message:`Chunk index ${e} exceeds available chunks (last index ${l-1}).`,totalChunks:l};let c=a[e];k(`readNote: returning chunk ${c.chunkIndex} of ${l} for ${i}`);let u=c.chunkIndex<l-1,d=p4t(c.content,o);return{notePath:i,noteTitle:o.basename,heading:c.heading,chunkId:c.id,chunkIndex:c.chunkIndex,totalChunks:l,hasMore:u,nextChunkIndex:u?c.chunkIndex+1:null,content:c.content,mtime:o.stat.mtime,linkedNotes:d.length>0?d:void 0}}});function o9(t,e,n,r){let o=t.trim();return o.length>0?o:n==="ENOENT"?`CLI binary not found. Tried: ${r.length>0?r.join(", "):"unknown"}. Ensure Obsidian CLI is installed or set OBSIDIAN_CLI_BINARY/OBSIDIAN_CLI_PATH.`:n!==null?`Obsidian CLI failed with error code ${String(n)}`:e!==null?`Obsidian CLI failed with exit code ${e}`:"Obsidian CLI command failed for an unknown reason"}function oP(t){throw new Error(o9(t.stderr,t.exitCode,t.errorCode,t.attemptedBinaries))}var Ndr=Rr({name:"obsidianDailyRead",description:"Read the current daily note via Obsidian CLI and return the note content as plain text.",schema:we.object({vault:we.string().optional().describe("Optional vault name to target. Omit to use the active/default vault resolution from Obsidian CLI.")}),func:async({vault:t})=>{let e=await fYe(t);if(!e.ok)throw new Error(`Failed to read daily note via Obsidian CLI: ${o9(e.stderr,e.exitCode,e.errorCode,e.attemptedBinaries)}`);return{type:"obsidian_cli_daily_read",command:e.command,vault:t||null,content:e.stdout,durationMs:e.durationMs}}}),gYe=Rr({name:"obsidianRandomRead",description:"Read a random note via Obsidian CLI and return the note content as plain text.",schema:we.object({vault:we.string().optional().describe("Optional vault name to target. Omit to use the active/default vault resolution from Obsidian CLI.")}),func:async({vault:t})=>{let e=await pYe(t);if(!e.ok)throw new Error(`Failed to read random note via Obsidian CLI: ${o9(e.stderr,e.exitCode,e.errorCode,e.attemptedBinaries)}`);return{type:"obsidian_cli_random_read",command:e.command,vault:t||null,content:e.stdout,durationMs:e.durationMs}}});function cR(t){return Object.fromEntries(Object.entries(t).filter(([e,n])=>e!=="command"&&e!=="vault"&&n!==void 0))}var g4t=we.object({command:we.enum(["daily","daily:read","daily:path"]).describe("daily \u2014 create today's daily note (applies configured template). daily:read \u2014 read today's daily note content. daily:path \u2014 get the vault-relative file path."),vault:we.string().optional().describe("Optional vault name to target. Omit to use the active vault.")}),yYe=Rr({name:"obsidianDailyNote",description:
`:`Semantic search index refreshed with ${n} documents.
`;return{success:!0,message:r?o+"Miyo will handle chunking and indexing for the registered folder.":o+`Semantic search index has been refreshed with ${n} documents.`,documentCount:n}}catch(e){return{success:!1,message:`Failed to index with semantic search: ${e instanceof Error?e.message:String(e)}`}}else return{success:!0,message:"Tiered lexical retriever uses on-demand indexing. No manual indexing required."}}}),T4t=we.object({query:we.string().min(1).describe("The search query to search the internet"),chatHistory:we.array(we.object({role:we.enum(["user","assistant"]),content:we.string()})).describe("Previous conversation turns for context (usually empty array)")}),s9=Rr({name:"webSearch",description:"Search the INTERNET (NOT vault notes) when user explicitly asks for web/online information",schema:T4t,func:async({query:t,chatHistory:e})=>{try{let n=await AG(t,e),r,o;if(pc()&&B5e()){let s=await z5e(n);r=s.content,o=s.citations}else{let s=await di.getInstance().webSearch(n);r=s.response.choices[0].message.content,o=s.response.citations||[]}return[{type:"web_search",content:r,citations:o,instruction:z9e()}]}catch(n){return console.error(`Error processing web search query ${t}:`,n),{error:`Web search failed: ${n}`}}}});var uxe=5e5,I4t=500,PYe=50,P4t=we.object({includeInline:we.boolean().optional().describe("Include inline tags in addition to frontmatter tags. Defaults to true."),maxEntries:we.number().int().min(1).max(5e3).optional().describe("Maximum number of tag entries to return, sorted by occurrences. Responses are capped at ~500KB.")}).describe("Parameters for retrieving the tag list.");function E4t(){return typeof app>"u"||!app?.metadataCache?null:app.metadataCache}function EYe(t){let e={};if(!t)return e;for(let[n,r]of Object.entries(t)){let o=n?.trim();if(!o)continue;let i=o.replace(/^#+/,"").trim().toLowerCase();if(!i)continue;let s=`#${i}`;if(s==="#")continue;let a=Number.isFinite(r)?Math.max(0,Math.floor(r)):0;e[s]=(e[s]||0)+a}return e}function A4t(t,e,n){let r=t,o=EYe(r.getFrontmatterTags?.()),i=e?EYe(r.getTags?.()):{},s=new Set([...Object.keys(o),...e?Object.keys(i):[]]),a=[],l=0;for(let u of s){let d=o[u]??0,f=e?Math.max(0,i[u]??0):0,p=0,m=d;e&&(f>=d?(p=f-d,m=f):f>0&&(p=f,m=d+p)),m!==0&&(l+=m,a.push({tag:u,occurrences:m,frontmatterOccurrences:d,inlineOccurrences:p}))}a.sort((u,d)=>d.occurrences===u.occurrences?u.tag.localeCompare(d.tag):d.occurrences-u.occurrences);let c=a.slice(0,n);return{totalUniqueTags:a.length,returnedTagCount:c.length,totalOccurrences:l,includedSources:e?["frontmatter","inline"]:["frontmatter"],truncated:c.length<a.length,tags:c}}function k4t(t){let e=t,n=JSON.stringify(e);if(n.length<=uxe)return e;let r=e.tags.length;for(;n.length>uxe&&r>PYe;)r=Math.max(PYe,Math.floor(r/2)),e={...e,tags:t.tags.slice(0,r),returnedTagCount:r,truncated:!0},n=JSON.stringify(e);return n.length>uxe?{totalUniqueTags:t.totalUniqueTags,returnedTagCount:0,totalOccurrences:t.totalOccurrences,includedSources:t.includedSources,truncated:!0,tags:[],note:"Tag list exceeded the size limit. Request a narrower scope or specify a smaller maxEntries value."}:e}function AYe(t){return`A JSON object lists the vault tags and their occurrence counts:
* totalUniqueTags: number of unique tags indexed across the vault
* returnedTagCount: number of tag entries included in this response
* totalOccurrences: total tag occurrences across included sources
* includedSources: sources represented in the counts (frontmatter, inline)
* truncated: whether the list was shortened due to limits
* tags: array of tag objects { tag, occurrences, frontmatterOccurrences, inlineOccurrences }
${JSON.stringify(t)}`}var kYe=()=>Rr({name:"getTagList",description:"Get the list of tags in the vault with occurrence statistics.",schema:P4t,func:async t=>{let e=E4t(),n=t?.includeInline??!0,r=t?.maxEntries??I4t;if(!e)return AYe({totalUniqueTags:0,returnedTagCount:0,totalOccurrences:0,includedSources:n?["frontmatter","inline"]:["frontmatter"],truncated:!1,tags:[],note:"Metadata cache is unavailable. Try again after the vault finishes indexing."});let o=A4t(e,n,r),i=k4t(o);return AYe(i)}});var RYe=N(MYe(),1),_z=N(i_(),1);var Lr;(function(t){t[t.AM=0]="AM",t[t.PM=1]="PM"})(Lr||(Lr={}));var Is;(function(t){t[t.SUNDAY=0]="SUNDAY",t[t.MONDAY=1]="MONDAY",t[t.TUESDAY=2]="TUESDAY",t[t.WEDNESDAY=3]="WEDNESDAY",t[t.THURSDAY=4]="THURSDAY",t[t.FRIDAY=5]="FRIDAY",t[t.SATURDAY=6]="SATURDAY"})(Is||(Is={}));var uf;(function(t){t[t.JANUARY=1]="JANUARY",t[t.FEBRUARY=2]="FEBRUARY",t[t.MARCH=3]="MARCH",t[t.APRIL=4]="APRIL",t[t.MAY=5]="MAY",t[t.JUNE=6]="JUNE",t[t.JULY=7]="JULY",t[t.AUGUST=8]="AUGUST",t[t.SEPTEMBER=9]="SEPTEMBER",t[t.OCTOBER=10]="OCTOBER",t[t.NOVEMBER=11]="NOVEMBER",t[t.DECEMBER=12]="DECEMBER"})(uf||(uf={}));function NYe(t,e){e=e.add(1,"day"),sP(t,e),uR(t,e)}function dh(t,e){t.assign("day",e.date()),t.assign("month",e.month()+1),t.assign("year",e.year())}function a9(t,e){t.assign("hour",e.hour()),t.assign("minute",e.minute()),t.assign("second",e.second()),t.assign("millisecond",e.millisecond()),t.get("hour")<12?t.assign("meridiem",Lr.AM):t.assign("meridiem",Lr.PM)}function sP(t,e){t.imply("day",e.date()),t.imply("month",e.month()+1),t.imply("year",e.year())}function uR(t,e){t.imply("hour",e.hour()),t.imply("minute",e.minute()),t.imply("second",e.second()),t.imply("millisecond",e.millisecond())}var hxe=N(i_(),1);var M4t={ACDT:630,ACST:570,ADT:-180,AEDT:660,AEST:600,AFT:270,AKDT:-480,AKST:-540,ALMT:360,AMST:-180,AMT:-240,ANAST:720,ANAT:720,AQTT:300,ART:-180,AST:-240,AWDT:540,AWST:480,AZOST:0,AZOT:-60,AZST:300,AZT:240,BNT:480,BOT:-240,BRST:-120,BRT:-180,BST:60,BTT:360,CAST:480,CAT:120,CCT:390,CDT:-300,CEST:120,CET:{timezoneOffsetDuringDst:2*60,timezoneOffsetNonDst:60,dstStart:t=>OYe(t,uf.MARCH,Is.SUNDAY,2),dstEnd:t=>OYe(t,uf.OCTOBER,Is.SUNDAY,3)},CHADT:825,CHAST:765,CKT:-600,CLST:-180,CLT:-240,COT:-300,CST:-360,CT:{timezoneOffsetDuringDst:-5*60,timezoneOffsetNonDst:-6*60,dstStart:t=>s_(t,uf.MARCH,Is.SUNDAY,2,2),dstEnd:t=>s_(t,uf.NOVEMBER,Is.SUNDAY,1,2)},CVT:-60,CXT:420,ChST:600,DAVT:420,EASST:-300,EAST:-360,EAT:180,ECT:-300,EDT:-240,EEST:180,EET:120,EGST:0,EGT:-60,EST:-300,ET:{timezoneOffsetDuringDst:-4*60,timezoneOffsetNonDst:-5*60,dstStart:t=>s_(t,uf.MARCH,Is.SUNDAY,2,2),dstEnd:t=>s_(t,uf.NOVEMBER,Is.SUNDAY,1,2)},FJST:780,FJT:720,FKST:-180,FKT:-240,FNT:-120,GALT:-360,GAMT:-540,GET:240,GFT:-180,GILT:720,GMT:0,GST:240,GYT:-240,HAA:-180,HAC:-300,HADT:-540,HAE:-240,HAP:-420,HAR:-360,HAST:-600,HAT:-90,HAY:-480,HKT:480,HLV:-210,HNA:-240,HNC:-360,HNE:-300,HNP:-480,HNR:-420,HNT:-150,HNY:-540,HOVT:420,ICT:420,IDT:180,IOT:360,IRDT:270,IRKST:540,IRKT:540,IRST:210,IST:330,JST:540,KGT:360,KRAST:480,KRAT:480,KST:540,KUYT:240,LHDT:660,LHST:630,LINT:840,MAGST:720,MAGT:720,MART:-510,MAWT:300,MDT:-360,MESZ:120,MEZ:60,MHT:720,MMT:390,MSD:240,MSK:180,MST:-420,MT:{timezoneOffsetDuringDst:-6*60,timezoneOffsetNonDst:-7*60,dstStart:t=>s_(t,uf.MARCH,Is.SUNDAY,2,2),dstEnd:t=>s_(t,uf.NOVEMBER,Is.SUNDAY,1,2)},MUT:240,MVT:300,MYT:480,NCT:660,NDT:-90,NFT:690,NOVST:420,NOVT:360,NPT:345,NST:-150,NUT:-660,NZDT:780,NZST:720,OMSST:420,OMST:420,PDT:-420,PET:-300,PETST:720,PETT:720,PGT:600,PHOT:780,PHT:480,PKT:300,PMDT:-120,PMST:-180,PONT:660,PST:-480,PT:{timezoneOffsetDuringDst:-7*60,timezoneOffsetNonDst:-8*60,dstStart:t=>s_(t,uf.MARCH,Is.SUNDAY,2,2),dstEnd:t=>s_(t,uf.NOVEMBER,Is.SUNDAY,1,2)},PWT:540,PYST:-180,PYT:-240,RET:240,SAMT:240,SAST:120,SBT:660,SCT:240,SGT:480,SRT:-180,SST:-660,TAHT:-600,TFT:300,TJT:300,TKT:780,TLT:540,TMT:300,TVT:720,ULAT:480,UTC:0,UYST:-120,UYT:-180,UZT:300,VET:-210,VLAST:660,VLAT:660,VUT:660,WAST:120,WAT:60,WEST:60,WESZ:60,WET:0,WEZ:0,WFT:720,WGST:-120,WGT:-180,WIB:420,WIT:540,WITA:480,WST:780,WT:0,YAKST:600,YAKT:600,YAPT:600,YEKST
tags: ${JSON.stringify(Array.from(this._tags).sort())},
knownValues: ${JSON.stringify(this.knownValues)},
impliedValues: ${JSON.stringify(this.impliedValues)}},
reference: ${JSON.stringify(this.reference)}]`}dayjs(){return(0,_z.default)(this.date())}date(){let e=this.dateWithoutTimezoneAdjustment(),n=this.reference.getSystemTimezoneAdjustmentMinute(e,this.get("timezoneOffset"));return new Date(e.getTime()+n*6e4)}addTag(e){return this._tags.add(e),this}addTags(e){for(let n of e)this._tags.add(n);return this}tags(){return new Set(this._tags)}dateWithoutTimezoneAdjustment(){let e=new Date(this.get("year"),this.get("month")-1,this.get("day"),this.get("hour"),this.get("minute"),this.get("second"),this.get("millisecond"));return e.setFullYear(this.get("year")),e}static createRelativeFromReference(e,n){let r=(0,_z.default)(e.instant);for(let i in n)r=r.add(n[i],i);let o=new t(e);return n.hour||n.minute||n.second?(a9(o,r),dh(o,r),e.timezoneOffset!==null&&o.assign("timezoneOffset",-e.instant.getTimezoneOffset())):(uR(o,r),e.timezoneOffset!==null&&o.imply("timezoneOffset",-e.instant.getTimezoneOffset()),n.d?(o.assign("day",r.date()),o.assign("month",r.month()+1),o.assign("year",r.year())):n.week?(o.assign("day",r.date()),o.assign("month",r.month()+1),o.assign("year",r.year()),o.imply("weekday",r.day())):(o.imply("day",r.date()),n.month?(o.assign("month",r.month()+1),o.assign("year",r.year())):(o.imply("month",r.month()+1),n.year?o.assign("year",r.year()):o.imply("year",r.year())))),o}},Tv=class t{constructor(e,n,r,o,i){this.reference=e,this.refDate=e.instant,this.index=n,this.text=r,this.start=o||new Dr(e),this.end=i}clone(){let e=new t(this.reference,this.index,this.text);return e.start=this.start?this.start.clone():null,e.end=this.end?this.end.clone():null,e}date(){return this.start.date()}tags(){let e=new Set(this.start.tags());if(this.end)for(let n of this.end.tags())e.add(n);return e}toString(){let e=Array.from(this.tags()).sort();return`[ParsingResult {index: ${this.index}, text: '${this.text}', tags: ${JSON.stringify(e)} ...}]`}};function gxe(t,e,n="\\s{0,5},?\\s{0,5}"){let r=e.replace(/\((?!\?)/g,"(?:");return`${t}${r}(?:${n}${r}){0,10}`}function N4t(t){let e;return t instanceof Array?e=[...t]:t instanceof Map?e=Array.from(t.keys()):e=Object.keys(t),e}function kl(t){return`(?:${N4t(t).sort((n,r)=>r.length-n.length).join("|").replace(/\./g,"\\.")})`}var LYe=N(i_(),1);function c9(t){return t<100&&(t>50?t=t+1900:t=t+2e3),t}function l_(t,e,n){let r=(0,LYe.default)(t),o=r;o=o.month(n-1),o=o.date(e),o=o.year(r.year());let i=o.add(1,"y"),s=o.add(-1,"y");return Math.abs(i.diff(r))<Math.abs(o.diff(r))?o=i:Math.abs(s.diff(r))<Math.abs(o.diff(r))&&(o=s),o.year()}var vxe={sunday:0,sun:0,"sun.":0,monday:1,mon:1,"mon.":1,tuesday:2,tue:2,"tue.":2,wednesday:3,wed:3,"wed.":3,thursday:4,thurs:4,"thurs.":4,thur:4,"thur.":4,thu:4,"thu.":4,friday:5,fri:5,"fri.":5,saturday:6,sat:6,"sat.":6},xxe={january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12},Op={...xxe,jan:1,"jan.":1,feb:2,"feb.":2,mar:3,"mar.":3,apr:4,"apr.":4,jun:6,"jun.":6,jul:7,"jul.":7,aug:8,"aug.":8,sep:9,"sep.":9,sept:9,"sept.":9,oct:10,"oct.":10,nov:11,"nov.":11,dec:12,"dec.":12},yxe={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12},wxe={first:1,second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,tenth:10,eleventh:11,twelfth:12,thirteenth:13,fourteenth:14,fifteenth:15,sixteenth:16,seventeenth:17,eighteenth:18,nineteenth:19,twentieth:20,"twenty first":21,"twenty-first":21,"twenty second":22,"twenty-second":22,"twenty third":23,"twenty-third":23,"twenty fourth":24,"twenty-fourth":24,"twenty fifth":25,"twenty-fifth":25,"twenty sixth":26,"twenty-sixth":26,"twenty seventh":27,"twenty-seventh":27,"twenty eighth":28,"twenty-eighth":28,"twenty ninth":29,"twenty-ninth":29,thirtieth:30,"thirty first":31,"thirty-first":31},$Ye={second:"second",seconds:"second",minute:"minute",minutes:"minute",hour:"hour",hours:"hour",day:"d",days:"d",week:"week",weeks:"week",month:"month",months:"month",quarter:"quarter",quarters:"quarter",year:"year",years:"year"},Sz={s:"second",sec:"second",second:"second",seconds:"second",m:"minute"
EXAMPLES OF CORRECT USAGE:
- "what time is it" \u2192 No parameter (uses local time)
- "what time is it in Tokyo" \u2192 timezoneOffset: "+9"
- "what time is it in Beijing" \u2192 timezoneOffset: "+8"
- "what time is it in New York" \u2192 timezoneOffset: "-5" (or "-4" during DST)
- "what time is it in Mumbai" \u2192 timezoneOffset: "+5:30"
SUPPORTED FORMATS:
- Simple: "+8", "-5", "+5:30"
- With prefix: "UTC+8", "GMT-5", "UTC+5:30"
COMMON TIMEZONE OFFSETS:
- Tokyo: UTC+9
- Beijing/Singapore: UTC+8
- Mumbai: UTC+5:30
- Dubai: UTC+4
- London: UTC+0 (UTC+1 during BST)
- New York: UTC-5 (UTC-4 during DST)
- Los Angeles: UTC-8 (UTC-7 during DST)`)}),func:async({timezoneOffset:t})=>zVt(t)}),PZe={jan:1,january:1,feb:2,february:2,mar:3,march:3,apr:4,april:4,may:5,jun:6,june:6,jul:7,july:7,aug:8,august:8,sep:9,sept:9,september:9,oct:10,october:10,nov:11,november:11,dec:12,december:12};function jVt(t,e){let n=t.match(/^(last|past|previous|prior)\s+(\d+)\s+(days?|weeks?|months?|years?)$/i);if(!n)return;let[,,r,o]=n,i=parseInt(r);if(i<=0)return;let s=o.replace(/s$/,""),a=e.startOf("day");return{start:a.minus({[s+"s"]:i}),end:a}}function VVt(t,e){switch(t){case"yesterday":return{start:e.minus({days:1}).startOf("day"),end:e.minus({days:1}).endOf("day")};case"last week":return{start:e.minus({weeks:1}).startOf("week"),end:e.minus({weeks:1}).endOf("week")};case"this week":return{start:e.startOf("week"),end:e.endOf("week")};case"next week":return{start:e.plus({weeks:1}).startOf("week"),end:e.plus({weeks:1}).endOf("week")};case"last month":return{start:e.minus({months:1}).startOf("month"),end:e.minus({months:1}).endOf("month")};case"this month":return{start:e.startOf("month"),end:e.endOf("month")};case"next month":return{start:e.plus({months:1}).startOf("month"),end:e.plus({months:1}).endOf("month")};case"last year":return{start:e.minus({years:1}).startOf("year"),end:e.minus({years:1}).endOf("year")};case"this year":return{start:e.startOf("year"),end:e.endOf("year")};case"next year":return{start:e.plus({years:1}).startOf("year"),end:e.plus({years:1}).endOf("year")};case"last quarter":return{start:e.minus({quarters:1}).startOf("quarter"),end:e.minus({quarters:1}).endOf("quarter")};case"this quarter":return{start:e.startOf("quarter"),end:e.endOf("quarter")};case"next quarter":return{start:e.plus({quarters:1}).startOf("quarter"),end:e.plus({quarters:1}).endOf("quarter")}}}function WVt(t,e){let n=t.match(/(?:the\s+)?week\s+of\s+(.+)/i);if(!n)return;let r=n[1],o=Pxe(r,e.toJSDate(),{forwardDate:!1});if(o.length===0)return;let i=hn.fromJSDate(o[0].start.date()).startOf("week"),s=i.endOf("week");return i>e&&(i=i.minus({years:1}),s=s.minus({years:1})),{start:i,end:s}}function HVt(t,e){let n=t.match(/^(jan|january|feb|february|mar|march|apr|april|may|jun|june|jul|july|aug|august|sep|sept|september|oct|october|nov|november|dec|december)$/i);if(!n)return;let r=PZe[n[1]],o=e.year;r>e.month&&o--;let i=hn.fromObject({year:o,month:r,day:1}),s=i.endOf("month");return i>e&&(i=i.minus({years:1}),s=s.minus({years:1})),{start:i,end:s}}function KVt(t,e){let n=t.match(/^(?:(?:the\s+)?(?:year|yr)(?:\s+(?:of|in))?\s+)?(\d{4})$/i);if(!n)return;let r=parseInt(n[1]),o=hn.fromObject({year:r,month:1,day:1}),i=hn.fromObject({year:r,month:12,day:31});return o>e&&(o=o.minus({years:1}),i=i.minus({years:1})),{start:o,end:i}}function qVt(t,e){let n=t.match(/^(?:(?:q|Q)(\d{1})\s+(\d{4})|(\d{4})\s+(?:q|Q)(\d{1}))$/),r=t.match(/^(?:q|Q)(\d{1})$/),o,i;if(n)o=parseInt(n[1]||n[4]),i=parseInt(n[2]||n[3]);else if(r){o=parseInt(r[1]),i=e.year;let c=Math.floor((e.month-1)/3)+1;o>c&&i--}else return;if(o<1||o>4)return;let s=(o-1)*3+1,a=hn.fromObject({year:i,month:s,day:1}).startOf("day"),l=a.plus({months:3}).minus({days:1}).endOf("day");return a>e&&(a=a.minus({years:1}),l=l.minus({years:1})),{start:a,end:l}}function GVt(t,e){let n=t.match(/^(jan|january|feb|february|mar|march|apr|april|may|jun|june|jul|july|aug|august|sep|sept|september|oct|october|nov|november|dec|december)\s+(\d{4})$/i);if(!n)return;let r=PZe[n[1].toLowerCase()],o=parseInt(n[2]),i=hn.fromObject({year:o,month:r,day:1}).startOf("day"),s=i.endOf("month");return i>e&&(i=i.minus({years:1}),s=s.minus({years:1})),{start:i,end:s}}function YVt(t){let e=hn.now(),n=t.toLowerCase().replace("@vault","").trim(),r=jVt(n,e)||VVt(n,e)||WVt(n,e)||HVt(n,e)||GVt(n,e)||qVt(n,e)||KVt(n,e);if(r)return{startTime:r.start.toMillis(),endTime:r.end.toMillis()};let o=Pxe(t,e.toJSDate(),{forwardDate:!1});if(o.length>0){let i=hn.fromJSDate(o[0].start.date()).startOf("day"),s=o[0].end?hn.fromJSDate(o[0].end.date()).endOf("day"):i.endOf("day");return i>e&&(i.minus({years:1}),s.minus({years:1})),{startTime:i.toMillis(),endTime:s.toMillis()}}consol
COMMON EXPRESSIONS:
- Relative past: "yesterday", "last week", "last month", "last year"
- Relative ranges: "this week", "this month", "this year"
- Specific dates: "July 1", "July 1 2023", "2023-07-01"
- Date ranges: "from July 1 to July 15", "between May and June"
- Time periods: "last 7 days", "past 30 days", "previous 3 months"
IMPORTANT: This tool is typically used as the first step before localSearch when searching notes by time.
EXAMPLE WORKFLOW:
1. User: "what did I do last week"
2. First call getTimeRangeMs with timeExpression: "last week"
3. Then use the returned time range with localSearch`)}),func:async({timeExpression:t})=>{let e=YVt(t);return e||{error:`Unable to parse time expression: ${t}`}}});function JVt(t){let e=t.toString().length===10?t*1e3:t,n=hn.fromMillis(e);return ZVt(n)}var AZe=Rr({name:"getTimeInfoByEpoch",description:"Convert a Unix timestamp (in seconds or milliseconds) to detailed time information",schema:we.object({epoch:we.number().describe("Unix timestamp in seconds or milliseconds")}),func:async({epoch:t})=>JVt(t)});async function XVt(t,e,n){let r=Exe(e),o=Exe(n);try{let i=hn.now().setZone(r),s=TZe(t,i.toJSDate());if(!s)throw new Error(`Could not parse time: ${t}`);let a=hn.fromJSDate(s,{zone:r}),l=a.setZone(o);if(!l.isValid)throw new Error("Invalid timezone conversion");let c=l.toJSDate(),u=l.offset;return{epoch:Math.floor(c.getTime()),isoString:c.toISOString(),userLocaleString:l.toLocaleString(hn.DATETIME_FULL),localDateString:l.toISODate()||"",timezoneOffset:u,timezone:l.offsetNameShort||o,originalTime:a.toLocaleString(hn.TIME_SIMPLE)+" "+a.offsetNameShort,convertedTime:l.toLocaleString(hn.TIME_SIMPLE)+" "+l.offsetNameShort}}catch(i){throw new Error(`Failed to convert time: ${i.message}`)}}var kZe=Rr({name:"convertTimeBetweenTimezones",description:"Convert a specific time from one timezone to another using UTC offsets",schema:we.object({time:we.string().describe(`Time to convert. Supports various formats:
- 12-hour: "6pm", "3:30 PM", "11:45 am"
- 24-hour: "18:00", "15:30", "23:45"
- Relative: "noon", "midnight"`),fromOffset:we.string().describe(`Source UTC offset. Must be numeric, not timezone name.
Examples: "-8" for PT, "+0" for London, "+8" for Beijing`),toOffset:we.string().describe(`Target UTC offset. Must be numeric, not timezone name.
Examples: "+9" for Tokyo, "-5" for NY, "+5:30" for Mumbai
EXAMPLE USAGE:
- "what time is 6pm PT in Tokyo" \u2192 time: "6pm", fromOffset: "-8", toOffset: "+9"
- "convert 3:30 PM EST to London time" \u2192 time: "3:30 PM", fromOffset: "-5", toOffset: "+0"
- "what is 9am Beijing time in New York" \u2192 time: "9am", fromOffset: "+8", toOffset: "-5"`)}),func:async({time:t,fromOffset:e,toOffset:n})=>XVt(t,e,n)});Zg();ns();Se();qe();var MZe=5e4,NZe=Rr({name:"youtubeTranscription",description:"Get transcripts of YouTube videos when the user provides YouTube URLs",schema:we.object({_userMessageContent:we.string().optional().describe("Internal: user message content injected by the system")}),func:async t=>{let{_userMessageContent:e}=t;if(typeof e!="string")return{success:!1,message:"Invalid input: User message must be a string"};if(e.length>MZe)return{success:!1,message:`Input too long: Maximum allowed length is ${MZe} characters`};let n=FAe(e);if(n.length===0)return{success:!1,message:"No YouTube URLs found in the user prompt. URLs must be in the user prompt instead of the context notes."};let r=await Promise.all(n.map(async i=>{try{let s=pc()&&q().supadataApiKey?await gG(i):await di.getInstance().youtube4llm(i);return s.response.transcript?{url:i,success:!0,transcript:s.response.transcript,elapsed_time_ms:s.elapsed_time_ms}:{url:i,success:!1,message:"Transcript not available. Only English videos with auto transcript enabled are supported"}}catch(s){return console.error(`Error transcribing YouTube video ${i}:`,s),{url:i,success:!1,message:"An error occurred while transcribing the YouTube video"}}}));return{success:r.some(i=>i.success),results:r,total_urls:n.length}}});var QVt=[{tool:i9,metadata:{id:"localSearch",displayName:"Vault Search",description:"Search through your vault notes",category:"search",copilotCommands:["@vault"],customPromptInstructions:`For localSearch (searching notes based on their contents in the vault):
- You MUST always provide both "query" (string) and "salientTerms" (array of strings)
- salientTerms MUST be extracted from the user's original query - never invent new terms
- They are keywords used for BM25 full-text search to find notes containing those exact words
- Treat every token that begins with "#" as a high-priority salient term. Keep the leading "#" and the full tag hierarchy (e.g., "#project/phase1").
- Include tagged terms alongside other meaningful words; never strip hashes or rewrite tags into plain words.
- Extract meaningful content words from the query (nouns, verbs, names, etc.)
- Exclude common words like "what", "I", "do", "the", "a", etc.
- Exclude time expressions like "last month", "yesterday", "last week"
- Preserve the original language - do NOT translate terms to English
Evaluating search results and re-searching:
- Results include a relevance quality summary: high (score \u22650.7), medium (0.3-0.7), low (<0.3)
- If most results are low relevance or miss key concepts from the user's question:
1. Try searching again with synonyms or related terms
2. Use more specific phrasing if query was too broad
3. Use more general phrasing if query was too narrow
- Example: "machine learning algorithms" returned low results \u2192 try "ML models", "neural networks", or "AI techniques"
Examples:
- Query "piano learning practice" \u2192 query: "piano learning practice", salientTerms: ["piano", "learning", "practice"]
- Query "#projectx status update" \u2192 query: "#projectx status update", salientTerms: ["#projectx", "status", "update"]
- Query "\u94A2\u7434\u5B66\u4E60" (Chinese) \u2192 query: "\u94A2\u7434\u5B66\u4E60", salientTerms: ["\u94A2\u7434", "\u5B66\u4E60"] (preserve original language)
For time-based searches (e.g., "what did I do last week"):
1. First call getTimeRangeMs with timeExpression: "last week"
2. Then use localSearch with the returned timeRange, query matching the user's question, and salientTerms: [] (empty for generic time queries)
For time-based searches with meaningful terms (e.g., "python debugging notes from yesterday"):
1. First call getTimeRangeMs with timeExpression: "yesterday"
2. Then use localSearch with the returned timeRange, query: "python debugging notes", salientTerms: ["python", "debugging", "notes"]
For broad searches:
- If the user wants a comprehensive list, use getFileTree to get all note titles as reference. This helps verify search completeness and identify notes the search may have missed.`}},{tool:s9,metadata:{id:"webSearch",displayName:"Web Search",description:"Search the INTERNET (NOT vault notes) when user explicitly asks for web/online information",category:"search",copilotCommands:["@websearch","@web"],customPromptInstructions:`For webSearch:
- ONLY use when the user's query contains explicit web-search intent like:
* "web search", "internet search", "online search"
* "Google", "search online", "look up online", "search the web"
- Always provide an empty chatHistory array
Example: "search the web for python tutorials" \u2192 query: "python tutorials", chatHistory: []`}},{tool:IZe,metadata:{id:"getCurrentTime",displayName:"Get Current Time",description:"Get the current time in any timezone",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For time queries (IMPORTANT: Always use UTC offsets, not timezone names):
- If the user mentions a specific city, country, or timezone name (e.g., "Tokyo", "Japan", "JST"), you MUST convert it to the correct UTC offset and pass it via the timezoneOffset parameter (e.g., "+9").
- Only omit timezoneOffset when the user asks for the current local time without naming any location or timezone.
- If you cannot confidently determine the offset from the user request, ask the user to clarify before calling the tool.
Examples:
- "what time is it" (local time) \u2192 call with no parameters
- "what time is it in Tokyo" (UTC+9) \u2192 timezoneOffset: "+9"
- "what time is it in New York" (UTC-5 or UTC-4 depending on DST) \u2192 timezoneOffset: "-5"`}},{tool:AZe,metadata:{id:"getTimeInfoByEpoch",displayName:"Get Time Info",description:"Convert epoch timestamp to human-readable format",category:"time",isAlwaysEnabled:!0}},{tool:EZe,metadata:{id:"getTimeRangeMs",displayName:"Get Time Range",description:"Convert time expressions to date ranges",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For time-based queries:
- Use this tool to convert time expressions like "last week", "yesterday", "last month" to proper time ranges
- This is typically the first step before using localSearch with a time range
Example: For "last week" \u2192 timeExpression: "last week"`}},{tool:kZe,metadata:{id:"convertTimeBetweenTimezones",displayName:"Convert Timezones",description:"Convert time between different timezones",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For timezone conversions:
Example: "what time is 6pm PT in Tokyo" (PT is UTC-8 or UTC-7, Tokyo is UTC+9) \u2192 time: "6pm", fromOffset: "-8", toOffset: "+9"`}},{tool:hYe,metadata:{id:"readNote",displayName:"Read Note",description:"Read a specific note in sequential chunks using its own line-chunking logic.",category:"file",requiresVault:!0,isAlwaysEnabled:!0,customPromptInstructions:`For readNote:
- Decide based on the user's request: only call this tool when the question requires reading note content.
- If the user asks about a note title that is already mentioned in the current or previous turns of the conversation, or linked in <active_note> or <note_context> blocks, call readNote directly\u2014do not use localSearch to look it up. Even if the note title mention is partial but similar to what you have seen in the context, try to infer the correct note path from context. Skip the tool when a note is irrelevant to the user query.
- If the user asks about notes linked from that note, read the original note first, then follow the "linkedNotes" paths returned in the tool result to inspect those linked notes.
- Always start with chunk 0 (omit chunkIndex or set it to 0). Only request the next chunk if the previous chunk did not answer the question.
- Pass vault-relative paths without a leading slash. If a call fails, adjust the path (for example, add ".md" or use an alternative candidate) and retry only if necessary.
- Every tool result may include a "linkedNotes" array. If the user needs information from those linked notes, call readNote again with one of the provided candidate paths, starting again at chunk 0. Do not expand links you don't need.
- Stop calling readNote as soon as you have the required information.
- Always call getFileTree to get the exact note path if it is not provided in the context before calling readNote.
Examples:
- First chunk: notePath: "Projects/launch-plan.md" (chunkIndex omitted or 0)
- Next chunk: notePath: "Projects/launch-plan.md", chunkIndex: 1`}},{tool:t9,metadata:{id:"writeFile",displayName:"Write to File",description:"Create or rewrite files in your vault",category:"file",requiresVault:!0,timeoutMs:0,copilotCommands:["@composer"],customPromptInstructions:`For writeFile:
- NEVER display the file content directly in your response
- Always pass the complete file content to the tool
- Include the full path to the file
- You MUST explicitly call writeFile for any intent of updating or creating files
- Do not call writeFile tool again if the result is not accepted
- Do not call writeFile tool if no change needs to be made
- Always create new notes in root folder or folders the user explicitly specifies
- When creating a new note in a folder, you MUST use getFileTree to get the exact folder path first
Examples:
- Basic: path: "path/to/note.md", content: "FULL CONTENT OF THE NOTE"
- Skip confirmation: path: "path/to/note.md", content: "FULL CONTENT", confirmation: false`}},{tool:lYe,metadata:{id:"editFile",displayName:"Edit File",description:"Make a targeted, single-match edit to an existing file",category:"file",requiresVault:!0,timeoutMs:0,customPromptInstructions:`For editFile:
- Use for targeted edits; use writeFile for major rewrites or new files
- oldText must uniquely identify the location \u2014 include surrounding context lines if needed
- The tool automatically handles minor whitespace/quote differences (fuzzy matching)
- Call once per edit; for multiple edits call the tool multiple times
Example: Add "Bob Johnson" to attendees in notes/meeting.md:
path: "notes/meeting.md"
oldText: "## Attendees\\n- John Smith\\n- Jane Doe"
newText: "## Attendees\\n- John Smith\\n- Jane Doe\\n- Bob Johnson"`}},{tool:NZe,metadata:{id:"youtubeTranscription",displayName:"YouTube Transcription",description:"Get transcripts from YouTube videos",category:"media",isPlusOnly:!0,requiresUserMessageContent:!0,customPromptInstructions:`For youtubeTranscription:
- Use when user provides YouTube URLs
- No parameters needed - the tool will process URLs from the conversation`}}];function eWt(t){Vi.getInstance().register({tool:mYe(t.getRoot()),metadata:{id:"getFileTree",displayName:"File Tree",description:"Browse vault file structure",category:"file",isAlwaysEnabled:!0,requiresVault:!0,isBackground:!0,customPromptInstructions:`For getFileTree:
- Use to browse the vault's file structure including paths of notes and folders
- Always call this tool to explore the exact path of notes or folders when you are not given the exact path.
- DO NOT use this tool to look up note contents or metadata - use localSearch or readNote instead.
- No parameters needed
Example queries that should use getFileTree:
- "Create a new note in the projects folder" \u2192 call getFileTree to get the exact folder path
- "Create a new note using the quick note template" \u2192 call getFileTree to look up the template path
- "How many files are in the projects folder" \u2192 call getFileTree to list all files`}})}function tWt(){Vi.getInstance().register({tool:kYe(),metadata:{id:"getTagList",displayName:"Tag List",description:"List vault tags with occurrence statistics",category:"file",isAlwaysEnabled:!0,requiresVault:!0,isBackground:!0,customPromptInstructions:`For getTagList:
- Use to inspect existing tags before suggesting new ones or reorganizing notes.
- Omit parameters to include both frontmatter and inline tags.
- Set includeInline to false when you only need frontmatter-defined tags.
- Use maxEntries to limit output for very large vaults.
Examples:
- Default (all tags): call with no parameters
- Frontmatter only: includeInline: false`}})}function nWt(){Vi.getInstance().register({tool:n9,metadata:{id:"updateMemory",displayName:"Update Memory",description:"Save information to user memory when the user explicitly asks to remember something or update the memory",category:"memory",copilotCommands:["@memory"],isAlwaysEnabled:!0,customPromptInstructions:`For updateMemory:
- Use this tool to update the memory when the user explicitly asks to update the memory
- DO NOT use for general information - only for personal facts, preferences, or specific things the user wants stored
Example: statement: "I'm studying Japanese and I'm preparing for JLPT N3"`}})}function rWt(){let t=Vi.getInstance();t.register({tool:yYe,metadata:{id:"obsidianDailyNote",displayName:"Daily Note",description:"Create or read today's daily note, or get its path",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianDailyNote:
- Use for daily note operations: creating, reading content, or getting the file path.
- Use readNote for reading specific notes by path. Use obsidianDailyNote only for today's daily note.
- daily \u2014 create today's daily note. Applies the user's configured daily note template automatically. Use this when the user asks to create or set up today's daily note.
- daily:read \u2014 read today's daily note content.
- daily:path \u2014 get the vault-relative file path (useful for follow-up readNote calls).
- For past or future daily notes (e.g. "yesterday's daily note"): NEVER ask the user for the date \u2014 use the time tools. Workflow: (1) call getCurrentTime to resolve the date, (2) call daily:path to discover the date format and folder, (3) call obsidianTemplates with command=templates to list available template names, then call template:read with the name that matches (e.g. "Daily Note Template"), (4) use writeFile to create the note at the resolved path with the template content, replacing variables like {{date}} with the target date. If templates returns an error or no daily template is found, ask the user for their template path and use readNote to read it.
- To add content to a daily note, use writeFile or editFile.
- Use \\n for newlines and \\t for tabs in content strings.
- For arbitrary file writes beyond daily notes, use writeFile or editFile instead.
- If the user names a specific vault, pass it using the vault parameter.`}}),t.register({tool:gYe,metadata:{id:"obsidianRandomRead",displayName:"Random Note",description:"Read a random note using the official Obsidian CLI",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianRandomRead:
- Use when the user explicitly asks for a random note or random note content.
- If the user names a specific vault, pass it using the vault parameter.
- Do not use when the user asks for a specific note; use readNote/getFileTree for specific targets.`}}),t.register({tool:wYe,metadata:{id:"obsidianProperties",displayName:"Properties",description:"Read frontmatter properties from notes or list all property names in the vault",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianProperties:
- Use to inspect frontmatter properties across the vault or within a specific note.
- properties (no file/path): list all property names used vault-wide. Add counts=true for occurrence counts. Add sort=count to sort by frequency.
- properties with file= or path=: list that note's key-value property pairs.
- property:read: read a single property value from a specific note. Requires name parameter.
- file= resolves like a wikilink (name only, no path or extension). path= uses exact vault-relative path.
- Do not use for full note content \u2014 use readNote for that.
- To modify properties, use writeFile or editFile to update the frontmatter YAML.`}}),t.register({tool:vYe,metadata:{id:"obsidianTasks",displayName:"Tasks",description:"List tasks across the vault with filters for status, file, and daily note",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianTasks:
- ALWAYS use this tool when the user asks about tasks, todos, or checkboxes. Do NOT use localSearch for task queries.
- Use to list and filter tasks across the vault.
- todo=true: show only incomplete tasks. done=true: show only completed tasks.
- status="x": filter by specific status character (e.g., "/" for in-progress, "x" for done, " " for open).
- daily=true: show tasks from today's daily note only.
- verbose=true: group tasks by file with line numbers.
- total=true: return only the task count.
- file= resolves like a wikilink (name only). path= uses exact vault-relative path.
- For time-based task queries (e.g. "tasks from last month"): use verbose=true to get tasks grouped by file, then filter results by file dates or daily note filenames to match the time range.`}}),t.register({tool:xYe,metadata:{id:"obsidianLinks",displayName:"Links",description:"Query the vault link graph: backlinks, outgoing links, orphans, unresolved",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianLinks:
- Use to explore the vault's link graph.
- backlinks: list notes that link TO a given file. Use file= or path= to target a note. Add counts=true for link counts.
- links: list outgoing links FROM a given file. Use file= or path= to target a note.
- orphans: list all notes with no incoming links. Use total=true for just the count. Add all=true to include non-markdown files.
- unresolved: list wikilinks that don't resolve to any existing file. Use counts=true for occurrence counts, verbose=true to see source files.
- file= resolves like a wikilink (name only). path= uses exact vault-relative path. Without either, targets the active file.`}}),t.register({tool:bYe,metadata:{id:"obsidianTemplates",displayName:"Templates",description:"List available templates or read template content",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianTemplates:
- Use 'templates' to list all available templates when you need to find the right template for a task.
- Use 'template:read' with a template name to get its content with variables resolved. Requires name parameter.
- This is useful for creating daily notes from templates \u2014 read the template first, then use writeFile to populate the note.`}}),t.register({tool:CYe,metadata:{id:"obsidianBases",displayName:"Bases",description:"List Base files, views, query data, or create new items in Obsidian Bases",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianBases:
- Use to explore and manage structured data in Obsidian Base (.base) database files.
- bases: list all Base files in the vault. Use total=true for just the count.
- base:views: list the views defined in a Base file. Requires file= or path=.
- base:query: query data from a specific Base view. Requires file= or path=, optionally view= and format= (e.g., format=csv).
- base:create: create a new item (row) in a Base. Requires file= or path=. Optional: view= (target view), name= (file name for the item), content= (initial note content).
- The created item appears as a new note that matches the Base's filter criteria.
- Use base:query first to understand the Base's structure and existing data before creating items.
- If the Base filters by a specific tag or folder, ensure the new item will match those filters.
Base file YAML reference (for creating new .base files with writeFile):
- filters: MUST be either a single string OR an object with and/or/not keys. NEVER use a bare YAML list.
- Single filter: filters: 'file.hasTag("book")'
- Multiple filters: filters: { and: ['file.hasTag("book")', 'status == "reading"'] }
- Negation: filters: { not: ['file.hasTag("archived")'] }
- Bare lists like "filters: - 'expr'" are INVALID and will cause parse errors.
- formulas: computed properties. Functions: date(), now(), today(), if(cond, true, false), duration(). Duration fields: .days, .hours, .minutes. Example: days_left: 'if(due, (date(due) - today()).days, "")'
- properties: display config per property (displayName, width, hidden).
- views: table (default), cards, list, or map. Each view can have its own filters, order (property display list), groupBy, summaries.
- Property types: note properties (from frontmatter), file properties (file.name, file.mtime, file.ctime, file.tags, file.links, file.backlinks), formula properties (formula.my_formula).
- YAML quoting: single-quote formulas containing double quotes: 'if(done, "Yes", "No")'. Quote strings with special chars (:, {, }, [, ]).
- Embed in notes with ![[MyBase.base]] or ![[MyBase.base#View Name]].
- VALIDATION: After creating or editing a .base file, ALWAYS call obsidianBases with base:views to verify it parses correctly. If it returns an error, fix the YAML with writeFile and re-validate. Do not stop until validation passes.`}})}function yR(t){let e=Vi.getInstance(),n=q(),r=e.getToolMetadata("getFileTree")!==void 0,o=t!==void 0,i=e.getToolMetadata("updateMemory")!==void 0,s=n.enableSavedMemory;(e.getAllTools().length===0||r!==o||i!==s)&&(e.clear(),e.registerAll(QVt),t&&(eWt(t),tWt()),n.enableSavedMemory&&nWt(),nxe()&&rWt())}qe();qe();var h9=class{constructor(e,n){this.toolManager=e;this.writeFileTool=n;this.buffer=""}findCompleteBlock(e){let n=/<writeFile>[\s\S]*?<\/writeFile>/,r=e.match(n);return!r||r.index===void 0?null:{block:r[0],endIdx:r.index+r[0].length}}async*processChunk(e){let n="";if(Array.isArray(e.content))for(let o of e.content)o.type==="text"&&o.text!=null&&(n+=typeof o.text=="string"?o.text:"");else e.content!=null&&(n=typeof e.content=="string"?e.content:"");n&&(this.buffer+=n),yield e;let r=this.findCompleteBlock(this.buffer);for(;r;){let{block:o,endIdx:i}=r,s=o.match(/<path>([\s\S]*?)<\/path>/),a=o.match(/<content>([\s\S]*?)<\/content>/),l=s?s[1].trim():void 0,c=a?a[1].trim():void 0;try{let u=await this.toolManager.callTool(this.writeFileTool,{path:l,content:c}),d=_v.format("writeFile",u);yield{...e,content:`
${d}
`}}catch(u){yield{...e,content:`
Error: ${u?.message??String(u)}
`}}this.buffer=this.buffer.substring(i),r=this.findCompleteBlock(this.buffer)}}};ye();function OZe(t){if(!Array.isArray(t)||t.length===0)return{high:0,medium:0,low:0,total:0,averageScore:0};let e=0,n=0,r=0,o=0;for(let i of t){let s=i.rerank_score??i.score??0;o+=s,s>=.7?e++:s>=.3?n++:r++}return{high:e,medium:n,low:r,total:t.length,averageScore:o/t.length}}function RZe(t){let e=[];return t.high>0&&e.push(`${t.high} high`),t.medium>0&&e.push(`${t.medium} medium`),t.low>0&&e.push(`${t.low} low`),e.length===0?"[Relevance: no results]":`[Relevance: ${e.join(", ")}]`}function Axe(t){if(!Array.isArray(t))return"";let e=t.filter(r=>r.includeInContext!==!1);return e.length===0?"No relevant documents found.":e.map((r,o)=>{let i=r.title||"Untitled",s=r.path||"",a=r.__sourceId||r.collection_name||r.source_id||o+1,l=null;if(r.mtime){let c=new Date(r.mtime);isNaN(c.getTime())||(l=c.toISOString())}return`<document>
<id>${a}</id>
<title>${i}</title>${s&&s!==i?`
<path>${s}</path>`:""}${l?`
<modified>${l}</modified>`:""}
<content>
${r.content||""}
</content>
</document>`}).filter(r=>r.length>0).join(`
`)}function LZe(t){try{let e=JSON.parse(t);return Array.isArray(e)?Axe(e):"Invalid search results format."}catch(e){return ee("Failed to format localSearch result string:",e),"Error processing search results."}}function DZe(t){return Array.isArray(t)?t.map(e=>({title:e.title||e.path||"Untitled",path:e.path||e.title||"",score:e.rerank_score||e.score||0,explanation:e.explanation||null})):[]}function g9(t){if(typeof t=="number"){let e=new Date(t);return isNaN(e.getTime())?"":e.toISOString()}if(typeof t=="string"){let e=new Date(t);return isNaN(e.getTime())?"":e.toISOString()}return""}function oWt(t){if(!t)return"";let e=[],n=t;try{if(Array.isArray(n.lexicalMatches)&&n.lexicalMatches.length>0){let r=new Set,o=new Set;for(let a of n.lexicalMatches)typeof a?.field=="string"&&r.add(a.field),typeof a?.query=="string"&&o.add(a.query);let i=Array.from(r).join("/"),s=Array.from(o).slice(0,3).join(", ");e.push(`Lexical(${i}): ${s}${o.size>3?", ...":""}`)}if(typeof n.semanticScore=="number"&&n.semanticScore>0&&e.push(`Semantic: ${(n.semanticScore*100).toFixed(1)}%`),n.folderBoost&&typeof n.folderBoost.boostFactor=="number"){let r=n.folderBoost,o=r.folder||"root";e.push(`Folder +${r.boostFactor.toFixed(2)} (${o})`)}if(n.graphConnections&&typeof n.graphConnections=="object"){let r=n.graphConnections,o=[];(r.backlinks??0)>0&&o.push(`${r.backlinks} backlinks`),(r.coCitations??0)>0&&o.push(`${r.coCitations} co-cites`),(r.sharedTags??0)>0&&o.push(`${r.sharedTags} tags`),typeof r.score=="number"?e.push(`Graph ${r.score.toFixed(1)}${o.length?` (${o.join(", ")})`:""}`):o.length&&e.push(`Graph (${o.join(", ")})`)}if(n.graphBoost&&typeof n.graphBoost.boostFactor=="number"&&!n.graphConnections){let r=n.graphBoost;e.push(`Graph +${r.boostFactor.toFixed(2)} (${r.connections} connections)`)}typeof n.baseScore=="number"&&typeof n.finalScore=="number"&&n.baseScore!==n.finalScore&&e.push(`Score: ${n.baseScore.toFixed(4)}\u2192${n.finalScore.toFixed(4)}`)}catch{}return e.join(" | ")}function $Ze(t,e,n=1){let r=n,o=[];if(t.length>0){let i=t.map(s=>{let a=s.__sourceId||r++,l=s.title||"Untitled",c=s.path||"",u=s.matchType||s.source||"filter",d=g9(s.mtime);return`<document>
<id>${a}</id>
<title>${l}</title>
<path>${c}</path>
<matchType>${u}</matchType>${d?`
<modified>${d}</modified>`:""}
<content>
${s.content||""}
</content>
</document>`}).join(`
`);o.push(`<filterResults>
${i}
</filterResults>`)}if(e.length>0){let i=e.map(s=>{let a=s.__sourceId||r++,l=s.title||"Untitled",c=s.path||"",u=g9(s.mtime);return`<document>
<id>${a}</id>
<title>${l}</title>${c&&c!==l?`
<path>${c}</path>`:""}${u?`
<modified>${u}</modified>`:""}
<content>
${s.content||""}
</content>
</document>`}).join(`
`);o.push(`<searchResults>
${i}
</searchResults>`)}return o.length===0?"No relevant documents found.":o.join(`
`)}var iWt=new Set(["time-filtered","tag-match"]);function FZe(t){return!Array.isArray(t)||t.length===0?!1:t.every(e=>e.source!=null&&iWt.has(e.source))}function UZe(t){return Array.isArray(t)?t.some(e=>e.source==="time-filtered"):!1}function kxe(t,e=300){if(!Array.isArray(t)||t.length===0)return"";let n=t.map(r=>{let o=r.title||"Untitled",i=r.path||"",s=g9(r.mtime),l=rR(r.content||"").slice(0,e),c=i?`
<path>${i}</path>`:"",u=s?`
<modified>${s}</modified>`:"",d=l?`
<snippet>${l}</snippet>`:"";return`<file>
<title>${o}</title>${c}${u}${d}
</file>`}).join(`
`);return`<additionalMatches count="${t.length}" note="These results contain titles and metadata only. To read the full content of a note, call the readNote tool with its path.">
${n}
</additionalMatches>`}function BZe(t){if(!Array.isArray(t)||t.length===0){k("Search Results: (none)");return}let e=0,n=t.map(l=>{let c=g9(l.mtime),u=typeof l.rerank_score=="number"?l.rerank_score:l.score||0,d=(Number.isFinite(u)?u:0).toFixed(4),f=l.chunkId||l.path||"",p=oWt(l.explanation),m=l.includeInContext!==!1;return m&&e++,{path:f,in:m?"Y":"",mtime:c,score:d,explanation:p}}),r=n.length;k(`Search Results (debug table): ${r} rows; in-context ${e}/${r}`),HAe(n,["path","in","mtime","score","explanation"]);let o=l=>String(l||"").replace(/\|/g,"\\|"),i="| PATH | IN | MTIME | SCORE | EXPLANATION |",s="| --- | :-: | --- | ---: | --- |",a=n.map(l=>`| ${o(l.path)} | ${l.in} | ${l.mtime||""} | ${l.score} | ${o(l.explanation)} |`);jW(["",`Results: ${r} rows; in-context ${e}/${r}`,"",i,s,...a,""])}function zZe(t,e){return[t,e].map(r=>r?.trim()).filter(r=>!!r).join(`
`)}function jZe(t,e){let n=t?`
${t}
`:"";return`<localSearch${e?` timeRange="${e}"`:""}>${n}</localSearch>`}function Mxe(t,e){let n=t.trim();return n?`${n}
${e}`:e}function VZe(t,e){let n=e.trim();return!n||t.includes(n)?t:Mxe(t,`[User query]:
${n}`)}function WZe(t,e){let n=e?.trim();if(!n)return t;let o=t.lastIndexOf("[User query]:");if(o===-1){let a=t.trimEnd(),l=a.length>0?`
`:"";return`${a}${l}${n}`}let i=t.slice(0,o).trimEnd(),s=t.slice(o).trimStart();return`${i}
${n}
${s}`}function HZe(t){let e=[],n=0;for(;n<t.length;){let r=t.indexOf("![",n);if(r===-1)break;let o=lWt(t,r+2);if(o===null){n=r+2;continue}let i=o+1;for(;i<t.length&&y9(t[i]);)i++;if(t[i]!=="("){n=i;continue}let s=cWt(t,i);if(s===null){n=i+1;continue}let a=sWt(t.slice(i+1,s));a&&e.push(a),n=s+1}return e}function sWt(t){let e=t.trim();if(e.length===0)return null;if(e.startsWith("<")){let r=uWt(e,0);if(r===null)return null;let o=e.slice(1,r).trim();return o.length>0?o:null}let n=aWt(e).trim();return n.length>0?n:null}function aWt(t){let e=t.trimEnd();if(e.length===0)return"";let n=e[e.length-1];if(n==='"'||n==="'"){let o=dWt(e,n,e.length-1);if(o!==null){let i=e.slice(0,o);if(i.length>0&&y9(i[i.length-1]))return i.trimEnd()}}if(n===")"){let r=fWt(e);if(r!==null){let o=e.slice(0,r);if(o.length>0&&y9(o[o.length-1]))return o.trimEnd()}}return e}function lWt(t,e){let n=e,r=0;for(;n<t.length;){let o=t[n];if(o==="\\"){n+=2;continue}if(o==="["){r++,n++;continue}if(o==="]"){if(r===0)return n;r--,n++;continue}n++}return null}function cWt(t,e){let n=e+1,r=1,o=!0,i=!1;for(;n<t.length;){let s=t[n];if(i){if(s==="\\"){n+=2;continue}if(s===">"){i=!1,o=!1,n++;continue}n++;continue}if(o){if(y9(s)){n++;continue}if(s==="<"){i=!0,n++;continue}o=!1}if(s==="\\"){n+=2;continue}if(s==="("){r++,n++;continue}if(s===")"){if(r--,r===0)return n;n++;continue}n++}return null}function uWt(t,e){for(let n=e+1;n<t.length;n++){let r=t[n];if(r==="\\"){n++;continue}if(r===">")return n}return null}function dWt(t,e,n){for(let r=n-1;r>=0;r--)if(t[r]===e&&!KZe(t,r))return r;return null}function fWt(t){if(t.length===0||t[t.length-1]!==")")return null;let e=0;for(let n=t.length-1;n>=0;n--){let r=t[n];if(!((r===")"||r==="(")&&KZe(t,n))){if(r===")"){e++;continue}if(r==="("&&(e--,e===0))return n}}return null}function KZe(t,e){let n=0;for(let r=e-1;r>=0&&t[r]==="\\";r--)n++;return n%2===1}function y9(t){return t===" "||t===" "||t===`
`||t==="\r"}function Ai(t){return typeof t!="string"?"":t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function qZe(t){return typeof t!="string"?"":t.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&")}Kr();Ir();var dy=class extends $C{constructor(){super(...arguments);this.lastCitationSources=null}getAvailableToolsForPlanning(){let n=Vi.getInstance();return n.getAllTools().length===0&&yR(this.chainManager.app?.vault),n.getAllTools().map(o=>o.tool).filter(o=>o.name==="getCurrentTime"||o.name==="convertTimeBetweenTimezones"||o.name==="getTimeInfoByEpoch"||o.name==="getTimeRangeMs"||o.name==="getFileTree")}async planToolCalls(n,r,o=!1){let i=this.getAvailableToolsForPlanning(),s=r;if(typeof s.bindTools!="function")return ee("[CopilotPlus] Model does not support native tool calling, skipping tool planning"),{toolCalls:[],salientTerms:this.extractSalientTermsFromQuery(n)};let a=s.bindTools(i),c=`You are a helpful AI assistant. Analyze the user's message and determine if any tools should be called.
Guidelines:
- Use tools when the user's request requires external information or computation
- For time-related queries, use getTimeRangeMs to convert time expressions to timestamps
- Use getFileTree ONLY when the user wants to discover or list notes/folders in the vault \u2014 not to read content already in context${o?`
- The user has an active note attached in this turn. Its content is already available; do NOT call getFileTree merely because the user says 'this note' or 'this file'. Only call getFileTree when the user explicitly wants to discover OTHER notes, list folders, or verify paths.`:""}
- If no tools are needed, respond with your analysis
After analyzing, extract key search terms from the user's message that would be useful for searching notes:
- Extract meaningful nouns, topics, and specific concepts
- Preserve the EXACT words and language from the user's message (works for any language)
- Exclude time expressions (those are handled by tools)
Include your extracted terms as: [SALIENT_TERMS: term1, term2, term3]`,u=[{role:e$(r),content:c},{role:"user",content:n}];k("[CopilotPlus] Requesting tool planning with native tool calling...");let d;{let g=await Nc(()=>a.stream(u)),y;for await(let w of g)y=y?y.concat(w):w;if(!y)throw new Error("[CopilotPlus] Received empty response from planning model");d=new kn({content:y.content,tool_calls:y.tool_calls,additional_kwargs:y.additional_kwargs})}let f=d.tool_calls||[],p=typeof d.content=="string"?d.content:JSON.stringify(d.content);k("[CopilotPlus] Native tool calls:",f.length);let{salientTerms:m}=this.extractPlanningFieldsFromResponse(p,n),h=[];for(let g of f){let y=i.find(w=>w.name===g.name);y?(h.push({tool:y,args:g.args}),k(`[CopilotPlus] Tool call: ${g.name}`,g.args)):ee(`[CopilotPlus] Tool '${g.name}' not found in available tools`)}return{toolCalls:h,salientTerms:m}}extractPlanningFieldsFromResponse(n,r){let o,i=n.match(/\[SALIENT_TERMS:\s*([^\]]+?)\s*\]/i);if(i){let s=i[1].split(",").map(a=>a.trim()).filter(a=>a.length>0);o=s.length>0?s:this.extractSalientTermsFromQuery(r)}else o=this.extractSalientTermsFromQuery(r);return{salientTerms:o}}extractSalientTermsFromQuery(n){return n.split(/[\s\p{P}]+/u).filter(r=>r.length>=3).slice(0,10)}async processAtCommands(n,r,o){let i=n.toLowerCase(),s=this.removeAtCommands(n),a=[...r];if(i.includes("@vault")&&(a.some(c=>c.tool.name==="localSearch")||a.push({tool:i9,args:{query:s,salientTerms:o.salientTerms,timeRange:o.timeRange}})),(i.includes("@websearch")||i.includes("@web"))&&!a.some(c=>c.tool.name==="webSearch")){let u=await Sl.instance.getCurrentChainManager().memoryManager.getMemory().loadMemoryVariables({}),d=BW(u);a.push({tool:s9,args:{query:s,chatHistory:d}})}return i.includes("@memory")&&(a.some(c=>c.tool.name==="updateMemory")||a.push({tool:n9,args:{statement:s}})),a}removeAtCommands(n){return n.split(" ").filter(r=>!oR.includes(r.toLowerCase())).join(" ").trim()}async processImageUrls(n){let r=[],o=await g0.processUrlBatch(n,r,this.chainManager.app.vault);return g0.showFailedImagesNotice(r),o}async processChatInputImages(n){let r=[],o=await g0.processChatImageBatch(n,r,this.chainManager.app.vault);return g0.showFailedImagesNotice(r),o}async extractImagesFromContextBlock(n,r){let i=new RegExp(`<${r.tagName}>([\\s\\S]*?)<\\/${r.tagName}>`).exec(n);if(!i)return[];let s=i[1],l=/<content>([\s\S]*?)<\/content>/.exec(s),c=l?qZe(l[1]):"";if(!c)return[];let d=new RegExp(`<${r.identifierTag}>(.*?)<\\/${r.identifierTag}>`).exec(s),f=d?d[1]:void 0;k(`[CopilotPlus] Extracting images from ${r.displayName}:`,f||`no ${r.identifierTag}`);let p=r.useForResolution?f:void 0;return this.extractEmbeddedImages(c,p)}async extractEmbeddedImages(n,r){let o=/!\[\[(.*?\.(png|jpg|jpeg|gif|webp|bmp|svg))\]\]/g,i=[],s=[...n.matchAll(o)];for(let l of s){let c=l[1];if(r){let u=app.metadataCache.getFirstLinkpathDest(c,r);u?i.push(u.path):(ee(`Could not resolve embedded image: ${c} from source: ${r}`),i.push(c))}else i.push(c)}let a=HZe(n);for(let l of a){if(!l)continue;if(l.match(/^https?:\/\//)){i.push(l);continue}let c=l.replace(/^\.\//,"").replace(/^\//,"");if(r){let u=app.metadataCache.getFirstLinkpathDest(c,r);u?i.push(u.path):i.push(c)}else i.push(c)}return i}async buildMessageContent(n,r){let o=[],i=[],s=q(),a=[];if(s.passMarkdownImages){let d=r.contextEnvelope;if(!d)throw new Error("[CopilotPlus] Context envelope is required but not available. Cannot extract images.");let f=d.layers.find(p=>p.id==="L3_TURN");if(f){let p=[{tagName:"active_note",identifierTag:"path",displayName:"active note",useForResolution:!0},{tagName:"active_web_tab",identifierTag:"url",displayName:"active web tab",useForResolution:!1}];for(let m of p){let h=await this.extractImagesFromContextBlock(f.text,m);h.length>0&&a.push({urls:h,type:"embedded"})}}}for(let d of a){let f=await this.processImageUrls(d.urls);i.push(...f.successfulImages),o.push(...f.failureDescriptions)}let l=r.content;if(l&&l.length>0){let d=await this.processChatInputImages(l);i.push(...d.successfulImages),o.push(...d.failureDescriptions)}let c=n;o.len
Note:
${o.join(`
`)}
`);let u=[{type:"text",text:c}];return i.length>0&&u.push(...i),u}hasCapability(n,r){let o=n,i=o.modelName||o.model||"";return this.chainManager.chatModelManager.findModelByName(i)?.capabilities?.includes(r)??!1}isMultimodalModel(n){return this.hasCapability(n,"vision")}appendComposerInstructionsIfNeeded(n,r){if(!r.message||!r.message.includes("@composer"))return n;let o=`<OUTPUT_FORMAT>
${mPe}
</OUTPUT_FORMAT>`;return`${n}
${o}`}async streamMultimodalResponse(n,r,o,i,s,a,l){let c=this.chainManager.memoryManager.getMemory(),u=this.chainManager.chatModelManager.getChatModel(),d=this.isMultimodalModel(u),f=[],p=r.contextEnvelope;if(!p)throw new Error("[CopilotPlus] Context envelope is required but not available. Cannot proceed with CopilotPlus chain.");k("[CopilotPlus] Using envelope-based context construction");let m=sy.convert(p,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),h=m.find(x=>x.role==="system");h&&f.push({role:e$(u),content:h.content}),await FC(c,f);let g=m.find(x=>x.role==="user");if(g){let x,b=o.length>0,_=S=>{let P="[User query]:";if(S.includes(P))return S;let A=S.trimEnd(),O=[];A.length>0&&O.push(A);let D=a.trim()||r.originalMessage?.trim()||"";return D.length>0?O.push(`${P}
${D}`):O.push(P),O.join(`
`)};if(b){let S=this.formatAllToolOutputs(o),P=_(g.content);x=Mxe(S,P);let A=U9e(q().enableInlineCitations);A&&(x=WZe(x,A))}else x=_(g.content);if(n.includes("<OUTPUT_FORMAT>")&&!x.includes("<OUTPUT_FORMAT>")){let S=n.match(/<OUTPUT_FORMAT>[\s\S]*?<\/OUTPUT_FORMAT>/);S&&(x+=`
`+S[0])}let T=d?await this.buildMessageContent(x,r):x;f.push({role:"user",content:T})}k("Final request to AI",{messages:f.length});let y=u?.modelName;UC({messages:f,modelName:y,contextEnvelope:r.contextEnvelope});let w=new h9(Cv,t9),v=await Nc(()=>this.chainManager.chatModelManager.getChatModel().stream(f,{signal:i.signal}));for await(let x of v){if(i.signal.aborted){k("CopilotPlus multimodal stream iteration aborted",{reason:i.signal.reason});break}for await(let b of w.processChunk(x))s.processChunk(b)}}async run(n,r,o,i,s){let{updateLoadingMessage:a}=s,l=this.chainManager.chatModelManager.getChatModel(),u=!this.hasCapability(l,"reasoning"),d=new of(o,u),f=[];if(!await _p({isCopilotPlus:!0})){await this.handleError(new Error("Invalid license key"),d.processErrorChunk.bind(d));let v=d.close().content;return this.handleResponse(v,n,r,i,o,void 0)}try{k("==== Step 1: Planning tools ====");let v,x=n.contextEnvelope;if(!x)throw new Error("[CopilotPlus] Context envelope is required but not available. Cannot proceed with CopilotPlus chain.");let _=x.layers.find($=>$.id==="L5_USER")?.text||n.originalMessage||"";try{let $=this.chainManager.chatModelManager.getChatModel(),W=!!x.layers.find(te=>te.id==="L3_TURN")?.segments?.some(te=>te.metadata?.source==="current_turn"&&/<active_note[\s>]/.test(te.content)),F=await this.planToolCalls(_,$,W),Z,V=F.toolCalls.find(te=>te.tool.name==="getTimeRangeMs");if(V){let te=await Cv.callTool(V.tool,V.args),fe=me=>me?.startTime?.epoch!==void 0&&me?.endTime?.epoch!==void 0?{startTime:me.startTime.epoch,endTime:me.endTime.epoch}:me;if(typeof te=="string")try{let me=JSON.parse(te);me.error||(Z=fe(me))}catch{ee("[CopilotPlus] Failed to parse getTimeRangeMs result:",te)}else if(te){let me=te;me.error||(Z=fe(me))}k("[CopilotPlus] Executed getTimeRangeMs, result:",Z)}let H=F.toolCalls.filter(te=>te.tool.name==="getFileTree"&&RA()?(k("Skipping getFileTree in project mode"),!1):te.tool.name==="getTimeRangeMs"&&Z?(k("Skipping getTimeRangeMs - already executed during planning"),!1):!0);v=await this.processAtCommands(_,H,{salientTerms:F.salientTerms,timeRange:Z})}catch($){return this.handleResponse(AAe($),n,r,i,o)}let T=n.contextEnvelope?.layers.find($=>$.id==="L5_USER")?.text,S=this.removeAtCommands(T||n.originalMessage||n.message),{toolOutputs:P,sources:A}=await this.executeToolCalls(v,a);f=A;let O=P.filter($=>$.output!=null),D=this.appendComposerInstructionsIfNeeded(S,n);k("Invoking LLM with envelope-based context construction"),await this.streamMultimodalResponse(D,n,O,r,d,S,a)}catch(v){a?.(Td.DEFAULT),v instanceof Error&&v.name==="AbortError"||r.signal.aborted?k("CopilotPlus stream aborted by user",{reason:r.signal.reason}):await this.handleError(v,d.processErrorChunk.bind(d))}if(r.signal.aborted&&r.signal.reason==="new-chat")return o(""),"";let m=d.close(),h=m.content,g={wasTruncated:m.wasTruncated,tokenUsage:m.tokenUsage??void 0},y=q(),w=this.lastCitationSources&&this.lastCitationSources.length>0?this.lastCitationSources:(f||[]).map(v=>({title:v.title,path:v.path}));return h=z8(h,w,y.enableInlineCitations),await this.handleResponse(h,n,r,i,o,f,void 0,g),h}async executeToolCalls(n,r){let o=[],i=[],s=n.some(a=>a.tool.name==="localSearch");for(let a of n){if(a.tool.name==="getFileTree"&&s){k("Skipping getFileTree since localSearch is already active");continue}k(`Step 2: Calling tool: ${a.tool.name}`),a.tool.name==="localSearch"?r?.(Td.READING_FILES):a.tool.name==="webSearch"?r?.(Td.SEARCHING_WEB):a.tool.name==="getFileTree"&&r?.(Td.READING_FILE_TREE);let l=await Cv.callTool(a.tool,a.args);if(a.tool.name==="localSearch"){let u={result:typeof l=="string"?l:JSON.stringify(l),success:l!=null},d=this.getTimeExpression(n),f=this.processLocalSearchResult(u,d);i.push(...f.sources),o.push({tool:a.tool.name,output:f.formattedForLLM})}else o.push({tool:a.tool.name,output:l})}return{toolOutputs:o,sources:iP(i)}}getTimeExpression(n){let r=n.find(o=>o.tool.name==="getTimeRangeMs");return r?r.args.timeExpression:""}prepareLocalSearchResult(n,r){let o=q(),s=n.filter(A=>A.includeInContext!==!1),a=OZe(s),l=RZe(a),c=FZe(s
${kxe(f)}`):c&&k(`Tag-only search: ${f.length} notes (metadata-only)`);let x=h.slice(0,Math.min(20,h.length)).map(A=>({title:A.title||A.path||"Untitled",path:A.path||A.title||""})),b=j8(x);this.lastCitationSources=h.slice(0,Math.min(20,h.length)).map(A=>({title:A.title||A.path||"Untitled",path:A.path||void 0}));let _=$9e(b,o.enableInlineCitations).trim(),S=zZe("Answer the question based only on the following context:",v),P=_?`${l}
${S}
${_}`:`${l}
${S}`;return jZe(P,r)}processLocalSearchResult(n,r){let o=[],i,s;if(!n.success)return i=`<localSearch>
Search failed.
</localSearch>`,s=`Search failed: ${n.result}`,{formattedForLLM:i,formattedForDisplay:s,sources:o};try{let a=JSON.parse(n.result),l=a&&typeof a=="object"&&a.type==="local_search"&&Array.isArray(a.documents)?a.documents:null;if(!Array.isArray(l))return i=`<localSearch>
Invalid search results format.
</localSearch>`,s="Search results were in an unexpected format.",{formattedForLLM:i,formattedForDisplay:s,sources:o};BZe(l),o=DZe(l),i=this.prepareLocalSearchResult(l,r||""),s=_v.format("localSearch",i)}catch(a){ee("Failed to parse localSearch results:",a);let l=LZe(n.result);i=r?`<localSearch timeRange="${r}">
${l}
</localSearch>`:`<localSearch>
${l}
</localSearch>`,s=_v.format("localSearch",i)}return{formattedForLLM:i,formattedForDisplay:s,sources:o}}async getSystemPrompt(){return xv(this.chainManager.userMemoryManager)}formatAllToolOutputs(n){return n.length===0?"":`# Additional context:
`+n.map(o=>{let i=typeof o.output=="string"?o.output:JSON.stringify(o.output);return`<${o.tool}>
${i}
</${o.tool}>`}).join(`
`)}};var Qz=class extends dy{};It();ye();ns();Se();qe();Kr();ye();function Dxe(t){return t.map(e=>e.content).filter(e=>e&&e.trim().length>0).join(`
`)}var lP=class{constructor(e){this.modelName=e}buildToolSpecificInstructions(e){let n=[];for(let o of e)o.customPromptInstructions&&n.push(o.customPromptInstructions);let r=this.buildCopilotCommandInstructions(e);return r&&n.push(r),n.length>0?n.join(`
`):""}buildCopilotCommandInstructions(e){let n=[];for(let r of e)if(!(!r.copilotCommands||r.copilotCommands.length===0))for(let o of r.copilotCommands)n.push(`- ${o}: call the tool named ${r.id}`);return n.length===0?null:["When the user explicitly includes a Copilot command alias (e.g., @vault) in their message, treat it as a direct request to call the mapped tool before proceeding.","Honor these aliases exactly (case-insensitive):",...n,"If the referenced tool is unavailable, explain that the command cannot be fulfilled instead of ignoring it."].join(`
`)}enhanceSystemPrompt(e,n,r,o){let i=this.buildSystemPromptSections(e,n,r,o);return Dxe(i)}buildSystemPromptSections(e,n,r,o){let i=o||[],s=this.buildToolSpecificInstructions(i).trim(),l=[{id:"base-system-prompt",label:"System prompt with memory",source:"src/system-prompts/systemPromptBuilder.ts#getSystemPromptWithMemory",content:e.trimEnd()},{id:"autonomous-agent-intro",label:"Autonomous agent introduction",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildSystemPromptSections",content:`# Autonomous Agent Mode
You are now in autonomous agent mode. You can use tools to gather information and complete tasks step by step.
Tools are provided via native function calling - use them when needed to complete tasks.
`}],c=n.trim();return c.length>0&&l.push({id:"tool-descriptions",label:"Tool descriptions (native tool calling via bindTools)",source:"Native tool calling - schemas provided via bindTools()",content:`Available tools:
${c}`}),l.push({id:"tool-usage-guidelines",label:"Tool usage guidelines",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildSystemPromptSections",content:`# Tool Usage Guidelines
## Time-based Queries
When users ask about temporal periods (e.g., "what did I do last month", "show me notes from last week"), you MUST:
1. First call getTimeRangeMs to convert the time expression to a proper time range
2. Then use localSearch with the timeRange parameter from step 1
3. For salientTerms, ONLY use words that exist in the user's original query (excluding time expressions)
Example for "what did I do last month":
1. Call getTimeRangeMs with timeExpression: "last month"
2. Use localSearch with query matching the user's question
3. salientTerms: [] - empty because "what", "I", "do" are not meaningful search terms
Example for "meetings about project X last week":
1. Call getTimeRangeMs with timeExpression: "last week"
2. Use localSearch with query "meetings about project X"
3. salientTerms: ["meetings", "project", "X"] - these words exist in the original query
## File-related Queries
### Handle ambiguity in folder/note paths
When user mentions a folder name (e.g., "meetings folder") or a note name (e.g., "meeting note template") without providing an exact path,
you MUST first call getFileTree to find the folder or notes best matching the user's query.
If multiple results or no result, you should ask the user to provide a more specific path.
`}),s.length>0&&l.push({id:"tool-specific-instructions",label:"Tool-specific instructions",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildToolSpecificInstructions",content:s}),l.push({id:"general-guidelines",label:"General guidelines",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildSystemPromptSections",content:`## Answer Source Priority (CRITICAL)
You are the user's personal knowledge assistant. Always ground your answers in real sources rather than your own training data. Follow this priority chain:
1. **Explicit context first.** If the user has attached notes, documents, URLs, YouTube transcripts, tweets, or any other content to the conversation, use that content as your primary source. The user added it for a reason.
2. **Vault second.** For any question that could plausibly be answered by the user's notes, search the vault (localSearch). The user's own writing, meeting notes, journal entries, and saved references are highly valuable.
3. **Web third.** If the vault has no relevant results, or the question is about external/current information the vault is unlikely to contain, search the web.
4. **Your own knowledge last.** Only fall back on your training data when all of the above have been exhausted or are clearly inapplicable (e.g., explaining a general concept, writing code, or creative tasks that don't need source material).
When in doubt, search the vault. It is always better to check and find nothing than to skip the search and miss relevant notes.
## General Guidelines
- NEVER mention tool names like "localSearch", "webSearch", etc. in your responses. Use natural language like "searching your vault", "searching the web", etc.
You can use multiple tools in sequence. After each tool execution, you'll receive the results and can decide whether to use more tools or provide your final response.
Always explain your reasoning before using tools. Be conversational and clear about what you're doing.
When you've gathered enough information, provide your final response without any tool calls.
## Citation Integrity (CRITICAL)
- ONLY cite sources from tools you ACTUALLY called and received results from
- NEVER fabricate or hallucinate search results, web searches, or any tool outputs
- If you did not call a tool, do not claim you did or cite results from it
- Each citation must correspond to a real document or result returned by a tool in this conversation`}),l}enhanceUserMessage(e,n){return e}needsSpecialHandling(){return!1}},Nxe=class extends lP{isGPT5Model(){return this.modelName.includes("gpt-5")||this.modelName.includes("gpt5")}buildSystemPromptSections(e,n,r,o){let i=super.buildSystemPromptSections(e,n,r,o),s=r||[],a=s.includes("writeFile")||s.includes("editFile"),l=[];this.isGPT5Model()?l.push(`GPT-5 SPECIFIC RULES:
- Use maximum 2 tool calls initially, then provide an answer
- Call each tool ONCE per unique query
- For optional parameters: OMIT them entirely if not needed (don't pass empty strings/null)
- For localSearch: OMIT timeRange if not doing time-based search`):l.push("CRITICAL FOR GPT MODELS: You MUST use tools when the user's request requires them. Do not just describe what you plan to do - actually call the tools."),a&&l.push(`\u{1F6A8} FILE EDITING WITH COMPOSER TOOLS \u{1F6A8}
When user asks you to edit or modify a file, you MUST:
1. Determine if it's a small edit (use editFile) or major rewrite (use writeFile)
2. Call the tool immediately - do not just describe what you plan to do
For editFile, pass the exact text to find and its replacement:
- path: vault-relative file path
- oldText: exact text to find (include surrounding context lines to make it unique)
- newText: replacement text (empty string to delete)
\u274C WRONG: "I'll help you add item 4 to the list. Let me update that for you." [No tool call = FAILURE]
\u2705 CORRECT: Actually call editFile or writeFile with proper parameters`),l.push("FINAL REMINDER FOR GPT MODELS: If the user asks you to search, find, edit, or modify anything, you MUST call the appropriate tool immediately. Do not wait for another turn.");let c=l.join(`
`);return i.push({id:"gpt-specific-guidelines",label:"GPT-specific guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#GPTModelAdapter.buildSystemPromptSections",content:c}),i}enhanceUserMessage(e,n){return n?this.getBaseEnhancement(e,n):e}getBaseEnhancement(e,n){if(!n)return e;let r=e.toLowerCase(),o=r.includes("find")||r.includes("search")||r.includes("my notes"),i=r.includes("edit")||r.includes("modify")||r.includes("update")||r.includes("change")||r.includes("fix")||r.includes("add")||r.includes("typo");return o?`${e}
REMINDER: Call the localSearch tool now.`:i?`${e}
\u{1F6A8} GPT REMINDER: Use editFile for small edits (oldText/newText parameters) or writeFile for full rewrites.`:e}needsSpecialHandling(){return!0}},Oxe=class extends lP{isThinkingModel(){return this.modelName.includes("claude-3-7-sonnet")||this.modelName.includes("claude-sonnet-4")||this.modelName.includes("claude-3.7-sonnet")||this.modelName.includes("claude-4-sonnet")||this.modelName.includes("claude-opus-4")}isClaudeSonnet4(){return this.modelName.includes("claude-sonnet-4")||this.modelName.includes("claude-4-sonnet")||this.modelName.includes("claude-sonnet-4-20250514")}buildSystemPromptSections(e,n,r,o){let i=super.buildSystemPromptSections(e,n,r,o);if(!this.isThinkingModel())return i;let s=[`IMPORTANT FOR CLAUDE THINKING MODELS:
- You are a thinking model with internal reasoning capability
- Your thinking process will be automatically wrapped in <think> tags - do not manually add thinking tags
- Call tools AFTER your thinking is complete
- Do not provide final answers before using tools - use tools first, then provide your response based on the results
CORRECT FLOW FOR THINKING MODELS:
1. Think through the problem (this happens automatically)
2. Use tools to gather information
3. Wait for tool results
4. Provide final response based on gathered information
INCORRECT: Providing a final answer before using tools
CORRECT: Using tools first, then providing answer based on results`];return this.isClaudeSonnet4()&&s.push(`\u{1F6A8} CRITICAL INSTRUCTIONS FOR CLAUDE SONNET 4 - AUTONOMOUS AGENT MODE \u{1F6A8}
\u26A0\uFE0F WARNING: You have a specific tendency to write complete responses immediately after tool calls. This BREAKS the autonomous agent pattern!
\u{1F504} CORRECT AUTONOMOUS AGENT ITERATION PATTERN:
1. User asks question
2. Brief sentence about what you'll do (1 sentence max)
3. Use tools to gather information
4. \u270B STOP after tool calls - Do not write anything else
5. Wait for tool results (system provides them)
6. Evaluate results and either: Use more tools OR provide final answer
\u2705 IDEAL RESPONSE FLOW:
- Brief action statement (1 sentence)
- Tool calls
- STOP (wait for results)
- Brief transition statement (1 sentence)
- More tool calls OR final answer
\u{1F3AF} CORRECT PATTERN:
I'll search your vault for piano practice information.
[Call localSearch tool]
[RESPONSE ENDS HERE - NO MORE TEXT]
\u274C WRONG PATTERN (DO NOT DO THIS):
[Call tool]
Based on the search results, here's a complete practice plan...
[This is FORBIDDEN - you haven't received results yet!]
\u{1F511} KEY UNDERSTANDING FOR CLAUDE 4:
- Brief 1-sentence explanations BEFORE tool calls are good
- Each response is ONE STEP in a multi-step process
- After tool calls, STOP and wait for the system to provide results
- Your thinking is automatically handled in <think> blocks
\u26A1 AUTONOMOUS AGENT RULES FOR CLAUDE 4:
1. If you need tools: Brief sentence + tool calls, then STOP
2. If you receive tool results: Evaluate if you need more tools
3. If you need more tools: Brief sentence + more tool calls, then STOP
4. If you have enough info: THEN provide your final response
REMEMBER: One brief sentence before tools is perfect. Nothing after tool calls.`),i.push({id:"claude-thinking-guidelines",label:"Claude thinking model guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#ClaudeModelAdapter.buildSystemPromptSections",content:s.join(`
`)}),i}needsSpecialHandling(){return this.isThinkingModel()}},Rxe=class extends lP{buildSystemPromptSections(e,n,r,o){let i=super.buildSystemPromptSections(e,n,r,o),l=[`\u{1F6A8} CRITICAL INSTRUCTIONS FOR GEMINI - AUTONOMOUS AGENT MODE \u{1F6A8}
You MUST use tools to complete tasks. DO NOT ask the user questions about how to proceed.
${(r||[]).includes("localSearch")?`
When the user mentions "my notes" or "my vault", use the localSearch tool.
\u274C WRONG:
"Let's start by searching your notes. What kind of information should I look for?"
\u2705 CORRECT: Call localSearch immediately with the user's topic as the query`:""}`.trim()];return l.push(`GEMINI SPECIFIC RULES:
1. When user mentions "my notes" about X \u2192 use localSearch with query "X"
2. DO NOT ask clarifying questions about search terms
3. DO NOT wait for permission to use tools
4. Use tools based on the user's request
\u{1F6A8} CRITICAL: SEQUENTIAL vs PARALLEL TOOL CALLS \u{1F6A8}
When one tool's OUTPUT is needed as INPUT to another tool, you MUST make them in SEPARATE responses:
1. Call the FIRST tool
2. STOP and wait for the result
3. In the NEXT response, use the result from step 1 in the SECOND tool call
\u274C WRONG (DO NOT DO THIS):
User: "Recap my last week"
- Call getTimeRangeMs AND localSearch together with made-up timeRange values
- This is WRONG because you're hallucinating the timeRange values!
\u2705 CORRECT (DO THIS):
User: "Recap my last week"
- FIRST: Call getTimeRangeMs with timeExpression "last week"
- WAIT for result
- SECOND: Call localSearch using the actual timeRange from the result
RULE: NEVER make up or guess parameter values. If you need a tool's output, call that tool FIRST, then WAIT for the result.
Remember: The user has already told you what to do. Execute it NOW with the available tools.`),i.push({id:"gemini-specific-guidelines",label:"Gemini-specific guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#GeminiModelAdapter.buildSystemPromptSections",content:l.join(`
`)}),i}enhanceUserMessage(e,n){return n?`${e}
REMINDER: Use the tools immediately. Do not ask questions. For "my notes", use localSearch.`:e}needsSpecialHandling(){return!0}},Lxe=class extends lP{buildSystemPromptSections(e,n,r,o){let i=super.buildSystemPromptSections(e,n,r,o);return i.push({id:"copilot-plus-guidelines",label:"Copilot Plus model guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#CopilotPlusModelAdapter.buildSystemPromptSections",content:`\u{1F6A8} CRITICAL: NO HALLUCINATED TOOL CALLS OR SOURCES \u{1F6A8}
You are a Copilot Plus model. You MUST follow these rules strictly:
## Tool Call Integrity
- You can ONLY reference results from tools you have ACTUALLY called in this conversation
- NEVER claim to have performed a web search unless you called the webSearch tool AND received results
- NEVER claim to have searched notes unless you called localSearch AND received results
- If you want to search the web, you MUST call the webSearch tool first - do not make up results
## Citation Rules
- Every citation [1], [2], etc. MUST correspond to a real source returned by a tool
- Do NOT invent sources like "General web search results for X" unless webSearch was actually called
- If you only called localSearch, your citations can ONLY reference notes from that search
- Count your actual tool calls - if you only made 1 tool call, you cannot have citations from multiple different tools
## Before Writing Citations
Ask yourself: "Did I actually call this tool and receive this result?"
- If YES: You may cite it
- If NO: Do NOT cite it or claim you did
REMEMBER: It is better to say "I only searched your notes, not the web" than to fabricate web search results.
## Formatting Guidelines
- AVOID using markdown tables - they often render poorly in chat interfaces
- Instead of tables, use bullet points, numbered lists, or simple formatted text
- Only use tables when the user explicitly requests tabular format`}),i}needsSpecialHandling(){return!0}},ej=class{static createAdapter(e){let n=(e.modelName||e.model||"").toLowerCase();if(k(`Creating model adapter for: ${n}`),n.includes("gpt")){let r=new Nxe(n);return r.isGPT5Model()?k("Using GPTModelAdapter with GPT-5 specific enhancements"):k("Using GPTModelAdapter"),r}return n.includes("claude")?(k("Using ClaudeModelAdapter"),new Oxe(n)):n.includes("gemini")||n.includes("google/gemini")?(k("Using GeminiModelAdapter"),new Rxe(n)):n.includes("copilot-plus")?(k("Using CopilotPlusModelAdapter"),new Lxe(n)):(k("Using BaseModelAdapter (default)"),new lP(n))}};function GZe(t){let e=["find","search","look for","look up","my notes","in my vault","from my vault","check the web","search online","from the internet","current time","what time","timer","youtube","video","transcript"],n=t.toLowerCase();return e.some(r=>n.includes(r))}function pWt(t){let{systemSections:e,rawHistory:n,adapterName:r,originalUserMessage:o,enhancedUserMessage:i}=t,s=[...e];if(n&&n.length>0){let l=wye(n);if(l.length>0){let u=dqe(l).map((d,f)=>`${f+1}. ${d.role.toUpperCase()}
${d.content}`);s.push({id:"chat-history",label:"Restored chat history from memory",source:"src/LLMProviders/chainRunner/utils/chatHistoryUtils.ts#processRawChatHistory",content:u.join(`
`)})}}s.push({id:"user-original-message",label:"Original user message",source:"Chat input",content:o});let a=i===o?" (unchanged)":"";return s.push({id:"user-enhanced-message",label:`User message after ${r}.enhanceUserMessage${a}`,source:`src/LLMProviders/chainRunner/utils/modelAdapter.ts#${r}.enhanceUserMessage`,content:i}),s}function mWt(t){return t.map(e=>`${`[Section: ${e.label} | Source: ${e.source}]`}
${e.content}`).join(`
`)}function YZe(t){let e=pWt(t),n=mWt(e),r=Dxe(t.systemSections);return{sections:e,annotatedPrompt:n,systemPrompt:r}}async function hWt(t){let{chainManager:e,adapter:n,basePrompt:r,toolDescriptions:o,toolNames:i,toolMetadata:s,userMessage:a}=t,l=n.buildSystemPromptSections(r,o,i,s),u=await e.memoryManager.getMemory().loadMemoryVariables({}),d=Array.isArray(u.history)?u.history:[],f=a.originalMessage||a.message,p=GZe(a.message),m=n.enhanceUserMessage(a.message,p);return YZe({systemSections:l,rawHistory:d,adapterName:n.constructor?.name||"ModelAdapter",originalUserMessage:f,enhancedUserMessage:m})}async function gWt(t){return xv(t.userMemoryManager)}async function ZZe(t){let{chainManager:e,adapter:n,availableTools:r,toolDescriptions:o,userMessage:i}=t,s=Vi.getInstance(),a=r.map(u=>u.name),l=r.map(u=>s.getToolMetadata(u.name)).filter(u=>u!==void 0),c=await gWt(e);return hWt({chainManager:e,adapter:n,basePrompt:c,toolDescriptions:o,toolNames:a,toolMetadata:l,userMessage:i})}function JZe(){return{status:"idle",startTime:null,elapsedSeconds:0,steps:[]}}function $xe(t){if(t.status==="idle")return"";let e=JSON.stringify(t.steps.map(n=>n.summary));return`<!--AGENT_REASONING:${t.status}:${t.elapsedSeconds}:${e}-->`}function tj(t){let e=t.match(/<!--AGENT_REASONING:(\w+):(\d+):(.+?)-->/);if(!e)return null;let[n,r,o,i]=e,s=[];try{s=JSON.parse(i)}catch{s=[]}return{hasReasoning:!0,status:r,elapsedSeconds:parseInt(o,10),steps:s,contentAfter:t.replace(n,"").trim()}}function XZe(t,e,n,r){if(!e.success)return`${Fxe(t,r)} failed`;switch(t){case"localSearch":{if(n&&n.count>0){let o=n.titles.slice(0,3),i=n.count-o.length,s=`Found ${n.count} note${n.count!==1?"s":""}: ${o.join(", ")}`;return i>0&&(s+=` +${i} more`),s}return"No matching notes found"}case"webSearch":return"Retrieved web search results";case"getTimeRangeMs":return"Calculated time range";case"readFile":return"Read file content";case"readNote":{let o=r?.notePath;return o?`Read "${o.split("/").pop()?.replace(/\.md$/i,"")||o}"`:"Read note content"}case"createNote":return"Created new note";case"appendToNote":return"Appended to note";case"editNote":return"Edited note";case"deleteNote":return"Deleted note";case"youtubeTranscript":case"youtubeTranscription":return"Fetched video transcript";case"fetchUrl":return"Fetched URL content";case"getFileTree":return"Retrieved vault file tree";case"getTagList":return"Retrieved vault tags";case"getCurrentTime":return"Got current time";case"getTimeInfoByEpoch":return"Converted timestamp";case"convertTimeBetweenTimezones":return"Converted timezone";case"obsidianDailyNote":{let o=r?.command,i=r?.vault,s=i&&i.trim().length>0?` from "${i}"`:"";return o==="daily:path"?`Got daily note path${s}`:`Loaded today's daily note${s}`}case"obsidianRandomRead":{let o=r?.vault;return o&&o.trim().length>0?`Loaded a random note from "${o}"`:"Loaded a random note"}case"obsidianProperties":{if(r?.command==="property:read"){let i=r?.name;return i?`Read property "${i}"`:"Read property"}return"Listed vault properties"}case"obsidianTasks":return"Listed vault tasks";case"obsidianLinks":{let o=r?.command;return o==="backlinks"?"Listed backlinks":o==="links"?"Listed outgoing links":o==="orphans"?"Listed orphaned notes":o==="unresolved"?"Listed unresolved links":"Queried link graph"}case"obsidianTemplates":{if(r?.command==="template:read"){let i=r?.name;return i?`Read template "${i}"`:"Read template"}return"Listed templates"}case"obsidianBases":{let o=r?.command;return o==="base:views"?"Listed base views":o==="base:query"?"Queried base data":"Listed bases"}case"indexVault":return"Indexed vault";case"updateMemory":return"Updated memory";case"writeFile":case"editFile":{let o=r?.path,i=o?o.split("/").pop()||o:"file",s=e.result||"";return s.includes('"rejected"')||s.includes("rejected")?`Edit rejected for "${i}"`:s.includes('"failed"')||s.includes("Error")?`Edit failed for "${i}"`:t==="writeFile"?`Wrote to "${i}"`:`Edited "${i}"`}default:return"Done"}}function Fxe(t,e,n){switch(t){case"localSearch":{if(n&&n.recallTerms&&n.recallTerms.length>0){let o=n.recallTerms.filter(i=>typeof
`)[0];return yWt(e,100)}function wWt(t,e){let n=new Set(t.toLowerCase().split(/\s+/).filter(Boolean)),r=new Set(e.toLowerCase().split(/\s+/).filter(Boolean));if(n.size===0&&r.size===0)return 1;if(n.size===0||r.size===0)return 0;let o=0;for(let l of n)r.has(l)&&o++;let i=n.size+r.size-o,s=o/i,a=o/Math.min(n.size,r.size);return Math.max(s,a)}function Uxe(t,e,n=.6){for(let r of e)if(wWt(t,r)>=n)return r;return null}var vWt=/^(user|assistant|system)\s*$/;function e7e(t){return t&&t.split(`
`).filter(e=>!vWt.test(e)).join(`
`)}var t7e=`## Agent Behavior
- You have a limited number of tool calls. Use them wisely.
- NEVER search for the same or very similar query twice. If results were insufficient, try substantially different terms.
- After 1-2 searches, synthesize an answer from the results you have. Do not keep searching unless the results are clearly insufficient.
- If you have enough information to answer, respond directly without calling any more tools.`,nj=class extends dy{constructor(){super(...arguments);this.llmFormattedMessages=[];this.lastDisplayedContent="";this.reasoningState=JZe();this.reasoningTimerInterval=null;this.accumulatedContent="";this.allReasoningSteps=[];this.abortHandledByTimer=!1}getAvailableTools(){let n=q(),r=Vi.getInstance();r.getAllTools().length===0&&yR(this.chainManager.app?.vault);let o=new Set(n.autonomousAgentEnabledToolIds||[]);return r.getEnabledTools(o,!!this.chainManager.app?.vault)}startReasoningTimer(n,r){this.reasoningState={status:"reasoning",startTime:Date.now(),elapsedSeconds:0,steps:[]},this.accumulatedContent="",this.allReasoningSteps=[],this.abortHandledByTimer=!1;let o=["Understanding your question","Analyzing your request","Processing your query","Thinking about this","Considering your question","Working on this","Pondering the possibilities","Diving into your request","Let me think about this","Exploring your question","Getting my thoughts together","Examining the details","Looking into this","Mulling this over","On it","Firing up the neurons","Connecting the dots","Brewing some ideas","Spinning up the gears","Warming up the engines","Crunching the details","Putting on my thinking cap","Consulting my notes","Gathering my thoughts","Rolling up my sleeves"],i=o[Math.floor(Math.random()*o.length)];this.addReasoningStep(i),this.reasoningTimerInterval=window.setInterval(()=>{if(r?.signal.aborted&&this.reasoningState.status==="reasoning"){this.stopReasoningTimer(),this.reasoningState.status="complete",this.abortHandledByTimer=!0;let s=this.buildReasoningBlockMarkup(),a="The response was interrupted.",l=s?s+`
`+a:a;n(l);return}if(this.reasoningState.startTime&&this.reasoningState.status==="reasoning"){this.reasoningState.elapsedSeconds=Math.floor((Date.now()-this.reasoningState.startTime)/1e3);let s=this.buildReasoningBlockMarkup(),a=s?s+(this.accumulatedContent?`
`+this.accumulatedContent:""):this.accumulatedContent;n(a)}},100)}addReasoningStep(n,r,o=!1){let i={timestamp:Date.now(),summary:n,toolName:r};this.allReasoningSteps.push(i),!o&&(this.reasoningState.steps.push(i),this.reasoningState.steps.length>4&&this.reasoningState.steps.shift())}stopReasoningTimer(){this.reasoningTimerInterval&&(window.clearInterval(this.reasoningTimerInterval),this.reasoningTimerInterval=null),this.reasoningState.status="collapsed"}buildReasoningBlockMarkup(){if(this.reasoningState.status==="complete"||this.reasoningState.status==="collapsed"){let n={...this.reasoningState,steps:this.allReasoningSteps};return $xe(n)}return $xe(this.reasoningState)}static async generateSystemPrompt(n,r,o){let i=await xv(o),s=Vi.getInstance(),l=n.map(u=>s.getToolMetadata(u.name)).filter(u=>u!==void 0).filter(u=>u.customPromptInstructions).map(u=>`For ${u.displayName}: ${u.customPromptInstructions}`).join(`
`),c=[i];return l&&c.push(`## Tool Guidelines
${l}`),c.push(t7e),c.join(`
`)}async buildToolPromptDebugReport(n){let r=this.getAvailableTools(),o=ej.createAdapter(this.chainManager.chatModelManager.getChatModel()),i=r.map(s=>`${s.name}: ${s.description}`).join(`
`);return ZZe({chainManager:this.chainManager,adapter:o,availableTools:r,toolDescriptions:i,userMessage:n})}applyCiCOrderingToLocalSearchResult(n,r){return VZe(n,r)}async run(n,r,o,i,s){this.llmFormattedMessages=[],this.lastDisplayedContent="";let a=await _p({isAutonomousAgent:!0}),l=this.chainManager.chatModelManager.getChatModel(),c=ej.createAdapter(l),u=new of(o,!0);if(!a){await this.handleError(new Error("Invalid license key"),u.processErrorChunk.bind(u));let m=u.close().content;return this.handleResponse(m,n,r,i,o,void 0)}let d=l?.modelName;if(!n.contextEnvelope)throw new Error("[Agent] Context envelope is required but not available. Cannot proceed with autonomous agent.");k("[Agent] Using native tool calling with ReAct pattern");let p=await this.prepareAgentConversation(n,l,s.updateLoadingMessage);try{this.startReasoningTimer(o,r);let m=await this.runReActLoop({boundModel:p.loopDeps.boundModel,chatModel:l,tools:p.loopDeps.availableTools,messages:p.messages,originalPrompt:p.originalUserPrompt,abortController:r,updateCurrentAiMessage:o,processLocalSearchResult:p.loopDeps.processLocalSearchResult,applyCiCOrderingToLocalSearchResult:p.loopDeps.applyCiCOrderingToLocalSearchResult,adapter:c});if(this.abortHandledByTimer)return this.lastDisplayedContent="","";let h=iP(m.sources);return p.messages.length>0&&UC({messages:[...p.messages],modelName:d,contextEnvelope:n.contextEnvelope}),await this.handleResponse(m.finalResponse,n,r,i,o,h.length>0?h:void 0,this.llmFormattedMessages.join(`
`),m.responseMetadata),this.lastDisplayedContent="",m.finalResponse}catch(m){if(this.stopReasoningTimer(),m.name==="AbortError"||r.signal.aborted)return k("Autonomous agent stream aborted by user",{reason:r.signal.reason}),"";z("Autonomous agent failed, falling back to regular Plus mode:",m);try{return await new dy(this.chainManager).run(n,r,o,i,s)}catch(h){z("Fallback to regular Plus mode also failed:",h),this.lastDisplayedContent&&u.processChunk({content:this.lastDisplayedContent});let g=Xt(m),y=`
Fallback to regular Plus mode also failed: `+Xt(h);await this.handleError(new Error(g+y),u.processErrorChunk.bind(u));let w=u.close().content;return this.handleResponse(w,n,r,i,o,void 0,w)}}}async prepareAgentConversation(n,r,o){let i=[],s=this.getAvailableTools(),a=r.modelName||r.model||"unknown";if(typeof r.bindTools!="function")throw new Error(`Model ${a} does not support native tool calling (bindTools not available). Agent mode requires a model with tool calling support.`);let l=r.bindTools(s),c={availableTools:s,boundModel:l,processLocalSearchResult:this.processLocalSearchResult.bind(this),applyCiCOrderingToLocalSearchResult:this.applyCiCOrderingToLocalSearchResult.bind(this)},u=n.contextEnvelope,d=sy.convert(u,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),f=this.chainManager.memoryManager.getMemory(),p=d.find(T=>T.role==="system"),m=Vi.getInstance(),g=s.map(T=>m.getToolMetadata(T.name)).filter(T=>T!==void 0).filter(T=>T.customPromptInstructions).map(T=>`For ${T.displayName}: ${T.customPromptInstructions}`).join(`
`),y=[p?.content||"",g?`
## Tool Guidelines
${g}`:"",t7e].filter(Boolean).join(`
`);y&&i.push(new Vu({content:y}));let x=u.layers.find(T=>T.id==="L5_USER")?.text||""||n.originalMessage||n.message,b=[];await FC(f,b);for(let T of b)T.role==="user"?i.push(new Zo(T.content)):i.push(new kn(T.content));let _=d.find(T=>T.role==="user");if(_){let S=this.isMultimodalModel(r)?await this.buildMessageContent(_.content,n):_.content;i.push(new Zo(S))}return{messages:i,collectedSources:[],originalUserPrompt:x,loopDeps:c}}async runReActLoop(n){let{boundModel:r,tools:o,messages:i,originalPrompt:s,abortController:a,updateCurrentAiMessage:l,processLocalSearchResult:c,applyCiCOrderingToLocalSearchResult:u}=n,d=q().autonomousAgentMaxIterations,f=[],p=Date.now(),m=[],h=0,g=0,y;for(;g<d&&!a.signal.aborted;){let T=Date.now()-p;if(T>=see){ee(`Agent loop timed out after ${Math.round(T/1e3)}s`);break}g++;let{content:S,aiMessage:P,streamingResult:A}=await this.streamModelResponse(r,i,a,l);y={wasTruncated:A.wasTruncated,tokenUsage:A.tokenUsage??void 0};let O=S?.trim();k(`[Agent] Iteration ${g} model output:`,O?O.slice(0,200):"(empty)");let D=P.tool_calls||[];if(k(`[Agent] Iteration ${g}: ${D.length} tool call(s)`),D.length===0){k(`[Agent] Iteration ${g}: Final response (no tool calls)`),this.stopReasoningTimer(),this.reasoningState.status="complete",i.push(P);let V=S;if(!V||V.trim()===""){let G=P.tool_call_chunks??[];ee(`[Agent] Empty response detected (iteration ${g}). Content length: ${S?.length??0}, tool_call_chunks from model: ${G.length}, parsed tool_calls: ${D.length}. This may indicate tool calls were dropped or the model produced only thinking tokens.`),V="The model did not produce a response. Please try again or switch to a different model."}let H=this.buildReasoningBlockMarkup(),te=20,fe=5,me="";for(let G=0;G<V.length&&!a.signal.aborted;G+=te){me+=V.slice(G,G+te);let J=H?H+`
`+me:me;l(J),G+te<V.length&&await new Promise(M=>window.setTimeout(M,fe))}let j=H?H+`
`+V:V;return l(j),{finalResponse:j,sources:f,responseMetadata:y}}let $=e7e(S),B=new kn({content:$,tool_calls:P.tool_calls});if(i.push(B),g>1&&$&&$.trim().length>0){let V=QZe($);V&&this.addReasoningStep(V)}let W=[],F=[],Z=[];for(let V of D){if(V.name==="localSearch"){let H=V.args?.query;if(H){let te=Uxe(H,m)??Uxe(H,F);if(te){k(`[Agent] Dedup: "${H}" (similar to: "${te}")`),i.push(vye(V.id||PG(),V.name,`You already searched for a similar query: "${te}". Synthesize your answer from existing results.`));continue}F.push(H),Z.push(H)}else Z.push(null)}else Z.push(null);W.push(V)}for(let V=0;V<W.length;V++){let H=W[V];if(a.signal.aborted)break;let te={name:H.name,args:H.args},fe=Fxe(H.name,te.args);this.addReasoningStep(fe,H.name),TYe(te,g);let me=await _Ye(te,o,s),j;if(H.name==="localSearch"&&me.success){let M=c(me);f.push(...M.sources),j={titles:M.sources.map(E=>E.title),count:M.sources.length},me.result=u(M.formattedForLLM,s||"")}if(IYe(H.name,me),H.name==="localSearch"&&me.success){let M=Z[V];M&&m.push(M)}let G=XZe(H.name,me,j,te.args);(!me.success||j)&&this.addReasoningStep(G,H.name);let J=vye(H.id||PG(),H.name,me.result);i.push(J)}if(W.length===0&&D.length>0){if(h++,k(`[Agent] All ${D.length} tool call(s) skipped as duplicates (${h} consecutive)`),h>=2){k("[Agent] Model stuck in search loop, forcing synthesis without tools"),this.addReasoningStep("Synthesizing answer from search results"),i.push(new Zo(`You have already searched and found relevant results. Do not call any tools. Answer the following question now based ONLY on the search results above:
`+s));let V=await this.streamModelResponse(n.chatModel,i,a,l);y={wasTruncated:V.streamingResult.wasTruncated,tokenUsage:V.streamingResult.tokenUsage??void 0},this.stopReasoningTimer(),this.reasoningState.status="complete";let H=this.buildReasoningBlockMarkup(),te=V.content||"Unable to synthesize a response from the search results.",fe=H?H+`
`+te:te;return l(fe),{finalResponse:fe,sources:f,responseMetadata:y}}}else h=0}this.stopReasoningTimer(),this.reasoningState.status="complete";let w=this.buildReasoningBlockMarkup();if(a.signal.aborted){if(k("Agent reasoning interrupted by user"),this.abortHandledByTimer)return{finalResponse:"",sources:f,responseMetadata:y};let T="The response was interrupted.";return{finalResponse:w?w+`
`+T:T,sources:f,responseMetadata:y}}let v=Date.now()-p,x=v>=see;x?ee(`Agent loop timed out after ${Math.round(v/1e3)}s`):ee(`Agent reached max iterations (${d})`);let b=x?"I've reached the time limit for reasoning. Here's what I found so far based on the search results.":"I've reached the maximum number of tool calls. Here's what I found so far based on the search results.";return{finalResponse:w?w+`
`+b:b,sources:f,responseMetadata:y}}async streamModelResponse(n,r,o,i){let s=new Map,a=new of(()=>{},!0),l="";try{let c=await Nc(()=>n.stream(r,{signal:o.signal}));for await(let g of c){if(o.signal.aborted)break;let y=g;if(y.response_metadata?.finish_reason==="MALFORMED_FUNCTION_CALL")throw ee("Backend returned MALFORMED_FUNCTION_CALL - falling back to non-agent mode"),new Error("MALFORMED_FUNCTION_CALL: Model does not support native tool calling");let v=y.tool_call_chunks;if(v&&Array.isArray(v))for(let b of v)mqe(s,b);let x=typeof y.content=="string"?y.content:"";x&&(l+=x),a.processChunk(y)}let u=a.close(),d=u.content,f=l.trim(),p=d.trim();f&&!p&&k(`[Agent] Model produced content that was entirely stripped (likely think blocks): ${f.slice(0,300)}`);let m=EG(s),h=new kn({content:d,tool_calls:m.map(g=>({id:g.id,name:g.name,args:g.args,type:"tool_call"}))});return{content:d,aiMessage:h,streamingResult:u}}catch(c){if(z(`Stream error: ${c.message}`),c.name==="AbortError"||o.signal.aborted){let u=a.close();return{content:u.content,aiMessage:new kn({content:u.content}),streamingResult:u}}throw c}}};ye();Se();qe();Nf();ph();var uJe=require("obsidian");eP();var SR=[{tag:"note_context",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"active_note",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"embedded_note",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"vault_note",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"retrieved_document",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"url_content",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"web_tab_context",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"active_web_tab",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"youtube_video_context",sourceType:"youtube",recoverable:!0,sourceExtractor:"url"},{tag:"twitter_content",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"embedded_pdf",sourceType:"pdf",recoverable:!0,sourceExtractor:"name"},{tag:"selected_text",sourceType:"selected_text",recoverable:!1,sourceExtractor:null},{tag:"web_selected_text",sourceType:"selected_text",recoverable:!1,sourceExtractor:null},{tag:"localSearch",sourceType:"note",recoverable:!0,sourceExtractor:null}],S9=new Map;for(let t of SR)S9.set(t.tag,t);function dP(t){return S9.get(t)?.sourceType??"unknown"}function T9(t){return S9.get(t)?.recoverable??!1}function TR(t,e){let n=S9.get(e);if(!n?.sourceExtractor)return"";let r=n.sourceExtractor;return new RegExp(`<${r}>([^<]+)</${r}>`).exec(t)?.[1]??""}function uj(t){let e=/<content>([\s\S]*?)<\/content>/.exec(t);return e?e[1]:t}var pf={previewCharsPerSection:500,maxSections:20,verbatimThreshold:5e3};function fP(t,e=500,n=20){let r=t.split(/(?=^#{1,6}\s+)/m).filter(a=>a.trim());if(r.length<=1)return Yxe(t,e*4);let o=r.slice(0,n),i=r.length>n,s=o.map(a=>{let l=a.trim().split(`
`),c=l[0],u=l.slice(1).join(`
`).trim();return u.length<=e?a.trim():`${c}
${Yxe(u,e)}`}).join(`
`);return i?`${s}
[... ${r.length-n} more sections omitted ...]`:s}function Yxe(t,e){if(t.length<=e)return t;let n=t.slice(0,e),r=/[.!?]\s+/g,o=-1,i;for(;(i=r.exec(n))!==null;)i.index>e*.5&&(o=i.index+1);if(o>0)return n.slice(0,o)+" ...";let s=n.lastIndexOf(`
`);if(s>e*.5)return n.slice(0,s)+`
...`;let a=n.lastIndexOf(" ");return a>e*.8?n.slice(0,a)+" ...":n+"..."}function I9(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function zWt(){return["localSearch","note_context","active_note","retrieved_document","url_content","youtube_video_context"].map(e=>({pattern:new RegExp(`<${e}[^>]*>[\\s\\S]*?</${e}>`,"g"),tag:e}))}var jWt=zWt(),IR="Tool 'readNote' result: ";function VWt(t,e){if(t[e]!=="{")return null;let n=0,r=!1,o=!1;for(let i=e;i<t.length;i++){let s=t[i];if(o){o=!1;continue}if(s==="\\"&&r){o=!0;continue}if(s==='"'){r=!r;continue}if(!r){if(s==="{")n++;else if(s==="}"&&(n--,n===0))return{json:t.slice(e,i+1),endPos:i+1}}}return null}function PR(t,e={}){return Array.isArray(t)?t.map(n=>n.type==="text"&&typeof n.text=="string"?{...n,text:g7e(n.text,e)}:n):typeof t=="string"?g7e(t,e):t}function g7e(t,e={}){let n=e.verbatimThreshold??pf.verbatimThreshold,r=t;for(let{pattern:o,tag:i}of jWt)o.lastIndex=0,r=r.replace(o,s=>s.length<n?s:HWt(s,i,e));return r=WWt(r,n,e),r}function WWt(t,e,n){let r="",o=0;for(;o<t.length;){let i=t.indexOf(IR,o);if(i===-1){r+=t.slice(o);break}r+=t.slice(o,i);let s=i+IR.length,a=VWt(t,s);if(!a){r+=IR,o=s;continue}try{let l=JSON.parse(a.json);if(l.content&&l.content.length>e){let c=qWt(l,n);r+=`${IR}${JSON.stringify(c)}`}else r+=IR+a.json}catch{r+=IR+a.json}o=a.endPos}return r}function HWt(t,e,n={}){if(!T9(e))return t;if(e==="localSearch")return KWt(t,n);let r=TR(t,e),o=uj(t),i=dP(e),s=n.previewCharsPerSection??pf.previewCharsPerSection,a=n.maxSections??pf.maxSections,l=fP(o,s,a);return`<prior_context source="${I9(r)}" type="${i}">
${l}
</prior_context>`}function KWt(t,e={}){let n=e.previewCharsPerSection??pf.previewCharsPerSection,r=/<document>([\s\S]*?)<\/document>/g,o=[],i;for(;(i=r.exec(t))!==null;){let a=i[1],l=/<path>([^<]+)<\/path>/.exec(a),c=/<title>([^<]+)<\/title>/.exec(a),u=/<content>([\s\S]*?)<\/content>/.exec(a),d=l?.[1]??"",f=c?.[1]??d.split("/").pop()??"Untitled",p=u?.[1]??"",m=p.length>n?p.slice(0,n)+"...":p;o.push({path:d,title:f,preview:m.trim()})}if(o.length===0){let a=uj(t);return`<prior_context source="localSearch" type="note">
${fP(a,n,e.maxSections??pf.maxSections)}
</prior_context>`}let s=o.map((a,l)=>`${l+1}. [[${a.title}]] (${a.path})
${a.preview}`).join(`
`);return`<prior_context source="localSearch" type="note">
[${o.length} search results - use localSearch to re-query]
${s}
</prior_context>`}function qWt(t,e={}){let{content:n,notePath:r,noteTitle:o,...i}=t;if(!n||typeof n!="string")return t;let s=e.previewCharsPerSection??pf.previewCharsPerSection,a=e.maxSections??pf.maxSections,l=fP(n,s,a);return{...i,notePath:r,noteTitle:o,content:`[COMPACTED - use readNote to get full content]
${l}`,_wasCompacted:!0}}ye();Se();var GWt=Object.defineProperty;var ER=(t,e)=>{for(var n in e)GWt(t,n,{get:e[n],enumerable:!0})};ph();var YWt=`Progressively summarize the lines of conversation provided, adding onto the previous summary returning a new summary.
EXAMPLE
Current summary:
The human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good.
New lines of conversation:
Human: Why do you think artificial intelligence is a force for good?
AI: Because artificial intelligence will help humans reach their full potential.
New summary:
The human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential.
END OF EXAMPLE
Current summary:
{summary}
New lines of conversation:
{new_lines}
New summary:`,y7e=new ki({inputVariables:["summary","new_lines"],template:YWt}),ZWt=`You are an assistant to a human, powered by a large language model trained by OpenAI.
You are designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, you are able to generate human-like text based on the input you receive, allowing you to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.
You are constantly learning and improving, and your capabilities are constantly evolving. You are able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. You have access to some personalized information provided by the human in the Context section below. Additionally, you are able to generate your own text based on the input you receive, allowing you to engage in discussions and provide explanations and descriptions on a wide range of topics.
Overall, you are a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether the human needs help with a specific question or just wants to have a conversation about a particular topic, you are here to assist.
Context:
{entities}
Current conversation:
{history}
Last line:
Human: {input}
You:`,w7e=new ki({inputVariables:["entities","history","input"],template:ZWt}),JWt=`You are an AI assistant reading the transcript of a conversation between an AI and a human. Extract all of the proper nouns from the last line of conversation. As a guideline, a proper noun is generally capitalized. You should definitely extract all names and places.
The conversation history is provided just in case of a coreference (e.g. "What do you know about him" where "him" is defined in a previous line) -- ignore items mentioned there that are not in the last line.
Return the output as a single comma-separated list, or NONE if there is nothing of note to return (e.g. the user is just issuing a greeting or having a simple conversation).
EXAMPLE
Conversation history:
Person #1: my name is Jacob. how's it going today?
AI: "It's going great! How about you?"
Person #1: good! busy working on Langchain. lots to do.
AI: "That sounds like a lot of work! What kind of things are you doing to make Langchain better?"
Last line:
Person #1: i'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff.
Output: Jacob,Langchain
END OF EXAMPLE
EXAMPLE
Conversation history:
Person #1: how's it going today?
AI: "It's going great! How about you?"
Person #1: good! busy working on Langchain. lots to do.
AI: "That sounds like a lot of work! What kind of things are you doing to make Langchain better?"
Last line:
Person #1: i'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff. I'm working with Person #2.
Output: Langchain, Person #2
END OF EXAMPLE
Conversation history (for reference only):
{history}
Last line of conversation (for extraction):
Human: {input}
Output:`,v7e=new ki({inputVariables:["history","input"],template:JWt}),XWt=`You are an AI assistant helping a human keep track of facts about relevant people, places, and concepts in their life. Update and add to the summary of the provided entity in the "Entity" section based on the last line of your conversation with the human. If you are writing the summary for the first time, return a single sentence.
The update should only include facts that are relayed in the last line of conversation about the provided entity, and should only contain facts about the provided entity.
If there is no new information about the provided entity or the information is not worth noting (not an important or relevant fact to remember long-term), output the exact string "UNCHANGED" below.
Full conversation history (for context):
{history}
Entity to summarize:
{entity}
Existing summary of {entity}:
{summary}
Last line of conversation:
Human: {input}
Updated summary (or the exact string "UNCHANGED" if there is no new information about {entity} above):`,x7e=new ki({inputVariables:["entity","summary","history","input"],template:XWt});$n();Rb();Wu();Bb();Kr();var QWt=class extends zu{addUserMessage(t){return this.addMessage(new Zo(t))}addAIMessage(t){return this.addMessage(new kn(t))}async addMessages(t){for(let e of t)await this.addMessage(e)}clear(){throw new Error("Not implemented.")}},P9=class extends QWt{constructor(e){super(...arguments);I(this,"lc_namespace",["langchain","stores","message","in_memory"]);I(this,"messages",[]);this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}};$n();var AR=class{},b7e=(t,e)=>{if(e!==void 0)return t[e];let n=Object.keys(t);if(n.length===1)return t[n[0]]},kR=(t,e)=>{let n=b7e(t,e);if(!n)throw new Error(`input values have ${Object.keys(t).length} keys, you must specify an input key or pass only 1 key as input`);return n},E9=(t,e)=>{let n=b7e(t,e);if(!n&&n!=="")throw new Error(`output values have ${Object.keys(t).length} keys, you must specify an output key or pass only 1 key as output`);return n};function Zxe(t,e){let n=Object.keys(t).filter(r=>!e.includes(r)&&r!=="stop");if(n.length!==1)throw new Error(`One input key expected, but got ${n.length}`);return n[0]}var eHt={};ER(eHt,{BaseChatMemory:()=>iu});var iu=class extends AR{constructor(e){super();I(this,"chatHistory");I(this,"returnMessages",!1);I(this,"inputKey");I(this,"outputKey");this.chatHistory=e?.chatHistory??new P9,this.returnMessages=e?.returnMessages??this.returnMessages,this.inputKey=e?.inputKey??this.inputKey,this.outputKey=e?.outputKey??this.outputKey}async saveContext(e,n){await this.chatHistory.addUserMessage(kR(e,this.inputKey)),await this.chatHistory.addAIMessage(E9(n,this.outputKey))}async clear(){await this.chatHistory.clear()}};pP();Kr();var gj=class extends iu{constructor(e){let{returnMessages:n,inputKey:r,outputKey:o,chatHistory:i,humanPrefix:s,aiPrefix:a,llm:l,prompt:c,summaryChatMessageClass:u}=e;super({returnMessages:n,inputKey:r,outputKey:o,chatHistory:i});I(this,"memoryKey","history");I(this,"humanPrefix","Human");I(this,"aiPrefix","AI");I(this,"llm");I(this,"prompt",y7e);I(this,"summaryChatMessageClass",Vu);this.memoryKey=e?.memoryKey??this.memoryKey,this.humanPrefix=s??this.humanPrefix,this.aiPrefix=a??this.aiPrefix,this.llm=l,this.prompt=c??this.prompt,this.summaryChatMessageClass=u??this.summaryChatMessageClass}async predictNewSummary(e,n){let r=ui(e,this.humanPrefix,this.aiPrefix);return await new Ka({llm:this.llm,prompt:this.prompt}).predict({summary:n,new_lines:r})}},nJe=class extends gj{constructor(e){super(e);I(this,"buffer","")}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){return this.returnMessages?{[this.memoryKey]:[new this.summaryChatMessageClass(this.buffer)]}:{[this.memoryKey]:this.buffer}}async saveContext(e,n){await super.saveContext(e,n);let r=await this.chatHistory.getMessages();this.buffer=await this.predictNewSummary(r.slice(-2),this.buffer)}async clear(){await super.clear(),this.buffer=""}};Kr();var rJe=class extends gj{constructor(e){super(e);I(this,"movingSummaryBuffer","");I(this,"maxTokenLimit",2e3);this.maxTokenLimit=e?.maxTokenLimit??this.maxTokenLimit}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){let n=await this.chatHistory.getMessages();this.movingSummaryBuffer&&(n=[new this.summaryChatMessageClass(this.movingSummaryBuffer),...n]);let r;return this.returnMessages?r=n:r=ui(n,this.humanPrefix,this.aiPrefix),{[this.memoryKey]:r}}async saveContext(e,n){await super.saveContext(e,n),await this.prune()}async prune(){let e=await this.chatHistory.getMessages();this.movingSummaryBuffer&&(e=[new this.summaryChatMessageClass(this.movingSummaryBuffer),...e]);let n=await this.llm.getNumTokens(ui(e,this.humanPrefix,this.aiPrefix));if(n>this.maxTokenLimit){let r=[];for(;n>this.maxTokenLimit;){let o=e.shift();o&&(r.push(o),n=await this.llm.getNumTokens(ui(e,this.humanPrefix,this.aiPrefix)))}this.movingSummaryBuf
`);iv();var oJe=class extends AR{constructor(e){super();I(this,"vectorStoreRetriever");I(this,"inputKey");I(this,"memoryKey");I(this,"returnDocs");I(this,"metadata");this.vectorStoreRetriever=e.vectorStoreRetriever,this.inputKey=e.inputKey,this.memoryKey=e.memoryKey??"memory",this.returnDocs=e.returnDocs??!1,this.metadata=e.metadata}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){let n=kR(e,this.inputKey),r=await this.vectorStoreRetriever.invoke(n);return{[this.memoryKey]:this.returnDocs?r:ebe(r)}}async saveContext(e,n){let r=typeof this.metadata=="function"?this.metadata(e,n):this.metadata,o=Object.entries(e).filter(([i])=>i!==this.memoryKey).concat(Object.entries(n)).map(([i,s])=>`${i}: ${s}`).join(`
`);await this.vectorStoreRetriever.addDocuments([new fi({pageContent:o,metadata:r})])}};pP();Rb();var iJe=class extends zu{};var sJe=class extends iJe{constructor(){super();I(this,"lc_namespace",["langchain","stores","entity","in_memory"]);I(this,"store");this.store=Object.create(null)}async get(e,n){return e in this.store?this.store[e]:n}async set(e,n){this.store[e]=n}async delete(e){delete this.store[e]}async exists(e){return e in this.store}async clear(){this.store=Object.create(null)}};Kr();var aJe=class extends iu{constructor(e){super({chatHistory:e.chatHistory,returnMessages:e.returnMessages??!1,inputKey:e.inputKey,outputKey:e.outputKey});I(this,"entityExtractionChain");I(this,"entitySummarizationChain");I(this,"entityStore");I(this,"entityCache",[]);I(this,"k",3);I(this,"chatHistoryKey","history");I(this,"llm");I(this,"entitiesKey","entities");I(this,"humanPrefix");I(this,"aiPrefix");this.llm=e.llm,this.humanPrefix=e.humanPrefix,this.aiPrefix=e.aiPrefix,this.chatHistoryKey=e.chatHistoryKey??this.chatHistoryKey,this.entitiesKey=e.entitiesKey??this.entitiesKey,this.entityExtractionChain=new Ka({llm:this.llm,prompt:e.entityExtractionPrompt??v7e}),this.entitySummarizationChain=new Ka({llm:this.llm,prompt:e.entitySummarizationPrompt??x7e}),this.entityStore=e.entityStore??new sJe,this.entityCache=e.entityCache??this.entityCache,this.k=e.k??this.k}get memoryKeys(){return[this.chatHistoryKey]}get memoryVariables(){return[this.entitiesKey,this.chatHistoryKey]}async loadMemoryVariables(e){let n=this.inputKey??Zxe(e,this.memoryVariables),r=await this.chatHistory.getMessages(),o=ui(r.slice(-this.k*2),this.humanPrefix,this.aiPrefix),i=await this.entityExtractionChain.predict({history:o,input:e[n]}),s=i.trim()==="NONE"?[]:i.split(",").map(c=>c.trim()),a={};for(let c of s)a[c]=await this.entityStore.get(c,"No current information known.");this.entityCache=[...s];let l=this.returnMessages?r.slice(-this.k*2):o;return{[this.chatHistoryKey]:l,[this.entitiesKey]:a}}async saveContext(e,n){await super.saveContext(e,n);let r=this.inputKey??Zxe(e,this.memoryVariables),o=await this.chatHistory.getMessages(),i=ui(o.slice(-this.k*2),this.humanPrefix,this.aiPrefix),s=e[r];for(let a of this.entityCache){let l=await this.entityStore.get(a,"No current information known."),c=await this.entitySummarizationChain.predict({summary:l,entity:a,history:i,input:s});c.trim()!=="UNCHANGED"&&await this.entityStore.set(a,c.trim())}}async clear(){await super.clear(),await this.entityStore.clear()}};var lJe=class extends iu{constructor(e){super({chatHistory:e?.chatHistory,returnMessages:e?.returnMessages??!1,inputKey:e?.inputKey,outputKey:e?.outputKey});I(this,"humanPrefix","Human");I(this,"aiPrefix","AI");I(this,"memoryKey","history");I(this,"memories",[]);this.memories=e?.memories??this.memories,this.humanPrefix=e?.humanPrefix??this.humanPrefix,this.aiPrefix=e?.aiPrefix??this.aiPrefix,this.memoryKey=e?.memoryKey??this.memoryKey,this.checkRepeatedMemoryVariable(),this.checkInputKey()}checkRepeatedMemoryVariable(){let e=[];for(let n of this.memories){let r=e.filter(o=>n.memoryKeys.includes(o));if(r.length>0)throw new Error(`The same variables ${[...r]} are found in multiple memory objects, which is not allowed by CombinedMemory.`);e.push(...n.memoryKeys)}}checkInputKey(){for(let e of this.memories)e.chatHistory!==void 0&&e.inputKey===void 0&&console.warn(`When using CombinedMemory, input keys should be set so the input is known. Was not set on ${e}.`)}async loadMemoryVariables(e){let n={};for(let r of this.memories){let o=await r.loadMemoryVariables(e);n={...n,...o}}return n}async saveContext(e,n){for(let r of this.memories)await r.saveContext(e,n)}async clear(){for(let e of this.memories)typeof e.clear=="function"&&await e.clear()}get memoryKeys(){let e=[];for(let n of this.memories)e.push(...n.memoryKeys);return e}};Kr();var cJe=class extends iu{constructor(e){super(e);I(this,"humanPrefix","Human");I(this,"aiPrefix","AI");I(this,"memoryKey","history");I(this,"maxTokenLimit",2e3);I(this,"llm");this.llm=e.llm,this.humanPrefix=e?.humanPrefix??this.humanPrefix,
Answer the question with as detailed as possible based only on the following context:
{context}
Question: {question}
`;this.qaPrompt=ou.fromMessages([fh.fromTemplate(e)])}escapeTemplateString(e){return e.replace(/\{/g,"{{").replace(/\}/g,"}}")}getChatPrompt(){return this.chatPrompt}async getQAPrompt({question:e,context:n,systemMessage:r}){return await this.qaPrompt.format({question:e,context:n,system_message:r})}};var vj=class{constructor(e){this.retrievedDocuments=[];this.pendingModelError=null;this.app=e,this.memoryManager=yj.getInstance(),this.chatModelManager=Np.getInstance(),this.promptManager=wj.getInstance(),this.userMemoryManager=new o_(e),this.initialize().catch(n=>z("ChainManager initialize failed",n)),Ho(()=>{this.createChainWithNewModel().catch(n=>z("createChainWithNewModel failed",n))})}getRetrievedDocuments(){return this.retrievedDocuments}async initialize(){await this.createChainWithNewModel()}validateChainType(e){if(e==null)throw new Error("No chain type set")}validateChatModel(){if(this.pendingModelError)throw this.pendingModelError;if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){let e="Chat model is not initialized properly, check your API key in Copilot setting and make sure you have API access.";throw new rA(e)}}storeRetrieverDocuments(e){this.retrievedDocuments=e}async createChainWithNewModel(e={},n=!0){let r,o=ym(),i=br();if(!(o==="project"&&!i))try{if(r=o==="project"?i?.projectModelKey:Iu(),!r)throw new rA("No model key found. Please select a model in settings.");if(n){let s=$f(r,q().activeModels);if(s||(console.error("Resetting default model. No model configuration found for: ",r),s=Gh[0],r=s.name+"|"+s.provider),o==="project"&&!s.projectEnabled){let l=q().activeModels.find(c=>c.enabled&&c.projectEnabled);if(l)s=l,r=l.name+"|"+l.provider,new uJe.Notice(`Model ${s.name} is not available in project mode. Switching to ${l.name}.`);else throw new Error("No project-enabled models available. Please enable a model for project mode in settings.")}let a={...s,...i?.modelConfigs};await this.chatModelManager.setChatModel(a),this.pendingModelError=null}this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())?(this.validateChainType(o),e.refreshIndex&&await this.refreshVaultIndex()):console.error("createChainWithNewModel: skipping chain-type housekeeping \u2014 no chat model set."),k(`Setting model to ${r}`)}catch(s){this.pendingModelError=s instanceof Error?s:new Error(String(s)),z(`createChainWithNewModel failed: ${s}`),k(`modelKey: ${r||Iu()}`)}}getChainRunner(){let e=ym(),n=q();switch(e){case"llm_chain":return new hB(this);case"vault_qa":return new pz(this);case"copilot_plus":return n.enableAutonomousAgent?new nj(this):new dy(this);case"project":return new Qz(this);default:throw new Error(`Unsupported chain type: ${String(e)}`)}}async refreshVaultIndex(){if(!q().enableSemanticSearchV3)return;await(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().indexVaultToVectorStore(!1)}async runChain(e,n,r,o,i={}){let{ignoreSystemMessage:s=!1}=i,a=e.contextEnvelope?.layers.find(u=>u.id==="L5_USER")?.text;k(`Step 0: Initial user message:
`,a||e.originalMessage||e.message),this.validateChatModel();let l=this.chatModelManager.getChatModel();if(s||QD(l)){let u=ou.fromMessages([new Pv("history"),ff.fromTemplate("{input}")]);QD(l)&&(u=ou.fromMessages([[uo,r_()||""],u])),this.createChainWithNewModel({prompt:u},!1).catch(d=>z("createChainWithNewModel failed",d))}return await this.getChainRunner().run(e,n,r,o,i)}};Ir();ye();Se();qe();var D9=class t{constructor(e){this.app=e}static getInstance(e){return t.instance||(t.instance=new t(e)),t.instance}clearAllLoadStates(){rke({success:[],failed:[],processingFiles:[],total:[]})}async executeWithProcessTracking(e,n,r){this.setFileOrUrlStartProcess(e);try{let o=await r();return this.setFileOrUrlProcessSuccessful(e),o}catch(o){let i=uv(o)?"Rate limit exceeded. (Rate limit: 50 files or 100MB per 3 hours, whichever is reached first)":Xt(o);throw this.setFileOrUrlProcessFailed(e,n,i),o}}setFileOrUrlStartProcess(e){Kn.set(n$,n=>{let r={...n};return r.failed.find(o=>o.path===e)&&(r.failed=r.failed.filter(o=>o.path!==e)),r.success.includes(e)&&(r.success=r.success.filter(o=>o!==e)),r.processingFiles.includes(e)||(r.processingFiles=[...r.processingFiles,e]),r.total.includes(e)||(r.total=[...r.total,e]),r})}setFileOrUrlProcessSuccessful(e){ig("processingFiles",n=>n.filter(r=>r!==e)),ig("success",n=>n.includes(e)?n:[...n,e])}setFileOrUrlProcessFailed(e,n,r){ig("processingFiles",o=>o.filter(i=>i!==e)),ig("failed",o=>{if(!o.find(s=>s.path===e)){let s={path:e,type:n,error:r,timestamp:Date.now()};return[...o,s]}return o})}preComputeAllItems(e,n){k(`[preComputeAllItems] Starting pre-computation for project: ${e.name}`);let r=[];r.push(...n.map(s=>s.path));let o=e.contextSource?.webUrls?.trim()||"";if(o){let s=o.split(`
`).filter(a=>a.trim());r.push(...s)}let i=e.contextSource?.youtubeUrls?.trim()||"";if(i){let s=i.split(`
`).filter(a=>a.trim());r.push(...s)}if(r.length>0){let s=[...new Set([...r])];ig("total",a=>s),k(`[preComputeAllItems] Project ${e.name}: Added ${r.length} items to tracking (${s.length} total unique items)`)}}markAllCachedItemsAsSuccess(e,n,r){k(`[markAllCachedItemsAsSuccess] Starting for project: ${e.name||"default"}`);let o=e.contextSource?.webUrls?.trim()||"";if(o){let a=o.split(`
`).filter(l=>l.trim()).filter(l=>n.webContexts[l]);a.forEach(l=>{this.markCachedItemAsSuccess(l)}),a.length>0&&k(`[markAllCachedItemsAsSuccess] Project ${e.name}: Marked ${a.length} cached Web URLs as successful`)}let i=e.contextSource?.youtubeUrls?.trim()||"";if(i){let a=i.split(`
`).filter(l=>l.trim()).filter(l=>n.youtubeContexts[l]);a.forEach(l=>{this.markCachedItemAsSuccess(l)}),a.length>0&&k(`[markAllCachedItemsAsSuccess] Project ${e.name}: Marked ${a.length} cached YouTube URLs as successful`)}if(n.fileContexts){let s=new Set(r.filter(l=>l.extension==="md").map(l=>l.path)),a=Object.keys(n.fileContexts).filter(l=>s.has(l));a.forEach(l=>{this.markCachedItemAsSuccess(l)}),a.length>0&&k(`[markAllCachedItemsAsSuccess] Project ${e.name}: Marked ${a.length} cached files that match current project patterns as successful.`)}}markCachedItemAsSuccess(e){ig("total",n=>n.includes(e)?n:[...n,e]),ig("success",n=>n.includes(e)?n:[...n,e])}makeItemFailed(e,n,r){ig("total",o=>o.includes(e)?o:[...o,e]),ig("failed",o=>{if(!o.find(s=>s.path===e)){let s={path:e,type:n,error:r,timestamp:Date.now()};return[...o,s]}return o})}};var Sl=class t{constructor(e,n){this.previousProjectRecords=[];this.app=e,this.plugin=n,this.currentProjectId=null,this.chainMangerInstance=new vj(e),this.projectContextCache=ti.getInstance(),this.fileParserManager=new iy(di.getInstance(),this.app.vault,!0,null),this.loadTracker=D9.getInstance(this.app),JAe(()=>{this.getCurrentChainManager().createChainWithNewModel()}),QAe(()=>{if(RA())return;let r=q(),o=r.enableSemanticSearchV3&&r.indexVaultToVectorStore==="ON MODE SWITCH"&&(ym()==="vault_qa"||ym()==="copilot_plus");this.getCurrentChainManager().createChainWithNewModel({refreshIndex:o})}),OA(r=>{this.switchProject(r)}),this.setupProjectListChangeMonitor()}setupProjectListChangeMonitor(){this.previousProjectRecords=[],this.projectRecordsUnsubscriber?.(),this.projectRecordsUnsubscriber=$5e(e=>{let n=this.previousProjectRecords.map(o=>o.project),r=e.map(o=>o.project);this.previousProjectRecords=e,this.currentProjectId&&!r.some(o=>o.id===this.currentProjectId)&&br()?.id===this.currentProjectId&&(ee(`[ProjectManager] Active project id="${this.currentProjectId}" no longer exists, clearing selection`),this.switchProject(null).catch(o=>z("[ProjectManager] Failed to switch away from removed project",o)));for(let o of r){let i=n.find(s=>s.id===o.id);i&&this.hasMeaningfulProjectConfigChange(i,o)&&(this.compareAndUpdateCache(i,o).catch(s=>z("[ProjectManager] compareAndUpdateCache failed",s)),this.currentProjectId===o.id&&br()?.id===o.id&&(Gx(o),Promise.all([this.loadProjectContext(o,!0),this.getCurrentChainManager().createChainWithNewModel()]).catch(s=>{z(`[Projects] Failed to refresh current project after config change id=${o.id}`,s)})))}})}hasMeaningfulProjectConfigChange(e,n){let r={...e,UsageTimestamps:0},o={...n,UsageTimestamps:0};return JSON.stringify(r)!==JSON.stringify(o)}static getInstance(e,n){return t.instance||(t.instance=new t(e,n)),t.instance}getCurrentChainManager(){return this.chainMangerInstance}getCurrentProjectId(){return this.currentProjectId}touchProjectUsageTimestamps(e){Xu.getInstance(this.app).touchProjectLastUsed(e.id)}getProjectUsageTimestampsManager(){return Xu.getInstance(this.app).getProjectUsageTimestampsManager()}async switchProject(e){if(!(e&&this.currentProjectId===e.id)&&!(!e&&this.currentProjectId===null))try{if(this.loadTracker.clearAllLoadStates(),rg(!0),k("Project loading started..."),!e){await this.saveCurrentProjectMessage(),this.currentProjectId=null,br()!==null&&Gx(null),await this.loadNextProjectMessage(),this.refreshChatView();return}let n=e.id;await this.saveCurrentProjectMessage(),this.currentProjectId=n,await this.loadNextProjectMessage(),await this.getCurrentChainManager().createChainWithNewModel(),this.fileParserManager=new iy(di.getInstance(),this.app.vault,!0,e),await this.loadProjectContext(e),this.refreshChatView(),this.touchProjectUsageTimestamps(e),k(`Switched to project: ${e.name}`)}catch(n){throw z(`Failed to switch project: ${n}`),n}finally{rg(!1)}}async saveCurrentProjectMessage(){await this.plugin.autosaveCurrentChat()}async loadNextProjectMessage(){await this.plugin.chatUIState.handleProjectSwitch()}async loadProjectContext(e,n=!1){n&&(this.loadTracker.clearAllLoadStates(),rg(!0));try{if(!e.contextSource)return ee(`[loadProjectContext] Project
`).filter(m=>m.trim()),p=c.split(`
`).filter(m=>m.trim());await this.projectContextCache.removeWebUrls(n,f.filter(m=>!p.includes(m)))}let u=e.contextSource?.youtubeUrls||"",d=n.contextSource?.youtubeUrls||"";if(u!==d){let f=u.split(`
`).filter(m=>m.trim()),p=d.split(`
`).filter(m=>m.trim());await this.projectContextCache.removeYoutubeUrls(n,f.filter(m=>!p.includes(m)))}}catch(r){z(`Error comparing project configurations: ${r}`)}}refreshChatView(){let e=this.app.workspace.getLeavesOfType(No)[0]?.view;e&&e.updateView()}async getProjectContext(e){let n=QN().find(o=>o.id===e);if(!n)return ee(`[getProjectContext] Project not found for ID: ${e}`),null;k(`[getProjectContext] Getting context for project: ${n.name} (ID: ${e})`);let r=this.projectContextCache.getSync(n);if(!r||r.markdownNeedsReload){r?k(`[getProjectContext] Project ${n.name}: Markdown needs reload. Triggering full load.`):k(`[getProjectContext] Project ${n.name}: Memory cache miss. Triggering full load.`);let o=await this.loadProjectContext(n,!0);if(!o)return z(`[getProjectContext] Project ${n.name}: loadProjectContext returned null.`),null;r=o}else k(`[getProjectContext] Project ${n.name}: Memory cache hit and markdown OK. Using existing context.`);return this.formatProjectContextWithFiles(r,n)}async formatProjectContextWithFiles(e,n){let r=[];if(e.markdownContext&&r.push(`## Markdown Files
${e.markdownContext}`),Object.keys(e.webContexts).length>0&&r.push(`## Web Content
${Object.values(e.webContexts).join(`
`)}`),Object.keys(e.youtubeContexts).length>0&&r.push(`## YouTube Content
${Object.values(e.youtubeContexts).join(`
`)}`),Object.keys(e.fileContexts).length>0){let o=Object.entries(e.fileContexts).filter(([i])=>i.split(".").pop()?.toLowerCase()!=="md");if(o.length>0){let i=o.map(async([a,l])=>{let c=a.split("/"),u=c[c.length-1],d=u.split(".").pop()||"",f=await this.projectContextCache.getOrReuseFileContext(n,a)||"[Content not available]";return`[[${u}]]
path: ${a}
type: ${d}
modified: ${new Date(l.timestamp).toISOString()}
${f}`}),s=await Promise.all(i);s.length>0&&r.push(`## Other Files
${s.join(`
`)}`)}}return`
# Project Context
The following information is the relevant context for this project. Use this information to inform your responses when appropriate:
<ProjectContext>
${r.join(`
`)}
</ProjectContext>
`}formatProjectContext(e){let n=[];if(e.markdownContext&&n.push(`## Markdown Files
${e.markdownContext}`),Object.keys(e.webContexts).length>0&&n.push(`## Web Content
${Object.values(e.webContexts).join(`
`)}`),Object.keys(e.youtubeContexts).length>0&&n.push(`## YouTube Content
${Object.values(e.youtubeContexts).join(`
`)}`),Object.keys(e.fileContexts).length>0){let r="";for(let[o,i]of Object.entries(e.fileContexts)){let s=o.split("/"),a=s[s.length-1],l=a.split(".").pop()||"";r+=`[[${a}]]
path: ${o}
type: ${l}
modified: ${new Date(i.timestamp).toISOString()}
`}r&&n.push(`## Other Files
${r}`)}return`
# Project Context
The following information is the relevant context for this project. Use this information to inform your responses when appropriate:
<ProjectContext>
${n.join(`
`)}
</ProjectContext>
`}async processMarkdownFiles(e,n,r){if(k(`[processMarkdownFiles] Starting for project: ${e.name}`),n.markdownNeedsReload||!n.markdownContext||!n.markdownContext.trim()){k(`[processMarkdownFiles] Project ${e.name}: Processing markdown content.`);let o=await this.processMarkdownFileContext(r);this.projectContextCache.updateProjectMarkdownFilesFromPatterns(e,n,r),n.markdownContext=o,n.markdownNeedsReload=!1,k(`[processMarkdownFiles] Project ${e.name}: Markdown content updated.`)}else k(`[processMarkdownFiles] Project ${e.name}: Markdown content already up-to-date.`);return k(`[processMarkdownFiles] Completed for project: ${e.name}. Total fileContexts: ${Object.keys(n.fileContexts||{}).length}`),n}async processMarkdownFileContext(e){let n=e.filter(o=>o.extension==="md");k(`Found ${n.length} markdown files to process for project context`);let r=await Promise.all(n.map(async o=>{let i="",s="";try{let[a,l]=await this.loadTracker.executeWithProcessTracking(o.path,"md",async()=>Promise.all([this.app.vault.adapter.stat(o.path),this.app.vault.read(o)]));s=`[[${o.basename}]]
path: ${o.path}
type: ${o.extension}
created: ${a?new Date(a.ctime).toISOString():"unknown"}
modified: ${a?new Date(a.mtime).toISOString():"unknown"}`,i=l,k(`Completed processing markdown file: ${o.path}`)}catch(a){z(`Error processing file ${o.path}: ${a}`),i=`[Error: ${Xt(a)}]`}return`${s}
${i}`}));return k("All markdown files processed for project context"),r.join(`
`)}async processWebUrls(e,n){k(`[processWebUrls] Starting for project: ${e.name}`);let r=e.contextSource?.webUrls?.trim()||"";if(!r)return Object.keys(n.webContexts).length>0&&(k(`[processWebUrls] Project ${e.name}: Clearing all Web contexts as none are configured.`),n.webContexts={}),n;let o=r.split(`
`).filter(u=>u.trim());k(`[processWebUrls] Project ${e.name}: Found ${o.length} URLs in config.`);let i=Object.keys(n.webContexts),s=o.filter(u=>!n.webContexts[u]);s.length>0&&k(`[processWebUrls] Project ${e.name}: Fetching content for ${s.length} new/updated Web URLs.`);let a=i.filter(u=>!o.includes(u));if(a.length>0){k(`[processWebUrls] Project ${e.name}: Removing ${a.length} obsolete Web URL contexts.`);for(let u of a)delete n.webContexts[u]}let l=s.map(async u=>{let d=await this.processWebUrlContext(u);return d&&k(`[processWebUrls] Project ${e.name}: Successfully fetched content for URL: ${u.substring(0,50)}...`),{url:u,context:d}});return(await Promise.all(l)).forEach(u=>{u&&u.context?n.webContexts[u.url]=u.context:u&&!u.context&&ee(`[processWebUrls] Project ${e.name}: Fetched empty content for Web URL: ${u.url}`)}),k(`[processWebUrls] Completed for project: ${e.name}. Total Web contexts: ${Object.keys(n.webContexts).length}`),n}async processYoutubeUrls(e,n){k(`[processYoutubeUrls] Starting for project: ${e.name}`);let r=e.contextSource?.youtubeUrls?.trim()||"";if(!r)return Object.keys(n.youtubeContexts).length>0&&(k(`[processYoutubeUrls] Project ${e.name}: Clearing all YouTube contexts as none are configured.`),n.youtubeContexts={}),n;let o=r.split(`
`).filter(u=>u.trim());k(`[processYoutubeUrls] Project ${e.name}: Found ${o.length} YouTube URLs in config.`);let i=Object.keys(n.youtubeContexts),s=o.filter(u=>!n.youtubeContexts[u]);s.length>0&&k(`[processYoutubeUrls] Project ${e.name}: Fetching transcripts for ${s.length} new/updated YouTube URLs.`);let a=i.filter(u=>!o.includes(u));if(a.length>0){k(`[processYoutubeUrls] Project ${e.name}: Removing ${a.length} obsolete YouTube URL contexts.`);for(let u of a)delete n.youtubeContexts[u]}let l=s.map(async u=>{let d=await this.processYoutubeUrlContext(u);return d&&k(`[processYoutubeUrls] Project ${e.name}: Successfully fetched transcript for YouTube URL: ${u.substring(0,50)}...`),{url:u,context:d}});return(await Promise.all(l)).forEach(u=>{u&&u.context?n.youtubeContexts[u.url]=u.context:u&&!u.context&&ee(`[processYoutubeUrls] Project ${e.name}: Fetched empty transcript for YouTube URL: ${u.url}`)}),k(`[processYoutubeUrls] Completed for project: ${e.name}. Total YouTube contexts: ${Object.keys(n.youtubeContexts).length}`),n}async processWebUrlContext(e){if(!e?.trim())return"";try{let n=tO.getInstance(),{urlContext:r}=await this.loadTracker.executeWithProcessTracking(e,"web",async()=>{let o=await n.processUrls(e);if(o.processedErrorUrls[e])throw new Error(o.processedErrorUrls[e]);return o});return r||""}catch(n){return z(`Failed to process web URL: ${n}`),""}}async processYoutubeUrlContext(e){if(!e?.trim())return"";try{let n=await this.loadTracker.executeWithProcessTracking(e,"youtube",async()=>di.getInstance().youtube4llm(e));return n.response.transcript?`
YouTube transcript from ${e}:
${n.response.transcript}`:""}catch(n){return z(`Failed to process YouTube URL ${e}: ${n}`),new mP.Notice(`Failed to process YouTube URL ${e}: ${Xt(n)}`),""}}async processNonMarkdownFiles(e,n,r){let o=n.filter(c=>c.extension!=="md");if(k(`[loadProjectContext] Project ${e.name}: Checking for non-markdown processing: ${o.length} files .`),o.length<=0)return;this.fileParserManager=new iy(di.getInstance(),this.app.vault,!0,e);let i=[],s=[];for(let c of o)r.fileContexts[c.path]?.cacheKey?i.push(c):s.push(c);let a=[...i,...s],l=0;for(let c of a){let u=c.path;if(this.fileParserManager.supportsExtension(c.extension))try{await this.loadTracker.executeWithProcessTracking(u,"nonMd",async()=>{let d=await this.projectContextCache.getOrReuseFileContext(e,u);d?(await DC(c,d,this.app.vault),l++):(k(`[loadProjectContext] Project ${e.name}: Parsing/caching new/updated file: ${u}`),await this.fileParserManager.parseFile(c,this.app.vault),l++)})}catch(d){if(z(`[loadProjectContext] Project ${e.name}: Error parsing file ${u}:`,d),uv(d))throw d}}l>0&&k(`[loadProjectContext] Project ${e.name}: Processed and cached ${l} non-markdown files.`)}async retryFailedItem(e){try{if(!this.currentProjectId){ee("[retryFailedItem] No current project, aborting retry");return}let n=QN().find(r=>r.id===this.currentProjectId);if(!n){z(`[retryFailedItem] Current project not found: ${this.currentProjectId}`);return}switch(k(`[retryFailedItem] Starting retry for ${e.type} item: ${e.path}`),e.type){case"web":await this.retryWebUrl(n,e.path);break;case"youtube":await this.retryYoutubeUrl(n,e.path);break;case"md":await this.retryMarkdownFile(n,e.path);break;case"nonMd":await this.retryNonMarkdownFile(n,e.path);break;default:ee("[retryFailedItem] Unknown item type:",e.type);return}k(`[retryFailedItem] Successfully retried ${e.type} item: ${e.path}`),new mP.Notice(`Retry successful: ${e.path}`)}catch(n){z(`[retryFailedItem] Failed to retry ${e.type} item ${e.path}:`,n),new mP.Notice(`Retry failed: ${Xt(n)}`)}}async retryWebUrl(e,n){let r=await this.processWebUrlContext(n);if(!r){ee(`[retryWebUrl] Project ${e.name}: Fetched empty content for Web URL: ${n}`);return}k(`[retryWebUrl] Project ${e.name}: Successfully fetched content for URL: ${n.substring(0,50)}...`),await this.projectContextCache.updateWebUrl(e,n,r)}async retryYoutubeUrl(e,n){let r=await this.processYoutubeUrlContext(n);if(!r){ee(`[retryYoutubeUrl] Project ${e.name}: Fetched empty transcript for YouTube URL: ${n}`);return}k(`[retryYoutubeUrl] Project ${e.name}: Successfully fetched transcript for YouTube URL: ${n.substring(0,50)}...`),await this.projectContextCache.updateYoutubeUrl(e,n,r)}async retryMarkdownFile(e,n){let r=this.app.vault.getAbstractFileByPath(n);if(!(r instanceof mP.TFile)||r.extension!=="md")throw new Error(`File not found or not a markdown file: ${n}`);try{await this.loadTracker.executeWithProcessTracking(r.path,"md",async()=>{}),k(`[retryMarkdownFile] Successfully reprocessed markdown file: ${n}`),await this.projectContextCache.invalidateMarkdownContext(e)}catch(o){throw z(`[retryMarkdownFile] Error processing file ${n}: ${o}`),o}}async retryNonMarkdownFile(e,n){let r=this.app.vault.getAbstractFileByPath(n);if(!(r instanceof mP.TFile)||r.extension==="md")throw new Error(`File not found or is a markdown file: ${n}`);if(!this.fileParserManager.supportsExtension(r.extension))throw new Error(`Unsupported file extension: ${r.extension}`);try{await this.loadTracker.executeWithProcessTracking(n,"nonMd",async()=>this.fileParserManager.parseFile(r,this.app.vault)),k(`[retryNonMarkdownFile] Successfully reprocessed non-markdown file: ${n}`)}catch(o){throw z(`[retryNonMarkdownFile] Error processing file ${n}: ${o}`),o}}getProjectAllFiles(e){let{inclusions:n,exclusions:r}=Bo({inclusions:e.contextSource.inclusions,exclusions:e.contextSource.exclusions,isProject:!0});return this.app.vault.getFiles().filter(o=>Qr(o,n,r,!0))}onunload(){this.projectRecordsUnsubscriber?.(),this.projectRecordsUnsubscriber=void 0,this.projectContextCache.cleanup()}};Ir();HS();ye();var WJe=require("obsidian");rn();var $9=N(U(
1. Preserve the meaning and tone
2. Maintain appropriate cultural context
3. Keep formatting and structure
Return only the translated text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1010,modelKey:"",lastUsedMs:0},{title:"Summarize",content:"Create a bullet-point summary of {}. Each bullet point should capture a key point. Return only the bullet-point summary.",showInContextMenu:!0,showInSlashMenu:!0,order:1020,modelKey:"",lastUsedMs:0},{title:"Simplify",content:"Simplify {} to a 6th-grade reading level (ages 11-12). Use simple sentences, common words, and clear explanations. Maintain the original key concepts. Return only the simplified text.",showInContextMenu:!0,showInSlashMenu:!0,order:1030,modelKey:"",lastUsedMs:0},{title:"Explain like I am 5",content:`Explain {} in simple terms that a 5-year-old would understand:
1. Use basic vocabulary
2. Include simple analogies
3. Break down complex concepts
Return only the simplified explanation.`,showInContextMenu:!0,showInSlashMenu:!0,order:1040,modelKey:"",lastUsedMs:0},{title:"Emojify",content:`Add relevant emojis to enhance {}. Follow these rules:
1. Insert emojis at natural breaks in the text
2. Never place two emojis next to each other
3. Keep all original text unchanged
4. Choose emojis that match the context and tone
Return only the emojified text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1050,modelKey:"",lastUsedMs:0},{title:"Make shorter",content:`Reduce {} to half its length while preserving these elements:
1. Main ideas and key points
2. Essential details
3. Original tone and style
Return only the shortened text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1060,modelKey:"",lastUsedMs:0},{title:"Make longer",content:`Expand {} to twice its length by:
1. Adding relevant details and examples
2. Elaborating on key points
3. Maintaining the original tone and style
Return only the expanded text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1070,modelKey:"",lastUsedMs:0},{title:"Generate table of contents",content:"Generate a hierarchical table of contents for {}. Use appropriate heading levels (H1, H2, H3, etc.). Include page numbers if present. Return only the table of contents.",showInContextMenu:!1,showInSlashMenu:!1,order:1080,modelKey:"",lastUsedMs:0},{title:"Generate glossary",content:'Create a glossary of important terms, concepts, and phrases from {}. Format each entry as "Term: Definition". Sort entries alphabetically. Return only the glossary.',showInContextMenu:!1,showInSlashMenu:!1,order:1090,modelKey:"",lastUsedMs:0},{title:"Remove URLs",content:"Remove all URLs from {}. Preserve all other content and formatting. URLs may be in various formats (http, https, www). Return only the text with URLs removed.",showInContextMenu:!1,showInSlashMenu:!1,order:1100,modelKey:"",lastUsedMs:0},{title:"Rewrite as tweet",content:`Rewrite {} as a single tweet with these requirements:
1. Maximum 280 characters
2. Use concise, impactful language
3. Maintain the core message
Return only the tweet text.`,showInContextMenu:!1,showInSlashMenu:!1,order:1110,modelKey:"",lastUsedMs:0},{title:"Rewrite as tweet thread",content:`Convert {} into a Twitter thread following these rules:
1. Each tweet must be under 240 characters
2. Start with "THREAD START" on its own line
3. Separate tweets with "
---
"
4. End with "THREAD END" on its own line
5. Make content engaging and clear
Return only the formatted thread.`,showInContextMenu:!1,showInSlashMenu:!1,order:1120,modelKey:"",lastUsedMs:0},{title:"Clip YouTube Transcript",content:`
Based on the YouTube video information and transcript provided in the context, generate a complete Obsidian note in the following format.
IMPORTANT: If no YouTube video context is found, remind the user to:
1. Open a YouTube video in Web Viewer (or use @ to select a YouTube web tab)
2. Then use this command again
Generate the note with this exact structure:
---
title: "<video title>"
description: "<first 200 chars of description>"
channel: "<channel name>"
url: "<video url>"
duration: "<duration>"
published: <upload date in YYYY-MM-DD format>
thumbnailUrl: "<YouTube thumbnail URL: i.ytimg.com/vi/VIDEO_ID/maxresdefault.jpg with https protocol>"
genre:
- "<genre>"
watched:
---
![<video title>](<video url>)
> [!summary]- Description
> <full video description, preserve line breaks>
## Summary
<Brief 2-3 paragraph summary of the video content>
## Key Takeaways
<List 5-8 key takeaways as bullet points>
## Mindmap
CRITICAL Mermaid mindmap syntax rules - MUST follow exactly:
- Root node format: root(Topic Name) - use round brackets, NO double brackets
- Child nodes: just plain text, no brackets needed
- Do NOT use quotes, parentheses, brackets, or any special characters in text
- Do NOT use icons or emojis
- Keep all node text short and simple - max 3-4 words per node
- Use only letters, numbers, and spaces
Example of CORRECT syntax:
\`\`\`mermaid
mindmap
root(Video Main Topic)
First Theme
Detail one
Detail two
Second Theme
Detail three
Third Theme
\`\`\`
## Notable Quotes
<List 5-10 notable quotes from the transcript. Format each as:>
- [<timestamp>: <quote text>](<video_url>&t=<seconds>s)
Return only the markdown content without any explanations or comments.`,showInContextMenu:!1,showInSlashMenu:!0,order:1130,modelKey:"",lastUsedMs:0},{title:"Clip Web Page",content:`
Based on the web page content provided in the context (from Obsidian Web Clipper or Web Viewer), generate a complete Obsidian note.
IMPORTANT: If no web page context is found, remind the user to:
1. Open a web page in Web Viewer (or use @ to select a web tab)
2. Or open a note clipped by Obsidian Web Clipper
3. Then use this command again
Generate the note with this exact structure:
---
title: "<page title>"
source: "<page url>"
description: "<brief description>"
tags:
- "clippings"
---
## Summary
<Brief 2-3 paragraph summary of the page content>
## Key Takeaways
<List 5-8 key takeaways as bullet points>
## Mindmap
CRITICAL Mermaid mindmap syntax rules - MUST follow exactly:
- Root node format: root(Topic Name) - use round brackets, NO double brackets
- Child nodes: just plain text, no brackets needed
- Do NOT use quotes, parentheses, brackets, or any special characters in text
- Keep all node text short and simple - max 3-4 words per node
\`\`\`mermaid
mindmap
root(Main Topic)
Theme One
Detail
Theme Two
Detail
\`\`\`
## Notable Quotes
<List 3-5 notable quotes from the content, if any>
Return only the markdown content without any explanations or comments.`,showInContextMenu:!1,showInSlashMenu:!0,order:1140,modelKey:"",lastUsedMs:0}];ye();var RR=require("obsidian");Se();Id();Id();var gP=Jh(),yP=Oo([]),ube=new Set;function wP(t){ube.add(t)}function vP(t){ube.delete(t)}function bj(t){return ube.has(t)}function Cj(t){let e=gP.get(yP);gP.set(yP,e.filter(n=>n.title!==t))}function xP(t,e){let n=gP.get(yP),r;(e?n.findIndex(i=>i.title===e):-1)!==-1?r=n.map(i=>i.title===e?t:i):r=[...n,t],gP.set(yP,r)}function q9(t){gP.set(yP,t)}function G9(){return Wl(yP,{store:gP})}function td(){return gP.get(yP)}rD();qe();Ky();It();function Y9(t,e,n){let r=t.trim();return r?t!==r?"Command name cannot have leading or trailing spaces":n&&t===n?null:/[#<>:"/\\|?*[\]^\x00-\x1F]/g.test(r)?'Command name contains invalid characters. Avoid using: < > : " / \\ | ? * [ ] ^':e.some(i=>i.title.toLowerCase()===r.toLowerCase())?"A command with this name already exists":null:"Command name cannot be empty"}function LR(t){return encodeURIComponent(t.toLowerCase())}function h_(){return(0,RR.normalizePath)(q().customPromptsFolder)}function DR(t){return`${h_()}/${t}.md`}function $R(t){if(!(t instanceof RR.TFile)||t.extension!=="md")return!1;let e=h_();return!(!t.path.startsWith(e+"/")||t.path.slice(e.length+1).includes("/"))}function jJe(t){return app.metadataCache.getFileCache(t)?.frontmatter?.[gy]!=null}async function _j(t){let e=await app.vault.read(t),n=Qh(e),r=app.metadataCache.getFileCache(t),o=r?.frontmatter?.[Av]??hy.showInContextMenu,i=r?.frontmatter?.[kv]??hy.showInSlashMenu,s=r?.frontmatter?.[Nv]??hy.lastUsedMs,a=r?.frontmatter?.[gy]??hy.order,l=r?.frontmatter?.[Mv]??hy.modelKey;return{title:t.basename,modelKey:l,content:n,showInContextMenu:o,showInSlashMenu:i,order:a,lastUsedMs:s}}async function Z9(){let t=app.vault.getFiles().filter(n=>$R(n)),e=await Promise.all(t.map(_j));return q9(e),e}function Sj(t){return Xh(t,"manual",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:()=>0,getManualOrder:e=>e.order})}function HHt(t){return Xh(t,"recent",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:e=>e.lastUsedMs})}function KHt(t){return Xh(t,"name",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:()=>0})}function J9(t){switch(q().promptSortStrategy){case"timestamp":return HHt(t);case"alphabetical":return KHt(t);case"manual":return Sj(t);default:return t}}async function Tj(t,e,n=!1){let o=(await Ij(t,e,app.vault,app.workspace.getActiveFile())).processedPrompt;if(o.includes(`{${bu}}`)||n)return o;let i=o.indexOf(cbe);return i===-1?e.trim()?o+`
<`+bu+">"+e+"</"+bu+">":o:o.slice(0,i)+e+o.slice(i+cbe.length)}var qHt=/\{(?!copilot-selection\}|\[\[)([^}]+)\}/g;async function GHt(t,e,n){let r=new Map,o=new Set,i;for(;(i=qHt.exec(t))!==null;){let s=i[1].trim(),a={content:"",files:[]},l=s.toLowerCase();if(l==="activenote")if(n){let c=await IA(n,e);c&&(a.content=`<${NS}>
<path>${n.path}</path>
## ${UW(n)}
${c}
</${NS}>`,a.files.push(n))}else new RR.Notice("No active note found.");else{if(l==="activewebtab")continue;if(s.startsWith("#")){let c=s.slice(1).split(",").map(f=>f.trim()),u=$W(e,c),d=[];for(let f of u){let p=await IA(f,e);p&&(d.push(`<${NS}>
<path>${f.path}</path>
## ${UW(f)}
${p}
</${NS}>`),a.files.push(f))}a.content=d.join(`
`)}else{let c=OAe(s),u=JD(e,c),d=[];for(let f of u){let p=await IA(f,e);p&&(d.push(`<${NS}>
<path>${f.path}</path>
## ${UW(f)}
${p}
</${NS}>`),a.files.push(f))}a.content=d.join(`
`)}}a.content?(r.set(s,a.content),a.files.forEach(c=>o.add(c))):l!=="activenote"&&l!=="activewebtab"&&(s.startsWith('"')||ee(`No notes found for variable: ${s}`))}return{variablesMap:r,includedFiles:o}}async function Ij(t,e,n,r,o=!1){let i=q(),s=new Set;if(!i.enableCustomPromptTemplating)return!o&&t.includes("{}")&&!e&&r&&s.add(r),{processedPrompt:t+`
`,includedFiles:Array.from(s)};let{variablesMap:a,includedFiles:l}=await GHt(t,n,r);l.forEach(p=>s.add(p));let c=t,u="",d=null;!o&&c.includes("{}")&&(c=c.replace(/\{\}/g,`{${bu}}`),e?u+=`<${bu}>
${e}
</${bu}>`:r?(d=await IA(r,n),u+=`<${bu} type="active_note">
${d||""}
</${bu}>`,s.add(r)):u+=`<${bu}>
(No selected text or active note available)
</${bu}>`);for(let[p,m]of a.entries())p.toLowerCase()==="activenote"&&d!==null||(u?u+=`
<${iD} name="${p}">
${m}
</${iD}>`:u+=`<${iD} name="${p}">
${m}
</${iD}>`);let f=NAe(c,n);for(let p of f)if(!s.has(p)){let m=await IA(p,n);if(m){let h=await n.adapter.stat(p.path),g=h?new Date(h.ctime).toISOString():"Unknown",y=h?new Date(h.mtime).toISOString():"Unknown",w=`<${oD}>
<title>${p.basename}</title>
<path>${p.path}</path>
<ctime>${g}</ctime>
<mtime>${y}</mtime>
<content>
${m}
</content>
</${oD}>`;u&&(u+=`
`),u+=`${w}`,s.add(p)}}return{processedPrompt:u?`${c}
${u}`:`${c}
`,includedFiles:Array.from(s)}}function VJe(t,e){let r=`${t} (copy)`,o=1;for(;e.some(i=>i.title.toLowerCase()===r.toLowerCase());)o++,r=`${t} (copy ${o})`;return r}function X9(){let e=td().reduce((n,r)=>n>r.order?n:r.order,0);return e===Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:e+10}async function dbe(t,e){try{wP(t.path),await app.fileManager.processFrontMatter(t,n=>{n[Av]==null&&(n[Av]=e.showInContextMenu),n[kv]==null&&(n[kv]=e.showInSlashMenu),n[gy]==null&&(n[gy]=e.order),n[Mv]==null&&(n[Mv]=e.modelKey),n[Nv]==null&&(n[Nv]=e.lastUsedMs)})}finally{vP(t.path)}}function YHt({commands:t,command:e,onConfirm:n,onCancel:r}){let i=Ht().activeModels.filter(f=>f.enabled).map(f=>({label:UJe(f),value:ln(f)})),[s,a]=(0,qr.useState)(e),[l,c]=(0,qr.useState)({}),u=(f,p)=>{a(m=>({...m,[f]:p})),c(m=>({...m,[f]:void 0}))},d=()=>{let f={},p=Y9(s.title,t,e.title);if(p&&(f.title=p),s.content.trim()||(f.content="Prompt is required"),Object.keys(f).length>0){c(f);return}n(s)};return qr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4 tw-p-4"},qr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},qr.default.createElement(hi,{htmlFor:"title"},"Name"),qr.default.createElement(Xn,{id:"title",value:s.title,onChange:f=>u("title",f.target.value),placeholder:"Enter command name"}),l.title&&qr.default.createElement("div",{className:"tw-text-sm tw-text-error"},l.title)),qr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},qr.default.createElement(hi,{htmlFor:"content"},"Prompt"),qr.default.createElement(BJe,null),qr.default.createElement(hf,{id:"content",value:s.content,onChange:f=>u("content",f.target.value),placeholder:"Enter command prompt",className:"tw-min-h-[200px]"}),l.content&&qr.default.createElement("div",{className:"tw-text-sm tw-text-error"},l.content)),qr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},qr.default.createElement(hi,{htmlFor:"modelKey"},"Model (Optional)"),qr.default.createElement("div",{className:"tw-group tw-relative tw-w-full"},qr.default.createElement("select",{value:s.modelKey,onChange:f=>{let p=f.target.value;if(!p){u("modelKey","");return}if(!i.find(h=>h.value===p)){z(`Model ${p} not found`),u("modelKey","");return}u("modelKey",f.target.value)},className:oe("tw-w-full tw-appearance-none","tw-flex tw-h-9 tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-dropdown tw-px-3 tw-py-1 tw-pr-8","tw-text-sm !tw-shadow tw-transition-colors","focus:tw-outline-none focus:tw-ring-1 focus:tw-ring-ring","disabled:tw-cursor-not-allowed disabled:tw-opacity-50","hover:tw-bg-interactive-hover hover:tw-text-normal")},qr.default.createElement("option",{value:""},"Inherit from chat model"),i.map(f=>qr.default.createElement("option",{key:f.value,value:f.value.toString()},f.label))),qr.default.createElement("div",{className:oe("tw-pointer-events-none tw-absolute tw-inset-y-0 tw-right-0 tw-flex tw-items-center tw-pr-2","tw-transition-colors group-hover:[&>svg]:tw-text-normal")},qr.default.createElement(hr,{className:"tw-size-4"})))),qr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},qr.default.createElement(To,{id:"showInContextMenu",checked:s.showInContextMenu,onCheckedChange:f=>u("showInContextMenu",f)}),qr.default.createElement(hi,{htmlFor:"showInContextMenu"},"Show in context menu")),qr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},qr.default.createElement(To,{id:"showInSlashMenu",checked:s.showInSlashMenu,onCheckedChange:f=>u("showInSlashMenu",f)}),qr.default.createElement(hi,{htmlFor:"showInSlashMenu"},"Show in slash menu")),qr.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},qr.default.createElement(X,{variant:"secondary",onClick:r},"Cancel"),qr.default.createElement(X,{variant:"default",onClick:d},"Save")))}var g_=class extends WJe.Modal{constructor(n,r,o,i){super(n);this.commands=r;this.command=o;this.onUpdate=i;this.setTitle("Edit Command")}onOpen(){let{contentEl:n}=this;this.root=sr(n,this.app);let r=o=>{this.onUpdate(o),this.close()};this.root.render
You are an AI assistant designed to execute user instructions with precision. Your responses should be:
- Direct and focused: Address only what is explicitly requested
- Concise: Avoid unnecessary elaboration unless the user asks for details
- Context-aware: When text is selected or highlighted, treat it as the primary target for any requested action
- Action-oriented: Prioritize completing the task over explaining the process
Key principles:
- Follow instructions literally and completely
- Assume selected/highlighted text is the focus unless told otherwise
- Use all provided context: Consider any additional information, examples, or constraints the user provides to better complete the task
- Add explanations only when explicitly requested or when clarification is essential
- Maintain the user's preferred format and style
Response format: Match the format implied by the user's request (e.g., if they ask for a list, provide a list; if they ask for a rewrite, provide only the rewritten text).
`;function eY(t,e){if(!e)return t;let n=t.includes("{}"),r=/\{activenote\}/i.test(t),o=[];return n||o.push("{}"),r||o.push("{activeNote}"),o.length>0?t+`
${o.join(`
`)}`:t}Ir();var Ml=N(U());vt();var urt=require("obsidian");var eo=N(U());Kt();var Ki=N(U());function tY(t,e,n){return Math.min(Math.max(t,e),n)}function nY(t={}){let{initialPosition:e={x:0,y:0},bounds:n="window",dragRef:r,getPosition:o,onPositionChange:i,writeToDom:s=!0}=t,[a,l]=(0,Ki.useState)(e),[c,u]=(0,Ki.useState)(!1),d=(0,Ki.useRef)(null),f=r??d,p=(0,Ki.useRef)(e),m=(0,Ki.useRef)({x:0,y:0}),h=(0,Ki.useRef)(null),g=(0,Ki.useRef)(null),y=(0,Ki.useRef)(null),w=(0,Ki.useRef)(!0),v=(0,Ki.useCallback)(S=>{if(!s)return;let P=f.current;P&&P.setCssProps({"--copilot-drag-x":`${S.x}px`,"--copilot-drag-y":`${S.y}px`})},[f,s]),x=(0,Ki.useCallback)(S=>{let P=S.x,A=S.y,O=f.current;if(n==="window"&&O){let $=O.win,B=O.getBoundingClientRect(),W=$.innerWidth-B.width,F=$.innerHeight-B.height;P=tY(P,0,Math.max(0,W)),A=tY(A,0,Math.max(0,F))}else if(n==="parent"&&O?.parentElement){let $=O.getBoundingClientRect(),B=O.parentElement.getBoundingClientRect(),W=B.left,F=B.top,Z=B.right-$.width,V=B.bottom-$.height;P=tY(P,W,Math.max(W,Z)),A=tY(A,F,Math.max(F,V))}let D={x:P,y:A};return p.current=D,v(D),i?.(D),D},[n,f,v,i]),b=(0,Ki.useCallback)(()=>{if(g.current!=null)return;let S=f.current?.win??window;g.current=S.requestAnimationFrame(()=>{g.current=null;let P=h.current;P&&(h.current=null,x(P))})},[x,f]);(0,Ki.useLayoutEffect)(()=>{v(p.current)},[v]);let _=(0,Ki.useCallback)(S=>{let P=p.current,A=typeof S=="function"?S(P):S;p.current=A,l(A),v(A),i?.(A)},[v,i]),T=(0,Ki.useCallback)(S=>{if(S.button!==0||(S.preventDefault(),y.current))return;u(!0);let P=o?o():p.current;p.current=P,v(P),m.current={x:S.clientX-P.x,y:S.clientY-P.y};let A=f.current?.doc??activeDocument,O=A.defaultView??window,D=A.body;D.classList.add("tw-select-none","tw-cursor-grabbing");let $=F=>{h.current={x:F.clientX-m.current.x,y:F.clientY-m.current.y},b()},B=F=>{if(y.current!==B)return;A.removeEventListener("mousemove",$,!0),A.removeEventListener("mouseup",W,!0),g.current!=null&&(O.cancelAnimationFrame(g.current),g.current=null);let Z=h.current;h.current=null;let V=Z?x(Z):p.current;D.classList.remove("tw-select-none","tw-cursor-grabbing"),y.current=null,F&&w.current&&(l(V),u(!1))},W=()=>{B(!0)};y.current=B,A.addEventListener("mousemove",$,!0),A.addEventListener("mouseup",W,!0)},[x,f,o,b,v]);return(0,Ki.useEffect)(()=>()=>{w.current=!1,y.current?.(!1)},[]),(0,Ki.useLayoutEffect)(()=>{v(p.current)}),{position:a,setPosition:_,isDragging:c,dragRef:f,handleMouseDown:T}}var hc=N(U());function HJe(t){let{enabled:e=!0,getRect:n,getConstraints:r,onResize:o}=t,[i,s]=(0,hc.useState)(!1),a=(0,hc.useRef)(null),l=(0,hc.useRef)(null),c=(0,hc.useRef)(null),u=(0,hc.useRef)(null),d=(0,hc.useRef)(null),f=(0,hc.useRef)(o);(0,hc.useEffect)(()=>{f.current=o},[o]);let p=(0,hc.useRef)(r);(0,hc.useEffect)(()=>{p.current=r},[r]);let m=(0,hc.useCallback)(h=>g=>{if(!e)return;let y=n();if(!y)return;let v=g.currentTarget?.doc??activeDocument;l.current=v,c.current=v.defaultView??window,a.current={direction:h,startClientX:g.clientX,startClientY:g.clientY,width:y.width,height:y.height,left:y.left,top:y.top,right:y.right},s(!0),g.preventDefault(),g.stopPropagation()},[e,n]);return(0,hc.useEffect)(()=>{if(!i)return;let h=a.current;if(!h)return;let g=h.direction,y=g==="right"?"ew-resize":g==="bottom"?"ns-resize":g==="bottom-left"?"nesw-resize":"nwse-resize",w=l.current??activeDocument,v=c.current??window,x=w.body;x.setCssProps({"--copilot-resize-cursor":y}),x.classList.add("tw-select-none","tw-cursor-[var(--copilot-resize-cursor)]");let b=()=>{u.current!==null&&(v.cancelAnimationFrame(u.current),u.current=null)},_=()=>{let O=d.current;O&&(d.current=null,f.current(O))},T=()=>{u.current===null&&(u.current=v.requestAnimationFrame(()=>{u.current=null,_()}))},S=O=>{let D=a.current;if(!D)return;let $=O.clientX-D.startClientX,B=O.clientY-D.startClientY,W=p.current?.()??{minWidth:0,minHeight:0},F=W.minWidth,Z=W.minHeight,V=W.maxWidth??Number.POSITIVE_INFINITY,H=W.maxHeight??Number.POSITIVE_INFINITY,te=D.width,fe=D.height,me,j;(g==="right"||g==="bottom-right")&&(te=Math.min(V,Math.max(F,D.width+$))),g==="bottom-left"&&(te=
.`.concat(Zbe,` {
overflow: hidden `).concat(r,`;
padding-right: `).concat(a,"px ").concat(r,`;
}
body[`).concat(JR,`] {
overflow: hidden `).concat(r,`;
overscroll-behavior: contain;
`).concat([e&&"position: relative ".concat(r,";"),n==="margin"&&`
padding-left: `.concat(o,`px;
padding-top: `).concat(i,`px;
padding-right: `).concat(s,`px;
margin-left:0;
margin-top:0;
margin-right: `).concat(a,"px ").concat(r,`;
`),n==="padding"&&"padding-right: ".concat(a,"px ").concat(r,";")].filter(Boolean).join(""),`
}
.`).concat(AP,` {
right: `).concat(a,"px ").concat(r,`;
}
.`).concat(kP,` {
margin-right: `).concat(a,"px ").concat(r,`;
}
.`).concat(AP," .").concat(AP,` {
right: 0 `).concat(r,`;
}
.`).concat(kP," .").concat(kP,` {
margin-right: 0 `).concat(r,`;
}
body[`).concat(JR,`] {
`).concat(Jbe,": ").concat(a,`px;
}
`)},mtt=function(){var t=parseInt(document.body.getAttribute(JR)||"0",10);return isFinite(t)?t:0},e5t=function(){XR.useEffect(function(){return document.body.setAttribute(JR,(mtt()+1).toString()),function(){var t=mtt()-1;t<=0?document.body.removeAttribute(JR):document.body.setAttribute(JR,t.toString())}},[])},sCe=function(t){var e=t.noRelative,n=t.noImportant,r=t.gapMode,o=r===void 0?"margin":r;e5t();var i=XR.useMemo(function(){return iCe(o)},[o]);return XR.createElement(XKt,{styles:QKt(i,!e,o,n?"":"!important")})};var aCe=!1;if(typeof window<"u")try{Bj=Object.defineProperty({},"passive",{get:function(){return aCe=!0,!0}}),window.addEventListener("test",Bj,Bj),window.removeEventListener("test",Bj,Bj)}catch{aCe=!1}var Bj,MP=aCe?{passive:!1}:!1;var t5t=function(t){return t.tagName==="TEXTAREA"},htt=function(t,e){if(!(t instanceof Element))return!1;var n=window.getComputedStyle(t);return n[e]!=="hidden"&&!(n.overflowY===n.overflowX&&!t5t(t)&&n[e]==="visible")},n5t=function(t){return htt(t,"overflowY")},r5t=function(t){return htt(t,"overflowX")},lCe=function(t,e){var n=e.ownerDocument,r=e;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var o=gtt(t,r);if(o){var i=ytt(t,r),s=i[1],a=i[2];if(s>a)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},o5t=function(t){var e=t.scrollTop,n=t.scrollHeight,r=t.clientHeight;return[e,n,r]},i5t=function(t){var e=t.scrollLeft,n=t.scrollWidth,r=t.clientWidth;return[e,n,r]},gtt=function(t,e){return t==="v"?n5t(e):r5t(e)},ytt=function(t,e){return t==="v"?o5t(e):i5t(e)},s5t=function(t,e){return t==="h"&&e==="rtl"?-1:1},wtt=function(t,e,n,r,o){var i=s5t(t,window.getComputedStyle(e).direction),s=i*r,a=n.target,l=e.contains(a),c=!1,u=s>0,d=0,f=0;do{if(!a)break;var p=ytt(t,a),m=p[0],h=p[1],g=p[2],y=h-g-i*m;(m||y)&&gtt(t,a)&&(d+=y,f+=m);var w=a.parentNode;a=w&&w.nodeType===Node.DOCUMENT_FRAGMENT_NODE?w.host:w}while(!l&&a!==document.body||l&&(e.contains(a)||e===a));return(u&&(o&&Math.abs(d)<1||!o&&s>d)||!u&&(o&&Math.abs(f)<1||!o&&-s>f))&&(c=!0),c};var HY=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},vtt=function(t){return[t.deltaX,t.deltaY]},xtt=function(t){return t&&"current"in t?t.current:t},a5t=function(t,e){return t[0]===e[0]&&t[1]===e[1]},l5t=function(t){return`
.block-interactivity-`.concat(t,` {pointer-events: none;}
.allow-interactivity-`).concat(t,` {pointer-events: all;}
`)},c5t=0,QR=[];function btt(t){var e=oi.useRef([]),n=oi.useRef([0,0]),r=oi.useRef(),o=oi.useState(c5t++)[0],i=oi.useState(Uj)[0],s=oi.useRef(t);oi.useEffect(function(){s.current=t},[t]),oi.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=itt([t.lockRef.current],(t.shards||[]).map(xtt),!0).filter(Boolean);return h.forEach(function(g){return g.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),h.forEach(function(g){return g.classList.remove("allow-interactivity-".concat(o))})}}},[t.inert,t.lockRef.current,t.shards]);var a=oi.useCallback(function(h,g){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!s.current.allowPinchZoom;var y=HY(h),w=n.current,v="deltaX"in h?h.deltaX:w[0]-y[0],x="deltaY"in h?h.deltaY:w[1]-y[1],b,_=h.target,T=Math.abs(v)>Math.abs(x)?"h":"v";if("touches"in h&&T==="h"&&_.type==="range")return!1;var S=lCe(T,_);if(!S)return!0;if(S?b=T:(b=T==="v"?"h":"v",S=lCe(T,_)),!S)return!1;if(!r.current&&"changedTouches"in h&&(v||x)&&(r.current=b),!b)return!0;var P=r.current||b;return wtt(P,g,h,P==="h"?v:x,!0)},[]),l=oi.useCallback(function(h){var g=h;if(!(!QR.length||QR[QR.length-1]!==i)){var y="deltaY"in g?vtt(g):HY(g),w=e.current.filter(function(b){return b.name===g.type&&(b.target===g.target||g.target===b.shadowParent)&&a5t(b.delta,y)})[0];if(w&&w.should){g.cancelable&&g.preventDefault();return}if(!w){var v=(s.current.shards||[]).map(xtt).filter(Boolean).filter(function(b){return b.contains(g.target)}),x=v.length>0?a(g,v[0]):!s.current.noIsolation;x&&g.cancelable&&g.preventDefault()}}},[]),c=oi.useCallback(function(h,g,y,w){var v={name:h,delta:g,target:y,should:w,shadowParent:u5t(y)};e.current.push(v),setTimeout(function(){e.current=e.current.filter(function(x){return x!==v})},1)},[]),u=oi.useCallback(function(h){n.current=HY(h),r.current=void 0},[]),d=oi.useCallback(function(h){c(h.type,vtt(h),h.target,a(h,t.lockRef.current))},[]),f=oi.useCallback(function(h){c(h.type,HY(h),h.target,a(h,t.lockRef.current))},[]);oi.useEffect(function(){return QR.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",l,MP),document.addEventListener("touchmove",l,MP),document.addEventListener("touchstart",u,MP),function(){QR=QR.filter(function(h){return h!==i}),document.removeEventListener("wheel",l,MP),document.removeEventListener("touchmove",l,MP),document.removeEventListener("touchstart",u,MP)}},[]);var p=t.removeScrollBar,m=t.inert;return oi.createElement(oi.Fragment,null,m?oi.createElement(i,{styles:l5t(o)}):null,p?oi.createElement(sCe,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function u5t(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var Ctt=eCe(WY,btt);var _tt=KY.forwardRef(function(t,e){return KY.createElement(Fj,id({},t,{ref:e,sideCar:Ctt}))});_tt.classNames=Fj.classNames;var jv=_tt;var Vn=N(Ve(),1),cCe=["Enter"," "],d5t=["ArrowDown","PageUp","Home"],Ttt=["ArrowUp","PageDown","End"],f5t=[...d5t,...Ttt],p5t={ltr:[...cCe,"ArrowRight"],rtl:[...cCe,"ArrowLeft"]},m5t={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Wj="Menu",[jj,h5t,g5t]=w_(Wj),[NP,uCe]=yXe(Wj,[g5t,Vp,Gbe]),Hj=Vp(),Itt=Gbe(),[Ptt,P_]=NP(Wj),[y5t,Kj]=NP(Wj),Ett=t=>{let{__scopeMenu:e,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=t,a=Hj(e),[l,c]=Gt.useState(null),u=Gt.useRef(!1),d=FY(i),f=wXe(o);return Gt.useEffect(()=>{let p=()=>{u.current=!0,document.addEventListener("pointerdown",m,{capture:!0,once:!0}),document.addEventListener("pointermove",m,{capture:!0,once:!0})},m=()=>u.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",m,{capture:!0}),document.removeEventListener("pointermove",m,{capture:!0})}},[]),(0,Vn.jsx)(Uv,{...a,children:(0,Vn.jsx)(Ptt,{scope:e,open:n,onOpenChange:d,content:l,onContentChange:c,children:(0,Vn.jsx)(y5t,{scope:e,onClose:Gt.useCallback(()=>d(!1),[d]),i
Source: ${d.url}
${d.transcript}`;await navigator.clipboard.writeText(x),new iL.Notice("Transcript copied to clipboard!")}catch(x){z("Failed to copy to clipboard:",x),new iL.Notice("Failed to copy to clipboard")}},y=async()=>{if(d)try{let x=`# YouTube Video Transcript
Source: ${d.url}
${d.transcript}`;await EA(x,!1),t()}catch(x){z("Failed to insert to note:",x),new iL.Notice("Failed to insert to note")}},w=()=>{n("input"),o(""),l(""),f(null)},v=x=>{x.key==="Enter"&&!i&&c&&h()};return e==="display"&&d?Eo.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Eo.createElement("div",{className:"tw-rounded tw-bg-secondary tw-p-3"},Eo.createElement("a",{href:d.url,className:"tw-text-sm tw-text-muted hover:tw-text-normal",target:"_blank",rel:"noopener noreferrer"},d.url)),Eo.createElement("div",{className:"tw-max-h-96 tw-overflow-y-auto tw-rounded tw-border tw-border-border tw-bg-primary tw-p-4"},Eo.createElement("div",{className:"tw-whitespace-pre-wrap tw-text-sm tw-leading-relaxed"},d.transcript)),Eo.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},Eo.createElement(X,{variant:"ghost",onClick:w},"Download Another"),Eo.createElement(X,{variant:"default",onClick:()=>void g()},"Copy to Clipboard"),Eo.createElement(X,{variant:"default",onClick:()=>void y()},"Insert at Cursor"),Eo.createElement(X,{variant:"secondary",onClick:t},"Close"))):Eo.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Eo.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Eo.createElement("div",{className:"tw-text-sm tw-text-muted"},"Enter a valid YouTube video URL"),Eo.createElement(Xn,{placeholder:"https://www.youtube.com/watch?v=...",value:r,onChange:x=>m(x.target.value),onKeyDown:v,disabled:i}),a&&Eo.createElement("div",{className:"tw-text-sm tw-text-error"},a)),Eo.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},Eo.createElement(X,{variant:"secondary",onClick:t,disabled:i},"Cancel"),Eo.createElement(X,{variant:"default",onClick:()=>void h(),disabled:i||!c},i?"Downloading...":"Download Transcript")))}var uZ=class extends iL.Modal{constructor(e){super(e),this.setTitle("Download YouTube Script (plus)")}onOpen(){let{contentEl:e}=this;this.root=sr(e,this.app);let n=()=>{this.close()};this.root.render(Eo.createElement(pGt,{onClose:n}))}onClose(){this.root.unmount()}};ns();yp();fc();qe();var vn=require("obsidian");qh();It();Ir();function Za(t,e,n){t.addCommand({id:e,name:nW[e],icon:rW[e],callback:()=>{let r=n();r instanceof Promise&&r.catch(o=>z(`Command ${e} failed`,o))}})}function eot(t,e,n){t.addCommand({id:e,name:nW[e],icon:rW[e],editorCallback:r=>{let o=n(r);o instanceof Promise&&o.catch(i=>z(`Editor command ${e} failed`,i))}})}function tot(t,e,n){t.addCommand({id:e,name:nW[e],icon:rW[e],checkCallback:n})}function n_e(t,e,n){eot(t,bt.COUNT_WORD_AND_TOKENS_SELECTION,async r=>{let o=r.getSelection(),i=o.split(" ").length,s=await t.projectManager.getCurrentChainManager().chatModelManager.countTokens(o);new vn.Notice(`Selected text contains ${i} words and ${s} tokens.`)}),Za(t,bt.COUNT_TOTAL_VAULT_TOKENS,async()=>{try{let r=await Vge(t.app),o=await t.projectManager.getCurrentChainManager().chatModelManager.countTokens(r);new vn.Notice(`Total tokens in your vault: ${o}`)}catch(r){z("Error counting tokens: ",r),new vn.Notice("An error occurred while counting tokens.")}}),Za(t,bt.TOGGLE_COPILOT_CHAT_WINDOW,()=>{t.toggleView()}),Za(t,bt.OPEN_COPILOT_CHAT_WINDOW,async()=>{await t.activateView()}),Za(t,bt.NEW_CHAT,async()=>{sO(),await t.newChat()}),tot(t,bt.TRIGGER_QUICK_COMMAND,r=>{let o=t.app.workspace.getActiveViewOfType(vn.MarkdownView);if(r)return!!(!t$()&&o&&o.editor);if(t$())return new vn.Notice("Quick command is not available in source mode."),!1;if(!o||!o.editor)return new vn.Notice("No active editor found."),!1;let s=o.editor.getSelection();if(!s.trim())return new vn.Notice("Please select some text first. Selected text is required for quick commands."),!1;let a={title:"Quick Command",content:"",showInContextMenu:!1,showInSlashMenu:!1,order:0,modelKey:"",lastUsedMs:Date.now()};return new A_(t.app,{selectedText:s,command:a,systemPrompt:Q9,behaviorConfig:{autoExecuteOnOpen:!1,hideContentAreaOnIdle:!0,commandLabel:"Quick Command",commandIcon:null,showIncludeNoteContext:!0,modelSelectionScope:"quick-command",firstSubmitTransform:(c,u)=>eY(c,u)}}).open(),!0}),Za(t,bt.CLEAR_LO
Are you sure you want to proceed?`;if(await new Promise(l=>{new Cr(t.app,()=>l(!0),s,"Clear Semantic Index","Clear Index","Cancel",()=>l(!1)).open()}))try{await(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().clearIndex(),new vn.Notice("Cleared local Copilot semantic index.")}catch(l){z("Error clearing semantic index:",l),new vn.Notice("Failed to clear semantic index.")}}),Za(t,bt.GARBAGE_COLLECT_COPILOT_INDEX,async()=>{try{let{getSettings:r}=await Promise.resolve().then(()=>(Se(),qy));if(Fa(r())){new vn.Notice("Miyo manages file cleanup automatically. Run Index (refresh) vault to trigger a scan if needed.");return}let i=await(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().garbageCollectVectorStore();new vn.Notice(`Garbage collection completed. Removed ${i} stale documents.`)}catch(r){z("Error during garbage collection:",r),new vn.Notice("Failed to garbage collect semantic index.")}}),Za(t,bt.INDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let{getSettings:r}=await Promise.resolve().then(()=>(Se(),qy)),o=r();if(o.enableSemanticSearchV3){let s=await(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().indexVaultToVectorStore(!1,{userInitiated:!0});Fa(o)?new vn.Notice("Miyo folder index refresh started. Open the Miyo app to check details."):new vn.Notice(`Semantic search index refreshed with ${s} documents.`)}else new vn.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(r){z("Error building index:",r),new vn.Notice("An error occurred while building the index.")}}),Za(t,bt.FORCE_REINDEX_VAULT_TO_COPILOT_INDEX,async()=>{if(await new Promise(o=>{new Cr(t.app,()=>o(!0),"This will delete and rebuild your entire vault index from scratch. This operation cannot be undone. Are you sure you want to proceed?","Force Reindex Vault","Continue","Cancel",()=>o(!1)).open()}))try{let{getSettings:o}=await Promise.resolve().then(()=>(Se(),qy)),i=o();if(i.enableSemanticSearchV3){let a=await(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().indexVaultToVectorStore(!0,{userInitiated:!0});Fa(i)?new vn.Notice("Miyo folder index refresh started. Open the Miyo app to check details."):new vn.Notice(`Semantic search index rebuilt with ${a} documents.`)}else new vn.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(o){z("Error rebuilding index:",o),new vn.Notice("An error occurred while rebuilding the index.")}}),Za(t,bt.LOAD_COPILOT_CHAT_CONVERSATION,async()=>{await t.loadCopilotChatHistory()}),Za(t,bt.LIST_INDEXED_FILES,async()=>{try{let o=await(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().getIndexedFiles(),{getMatchingPatterns:i,shouldIndexFile:s}=await Promise.resolve().then(()=>(fc(),g5e)),{inclusions:a,exclusions:l}=i(),c=t.app.vault.getMarkdownFiles(),u=new Set,d=new Set,f=new Set,p=new Set(o);for(let x of c){if(!s(x,a,l)){f.add(x.path);continue}let b=await t.app.vault.cachedRead(x);!b||b.trim().length===0?u.add(x.path):p.has(x.path)||d.add(x.path)}let m=["# Copilot Files Status",`- Indexed files: ${p.size}`,`- Unindexed files: ${d.size}`,`- Empty files: ${u.size}`,`- Excluded files: ${f.size}`,"","## Indexed Files",...p.size>0?Array.from(p).sort().map(x=>`- [[${x}]]`):["No indexed files found."],"","## Unindexed Files",...d.size>0?Array.from(d).sort().map(x=>`- [[${x}]]`):["No unindexed files found."],"","## Empty Files",...u.size>0?Array.from(u).sort().map(x=>`- [[${x}]]`):["No empty files found."],"","## Excluded Files (based on settings)",...f.size>0?Array.from(f).sort().map(x=>`- [[${x}]]`):["No excluded files."]].join(`
`),h=`Copilot-Indexed-Files-${new Date().toLocaleDateString().replace(/\//g,"-")}.md`,g="copilot",y=`${g}/${h}`;await Fr(g);let w=t.app.vault.getAbstractFileByPath(y);w instanceof vn.TFile?await t.app.vault.modify(w,m):await t.app.vault.create(y,m);let v=t.app.vault.getAbstractFileByPath(y);v instanceof vn.TFile&&(await t.app.workspace.getLeaf().openFile(v),new vn.Notice(`Listed ${p.size} indexed files`))}catch(r){z("Error listing indexed files:",r),new vn.Notice("Failed to list indexed files.")}}),Za(t,bt.INSPECT_COPILOT_INDEX_BY_NOTE_PATHS,async()=>{try{let r=t.app.workspace.getActiveFile();if(!r){new vn.Notice("No active file. Please open a note first.");return}let o=(await Promise.resolve().then(()=>(ei(),ji))).default,{DBOperations:i}=await Promise.resolve().then(()=>(aG(),w5e)),s=await o.getInstance().getDb(),a=await i.getDocsByPath(s,r.path);if(!a||a.length===0){new vn.Notice(`No embedding data found for: ${r.path}`);return}let l=a.map(h=>h.document),c=[`# Embedding Debug: ${r.basename}`,"",`**Path:** ${r.path}`,`**Chunks:** ${l.length}`,`**Embedding Model:** ${l[0]?.embeddingModel||"unknown"}`,"",...l.flatMap((h,g)=>{let y=h.embedding||[],w=y.slice(0,10).map(v=>v.toFixed(6)).join(", ");return[`## Chunk ${g+1}`,`- **ID:** ${h.id}`,`- **Content Preview:** "${(h.content||"").substring(0,200)}..."`,`- **Vector Length:** ${y.length}`,`- **Vector Preview:** [${w}${y.length>10?", ...":""}]`,`- **Tags:** ${(h.tags||[]).join(", ")||"none"}`,`- **Characters:** ${h.nchars||0}`,""]})].join(`
`),u=`Copilot-Embedding-Debug-${r.basename.replace(/[\\/:*?"<>|]/g,"_")}.md`,d="copilot",f=`${d}/${u}`;await Fr(d);let p=t.app.vault.getAbstractFileByPath(f);p instanceof vn.TFile?await t.app.vault.modify(p,c):await t.app.vault.create(f,c);let m=t.app.vault.getAbstractFileByPath(f);m instanceof vn.TFile&&(await t.app.workspace.getLeaf().openFile(m),new vn.Notice(`Embedding debug info for ${l.length} chunk(s)`))}catch(r){z("Error inspecting embeddings:",r),new vn.Notice("Failed to inspect embeddings. Is the index loaded?")}}),Za(t,bt.CLEAR_COPILOT_CACHE,async()=>{try{await t.fileParserManager.clearPDFCache(),await ti.getInstance().clearAllCache(),await JN.getInstance().clear(),new vn.Notice("All Copilot caches cleared successfully")}catch(r){z("Error clearing Copilot caches:",r),new vn.Notice("Failed to clear Copilot caches")}}),Za(t,bt.OPEN_LOG_FILE,async()=>{try{await TG(),await Ds.openLogFile()}catch(r){z("Error creating Copilot log file:",r),new vn.Notice("Failed to create Copilot log file.")}}),Za(t,bt.CLEAR_LOG_FILE,async()=>{try{await Ds.clear(),new vn.Notice("Copilot log cleared.")}catch(r){z("Error clearing Copilot log file:",r),new vn.Notice("Failed to clear Copilot log file.")}}),eot(t,bt.ADD_SELECTION_TO_CHAT_CONTEXT,async r=>{let o=r.getSelection();if(!o){new vn.Notice("No text selected");return}let i=t.app.workspace.getActiveFile();if(!i){new vn.Notice("No active file");return}let s=r.listSelections()[0];if(!s){new vn.Notice("Could not determine selection range");return}let a=s.anchor.line+1,l=s.head.line+1,c={id:si(),content:o,sourceType:"note",noteTitle:i.basename,notePath:i.path,startLine:Math.min(a,l),endLine:Math.max(a,l)};og([c]),await t.activateView()}),Za(t,bt.ADD_WEB_SELECTION_TO_CHAT_CONTEXT,async()=>{let{Platform:r}=await import("obsidian");if(!r.isDesktopApp){new vn.Notice("Web selection is only available on desktop");return}let{getWebViewerService:o}=await Promise.resolve().then(()=>(FP(),Qrt));try{let i=o(t.app),s=i.getActiveLeaf()??i.getLastActiveLeaf();if(!s){new vn.Notice("No active Web Tab found");return}let a=await i.getSelectedMarkdown(s);if(!a.trim()){new vn.Notice("No text selected in Web Tab");return}let l=i.getPageInfo(s),c={id:si(),content:a,sourceType:"web",title:l.title||"Untitled",url:l.url,faviconUrl:l.faviconUrl||void 0};og([c]),await t.activateView()}catch(i){z("Error adding web selection to context:",i),new vn.Notice("Failed to get web selection")}}),Za(t,bt.ADD_CUSTOM_COMMAND,async()=>{let r=td(),o={...hy};new g_(t.app,r,o,async s=>{await Xs.getInstance().createCommand(s)}).open()}),Za(t,bt.APPLY_CUSTOM_COMMAND,()=>{new lZ(t.app).open()}),Za(t,bt.DOWNLOAD_YOUTUBE_SCRIPT,async()=>{if(!await _p()){new vn.Notice("Download YouTube Script (plus) is a Copilot Plus feature");return}new uZ(t.app).open()}),tot(t,bt.TRIGGER_QUICK_ASK,r=>{let o=t.app.workspace.getActiveViewOfType(vn.MarkdownView);if(r)return!!(!t$()&&o&&o.editor);if(t$())return new vn.Notice("Quick Ask is not available in source mode."),!1;if(!o||!o.editor)return new vn.Notice("No active editor found."),!1;let i=o.editor.cm;return i?(t.quickAskController.show(o,i),!0):(new vn.Notice("Could not access CodeMirror editor."),!1)})}Ir();var mL={title:"",content:"",createdMs:0,modifiedMs:0,lastUsedMs:0},hL="copilot-system-prompt-created",gL="copilot-system-prompt-modified",yL="copilot-system-prompt-last-used",r_e="copilot-system-prompt-default";var N_=require("obsidian");Se();qe();ye();function n4(t,e,n){let r=t.trim();return r?t!==r?"Prompt name cannot have leading or trailing spaces":n&&t===n?null:/[#<>:"/\\|?*[\]^\x00-\x1F]/g.test(r)?'Prompt name contains invalid characters. Avoid using: < > : " / \\ | ? * [ ] ^':e.some(i=>i.title.toLowerCase()===r.toLowerCase())?"A prompt with this name already exists":null:"Prompt name cannot be empty"}function qp(){return(0,N_.normalizePath)(q().userSystemPromptsFolder)}function Gp(t){return(0,N_.normalizePath)(`${qp()}/${t}.md`)}function KGt(t,e){let n=e?(0,N_.normalizePath)(e):qp();return(0,N_.normalizePath)(`${n}/${t}.md`)}function wL(t){if(!(t instanceof N_.TFile)||t.extension!=="m
`).replace(/\r/g,`
`)}async function oot(t,e,n){let r=qp(),o=`${r}/unsupported`;await Fr(o);let i="Migrated System Prompt (Failed Verification)",s=i,a=1;for(;t.getAbstractFileByPath(`${o}/${s}.md`);)a++,s=`${i} ${a}`;let l=`${o}/${s}.md`,c=`> Migration failed: ${n}
>
> To fix: Review the content below, then move this file to ${r}
${e}`;return await t.create(l,c),l}async function YGt(t,e,n){try{let r=await t.read(e),o=Qh(r,{trimStart:!1}),i=a_e(o).replace(/^\n+/,""),s=a_e(n).replace(/^\n+/,"");return i!==s?(ee(`Migration verification failed: content mismatch. Expected ${s.length} chars, got ${i.length} chars`),!1):!0}catch(r){return z("Migration verification failed: unable to read back file",r),!1}}async function l_e(t){let n=q().userSystemPrompt;if(!n||n.trim().length===0){k("No legacy userSystemPrompt to migrate");return}try{k("Migrating legacy userSystemPrompt from settings to file system");let r=qp();await Fr(r);let o=GGt(rot,t),i=Gp(o);o!==rot&&k(`Default name already exists, using unique name: "${o}"`);let s=Date.now(),a=a_e(n),l={title:o,content:a,createdMs:s,modifiedMs:s,lastUsedMs:0};await t.create(i,a);let c=t.getAbstractFileByPath(i);if(!(c instanceof iot.TFile))throw new Error("File not found after creation");if(await BP(c,l),await YGt(t,c,n)){pe("defaultSystemPromptTitle",o);try{await vL()}catch(d){ee("Failed to reload prompts after migration:",d)}pe("userSystemPrompt",""),k("Cleared legacy userSystemPrompt field"),new Cr(app,()=>{},`We have upgraded your system prompt to the new file-based format. It is now stored as "${o}" in ${r}.
You can now:
\u2022 Edit your system prompt directly in the file
\u2022 Create multiple system prompts
\u2022 Manage prompts through the settings UI
Your migrated prompt has been set as the default system prompt.`,"\u{1F680} System Prompt Upgraded","OK","").open()}else{let d=await oot(t,n,"content verification mismatch");try{await vL()}catch(f){ee("Failed to reload prompts after failed migration:",f)}pe("userSystemPrompt",""),k("Cleared legacy userSystemPrompt field (saved to unsupported)"),new Cr(app,()=>{},`\u26A0\uFE0F System Prompt Migration Issue
Your system prompt was migrated but verification failed. Your data has been saved to:
${d}
To recover:
1. Open the file and review the content
2. Move it to ${r}
3. The prompt will be available immediately`,"Migration Verification Failed","OK","").open()}}catch(r){let o=r instanceof Error?r.message:String(r);z("Failed to migrate legacy userSystemPrompt:",r);try{let i=await oot(t,n,o);pe("userSystemPrompt",""),k("Cleared legacy userSystemPrompt field (saved to unsupported after error)"),new Cr(app,()=>{},`\u26A0\uFE0F System Prompt Migration Failed
An error occurred during migration. Your data has been saved to:
${i}
To recover:
1. Open the file and review the content
2. Move it to ${qp()}
3. The prompt will be available immediately`,"Migration Failed","OK","").open()}catch(i){z("Failed to save to unsupported folder:",i),ee("Preserving userSystemPrompt in settings for manual recovery"),new Cr(app,()=>{},`Failed to migrate system prompt: ${o}
Unable to save to file system. Your system prompt is still in settings and will continue to work.
Please check:
- Folder permissions for ${qp()}
- Available disk space
- Vault is accessible
You can retry by reloading the plugin.`,"Migration Failed - Data Preserved","OK","").open()}}}Qi();Qi();Ir();function _Z(){let[t]=kd(),[e]=KW(),[n]=Yx();return(()=>{if(t!=="project")return"initial";let{total:o,success:i,failed:s,processingFiles:a}=n;return e||a.length>0?"loading":s.length>0?"error":o.length>0&&i.length===o.length?"success":"initial"})()}ye();Ir();Qi();rn();It();ye();yp();ns();Se();bi();vt();var Nl=require("obsidian"),Pt=N(U());var Ot=N(U());vt();rn();var CL=N(U());rn();vt();var _L=({value:t,onChange:e,placeholder:n="Search..."})=>CL.default.createElement("div",{className:"tw-relative"},CL.default.createElement(Xn,{type:"text",placeholder:n,value:t,onChange:r=>e(r.target.value),className:"tw-pr-10"}),t&&CL.default.createElement(X,{variant:"secondary",onClick:()=>e(""),className:"tw-absolute tw-right-8 tw-top-1/2 tw-size-4 -tw-translate-y-1/2 tw-transform tw-rounded-full tw-p-0 tw-transition-colors","aria-label":"Clear search"},CL.default.createElement(sg,{className:"tw-size-4 tw-text-muted/60 hover:tw-text-accent-hover"})),CL.default.createElement(ZS,{className:"tw-absolute tw-right-3 tw-top-1/2 tw-size-4 -tw-translate-y-1/2 tw-transform tw-text-muted"}));var l4=N(U());var gi=N(U(),1);var xOr=!!(typeof window<"u"&&window.document&&window.document.createElement);function SL(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t?.(o),n===!1||!o.defaultPrevented)return e?.(o)}}var aot=N(U(),1);function sot(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function c_e(...t){return e=>{let n=!1,r=t.map(o=>{let i=sot(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():sot(t[o],null)}}}}function s4(...t){return aot.useCallback(c_e(...t),t)}var Hv=N(U(),1),lot=N(Ve(),1);function cot(t,e=[]){let n=[];function r(i,s){let a=Hv.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=Hv.useMemo(()=>m,Object.values(m));return(0,lot.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=Hv.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>Hv.createContext(s));return function(a){let l=a?.[t]||i;return Hv.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,ZGt(o,...e)]}function ZGt(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return Hv.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var u_e=N(U(),1);var uot=N(U(),1),jP=globalThis?.document?uot.useLayoutEffect:()=>{};var JGt=u_e[" useId ".trim().toString()]||(()=>{}),XGt=0;function dot(t){let[e,n]=u_e.useState(JGt());return jP(()=>{t||n(r=>r??String(XGt++))},[t]),t||(e?`radix-${e}`:"")}var cd=N(U(),1);var fot=N(U(),1);function QGt(t,e){return fot.useReducer((n,r)=>e[n][r]??n,t)}var TZ=t=>{let{present:e,children:n}=t,r=e8t(e),o=typeof n=="function"?n({present:r.isPresent}):cd.Children.only(n),i=s4(r.ref,t8t(o));return typeof n=="function"||r.isPresent?cd.cloneElement(o,{ref:i}):null};TZ.displayName="Presence";function e8t(t){let[e,n]=cd.useState(),r=cd.useRef(null),o=cd.useRef(t),i=cd.useRef("none"),s=t?"mounted":"unmounted",[a,l]=QGt(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return cd.useEffect(()=>{let c=SZ(r.current);i.current=a==="mounted"?c:"none"},[a]),jP(()=>{let c=r.current,u=o.current;if(u!==t){let f=i.current,p=SZ(c);t?l("MOUNT"):p==="none"||c?.display==="none"?l("UNMOUNT"):l(u&&f!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=t}},[t,l]),jP(()=>{if(e){let c,u=e.ownerDocument.defaultView??window,d=p=>{let h=SZ(r.current).includes(CSS.escape(p.animationName));if(p.target===e&&h&&(l("ANIMATION_END"),!o.current)){let g=e.style.animationFillMo
`,BYt=tE?"\xA0":L7,Uat="\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC",Bat="A-Za-z\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u0300-\u0590\u0800-\u1FFF\u200E\u2C00-\uFB1C\uFE00-\uFE6F\uFEFD-\uFFFF",zYt=new RegExp("^[^"+Bat+"]*["+Uat+"]"),jYt=new RegExp("^[^"+Uat+"]*["+Bat+"]"),vc={bold:1,capitalize:1024,code:16,highlight:R7,italic:2,lowercase:256,strikethrough:C4,subscript:32,superscript:64,underline:_4,uppercase:512},VYt={directionless:1,unmergeable:2},Kst={center:NSe,end:DSe,justify:RSe,left:MSe,right:OSe,start:LSe},WYt={[NSe]:"center",[DSe]:"end",[RSe]:"justify",[MSe]:"left",[OSe]:"right",[LSe]:"start"},HYt={normal:0,segmented:2,token:1},KYt={[NYt]:"normal",[RYt]:"segmented",[OYt]:"token"},qYt="$",qst="$config";function zat(t,e,n,r,o,i){let s=t.getFirstChild();for(;s!==null;){let a=s.__key;s.__parent===e&&(Le(s)&&zat(s,a,n,r,o,i),n.has(a)||i.delete(a),o.push(a)),s=s.getNextSibling()}}var GYt=100,oSe=!1,$Se=0;function YYt(t){$Se=t.timeStamp}function H_e(t,e,n){let r=t.nodeName==="BR",o=e.__lexicalLineBreak;return o&&(t===o||r&&t.previousSibling===o)||r&&j7(t,n)!==void 0}function ZYt(t,e,n){let r=Ay(em(n)),o=null,i=null;r!==null&&r.anchorNode===t&&(o=r.anchorOffset,i=r.focusOffset);let s=t.nodeValue;s!==null&&rTe(e,s,o,i,!1)}function JYt(t,e,n){if(dn(t)){let r=t.anchor.getNode();if(r.is(n)&&t.format!==r.getFormat())return!1}return ky(e)&&n.isAttached()}function XYt(t,e,n,r){for(let o=t;o&&!uct(o);o=R4(o)){let i=j7(o,e);if(i!==void 0){let s=wa(i,n);if(s)return Ao(s)||!pu(o)?void 0:[o,s]}else if(o===r)return[r,Glt(n)]}}function jat(t,e,n){oSe=!0;let r=performance.now()-$Se>GYt;try{wf(t,()=>{let o=Gr()||function(f){return f.getEditorState().read(()=>{let p=Gr();return p!==null?p.clone():null})}(t),i=new Map,s=t.getRootElement(),a=t._editorState,l=t._blockCursorElement,c=!1,u="";for(let f=0;f<e.length;f++){let p=e[f],m=p.type,h=p.target,g=XYt(h,t,a,s);if(!g)continue;let[y,w]=g;if(m==="characterData")r&&Bt(w)&&ky(h)&&JYt(o,h,w)&&ZYt(h,w,t);else if(m==="childList"){c=!0;let v=p.addedNodes;for(let _=0;_<v.length;_++){let T=v[_],S=Klt(T),P=T.parentNode;if(P!=null&&T!==l&&S===null&&!H_e(T,P,t)){if(tE){let A=(pu(T)?T.innerText:null)||T.nodeValue;A&&(u+=A)}P.removeChild(T)}}let x=p.removedNodes,b=x.length;if(b>0){let _=0;for(let T=0;T<b;T++){let S=x[T];(H_e(S,h,t)||l===S)&&(h.appendChild(S),_++)}b!==_&&i.set(y,w)}}}if(i.size>0)for(let[f,p]of i)p.reconcileObservedMutation(f,t);let d=n.takeRecords();if(d.length>0){for(let f=0;f<d.length;f++){let p=d[f],m=p.addedNodes,h=p.target;for(let g=0;g<m.length;g++){let y=m[g],w=y.parentNode;w==null||y.nodeName!=="BR"||H_e(y,h,t)||w.removeChild(y)}}n.takeRecords()}o!==null&&(c&&hd(o),tE&&ect(t)&&o.insertRawText(u))})}finally{oSe=!1}}function Vat(t){let e=t._observer;e!==null&&jat(t,e.takeRecords(),e)}function Wat(t){(function(e){$Se===0&&em(e).addEventListener("textInput",YYt,!0)})(t),t._observer=new MutationObserver((e,n)=>{jat(t,e,n)})}var iSe=class{constructor(e,n){this.key=e,this.parse=n.parse.bind(n),this.unparse=(n.unparse||nZt).bind(n),this.isEqual=(n.isEqual||Object.is).bind(n),this.defaultValue=this.parse(void 0)}};function QYt(t,e){return new iSe(t,e)}function w7(t,e,n="latest"){let r=(n==="latest"?t.getLatest():t).__state;return r?r.getValue(e):e.defaultValue}function eZt(t,e,n){let r=w7(t,n,"direct"),o=w7(e,n,"direct");return n.isEqual(r,o)?null:[r,o]}function tZt(t,e,n){let r;if(Qa(),typeof n=="function"){let i=t.getLatest(),s=w7(i,e);if(r=n(s),e.isEqual(s,r))return i}else r=n;let o=t.getWritable();return FSe(o).updateFromKnown(e,r),o}function Hat(t){let e=new Map,n=new Set;for(let r=typeof t=="function"?t:t.replace;r.prototype&&r.prototype.getType!==void 0;r=Object.getPrototypeOf(r)){let{ownNodeConfig:o}=cTe(r);if(o&&o.stateConfigs)for(let i of o.stateConfigs){let s;"stateConfig"in i?(s=i.stateConfig,i.flat&&n.add(s.key)):s=i,e.set(s.key,s)}}return{flatKeys:n,sharedConfigMap:e}}var sSe=class t{constructor(e,n,r=void 0,o=new Map,i=void 0){this.node=e,this.sharedNodeState=n,this.unknownState=r,this.knownState=o;let{sharedConfigMap:s}=this.sharedNodeState,a=i!==void 0?i:function(l,c,u){let d=u.size;if
`)n.preventDefault(),Et(r,h4,!1);else if(l===sx)n.preventDefault(),Et(r,pSe,void 0);else if(l==null&&n.dataTransfer){let p=n.dataTransfer.getData("text/plain");n.preventDefault(),s.insertRawText(p)}else l!=null&&Clt(s,i,l,n.timeStamp,!0)?(n.preventDefault(),Et(r,$L,l)):LL=l;xlt=n.timeStamp}})}(t,e)]);var g4=0,vlt=null,xlt=0,LL=null,S7=new WeakMap,wSe=!1,vSe=!1,y4=!1,f4=!1,q_e=!1,G_e="",QP=null,blt=[0,"",0,"root",0];function Clt(t,e,n,r,o){let i=t.anchor,s=t.focus,a=i.getNode(),l=wi(),c=Ay(em(l)),u=c!==null?c.anchorNode:null,d=i.key,f=l.getElementByKey(d),p=n.length;return d!==s.key||!Bt(a)||(!o&&(!h7||xlt<r+50)||a.isDirty()&&p<2||Ylt(n))&&i.offset!==s.offset&&!a.isComposing()||ex(a)||a.isDirty()&&p>1||(o||!h7)&&f!==null&&!a.isComposing()&&u!==sE(f)||c!==null&&e!==null&&(!e.collapsed||e.startContainer!==c.anchorNode||e.startOffset!==c.anchorOffset)||a.getFormat()!==t.format||a.getStyle()!==t.style||function(m,h){if(h.isSegmented())return!0;if(!m.isCollapsed())return!1;let g=m.anchor.offset,y=h.getParentOrThrow(),w=q_(h);return g===0?!h.canInsertTextBefore()||!y.canInsertTextBefore()&&!h.isComposing()||w||function(v){let x=v.getPreviousSibling();return(Bt(x)||Le(x)&&x.isInline())&&!x.canInsertTextAfter()}(h):g===h.getTextContentSize()&&(!h.canInsertTextAfter()||!y.canInsertTextAfter()&&!h.isComposing()||w)}(t,a)}function rat(t,e){return ky(t)&&t.nodeValue!==null&&e!==0&&e!==t.nodeValue.length}function oat(t,e,n){let{anchorNode:r,anchorOffset:o,focusNode:i,focusOffset:s}=t;wSe&&(wSe=!1,rat(r,o)&&rat(i,s)&&!QP)||wf(e,()=>{if(!n)return void hd(null);if(!N4(e,r,i))return;let a=Gr();if(QP&&dn(a)&&a.isCollapsed()){let l=a.anchor,c=QP.anchor;(l.key===c.key&&l.offset===c.offset+1||l.offset===1&&c.getNode().is(l.getNode().getPreviousSibling()))&&(a=QP.clone(),hd(a))}if(QP=null,dn(a)){let l=a.anchor,c=l.getNode();if(a.isCollapsed()){t.type==="Range"&&t.anchorNode===t.focusNode&&(a.dirty=!0);let u=em(e).event,d=u?u.timeStamp:performance.now(),[f,p,m,h,g]=blt,y=md(),w=e.isComposing()===!1&&y.getTextContent()==="";if(d<g+200&&l.offset===m&&l.key===h)f7(a,f,p);else if(l.type==="text")Bt(c)||De(141),_lt(a,c);else if(l.type==="element"&&!w){Le(c)||De(259);let v=l.getNode();v.isEmpty()?function(x,b){let _=b.getTextFormat(),T=b.getTextStyle();f7(x,_,T)}(a,v):f7(a,0,"")}}else{let u=l.key,d=a.focus.key,f=a.getNodes(),p=f.length,m=a.isBackward(),h=m?s:o,g=m?o:s,y=m?d:u,w=m?u:d,v=Fat,x=!1;for(let b=0;b<p;b++){let _=f[b],T=_.getTextContentSize();if(Bt(_)&&T!==0&&!(b===0&&_.__key===y&&h===T||b===p-1&&_.__key===w&&g===0)&&(x=!0,v&=_.getFormat(),v===0))break}a.format=x?v:0}}Et(e,USe,void 0)})}function f7(t,e,n){t.format===e&&t.style===n||(t.format=e,t.style=n,t.dirty=!0)}function _lt(t,e){f7(t,e.getFormat(),e.getStyle())}function Slt(t){if(!t.getTargetRanges)return null;let e=t.getTargetRanges();return e.length===0?null:e[0]}function s7(t,e){let n=t._compositionKey;if(el(null),n!==null&&e!=null){if(e===""){let r=wa(n),o=sE(t.getElementByKey(n));return void(o!==null&&o.nodeValue!==null&&Bt(r)&&rTe(r,o.nodeValue,null,null,!0))}if(e[e.length-1]===`
`){let r=Gr();if(dn(r)){let o=r.focus;return r.anchor.set(o.key,o.offset,o.type),void Et(t,_7,null)}}}nTe(!0,t,e)}function Tlt(t){let e=t.__lexicalEventHandles;return e===void 0&&(e=[],t.__lexicalEventHandles=e),e}var FL=new Map;function Ilt(t){let e=ict(t.target);if(e===null)return;let n=eTe(e.anchorNode);if(n===null)return;vSe&&(vSe=!1,wf(n,()=>{let l=lE(),c=e.anchorNode;(pu(c)||ky(c))&&hd(U7(l,e,n,t))}));let r=tTe(n),o=r[r.length-1],i=o._key,s=FL.get(i),a=s||o;a!==n&&oat(e,a,!1),oat(e,n,!0),n!==o?FL.set(i,n):s&&FL.delete(i)}function iat(t){t._lexicalHandled=!0}function sat(t){return t._lexicalHandled===!0}var hZt=()=>{};function gZt(t){let e=t.ownerDocument,n=S7.get(e);if(n===void 0)return void hZt();let r=n-1;r>=0||De(164),S7.set(e,r),r===0&&e.removeEventListener("selectionchange",Ilt);let o=O4(t);z7(o)?(function(s){if(s._parentEditor!==null){let a=tTe(s),l=a[a.length-1]._key;FL.get(l)===s&&FL.delete(l)}else FL.delete(s._key)}(o),t.__lexicalEditor=null):o&&De(198);let i=Tlt(t);for(let s=0;s<i.length;s++)i[s]();t.__lexicalEventHandles=[]}function xSe(t,e,n){Qa();let r=t.__key,o=t.getParent();if(o===null)return;let i=function(a){let l=Gr();if(!dn(l)||!Le(a))return l;let{anchor:c,focus:u}=l,d=c.getNode(),f=u.getNode();return N7(d,a)&&c.set(a.__key,0,"element"),N7(f,a)&&u.set(a.__key,0,"element"),l}(t),s=!1;if(dn(i)&&e){let a=i.anchor,l=i.focus;a.key===r&&(P7(a,t,o,t.getPreviousSibling(),t.getNextSibling()),s=!0),l.key===r&&(P7(l,t,o,t.getPreviousSibling(),t.getNextSibling()),s=!0)}else F7(i)&&e&&t.isSelected()&&t.selectPrevious();if(dn(i)&&e&&!s){let a=t.getIndexWithinParent();G_(t),I7(i,o,a,-1)}else G_(t);n||Ah(o)||o.canBeEmpty()||!o.isEmpty()||xSe(o,e),e&&i&&fd(o)&&o.isEmpty()&&o.selectEnd()}function yZt(t){return t}var Z_=class{static getType(){let{ownNodeType:e}=cTe(this);return e===void 0&&De(64,this.name),e}static clone(e){De(65,this.name)}$config(){return{}}config(e,n){let r=n.extends||Object.getPrototypeOf(this.constructor);return Object.assign(n,{extends:r,type:e}),{[e]:n}}afterCloneFrom(e){this.__key===e.__key?(this.__parent=e.__parent,this.__next=e.__next,this.__prev=e.__prev,this.__state=e.__state):e.__state&&(this.__state=e.__state.getWritable(this))}constructor(e){this.__type=this.constructor.getType(),this.__parent=null,this.__prev=null,this.__next=null,Object.defineProperty(this,"__state",{configurable:!0,enumerable:!1,value:void 0,writable:!0}),Hlt(this,e)}getType(){return this.__type}isInline(){De(137,this.constructor.name)}isAttached(){let e=this.__key;for(;e!==null;){if(e==="root")return!0;let n=wa(e);if(n===null)break;e=n.__parent}return!1}isSelected(e){let n=e||Gr();if(n==null)return!1;let r=n.getNodes().some(o=>o.__key===this.__key);if(Bt(this))return r;if(dn(n)&&n.anchor.type==="element"&&n.focus.type==="element"){if(n.isCollapsed())return!1;let o=this.getParent();if(Ao(this)&&this.isInline()&&o){let i=n.isBackward()?n.focus:n.anchor;if(o.is(i.getNode())&&i.offset===o.getChildrenSize()&&this.is(o.getLastChild()))return!1}}return r}getKey(){return this.__key}getIndexWithinParent(){let e=this.getParent();if(e===null)return-1;let n=e.getFirstChild(),r=0;for(;n!==null;){if(this.is(n))return r;r++,n=n.getNextSibling()}return-1}getParent(){let e=this.getLatest().__parent;return e===null?null:wa(e)}getParentOrThrow(){let e=this.getParent();return e===null&&De(66,this.__key),e}getTopLevelElement(){let e=this;for(;e!==null;){let n=e.getParent();if(Ah(n))return Le(e)||e===this&&Ao(e)||De(194),e;e=n}return null}getTopLevelElementOrThrow(){let e=this.getTopLevelElement();return e===null&&De(67,this.__key),e}getParents(){let e=[],n=this.getParent();for(;n!==null;)e.push(n),n=n.getParent();return e}getParentKeys(){let e=[],n=this.getParent();for(;n!==null;)e.push(n.__key),n=n.getParent();return e}getPreviousSibling(){let e=this.getLatest().__prev;return e===null?null:wa(e)}getPreviousSiblings(){let e=[],n=this.getParent();if(n===null)return e;let r=n.getFirstChild();for(;r!==null&&!r.is(this);)e.push(r),r=r.getNextSibling();return e}getNextSibling(){let e=this.getLatest().__next;return e===null?null:wa(e)}get
`}createDOM(){return document.createElement("br")}updateDOM(){return!1}isInline(){return!0}static importDOM(){return{br:e=>function(n){let r=n.parentElement;if(r!==null&&ISe(r)){let o=r.firstChild;if(o===n||o.nextSibling===n&&a7(o)){let i=r.lastChild;if(i===n||i.previousSibling===n&&a7(i))return!0}}return!1}(e)||function(n){let r=n.parentElement;if(r!==null&&ISe(r)){let o=r.firstChild;if(o===n||o.nextSibling===n&&a7(o))return!1;let i=r.lastChild;if(i===n||i.previousSibling===n&&a7(i))return!0}return!1}(e)?null:{conversion:wZt,priority:0}}}static importJSON(e){return VL().updateFromJSON(e)}};function wZt(t){return{node:VL()}}function VL(){return L4(new jL)}function eE(t){return t instanceof jL}function a7(t){return ky(t)&&/^( |\t|\r?\n)+$/.test(t.textContent||"")}function Y_e(t,e){return 16&e?"code":e&R7?"mark":32&e?"sub":64&e?"sup":null}function Z_e(t,e){return 1&e?"strong":2&e?"em":"span"}function Plt(t,e,n,r,o){let i=r.classList,s=UL(o,"base");s!==void 0&&i.add(...s),s=UL(o,"underlineStrikethrough");let a=!1,l=e&_4&&e&C4;s!==void 0&&(n&_4&&n&C4?(a=!0,l||i.add(...s)):l&&i.remove(...s));for(let c in vc){let u=vc[c];if(s=UL(o,c),s!==void 0)if(n&u){if(a&&(c==="underline"||c==="strikethrough")){e&u&&i.remove(...s);continue}e&u&&(!l||c!=="underline")&&c!=="strikethrough"||i.add(...s)}else e&u&&i.remove(...s)}}function Elt(t,e,n){let r=e.firstChild,o=n.isComposing(),i=t+(o?L7:"");if(r==null)e.textContent=i;else{let s=r.nodeValue;if(s!==i)if(o||tE){let[a,l,c]=function(u,d){let f=u.length,p=d.length,m=0,h=0;for(;m<f&&m<p&&u[m]===d[m];)m++;for(;h+m<f&&h+m<p&&u[f-h-1]===d[p-h-1];)h++;return[m,f-m-h,d.slice(m,p-h)]}(s,i);l!==0&&r.deleteData(a,l),r.insertData(a,c)}else r.nodeValue=i}}function aat(t,e,n,r,o,i){Elt(o,t,e);let s=i.theme.text;s!==void 0&&Plt(0,0,r,t,s)}function l7(t,e){let n=document.createElement(e);return n.appendChild(t),n}var oE=class t extends Z_{static getType(){return"text"}static clone(e){return new t(e.__text,e.__key)}afterCloneFrom(e){super.afterCloneFrom(e),this.__text=e.__text,this.__format=e.__format,this.__style=e.__style,this.__mode=e.__mode,this.__detail=e.__detail}constructor(e="",n){super(n),this.__text=e,this.__format=0,this.__style="",this.__mode=0,this.__detail=0}getFormat(){return this.getLatest().__format}getDetail(){return this.getLatest().__detail}getMode(){let e=this.getLatest();return KYt[e.__mode]}getStyle(){return this.getLatest().__style}isToken(){return this.getLatest().__mode===1}isComposing(){return this.__key===K_()}isSegmented(){return this.getLatest().__mode===2}isDirectionless(){return!!(1&this.getLatest().__detail)}isUnmergeable(){return!!(2&this.getLatest().__detail)}hasFormat(e){let n=vc[e];return!!(this.getFormat()&n)}isSimpleText(){return this.__type==="text"&&this.__mode===0}getTextContent(){return this.getLatest().__text}getFormatFlags(e,n){return k7(this.getLatest().__format,e,n)}canHaveFormat(){return!0}isInline(){return!0}createDOM(e,n){let r=this.__format,o=Y_e(0,r),i=Z_e(0,r),s=o===null?i:o,a=document.createElement(s),l=a;this.hasFormat("code")&&a.setAttribute("spellcheck","false"),o!==null&&(l=document.createElement(i),a.appendChild(l)),aat(l,this,0,r,this.__text,e);let c=this.__style;return c!==""&&(a.style.cssText=c),a}updateDOM(e,n,r){let o=this.__text,i=e.__format,s=this.__format,a=Y_e(0,i),l=Y_e(0,s),c=Z_e(0,i),u=Z_e(0,s);if((a===null?c:a)!==(l===null?u:l))return!0;if(a===l&&c!==u){let h=n.firstChild;h==null&&De(48);let g=document.createElement(u);return aat(g,this,0,s,o,r),n.replaceChild(g,h),!1}let d=n;l!==null&&a!==null&&(d=n.firstChild,d==null&&De(49)),Elt(o,d,this);let f=r.theme.text;f!==void 0&&i!==s&&Plt(0,i,s,d,f);let p=e.__style,m=this.__style;return p!==m&&(n.style.cssText=m),!1}static importDOM(){return{"#text":()=>({conversion:CZt,priority:0}),b:()=>({conversion:xZt,priority:0}),code:()=>({conversion:Xv,priority:0}),em:()=>({conversion:Xv,priority:0}),i:()=>({conversion:Xv,priority:0}),mark:()=>({conversion:Xv,priority:0}),s:()=>({conversion:Xv,priority:0}),span:()=>({conversion:vZt,priority:0}),strong:()=>({conversion:Xv,priority:0}),sub:()=>({convers
`||a===`\r
`?o.push(VL()):a===" "?o.push($7()):a!==""&&o.push(Xa(a))}return{node:o}}if(n=n.replace(/\r/g,"").replace(/[ \t\n]+/g," "),n==="")return{node:null};if(n[0]===" "){let r=e,o=!0;for(;r!==null&&(r=cat(r,!1))!==null;){let i=r.textContent||"";if(i.length>0){/[ \t\n]$/.test(i)&&(n=n.slice(1)),o=!1;break}}o&&(n=n.slice(1))}if(n[n.length-1]===" "){let r=e,o=!0;for(;r!==null&&(r=cat(r,!0))!==null;)if((r.textContent||"").replace(/^( |\t|\r?\n)+/,"").length>0){o=!1;break}o&&(n=n.slice(0,n.length-1))}return n===""?{node:null}:{node:Xa(n)}}function cat(t,e){let n=t;for(;;){let r;for(;(r=e?n.nextSibling:n.previousSibling)===null;){let i=n.parentElement;if(i===null)return null;n=i}if(n=r,pu(n)){let i=n.style.display;if(i===""&&!act(n)||i!==""&&!i.startsWith("inline"))return null}let o=n;for(;(o=e?n.firstChild:n.lastChild)!==null;)n=o;if(ky(n))return n;if(n.nodeName==="BR")return null}}var _Zt={code:"code",em:"italic",i:"italic",mark:"highlight",s:"strikethrough",strong:"bold",sub:"subscript",sup:"superscript",u:"underline"};function Xv(t){let e=_Zt[t.nodeName.toLowerCase()];return e===void 0?{node:null}:{forChild:HSe(t.style,e),node:null}}function Xa(t=""){return L4(new oE(t))}function Bt(t){return t instanceof oE}function HSe(t,e){let n=t.fontWeight,r=t.textDecoration.split(" "),o=n==="700"||n==="bold",i=r.includes("line-through"),s=t.fontStyle==="italic",a=r.includes("underline"),l=t.verticalAlign;return c=>(Bt(c)&&(o&&!c.hasFormat("bold")&&c.toggleFormat("bold"),i&&!c.hasFormat("strikethrough")&&c.toggleFormat("strikethrough"),s&&!c.hasFormat("italic")&&c.toggleFormat("italic"),a&&!c.hasFormat("underline")&&c.toggleFormat("underline"),l!=="sub"||c.hasFormat("subscript")||c.toggleFormat("subscript"),l!=="super"||c.hasFormat("superscript")||c.toggleFormat("superscript"),e&&!c.hasFormat(e)&&c.toggleFormat(e)),c)}var WL=class t extends oE{static getType(){return"tab"}static clone(e){return new t(e.__key)}constructor(e){super(" ",e),this.__detail=2}static importDOM(){return null}createDOM(e){let n=super.createDOM(e),r=UL(e.theme,"tab");return r!==void 0&&n.classList.add(...r),n}static importJSON(e){return $7().updateFromJSON(e)}setTextContent(e){return e!==" "&&e!==""&&De(126),super.setTextContent(" ")}spliceText(e,n,r,o){return r===""&&n===0||r===" "&&n===1||De(286),this}setDetail(e){return e!==2&&De(127),this}setMode(e){return e!=="normal"&&De(128),this}canInsertTextBefore(){return!1}canInsertTextAfter(){return!1}};function $7(){return L4(new WL)}function KSe(t){return t instanceof WL}var bSe=class{constructor(e,n,r){this._selection=null,this.key=e,this.offset=n,this.type=r}is(e){return this.key===e.key&&this.offset===e.offset&&this.type===e.type}isBefore(e){return this.key===e.key?this.offset<e.offset:pTe(Sh(eS(this,"next")),Sh(eS(e,"next")))<0}getNode(){let e=wa(this.key);return e===null&&De(20),e}set(e,n,r,o){let i=this._selection,s=this.key;o&&this.key===e&&this.offset===n&&this.type===r||(this.key=e,this.offset=n,this.type=r,e1()||(K_()===s&&el(e),i!==null&&(i.setCachedNodes(null),i.dirty=!0)))}};function Eh(t,e,n){return new bSe(t,e,n)}function J_e(t,e){let n=e.__key,r=t.offset,o="element";if(Bt(e)){o="text";let i=e.getTextContentSize();r>i&&(r=i)}else if(!Le(e)){let i=e.getNextSibling();if(Bt(i))n=i.__key,r=0,o="text";else{let s=e.getParent();s&&(n=s.__key,r=e.getIndexWithinParent()+1)}}t.set(n,r,o)}function uat(t,e){if(Le(e)){let n=e.getLastDescendant();Le(n)||Bt(n)?J_e(t,n):J_e(t,e)}else J_e(t,e)}var T7=class t{constructor(e){this._cachedNodes=null,this._nodes=e,this.dirty=!1}getCachedNodes(){return this._cachedNodes}setCachedNodes(e){this._cachedNodes=e}is(e){if(!F7(e))return!1;let n=this._nodes,r=e._nodes;return n.size===r.size&&Array.from(n).every(o=>r.has(o))}isCollapsed(){return!1}isBackward(){return!1}getStartEndPoints(){return null}add(e){this.dirty=!0,this._nodes.add(e),this._cachedNodes=null}delete(e){this.dirty=!0,this._nodes.delete(e),this._cachedNodes=null}clear(){this.dirty=!0,this._nodes.clear(),this._cachedNodes=null}has(e){return this._nodes.has(e)}clone(){return new t(new Set(this._nodes))}extract(){return th
`),u=!f.isEmpty();else if(u=!1,Bt(f)){let p=f.getTextContent();f===n?f===r?o.type==="element"&&i.type==="element"&&i.offset!==o.offset||(p=a<l?p.slice(a,l):p.slice(l,a)):p=s?p.slice(a):p.slice(l):f===r&&(p=s?p.slice(0,l):p.slice(0,a)),c+=p}else!Ao(f)&&!eE(f)||f===r&&this.isCollapsed()||(c+=f.getTextContent())}return c}applyDOMRange(e){let n=wi(),r=n.getEditorState()._selection,o=klt(e.startContainer,e.startOffset,e.endContainer,e.endOffset,n,r);if(o===null)return;let[i,s]=o;this.anchor.set(i.key,i.offset,i.type,!0),this.focus.set(s.key,s.offset,s.type,!0),v7(this)}clone(){let e=this.anchor,n=this.focus;return new t(Eh(e.key,e.offset,e.type),Eh(n.key,n.offset,n.type),this.format,this.style)}toggleFormat(e){this.format=k7(this.format,e,null),this.dirty=!0}setFormat(e){this.format=e,this.dirty=!0}setStyle(e){this.style=e,this.dirty=!0}hasFormat(e){let n=vc[e];return!!(this.format&n)}insertRawText(e){let n=e.split(/(\r?\n|\t)/),r=[],o=n.length;for(let i=0;i<o;i++){let s=n[i];s===`
`||s===`\r
`?r.push(VL()):s===" "?r.push($7()):r.push(Xa(s))}this.insertNodes(r)}insertText(e){let n=this.anchor,r=this.focus,o=this.format,i=this.style,s=n,a=r;!this.isCollapsed()&&r.isBefore(n)&&(s=r,a=n),s.type==="element"&&function(g,y,w,v){let x=g.getNode(),b=x.getChildAtIndex(g.offset),_=Xa(),T=fd(x)?ox().append(_):_;_.setFormat(w),_.setStyle(v),b===null?x.append(T):b.insertBefore(T),g.is(y)&&y.set(_.__key,0,"text"),g.set(_.__key,0,"text")}(s,a,o,i),a.type==="element"&&QL(a,Sh(eS(a,"next")));let l=s.offset,c=a.offset,u=this.getNodes(),d=u.length,f=u[0];Bt(f)||De(26);let p=f.getTextContent().length,m=f.getParentOrThrow(),h=u[d-1];if(d===1&&a.type==="element"&&(c=p,a.set(s.key,c,"text")),this.isCollapsed()&&l===p&&(ex(f)||!f.canInsertTextAfter()||!m.canInsertTextAfter()&&f.getNextSibling()===null)){let g=f.getNextSibling();if(Bt(g)&&g.canInsertTextBefore()&&!ex(g)||(g=Xa(),g.setFormat(o),g.setStyle(i),m.canInsertTextAfter()?f.insertAfter(g):m.insertAfter(g)),g.select(0,0),f=g,e!=="")return void this.insertText(e)}else if(this.isCollapsed()&&l===0&&(ex(f)||!f.canInsertTextBefore()||!m.canInsertTextBefore()&&f.getPreviousSibling()===null)){let g=f.getPreviousSibling();if(Bt(g)&&!ex(g)||(g=Xa(),g.setFormat(o),m.canInsertTextBefore()?f.insertBefore(g):m.insertBefore(g)),g.select(),f=g,e!=="")return void this.insertText(e)}else if(f.isSegmented()&&l!==p){let g=Xa(f.getTextContent());g.setFormat(o),f.replace(g),f=g}else if(!this.isCollapsed()&&e!==""){let g=h.getParent();if(!m.canInsertTextBefore()||!m.canInsertTextAfter()||Le(g)&&(!g.canInsertTextBefore()||!g.canInsertTextAfter()))return this.insertText(""),Alt(this.anchor,this.focus,null),void this.insertText(e)}if(d===1){if(q_(f)){let v=Xa(e);return v.select(),void f.replace(v)}let g=f.getFormat(),y=f.getStyle();if(l!==c||g===o&&y===i){if(KSe(f)){let v=Xa(e);return v.setFormat(o),v.setStyle(i),v.select(),void f.replace(v)}}else{if(f.getTextContent()!==""){let v=Xa(e);if(v.setFormat(o),v.setStyle(i),v.select(),l===0)f.insertBefore(v,!1);else{let[x]=f.splitText(l);x.insertAfter(v,!1)}return void(v.isComposing()&&this.anchor.type==="text"&&(this.anchor.offset-=e.length))}f.setFormat(o),f.setStyle(i)}let w=c-l;f=f.spliceText(l,w,e,!0),f.getTextContent()===""?f.remove():this.anchor.type==="text"&&(f.isComposing()?this.anchor.offset-=e.length:(this.format=g,this.style=y))}else{let g=new Set([...f.getParentKeys(),...h.getParentKeys()]),y=Le(f)?f:f.getParentOrThrow(),w=Le(h)?h:h.getParentOrThrow(),v=h;if(!y.is(w)&&w.isInline())do v=w,w=w.getParentOrThrow();while(w.isInline());if(a.type==="text"&&(c!==0||h.getTextContent()==="")||a.type==="element"&&h.getIndexWithinParent()<c)if(Bt(h)&&!q_(h)&&c!==h.getTextContentSize()){if(h.isSegmented()){let S=Xa(h.getTextContent());h.replace(S),h=S}fd(a.getNode())||a.type!=="text"||(h=h.spliceText(0,c,"")),g.add(h.__key)}else{let S=h.getParentOrThrow();S.canBeEmpty()||S.getChildrenSize()!==1?h.remove():S.remove()}else g.add(h.__key);let x=w.getChildren(),b=new Set(u),_=y.is(w),T=y.isInline()&&f.getNextSibling()===null?y:f;for(let S=x.length-1;S>=0;S--){let P=x[S];if(P.is(f)||Le(P)&&P.isParentOf(f))break;P.isAttached()&&(!b.has(P)||P.is(v)?_||T.insertAfter(P,!1):P.remove())}if(!_){let S=w,P=null;for(;S!==null;){let A=S.getChildren(),O=A.length;(O===0||A[O-1].is(P))&&(g.delete(S.__key),P=S),S=S.getParent()}}if(q_(f))if(l===p)f.select();else{let S=Xa(e);S.select(),f.replace(S)}else f=f.spliceText(l,p-l,e,!0),f.getTextContent()===""?f.remove():f.isComposing()&&this.anchor.type==="text"&&(this.anchor.offset-=e.length);for(let S=1;S<d;S++){let P=u[S],A=P.__key;g.has(A)||P.remove()}}}removeText(){let e=Gr()===this;x4(this,mct(kSe(this))),e&&Gr()!==this&&hd(this)}formatText(e,n=null){if(this.isCollapsed())return this.toggleFormat(e),void el(null);let r=this.getNodes(),o=[];for(let x of r)Bt(x)&&o.push(x);let i=x=>{r.forEach(b=>{if(Le(b)){let _=b.getFormatFlags(e,x);b.setTextFormat(_)}})},s=o.length;if(s===0)return this.toggleFormat(e),el(null),void i(n);let a=this.anchor,l=this.focus,c=this.isBackward(),u=c?l:a,d=c?a:l,f=0,p=o[0],m=u.type==="element"?0:u.offs
`);let l=a.length;if(!Mr(r)||o>=l){let c=r.getParent();r.remove(),c==null||c.getChildrenSize()!==0||o1(c)||c.remove(),o-=l+s,r=i}else{let c=r.getKey(),u=t.getEditorState().read(()=>{let p=_ct(c);return Mr(p)&&p.isSimpleText()?p.getTextContent():null}),d=l-o,f=a.slice(0,d);if(u!==null&&u!==a){let p=$4(),m=r;if(r.isSimpleText())r.setTextContent(u);else{let h=vf(u);r.replace(h),m=h}if(jt(p)&&p.isCollapsed()){let h=p.anchor.offset;m.select(h,h)}}else if(r.isSimpleText()){let p=e.key===c,m=e.offset;m<o&&(m=l);let h=p?m-o:0,g=p?m:d;if(p&&h===0){let[y]=r.splitText(h,g);y.remove()}else{let[,y]=r.splitText(h,g);y.remove()}}else{let p=vf(f);r.replace(p)}o=0}}}function sJt(t){let e=t.getStyle(),n=sdt(e);PJ.set(e,n)}function VTe(t,e){(jt(t)?t.isCollapsed():Mr(t)||lr(t))||KTe(280);let n=EJ(jt(t)?t.style:Mr(t)?t.getStyle():t.getTextStyle()),r=Object.entries(e).reduce((i,[s,a])=>(typeof a=="function"?i[s]=a(n[s],t):a===null?delete i[s]:i[s]=a,i),{...n}),o=adt(r);jt(t)||Mr(t)?t.setStyle(o):t.setTextStyle(o),PJ.set(o,r)}function aJt(t,e){if(jt(t)&&t.isCollapsed()){VTe(t,e);let n=t.anchor.getNode();lr(n)&&n.isEmpty()&&VTe(n,e)}cdt(n=>{VTe(n,e)})}function cdt(t){let e=gn();if(!e)return;let n=new Map;if(jt(e))for(let i of yct(e).getTextSlices())i&&n.set(i.caret.origin.getKey(),i.getSliceIndices());let r=e.getNodes();for(let i of r){if(!Mr(i)||!i.canHaveFormat())continue;let[s,a]=(o=i,n.get(o.getKey())||[0,o.getTextContentSize()]);a!==s&&(xTe(i)||s===0&&a===i.getTextContentSize()?t(i):t(i.splitText(s,a)[s===0?0:1]))}var o;jt(e)&&e.anchor.type==="text"&&e.focus.type==="text"&&e.anchor.key===e.focus.key&&udt(e)}function udt(t){if(t.isBackward()){let{anchor:e,focus:n}=t,{key:r,offset:o,type:i}=e;e.set(n.key,n.offset,n.type),n.set(r,o,i)}}function ddt(t,e){let n=t.getFormatType(),r=t.getIndent();n!==e.getFormatType()&&e.setFormat(n),r!==e.getIndent()&&e.setIndent(r)}function lJt(t,e,n=ddt){if(t===null)return;let r=t.getStartEndPoints(),o=new Map,i=null;if(r){let[s,a]=r;i=H7(),i.anchor.set(s.key,s.offset,s.type),i.focus.set(a.key,a.offset,a.type);let l=HTe(s.getNode(),z4),c=HTe(a.getNode(),z4);lr(l)&&o.set(l.getKey(),l),lr(c)&&o.set(c.getKey(),c)}for(let s of t.getNodes())if(lr(s)&&z4(s))o.set(s.getKey(),s);else if(r===null){let a=HTe(s,z4);lr(a)&&o.set(a.getKey(),a)}for(let[s,a]of o){let l=e();n(a,l),a.replace(l,!0),i&&(s===i.anchor.key&&i.anchor.set(l.getKey(),i.anchor.offset,i.anchor.type),s===i.focus.key&&i.focus.set(l.getKey(),i.focus.offset,i.focus.type))}i&&t.is(gn())&&uE(i)}function idt(t){return t.getNode().isAttached()}function cJt(t){let e=t;for(;e!==null&&!cE(e);){let n=e.getLatest(),r=e.getParent();n.getChildrenSize()===0&&e.remove(!0),e=r}}function uJt(t,e,n=null){let r=t.getStartEndPoints(),o=r?r[0]:null,i=t.getNodes(),s=i.length;if(o!==null&&(s===0||s===1&&o.type==="element"&&o.getNode().getChildrenSize()===0)){let c=o.type==="text"?o.getNode().getParentOrThrow():o.getNode(),u=c.getChildren(),d=e();return d.setFormat(c.getFormatType()),d.setIndent(c.getIndent()),u.forEach(f=>d.append(f)),n&&(d=n.append(d)),void c.replace(d)}let a=null,l=[];for(let c=0;c<s;c++){let u=i[c];cE(u)?(WTe(t,l,l.length,e,n),l=[],a=u):a===null||a!==null&&Tct(u,a)?l.push(u):(WTe(t,l,l.length,e,n),l=[u])}WTe(t,l,l.length,e,n)}function WTe(t,e,n,r,o=null){if(e.length===0)return;let i=e[0],s=new Map,a=[],l=lr(i)?i:i.getParentOrThrow();l.isInline()&&(l=l.getParentOrThrow());let c=!1;for(;l!==null;){let m=l.getPreviousSibling();if(m!==null){l=m,c=!0;break}if(l=l.getParentOrThrow(),cE(l))break}let u=new Set;for(let m=0;m<n;m++){let h=e[m];lr(h)&&h.getChildrenSize()===0&&u.add(h.getKey())}let d=new Set;for(let m=0;m<n;m++){let h=e[m],g=h.getParent();if(g!==null&&g.isInline()&&(g=g.getParent()),g!==null&&Pct(h)&&!d.has(h.getKey())){let y=g.getKey();if(s.get(y)===void 0){let w=r();w.setFormat(g.getFormatType()),w.setIndent(g.getIndent()),a.push(w),s.set(y,w),g.getChildren().forEach(v=>{w.append(v),d.add(v.getKey()),lr(v)&&v.getChildrenKeys().forEach(x=>d.add(x))}),cJt(g)}}else if(u.has(h.getKey())){lr(h)||KTe(179);let y=r();y.setFormat(h.getFormatType()),y.setInden
`||u===`\r
`?c.insertParagraph():u===" "?c.insertNodes([wct()]):c.insertText(u)}}}else e.insertRawText(s)}function oIe(t,e,n){t.dispatchCommand(sut,{nodes:e,selection:n})||(n.insertNodes(e),function(r){if(jt(r)&&r.isCollapsed()){let o=r.anchor,i=null,s=r1(o,"previous");if(s)if(Y7(s))i=s.origin;else{let a=xct(s,oS(mr(),"next").getFlipped());for(let l of a){if(Mr(l.origin)){i=l.origin;break}if(lr(l.origin)&&!l.origin.isInline())break}}if(i&&Mr(i)){let a=i.getFormat(),l=i.getStyle();r.format===a&&r.style===l||(r.format=a,r.style=l,r.dirty=!0)}}}(n))}function Wdt(t,e,n,r=[]){let o=e===null||n.isSelected(e),i=lr(n)&&n.excludeFromCopy("html"),s=n;if(e!==null){let c=rS(n);c=Mr(c)&&e!==null?AJ(e,c):c,s=c}let a=lr(s)?s.getChildren():[],l=function(c){let u=c.exportJSON(),d=c.constructor;if(u.type!==d.getType()&&MJ(58,d.name),lr(c)){let f=u.children;Array.isArray(f)||MJ(59,d.name)}return u}(s);if(Mr(s)){let c=s.__text;c.length>0?l.text=c:o=!1}for(let c=0;c<a.length;c++){let u=a[c],d=Wdt(t,e,u,l.children);!o&&lr(n)&&d&&n.extractWithChild(u,e,"clone")&&(o=!0)}if(o&&!i)r.push(l);else if(Array.isArray(l.children))for(let c=0;c<l.children.length;c++){let u=l.children[c];r.push(u)}return o}function Hdt(t,e){let n=[],r=mr().getChildren();for(let o=0;o<r.length;o++)Wdt(t,e,r[o],n);return{namespace:t._config.namespace,nodes:n}}function Kdt(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=Mct(r);Mr(o)&&mdt(o),e.push(o)}return e}var f1=null;async function dXt(t,e,n){if(f1!==null)return!1;if(e!==null)return new Promise((c,u)=>{t.update(()=>{c(zdt(t,e,n))})});let r=t.getRootElement(),o=t._window||window,i=window.document,s=_Te(o);if(r===null||s===null)return!1;let a=i.createElement("span");a.style.cssText="position: fixed; top: -1000px;",a.append(i.createTextNode("#")),r.append(a);let l=new Range;return l.setStart(a,0),l.setEnd(a,1),s.removeAllRanges(),s.addRange(l),new Promise((c,u)=>{let d=t.registerCommand(X7,f=>(eV(f,ClipboardEvent)&&(d(),f1!==null&&(window.clearTimeout(f1),f1=null),c(zdt(t,f,n))),!0),J7);f1=window.setTimeout(()=>{d(),f1=null,c(!1)},50),i.execCommand("copy"),a.remove()})}function zdt(t,e,n){if(n===void 0){let o=_Te(t._window);if(!o)return!1;let i=o.anchorNode,s=o.focusNode;if(i!==null&&s!==null&&!hut(t,i,s))return!1;let a=gn();if(a===null)return!1;n=qdt(a)}e.preventDefault();let r=e.clipboardData;return r!==null&&(Gdt(r,n),!0)}var fXt=[["text/html",jdt],["application/x-lexical-editor",Vdt]];function qdt(t=gn()){let e={"text/plain":t?t.getTextContent():""};if(t){let n=K7();for(let[r,o]of fXt){let i=o(n,t);i!==null&&(e[r]=i)}}return e}function Gdt(t,e){for(let n in e){let r=e[n];r!==void 0&&t.setData(n,r)}}var Dy=iIe,Yjr=Dy.$generateJSONFromSelectedNodes,Zjr=Dy.$generateNodesFromSerializedNodes,Jjr=Dy.$getClipboardDataFromSelection,Ydt=Dy.$getHtmlContent,Xjr=Dy.$getLexicalContent,sIe=Dy.$insertDataTransferForPlainText,Qjr=Dy.$insertDataTransferForRichText,e4r=Dy.$insertGeneratedNodes,t4r=Dy.copyToClipboard,n4r=Dy.setLexicalClipboardDataTransfer;var aIe={};zn(aIe,{registerPlainText:()=>wXt});var p1=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0,pXt=p1&&"documentMode"in document?document.documentMode:null,mXt=!(!p1||!("InputEvent"in window)||pXt)&&"getTargetRanges"in new window.InputEvent("input"),hXt=p1&&/Version\/[\d.]+.*Safari/.test(navigator.userAgent),Zdt=p1&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,gXt=p1&&/^(?=.*Chrome).*/i.test(navigator.userAgent),yXt=p1&&/AppleWebKit\/[\d.]+/.test(navigator.userAgent)&&!gXt;function Jdt(t,e){e.update(()=>{if(t!==null){let n=eV(t,KeyboardEvent)?null:t.clipboardData,r=gn();if(r!==null&&n!=null){t.preventDefault();let o=Ydt(e);o!==null&&n.setData("text/html",o),n.setData("text/plain",r.getTextContent())}}})}function wXt(t){return mx(t.registerCommand(i1,e=>{let n=gn();return!!jt(n)&&(n.deleteCharacter(e),!0)},zo),t.registerCommand(Wct,e=>{let n=gn();return!!jt(n)&&(n.deleteWord(e),!0)},zo),t.registerCommand(Vct,e=>{let n=gn();return!!jt(n)&&(n.deleteLine(e),!0)},zo),t.registerCommand(zct,e=>{let n=gn();if(!jt(n))return!1;if(typeof e=="
`)};function Lft({onWebTabsChange:t,onWebTabsRemoved:e,onActiveWebTabAdded:n,onActiveWebTabRemoved:r}){return hS.default.createElement(hS.default.Fragment,null,hS.default.createElement(Dh,{config:rQt,onChange:t,onRemoved:e}),(n||r)&&hS.default.createElement(oQt,{onActiveWebTabAdded:n,onActiveWebTabRemoved:r}))}function oQt({onActiveWebTabAdded:t,onActiveWebTabRemoved:e}){let n={isPillNode:LTe,extractData:()=>!0,getKey:()=>"active-web-tab"},r=hS.default.useCallback(i=>{i.length>0&&t&&t()},[t]),o=hS.default.useCallback(i=>{i.length>0&&e&&e()},[e]);return hS.default.createElement(Dh,{config:n,onChange:r,onRemoved:o})}var Dft=N(U());function $ft({enableURLPills:t=!1,onImagePaste:e}){let[n]=vr();return Dft.default.useEffect(()=>n.registerCommand(tJ,r=>{let o=r.clipboardData;if(!o)return!1;if(e){let p=o.items;if(p){let m=Array.from(p).filter(h=>h.type.indexOf("image")!==-1);if(m.length>0){r.preventDefault();let g=m.map(y=>y.getAsFile()).filter(y=>y!==null);return g.length>0&&e(g),!0}}}let i=o.getData("text/plain"),s=i.includes("[["),a=t&&i.includes("http"),l=i.includes("@"),c=i.includes("#"),u=i.includes("{")&&i.includes("}");if(!i||!s&&!a&&!l&&!c&&!u)return!1;let d=VJ(i,{includeNotes:!0,includeURLs:t,includeTools:!0,includeCustomTemplates:!0});return d.some(p=>p.type==="note-pill"||p.type==="active-note-pill"||t&&p.type==="url-pill"||p.type==="tool-pill"||p.type==="folder-pill")?(r.preventDefault(),n.update(()=>{let p=gn();if(!jt(p))return;let m=WJ(d);m.length>0&&p.insertNodes(m)}),!0):!1},dx),[n,t,e]),null}var Fft=N(U());function Uft(){let[t]=vr();return Fft.default.useEffect(()=>t.registerCommand(jJ,e=>{let{text:n,options:r={}}=e;return t.update(()=>{mft(n,r)}),!0},zo),[t]),null}var _c=N(U());var Bft=(0,_c.createContext)(void 0);function gS(){let t=(0,_c.useContext)(Bft);if(t===void 0)throw new Error("useChatInput must be used within a ChatInputProvider");return t}function zft({children:t}){let[e,n]=(0,_c.useState)(null),[r,o]=(0,_c.useState)(null),i=(0,_c.useCallback)(u=>{n(u)},[]),s=(0,_c.useCallback)(u=>{o(()=>u)},[]),a=(0,_c.useCallback)((u,d=!1)=>{e&&e.dispatchCommand(jJ,{text:u,options:{enableURLPills:d,insertAtSelection:!0}})},[e]),l=(0,_c.useCallback)(()=>{r&&r()},[r]),c=(0,_c.useMemo)(()=>({insertTextWithPills:a,focusInput:l,registerEditor:i,registerFocusHandler:s}),[a,l,i,s]);return _c.default.createElement(Bft.Provider,{value:c},t)}Kt();ye();Qi();Se();var iQt=({value:t,onChange:e,onSubmit:n,placeholder:r="Type a message...",disabled:o=!1,className:i="",onNotesChange:s,onNotesRemoved:a,onURLsChange:l,onURLsRemoved:c,onToolsChange:u,onToolsRemoved:d,onFoldersChange:f,onFoldersRemoved:p,onActiveNoteAdded:m,onActiveNoteRemoved:h,onWebTabsChange:g,onWebTabsRemoved:y,onActiveWebTabAdded:w,onActiveWebTabRemoved:v,onEditorReady:x,onImagePaste:b,onTagSelected:_,isCopilotPlus:T=!1,currentActiveFile:S=null,currentChain:P})=>{let[A,O]=Nr.default.useState(null),[D,$]=Nr.default.useState(null),B=gS(),W=Ht(),F=Nr.default.useCallback(te=>{O(()=>te)},[]);(0,Nr.useEffect)(()=>{D&&B.registerEditor(D)},[D,B]),(0,Nr.useEffect)(()=>{A&&B.registerFocusHandler(A)},[A,B]);let Z=Nr.default.useMemo(()=>({namespace:"ChatEditor",theme:{root:"tw-outline-none",paragraph:"tw-m-0"},nodes:[aS,cS,mE,fx,px,uS,...l?[pE]:[]],onError:te=>{z("Lexical error:",te)},editable:!o}),[l,o]),V=(0,Nr.useCallback)(te=>{te.read(()=>{let me=mr().getTextContent();e(me)})},[e]),H=(0,Nr.useCallback)(te=>{$(te),x?.(te)},[x]);return Nr.default.createElement(TJ,{initialConfig:Z},Nr.default.createElement(wJ,{currentActiveFile:S},Nr.default.createElement("div",{className:oe("tw-relative",i)},Nr.default.createElement(OJ,{contentEditable:Nr.default.createElement(RJ,{className:"tw-max-h-40 tw-min-h-[60px] tw-w-full tw-resize-none tw-overflow-y-auto tw-rounded-md tw-border-none tw-bg-transparent tw-px-2 tw-text-sm tw-text-normal tw-outline-none focus-visible:tw-ring-0","aria-label":"Chat input"}),placeholder:Nr.default.createElement("div",{className:"tw-pointer-events-none tw-absolute tw-left-2 tw-top-0 tw-select-none tw-text-sm tw-text-muted/60"},r),ErrorBoundary:zJ}),Nr.de
\u2026 (truncated ${(n.length-nV).toLocaleString()} characters for display)`:n}catch{return e.length>nV?`Tool '${t}' returned ${e.length.toLocaleString()} characters. The full output is preserved in chat history but omitted here to keep the UI responsive.`:e}},hpt=({toolName:t,displayName:e,emoji:n,isExecuting:r,result:o,confirmationMessage:i,onAccept:s,onReject:a})=>{let[l,c]=(0,jo.useState)(!1),u=(0,jo.useMemo)(()=>IQt(t,o),[t,o]),d=r&&!o,f=!d&&u!==null;return jo.default.createElement(cs,{open:f?l:!1,onOpenChange:c,disabled:!f,"aria-disabled":!f,className:"tw-my-3 tw-w-full sm:tw-max-w-sm"},jo.default.createElement("div",{className:oe("tw-rounded-md tw-border tw-border-border tw-bg-secondary/50",d&&"tw-relative tw-overflow-hidden")},d&&jo.default.createElement("div",{className:"tw-absolute tw-inset-0 tw-z-[1] tw-overflow-hidden"},jo.default.createElement("div",{className:"tw-absolute tw-inset-0 -tw-translate-x-full",style:{background:"linear-gradient(90deg, transparent 0%, rgba(255, 255, 255, 0.3) 50%, transparent 100%)",animation:TQt}})),jo.default.createElement(hu,{className:oe("tw-flex tw-w-full tw-items-center tw-justify-between tw-px-3 tw-py-2.5 tw-text-sm sm:tw-px-4 sm:tw-py-3",f&&"hover:tw-bg-secondary/70",!f&&"tw-cursor-default")},jo.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},jo.default.createElement("span",{className:"tw-text-base"},n),jo.default.createElement("span",{className:"tw-font-medium"},t==="readNote"?`${d?"Reading":"Read"} ${e}`:`${d?"Calling":"Called"} ${e}`,d&&t!=="readNote"&&"..."),d&&i&&jo.default.createElement("span",{className:"tw-text-xs tw-text-muted"},"\u2022 ",i,"...")),jo.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},!d&&s&&a&&jo.default.createElement(jo.default.Fragment,null,jo.default.createElement("button",{type:"button",onClick:p=>{p.stopPropagation(),s()},className:"hover:tw-bg-green-rgb/20 tw-rounded tw-p-1",title:"Accept"},jo.default.createElement(Ro,{className:"tw-size-4 tw-text-success"})),jo.default.createElement("button",{type:"button",onClick:p=>{p.stopPropagation(),a()},className:"hover:tw-bg-red-rgb/20 tw-rounded tw-p-1",title:"Reject"},jo.default.createElement(Sn,{className:"tw-size-4 tw-text-error"}))),f&&jo.default.createElement(Di,{className:oe("tw-size-4 tw-text-muted tw-transition-transform",l&&"tw-rotate-90")}))),jo.default.createElement(us,null,jo.default.createElement("div",{className:"tw-border-t tw-border-border tw-px-3 tw-py-2.5 sm:tw-px-4 sm:tw-py-3"},jo.default.createElement("div",{className:"tw-text-sm tw-text-muted"},jo.default.createElement("pre",{className:"tw-overflow-x-auto tw-whitespace-pre-wrap tw-font-mono tw-text-xs"},u??"No result available"))))))};ye();ws();var gpt=60*60*1e3,x1=()=>(window.__copilotToolCallRoots||(window.__copilotToolCallRoots=new Map),window.__copilotToolCallRoots),b1=()=>(window.__copilotErrorBlocks||(window.__copilotErrorBlocks=new Map),window.__copilotErrorBlocks),LIe=(t,e,n)=>{if(e.size>0)return;n.get(t)===e&&n.delete(t)},DIe=(t,e,n,r,o,i)=>{try{r.root.unmount()}catch(s){ee(`Error unmounting tool call root during ${o}`,n,s)}r.isUnmounting=!1,e.get(n)===r&&e.delete(n),LIe(t,e,i)},ypt=(t,e,n,r,o,i)=>{e.delete(n),r.isUnmounting=!0,window.setTimeout(()=>{try{r.root.unmount()}catch(s){ee(`Error unmounting tool call root during ${o}`,n,s)}r.isUnmounting=!1,LIe(t,e,i)},0)},wS=(t,e,n,r,o,i)=>{r.isUnmounting||(r.isUnmounting=!0,window.setTimeout(()=>{let s=i.get(t),a=s?.get(n);if(!s||a!==r){r.isUnmounting=!1,LIe(t,e,i);return}DIe(t,s,n,a,o,i)},0))},wpt=(t,e,n,r,o,i)=>{let s=n.get(r);return s?.isUnmounting&&(DIe(e,n,r,s,`${i} (finalizing stale root)`,x1()),s=void 0),s&&s.container&&s.container!==o&&(ypt(e,n,r,s,`${i} (container changed)`,x1()),s=void 0),s||(s={root:sr(o,t),isUnmounting:!1,container:o},n.set(r,s)),s},vpt=(t,e,n,r,o,i)=>{let s=n.get(r);return s?.isUnmounting&&(DIe(e,n,r,s,`${i} (finalizing stale error root)`,b1()),s=void 0),s&&s.container&&s.container!==o&&(ypt(e,n,r,s,`${i} (container changed)`,b1()),s=void 0),s||(s={root:sr(o,t),isUnmounting:!1,container:o},n.s
`,rt=(ke,Ln,He)=>`<details id="${He}"${Ln} style="${re}"><summary style="${ae}">${K}</summary><div class="tw-text-muted" style="${ve}">${nt(ke)}</div></details>
`;if(n&&R.includes(Te)){let ke=new RegExp(`<${L}>([\\s\\S]*?)<\\/${L}>`,"g");R=R.replace(ke,(He,Ie)=>{let dt=`${L}-${Ee}`;Ee+=1;let Me=$Ie(h.current,dt),Ue=v.get(Me)?" open":"";return rt(Ie,Ue,Me)});let Ln=new RegExp(`<${L}>([\\s\\S]*)$`);return R=R.replace(Ln,(He,Ie)=>`<div style="${re}"><div style="${ae}">${Y}</div><div class="tw-text-muted" style="${ve}">${nt(Ie)}</div></div>`),R}let Jt=new RegExp(`<${L}>([\\s\\S]*?)<\\/${L}>`,"g");return R.replace(Jt,(ke,Ln)=>{let He=`${L}-${Ee}`;Ee+=1;let Ie=$Ie(h.current,He),dt=v.get(Ie)?" open":"";return rt(Ln,dt,Ie)})},Z=R=>F(R,"think","Thought for a while","Thinking..."),V=R=>{let L=ae=>ae.replace(/<(\/?)writeToFile>/g,"<$1writeFile>"),K=ae=>{let ve=/```(?:xml)?\s*([\s\S]*?<writeFile>[\s\S]*?<\/writeFile>[\s\S]*?)\s*```/g;return ae.replace(ve,(Te,Ee)=>Ee.trim())},Y=ae=>{if(!n)return ae;let ve=/```xml\s*([\s\S]*?<writeFile>[\s\S]*?)$/g;return ae.replace(ve,(Te,Ee)=>Ee.trim())},re=L(R);return re=K(re),re=Y(re),F(re,"writeFile","Generated new content","Generating changes...")},H=(R,L,K)=>R.split(/(```[\s\S]*?```|`[^`]*`)/g).map((re,ae)=>ae%2===0?re.replace(L,(ve,Te)=>{let Ee=e.metadataCache.getFirstLinkpathDest(Te,W);return Ee?K(Ee):ve}):re).join(""),te=oL($),fe=H(te,/!\[\[(.*?)]]/g,R=>`![](${e.vault.getResourcePath(R)})`),me=Z(fe),j=V(me),J=j9e(j,x.enableInlineCitations).replace(/\[\^(\d+)\](?!:)/g,'<span class="copilot-citation-ref">[$1]</span>'),M=H(J,/(?<!!)\[\[([^\]]+)]]/g,R=>`<a href="obsidian://open?file=${encodeURIComponent(R.path)}">${R.basename}</a>`);return(R=>{if(!n)return R;let L=/!\[([^\]]*)\]\(([^)]+)\)/g;return R.replace(L,(K,Y,re)=>{let ae=Ute(re);if(!ae)return K;let ve=Y||"YouTube Video",Te=`https://i.ytimg.com/vi/${ae}/hqdefault.jpg`;return`[![${ve}](${Te})](${re})`})})(M)},[e,n,x.enableInlineCitations,v]);(0,mt.useEffect)(()=>{let $=f.current;if(!$||t.sender===uo||!n)return;let B=Z=>{if(Z instanceof PointerEvent&&(Z.button!==0||!Z.isPrimary))return;let V=uX(Z,$);if(!V||!FIe(Z,V))return;let H=!V.open;V.open=H,v.set(V.id,H)},W=Z=>{let V=uX(Z,$);!V||!FIe(Z,V)||Z.preventDefault()},F=Z=>{let V=uX(Z,$);V&&v.set(V.id,V.open)};return $.addEventListener("pointerdown",B,!0),$.addEventListener("click",W,!0),$.addEventListener("toggle",F,!0),()=>{$.removeEventListener("pointerdown",B,!0),$.removeEventListener("click",W,!0),$.removeEventListener("toggle",F,!0)}},[n,t.sender,v]),(0,mt.useEffect)(()=>{if(m.current=!1,f.current&&t.sender!==uo){p.current||(p.current=new xE.Component,p.current.load()),Npt(f.current,v,{overwriteExisting:!n});let $=t.message,B=u?.contentAfter??$,W=_(B),F=gye(W,h.current);if(!m.current){let Z=f.current.doc,V=new Set,H=new Set;f.current.querySelectorAll('[id^="tool-call-"]').forEach(M=>{let E=M.id.replace("tool-call-","");V.add(E)}),f.current.querySelectorAll('[id^="error-block-"]').forEach(M=>{let E=M.id.replace("error-block-","");H.add(E)}),f.current.querySelectorAll(".message-segment").forEach(M=>M.remove());let j=0;F.segments.forEach(M=>{if(M.type==="text"&&M.content.trim()){let E=f.current.children[j],R=Z.createElement("div");R.className="message-segment",E?f.current.insertBefore(R,E):f.current.appendChild(R),xE.MarkdownRenderer.renderMarkdown(M.content,R,"",p.current).then(()=>MQt(R)).catch(L=>z("renderMarkdown failed",L)),j++}else if(M.type==="toolCall"&&M.toolCall){let E=M.toolCall.id,R=Z.getElementById(`tool-call-${E}`);if(!R){let K=f.current.children[j],Y=Z.createElement("div");Y.className="tool-call-container",Y.id=`tool-call-${E}`,K?f.current.insertBefore(Y,K):f.current.appendChild(Y),R=Y}let L=wpt(e,h.current,g.current,E,R,"render refresh");!m.current&&!L.isUnmounting&&xpt(L,M.toolCall),j++}else if(M.type==="error"&&M.error){let E=M.error.id,R=Z.getElementById(`error-block-${E}`);if(!R){let K=f.current.children[j],Y=Z.createElement("div");Y.className="error-block-container",Y.id=`error-block-${E}`,K?f.current.insertBefore(Y,K):f.current.appendChild(Y),R=Y}let L=vpt(e,h.current,y.current,E,R,"error render");!m.current&&!L.isUnmounting&&bpt(L,M.error),j++}});let G=new Set(F.segments.filter(M=>M.type==="toolCall"&&M.toolCall).map(M=>M.tool
Use 'Refresh Vault Index' or 'Force Reindex Vault' commands to build the index after enabling. Pick your embedding model below.`:`Disabling semantic search will fall back to index-free lexical search (less resource-intensive, could be less accurate).
Your existing index will be preserved but not used.`,i=r?"Enable Semantic Search":"Disable Semantic Search",s=r?"Enable":"Disable";super(e,n,o,i,s,"Cancel")}};yp();ye();RN();yp();rD();var Rpt=require("obsidian");function Lpt(t,e=20){let n=app.metadataCache.getFileCache(t),r=[];if(n?.links)for(let o of n.links){let i=app.metadataCache.getFirstLinkpathDest(o.link,t.path);if(i&&(r.push(i),r.length>=e))break}if(n?.embeds&&r.length<e)for(let o of n.embeds){let i=app.metadataCache.getFirstLinkpathDest(o.link,t.path);if(i&&(r.push(i),r.length>=e))break}return[...new Set(r)]}function Dpt(t,e=20){let n=[],r=app.metadataCache.getBacklinksForFile(t);if(r?.data)for(let[o]of r.data){let i=app.vault.getAbstractFileByPath(o);if(i instanceof Rpt.TFile&&(n.push(i),n.length>=e))break}return n}aG();ei();Se();var jIe=require("obsidian"),fX=20,$pt=.7,dX=.3;function LQt(){return Fa(q())}function DQt(t,e){let n=new Map;for(let r of t){let o=r.document.path,i=n.get(o);i?r.score>i&&n.set(o,r.score):n.set(o,r.score)}return n.delete(e),n}function Upt(t){if(t.size<=fX)return t;let e=Array.from(t.entries()).sort((n,r)=>r[1]-n[1]).slice(0,fX);return new Map(e)}function $Qt(t){return Array.isArray(t.embedding)&&t.embedding.length>0}function FQt(t){return t.some(e=>e.content.trim().length>0)}async function UQt({db:t,filePath:e,currentNoteEmbeddings:n}){let r=n.map(a=>IC.getDocsByEmbedding(t,a,{limit:fX,similarity:0})),i=(await Promise.all(r)).flat(),s=DQt(i,e);return Upt(s)}async function Fpt(t){let e=q(),n=new wp,r=Jg(app),o=Uq(app,t);try{let i=await n.resolveBaseUrl(Jm(e)),s=await n.searchRelated(i,o,{folderName:r,limit:fX}),a=new Map,l=s.results||[];for(let c of l){let u=i0(app,c.path);if(u===t||typeof c.score!="number"||Number.isNaN(c.score))continue;let d=a.get(u);(d===void 0||c.score>d)&&a.set(u,c.score)}if(e.debug){let c=l[0]?.path,u=c?i0(app,c):void 0;k(`RelevantNotes(Miyo): file_path=${o} folder_name=${r} received ${l.length} chunks, collected ${a.size} note scores (sample response.path=${c??"n/a"} \u2192 stripped=${u??"n/a"})`)}return Upt(a)}catch(i){return z(`RelevantNotes(Miyo): searchRelated failed for file_path=${o} folder_name=${r}: ${i.message}`),new Map}}async function BQt(t){if(LQt())return Fpt(t);let e=await Cp.getInstance().getDocumentsByPath(t);if(e.length===0)return new Map;let n=e.filter(r=>$Qt(r)).map(r=>r.embedding);if(n.length>0)try{let r=await Cp.getInstance().getDb();return UQt({db:r,filePath:t,currentNoteEmbeddings:n})}catch(r){return ee("RelevantNotes(Orama): failed to compute similarity scores",r),new Map}return FQt(e)?Fpt(t):new Map}function zQt(t){let e=new Map,r=Lpt(t).map(s=>s.path);for(let s of r)e.set(s,{links:!0,backlinks:!1});let i=Dpt(t).map(s=>s.path);for(let s of i)e.has(s)?e.set(s,{links:!0,backlinks:!0}):e.set(s,{links:!1,backlinks:!0});return e}function jQt(t,e){let n=new Map,r=$pt+dX;for(let[o,i]of t)n.set(o,i*$pt/r);for(let[o,i]of e){let s=0;i.links&&i.backlinks?s=dX:(i.links||i.backlinks)&&(s=dX*.8),n.set(o,(n.get(o)??0)+s)}return n}async function Bpt({filePath:t}){let e=app.vault.getAbstractFileByPath(t);if(!(e instanceof jIe.TFile))return[];let n=await BQt(t),r=zQt(e),o=jQt(n,r);return Array.from(o.entries()).sort((s,a)=>{let l=s[0],c=a[0],u=pX(n.get(l)??0),d=pX(n.get(c)??0);return u!==d?d-u:a[1]-s[1]}).map(([s,a])=>{let l=app.vault.getAbstractFileByPath(s);return!(l instanceof jIe.TFile)||l.extension!=="md"?null:{note:{path:s,title:l.basename},metadata:{score:a,similarityScore:n.get(s),hasOutgoingLinks:r.get(s)?.links??!1,hasBacklinks:r.get(s)?.backlinks??!1}}}).filter(s=>s!==null)}function pX(t){return t>.7?3:t>.55?2:1}Gge();vt();var bE=require("obsidian"),Ye=N(U());function VQt(t){let[e,n]=(0,Ye.useState)([]),[r,o]=(0,Ye.useState)(0),i=BIe();return(0,Ye.useEffect)(()=>qge(()=>o(s=>s+1)),[]),(0,Ye.useEffect)(()=>{async function s(){if(i?.path)try{let a=await Bpt({filePath:i.path});n(a)}catch(a){ee("Failed to fetch relevant notes",a),n([])}}s()},[i?.path,t,r]),e}function WQt(t,e){let[n,r]=(0,Ye.useState)(!0),[o,i]=(0,Ye.useState)(0);return(0,Ye.useEffect)(()=>qge(()=>i(s=>s+1)),[]),(0,Ye.useEffect)(()
- a positive number
- less than the value passed to \`max\` (or ${c0e} if no \`max\` prop is set)
- \`null\` or \`undefined\` if the progress is indeterminate.
Defaulting to \`null\`.`}var u0e=$mt,zmt=Umt;Kt();var IE=dV.forwardRef(({className:t,value:e,...n},r)=>dV.createElement(u0e,{ref:r,className:oe("tw-relative tw-h-2 tw-w-full tw-overflow-hidden tw-rounded-full tw-bg-interactive-accent/20 tw-border-interactive-accent/30",t),...n},dV.createElement(zmt,{className:"tw-size-full tw-flex-1 tw-bg-interactive-accent tw-transition-all",style:{transform:`translateX(-${100-Math.min(Math.max(e||0,0),100)}%)`}})));IE.displayName=u0e.displayName;vt();var Ze=N(U());function Zen({status:t,contentEmpty:e}){if(t==="ready"&&e)return Ze.default.createElement(Uf,{className:"tw-size-3.5 tw-text-warning"});switch(t){case"ready":return Ze.default.createElement(vm,{className:"tw-size-3.5 tw-text-success"});case"processing":return Ze.default.createElement(Pr,{className:"tw-size-3.5 tw-animate-spin tw-text-loading"});case"failed":return Ze.default.createElement(Fs,{className:"tw-size-3.5 tw-text-error"});case"pending":return Ze.default.createElement(jA,{className:"tw-size-3.5 tw-text-muted"});case"unsupported":return Ze.default.createElement(Uf,{className:"tw-size-3.5 tw-text-muted"})}}function Jen({fileType:t}){switch(t){case"pdf":return Ze.default.createElement(Ur,{className:"tw-size-3.5 tw-text-error"});case"image":return Ze.default.createElement(qS,{className:"tw-size-3.5 tw-text-accent"});case"web":case"youtube":return Ze.default.createElement(Br,{className:"tw-size-3.5 tw-text-accent"});case"audio":return Ze.default.createElement(GS,{className:"tw-size-3.5 tw-text-warning"});default:return Ze.default.createElement(Ur,{className:"tw-size-3.5 tw-text-muted"})}}function Xen(t){return{ready:t.filter(e=>e.status==="ready").length,processing:t.filter(e=>e.status==="processing").length,failed:t.filter(e=>e.status==="failed").length,pending:t.filter(e=>e.status==="pending").length,unsupported:t.filter(e=>e.status==="unsupported").length,total:t.length}}function Qen(t,e){if(t==="ready"&&e)return"No content";switch(t){case"ready":return"Converted";case"processing":return"Converting...";case"failed":return"Failed";case"pending":return"Queued";case"unsupported":return"Unsupported"}}var jmt={processing:0,failed:1,pending:2,unsupported:3,ready:4};function Vmt(t){return[...t].sort((e,n)=>(jmt[e.status]??99)-(jmt[n.status]??99))}function kX({items:t,onRetry:e,onOpenCachedItem:n,onRemoveUrl:r,defaultExpanded:o=!1,maxHeight:i,showHeader:s=!0}){let[a,l]=(0,Ze.useState)(o),c=Xen(t),u=Vmt(t.filter(f=>f.source==="file")),d=Vmt(t.filter(f=>f.source==="url"));return Ze.default.createElement("div",{className:"tw-space-y-2"},s&&Ze.default.createElement("div",{className:"tw-space-y-1"},Ze.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Ze.default.createElement("h4",{className:"tw-text-sm tw-font-medium tw-text-normal"},"Content Conversion")),Ze.default.createElement("p",{className:"tw-text-ui-smaller tw-text-muted"},"Non-markdown files (PDF, images, web pages, ...) are converted to text for AI.")),t.length===0&&Ze.default.createElement("div",{className:"tw-rounded-lg tw-border tw-border-border tw-p-3 tw-bg-muted/10"},Ze.default.createElement("div",{className:"tw-text-ui-smaller tw-text-muted"},"No non-markdown files or URLs need conversion for this project.")),t.length>0&&Ze.default.createElement("div",{className:"tw-rounded-lg tw-border tw-border-border"},Ze.default.createElement(cs,{open:a,onOpenChange:l},Ze.default.createElement(hu,{asChild:!0},Ze.default.createElement(X,{variant:"secondary",className:" tw-flex tw-h-auto tw-w-full tw-items-center tw-justify-between tw-rounded-lg tw-p-3 tw-text-left tw-transition-colors hover:tw-bg-modifier-hover"},Ze.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Ze.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},c.ready>0&&Ze.default.createElement(ro,{variant:"secondary",className:"tw-h-5 tw-gap-1 tw-bg-success tw-px-1.5 tw-text-ui-smaller tw-text-success"},Ze.default.createElement(vm,{className:"tw-size-3"}),c.ready),c.processing>0&&Ze.default.createElement(ro,{variant:"secondary",className:"tw-h-
`);for(let l of a){let c=l.trim();if(!c)continue;let u=etn(s,c);n.has(u)||(n.add(u),r.push({id:u,url:c,type:s}))}};return o(t,"web"),o(e,"youtube"),r}function NX(t){let e=new Set,n=new Set,r=[],o=[];for(let i of t){let s=i.url.trim();if(s)if(i.type==="youtube"){if(n.has(s))continue;n.add(s),o.push(s)}else{if(e.has(s))continue;e.add(s),r.push(s)}}return{webUrls:r.join(`
`),youtubeUrls:o.join(`
`)}}function d0e(t){let e=t.trim();if(!e)return!1;try{let n=new URL(e.startsWith("http://")||e.startsWith("https://")?e:`https://${e}`);if(n.protocol!=="http:"&&n.protocol!=="https:"||n.username)return!1;let r=n.hostname.toLowerCase();return r?!!(r==="localhost"||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(r)||r.startsWith("[")&&r.endsWith("]")||r.includes(".")):!1}catch{return!1}}var ttn=new Set(["jpg","jpeg","png","gif","bmp","webp","svg","tiff"]),ntn=new Set(["mp3","wav","m4a","ogg","flac","aac","mp4","mpeg","mpga","webm"]);function qmt(t){let e=t.split(".").pop()?.toLowerCase()??"";return e==="pdf"?"pdf":ttn.has(e)?"image":ntn.has(e)?"audio":"other"}function rtn(t){return MX(t)}function OX(t){if(t.startsWith("http://")||t.startsWith("https://"))try{let n=new URL(t),r=n.hostname.replace("www.",""),o=n.pathname+n.search;if(o&&o!=="/"){let s=o.length>30?o.slice(0,30)+"...":o;return r+s}return r}catch{return t.slice(0,50)}let e=t.split("/");return e[e.length-1]||t}function Gmt(t){return t?[...new Set(t.split(`
`).map(e=>e.trim()).filter(Boolean))]:[]}function f0e(t,e,n,r){if(e.has(t))return{status:"processing"};if(n.has(t)){let o=n.get(t);return{status:"failed",error:o.error,failedItem:o}}return r.has(t)?{status:"ready"}:{status:"pending"}}function Ymt(t,e,n){if(!n)return!1;if(e==="youtube"){let o=n.youtubeContexts?.[t];return!o||o.trim().length===0}let r=n.webContexts?.[t];return!r||r.trim().length===0}function p0e(t,e,n,r){if(!r)return"pending";if(e&&n){if(n==="youtube"){let s=r.youtubeContexts?.[t];return s&&s.trim().length>0?"ready":"pending"}let i=r.webContexts?.[t];return i&&i.trim().length>0?"ready":"pending"}return r.fileContexts?.[t]?.cacheKey?"ready":"pending"}function Zmt(t){let{project:e,isCurrentProject:n,liveState:r,projectCache:o,projectFiles:i,supportedExtensions:s}=t,a=new Set(r.success),l=new Set(r.processingFiles),c=new Map;for(let p of r.failed)c.set(p.path,p);let u=[],d=new Map,f=new Set;for(let p of i){if(p.extension==="md")continue;let m=p.path;if(f.has(m))continue;f.add(m);let h=p.extension.toLowerCase();if(!s.has(h)){u.push({id:m,name:OX(m),source:"file",fileType:qmt(m),status:"unsupported",cacheKind:"file"});continue}let g,y;if(n){let w=f0e(m,l,c,a);g=w.status,y=w.error,w.failedItem&&d.set(m,w.failedItem)}else g=p0e(m,!1,null,o);u.push({id:m,name:OX(m),source:"file",fileType:qmt(m),status:g,error:y,cacheKind:"file"})}for(let p of Gmt(e.contextSource?.webUrls)){if(f.has(p))continue;f.add(p);let m=rtn(p),h,g,y;if(n){let w=f0e(p,l,c,a);h=w.status,g=w.error,w.failedItem&&d.set(p,w.failedItem),h==="ready"&&(y=Ymt(p,"web",o)||void 0)}else h=p0e(p,!0,"web",o);u.push({id:p,name:OX(p),source:"url",fileType:m,status:h,error:g,contentEmpty:y,cacheKind:"web"})}for(let p of Gmt(e.contextSource?.youtubeUrls)){if(f.has(p))continue;f.add(p);let m="youtube",h,g,y;if(n){let w=f0e(p,l,c,a);h=w.status,g=w.error,w.failedItem&&d.set(p,w.failedItem),h==="ready"&&(y=Ymt(p,"youtube",o)||void 0)}else h=p0e(p,!0,"youtube",o);u.push({id:p,name:OX(p),source:"url",fileType:m,status:h,error:g,contentEmpty:y,cacheKind:"youtube"})}return{items:u,failedItemMap:n?d:new Map}}bi();fc();var Uh=N(U());function RX(t){let e=tr(),{cacheProject:n,contextSource:r}=t,[o,i]=(0,Uh.useState)(void 0),[s]=Yx(),a=n?.id;(0,Uh.useEffect)(()=>{i(void 0)},[a]),(0,Uh.useEffect)(()=>{if(!n){i(void 0);return}let g=!0;return ti.getInstance().get(n).then(y=>{g&&i(y)}),()=>{g=!1}},[n,s]);let l=!!n&&n.id===br()?.id,c=r?.inclusions??n?.contextSource?.inclusions,u=r?.exclusions??n?.contextSource?.exclusions,[d,f]=(0,Uh.useState)([]);(0,Uh.useEffect)(()=>{if(!n){f([]);return}let{inclusions:g,exclusions:y}=Bo({inclusions:c,exclusions:u,isProject:!0});f(e.vault.getFiles().filter(w=>Qr(w,g,y,!0)))},[e,n,c,u]);let p=(0,Uh.useMemo)(()=>iy.getProjectSupportedExtensions(),[]),m=(0,Uh.useMemo)(()=>n?r?{...n,contextSource:r}:n:null,[n,r]);return{processingData:(0,Uh.useMemo)(()=>!m||o===void 0&&!l?null:Zmt({project:m,isCurrentProject:l,liveState:s,projectCache:o,projectFiles:d,supportedExtensions:p}),[m,l,s,o,d,p]),projectCache:o,isCurrentProject:l}}rn();var N1=N(U());Kt();function fV({value:t,onChange:e,min:n,max:r,step:o,disabled:i,className:s,suffix:a}){let[l,c]=(0,N1.useState)(null),u=l??t;return N1.default.createElement("div",{className:oe("tw-flex tw-items-center tw-gap-4",s)},N1.default.createElement(u4,{value:[u],onValueChange:([d])=>c(d),onValueCommit:([d])=>{c(null),e?.(d)},min:n,max:r,step:o,disabled:i,className:"tw-flex-1"}),N1.default.createElement("div",{className:"tw-min-w-[60px] tw-text-right tw-text-sm tw-tabular-nums"},u>=1e3?`${u%1e3===0?u/1e3:(u/1e3).toFixed(1)}k`:u,a))}rn();vt();var rr=N(U());function otn(){return Math.random().toString(36).substring(2,9)}function Qmt({urls:t,onAdd:e,onRemove:n}){let[r,o]=(0,rr.useState)(""),[i,s]=(0,rr.useState)(!1),a=(0,rr.useRef)(null),l=new Set(t.map(h=>h.url.trim())),c=h=>{let g=h.split(/[\n\s]+/).map(w=>w.trim()).filter(w=>w.length>0&&d0e(w));if(g.length===0)return;let y=[];for(let w of g){let v=w.startsWith("http")?w:`https://${w}`;l.has(v)||(l.add(v),y.push({id:otn(),url:v,type:MX(w)}))}y.length>0&&e(y),o("")},
`)||g.split(/\s+/).filter(d0e).length>1)&&(h.preventDefault(),c(g))},f=async()=>{try{let h=await navigator.clipboard.readText();h&&c(h)}catch{}},p=t.filter(h=>h.type==="web"),m=t.filter(h=>h.type==="youtube");return rr.default.createElement("div",{className:"tw-space-y-3"},rr.default.createElement("div",{className:"tw-flex tw-gap-2"},rr.default.createElement("div",{className:`tw-flex tw-min-h-[40px] tw-flex-1 tw-items-center tw-rounded-md tw-border tw-border-border tw-px-3 tw-transition-colors ${i?"tw-border-interactive-accent tw-ring-1 tw-ring-ring":""}`,onClick:()=>a.current?.focus()},rr.default.createElement(_$,{className:"tw-mr-2 tw-size-4 tw-text-muted"}),rr.default.createElement("input",{ref:a,type:"text",value:r,onChange:h=>o(h.target.value),onKeyDown:u,onPaste:d,onFocus:()=>s(!0),onBlur:()=>s(!1),className:"tw-flex-1 tw-bg-transparent tw-text-sm tw-text-normal tw-outline-none placeholder:tw-text-muted",placeholder:"Enter URL and press Enter..."})),rr.default.createElement(X,{variant:"secondary",onClick:f,title:"Paste from clipboard",className:"tw-px-2"},rr.default.createElement(KS,{className:"tw-size-4"}))),t.length>0&&rr.default.createElement("div",{className:"tw-divide-y tw-divide-border tw-rounded-md tw-border tw-border-border"},p.length>0&&rr.default.createElement("div",{className:"tw-p-2"},rr.default.createElement("div",{className:"tw-mb-2 tw-flex tw-items-center tw-gap-1.5 tw-px-1"},rr.default.createElement(Br,{className:"tw-size-3.5 tw-text-accent"}),rr.default.createElement("span",{className:"tw-text-ui-smaller tw-font-medium tw-text-muted"},"Web (",p.length,")")),rr.default.createElement(Jmt,{maxHeight:"120px"},[...p].reverse().map(h=>rr.default.createElement(Xmt,{key:h.id,url:h,onRemove:n})))),m.length>0&&rr.default.createElement("div",{className:"tw-p-2"},rr.default.createElement("div",{className:"tw-mb-2 tw-flex tw-items-center tw-gap-1.5 tw-px-1"},rr.default.createElement(Br,{className:"tw-size-3.5 tw-text-accent"}),rr.default.createElement("span",{className:"tw-text-ui-smaller tw-font-medium tw-text-muted"},"YouTube (",m.length,")")),rr.default.createElement(Jmt,{maxHeight:"120px"},[...m].reverse().map(h=>rr.default.createElement(Xmt,{key:h.id,url:h,onRemove:n}))))),t.length===0&&rr.default.createElement("p",{className:"tw-text-ui-smaller tw-text-muted"},"Add web pages or YouTube videos. Supports batch paste (one URL per line)."))}function Jmt({maxHeight:t,children:e}){let n=(0,rr.useRef)(null),[r,o]=(0,rr.useState)(!1),i=(0,rr.useCallback)(a=>{n.current=a,a&&o(a.scrollHeight>a.clientHeight)},[]),s=(0,rr.useCallback)(()=>{let a=n.current;if(!a)return;let l=a.scrollHeight-a.scrollTop-a.clientHeight<4;o(!l)},[]);return rr.default.createElement("div",{className:"tw-relative"},rr.default.createElement("div",{ref:i,className:"tw-space-y-1 tw-overflow-y-auto",style:{maxHeight:t},onScroll:s},e),r&&rr.default.createElement("div",{className:"copilot-fade-mask-bottom tw-pointer-events-none tw-absolute tw-inset-x-0 tw-bottom-0 tw-h-8 tw-rounded-b-md"}))}function Xmt({url:t,onRemove:e}){return rr.default.createElement("div",{className:"tw-group tw-flex tw-items-center tw-justify-between tw-rounded tw-px-2 tw-py-1.5 hover:tw-bg-modifier-hover"},rr.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-flex-1 tw-items-center tw-gap-2"},rr.default.createElement(Br,{className:"tw-size-3.5 tw-shrink-0 tw-text-accent"}),rr.default.createElement(go,{className:"tw-text-sm tw-text-normal",tooltipContent:t.url},t.url.replace(/^https?:\/\//,""))),rr.default.createElement(X,{type:"button",variant:"ghost2",size:"fit",onClick:()=>e(t.id),className:"tw-rounded tw-p-1 tw-opacity-0 tw-transition-opacity hover:tw-bg-modifier-hover group-hover:tw-opacity-100",title:"Remove"},rr.default.createElement(Sn,{className:"tw-size-3.5 tw-text-muted"})))}It();var ur=N(U());vt();rn();Kt();fc();var itn={folder:{icon:es,colorClass:"tw-text-context-manager-yellow"},tag:{icon:_m,colorClass:"tw-text-context-manager-orange"},note:{icon:Ur,colorClass:"tw-text-context-manager-blue"},extension:{icon:cg,colorClass:"tw-text-context-manager-gre
`)}};try{await Xu.getInstance().updateProject(p.id,D)}catch($){z(`Error removing URL from project: ${$}`)}},T=S=>{yX(r,h,S)};return En.createElement(wx,{className:"tw-w-full tw-border tw-border-solid tw-border-border tw-bg-transparent tw-shadow-none"},En.createElement(vx,null,En.createElement(CE,{className:"tw-flex tw-items-center tw-justify-between tw-gap-2"},En.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},En.createElement(Ur,{className:"tw-size-5"}),"Context Loading",En.createElement(X,{size:"sm",variant:"ghost2",className:"tw-size-6 tw-p-0 tw-text-muted",title:"Edit Context",onClick:()=>n?.()},En.createElement(Di,{className:"tw-size-4"}),En.createElement("span",{className:"tw-sr-only"},"Edit Context"))),En.createElement("div",{className:"tw-flex tw-items-center tw-gap-2 tw-rounded tw-p-1"},En.createElement(X,{size:"sm",variant:"ghost2",className:"tw-size-6 tw-p-0 tw-text-muted",title:"Close Progress Bar",onClick:()=>e(!0)},En.createElement(Sn,{className:"tw-size-4"}))))),En.createElement(xx,{className:"tw-space-y-4"},En.createElement("div",{className:"tw-space-y-2"},En.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-text-sm"},En.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},En.createElement("span",{className:"tw-text-muted"},"Total progress"),En.createElement("span",{className:"tw-text-xs tw-text-muted"},"(Success:"," ",En.createElement("span",{className:"tw-font-medium tw-text-success"},l.length),", Failed: ",En.createElement("span",{className:"tw-font-medium tw-text-error"},c.length),")")),En.createElement("span",{className:"tw-font-medium"},d,"/",a.length," (",f,"%)")),En.createElement(IE,{value:f,className:"tw-h-2"})),v&&En.createElement(cs,{open:o,onOpenChange:i},En.createElement(hu,{asChild:!0},En.createElement(X,{variant:"secondary",className:"tw-flex tw-h-auto tw-w-full tw-items-center tw-justify-between tw-rounded-md tw-p-2 tw-text-left tw-transition-colors hover:tw-bg-modifier-hover"},En.createElement("span",{className:"tw-text-ui-smaller tw-text-muted"},"View Details"),o?En.createElement(hr,{className:"tw-size-4 tw-text-muted"}):En.createElement(Di,{className:"tw-size-4 tw-text-muted"}))),En.createElement(us,null,En.createElement("div",{className:"tw-mt-2 tw-space-y-3"},m&&m.items.length>0&&En.createElement(kX,{items:m.items,onRetry:x,onOpenCachedItem:h!=null?T:void 0,onRemoveUrl:_,defaultExpanded:!0,maxHeight:"200px"}),w&&En.createElement("div",{className:"tw-space-y-1.5"},En.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5 tw-px-1"},En.createElement(Ur,{className:"tw-size-3.5 tw-text-muted"}),En.createElement("span",{className:"tw-text-ui-smaller tw-font-medium tw-text-muted"},"Markdown Files"),g.length>0&&En.createElement(ro,{variant:"secondary",className:"tw-h-4 tw-gap-0.5 tw-px-1 tw-text-[10px]"},En.createElement(Pr,{className:"tw-size-2.5 tw-animate-spin"}),g.length),y.length>0&&En.createElement(ro,{variant:"secondary",className:"tw-h-4 tw-gap-0.5 tw-bg-error tw-px-1 tw-text-[10px] tw-text-error"},En.createElement(Fs,{className:"tw-size-2.5"}),y.length)),g.map(S=>En.createElement("div",{key:`md-proc-${S}`,className:"tw-flex tw-items-center tw-gap-2 tw-rounded-md tw-border tw-border-border tw-bg-primary tw-p-2"},En.createElement(Pr,{className:"tw-size-3.5 tw-animate-spin tw-text-loading"}),En.createElement(go,{className:"tw-flex-1 tw-text-ui-smaller tw-text-normal",title:S},S))),y.map(S=>En.createElement("div",{key:`md-fail-${S.path}`,className:"tw-rounded-md tw-border tw-border-border tw-bg-primary tw-p-2"},En.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},En.createElement(Fs,{className:"tw-size-3.5 tw-shrink-0 tw-text-error"}),En.createElement(go,{className:"tw-flex-1 tw-text-ui-smaller tw-text-normal",title:S.path},S.path),En.createElement(X,{size:"sm",variant:"ghost",className:"tw-h-5 tw-shrink-0 tw-px-1.5 tw-text-ui-smaller",title:"Retry",onClick:()=>b(S)},En.createElement(zf,{className:"tw-mr-1 tw-size-3"}),"Retry")),S.error&&En.createElement(go,{className:"tw-mt-1 tw-pl-5.5 tw-text-ui-
`).filter(o=>o.trim()),r=[];for(let o of n){let i=dtn(t,o.trim());i&&r.push(i)}return r}function sht(t){let{app:e,contextNotes:n,setContextNotes:r,selectedImages:o,onAddImage:i,containerRef:s}=t,[a,l]=(0,$X.useState)(!1);return(0,$X.useEffect)(()=>{let c=s.current;if(!c)return;let u=m=>{if(m.preventDefault(),m.dataTransfer){if(m.dataTransfer.dropEffect="copy",m.dataTransfer.types.includes("copilot/internal-drag"))return;let h=Array.from(m.dataTransfer.items).some(y=>y.kind==="string"),g=Array.from(m.dataTransfer.items).some(y=>y.kind==="file");(h||g)&&l(!0)}},d=m=>{let h=c.getBoundingClientRect(),g=m.clientX,y=m.clientY;(g<h.left||g>=h.right||y<h.top||y>=h.bottom)&&l(!1)},f=async m=>{if(!m.dataTransfer)return;m.preventDefault(),l(!1);let h=m.dataTransfer.items,g=[],y=[];for(let w=0;w<h.length;w++){let v=h[w];v.kind==="string"?g.push(v):v.kind==="file"&&y.push(v)}if(g.length>0){m.stopPropagation();let w=g.map(b=>new Promise(_=>{b.getAsString(T=>_(T))})),v=await Promise.all(w),x=new Map;for(let b of v){let _=ftn(e,b);for(let T of _)x.set(T.path,T)}for(let b of x.values())if(["png","gif","jpeg","jpg","webp"].includes(b.extension)){if(o.some(O=>O.name===b.name)){new PE.Notice("This image is already in the context");continue}let S=await e.vault.readBinary(b),P=new Blob([S]),A=new File([P],b.name,{type:`image/${b.extension}`});i([A])}else if(tg(b)){if(n.some(S=>S.path===b.path)){new PE.Notice("This note is already in the context");continue}r(S=>[...S,b])}else new PE.Notice(`Unsupported file type: ${b.extension}. Supported types: md, pdf, canvas, and images.`)}else if(y.length>0){let w=[];for(let v of y){let x=v.getAsFile();x&&x.type.startsWith("image/")&&w.push(x)}w.length>0&&i(w)}},p=m=>{f(m)};return c.addEventListener("dragover",u),c.addEventListener("dragleave",d),c.addEventListener("drop",p),()=>{c.removeEventListener("dragover",u),c.removeEventListener("dragleave",d),c.removeEventListener("drop",p)}},[e,n,o,i,r,s]),{isDragActive:a}}It();qe();ye();qh();var y0e=async(t,e,n,r,o,i={})=>{let s=new AbortController;o(s);try{await e.runChain(t,s,r,n,i)}catch(a){z("Model request failed:",a);let l=IG("Model request failed: "+Xt(a));n({id:si(),sender:Sd,isErrorMessage:!0,message:l,isVisible:!0,timestamp:ll(new Date)})}};HS();ns();Se();qe();pG();var ds=require("obsidian");var tt=N(U());qh();var ptn=({chainManager:t,onSaveChat:e,updateUserMessageHistory:n,fileParserManager:r,plugin:o,chatUIState:i,chatInput:s})=>{let a=Ht(),l=L5e(),c=(0,tt.useContext)(qA),{messages:u,addMessage:d}=iht(i),[f]=qx(),[p]=kd(),[m,h]=(0,tt.useState)(""),[g,y]=(0,tt.useState)(""),w=(0,tt.useRef)(null),v=(0,tt.useRef)(null),x=(0,tt.useCallback)(ge=>{let ht=v.current,Ef=ht&&ge.sender===Sd&&!ge.isErrorMessage&&!ge.id?{...ge,id:ht}:ge;d(Ef)},[d]),b=(0,tt.useCallback)(ge=>{w.current=ge},[]),[_,T]=(0,tt.useState)(!1),[S,P]=(0,tt.useState)(Td.DEFAULT),[A,O]=(0,tt.useState)([]),[D,$]=(0,tt.useState)(a.autoAddActiveContentToContext===!0&&p!=="project"),[B,W]=(0,tt.useState)(a.autoAddActiveContentToContext===!0&&p!=="project"),[F,Z]=(0,tt.useState)([]),[V,H]=(0,tt.useState)(!1),[te,fe]=(0,tt.useState)([]),[me,j]=(0,tt.useState)(null),[G,J]=(0,tt.useState)(null),[M]=DA(),E=(0,tt.useRef)(!1),R=(0,tt.useRef)(null),L=(0,tt.useCallback)(()=>{o.chatSelectionHighlightController.persistFromPointerDown()},[o]),K=(0,tt.useMemo)(()=>({setCurrentAiMessage:ge=>E.current&&h(ge),setLoadingMessage:ge=>E.current&&P(ge),setLoading:ge=>E.current&&T(ge)}),[]),[Y]=nke(),re=Y.length>0,ae=D&&!re,ve=B&&!re,{activeWebTabForMentions:Te}=iS(),Ee=_Z(),nt=()=>oo!=="project"?!1:me!==null?me:Ee==="loading"||Ee==="error",[rt,Jt]=(0,tt.useState)(Ee);rt!==Ee&&(Jt(Ee),j(null));let ke=()=>oo==="project"||G===!1?!1:M.isActive||M.completionStatus!=="none",[Ln,He]=(0,tt.useState)({isActive:M.isActive,completionStatus:M.completionStatus});(Ln.isActive!==M.isActive||Ln.completionStatus!==M.completionStatus)&&(He({isActive:M.isActive,completionStatus:M.completionStatus}),(M.isActive||M.completionStatus!=="none")&&J(null));let Ie=(0,tt.useCallback)(()=>{J(!1),M.isActive||ul({completionStatus:"none"})},[M.isAc
`));let rwt={notes:nwt,urls:Mc(p)?ht||[]:[],tags:Ef||[],folders:HQ||[],selectedTextContexts:Y,webTabs:GE||[]};y(""),Z([]),v.current=`msg-${si()}`,K.setLoading(!0),K.setLoadingMessage(Td.DEFAULT);let owt=await i.sendMessage(nPe,rwt,p,ae,ve,YE.length>0?YE:void 0,K.setLoadingMessage);g&&n(g),a.autosaveChat&&await zl();let rPe=i.getLLMMessage(owt);rPe&&await y0e(rPe,t,x,K.setCurrentAiMessage,b,{debug:a.debug,updateLoadingMessage:K.setLoadingMessage}),a.autosaveChat&&await zl()}catch(YE){z("Error sending message:",YE),new ds.Notice("Failed to send message. Please try again.")}finally{K.setLoading(!1),K.setLoadingMessage(Td.DEFAULT),v.current=null}},zl=(0,tt.useCallback)(async()=>{if(!Zi){z("App instance is not available.");return}try{await i.saveChat(f)}catch(ge){z("Error saving chat as note:",Xt(ge)),new ds.Notice("Failed to save chat as note. Check console for details.")}},[Zi,i,f]),zy=(0,tt.useCallback)(ge=>{w.current&&(k(`stopping generation..., reason: ${ge}`),w.current.abort(ge),K.setLoading(!1),K.setLoadingMessage(Td.DEFAULT))},[K]);(0,tt.useEffect)(()=>(E.current=!0,()=>{E.current=!1,w.current&&w.current.abort("component-unmount")}),[]);let eD=(0,tt.useCallback)(async ge=>{if(ge<=0){new ds.Notice("Cannot regenerate the first message.");return}let ht=u[ge];if(!ht){new ds.Notice("Message not found.");return}K.setCurrentAiMessage(""),v.current=`msg-${si()}`,K.setLoading(!0);try{await i.regenerateMessage(ht.id,K.setCurrentAiMessage,x)?a.debug&&k("Message regenerated successfully"):new ds.Notice("Failed to regenerate message. Please try again."),a.autosaveChat&&await zl()}catch(ir){z("Error regenerating message:",ir),new ds.Notice("Failed to regenerate message. Please try again.")}finally{K.setLoading(!1),v.current=null}},[u,i,a.debug,a.autosaveChat,zl,x,K]),tD=(0,tt.useCallback)(async(ge,ht)=>{let ir=u[ge];if(!(!ir||ir.message===ht))try{if(!await i.editMessage(ir.id,ht,p,ae)){new ds.Notice("Failed to edit message. Please try again.");return}if(ir.sender===uo){let HQ=ge<u.length-1;if(await i.truncateAfterMessageId(ir.id),HQ){v.current=`msg-${si()}`,K.setLoading(!0);try{let GE=i.getLLMMessage(ir.id);GE&&await y0e(GE,t,x,K.setCurrentAiMessage,b,{debug:a.debug,updateLoadingMessage:K.setLoadingMessage})}catch(GE){z("Error regenerating AI response:",GE),new ds.Notice("Failed to regenerate AI response. Please try again.")}finally{K.setLoading(!1),v.current=null}}}a.autosaveChat&&await zl()}catch(Ef){z("Error editing message:",Ef),new ds.Notice("Failed to edit message. Please try again.")}},[u,i,p,ae,x,t,a.debug,a.autosaveChat,zl,K,b]);(0,tt.useEffect)(()=>{e&&e(zl)},[e,zl]);let hs=(0,tt.useCallback)(async ge=>{await Xu.getInstance(o.app).createProject(ge),new ds.Notice(`${ge.name} added successfully`),br()?.id===ge.id&&W_e(o.app)},[o.app]),Ta=(0,tt.useCallback)(async(ge,ht)=>{await Xu.getInstance(o.app).updateProject(ge.id,ht),new ds.Notice(`${ge.name} updated successfully`)},[o.app]),sl=(0,tt.useCallback)(ge=>{let ir=wm().find(Ef=>Ef.id===ge);eke(ge),ir?.sourceType==="web"&&o.suppressCurrentWebSelection(ir.url)},[o]);(0,tt.useEffect)(()=>{o.chatSelectionHighlightController.clearIfNoNoteContexts(Y)},[Y,o]),(0,tt.useEffect)(()=>{let ge=()=>{s.focusInput()};return c?.addEventListener(kf.CHAT_IS_VISIBLE,ge),()=>{c?.removeEventListener(kf.CHAT_IS_VISIBLE,ge)}},[c,s]);let If=(0,tt.useCallback)(async ge=>{let ht=u[ge];if(!ht){new ds.Notice("Message not found.");return}try{await i.deleteMessage(ht.id)||new ds.Notice("Failed to delete message. Please try again.")}catch(ir){z("Error deleting message:",ir),new ds.Notice("Failed to delete message. Please try again.")}},[u,i]),jl=(0,tt.useCallback)(async()=>{if(sO(),await Ds.clear(),zy("new-chat"),a.enableRecentConversations)try{let ht=t.chatModelManager.getChatModel();o.userMemoryManager.addRecentConversation(i.getMessages(),ht)}catch(ht){k("Failed to analyze chat messages for memory:",ht)}a.autosaveChat&&await zl(),i.clearMessages(),Yve(),K.setCurrentAiMessage(""),O([]);let ge=Y.find(ht=>ht.sourceType==="web")?.url;tke(),o.chatSelectionHighlightController.clearForNewChat(),o.suppressCurr
Original name: ${s.title}
${s.content}`}):e.push(s)}await Xs.getInstance().updateCommands([...r.map(s=>({...s,showInSlashMenu:!0})),...e]);let i=`We have upgraded your commands to the new format. They are now also stored as notes in ${h_()}.`;n.length>0&&(await vtn(n),i+=`
We found ${n.length} unsupported commands. They are saved in ${h_()}/unsupported. To fix them, please resolve the errors and move the note file out of the unsupported folder.`),pe("inlineEditCommands",[]),new Cr(app,()=>{},i,"\u{1F680} New Copilot Custom Commands","OK","").open()}async function w0e(){let t=td(),e=zJe.filter(r=>!t.some(o=>o.title===r.title)),n=[...t,...e];await Xs.getInstance().updateCommands(n)}async function yht(){if(q().suggestedDefaultCommands)return;td().length===0&&(new Cr(app,()=>{w0e().catch(n=>z("generateDefaultCommands failed",n))},"Would you like to add Copilot recommended commands in your custom prompts folder? These commands will be available through the right-click context menu and slash commands in chat.","Welcome to Copilot","Confirm","Skip").open(),pe("suggestedDefaultCommands",!0))}Ir();ye();Se();Hx();var O1=require("obsidian"),VX=class{constructor(e){this.folderChangeRequestId=0;this.fileModifyDebouncers=new Map;this.handleSettingsChange=(e,n)=>{e.projectsFolder!==n.projectsFolder&&this.debouncedFolderChange(n.projectsFolder)};this.debouncedFolderChange=Li(e=>{this.handleProjectsFolderChange(e)},1e3,{leading:!1,trailing:!0});this.handleFileCreation=async e=>{if(!(!T0(e)||th(e.path)))try{let n=await E0(e);if(!n)return;let r=ef(n.project.id);if(r&&r.filePath!==n.filePath){ee(`[Projects] Duplicate id="${n.project.id}": existing=${r.filePath}, incoming=${n.filePath}; ignored`);return}await pB(e,n);let o=await E0(e);o&&m0(o)}catch(n){z(`[Projects] Error on file creation: ${e.path}`,n)}};this.handleFileDeletion=async e=>{if(!(!T0(e)||th(e.path))){this.evictFileModifyDebouncer(e.path);try{let n=eO(e.path);AC(e.path),n&&(br()?.id===n.project.id&&new O1.Notice(`Project "${n.project.name}" was deleted.`),await ti.getInstance().clearForProject(n.project).catch(o=>z("[Projects] Failed to clear context cache on external delete",o)),cv().catch(o=>z("[Projects] Rescan after delete failed",o)))}catch(n){z(`[Projects] Error on file deletion: ${e.path}`,n)}}};this.handleFileRename=async(e,n)=>{if(th(e.path)||th(n))return;let r=this.isProjectConfigPathString(n),o=T0(e);if(!(!r&&!o)){r&&this.evictFileModifyDebouncer(n);try{let i=r?eO(n):void 0;if(o){let s=await E0(e);if(!s){r&&AC(n);return}let a=ef(s.project.id);if(a&&a.filePath!==s.filePath&&a.filePath!==n){r&&AC(n),ee(`[Projects] Duplicate id="${s.project.id}" after rename: existing=${a.filePath}, incoming=${s.filePath}; ignored`);return}await pB(e,s);let c=await E0(e);c?r?uye(n,c):m0(c):r&&AC(n)}else r&&AC(n);r&&!o&&i&&(br()?.id===i.project.id&&new O1.Notice(`Project "${i.project.name}" was moved.`),await ti.getInstance().clearForProject(i.project).catch(a=>z("[Projects] Failed to clear context cache on rename-out",a)),cv().catch(a=>z("[Projects] Rescan after rename-out failed",a)))}catch(i){z(`[Projects] Error on file rename: ${n} -> ${e.path}`,i)}}};this.handleFileModify=e=>{!T0(e)||th(e.path)||this.getFileModifyDebouncer(e.path)(e)};this.vault=e.vault,this.manager=Xu.getInstance(e)}async initialize(){this.initializeEventListeners(),await this.manager.initialize()}cleanup(){for(let e of this.fileModifyDebouncers.values())e.cancel();this.fileModifyDebouncers.clear(),this.debouncedFolderChange.cancel(),this.settingsUnsubscriber?.(),this.vault.off("create",this.handleFileCreation),this.vault.off("delete",this.handleFileDeletion),this.vault.off("rename",this.handleFileRename),this.vault.off("modify",this.handleFileModify)}initializeEventListeners(){this.vault.on("create",this.handleFileCreation),this.vault.on("delete",this.handleFileDeletion),this.vault.on("rename",this.handleFileRename),this.vault.on("modify",this.handleFileModify),this.settingsUnsubscriber=Ho(this.handleSettingsChange)}async handleProjectsFolderChange(e){let n=++this.folderChangeRequestId;try{let r=await this.manager.fetchProjects();if(n!==this.folderChangeRequestId)return;for(let a of this.fileModifyDebouncers.values())a.cancel();this.fileModifyDebouncers.clear();let o=Sp(),i=ti.getInstance();await Promise.all(o.map(a=>i.clearForProject(a.project).catch(l=>z("[Projects] Failed to clea
`));return{id:e,label:xht[e],text:o,segments:r,stable:r.every(i=>i.stable),metadata:r.length===1?r[0].metadata:void 0,hash:this.hash(o)}}serializeLayers(e){return e.map(n=>n.text).filter(n=>n.length>0).join(`
`)}collectLayerHashes(e){return e.reduce((n,r)=>(n[r.id]=r.hash,n),{})}hash(e){return p5e(e||"")}normalizeWhitespace(e){return e.replace(/\s+$/g,"").trim()}collectWarnings(e){let n=[];return e.forEach(r=>{if(!r.text)return;r.text.includes("\0")&&n.push(`Layer ${r.id} contains control characters and was normalized`)}),n}};bS.ENVELOPE_VERSION=1;var WX=bS;function xtn(t){let e=/<path>([^<]+)<\/path>/.exec(t);if(e)return e[1];let n=/<url>([^<]+)<\/url>/.exec(t);if(n)return n[1];let r=/<name>([^<]+)<\/name>/.exec(t);return r?r[1]:""}function btn(t,e,n,r={}){let o=r.verbatimThreshold??pf.verbatimThreshold;if(t.length<=o)return t;let i=r.previewCharsPerSection??pf.previewCharsPerSection,s=r.maxSections??pf.maxSections,a=fP(t,i,s);return`<prior_context source="${I9(e)}" type="${n}">
${a}
</prior_context>`}function bht(t,e,n={}){if(!T9(e))return t;let r=n.verbatimThreshold??pf.verbatimThreshold;if(t.length<=r)return t;let o=TR(t,e)||xtn(t),i=uj(t),s=dP(e);return btn(i,o,s,n)}function Cht(){return`<prior_context_note>
The above prior_context blocks contain previews of content from earlier turns.
To access full content: use [[note title]] for notes, or ask to read a specific URL/video.
</prior_context_note>`}function _ht(t,e){if(!t.trim())return[];let n=[],o=[...SR.map(l=>l.tag),"prior_context"],i=new RegExp(`<(${o.join("|")})(\\s[^>]*)?>[\\s\\S]*?</\\1>`,"g"),s=new Map,a;for(;(a=i.exec(t))!==null;){let l=a[0],c=a[1];if(c==="prior_context"){let d=/source="([^"]+)"/.exec(l)?.[1]??"prior_context";n.push({id:d,content:l,stable:e,metadata:{source:"previous_turns_compacted",notePath:d}})}else{let u=TR(l,c),d;if(u)d=u;else{let p=(s.get(c)||0)+1;s.set(c,p),d=p===1?c:`${c}:${p}`}let f=dP(c)==="note";n.push({id:d,content:l,stable:e,metadata:{source:e?"previous_turns":"current_turn",...f?{notePath:d}:{}}})}}return n}Ir();It();ye();FP();aL();qe();fL();var xV=require("obsidian");It();var HX=class t{constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}async processEmbeddedPDFs(e,n,r){let o=/!\[\[(.*?\.pdf)\]\]/g,i=[...e.matchAll(o)];for(let s of i){let a=s[1],l=n.getAbstractFileByPath(a);if(l instanceof xV.TFile)try{let c=await r.parseFile(l,n);e=e.replace(s[0],`
<${sD}>
<name>${a}</name>
<content>
${c}
</content>
</${sD}>
`)}catch(c){z(`Error processing embedded PDF ${a}:`,c),e=e.replace(s[0],`
<${sD}>
<name>${a}</name>
<error>Could not process PDF</error>
</${sD}>
`)}}return e}async processDataviewBlocks(e,n){let r=app.plugins?.plugins?.dataview;if(!r)return e;let o=r.api;if(!o)return e;let i=/```(dataview|dataviewjs)\s*\n([\s\S]*?)```/g,s=[...e.matchAll(i)];for(let a=s.length-1;a>=0;a--){let l=s[a],c=l[1],u=l[2].trim(),d=l.index,f=d+l[0].length;try{let p=await Promise.race([this.executeDataviewQuery(o,u,c,n),new Promise((g,y)=>window.setTimeout(()=>y(new Error("Query timeout")),5e3))]),m=typeof p=="string"?p:JSON.stringify(p),h=`
<${aD}>
<query_type>${c}</query_type>
<original_query>
${u}
</original_query>
<executed_result>
${m}
</executed_result>
</${aD}>
`;e=e.slice(0,d)+h+e.slice(f)}catch(p){z("Error executing Dataview query:",p);let m=`
<${aD}>
<query_type>${c}</query_type>
<original_query>
${u}
</original_query>
<error>${p instanceof Error?p.message:"Query execution failed"}</error>
</${aD}>
`;e=e.slice(0,d)+m+e.slice(f)}}return e}async executeDataviewQuery(e,n,r,o){if(r==="dataviewjs")return"[DataviewJS execution not yet supported - showing original query]";let i=await e.query(n,o);if(!i.successful)throw new Error(i.error??"Query failed");return this.formatDataviewResult(i.value)}formatDataviewResult(e){return e?e.type==="list"?this.formatDataviewList(e.values):e.type==="table"?this.formatDataviewTable(e.headers??[],e.values):e.type==="task"?this.formatDataviewTasks(e.values):Array.isArray(e)?e.map(n=>this.formatDataviewValue(n)).join(`
`):JSON.stringify(e):"No results"}formatDataviewList(e){return!e||e.length===0?"No results":e.map(n=>`- ${this.formatDataviewValue(n)}`).join(`
`)}formatDataviewTable(e,n){if(!n||n.length===0)return"No results";let r=`| ${e.join(" | ")} |
`;r+=`| ${e.map(()=>"---").join(" | ")} |
`;for(let o of n)r+=`| ${o.map(i=>this.formatDataviewValue(i)).join(" | ")} |
`;return r}formatDataviewTasks(e){return!e||e.length===0?"No results":e.map(n=>`- ${n.completed?"[x]":"[ ]"} ${this.formatDataviewValue(n.text??n)}`).join(`
`)}formatDataviewValue(e){return e==null?"":e&&typeof e=="object"&&"path"in e?`[[${e.path}]]`:Array.isArray(e)?e.map(n=>this.formatDataviewValue(n)).join(", "):typeof e=="object"?JSON.stringify(e):`${e}`}async buildMarkdownContextContent(e,n,r,o){let i=await r.parseFile(e,n);return i=await this.processEmbeddedNotes(i,e,n,r,o),Mc(o)&&(i=await this.processEmbeddedPDFs(i,n,r)),await this.processDataviewBlocks(i,e.path)}async processEmbeddedNotes(e,n,r,o,i){let s=/!\[\[([^\]]+)\]\]/g,a,l=0,c="";for(;(a=s.exec(e))!==null;){c+=e.slice(l,a.index);let u=a[1].trim(),d=await this.buildEmbeddedNoteBlock(u,a[0],n,r,o,i);c+=d,l=a.index+a[0].length}return c+=e.slice(l),c}async buildEmbeddedNoteBlock(e,n,r,o,i,s){let a=this.parseEmbeddedLinkTarget(e);if(!a)return n;let l=a.path===null?r:app.metadataCache.getFirstLinkpathDest(a.path,r.path);if(!(l instanceof xV.TFile))return this.formatEmbeddedNoteBlock({title:a.path??r.basename,path:a.path??r.path,heading:a.heading,blockId:a.blockId,error:"Embedded note not found"});if(l.extension!=="md")return n;try{let c=await i.parseFile(l,o);if(a.heading||a.blockId){let u=this.extractMarkdownSegment(l,c,a);if(!u.found){let d=a.blockId?`block reference "${a.blockId}"`:`heading "${a.heading??""}"`;throw new Error(`Embedded note ${d} not found in ${l.path}`)}c=u.content}return Mc(s)&&(c=await this.processEmbeddedPDFs(c,o,i)),c=await this.processDataviewBlocks(c,l.path),this.formatEmbeddedNoteBlock({title:l.basename,path:l.path,heading:a.heading,blockId:a.blockId,content:c})}catch(c){ee("Failed to process embedded note",c);let u=c instanceof Error?c.message:"Could not process embedded note";return this.formatEmbeddedNoteBlock({title:l.basename,path:l.path,heading:a.heading,blockId:a.blockId,error:u})}}parseEmbeddedLinkTarget(e){if(!e)return null;let n=e.indexOf("|"),o=(n>=0?e.slice(0,n):e).trim();if(!o)return{path:null};let i,s,a=o.indexOf("#^");a!==-1&&(i=o.slice(a+2).trim(),o=o.slice(0,a));let l=o.indexOf("#");return l!==-1&&(s=o.slice(l+1).trim(),o=o.slice(0,l)),{path:o.length>0?o:null,heading:s&&s.length>0?s:void 0,blockId:i&&i.length>0?i:void 0}}extractMarkdownSegment(e,n,r){let o=app.metadataCache.getFileCache(e);if(r.blockId){let i=o?.blocks?.[r.blockId],s=i?.position?.start?.offset,a=i?.position?.end?.offset;return s===void 0||a===void 0?{content:"",found:!1}:{content:n.slice(s,a),found:!0}}if(r.heading){let i=o?.headings??[],s=this.normalizeHeadingForMatch(r.heading),a=i.findIndex(d=>this.normalizeHeadingForMatch(d.heading)===s);if(a===-1)return{content:"",found:!1};let l=i[a],c=l.position?.start?.offset??0,u=n.length;for(let d=a+1;d<i.length;d++)if(i[d].level<=l.level){u=i[d].position?.start?.offset??u;break}return{content:n.slice(c,u),found:!0}}return{content:n,found:!0}}normalizeHeadingForMatch(e){return e.trim().toLowerCase().replace(/\s+/g," ")}formatEmbeddedNoteBlock(e){let{title:n,path:r,heading:o,blockId:i,content:s,error:a}=e,l=`
<${tee}>
<title>${n}</title>
<path>${r}</path>`;return o&&(l+=`
<heading>${o}</heading>`),i&&(l+=`
<block_id>${i}</block_id>`),a?l+=`
<error>${a}</error>`:l+=`
<content>
${s??""}
</content>`,l+=`
</${tee}>
`,l}async processContextNotes(e,n,r,o,i,s,a){let l="",c=async(d,f=oD)=>{try{if(e.has(d.path)){k(`Skipping note ${d.path} as it was included via custom prompt.`);return}if(!n.supportsExtension(d.extension)){ee(`Unsupported file type: ${d.extension}`);return}if(!Mc(a)&&!FW(d)){ee(`File type ${d.extension} requires Copilot Plus mode for context processing.`),new xV.Notice(XE.NON_MARKDOWN_FILES_RESTRICTED);return}let p=d.extension==="md"?await this.buildMarkdownContextContent(d,r,n,a):await n.parseFile(d,r),m=await r.adapter.stat(d.path),h=m?new Date(m.ctime).toISOString():"Unknown",g=m?new Date(m.mtime).toISOString():"Unknown";l+=`
<${f}>
<title>${Ai(d.basename)}</title>
<path>${d.path}</path>
<ctime>${h}</ctime>
<mtime>${g}</mtime>
<content>
${p}
</content>
</${f}>`}catch(p){z(`Error processing file ${d.path}:`,p),l+=`
<${f}_error>
<title>${Ai(d.basename)}</title>
<path>${d.path}</path>
<error>[Error: Could not process file]</error>
</${f}_error>`}},u=new Set;i&&s&&(await c(s,"active_note"),u.add(s.path));for(let d of o)u.has(d.path)||(await c(d),u.add(d.path));return l}async hasEmbeddedPDFs(e){return/!\[\[(.*?\.pdf)\]\]/g.test(e)}async addNoteToContext(e,n,r,o,i,s){if(r.some(c=>c.path===e.path))return;let a=await n.read(e),l=await this.hasEmbeddedPDFs(a);o&&e.path===o.path&&s(!0),i(c=>[...c,Object.assign(e,{wasAddedViaReference:!0,hasEmbeddedPDFs:l})])}processSelectedTextContexts(){let e=wm();if(!e||e.length===0)return"";let n="";for(let r of e)r.sourceType==="web"?n+=`
<${eee}>
<title>${Ai(r.title)}</title>
<url>${Ai(r.url)}</url>
<content>
${Ai(r.content)}
</content>
</${eee}>`:n+=`
<${bu}>
<title>${Ai(r.noteTitle)}</title>
<path>${Ai(r.notePath)}</path>
<start_line>${r.startLine.toString()}</start_line>
<end_line>${r.endLine.toString()}</end_line>
<content>
${r.content}
</content>
</${bu}>`;return n}async processContextWebTabs(e){if(!e||e.length===0)return"";let n=2500,r=8e3,o=15e3,i=2,s=(w,v)=>{let x=[`
<${w}>`,`
<title>${Ai(v.title)}</title>`,`
<url>${Ai(v.url)}</url>`];return v.mode&&x.push(`
<mode>${Ai(v.mode)}</mode>`),v.error?x.push(`
<error>${Ai(v.error)}</error>`):v.content!==void 0&&x.push(`
<content>
${Ai(v.content)}
</content>`),x.push(`
</${w}>`),x.join("")},a=w=>{let v=[`
<${oee}>`,`
<title>${Ai(w.title)}</title>`,`
<url>${Ai(w.url)}</url>`,`
<video_id>${Ai(w.videoId)}</video_id>`];w.isActive&&v.push(`
<is_active>true</is_active>`),w.channel&&v.push(`
<channel>${Ai(w.channel)}</channel>`),w.uploadDate&&v.push(`
<upload_date>${Ai(w.uploadDate)}</upload_date>`),w.duration&&v.push(`
<duration>${Ai(w.duration)}</duration>`),w.genre&&v.push(`
<genre>${Ai(w.genre)}</genre>`),w.description&&v.push(`
<description>${Ai(w.description)}</description>`),w.error&&v.push(`
<error>${Ai(w.error)}</error>`);let x=w.transcript||"No transcript available for this video";return v.push(`
<content>
${Ai(x)}
</content>`),v.push(`
</${oee}>`),v.join("")},l=null,c=[],u=new Set,d=new Set,f=ls(app),p=w=>{let v=f.getYouTubeVideoId(w);return v?d.has(v)?!0:(d.add(v),!1):u.has(w)?!0:(u.add(w),!1)};for(let w of e){let v=wc(w.url);v&&w.isActive&&!l&&(l={...w,url:v},p(v))}for(let w of e){let v=wc(w.url);!v||p(v)||c.push({...w,url:v})}if(!l&&c.length===0)return"";let m=f.getAvailability();if(!m.supported||!m.available){let w=m.reason??(m.supported?"Web Viewer is not available.":"Web Viewer is not supported on this platform."),v=[];l&&v.push(s(ZV,{title:l.title||"Unknown",url:l.url,error:w}));for(let x of c)v.push(s(ree,{title:x.title||"Unknown",url:x.url,error:w}));return v.join("")}let h=async(w,v)=>{try{let x=w.url,b=f.getYouTubeVideoId(x);if(b)return await g(w,b,v===ZV);let _=f.findLeafByUrl(x,{title:w.title});if(!_)return s(v,{title:w.title||"Unknown",url:x,error:"Web tab not found or closed"});let T=f.getPageInfo(_),S=_.view;if(!(S.webviewMounted===void 0||S.webviewFirstLoadFinished===void 0?!0:!!(S.webviewMounted&&S.webviewFirstLoadFinished)))try{await f.waitForWebviewReady(_,n),T=f.getPageInfo(_)}catch(D){return ee(`Web tab content not loaded yet for ${x}:`,D),s(v,{title:T.title||w.title||"Untitled",url:T.url||x,mode:T.mode,error:"Web tab content not loaded yet"})}let A=new AbortController,O=window.setTimeout(()=>{A.abort()},r);try{let D=await f.getReaderModeMarkdown(_,{signal:A.signal});return T=f.getPageInfo(_),s(v,{title:T.title||w.title||"Untitled",url:T.url||x,mode:T.mode,content:D})}finally{window.clearTimeout(O)}}catch(x){return z(`Error processing web tab ${w.url}:`,x),s(v,{title:w.title||"Unknown",url:w.url,error:x instanceof M_?"Web tab content extraction timed out":"Could not process web tab"})}},g=async(w,v,x)=>{try{let b=null,_=w.url;for(let O of f.getLeaves()){let D=f.getPageInfo(O).url;if(f.getYouTubeVideoId(D)===v){b=O,_=D;break}}if(!b)return a({title:w.title||"YouTube Video",url:w.url,videoId:v,isActive:x,error:"Web tab not found or closed"});let T=b.view;if(!(T.webviewMounted===void 0||T.webviewFirstLoadFinished===void 0?!0:!!(T.webviewMounted&&T.webviewFirstLoadFinished)))try{await f.waitForWebviewReady(b,n)}catch(O){return ee(`YouTube tab content not loaded yet for ${_}:`,O),a({title:w.title||"YouTube Video",url:_,videoId:v,isActive:x,error:"Web tab content not loaded yet"})}let P=await f.getYouTubeTranscript(b,{timeoutMs:o}),A=P.transcript.length>0?P.transcript.map(O=>`${O.timestamp}: ${O.text}`).join(`
`):void 0;return a({title:P.title||w.title||"YouTube Video",url:_,videoId:P.videoId,channel:P.channel,description:P.description,uploadDate:P.uploadDate,duration:P.duration,genre:P.genre,transcript:A,isActive:x})}catch(b){return ee(`YouTube transcript extraction failed for ${w.url}:`,b),a({title:w.title||"YouTube Video",url:w.url,videoId:v,isActive:x,error:b instanceof Error?b.message:"Failed to extract video info"})}},y=[];if(l){let w=await h(l,ZV);y.push(w)}for(let w=0;w<c.length;w+=i){let v=c.slice(w,w+i),x=await Promise.all(v.map(b=>h(b,ree)));y.push(...x)}return y.join("")}};ye();Se();qe();var x0e=null;async function Ctn(){return x0e||(x0e=(await Promise.resolve().then(()=>(Tht(),Sht))).ContextCompactor),x0e.getInstance()}var KX=class t{constructor(){this.contextProcessor=HX.getInstance(),this.mention=tO.getInstance(),this.promptContextEngine=WX.getInstance()}static getInstance(){return t.instance||(t.instance=new t),t.instance}async processMessageContext(e,n,r,o,i,s,a,l,c=[],u){try{k(`[ContextManager] Processing context for message ${e.id}`);let d=e.originalMessage||e.message,{processedPrompt:f,includedFiles:p}=await Ij(d,"",r,s),{l2Context:m,l2Paths:h}=this.buildL2ContextFromPreviousTurns(e.id,a),g=e.context?.urls||[],y=o==="copilot_plus"?await this.mention.processUrlList(g):{urlContext:"",imageUrls:[]},w=new Set([...p.map(G=>G.path),...c.map(G=>G.path),...h]),v=new Set,b=(e.context?.notes||[]).filter(G=>!h.has(G.path));i&&o!=="project"&&s&&!w.has(s.path)&&!b.some(G=>G.path===s.path)&&b.push(s);let _=await this.contextProcessor.processContextNotes(w,n,r,b,i,s,o);b.forEach(G=>{w.add(G.path),v.add(G.path)});let T=e.context?.tags||[],S="",P=[];if(T.length>0){let J=$W(r,T).filter(M=>!w.has(M.path));J.length>0&&(S=await this.contextProcessor.processContextNotes(new Set,n,r,J,!1,null,o),J.forEach(M=>{w.add(M.path),v.add(M.path),P.push(M.path)}))}let A=e.context?.folders||[],O="",D=[];if(A.length>0){let J=A.flatMap(M=>JD(r,M)).filter(M=>!w.has(M.path));J.length>0&&(O=await this.contextProcessor.processContextNotes(new Set,n,r,J,!1,null,o),J.forEach(M=>{w.add(M.path),v.add(M.path),D.push(M.path)}))}let $=this.contextProcessor.processSelectedTextContexts(),B=e.context?.webTabs||[],W=await this.contextProcessor.processContextWebTabs(B),F=m+_+S+O+y.urlContext+$+W,Z=f+F,te=(o==="project"?1e6:q().autoCompactThreshold)*4,fe=!1,me=F;if(Z.length>te){u?.(Td.COMPACTING);let J=await(await Ctn()).compact(F);J.wasCompacted&&(me=J.content,Z=f+me,fe=!0,k(`[ContextManager] Compacted context: ${J.originalCharCount} -> ${J.compactedCharCount} chars`)),u?.(Td.DEFAULT)}k(`[ContextManager] Successfully processed context for message ${e.id}`);let j=fe?this.buildCompactedEnvelope({chainType:o,message:e,systemPrompt:l||"",processedUserMessage:f,compactedContext:me,compactedPaths:Array.from(v)}):this.buildPromptContextEnvelope({chainType:o,message:e,systemPrompt:l||"",processedUserMessage:f,l2PreviousContext:m,noteContextAddition:_,tagContextAddition:S,tagNotePaths:P,folderContextAddition:O,folderNotePaths:D,urlContext:y.urlContext,selectedText:$,webTabContext:W});return{processedContent:Z,contextEnvelope:j}}catch(d){return k(`[ContextManager] Error processing context for message ${e.id}:`,d),{processedContent:e.originalMessage||e.message,contextEnvelope:void 0}}}async reprocessMessageContext(e,n,r,o,i,s,a,l,c=[]){let u=n.getMessage(e);if(!u||u.sender!=="user"||!u.id)return;k(`[ContextManager] Reprocessing context for message ${e}`);let{processedContent:d,contextEnvelope:f}=await this.processMessageContext(u,r,o,i,s,a,n,l,c);n.updateProcessedText(u.id,d,f),k(`[ContextManager] Completed context reprocessing for message ${e}`)}buildL2ContextFromPreviousTurns(e,n){let r=n.getDisplayMessages(),o=r.findIndex(p=>p.id===e);if(o===-1||o===0)return{l2Context:"",l2Paths:new Set};let i=r.slice(0,o).filter(p=>p.sender==="user"),s=new Map,a=[],l=new Set,c=-1;for(let p=i.length-1;p>=0;p--)if(i[p].contextEnvelope?.layers?.find(y=>y.id==="L3_TURN")?.segments?.some(y=>y.metadata?.wasCompacted)){c=p;break}for(let p=0;p<i.length;p++){let h=i[p].contextEnvelope?.lay
`);return{l2Context:/<prior_context\s+source=/.test(u)?u+`
`+Cht():u,l2Paths:l}}buildPromptContextEnvelope(e){let n=e.message.id;if(!n)return;let r={};if(e.systemPrompt&&(r.L1_SYSTEM=[{id:"system",content:e.systemPrompt,stable:!0,metadata:{source:"system_prompt"}}]),e.l2PreviousContext){let i=this.parseContextIntoSegments(e.l2PreviousContext,!0);i.length>0&&(r.L2_PREVIOUS=i)}let o=[];if(e.noteContextAddition){let i=this.parseContextIntoSegments(e.noteContextAddition,!1);o.push(...i)}return this.appendParsedSegments(o,e.tagContextAddition,{source:"tags",notePaths:e.tagNotePaths}),this.appendParsedSegments(o,e.folderContextAddition,{source:"folders",notePaths:e.folderNotePaths}),this.appendParsedSegments(o,e.urlContext),this.appendParsedSegments(o,e.selectedText),this.appendParsedSegments(o,e.webTabContext),o.length>0&&(r.L3_TURN=o),r.L5_USER=[{id:`${n}-user`,content:e.processedUserMessage,stable:!1,metadata:{source:"user_input"}}],this.promptContextEngine.buildEnvelope({conversationId:null,messageId:n,layerSegments:r,metadata:{debugLabel:`message:${n}`,chainType:e.chainType}})}buildCompactedEnvelope(e){let n=e.message.id;if(!n)return;let r={};return e.systemPrompt&&(r.L1_SYSTEM=[{id:"system",content:e.systemPrompt,stable:!0,metadata:{source:"system_prompt"}}]),e.compactedContext.trim()&&(r.L3_TURN=[{id:"compacted_context",content:e.compactedContext,stable:!1,metadata:{source:"compacted",wasCompacted:!0,compactedPaths:e.compactedPaths}}]),r.L5_USER=[{id:`${n}-user`,content:e.processedUserMessage,stable:!1,metadata:{source:"user_input"}}],this.promptContextEngine.buildEnvelope({conversationId:null,messageId:n,layerSegments:r,metadata:{debugLabel:`message:${n}:compacted`,chainType:e.chainType}})}parseContextIntoSegments(e,n){return _ht(e,n)}appendParsedSegments(e,n,r){let o=(n||"").trim();if(!o)return;let i=this.parseContextIntoSegments(o,!1);if(i.length>0)for(let s of i)r&&(s.metadata={...s.metadata,...r}),e.push(s);else e.push({id:`unparsed-${Date.now()}`,content:o,stable:!1,metadata:{source:"unparsed",...r}})}createMessageContext(e,n,r=wm()){return{notes:e,urls:n,selectedTextContexts:r}}async extractContextNotes(e,n,r=[]){return[...Df(e,n),...r].filter((a,l,c)=>c.findIndex(u=>u.path===a.path)===l)}needsContextReprocessing(e){return e.needsContextReprocessing===!0}getSelectedTextContexts(){return wm()}compactSegmentForL2(e){let n=[...SR.map(i=>i.tag),"prior_context","prior_context_note"].join("|"),r=new RegExp(`<(${n})(\\s[^>]*)?>[\\s\\S]*?</\\1>`,"g");return e.replace(r,(i,s)=>{let a=SR.find(l=>l.tag===s);return a&&!a.recoverable||s==="prior_context_note"?"":s==="prior_context"?i:a?bht(i,s):i}).trim()}};qe();ye();var R1=class{constructor(){this.messages=[]}generateId(){return`msg-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}addMessage(e,n,r,o,i){if(typeof e=="object"){let u=e,d=u.id||this.generateId(),f=u.timestamp||ll(new Date),p={id:d,displayText:u.message,processedText:u.originalMessage||u.message,sender:u.sender,timestamp:f,context:u.context,contextEnvelope:u.contextEnvelope,isVisible:u.isVisible!==!1,isErrorMessage:u.isErrorMessage,sources:u.sources,content:u.content,responseMetadata:u.responseMetadata};return this.messages.push(p),k(`[MessageRepository] Added message with ID: ${d}`),d}if(n===void 0||r===void 0)throw new Error("processedText and sender are required when using string-based addMessage");let s=e,a=this.generateId(),l=ll(new Date),c={id:a,displayText:s,processedText:n,sender:r,timestamp:l,context:o,contextEnvelope:void 0,isVisible:!0,isErrorMessage:!1,content:i};return this.messages.push(c),k(`[MessageRepository] Added message with ID: ${a}`),a}editMessage(e,n){let r=this.messages.find(o=>o.id===e);return r?r.displayText===n?(k(`[MessageRepository] No changes needed for message: ${e}`),!0):(r.displayText=n,r.sender==="user"||r.sender==="USER"?k(`[MessageRepository] Edited user message ${e}, needs context reprocessing`):(r.processedText=n,k(`[MessageRepository] Edited AI message ${e}`)),!0):(k(`[MessageRepository] Message not found for edit: ${e}`),!1)}updateProcessedText(e,n,r){let o=this.messages.find(i=>i.id===e);return o?(o.processedText=n,o.cont
[Context: ${s.join(" | ")}]`)}return i+=`
[Timestamp: ${r}]`,i}).join(`
`)}parseChatContent(e){let n=[],r=e.match(/^---\n([\s\S]*?)\n---/),o=e;r&&(o=e.slice(r[0].length).trim());let i=/\*\*(user|ai)\*\*: ([\s\S]*?)(?=(?:\n\*\*(?:user|ai)\*\*: )|$)/g,s;for(;(s=i.exec(o))!==null;){let a=s[1]==="user"?uo:Sd,l=s[2].trim(),c=l.split(`
`),u=l,d="Unknown time",f,p=c.length;if(c[p-1]?.startsWith("[Timestamp: ")){let h=c[p-1].match(/\[Timestamp: (.*?)\]/);h&&(d=h[1],p--)}if(p>0&&c[p-1]?.startsWith("[Context: ")){let h=c[p-1].match(/\[Context: (.*?)\]/);if(h){let g=h[1];f=this.parseContextString(g),p--}}if(u=c.slice(0,p).join(`
`).trim(),a===Sd){u=u.replace(/<!--TOOL_CALL_START:[^:]+:[^:]+:[^:]+:[^:]+:[^:]*:[^:]+-->[\s\S]*?<!--TOOL_CALL_END:[^:]+:[\s\S]*?-->/g,"");let h=tj(u);h&&(u=h.contentAfter),u=u.replace(/\n{3,}/g,`
`).trim()}let m;if(d!=="Unknown time"){let h=new Date(d);isNaN(h.getTime())||(m=h.getTime())}n.push({message:u,sender:a,isVisible:!0,timestamp:m?{epoch:m,display:d,fileName:""}:null,context:f})}return n}parseContextString(e){let n={notes:[],urls:[],tags:[],folders:[],webTabs:[]},r=e.split(" | ");for(let o of r){let i=o.trim();if(i.startsWith("Notes: ")){let s=i.substring(7);s&&(n.notes=s.split(", ").map(a=>{let l=a.trim(),c=this.app.vault.getAbstractFileByPath(l);if(c instanceof ol.TFile)return c;let u=l.includes("/")?l.split("/").pop():l,d=this.app.vault.getMarkdownFiles().filter(f=>f.basename===u);return d.length===1?(k(`[ChatPersistenceManager] Resolved legacy basename "${u}" to ${d[0].path}`),d[0]):(d.length>1?ee(`[ChatPersistenceManager] Ambiguous basename "${u}", skipping. Matches: ${d.map(f=>f.path).join(", ")}`):ee(`[ChatPersistenceManager] Note not found: ${l}`),null)}).filter(a=>a!==null))}else if(i.startsWith("URLs: ")){let s=i.substring(6);s&&(n.urls=s.split(", ").map(a=>a.trim()))}else if(i.startsWith("Web Tabs: ")||i.startsWith("WebTabs: ")){let s=i.startsWith("Web Tabs: ")?i.substring(10):i.substring(9);s&&(n.webTabs=s.split(", ").map(a=>a.trim()).filter(a=>a.length>0).map(a=>({url:a})))}else if(i.startsWith("Tags: ")){let s=i.substring(6);s&&(n.tags=s.split(", ").map(a=>a.trim()))}else if(i.startsWith("Folders: ")){let s=i.substring(9);s&&(n.folders=s.split(", ").map(a=>a.trim()))}}if(n.notes.length>0||n.urls.length>0||(n.tags?.length??0)>0||(n.folders?.length??0)>0||(n.webTabs?.length??0)>0)return n}async findFileByEpoch(e){let n=await this.getChatHistoryFiles();for(let r of n){let o=this.app.metadataCache.getFileCache(r)?.frontmatter?.epoch;if(o===void 0)try{let s=await oy(this.app,r.path);s?.epoch&&(o=Number(s.epoch))}catch{continue}let i=typeof o=="number"?o:typeof o=="string"?Number(o):void 0;if(typeof i=="number"&&!Number.isNaN(i)&&i===e)return r}return null}async generateAITopic(e){if(this.chainManager)try{let n=this.chainManager.chatModelManager.getChatModel();if(!n)return;let r=6,o=200,s=`Generate a concise title (max 5 words) for this conversation based on its content. Return only the title without any explanation or quotes.
Conversation:
${e.reduce((u,d,f)=>f>=r?u:u+(u?`
`:"")+`${d.sender}: ${d.message.slice(0,o)}`,"")}`,a=await n.invoke(s),l=typeof a=="string"?a:a.content??a.text??a;return Kx(l).trim().replace(/^["']|["']$/g,"").replace(/[\\/:*?"<>|]/g,"").slice(0,50)||void 0}catch(n){z("[ChatPersistenceManager] Error generating AI topic:",n);return}}generateFileName(e,n,r,o){let i=q(),a=ll(new Date(r)).fileName,l;if(o)l=o;else{let b=n.find(_=>_.sender===uo);l=b&&b.message.replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/[{}[\]]/g,"").split(/\s+/).slice(0,10).join(" ").replace(/[\\/:*?"<>|\x00-\x1F]/g,"").trim()||"Untitled Chat"}let c=i.defaultConversationNoteName||"{$date}_{$time}__{$topic}",u=e===void 0?br():e,d=u?`${Xc(u.id)}__`:"",f=WS(".md"),p=WS(d),m=c.replace("{$topic}","").replace("{$date}",a.split("_")[0]).replace("{$time}",a.split("_")[1]),h=WS(m),g=Math.max(20,b0e-f-p-h),y=l.replace(/\s+/g,"_"),w=ZD(y,g);c=c.replace("{$topic}",w).replace("{$date}",a.split("_")[0]).replace("{$time}",a.split("_")[1]);let v=c.replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/[{}[\]]/g,"_").replace(/[\\/:*?"<>|\x00-\x1F]/g,"_"),x=`${d}${v}.md`;if(WS(x)>b0e){let b=b0e-f-p,_=ZD(v,b);return`${i.defaultSaveFolder}/${d}${_}.md`}return`${i.defaultSaveFolder}/${x}`}generateNoteContent(e,n,r,o,i){let s=q(),a=br();return`---
epoch: ${n}
modelKey: "${qX(r)}"
${o?`topic: "${qX(o)}"`:""}
${i?`lastAccessedAt: ${i}`:""}
${a?`projectId: "${qX(a.id)}"`:""}
${a?`projectName: "${qX(a.name)}"`:""}
tags:
- ${s.defaultConversationTag}
---
${e}`}generateTopicAsyncIfNeeded(e,n,r,o){!q().generateAIChatTitleOnSave||!n||o||(async()=>{try{let s=await this.generateAITopic(r);if(!s)return;await this.applyTopicToFrontmatter(n,s),await this.renameFileToMatchTopic(e,n,s)}catch(s){z("[ChatPersistenceManager] Error during async topic generation:",s)}})()}async applyTopicToFrontmatter(e,n){try{await LC(this.app,e.path,{topic:n.trim()}),k(`[ChatPersistenceManager] Applied AI topic to chat file: ${e.path}`)}catch(r){z("[ChatPersistenceManager] Error applying AI topic to file:",r)}}errorToMessage(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}isNameTooLongError(e){if(!e)return!1;let n=this.errorToMessage(e).toLowerCase();return n.includes("enametoolong")||n.includes("name too long")}isFileAlreadyExistsError(e){return e?this.errorToMessage(e).toLowerCase().includes("already exists"):!1}async renameFileToMatchTopic(e,n,r){if(!n||!r)return;let o,i=this.app.metadataCache.getFileCache(n);if(i?.frontmatter?.epoch)o=i.frontmatter.epoch;else try{let l=await oy(this.app,n.path);l?.epoch&&(o=Number(l.epoch))}catch{}if(!o)return;let s=this.messageRepo.getDisplayMessages(),a=this.generateFileName(e,s,o,r);n.path!==a&&await this.app.fileManager.renameFile(n,a)}};It();FP();fL();var GX=class{constructor(e,n,r,o){this.messageRepo=e;this.chainManager=n;this.fileParserManager=r;this.plugin=o;this.projectMessageRepos=new Map;this.defaultProjectKey="defaultProjectKey";this.lastKnownProjectId=null;this.contextManager=KX.getInstance(),this.projectMessageRepos.set(this.defaultProjectKey,e),this.persistenceManager=new bV(o.app,e,n)}getCurrentMessageRepo(){let e=this.plugin.projectManager.getCurrentProjectId(),n=e??this.defaultProjectKey;if(this.lastKnownProjectId!==e&&(k(`[ChatManager] Project changed from ${this.lastKnownProjectId} to ${e}`),this.lastKnownProjectId=e),!this.projectMessageRepos.has(n)){k(`[ChatManager] Creating new message repository for project: ${n}`);let o=new R1;this.projectMessageRepos.set(n,o)}let r=this.projectMessageRepos.get(n);return this.persistenceManager=new bV(this.plugin.app,r,this.chainManager),r}setOnMessageCreatedCallback(e){this.onMessageCreatedCallback=e}async processSystemPromptTemplates(e,n,r){if(!e.includes("{")||!e.includes("}"))return{processedPrompt:e,includedFiles:[]};if(!q().enableCustomPromptTemplating)return{processedPrompt:e,includedFiles:[]};try{let i=await Ij(e,"",n,r,!0);return{processedPrompt:i.processedPrompt.trimEnd(),includedFiles:i.includedFiles}}catch(i){return ee("[ChatManager] Error processing system prompt templates:",i),{processedPrompt:e,includedFiles:[]}}}injectProcessedUserCustomPromptIntoSystemPrompt(e){let{systemPromptWithoutMemory:n,userCustomPrompt:r,processedUserCustomPrompt:o}=e,i=/<user_custom_instructions>\n[\s\S]*?\n<\/user_custom_instructions>/;return i.test(n)?n.replace(i,()=>`<user_custom_instructions>
${o}
</user_custom_instructions>`):n===r?o:(k("[ChatManager] Could not locate <user_custom_instructions> block for injection; returning original system prompt."),n)}replaceSystemPromptWithoutMemoryInBasePrompt(e){let{basePromptWithMemory:n,systemPromptWithoutMemory:r,processedSystemPromptWithoutMemory:o}=e;return n.endsWith(r)?`${n.slice(0,n.length-r.length)}${o}`:(k("[ChatManager] basePromptWithMemory does not end with systemPromptWithoutMemory; returning original base prompt."),n)}async getSystemPromptForMessage(e,n,r){let o=K8(),i=[],s=await xv(this.chainManager.userMemoryManager),a=r_(),l=s;if(o){let c=await this.processSystemPromptTemplates(o,n,r),u=this.injectProcessedUserCustomPromptIntoSystemPrompt({systemPromptWithoutMemory:a,userCustomPrompt:o,processedUserCustomPrompt:c.processedPrompt}),d=this.replaceSystemPromptWithoutMemoryInBasePrompt({basePromptWithMemory:s,systemPromptWithoutMemory:a,processedSystemPromptWithoutMemory:u});d!==s&&i.push(...c.includedFiles),l=d}if(e==="project"){let c=br();if(c){let u=await Sl.instance.getProjectContext(c.id),d=await this.processSystemPromptTemplates(c.systemPrompt,n,r);i.push(...d.includedFiles);let f=`${l}
<project_system_prompt>
${d.processedPrompt}
</project_system_prompt>`;if(u){let m=u;u.length>24e5&&(m=u.substring(0,24e5),ee(`Project context truncated from ${Math.round(u.length/4e3)}k to ${Math.round(24e5/4e3)}k estimated tokens to stay within token budget`)),f+=`
<project_context>
${m}
</project_context>`}return{processedPrompt:f,includedFiles:i}}}return{processedPrompt:l,includedFiles:i}}buildWebTabsWithActiveSnapshot(e,n){let r=Grt(e);if(!n)return r;try{let s=ls(this.plugin.app).getActiveWebTabState().activeWebTabForMentions,a=dL(s?.url);if(!a)return r;let l=r.map(u=>{if(u.isActive){let{isActive:d,...f}=u;return f}return u}),c=l.findIndex(u=>dL(u.url)===a);if(c>=0){let u=l[c];return l[c]={...u,url:wc(s?.url)??u.url,title:s?.title??u.title,faviconUrl:s?.faviconUrl??u.faviconUrl,isActive:!0},l}return[...l,{url:wc(s?.url)??a,title:s?.title,faviconUrl:s?.faviconUrl,isActive:!0}]}catch(o){return ee("[ChatManager] Failed to resolve active web tab:",o),r}}async sendMessage(e,n,r,o=!1,i=!1,s,a){try{k(`[ChatManager] Sending message: "${e}"`);let l=this.plugin.app.workspace.getActiveFile(),c={...n};if(o&&l){let v=n.notes||[],x=v.some(b=>b.path===l.path);c.notes=x?v:[...v,l]}let d=!((c.selectedTextContexts||[]).length>0)&&(i||e.includes(lD));c.webTabs=this.buildWebTabsWithActiveSnapshot(c.webTabs||[],d);let f=this.getCurrentMessageRepo(),p=f.addMessage(e,e,uo,c,s);this.onMessageCreatedCallback&&this.onMessageCreatedCallback(p);let m=f.getMessage(p);if(!m)throw new Error(`Failed to retrieve message ${p}`);let{processedPrompt:h,includedFiles:g}=await this.getSystemPromptForMessage(r,this.plugin.app.vault,l),{processedContent:y,contextEnvelope:w}=await this.contextManager.processMessageContext(m,this.fileParserManager,this.plugin.app.vault,r,o,l,f,h,g,a);return f.updateProcessedText(p,y,w),k(`[ChatManager] Successfully sent message ${p}`),p}catch(l){throw k("[ChatManager] Error sending message:",l),l}}async editMessage(e,n,r,o=!1){try{k(`[ChatManager] Editing message ${e}: "${n}"`);let i=this.getCurrentMessageRepo();if(!i.editMessage(e,n))return!1;let a=this.plugin.app.workspace.getActiveFile(),{processedPrompt:l,includedFiles:c}=await this.getSystemPromptForMessage(r,this.plugin.app.vault,a);return await this.contextManager.reprocessMessageContext(e,i,this.fileParserManager,this.plugin.app.vault,r,o,a,l,c),await this.updateChainMemory(),k(`[ChatManager] Successfully edited message ${e}`),!0}catch(i){return k(`[ChatManager] Error editing message ${e}:`,i),!1}}async regenerateMessage(e,n,r,o){try{k(`[ChatManager] Regenerating message ${e}`);let i=this.getCurrentMessageRepo();if(!i.getMessage(e))return k(`[ChatManager] Message not found: ${e}`),!1;let a=i.getDisplayMessages(),l=a.findIndex(f=>f.id===e);if(l<=0)return k("[ChatManager] Cannot regenerate first message or no user message found"),!1;let c=a[l-1];if(c.sender!==uo)return k("[ChatManager] Previous message is not from user"),!1;if(i.truncateAfter(l-1),o&&o(),await this.updateChainMemory(),!c.id)return k("[ChatManager] User message has no ID for regeneration"),!1;let u=i.getLLMMessage(c.id);if(!u)return k("[ChatManager] LLM message not found for regeneration"),!1;if(!u.contextEnvelope){k("[ChatManager] Context envelope missing, reprocessing context for regeneration");let f=ym(),p=this.plugin.app.workspace.getActiveFile(),{processedPrompt:m,includedFiles:h}=await this.getSystemPromptForMessage(f,this.plugin.app.vault,p);await this.contextManager.reprocessMessageContext(c.id,i,this.fileParserManager,this.plugin.app.vault,f,!1,p,m,h),u=i.getLLMMessage(c.id)}let d=new AbortController;return await this.chainManager.runChain(u,d,n,r,{debug:q().debug}),k(`[ChatManager] Successfully regenerated message ${e}`),!0}catch(i){return k(`[ChatManager] Error regenerating message ${e}:`,i),!1}}async deleteMessage(e){try{return k(`[ChatManager] Deleting message ${e}`),this.getCurrentMessageRepo().deleteMessage(e)?(await this.updateChainMemory(),k(`[ChatManager] Successfully deleted message ${e}`),!0):!1}catch(n){return k(`[ChatManager] Error deleting message ${e}:`,n),!1}}addMessage(e){return this.getCurrentMessageRepo().addMessage(e)}clearMessages(){this.getCurrentMessageRepo().clear(),this.chainManager.memoryManager.clearChatMemory().catch(n=>z("clearChatMemory failed",n)),k("[ChatManager] Cleared all messages")}async truncateAfterMessageId(e){this.getCurrentMessageRepo().t
To pick up a draggable item, press the space bar.
While dragging, use the arrow keys to move the item.
Press space again to drop the item in its new position, or press escape to cancel.
`},Utn={onDragStart(t){let{active:e}=t;return"Picked up draggable item "+e.id+"."},onDragOver(t){let{active:e,over:n}=t;return n?"Draggable item "+e.id+" was moved over droppable area "+n.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(t){let{active:e,over:n}=t;return n?"Draggable item "+e.id+" was dropped over droppable area "+n.id:"Draggable item "+e.id+" was dropped."},onDragCancel(t){let{active:e}=t;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function Btn(t){let{announcements:e=Utn,container:n,hiddenTextDescribedById:r,screenReaderInstructions:o=Ftn}=t,{announce:i,announcement:s}=Zht(),a=OE("DndLiveRegion"),[l,c]=(0,Pe.useState)(!1);if((0,Pe.useEffect)(()=>{c(!0)},[]),Dtn((0,Pe.useMemo)(()=>({onDragStart(d){let{active:f}=d;i(e.onDragStart({active:f}))},onDragMove(d){let{active:f,over:p}=d;e.onDragMove&&i(e.onDragMove({active:f,over:p}))},onDragOver(d){let{active:f,over:p}=d;i(e.onDragOver({active:f,over:p}))},onDragEnd(d){let{active:f,over:p}=d;i(e.onDragEnd({active:f,over:p}))},onDragCancel(d){let{active:f,over:p}=d;i(e.onDragCancel({active:f,over:p}))}}),[i,e])),!l)return null;let u=Pe.default.createElement(Pe.default.Fragment,null,Pe.default.createElement(Ght,{id:r,value:o.draggable}),Pe.default.createElement(Yht,{id:a,announcement:s}));return n?(0,$E.createPortal)(u,n):u}var Ca;(function(t){t.DragStart="dragStart",t.DragMove="dragMove",t.DragEnd="dragEnd",t.DragCancel="dragCancel",t.DragOver="dragOver",t.RegisterDroppable="registerDroppable",t.SetDroppableDisabled="setDroppableDisabled",t.UnregisterDroppable="unregisterDroppable"})(Ca||(Ca={}));function cQ(){}function z1(t,e){return(0,Pe.useMemo)(()=>({sensor:t,options:e??{}}),[t,e])}function dQ(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return(0,Pe.useMemo)(()=>[...e].filter(r=>r!=null),[...e])}var jh=Object.freeze({x:0,y:0});function ugt(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function dgt(t,e){let{data:{value:n}}=t,{data:{value:r}}=e;return n-r}function ztn(t,e){let{data:{value:n}}=t,{data:{value:r}}=e;return r-n}function Jht(t){let{left:e,top:n,height:r,width:o}=t;return[{x:e,y:n},{x:e+o,y:n},{x:e,y:n+r},{x:e+o,y:n+r}]}function $0e(t,e){if(!t||t.length===0)return null;let[n]=t;return e?n[e]:n}function Xht(t,e,n){return e===void 0&&(e=t.left),n===void 0&&(n=t.top),{x:e+t.width*.5,y:n+t.height*.5}}var j1=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t,o=Xht(e,e.left,e.top),i=[];for(let s of r){let{id:a}=s,l=n.get(a);if(l){let c=ugt(Xht(l),o);i.push({id:a,data:{droppableContainer:s,value:c}})}}return i.sort(dgt)},fgt=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t,o=Jht(e),i=[];for(let s of r){let{id:a}=s,l=n.get(a);if(l){let c=Jht(l),u=o.reduce((f,p,m)=>f+ugt(c[m],p),0),d=Number((u/4).toFixed(4));i.push({id:a,data:{droppableContainer:s,value:d}})}}return i.sort(dgt)};function jtn(t,e){let n=Math.max(e.top,t.top),r=Math.max(e.left,t.left),o=Math.min(e.left+e.width,t.left+t.width),i=Math.min(e.top+e.height,t.top+t.height),s=o-r,a=i-n;if(r<o&&n<i){let l=e.width*e.height,c=t.width*t.height,u=s*a,d=u/(l+c-u);return Number(d.toFixed(4))}return 0}var Vtn=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t,o=[];for(let i of r){let{id:s}=i,a=n.get(s);if(a){let l=jtn(a,e);l>0&&o.push({id:s,data:{droppableContainer:i,value:l}})}}return o.sort(ztn)};function Wtn(t,e,n){return{...t,scaleX:e&&n?e.width/n.width:1,scaleY:e&&n?e.height/n.height:1}}function pgt(t,e){return t&&e?{x:t.left-e.left,y:t.top-e.top}:jh}function Htn(t){return function(n){for(var r=arguments.length,o=new Array(r>1?r-1:0),i=1;i<r;i++)o[i-1]=arguments[i];return o.reduce((s,a)=>({...s,top:s.top+t*a.y,bottom:s.bottom+t*a.y,left:s.left+t*a.x,right:s.right+t*a.x}),{...n})}}var Ktn=Htn(1);function qtn(t){if(t.startsWith("matrix3d(")){let e=t.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(t.startsWith("matrix(")){let e=t.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}functio
If you want to hide the \`${e.titleName}\`, you can wrap it with our VisuallyHidden component.
For more information, see https://radix-ui.com/primitives/docs/components/${e.docsSlug}`;return Wo.useEffect(()=>{t&&(document.getElementById(t)||console.error(n))},[n,t]),null},Prn="DialogDescriptionWarning",Ern=({contentRef:t,descriptionId:e})=>{let r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${ryt(Prn).contentName}}.`;return Wo.useEffect(()=>{let o=t.current?.getAttribute("aria-describedby");e&&o&&(document.getElementById(e)||console.warn(r))},[r,t,e]),null},oyt=Vgt,iyt=Hgt,syt=qgt,W0e=Ggt,H0e=Ygt,K0e=Jgt,q0e=Qgt,ayt=tyt;vt();Kt();var PQ=oyt,lyt=iyt,krn=syt;var cyt=Ul.forwardRef(({className:t,...e},n)=>Ul.createElement(W0e,{ref:n,className:oe("tw-fixed tw-inset-0 tw-z-modal data-[state=open]:tw-animate-in data-[state=closed]:tw-animate-out data-[state=closed]:tw-fade-out-0 data-[state=open]:tw-fade-in-0","tw-bg-overlay/50",t),...e}));cyt.displayName=W0e.displayName;var $V=Ul.forwardRef(({className:t,children:e,container:n,...r},o)=>Ul.createElement(krn,{container:n},Ul.createElement(cyt,null),Ul.createElement(H0e,{ref:o,className:oe("tw-fixed tw-left-1/2 tw-top-1/2 tw-z-modal tw-grid tw-w-full tw-max-w-lg -tw-translate-x-1/2 -tw-translate-y-1/2 tw-gap-4 tw-border tw-bg-primary tw-p-6 tw-shadow-lg tw-duration-200 data-[state=open]:tw-animate-in data-[state=closed]:tw-animate-out data-[state=closed]:tw-fade-out-0 data-[state=open]:tw-fade-in-0 data-[state=closed]:tw-zoom-out-95 data-[state=open]:tw-zoom-in-95 data-[state=closed]:tw-slide-out-to-left-1/2 data-[state=closed]:tw-slide-out-to-top-[48%] data-[state=open]:tw-slide-in-from-left-1/2 data-[state=open]:tw-slide-in-from-top-[48%] sm:tw-rounded-lg",t),...r},e,Ul.createElement(ayt,{className:"clickable-icon tw-absolute tw-right-4 tw-top-4 tw-border-none tw-bg-transparent tw-text-faint tw-outline-none hover:tw-bg-transparent hover:tw-bg-opacity-100 hover:tw-text-normal focus-visible:tw-text-normal focus-visible:tw-outline-none focus-visible:tw-ring-0"},Ul.createElement(Sn,{className:"tw-size-4"}),Ul.createElement("span",{className:"tw-sr-only"},"Close")))));$V.displayName=H0e.displayName;var FV=({className:t,...e})=>Ul.createElement("div",{className:oe("tw-flex tw-flex-col tw-space-y-0.5 tw-text-center sm:tw-text-left",t),...e});FV.displayName="DialogHeader";var Mrn=({className:t,...e})=>Ul.createElement("div",{className:oe("tw-flex tw-flex-col-reverse sm:tw-flex-row sm:tw-justify-end sm:tw-space-x-2",t),...e});Mrn.displayName="DialogFooter";var UV=Ul.forwardRef(({className:t,...e},n)=>Ul.createElement(K0e,{ref:n,className:oe("tw-mt-0 tw-text-lg tw-font-semibold tw-leading-none tw-tracking-tight",t),...e}));UV.displayName=K0e.displayName;var BV=Ul.forwardRef(({className:t,...e},n)=>Ul.createElement(q0e,{ref:n,className:oe("tw-text-sm tw-text-muted",t),...e}));BV.displayName=q0e.displayName;qe();function $t(t){let{title:e,description:n,className:r,disabled:o}=t,{modalContainer:i}=SS(),s="onChange"in t?t.onChange:void 0,a=(0,ii.useMemo)(()=>{if(s)return Li(c=>{s(c)},1e3)},[s]),l=()=>{switch(t.type){case"text":case"number":return ii.default.createElement(Xn,{type:t.type,defaultValue:t.value,onChange:c=>{a?.(c.target.value)},placeholder:t.placeholder,disabled:o,className:"tw-w-full sm:tw-w-[200px]"});case"password":return ii.default.createElement(Fy,{value:t.value!==void 0?String(t.value):void 0,onChange:c=>{a?.(c)},placeholder:t.placeholder,disabled:o,className:"tw-w-full sm:tw-w-[200px]"});case"textarea":return ii.default.createElement(hf,{defaultValue:t.value,onChange:c=>{a?.(c.target.value)},placeholder:t.placeholder,rows:t.rows||3,disabled:o,className:"tw-min-h-[80px] tw-w-full sm:tw-w-[300px]"});case"switch":return ii.default.createElement(uh,{checked:t.checked,onCheckedChange:t.onCheckedChange,disabled:o});case"select":return ii.default.createElement("div",{className:"tw-group tw-relative tw-w-full sm:tw-w-[200px]"},ii.default.createElement("select",{value:t.value?.toString(),onChange:c=>t.onChange?.(c.target.value),disabled:o,className:oe("tw-w-full tw-appearance-none","tw-flex tw-h-9 tw-rounded-md tw-border tw-border-solid tw-bo
`);new zV.Notice(`API keys moved to Obsidian Keychain.
${_.fieldsRequiringReentry.length} key(s) could not be decrypted and need to be re-entered:
${T}`,0)}else new zV.Notice("API keys moved to Obsidian Keychain.")}catch(b){z("Failed to migrate secrets to Obsidian Keychain.",b),new zV.Notice("Failed to migrate to Obsidian Keychain. Please try again.")}finally{s(!1)}}},[t,i]);return nn.default.createElement("div",{className:"tw-space-y-4"},nn.default.createElement("section",{className:"tw-space-y-4 tw-rounded-lg tw-border tw-p-4"},nn.default.createElement("div",{className:"tw-text-xl tw-font-bold"},"User System Prompt"),nn.default.createElement($t,{type:"custom",title:"Default System Prompt",description:"Customize the system prompt for all messages, may result in unexpected behavior!"},nn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},nn.default.createElement(Ty,{value:m,onChange:x=>h(x.target.value),options:[{label:"None (use built-in prompt)",value:""},...n.map(x=>({label:x.title===e.defaultSystemPromptTitle?`${x.title} (Default)`:x.title,value:x.title}))],containerClassName:"tw-flex-1"}),nn.default.createElement(X,{variant:"ghost",size:"icon",onClick:g,className:"tw-size-5 tw-shrink-0 tw-p-0",title:"Open the source file",disabled:!m},nn.default.createElement(Oc,{className:"tw-size-5"})),nn.default.createElement(X,{variant:"default",size:"icon",onClick:y,title:"Add new prompt"},nn.default.createElement(Lc,{className:"tw-size-4"})))),nn.default.createElement($t,{type:"text",title:"System Prompts Folder Name",description:"Folder where system prompts are stored.",value:e.userSystemPromptsFolder,onChange:x=>pe("userSystemPromptsFolder",x),placeholder:"copilot/system-prompts"})),nn.default.createElement("section",{className:"tw-space-y-4 tw-rounded-lg tw-border tw-p-4"},nn.default.createElement("div",{className:"tw-text-xl tw-font-bold"},"Others"),nn.default.createElement($t,{type:"custom",title:"API Key Storage",description:d==="unavailable"?nn.default.createElement(nn.default.Fragment,null,"Update Obsidian to ",nn.default.createElement("code",null,"1.11.4+")," to enable the"," ",nn.default.createElement("strong",{className:"tw-font-semibold tw-text-normal"},"Obsidian Keychain"),". Keys are stored in ",nn.default.createElement("code",null,"data.json"),"."):d==="stranded"?nn.default.createElement(nn.default.Fragment,null,"This vault uses the"," ",nn.default.createElement("strong",{className:"tw-font-semibold tw-text-normal"},"Obsidian Keychain"),", but this Obsidian build cannot access it. Keys you enter here won't persist. Update Obsidian to ",nn.default.createElement("code",null,"1.11.4+"),", or re-enter keys on a supported device."):d==="active"?f?nn.default.createElement("span",{className:"tw-text-warning"},"No API keys found in this device's"," ",nn.default.createElement("strong",{className:"tw-font-semibold tw-text-normal"},"Obsidian Keychain"),". Re-enter your API keys in the relevant settings sections \u2014 this device's keychain is separate from other devices."):nn.default.createElement(nn.default.Fragment,null,"API keys are stored in this device's"," ",nn.default.createElement("strong",{className:"tw-font-semibold tw-text-normal"},"Obsidian Keychain"),"."):nn.default.createElement(nn.default.Fragment,null,"Your API keys are stored in ",nn.default.createElement("code",null,"data.json"),". Move them to the"," ",nn.default.createElement("strong",{className:"tw-font-semibold tw-text-normal"},"Obsidian Keychain")," for stronger protection.")},nn.default.createElement("div",{className:"tw-flex tw-flex-col tw-items-start tw-gap-2 sm:tw-items-end"},d==="active"&&nn.default.createElement("div",{className:"tw-inline-flex tw-items-center tw-gap-1.5 tw-rounded-md tw-bg-success tw-px-3 tw-py-1 tw-text-smallest tw-font-semibold tw-text-success"},nn.default.createElement(sw,{className:"tw-size-4"}),"Obsidian Keychain"),(d==="standard"||d==="blocked")&&nn.default.createElement("div",{className:"tw-inline-flex tw-items-center tw-gap-1.5 tw-rounded-md tw-border tw-border-border tw-bg-callout-warning/20 tw-px-3 tw-py-1 tw-text-smallest tw-font-semibold tw-text-warning"},nn.default.createElement(tb,{className:"tw-size-4"}),"Standard Storage"),d==="u
detail: `+a)}let i=await o.json();return{success:!0,models:G0e(t,i)}}catch(e){return z(`Error fetching models for ${t}:`,e),{success:!1,models:[],error:Xt(e)}}}async function yyt(t,e,n){let r=n?.skipVerification??!1,i=!!e.find(u=>u.name===t.name&&u.provider===t.provider),s=t.provider==="github-copilot"?void 0:Ad(t.provider),a={name:t.name,provider:t.provider,apiKey:s,enabled:!0},l=!1,c;if(!r)try{await Sl.instance.getCurrentChainManager().chatModelManager.ping(a)}catch(u){if(l=!0,c=Xt(u),a.provider==="github-copilot"&&c.toLowerCase().includes("not supported")){let d=sh.getInstance().getPolicyTerms(t.id);d&&(c+=`
${d}`)}z("Model verification failed:",u)}return{success:!0,alreadyExists:i,verificationFailed:l,verificationError:c}}function wyt(t){return{name:t.name,provider:t.provider,enabled:!0}}qe();vt();var Tx=require("obsidian"),co=N(U());function Urn(t){return t.split(/\n\n+/).map((n,r)=>{let i=n.split(/(\[[^\]]+\]\([^)]+\))/g).map((s,a)=>{let l=s.match(/^\[([^\]]+)\]\(([^)]+)\)$/);return l?co.default.createElement("a",{key:a,href:l[2],target:"_blank",rel:"noopener noreferrer",className:"tw-underline"},l[1]):s});return co.default.createElement("p",{key:r,className:r>0?"tw-mt-1":""},i)})}function MQ({provider:t,isReady:e,expanded:n=!1,skipVerification:r=!1,credentialVersion:o}){let i=Ht(),[s,a]=(0,co.useState)(null),[l,c]=(0,co.useState)(!1),[u,d]=(0,co.useState)(null),[f,p]=(0,co.useState)(null),[m,h]=(0,co.useState)(!1),[g,y]=(0,co.useState)(null),w=(0,co.useRef)(!1),v=(0,co.useCallback)(async()=>{if(!(w.current||!e)){w.current=!0,c(!0),d(null);try{let _=await gyt(t);_.success?a(_.models):(d(_.error||"Failed to load models"),new Tx.Notice(`Failed to load models for ${cl(t)}: ${_.error}`,5e3))}catch(_){let T=Xt(_);d(T),new Tx.Notice(`Failed to load models for ${cl(t)}: ${T}`,5e3)}finally{c(!1),w.current=!1}}},[t,e]);(0,co.useEffect)(()=>{n&&e&&s===null&&!l&&!u&&v()},[n,e,s,l,u,v]);let x=async()=>{if(!f){new Tx.Notice("Please select a model first");return}h(!0),y(null);try{let _=await yyt({id:f.id,name:f.name,provider:t},i.activeModels,{skipVerification:r});if(_.alreadyExists)_.verificationFailed?(y(_.verificationError??null),new Tx.Notice(`Model ${f.name} already exists (verification failed: ${_.verificationError})`,1e4)):new Tx.Notice(`Model ${f.name} verified successfully! It already exists in your models list.`);else{let T=wyt({id:f.id,name:f.name,provider:t}),S=[...i.activeModels,T];pe("activeModels",S),_.verificationFailed?(y(_.verificationError??null),new Tx.Notice(`Model ${f.name} added (verification failed: ${_.verificationError})`,1e4)):new Tx.Notice(`Model ${f.name} verified and added to your models list!`)}}catch(_){z("Error adding model:",_),new Tx.Notice(`Failed to add model: ${Xt(_)}`)}finally{h(!1)}},b=s?.filter((_,T,S)=>S.findIndex(P=>P.id===_.id)===T).sort((_,T)=>_.name.localeCompare(T.name));return co.default.createElement(Zn,{label:"Model",description:"Add the selected model to your models list. After adding, check the Model Tab."},co.default.createElement("div",null,co.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},co.default.createElement("div",{className:"tw-flex-1"},co.default.createElement(Ty,{options:b?.map(_=>({label:_.name,value:_.id}))||[],onChange:_=>{let T=_.target.value,S=s?.find(P=>P.id===T);S&&(p(S),y(null))},onClick:()=>{s===null&&!l&&v()},value:f?.id||"",placeholder:"Select Model",disabled:!e||l})),co.default.createElement("div",{className:"tw-w-[72px]"},co.default.createElement(X,{onClick:x,disabled:!f||m,variant:"secondary",size:"sm",className:"tw-w-full tw-whitespace-nowrap"},m?co.default.createElement(Pr,{className:"tw-mr-2 tw-size-4 tw-animate-spin"}):"Add"))),co.default.createElement("div",{className:"tw-mt-1 tw-text-xs"},l&&co.default.createElement("div",{className:"tw-p-1 tw-text-muted"},"Loading models..."),u&&co.default.createElement("div",{className:"tw-p-1 tw-text-error"},"Failed to load models. ",u),s&&s.length===0&&co.default.createElement("div",{className:"tw-p-1 tw-text-muted"},"No models available."),s===null&&!l&&!u&&co.default.createElement("div",{className:"tw-p-1 tw-text-muted"},"Click to load available models."),g&&co.default.createElement("div",{className:"tw-mt-2 tw-rounded-md tw-border tw-border-border tw-p-2 tw-text-error tw-bg-modifier-error/10"},Urn(g)))))}vt();var VE=require("obsidian"),Nt=N(U());function vyt(){let t=Ht(),[e]=(0,Nt.useState)(()=>sh.getInstance()),[n,r]=(0,Nt.useState)(()=>e.getAuthState().status==="authenticated"?"done":"idle"),[o,i]=(0,Nt.useState)(null),[s,a]=(0,Nt.useState)(0),[l,c]=(0,Nt.useState)(null),[u,d]=(0,Nt.useState)(!1),f=(0,Nt.useRef)(0),p=(0,Nt.useRef)(!0),[m,h]=(0,Nt.useState)({token:t.githubCopilotToken
`)}async function ton(t,e){let n=[],r=t.provider?.trim()??"",o=OQ(r),i=t.baseUrl?.trim()??"",s=AS(i||o||"https://api.example.com/v1"),a=Xrn(s),l=t.name?.trim()||"<MODEL_NAME>";t.name?.trim()||n.push("Model name is empty; using placeholder.");let c=await Z1(t.apiKey);n.push(...c.warnings);let u={"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${c.apiKey}`};if(t.openAIOrgId?.trim())try{let d=(await pn(t.openAIOrgId))?.trim();d?u["OpenAI-Organization"]=d:n.push("OpenAI organization ID could not be decrypted; omitting header.")}catch{n.push("OpenAI organization ID could not be decrypted; omitting header.")}return r==="openrouterai"&&(u["HTTP-Referer"]="https://obsidiancopilot.com",u["X-Title"]="Obsidian Copilot"),e?{ok:!0,warnings:n,spec:{method:"POST",url:`${a}/embeddings`,headers:u,body:{model:l,input:WV}}}:{ok:!0,warnings:n,spec:{method:"POST",url:`${a}/chat/completions`,headers:u,body:{model:l,messages:[{role:"user",content:HE}],stream:!1,max_tokens:Y0e}}}}function non(t,e,n,r){let o=[],i=t.azureOpenAIApiInstanceName?.trim()||"[instance]";t.azureOpenAIApiInstanceName?.trim()||o.push("Azure instance name is empty; using placeholder.");let s=t.baseUrl?.trim();if(s){let a=Jrn(s);if(a){let l=AS(a.pathname||"");l.includes("/openai/deployments/")&&(l=l.split("/openai/deployments/")[0]);let c=`${a.origin}${l}`;return{warnings:o,url:`${c}/openai/deployments/${encodeURIComponent(e)}/${n}?api-version=${encodeURIComponent(r)}`}}}return{warnings:o,url:`https://${i}.openai.azure.com/openai/deployments/${encodeURIComponent(e)}/${n}?api-version=${encodeURIComponent(r)}`}}async function ron(t,e){let n=[],r=await Z1(t.apiKey);n.push(...r.warnings);let o=e?"embeddings":"chat/completions";if(t.baseUrl?.trim()){let{normalizeAzureUrl:c}=await Promise.resolve().then(()=>(eP(),Vve)),{baseUrl:u,apiVersion:d}=c(t.baseUrl.trim()),f=d||t.azureOpenAIApiVersion?.trim()||"2024-05-01-preview",p=`${u}/${o}?api-version=${encodeURIComponent(f)}`,m=t.name?.trim(),h=e?{input:WV,...m?{model:m}:{}}:{messages:[{role:"user",content:HE}],stream:!1,max_tokens:Y0e,...m?{model:m}:{}};return{ok:!0,warnings:n,spec:{method:"POST",url:p,headers:{"Content-Type":"application/json",Accept:"application/json","api-key":r.apiKey},body:h}}}let i=e?t.azureOpenAIApiEmbeddingDeploymentName?.trim()||"[deployment]":t.azureOpenAIApiDeploymentName?.trim()||"[deployment]";(!i||i==="[deployment]")&&n.push("Azure deployment name is empty; using placeholder.");let s=t.azureOpenAIApiVersion?.trim()||"[api-version]";t.azureOpenAIApiVersion?.trim()||n.push("Azure api-version is empty; using placeholder.");let a=non(t,i,o,s);n.push(...a.warnings);let l=e?{input:WV}:{messages:[{role:"user",content:HE}],stream:!1,max_tokens:Y0e};return{ok:!0,warnings:n,spec:{method:"POST",url:a.url,headers:{"Content-Type":"application/json",Accept:"application/json","api-key":r.apiKey},body:l}}}async function oon(t){let e=[],n=t.baseUrl?.trim()??"",r=OQ("anthropic"),o=AS(n||r||"https://api.anthropic.com"),i=["/v1/messages","/v1"];for(let c of i)if(o.endsWith(c)){o=o.slice(0,-c.length);break}let s=`${o}/v1/messages`,a=await Z1(t.apiKey);e.push(...a.warnings);let l=t.name?.trim()||"<MODEL_NAME>";return t.name?.trim()||e.push("Model name is empty; using placeholder."),{ok:!0,warnings:e,spec:{method:"POST",url:s,headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":a.apiKey,"anthropic-version":Hrn},body:{model:l,max_tokens:qrn,messages:[{role:"user",content:HE}]}}}}async function ion(t,e){let n=[],r=t.baseUrl?.trim()??"",o=OQ("google"),s=Qrn(r||o||"https://generativelanguage.googleapis.com"),a=t.name?.trim()||"<MODEL_NAME>";t.name?.trim()||n.push("Model name is empty; using placeholder.");let l=a.includes("/")?a:`models/${a}`,c=await Z1(t.apiKey);n.push(...c.warnings);let u={"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":c.apiKey};return e?{ok:!0,warnings:n,spec:{method:"POST",url:`${s}/${l}:embedContent`,headers:u,body:{content:{parts:[{text:WV}]}}}}:{ok:!0,warnings:n,spec:{method:"POST",url:`${s}/${l}:generateContent`,h
`),warnings:e}}async function lon(t,e){let n=[],r=t.baseUrl?.trim()??"",o=OQ("ollama"),i=eon(AS(r||o||"http://localhost:11434")),s=t.name?.trim()||"<MODEL_NAME>";t.name?.trim()||n.push("Model name is empty; using placeholder.");let a={"Content-Type":"application/json",Accept:"application/json"};if(t.apiKey?.trim()){let c=await Z1(t.apiKey),u=c.warnings.filter(d=>!d.includes("API key is empty"));n.push(...u),a.Authorization=`Bearer ${c.apiKey}`}return e?{ok:!0,warnings:n,spec:{method:"POST",url:`${i}/api/embed`,headers:a,body:{model:s,input:WV,truncate:!0}}}:{ok:!0,warnings:n,spec:{method:"POST",url:`${i}/api/chat`,headers:a,body:{model:s,messages:[{role:"user",content:HE}],stream:!1}}}}async function Pyt(t){let e=[],n=t.provider?.trim();if(!n)return{ok:!1,error:"Provider is required to build a curl command.",warnings:e};let r=!!t.isEmbeddingModel;if(n==="azure openai"){let o=await ron(t,r);return o.ok?{ok:!0,command:WE(o.spec),warnings:o.warnings}:o}if(n==="anthropic"){if(r)return{ok:!1,error:"Anthropic does not support embeddings.",warnings:e};let o=await oon(t);return o.ok?{ok:!0,command:WE(o.spec),warnings:o.warnings}:o}if(n==="amazon-bedrock")return r?{ok:!1,error:"Bedrock embeddings are not supported by this generator.",warnings:e}:await aon(t);if(n==="google"||n==="google"){let o=await ion(t,r);return o.ok?{ok:!0,command:WE(o.spec),warnings:o.warnings}:o}if(n==="ollama"||n==="ollama"){let o=await lon(t,r);return o.ok?{ok:!0,command:WE(o.spec),warnings:o.warnings}:o}if(Zrn.has(n)){let o=await ton(t,r);return o.ok?{ok:!0,command:WE(o.spec),warnings:o.warnings}:o}return{ok:!1,error:`Provider "${n}" is not supported for curl generation.`,warnings:e}}vt();VS();var kS=require("obsidian"),Ae=N(U()),Z0e=({open:t,onOpenChange:e,onAdd:n,ping:r,isEmbeddingModel:o=!1})=>{let{modalContainer:i}=SS(),s=q(),a=o?"openai":"openrouterai",l=j=>j==="azure openai"&&!T.baseUrl,[c,u]=(0,Ae.useState)(null),[d,f]=(0,Ae.useState)(()=>l(a)),[p,m]=(0,Ae.useState)(!1),[h,g]=(0,Ae.useState)("idle"),[y,w]=(0,Ae.useState)({name:!1,instanceName:!1,deploymentName:!1,embeddingDeploymentName:!1,apiVersion:!1,displayName:!1,bedrockRegion:!1}),v=(j,G)=>{w(J=>({...J,[j]:G}))},x=()=>{w({name:!1,instanceName:!1,deploymentName:!1,embeddingDeploymentName:!1,apiVersion:!1,displayName:!1,bedrockRegion:!1})},b=()=>{let j=!0,G={...y};return G.name=!T.name,T.name||(j=!1),T.provider==="azure openai"&&(o||!T.baseUrl?.trim())&&(G.instanceName=!T.azureOpenAIApiInstanceName,G.apiVersion=!T.azureOpenAIApiVersion,o?(G.embeddingDeploymentName=!T.azureOpenAIApiEmbeddingDeploymentName,T.azureOpenAIApiEmbeddingDeploymentName||(j=!1)):(G.deploymentName=!T.azureOpenAIApiDeploymentName,T.azureOpenAIApiDeploymentName||(j=!1)),(!T.azureOpenAIApiInstanceName||!T.azureOpenAIApiVersion)&&(j=!1)),T.provider,"amazon-bedrock",G.bedrockRegion=!1,w(G),j},_=(j=a)=>{let G={name:"",provider:j,enabled:!0,isBuiltIn:!1,baseUrl:"",apiKey:Ad(j),isEmbeddingModel:o,capabilities:[]};if(!o){let J={...G,stream:!0};return j==="amazon-bedrock"?{...J,bedrockRegion:s.amazonBedrockRegion}:J}return G},[T,S]=(0,Ae.useState)(()=>_()),P=j=>{S(G=>({...G,...j})),g("idle")},A=j=>({...j,name:j.name?.trim(),baseUrl:j.baseUrl?.trim(),apiKey:j.apiKey?.trim(),openAIOrgId:j.openAIOrgId?.trim(),azureOpenAIApiInstanceName:j.azureOpenAIApiInstanceName?.trim(),azureOpenAIApiDeploymentName:j.azureOpenAIApiDeploymentName?.trim(),azureOpenAIApiEmbeddingDeploymentName:j.azureOpenAIApiEmbeddingDeploymentName?.trim(),azureOpenAIApiVersion:j.azureOpenAIApiVersion?.trim(),bedrockRegion:j.bedrockRegion?.trim()}),[O,D]=(0,Ae.useState)(()=>ew(a)),$=()=>!!(T.name&&T.provider),B=()=>p||!$(),W=()=>{if(!b()){new kS.Notice("Please fill in all required fields");return}let j=A(T);n(j),e(!1),S(_()),x(),g("idle"),f(!1)},F=j=>{D(ew(j)),g("idle"),S({...T,provider:j,apiKey:Ad(j),...j==="openai"?{openAIOrgId:s.openAIOrgId}:{},...j==="azure openai"?{azureOpenAIApiInstanceName:s.azureOpenAIApiInstanceName,azureOpenAIApiDeploymentName:s.azureOpenAIApiDeploymentName,azureOpenAIApiVersion:s.azureOpenAIApiVersion,azureOpenAIApiEmbeddingDeploymentNam
/*! Bundled license information:
ieee754/index.js:
(*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)
buffer/index.js:
(*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*)
react/cjs/react.production.min.js:
(**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
react/cjs/react-jsx-runtime.production.min.js:
(**
* @license React
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/shared/src/utils.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/defaultAttributes.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/Icon.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/createLucideIcon.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/arrow-big-up.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/arrow-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/arrow-up-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/book-open.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/brain.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/check.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-down.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-up.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-alert.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-check-big.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-check.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-dashed.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-help.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-plus.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-stop.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-x.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/clipboard-paste.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/clock.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/cog.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/coins.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/command.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/copy-plus.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/copy.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/corner-down-left.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/cpu.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/database.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/download.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/ellipsis-vertical.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/ellipsis.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/external-link.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/eye-off.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/eye.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-audio.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-clock.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-image.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-input.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-output.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-text.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-video.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/folder-open.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/folder.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/globe.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/grip-vertical.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/hash.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/history.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/image.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/info.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/key.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/library-big.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/lightbulb.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/link.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/loader-circle.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/lock-open.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/message-circle-plus.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/message-circle.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/message-square-x.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/message-square.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/pause.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/pen-line.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/pen.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/pencil-line.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/pencil.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/play.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/plus.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/refresh-ccw.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/refresh-cw.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/replace.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/rotate-ccw.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/rotate-cw.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/search.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/send.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/settings.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/shield-check.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/smartphone.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/sparkles.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/square-arrow-out-up-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/square-pen.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/square.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/tag.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/text-cursor-input.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/trash-2.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/triangle-alert.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/wrench.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/x.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/zap-off.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/zap.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/lucide-react.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
scheduler/cjs/scheduler.production.min.js:
(**
* @license React
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
react-dom/cjs/react-dom.production.min.js:
(**
* @license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
@langchain/core/dist/utils/fast-json-patch/src/helpers.js:
(*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2017-2022 Joachim Wester
* MIT licensed
*)
@langchain/core/dist/utils/fast-json-patch/src/duplex.js:
(*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2013-2021 Joachim Wester
* MIT license
*)
@langchain/core/dist/utils/js-sha256/hash.js:
(**
* [js-sha256]{@link https://github.com/emn178/js-sha256}
*
* @version 0.11.1
* @author Chen, Yi-Cyuan [emn178@gmail.com]
* @copyright Chen, Yi-Cyuan 2014-2025
* @license MIT
*)
@langchain/core/dist/utils/sax-js/sax.js:
(*! http://mths.be/fromcodepoint v0.1.0 by @mathias *)
@google/generative-ai/dist/index.mjs:
(**
* @license
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*)
mustache/mustache.mjs:
(*!
* mustache.js - Logic-less {{mustache}} templates with JavaScript
* http://github.com/janl/mustache.js
*)
*/
/* nosourcemap */