Files
VNGame/notes/.obsidian/plugins/agent-client/main.js
T

219 lines
772 KiB
JavaScript
Raw Normal View History

2026-06-09 11:08:04 +02:00
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var sM=Object.create;var Cs=Object.defineProperty;var lM=Object.getOwnPropertyDescriptor;var cM=Object.getOwnPropertyNames;var uM=Object.getPrototypeOf,dM=Object.prototype.hasOwnProperty;var fM=(e,t,n)=>t in e?Cs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var te=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ei=(e,t)=>{for(var n in t)Cs(e,n,{get:t[n],enumerable:!0})},g$=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of cM(t))!dM.call(e,i)&&i!==n&&Cs(e,i,{get:()=>t[i],enumerable:!(r=lM(t,i))||r.enumerable});return e};var G=(e,t,n)=>(n=e!=null?sM(uM(e)):{},g$(t||!e||!e.__esModule?Cs(n,"default",{value:e,enumerable:!0}):n,e)),mM=e=>g$(Cs({},"__esModule",{value:!0}),e);var qc=(e,t,n)=>(fM(e,typeof t!="symbol"?t+"":t,n),n),kp=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var ie=(e,t,n)=>(kp(e,t,"read from private field"),n?n.call(e):t.get(e)),pt=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},Fn=(e,t,n,r)=>(kp(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),h$=(e,t,n,r)=>({set _(i){Fn(e,t,i,n)},get _(){return ie(e,t,r)}}),ti=(e,t,n)=>(kp(e,t,"access private method"),n);var Es=te((J3,v$)=>{"use strict";var pM="2.0.0",gM=Number.MAX_SAFE_INTEGER||9007199254740991,hM=16,vM=256-6,yM=["major","premajor","minor","preminor","patch","prepatch","prerelease"];v$.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:hM,MAX_SAFE_BUILD_LENGTH:vM,MAX_SAFE_INTEGER:gM,RELEASE_TYPES:yM,SEMVER_SPEC_VERSION:pM,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var As=te((K3,y$)=>{"use strict";var SM=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};y$.exports=SM});var Po=te((ni,S$)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Np,MAX_SAFE_BUILD_LENGTH:bM,MAX_LENGTH:xM}=Es(),_M=As();ni=S$.exports={};var wM=ni.re=[],$M=ni.safeRe=[],X=ni.src=[],CM=ni.safeSrc=[],Y=ni.t={},EM=0,Op="[a-zA-Z0-9-]",AM=[["\\s",1],["\\d",xM],[Op,bM]],zM=e=>{for(let[t,n]of AM)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e},le=(e,t,n)=>{let r=zM(t),i=EM++;_M(e,i,t),Y[e]=i,X[i]=t,CM[i]=r,wM[i]=new RegExp(t,n?"g":void 0),$M[i]=new RegExp(r,n?"g":void 0)};le("NUMERICIDENTIFIER","0|[1-9]\\d*");le("NUMERICIDENTIFIERLOOSE","\\d+");le("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Op}*`);le("MAINVERSION",`(${X[Y.NUMERICIDENTIFIER]})\\.(${X[Y.NUMERICIDENTIFIER]})\\.(${X[Y.NUMERICIDENTIFIER]})`);le("MAINVERSIONLOOSE",`(${X[Y.NUMERICIDENTIFIERLOOSE]})\\.(${X[Y.NUMERICIDENTIFIERLOOSE]})\\.(${X[Y.NUMERICIDENTIFIERLOOSE]})`);le("PRERELEASEIDENTIFIER",`(?:${X[Y.NONNUMERICIDENTIFIER]}|${X[Y.NUMERICIDENTIFIER]})`);le("PRERELEASEIDENTIFIERLOOSE",`(?:${X[Y.NONNUMERICIDENTIFIER]}|${X[Y.NUMERICIDENTIFIERLOOSE]})`);le("PRERELEASE",`(?:-(${X[Y.PRERELEASEIDENTIFIER]}(?:\\.${X[Y.PRERELEASEIDENTIFIER]})*))`);le("PRERELEASELOOSE",`(?:-?(${X[Y.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${X[Y.PRERELEASEIDENTIFIERLOOSE]})*))`);le("BUILDIDENTIFIER",`${Op}+`);le("BUILD",`(?:\\+(${X[Y.BUILDIDENTIFIER]}(?:\\.${X[Y.BUILDIDENTIFIER]})*))`);le("FULLPLAIN",`v?${X[Y.MAINVERSION]}${X[Y.PRERELEASE]}?${X[Y.BUILD]}?`);le("FULL",`^${X[Y.FULLPLAIN]}$`);le("LOOSEPLAIN",`[v=\\s]*${X[Y.MAINVERSIONLOOSE]}${X[Y.PRERELEASELOOSE]}?${X[Y.BUILD]}?`);le("LOOSE",`^${X[Y.LOOSEPLAIN]}$`);le("GTLT","((?:<|>)?=?)");le("XRANGEIDENTIFIERLOOSE",`${X[Y.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);le("XRANGEIDENTIFIER",`${X[Y.NUMERICIDENTIFIER]}|x|X|\\*`);le("XRANGEPLAIN",`[v=\\s]*(${X[Y.XRANGEIDENTIFIER]})(?:\\.(${X[Y.XRANGEIDENTIFIER]})(?:\\.(${X[Y.XRANGEIDENTIFIER]})(?:${X[Y.PRERELEASE]})?${X[Y.BUILD]}?)?)?`);le("XRANGEPLAINLOOSE",`[v=\\s]*(${X[Y.XRANGEIDENTIFIERLOOSE]})(?:\\.(${X[Y.XRANGEIDENTIFIERLOOSE]})(?:\\.(${X[Y.XRANGEIDENTIFIERLOOSE]})(?:${X[Y.PRERELEASELOOSE]})?${X[Y.BUILD]}?)?)?`);le("XRANGE",`^${X[Y.GTLT]}\\s*${X[Y.XRANGEPLAIN]}$`);le("XRANGELOOSE",`^${X[Y.GTLT]}\\s*${X[Y.XRANGEPLAINLOOSE]}$`);le("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Np}})(?:\\.(\\d{1,${Np}}))?(?:\\.(\\d{1,${Np}})
at`)?" (<anonymous>)":-1<n.stack.indexOf("@")?"@unknown:0:0":""}return`
`+dg+e+DC}var fg=!1;function mg(e,t){if(!e||fg)return"";fg=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var r={DetermineComponentFrameRoot:function(){try{if(t){var l=function(){throw Error()};if(Object.defineProperty(l.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(l,[])}catch(p){var f=p}Reflect.construct(e,[],l)}else{try{l.call()}catch(p){f=p}e.call(l.prototype)}}else{try{throw Error()}catch(p){f=p}(l=e())&&typeof l.catch=="function"&&l.catch(function(){})}}catch(p){if(p&&f&&typeof p.stack=="string")return[p.stack,f.stack]}return[null,null]}};r.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var i=Object.getOwnPropertyDescriptor(r.DetermineComponentFrameRoot,"name");i&&i.configurable&&Object.defineProperty(r.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var o=r.DetermineComponentFrameRoot(),a=o[0],s=o[1];if(a&&s){var c=a.split(`
`),d=s.split(`
`);for(i=r=0;r<c.length&&!c[r].includes("DetermineComponentFrameRoot");)r++;for(;i<d.length&&!d[i].includes("DetermineComponentFrameRoot");)i++;if(r===c.length||i===d.length)for(r=c.length-1,i=d.length-1;1<=r&&0<=i&&c[r]!==d[i];)i--;for(;1<=r&&0<=i;r--,i--)if(c[r]!==d[i]){if(r!==1||i!==1)do if(r--,i--,0>i||c[r]!==d[i]){var m=`
`+c[r].replace(" at new "," at ");return e.displayName&&m.includes("<anonymous>")&&(m=m.replace("<anonymous>",e.displayName)),m}while(1<=r&&0<=i);break}}}finally{fg=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:"")?Yr(n):""}function MU(e,t){switch(e.tag){case 26:case 27:case 5:return Yr(e.type);case 16:return Yr("Lazy");case 13:return e.child!==t&&t!==null?Yr("Suspense Fallback"):Yr("Suspense");case 19:return Yr("SuspenseList");case 0:case 15:return mg(e.type,!1);case 11:return mg(e.type.render,!1);case 1:return mg(e.type,!0);case 31:return Yr("Activity");default:return""}}function RC(e){try{var t="",n=null;do t+=MU(e,n),n=e,e=e.return;while(e);return t}catch(r){return`
Error generating stack: `+r.message+`
`+r.stack}}var Kg=Object.prototype.hasOwnProperty,Zh=ht.unstable_scheduleCallback,pg=ht.unstable_cancelCallback,DU=ht.unstable_shouldYield,RU=ht.unstable_requestPaint,mn=ht.unstable_now,UU=ht.unstable_getCurrentPriorityLevel,dA=ht.unstable_ImmediatePriority,fA=ht.unstable_UserBlockingPriority,qu=ht.unstable_NormalPriority,PU=ht.unstable_LowPriority,mA=ht.unstable_IdlePriority,LU=ht.log,jU=ht.unstable_setDisableYieldValue,wl=null,pn=null;function cr(e){if(typeof LU=="function"&&jU(e),pn&&typeof pn.setStrictMode=="function")try{pn.setStrictMode(wl,e)}catch(t){}}var gn=Math.clz32?Math.clz32:VU,ZU=Math.log,qU=Math.LN2;function VU(e){return e>>>=0,e===0?32:31-(ZU(e)/qU|0)|0}var su=256,lu=262144,cu=4194304;function Jr(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function pd(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,o=e.suspendedLanes,a=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s!==0?(r=s&~o,r!==0?i=Jr(r):(a&=s,a!==0?i=Jr(a):n||(n=s&~e,n!==0&&(i=Jr(n))))):(s=r&~o,s!==0?i=Jr(s):a!==0?i=Jr(a):n||(n=r&~e,n!==0&&(i=Jr(n)))),i===0?0:t!==0&&t!==i&&!(t&o)&&(o=i&-i,n=t&-t,o>=n||o===32&&(n&4194048)!==0)?t:i}function $l(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function FU(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function pA(){var e=cu;return cu<<=1,!(cu&62914560)&&(cu=4194304),e}function gg(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Cl(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function HU(e,t,n,r,i,o){var a=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,d=e.hiddenUpdates;for(n=a&~n;0<n;){var m=31-gn(n),l=1<<m;s[m]=0,c[m]=-1;var f=d[m];if(f!==null)for(d[m]=null,m=0;m<f.length;m++){var p=f[m];p!==null&&(p.lane&=-536870913)}n&=~l}r!==0&&gA(e,r,0),o!==0&&i===0&&e.tag!==0&&(e.suspendedLanes|=o&~(a&~t))}function gA(e,t,n){e.pendingLanes|=t,e.suspendedLanes&=~t;var r=31-gn(t);e.entangledLanes|=t,e.entanglements[r]=e.entanglements[r]|1073741824|n&261930}function hA(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-gn(n),i=1<<r;i&t|e[r]&t&&(e[r]|=t),n&=~i}}function vA(e,t){var n=t&-t;return n=n&42?1:qh(n),n&(e.suspendedLanes|t)?0:n}function qh(e){switch(e){case 2:e=1;break;case 8:e=4;break;case 32:e=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:e=128;break;case 268435456:e=134217728;break;default:e=0}return e}function Vh(e){return e&=-e,2<e?8<e?e&134217727?32:268435456:8:2}function yA(){var e=_e.p;return e!==0?e:(e=window.event,e===void 0?32:ZT(e.type))}function UC(e,t){var n=_e.p;try{return _e.p=e,t()}finally{_e.p=n}}var Ar=Math.random().toString(36).slice(2),Ct="__reactFiber$"+Ar,Wt="__reactProps$"+Ar,Ca="__reactContainer$"+Ar,Wg="__reactEvents$"+Ar,BU="__reactListeners$"+Ar,GU="__reactHandles$"+Ar,PC="__reactResources$"+Ar,El="__reactMarker$"+Ar;function Fh(
`).replace(wP,"")}function TT(e,t){return t=LE(t),LE(e)===t}function Ie(e,t,n,r,i,o){switch(n){case"children":typeof r=="string"?t==="body"||t==="textarea"&&r===""||ha(e,r):(typeof r=="number"||typeof r=="bigint")&&t!=="body"&&ha(e,""+r);break;case"className":uu(e,"class",r);break;case"tabIndex":uu(e,"tabindex",r);break;case"dir":case"role":case"viewBox":case"width":case"height":uu(e,n,r);break;case"style":EA(e,r,o);break;case"data":if(t!=="object"){uu(e,"data",r);break}case"src":case"href":if(r===""&&(t!=="a"||n!=="href")){e.removeAttribute(n);break}if(r==null||typeof r=="function"||typeof r=="symbol"||typeof r=="boolean"){e.removeAttribute(n);break}r=Cu(""+r),e.setAttribute(n,r);break;case"action":case"formAction":if(typeof r=="function"){e.setAttribute(n,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof o=="function"&&(n==="formAction"?(t!=="input"&&Ie(e,t,"name",i.name,i,null),Ie(e,t,"formEncType",i.formEncType,i,null),Ie(e,t,"formMethod",i.formMethod,i,null),Ie(e,t,"formTarget",i.formTarget,i,null)):(Ie(e,t,"encType",i.encType,i,null),Ie(e,t,"method",i.method,i,null),Ie(e,t,"target",i.target,i,null)));if(r==null||typeof r=="symbol"||typeof r=="boolean"){e.removeAttribute(n);break}r=Cu(""+r),e.setAttribute(n,r);break;case"onClick":r!=null&&(e.onclick=ki);break;case"onScroll":r!=null&&ge("scroll",e);break;case"onScrollEnd":r!=null&&ge("scrollend",e);break;case"dangerouslySetInnerHTML":if(r!=null){if(typeof r!="object"||!("__html"in r))throw Error(I(61));if(n=r.__html,n!=null){if(i.children!=null)throw Error(I(60));e.innerHTML=n}}break;case"multiple":e.multiple=r&&typeof r!="function"&&typeof r!="symbol";break;case"muted":e.muted=r&&typeof r!="function"&&typeof r!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(r==null||typeof r=="function"||typeof r=="boolean"||typeof r=="symbol"){e.removeAttribute("xlink:href");break}n=Cu(""+r),e.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",n);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":r!=null&&typeof r!="function"&&typeof r!="symbol"?e.setAttribute(n,""+r):e.removeAttribute(n);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":r&&typeof r!="function"&&typeof r!="symbol"?e.setAttribute(n,""):e.removeAttribute(n);break;case"capture":case"download":r===!0?e.setAttribute(n,""):r!==!1&&r!=null&&typeof r!="function"&&typeof r!="symbol"?e.setAttribute(n,r):e.removeAttribute(n);break;case"cols":case"rows":case"size":case"span":r!=null&&typeof r!="function"&&typeof r!="symbol"&&!isNaN(r)&&1<=r?e.setAttribute(n,r):e.removeAttribute(n);break;case"rowSpan":case"start":r==null||typeof r=="function"||typeof r=="symbol"||isNaN(r)?e.removeAttribute(n):e.setAttribute(n,r);break;case"popover":ge("beforetoggle",e),ge("toggle",e),$u(e,"popover",r);break;case"xlinkActuate":wi(e,"http://www.w3.org/1999/xlink","xlink:actuate",r);break;case"xlinkArcrole":wi(e,"http://www.w3.org/1999/xlink","xlink:arcrole",r);break;case"xlinkRole":wi(e,"http://www.w3.org/1999/xlink","xlink:role",r);break;case"xlinkShow":wi(e,"http://www.w3.org/1999/xlink","xlink:show",r);break;case"xlinkTitle":wi(e,"http://www.w3.org/1999/xlink","xlink:title",r);break;case"xlinkType":wi(e,"http://www.w3.org/1999/xlink","xlink:type",r);break;case"xmlBase":wi(e,"http://www.w3.org/XML/1998/namespace","xml:ba
${p}`,y=this.plugin.app.vault.getAbstractFileByPath(l),x;return y instanceof Dl.TFile?(await this.plugin.app.vault.modify(y,h),x=y):x=await this.plugin.app.vault.create(l,h),a&&await this.plugin.app.workspace.getLeaf(!1).openFile(x),this.logger.log(`Chat exported to: ${l}`),l}catch(f){throw this.logger.error("Export error:",f),f}}async ensureFolderExists(t){this.plugin.app.vault.getAbstractFileByPath(t)||await this.plugin.app.vault.createFolder(t)}getSessionIdFromFile(t){var i;let n=this.plugin.app.metadataCache.getFileCache(t),r=(i=n==null?void 0:n.frontmatter)==null?void 0:i.session_id;return r!=null?r:null}resolveExportFilePath(t,n,r){let i=`${t}/${n}.md`,o=this.plugin.app.vault.getAbstractFileByPath(i);if(!(o instanceof Dl.TFile)||this.getSessionIdFromFile(o)===r)return i;for(let s=2;s<=100;s++){let c=`${t}/${n}_${s}.md`,d=this.plugin.app.vault.getAbstractFileByPath(c);if(!(d instanceof Dl.TFile)||this.getSessionIdFromFile(d)===r)return c}return this.logger.warn(`Too many export files with same base name: ${n}`),`${t}/${n}_101.md`}generateFileName(t){let r=this.plugin.settings.exportSettings.filenameTemplate||"agent_client_{date}_{time}",i=t.getFullYear(),o=String(t.getMonth()+1).padStart(2,"0"),a=String(t.getDate()).padStart(2,"0"),s=`${i}${o}${a}`,c=String(t.getHours()).padStart(2,"0"),d=String(t.getMinutes()).padStart(2,"0"),m=String(t.getSeconds()).padStart(2,"0"),l=`${c}${d}${m}`;return r.replace("{date}",s).replace("{time}",l)}generateFrontmatter(t,n,r,i){let o=this.plugin.settings.exportSettings,a=i.getFullYear(),s=String(i.getMonth()+1).padStart(2,"0"),c=String(i.getDate()).padStart(2,"0"),d=String(i.getHours()).padStart(2,"0"),m=String(i.getMinutes()).padStart(2,"0"),l=String(i.getSeconds()).padStart(2,"0"),f=`${a}-${s}-${c}T${d}:${m}:${l}`,p=o.frontmatterTag.trim()?`
tags: [${o.frontmatterTag.trim()}]`:"";return`---
created: ${f}
agentDisplayName: ${t}
agentId: ${n}
session_id: ${r}${p}
---`}async convertMessagesToMarkdown(t,n,r){let i=this.plugin.settings.exportSettings,o={exportFilePath:r,imageIndex:0,includeImages:i.includeImages,imageLocation:i.imageLocation,imageCustomFolder:i.imageCustomFolder},a=`# ${n}
`;for(let s of t){let c=s.timestamp.toLocaleTimeString(),d=s.role==="user"?"User":"Assistant";a+=`## ${c} - ${d}
`;for(let m of s.content)a+=await this.convertContentToMarkdown(m,o);a+=`
---
`}return a}async convertContentToMarkdown(t,n){switch(t.type){case"text":return t.text+`
`;case"text_with_context":{let r="";if(t.autoMentionContext){let{noteName:i,selection:o}=t.autoMentionContext;o?r+=`@[[${i}]]:${o.fromLine}-${o.toLine}
`:r+=`@[[${i}]]
`}return r+=t.text+`
`,r}case"agent_thought":return`> [!info]- Thinking
> ${t.text.split(`
`).join(`
> `)}
`;case"tool_call":return this.convertToolCallToMarkdown(t);case"terminal":return`### \u{1F5A5}\uFE0F Terminal: ${t.terminalId.slice(0,8)}
`;case"plan":return this.convertPlanToMarkdown(t);case"permission_request":return this.convertPermissionRequestToMarkdown(t);case"resource_link":return`[${t.name}](${t.uri})
`;case"image":if(!n.includeImages)return"";if(t.uri)return`![Image](${t.uri})
`;if(n.imageLocation==="base64")return`![Image](data:${t.mimeType};base64,${t.data})
`;try{return n.imageIndex++,`![[${(await this.saveImageAsAttachment(t.data,t.mimeType,n.exportFilePath,n.imageIndex,n.imageLocation,n.imageCustomFolder)).split("/").pop()}]]
`}catch(r){return this.logger.error(`Failed to save image as attachment: ${r}`),`![Image](data:${t.mimeType};base64,${t.data})
`}default:return""}}convertToolCallToMarkdown(t){let n=`### \u{1F527} ${t.title||"Tool"}
`;if(t.locations&&t.locations.length>0){let r=t.locations.map(i=>i.line!=null?`\`${i.path}:${i.line}\``:`\`${i.path}\``);n+=`**Locations**: ${r.join(", ")}
`}if(n+=`**Status**: ${t.status}
`,t.content&&t.content.length>0)for(let r of t.content)r.type==="diff"&&(n+=this.convertDiffToMarkdown(r));return n}convertDiffToMarkdown(t){let n=`**File**: \`${t.path}\`
`;if(t.oldText===null||t.oldText===void 0||t.oldText==="")return n+="```diff\n",t.newText.split(`
`).forEach(o=>{n+=`+ ${o}
`}),n+="```\n\n",n;let r=t.oldText.split(`
`),i=t.newText.split(`
`);return n+="```diff\n",r.forEach(o=>{n+=`- ${o}
`}),i.forEach(o=>{n+=`+ ${o}
`}),n+="```\n\n",n}convertPlanToMarkdown(t){let n=`> [!plan] Plan
`;for(let r of t.entries){let i=r.status==="completed"?"\u2705":r.status==="in_progress"?"\u{1F504}":"\u23F3";n+=`> ${i} ${r.content}
`}return n+=`
`,n}convertPermissionRequestToMarkdown(t){let n=t.isCancelled?"Cancelled":"Requested";return`### \u26A0\uFE0F Permission: ${t.toolCall.title||"Unknown"} (${n})
`}async saveImageAsAttachment(t,n,r,i,o,a){let s=this.getExtensionFromMimeType(n),m=`${r.replace(/\.md$/,"").split("/").pop()||"image"}_${String(i).padStart(3,"0")}.${s}`,l;if(o==="custom"){let p=a||"Agent Client";if(await this.ensureFolderExists(p),l=`${p}/${m}`,this.plugin.app.vault.getAbstractFileByPath(l)instanceof Dl.TFile)return this.logger.log(`Image already exists, skipping: ${l}`),l}else if(l=await this.plugin.app.fileManager.getAvailablePathForAttachment(m,r),!l.endsWith(m)){let p=l.replace(/ \d+(\.[^.]+)$/,"$1");return this.logger.log(`Image already exists, skipping: ${p}`),p}let f=this.base64ToArrayBuffer(t);return await this.plugin.app.vault.createBinary(l,f),this.logger.log(`Image saved as attachment: ${l}`),l}getExtensionFromMimeType(t){return{"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp"}[t]||"png"}base64ToArrayBuffer(t){let n=atob(t),r=new Uint8Array(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r.buffer}};var Zd=require("child_process"),rI=require("obsidian");var Pv=require("child_process"),go=require("obsidian");function tI(e){let t=e.replace(/%/g,"%%").replace(/"/g,'""');return/[\s&()<>|^]/.test(e)?`"${t}"`:t}function jv(){return process.env.SHELL?process.env.SHELL:go.Platform.isMacOS?"/bin/zsh":"/bin/sh"}function Lv(e){return`'${e.replace(/'/g,"'\\''")}'`}var Pd=null;function s6(){if(!go.Platform.isWin)return null;if(Pd!==null)return Pd;try{let e=(0,Pv.execSync)('reg query "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment" /v Path',{encoding:"utf8",windowsHide:!0}),t=(0,Pv.execSync)('reg query "HKCU\\Environment" /v Path',{encoding:"utf8",windowsHide:!0}),n=nI(e),r=nI(t),i=[];return r&&i.push(r),n&&i.push(n),Pd=i.join(";"),Pd}catch(e){return null}}function nI(e){let t=e.split(`
`);for(let n of t){let r=n.trim();if(r.toLowerCase().startsWith("path")){let i=r.match(/Path\s+REG_(?:EXPAND_)?SZ\s+(.+)/i);if(i)return i[1].trim()}}return null}function Ld(e){if(!go.Platform.isWin)return e;let t=s6();if(!t)return e;let r=(e.PATH||"").split(";").filter(a=>a.length>0),i=t.split(";").filter(a=>a.length>0),o=[...r];for(let a of i)o.some(s=>s.toLowerCase()===a.toLowerCase())||o.push(a);return{...e,PATH:o.join(";")}}function Pn(e){let n=e.replace(/\\/g,"/").match(/^([A-Za-z]):(\/.*)/);if(n){let r=n[1].toLowerCase(),i=n[2];return`/mnt/${r}${i}`}return e}function iI(e){let t=e.match(/^\/mnt\/([a-zA-Z])\/(.*)/);if(t){let n=t[1].toUpperCase(),r=t[2].replace(/\//g,"\\");return`${n}:\\${r}`}return e}function Zv(e){let t=e.replace(/'/g,"'\\''");return`. ~/.profile 2>/dev/null; case \${SHELL:-/bin/sh} in */fish|*/elvish|*/nushell|*/xonsh) exec /bin/sh -l -c '${t}';; *) exec \${SHELL:-/bin/sh} -l -c '${t}';; esac`}function l6(e,t,n,r,i){if(/^\\\\/.test(n))throw new Error(`UNC paths are not supported in WSL mode: ${n}. Please use a local drive path.`);let o=Pn(n);if(o===n&&/^[A-Za-z]:[\\/]/.test(n))throw new Error(`Failed to convert Windows path to WSL format: ${n}`);let a=[];if(r){if(!/^[a-zA-Z0-9._-]+$/.test(r))throw new Error(`Invalid WSL distribution name: ${r}`);a.push("-d",r)}let s=t.map(Lv).join(" "),c=s.length>0?` ${s}`:"",d="";if(i){let l=Pn(i);d=`export PATH="${c6(l)}:$PATH"; `}let m=`${d}cd ${Lv(o)} && ${e}${c}`;return a.push("sh","-c",Zv(m)),{command:"C:\\Windows\\System32\\wsl.exe",args:a}}function c6(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function jd(e,t,n,r){var o;let i=(o=r.alwaysEscape)!=null?o:!0;if(go.Platform.isWin&&r.wslMode){let a=l6(e,t,n,r.wslDistribution,r.nodeDir);return{command:a.command,args:a.args,needsShell:!1}}if(go.Platform.isMacOS||go.Platform.isLinux){let a=jv(),s;return t.length>0||i?s=[e,...t].map(Lv).join(" "):s=e,r.nodeDir&&(s=`export PATH='${r.nodeDir.replace(/'/g,"'\\''")}':"$PATH"; ${s}`),{command:a,args:["-l","-c",s],needsShell:!1}}return t.length>0||i?{command:tI(e),args:t.map(tI),needsShell:!0}:{command:e,args:t,needsShell:!0}}function Ul(e){return e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e)}function oI(e){if(!e||e.trim().length===0)return Promise.resolve(null);let t=e.trim();return Ul(t)?Promise.resolve(t):new Promise(n=>{if(rI.Platform.isWin)(0,Zd.execFile)("where",[t],{timeout:5e3,windowsHide:!0},(r,i)=>{if(r){n(null);return}let o=i.split(`
`)[0].trim();n(o.length>0?o:null)});else{let r=jv(),i=t.replace(/'/g,"'\\''");(0,Zd.execFile)(r,["-l","-c",`which '${i}'`],{timeout:5e3},(o,a)=>{if(o){n(null);return}let s=a.split(`
`)[0].trim();n(s.length>0?s:null)})}})}function aI(e,t){if(!e||e.trim().length===0)return Promise.resolve(null);let n=e.trim();return Ul(n)?Promise.resolve(n):new Promise(r=>{let i=n.replace(/'/g,"'\\''"),o=[];t&&o.push("-d",t);let a=`which '${i}'`;o.push("sh","-c",Zv(a)),(0,Zd.execFile)("C:\\Windows\\System32\\wsl.exe",o,{timeout:5e3},(s,c)=>{if(s){r(null);return}let d=c.split(`
`)[0].trim();r(d.length>0?d:null)})})}function u6(e){if(!e)return null;let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t<=0?null:e.slice(0,t)}function qd(e){if(!e)return;let t=e.trim();if(Ul(t))return u6(t)||void 0}function sI(e,t){let n=t.replace(/\/+$/,""),r=e.replace(/\/+$/,"");return r.startsWith(n+"/")?r.slice(n.length+1):e}function Pl(e){let t=e.replace(/\\/g,"/");return/^[A-Za-z]:/.test(t)?`file:///${t}`:`file://${t}`}function lI(e,t,n,r,i,o,a,s){let c=Ne(),[d,m]=(0,Tt.useState)(null),[l,f]=(0,Tt.useState)(null),p=(0,Tt.useCallback)(async(P,V,O)=>{if((P==="newChat"?e.settings.exportSettings.autoExportOnNewChat:e.settings.exportSettings.autoExportOnCloseChat)&&V.length!==0&&O.sessionId)try{let w=new Rl(e),k=e.settings.exportSettings.openFileAfterExport,N=await w.exportToMarkdown(V,O.agentDisplayName,O.agentId,O.sessionId,O.createdAt,k);if(N){let j=P==="newChat"?"new session":"closing chat";new Xn.Notice(`[Agent Client] Chat exported to ${N}`),c.log(`Chat auto-exported before ${j}`)}}catch(w){new Xn.Notice("[Agent Client] Failed to export chat")}},[e,c]),h=Xn.Platform.isWin&&a.windowsWslMode,y=(0,Tt.useCallback)(async(P,V)=>{var k,N;t.clearError(),f(null);let O=o.length===0,L=[],w=[];if(V){for(let j of V)if(j.kind==="image"&&j.data)L.push({type:"image",data:j.data,mimeType:j.mimeType});else if(j.kind==="file"&&j.path){let F=j.path;h&&(F=Pn(F)),w.push({type:"resource_link",uri:Pl(F),name:(N=(k=j.name)!=null?k:j.path.split("/").pop())!=null?N:"file",mimeType:j.mimeType||void 0,size:j.size})}}await t.sendMessage(P,{activeNote:a.autoMentionActiveNote?r.mentions.activeNote:null,vaultBasePath:s,isAutoMentionDisabled:r.mentions.isAutoMentionDisabled,images:L.length>0?L:void 0,resourceLinks:w.length>0?w:void 0}),O&&i.sessionId&&(await n.saveSessionLocally(i.sessionId,P),c.log(`[ChatPanel] Session saved locally: ${i.sessionId}`))},[t.clearError,t.sendMessage,o.length,i.sessionId,n.saveSessionLocally,c,a.autoMentionActiveNote,r.mentions.activeNote,r.mentions.isAutoMentionDisabled,h,s]),x=(0,Tt.useCallback)(async()=>{c.log("Cancelling current operation...");let P=t.lastUserMessage;await t.cancelOperation(),P&&m(P)},[c,t.cancelOperation,t.lastUserMessage]),S=(0,Tt.useCallback)(async P=>{let V=P&&P!==i.agentId;if(o.length===0&&!V){new Xn.Notice("[Agent Client] Already a new session");return}t.isSending&&await t.cancelOperation(),c.log(`[Debug] Creating new session${V?` with agent: ${P}`:""}...`),o.length>0&&await p("newChat",o,i),r.mentions.toggleAutoMention(!1),t.clearMessages();let O=V?P:i.agentId;await t.restartSession(O),n.invalidateCache()},[o,i,c,p,t.isSending,t.cancelOperation,t.clearMessages,t.restartSession,r.mentions.toggleAutoMention,n.invalidateCache]),g=(0,Tt.useCallback)(async()=>{if(o.length===0){new Xn.Notice("[Agent Client] No messages to export");return}try{let P=new Rl(e),V=e.settings.exportSettings.openFileAfterExport,O=await P.exportToMarkdown(o,i.agentDisplayName,i.agentId,i.sessionId||"unknown",i.createdAt,V);new Xn.Notice(`[Agent Client] Chat exported to ${O}`)}catch(P){new Xn.Notice("[Agent Client] Failed to export chat"),c.error("Export error:",P)}},[o,i,e,c]),b=(0,Tt.useCallback)(async P=>{P!==i.agentId&&await S(P)},[i.agentId,S]),v=(0,Tt.useCallback)(async()=>{c.log("[ChatPanel] Restarting agent process..."),o.length>0&&await p("newChat",o,i),t.clearMessages();try{await t.forceRestartAgent(),new Xn.Notice("[Agent Client] Agent restarted")}catch(P){new Xn.Notice("[Agent Client] Failed to restart agent"),c.error("Restart error:",P)}},[c,o,i,p,t.clearMessages,t.forceRestartAgent]),_=(0,Tt.useCallback)(async P=>{await t.setMode(P)},[t.setMode]),C=(0,Tt.useCallback)(async P=>{await t.setModel(P)},[t.setModel]),E=(0,Tt.useCallback)(async(P,V)=>{await t.setConfigOption(P,V)},[t.setConfigOption]),A=(0,Tt.useCallback)(()=>{t.clearError()},[t.clearError]),T=(0,Tt.useCallback)(()=>{f(null)},[]),M=(0,Tt.useCallback)(()=>{m(null)},[]);return{handleSendMessage:y,handleStopGeneration:x,handleNewChat:S,handleExportChat:g,handleSwitchAgent:b,handleRestartAgent:v,handleSetMode:_,handleSetModel:C,handleSe
`))return null;a=o,s=t}let c={start:i,end:s,query:a};return n.log("[detectMention] Mention context:",c),c}function fI(e,t,n){let r=e.slice(0,t.start),i=e.slice(t.end),o=` @[[${n}]] `,a=r+o+i,s=t.start+o.length;return{newText:a,newCursorPos:s}}function mI(e,t){let n=/@\[\[([^\]]+)\]\]/g,r=Array.from(e.matchAll(n)),i=[],o=new Set;for(let a of r){let s=a[1];if(o.has(s))continue;o.add(s);let c=t.getAllFiles().find(d=>d.basename===s);i.push({noteTitle:s,file:c})}return i}function pI(e,t,n){let[r,i]=(0,Xe.useState)([]),[o,a]=(0,Xe.useState)(0),[s,c]=(0,Xe.useState)(null),[d,m]=(0,Xe.useState)(null),[l,f]=(0,Xe.useState)(!1),p=r.length>0&&s!==null,[h,y]=(0,Xe.useState)([]),[x,S]=(0,Xe.useState)(0),g=h.length>0,b=(0,Xe.useCallback)(w=>{f(w===void 0?k=>!k:w)},[]),v=(0,Xe.useCallback)(async(w,k)=>{let N=dI(w,k);if(!N){i([]),a(0),c(null);return}let j=await e.searchNotes(N.query);i(j),a(0),c(N)},[e,t]),_=(0,Xe.useCallback)((w,k)=>{if(!s)return w;let{newText:N}=fI(w,s,k.name);return i([]),a(0),c(null),N},[s]),C=(0,Xe.useCallback)(w=>{if(!p)return;let k=r.length-1;a(N=>w==="down"?Math.min(N+1,k):Math.max(N-1,0))},[p,r.length]),E=(0,Xe.useCallback)(()=>{i([]),a(0),c(null)},[]),A=(0,Xe.useCallback)(async()=>{let w=await e.getActiveNote();m(w)},[e]),T=(0,Xe.useCallback)((w,k)=>{let N=h.length>0;if(!w.startsWith("/")){N&&b(!1),y([]),S(0);return}let F=w.slice(0,k).slice(1);if(F.includes(" ")){y([]),S(0),b(!0);return}let K=F.toLowerCase(),ne=n.filter(ue=>ue.name.toLowerCase().includes(K));y(ne),S(0),b(!0)},[n,b,h.length]),M=(0,Xe.useCallback)((w,k)=>{let N=`/${k.name} `;return y([]),S(0),N},[]),P=(0,Xe.useCallback)(w=>{if(h.length===0)return;let k=h.length-1;S(N=>w==="down"?Math.min(N+1,k):Math.max(N-1,0))},[h.length]),V=(0,Xe.useCallback)(()=>{y([]),S(0)},[]),O=(0,Xe.useMemo)(()=>({suggestions:r,selectedIndex:o,isOpen:p,context:s,updateSuggestions:v,selectSuggestion:_,navigate:C,close:E,activeNote:d,isAutoMentionDisabled:l,toggleAutoMention:b,updateActiveNote:A}),[r,o,p,s,v,_,C,E,d,l,b,A]),L=(0,Xe.useMemo)(()=>({suggestions:h,selectedIndex:x,isOpen:g,updateSuggestions:T,selectSuggestion:M,navigate:P,close:V}),[h,x,g,T,M,P,V]);return(0,Xe.useMemo)(()=>({mentions:O,commands:L}),[O,L])}var A6=G(Ce());var d6=G(Ce());var jl=e=>{if(e==null)return null;let t=(()=>{if(typeof e=="number")return e;if(typeof e=="string"){let n=e.trim();return n.length===0||!/^-?\d+$/.test(n)?Number.NaN:Number.parseInt(n,10)}return Number.NaN})();return Number.isFinite(t)?Math.min(30,Math.max(10,Math.round(t))):null},Oa=e=>Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():"").filter(t=>t.length>0):typeof e=="string"?e.split(/\r?\n/).map(t=>t.trim()).filter(t=>t.length>0):[],ho=e=>{let t=[];if(!e)return t;if(Array.isArray(e)){for(let r of e)if(r&&typeof r=="object"){let i=r,o="key"in i?i.key:void 0,a="value"in i?i.value:void 0;typeof o=="string"&&o.trim().length>0&&t.push({key:o.trim(),value:typeof a=="string"?a:""})}}else if(typeof e=="object")for(let[r,i]of Object.entries(e))typeof r=="string"&&r.trim().length>0&&t.push({key:r.trim(),value:typeof i=="string"?i:""});let n=new Set;return t.filter(r=>n.has(r.key)?!1:(n.add(r.key),!0))},gI=e=>{let t=e&&typeof e.id=="string"&&e.id.trim().length>0?e.id.trim():"custom-agent",n=e&&typeof e.displayName=="string"&&e.displayName.trim().length>0?e.displayName.trim():t;return{id:t,displayName:n,command:e&&typeof e.command=="string"&&e.command.trim().length>0?e.command.trim():"",args:Oa(e==null?void 0:e.args),env:ho(e==null?void 0:e.env)}},hI=e=>{let t=new Set;return e.map(n=>{let r=n.id&&n.id.trim().length>0?n.id.trim():"custom-agent",i=r,o=2;for(;t.has(i);)i=`${r}-${o}`,o+=1;return t.add(i),{...n,id:i}})},vI=(e,t)=>{let n=e.env.reduce((r,{key:i,value:o})=>(r[i]=o,r),{});return{id:e.id,displayName:e.displayName,command:e.command,args:e.args,env:n,workingDirectory:t}};function tt(e,t){return typeof e=="string"?e:t}function en(e,t){return typeof e=="boolean"?e:t}function Vd(e,t,n){return typeof e!="number"||n!==void 0&&e<n?t:e}function Fd(e,t,n){return t.includes(e)?e:n}function di(e){return e&&typeof e=="object"&&!Array.isArr
`).slice(t.from.line,t.to.line+1).join(`
`),c=s.length>r;return{text:c?s.substring(0,r):s,wasTruncated:c,originalLength:s.length}}catch(i){return console.error(`Failed to read selection from ${e}:`,i),null}}function TI(e,t){return!e||t?"":e.selection?`@[[${e.name}]]:${e.selection.from.line+1}-${e.selection.to.line+1}
`:`@[[${e.name}]]
`}function II(e){return[...e.message?[{type:"text",text:e.message}]:[],...e.images||[],...e.resourceLinks||[]]}function kI(e,t){if(!(!e||t))return{noteName:e.name,notePath:e.path,selection:e.selection?{fromLine:e.selection.from.line+1,toLine:e.selection.to.line+1}:void 0}}function NI(e,t,n){let r=t?`${t}/${e}`:e;return n&&(r=Pn(r)),r}async function OI(e,t,n){let r=mI(e.message,n);return e.supportsEmbeddedContext?v6(e,t,r):y6(e,t,r)}async function v6(e,t,n){var c,d,m,l;let r=(c=e.maxNoteLength)!=null?c:CI,i=[];for(let{file:f}of n){if(!f)continue;let p=await AI(f,e.vaultBasePath,t,(d=e.convertToWsl)!=null?d:!1,r);if(!p)continue;let h=p.wasTruncated?p.content+`
[Note: Truncated from ${p.originalLength} to ${r} characters]`:p.content;i.push({type:"resource",resource:{uri:p.uri,mimeType:"text/markdown",text:h},annotations:{audience:["assistant"],priority:1,lastModified:p.lastModified}})}let o=[];if(e.activeNote&&!e.isAutoMentionDisabled){let f=await S6(e.activeNote,e.vaultBasePath,t,(m=e.convertToWsl)!=null?m:!1,(l=e.maxSelectionLength)!=null?l:EI);o.push(...f)}let a=TI(e.activeNote,e.isAutoMentionDisabled),s=[...i,...o,...e.message||a?[{type:"text",text:a+e.message}]:[],...e.images||[],...e.resourceLinks||[]];return{displayContent:II(e),agentContent:s,autoMentionContext:kI(e.activeNote,e.isAutoMentionDisabled)}}async function y6(e,t,n){var c,d,m,l;let r=(c=e.maxNoteLength)!=null?c:CI,i=[];for(let{file:f}of n){if(!f)continue;let p=await AI(f,e.vaultBasePath,t,(d=e.convertToWsl)!=null?d:!1,r);if(!p)continue;let h=p.wasTruncated?`
[Note: This note was truncated. Original length: ${p.originalLength} characters, showing first ${r} characters]`:"";i.push(`<obsidian_mentioned_note ref="${p.absolutePath}">
${p.content}${h}
</obsidian_mentioned_note>`)}if(e.activeNote&&!e.isAutoMentionDisabled){let f=await b6(e.activeNote.path,e.vaultBasePath,t,(m=e.convertToWsl)!=null?m:!1,e.activeNote.selection,(l=e.maxSelectionLength)!=null?l:EI);i.push(f)}let o=TI(e.activeNote,e.isAutoMentionDisabled),a=i.length>0?i.join(`
`)+`
`+o+e.message:o+e.message,s=[...a?[{type:"text",text:a}]:[],...e.images||[],...e.resourceLinks||[]];return{displayContent:II(e),agentContent:s,autoMentionContext:kI(e.activeNote,e.isAutoMentionDisabled)}}async function S6(e,t,n,r,i){let o=NI(e.path,t,r),a=Pl(o);if(e.selection){let s=e.selection.from.line+1,c=e.selection.to.line+1,d=await zI(e.path,e.selection,n,i);if(!d)return[{type:"text",text:`The user has selected lines ${s}-${c} in ${a}. If relevant, use the Read tool to examine the specific lines.`}];let m=d.wasTruncated?d.text+`
[Note: Truncated from ${d.originalLength} to ${i} characters]`:d.text;return[{type:"resource",resource:{uri:a,mimeType:"text/markdown",text:m},annotations:{audience:["assistant"],priority:.8,lastModified:new Date(e.modified).toISOString()}},{type:"text",text:`The user has selected lines ${s}-${c} in the above note. This is what they are currently focusing on.`}]}return[{type:"text",text:`The user has opened the note ${a} in Obsidian. This may or may not be related to the current conversation. If it seems relevant, consider using the Read tool to examine its content.`}]}async function b6(e,t,n,r,i,o){let a=NI(e,t,r);if(i){let s=i.from.line+1,c=i.to.line+1,d=await zI(e,i,n,o);if(!d)return`<obsidian_opened_note selection="lines ${s}-${c}">The user opened the note ${a} in Obsidian and is focusing on lines ${s}-${c}. This may or may not be related to the current conversation. If it seems relevant, consider using the Read tool to examine the specific lines.</obsidian_opened_note>`;let m=d.wasTruncated?`
[Note: The selection was truncated. Original length: ${d.originalLength} characters, showing first ${o} characters]`:"";return`<obsidian_opened_note selection="lines ${s}-${c}">
The user opened the note ${a} in Obsidian and selected the following text (lines ${s}-${c}):
${d.text}${m}
This is what the user is currently focusing on.
</obsidian_opened_note>`}return`<obsidian_opened_note>The user opened the note ${a} in Obsidian. This may or may not be related to the current conversation. If it seems relevant, consider using the Read tool to examine the content.</obsidian_opened_note>`}async function MI(e,t){try{return await t.sendPrompt(e.sessionId,e.agentContent),{success:!0,displayContent:e.displayContent,agentContent:e.agentContent}}catch(n){return await x6(n,e.sessionId,e.agentContent,e.displayContent,e.authMethods,t)}}async function x6(e,t,n,r,i,o){if(Gd(e))return{success:!0,displayContent:r,agentContent:n};if(Vl(e)===lt.AUTHENTICATION_REQUIRED&&i&&i.length>0){if(i.length===1){let s=await _6(t,n,r,i[0].id,o);if(s)return s}return{success:!1,displayContent:r,agentContent:n,requiresAuth:!0,error:Bd(e,t)}}return{success:!1,displayContent:r,agentContent:n,error:Bd(e,t)}}async function _6(e,t,n,r,i){try{return await i.authenticate(r)?(await i.sendPrompt(e,t),{success:!0,displayContent:n,agentContent:t,retriedSuccessfully:!0}):null}catch(o){return{success:!1,displayContent:n,agentContent:t,error:Bd(o,e)}}}var LI=require("obsidian");function DI(e,t){let n=e.content||[];if(t.content!==void 0){let r=t.content||[];r.some(o=>o.type==="diff")&&(n=n.filter(o=>o.type!=="diff")),n=[...n,...r]}return{...e,toolCallId:t.toolCallId,title:t.title!==void 0?t.title:e.title,kind:t.kind!==void 0?t.kind:e.kind,status:t.status!==void 0?t.status:e.status,content:n,locations:t.locations!==void 0?t.locations:e.locations,rawInput:t.rawInput!==void 0&&Object.keys(t.rawInput).length>0?t.rawInput:e.rawInput,permissionRequest:t.permissionRequest!==void 0?t.permissionRequest:e.permissionRequest}}function Jv(e,t){if(e.length===0||e[e.length-1].role!=="assistant"){let i={id:crypto.randomUUID(),role:"assistant",content:[t],timestamp:new Date};return[...e,i]}let r={...e[e.length-1]};if(t.type==="text"||t.type==="agent_thought"){let i=r.content.findIndex(o=>o.type===t.type);if(i>=0){let o=r.content[i];(o.type==="text"||o.type==="agent_thought")&&(r.content[i]={type:t.type,text:o.text+t.text})}else r.content.push(t)}else{let i=r.content.findIndex(o=>o.type===t.type);i>=0?r.content[i]=t:r.content.push(t)}return[...e.slice(0,-1),r]}function w6(e,t){if(e.length===0||e[e.length-1].role!=="user"){let i={id:crypto.randomUUID(),role:"user",content:[t],timestamp:new Date};return[...e,i]}let r={...e[e.length-1]};if(t.type==="text"){let i=r.content.findIndex(o=>o.type==="text");if(i>=0){let o=r.content[i];o.type==="text"&&(r.content[i]={type:"text",text:o.text+t.text})}else r.content.push(t)}else{let i=r.content.findIndex(o=>o.type===t.type);i>=0?r.content[i]=t:r.content.push(t)}return[...e.slice(0,-1),r]}function $6(e,t,n){let r=n.get(t.toolCallId);if(r!==void 0&&r<e.length){let a=e[r];if(a.content.some(c=>c.type==="tool_call"&&c.toolCallId===t.toolCallId)){let c={...a,content:a.content.map(m=>m.type==="tool_call"&&m.toolCallId===t.toolCallId?DI(m,t):m)},d=[...e];return d[r]=c,d}}let i=!1,o=e.map((a,s)=>a.content.some(d=>d.type==="tool_call"&&d.toolCallId===t.toolCallId)?(i=!0,n.set(t.toolCallId,s),{...a,content:a.content.map(d=>d.type==="tool_call"&&d.toolCallId===t.toolCallId?DI(d,t):d)}):a);return i?o:(n.set(t.toolCallId,e.length),[...e,{id:crypto.randomUUID(),role:"assistant",content:[t],timestamp:new Date}])}function Kv(e,t){t.clear(),e.forEach((n,r)=>{for(let i of n.content)i.type==="tool_call"&&t.set(i.toolCallId,r)})}function RI(e,t,n){switch(t.type){case"agent_message_chunk":return Jv(e,{type:"text",text:t.text});case"agent_thought_chunk":return Jv(e,{type:"agent_thought",text:t.text});case"user_message_chunk":return w6(e,{type:"text",text:t.text});case"tool_call":case"tool_call_update":return $6(e,{type:"tool_call",toolCallId:t.toolCallId,title:t.title,status:t.status||"pending",kind:t.kind,content:t.content,locations:t.locations,rawInput:t.rawInput,permissionRequest:t.permissionRequest},n);case"plan":return Jv(e,{type:"plan",entries:t.entries});default:return e}}function UI(e){for(let t of e)for(let n of t.content)if(n.type==="tool_call"){let r=n.permissionRequest;if(r!=null&&r.isAct
Run the following in your terminal:`,suggestion:`npm uninstall -g ${e.name} && npm install -g ${t}`};let n=M6[e.name];if(!n||!e.version)return null;try{let r=await R6(n);if(r&&Da.valid(e.version)&&Da.gt(r,e.version))return{variant:"info",title:"Agent Update Available",message:`${n}: ${e.version} \u2192 ${r}.
Run the following in your terminal:`,suggestion:`npm install -g ${n}@latest`}}catch(r){}return null}async function R6(e){var r;let n=(await(0,VI.requestUrl)({url:`https://registry.npmjs.org/${e}/latest`})).json;return n.version&&(r=Da.clean(n.version))!=null?r:null}var j6=G(Ce()),Fl=require("obsidian");var U6=G(Ce()),ty=require("obsidian"),ny=G(ve()),{useRef:HI,useEffect:BI,useImperativeHandle:P6,forwardRef:L6}=U6;function Yn({name:e,className:t}){let n=HI(null);return BI(()=>{n.current&&(0,ty.setIcon)(n.current,e)},[e]),(0,ny.jsx)("span",{ref:n,className:t})}var Yd=L6(function({iconName:t,tooltip:n,onClick:r},i){let o=HI(null);return P6(i,()=>o.current,[]),BI(()=>{o.current&&(0,ty.setIcon)(o.current,t)},[t]),(0,ny.jsx)("button",{ref:o,title:n,onClick:r,className:"clickable-icon agent-client-header-button"})});var Ge=G(ve()),{useRef:Kd,useEffect:iy}=j6;function Jd({icon:e,label:t,onClick:n}){let r=Kd(null);return iy(()=>{r.current&&(0,Fl.setIcon)(r.current,e)},[e]),(0,Ge.jsx)("div",{ref:r,className:"clickable-icon nav-action-button","aria-label":t,onClick:n})}function Z6({agentLabel:e,isUpdateAvailable:t,hasHistoryCapability:n=!1,onNewChat:r,onExportChat:i,onShowMenu:o,onOpenHistory:a}){return(0,Ge.jsx)("div",{className:"nav-header agent-client-chat-view-header",children:(0,Ge.jsxs)("div",{className:"nav-buttons-container",children:[(0,Ge.jsx)("span",{className:"agent-client-chat-view-header-title",children:e}),t&&(0,Ge.jsx)("span",{className:"agent-client-chat-view-header-update",children:"Plugin update available!"}),(0,Ge.jsx)(Jd,{icon:"plus",label:"New chat",onClick:r}),a&&(0,Ge.jsx)(Jd,{icon:"history",label:"Session history",onClick:a}),(0,Ge.jsx)(Jd,{icon:"save",label:"Export chat to Markdown",onClick:i}),(0,Ge.jsx)(Jd,{icon:"more-vertical",label:"More",onClick:o})]})})}function q6({agentLabel:e,availableAgents:t,currentAgentId:n,isUpdateAvailable:r,onAgentChange:i,onShowMenu:o,onMinimize:a,onClose:s}){let c=Kd(null),d=Kd(null),m=Kd(i);return m.current=i,iy(()=>{let l=c.current;if(l){if(t.length<=1){d.current&&(l.empty(),d.current=null);return}if(!d.current){let f=new Fl.DropdownComponent(l);d.current=f;for(let p of t)f.addOption(p.id,p.displayName);n&&f.setValue(n),f.onChange(p=>{var h;(h=m.current)==null||h.call(m,p)})}return()=>{d.current&&(l.empty(),d.current=null)}}},[t]),iy(()=>{d.current&&n&&d.current.setValue(n)},[n]),(0,Ge.jsxs)("div",{className:"agent-client-inline-header agent-client-inline-header-floating",children:[(0,Ge.jsx)("div",{className:"agent-client-inline-header-main",children:t.length>1?(0,Ge.jsxs)("div",{className:"agent-client-agent-selector",children:[(0,Ge.jsx)("div",{ref:c}),(0,Ge.jsx)("span",{className:"agent-client-agent-selector-icon",ref:l=>{l&&(0,Fl.setIcon)(l,"chevron-down")}})]}):(0,Ge.jsx)("span",{className:"agent-client-agent-label",children:e})}),r&&(0,Ge.jsx)("p",{className:"agent-client-chat-view-header-update",children:"Plugin update available!"}),(0,Ge.jsxs)("div",{className:"agent-client-inline-header-actions",children:[(0,Ge.jsx)(Yd,{iconName:"more-vertical",tooltip:"More",onClick:o}),a&&(0,Ge.jsx)(Yd,{iconName:"minimize-2",tooltip:"Minimize",onClick:a}),s&&(0,Ge.jsx)(Yd,{iconName:"x",tooltip:"Close",onClick:s})]})]})}function ry(e){return e.variant==="floating"?(0,Ge.jsx)(q6,{...e}):(0,Ge.jsx)(Z6,{...e})}var fL=G(Ce()),_k=require("obsidian");var by=G(Ce()),xy=require("obsidian");var V6=G(Ce()),Ir=require("obsidian");var GI=G(ve()),{useRef:F6,useEffect:H6}=V6;function oy({text:e,plugin:t}){let n=F6(null);return H6(()=>{var d;let r=n.current;if(!r)return;(d=r.empty)==null||d.call(r),r.classList.add("markdown-rendered");let i=new Ir.Component;i.load(),Ir.MarkdownRenderer.render(t.app,e,r,"",i);let o=t.app.vault.adapter instanceof Ir.FileSystemAdapter?t.app.vault.adapter.getBasePath():null,a=Ir.Platform.isWin&&t.settings.windowsWslMode,s=o?o.replace(/\\/g,"/").replace(/\/+$/,""):null,c=m=>{let f=m.target.closest("a.internal-link");if(f){m.preventDefault();let p=f.getAttribute("data-href");if(p){let h=decodeURIComponent(p);a&&h.startsWith("/mnt/")&&(h=iI(h));let y=h.replace(/\
`))&&(t=t.trim()),(!r.newlineIsToken||!n.includes(`
`))&&(n=n.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(t.endsWith(`
`)&&(t=t.slice(0,-1)),n.endsWith(`
`)&&(n=n.slice(0,-1))),super.equals(t,n,r)}},Y6=new vy;function yy(e,t,n){return Y6.diff(e,t,n)}function J6(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
`));let n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let i=0;i<r.length;i++){let o=r[i];i%2&&!t.newlineIsToken?n[n.length-1]+=o:n.push(o)}return n}function Sy(e,t,n,r,i,o,a){let s;a?typeof a=="function"?s={callback:a}:s=a:s={},typeof s.context=="undefined"&&(s.context=4);let c=s.context;if(s.newlineIsToken)throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");if(s.callback){let{callback:m}=s;yy(n,r,Object.assign(Object.assign({},s),{callback:l=>{let f=d(l);m(f)}}))}else return d(yy(n,r,s));function d(m){if(!m)return;m.push({value:"",lines:[]});function l(g){return g.map(function(b){return" "+b})}let f=[],p=0,h=0,y=[],x=1,S=1;for(let g=0;g<m.length;g++){let b=m[g],v=b.lines||K6(b.value);if(b.lines=v,b.added||b.removed){if(!p){let _=m[g-1];p=x,h=S,_&&(y=c>0?l(_.lines.slice(-c)):[],p-=y.length,h-=y.length)}for(let _ of v)y.push((b.added?"+":"-")+_);b.added?S+=v.length:x+=v.length}else{if(p)if(v.length<=c*2&&g<m.length-2)for(let _ of l(v))y.push(_);else{let _=Math.min(v.length,c);for(let E of l(v.slice(0,_)))y.push(E);let C={oldStart:p,oldLines:x-p+_,newStart:h,newLines:S-h+_,lines:y};f.push(C),p=0,h=0,y=[]}x+=v.length,S+=v.length}}for(let g of f)for(let b=0;b<g.lines.length;b++)g.lines[b].endsWith(`
`)?g.lines[b]=g.lines[b].slice(0,-1):(g.lines.splice(b+1,0,"\\ No newline at end of file"),b++);return{oldFileName:e,newFileName:t,oldHeader:i,newHeader:o,hunks:f}}}function K6(e){let t=e.endsWith(`
`),n=e.split(`
`).map(r=>r+`
`);return t?n.pop():n.push(n.pop().slice(0,-1)),n}var we=G(ve()),{useState:tk,useMemo:nk}=Bl,rk=Bl.memo(function({content:t,plugin:n,terminalClient:r,onApprovePermission:i}){let{kind:o,title:a,status:s,toolCallId:c,permissionRequest:d,locations:m,rawInput:l,content:f}=t,[p,h]=tk(d==null?void 0:d.selectedOptionId);Bl.useEffect(()=>{(d==null?void 0:d.selectedOptionId)!==p&&h(d==null?void 0:d.selectedOptionId)},[d==null?void 0:d.selectedOptionId]);let y=nk(()=>{let g=n.app.vault.adapter;return g instanceof ik.FileSystemAdapter?g.getBasePath():""},[n]),x=n.settings.displaySettings.showEmojis;return(0,we.jsxs)("div",{className:"agent-client-message-tool-call",children:[(0,we.jsxs)("div",{className:"agent-client-message-tool-call-header",children:[(0,we.jsxs)("div",{className:"agent-client-message-tool-call-title",children:[x&&(0,we.jsx)(Yn,{name:(g=>{switch(g){case"read":return"book-open";case"edit":return"pencil";case"delete":return"trash";case"move":return"folder-open";case"search":return"search";case"execute":return"square-terminal";case"think":return"message-circle-more";case"fetch":return"globe";case"switch_mode":return"arrow-left-right";default:return"hammer"}})(o),className:"agent-client-message-tool-call-icon"}),(0,we.jsx)("span",{className:"agent-client-message-tool-call-title-text",children:a}),s!=="completed"&&(0,we.jsx)(Yn,{name:s==="failed"?"x":"ellipsis",className:`agent-client-message-tool-call-status-icon agent-client-status-${s}`})]}),o==="execute"&&l&&typeof l.command=="string"&&(0,we.jsx)("div",{className:"agent-client-message-tool-call-command",children:(0,we.jsxs)("code",{children:[l.command,Array.isArray(l.args)&&l.args.length>0&&` ${l.args.join(" ")}`]})}),m&&m.length>0&&(0,we.jsx)("div",{className:"agent-client-message-tool-call-locations",children:m.map((g,b)=>(0,we.jsxs)("span",{className:"agent-client-message-tool-call-location",children:[sI(g.path,y),g.line!=null&&`:${g.line}`]},b))})]}),f&&f.map((g,b)=>g.type==="terminal"?(0,we.jsx)(Wd,{terminalId:g.terminalId,terminalClient:r||null,plugin:n},b):g.type==="diff"?(0,we.jsx)(nL,{diff:g,plugin:n,autoCollapse:n.settings.displaySettings.autoCollapseDiffs,collapseThreshold:n.settings.displaySettings.diffCollapseThreshold},b):null),d&&(0,we.jsx)(YI,{permissionRequest:{...d,selectedOptionId:p},toolCallId:c,plugin:n,onApprovePermission:i,onOptionSelected:h})]})});function ek(e){return e.oldText===null||e.oldText===void 0||e.oldText===""}function Q6(e){return e.map(t=>({type:t.added?"added":t.removed?"removed":"context",value:t.value}))}function eL(e,t){let n=e.filter(r=>!(t==="removed"&&r.type==="added"||t==="added"&&r.type==="removed"));return(0,we.jsx)(we.Fragment,{children:n.map((r,i)=>r.type==="added"?(0,we.jsx)("span",{className:"agent-client-diff-word-added",children:r.value},i):r.type==="removed"?(0,we.jsx)("span",{className:"agent-client-diff-word-removed",children:r.value},i):(0,we.jsx)("span",{children:r.value},i))})}var tL=3;function nL({diff:e,autoCollapse:t=!1,collapseThreshold:n=10}){let r=nk(()=>{if(ek(e))return e.newText.split(`
`).map((x,S)=>({type:"added",newLineNumber:S+1,content:x}));let m=e.oldText||"",l=Sy("old","new",m,e.newText,"","",{context:tL}),f=[],p=0,h=0;for(let y of l.hunks){l.hunks.length>1&&f.push({type:"context",content:`@@ -${y.oldStart},${y.oldLines} +${y.newStart},${y.newLines} @@`}),p=y.oldStart,h=y.newStart;for(let x of y.lines){let S=x[0],g=x.substring(1);S==="+"?f.push({type:"added",newLineNumber:h++,content:g}):S==="-"?f.push({type:"removed",oldLineNumber:p++,content:g}):f.push({type:"context",oldLineNumber:p++,newLineNumber:h++,content:g})}}for(let y=0;y<f.length-1;y++){let x=f[y],S=f[y+1];if(x.type==="removed"&&S.type==="added"){let g=hy(x.content,S.content),b=Q6(g);x.wordDiff=b,S.wordDiff=b}}return f},[e.oldText,e.newText]),i=(m,l)=>{if(m.type==="context"&&m.content.startsWith("@@"))return(0,we.jsx)("div",{className:"agent-client-diff-hunk-header",children:m.content},l);let p="agent-client-diff-line";return m.type==="added"?p+=" agent-client-diff-line-added":m.type==="removed"?p+=" agent-client-diff-line-removed":p+=" agent-client-diff-line-context",(0,we.jsx)("div",{className:p,children:(0,we.jsx)("span",{className:"agent-client-diff-line-content",children:m.wordDiff&&(m.type==="added"||m.type==="removed")?eL(m.wordDiff,m.type):m.content})},l)},o=t&&r.length>n,[a,s]=tk(o),c=a?r.slice(0,n):r,d=r.length-n;return(0,we.jsxs)("div",{className:"agent-client-tool-call-diff",children:[ek(e)?(0,we.jsx)("div",{className:"agent-client-diff-line-info",children:"New file"}):null,(0,we.jsx)("div",{className:"agent-client-tool-call-diff-content",children:c.map((m,l)=>i(m,l))}),o&&(0,we.jsxs)("div",{className:"agent-client-diff-expand-bar",onClick:()=>s(!a),children:[(0,we.jsx)("span",{className:"agent-client-diff-expand-text",children:a?`${d} more lines`:"Collapse"}),(0,we.jsx)(Yn,{name:a?"chevron-right":"chevron-up",className:"agent-client-diff-expand-icon"})]})]})}var ye=G(ve()),{useState:lk,useCallback:ok}=by;function ak({text:e,plugin:t,autoMentionContext:n}){let r=/@\[\[([^\]]+)\]\]/g,i=[];if(n){let s=n.selection?`@${n.noteName}:${n.selection.fromLine}-${n.selection.toLine}`:`@${n.noteName}`;i.push((0,ye.jsx)("span",{className:"agent-client-text-mention",onClick:()=>{t.app.workspace.openLinkText(n.notePath,"")},children:s},"auto-mention")),i.push(`
`)}let o=0,a;for(;(a=r.exec(e))!==null;){a.index>o&&i.push(e.slice(o,a.index));let s=a[1],c=t.app.vault.getMarkdownFiles().find(d=>d.basename===s);c?i.push((0,ye.jsxs)("span",{className:"agent-client-text-mention",onClick:()=>{t.app.workspace.openLinkText(c.path,"")},children:["@",s]},a.index)):i.push(`@${s}`),o=a.index+a[0].length}return o<e.length&&i.push(e.slice(o)),(0,ye.jsx)("div",{className:"agent-client-text-with-mentions",children:i})}function iL({text:e,plugin:t}){let[n,r]=lk(!1),i=t.settings.displaySettings.showEmojis;return(0,ye.jsxs)("div",{className:"agent-client-collapsible-thought",onClick:()=>r(!n),children:[(0,ye.jsxs)("div",{className:"agent-client-collapsible-thought-header",children:[i&&(0,ye.jsx)(Yn,{name:"lightbulb",className:"agent-client-collapsible-thought-label-icon"}),"Thinking",(0,ye.jsx)(Yn,{name:n?"chevron-down":"chevron-right",className:"agent-client-collapsible-thought-icon"})]}),n&&(0,ye.jsx)("div",{className:"agent-client-collapsible-thought-content",children:(0,ye.jsx)(oy,{text:e,plugin:t})})]})}function sk({content:e,plugin:t,messageId:n,messageRole:r,terminalClient:i,onApprovePermission:o}){switch(e.type){case"text":return r==="user"?(0,ye.jsx)(ak,{text:e.text,plugin:t}):(0,ye.jsx)(oy,{text:e.text,plugin:t});case"text_with_context":return(0,ye.jsx)(ak,{text:e.text,autoMentionContext:e.autoMentionContext,plugin:t});case"agent_thought":return(0,ye.jsx)(iL,{text:e.text,plugin:t});case"tool_call":return(0,ye.jsx)(rk,{content:e,plugin:t,terminalClient:i,onApprovePermission:o});case"plan":{let a=t.settings.displaySettings.showEmojis;return(0,ye.jsxs)("div",{className:"agent-client-message-plan",children:[(0,ye.jsxs)("div",{className:"agent-client-message-plan-title",children:[a&&(0,ye.jsx)(Yn,{name:"list-checks",className:"agent-client-message-plan-label-icon"}),"Plan"]}),e.entries.map((s,c)=>(0,ye.jsxs)("div",{className:`agent-client-message-plan-entry agent-client-plan-status-${s.status}`,children:[a&&(0,ye.jsx)("span",{className:`agent-client-message-plan-entry-icon agent-client-status-${s.status}`,children:(0,ye.jsx)(Yn,{name:s.status==="completed"?"check":s.status==="in_progress"?"loader":"circle"})})," ",s.content]},c))]})}case"terminal":return(0,ye.jsx)(Wd,{terminalId:e.terminalId,terminalClient:i||null,plugin:t});case"image":return(0,ye.jsx)("div",{className:"agent-client-message-image",children:(0,ye.jsx)("img",{src:`data:${e.mimeType};base64,${e.data}`,alt:"Attached image",className:"agent-client-message-image-thumbnail"})});case"resource_link":return(0,ye.jsxs)("div",{className:"agent-client-message-resource-link",children:[(0,ye.jsx)("span",{className:"agent-client-message-resource-link-icon",ref:a=>{a&&(0,xy.setIcon)(a,"file")}}),(0,ye.jsx)("span",{className:"agent-client-message-resource-link-name",children:e.name})]});default:return(0,ye.jsx)("span",{children:"Unsupported content type"})}}function rL(e){return e.filter(t=>t.type==="text"||t.type==="text_with_context").map(t=>"text"in t?t.text:"").join(`
`)}function oL({contents:e}){let[t,n]=lk(!1),r=ok(()=>{let o=rL(e);o&&navigator.clipboard.writeText(o).then(()=>{n(!0),setTimeout(()=>n(!1),2e3)}).catch(()=>{})},[e]),i=ok(o=>{o&&(0,xy.setIcon)(o,t?"check":"copy")},[t]);return(0,ye.jsx)("button",{className:"clickable-icon agent-client-message-action-button",onClick:r,"aria-label":"Copy message",ref:i})}function aL(e){let t=[],n=[];for(let r of e)r.type==="image"||r.type==="resource_link"?n.push(r):(n.length>0&&(t.push({type:"attachments",items:n}),n=[]),t.push({type:"single",item:r}));return n.length>0&&t.push({type:"attachments",items:n}),t}var ck=by.memo(function({message:t,plugin:n,terminalClient:r,onApprovePermission:i}){let o=aL(t.content);return(0,ye.jsxs)("div",{className:`agent-client-message-renderer ${t.role==="user"?"agent-client-message-user":"agent-client-message-assistant"}`,children:[o.map((a,s)=>a.type==="attachments"?(0,ye.jsx)("div",{className:"agent-client-message-images-strip",children:a.items.map((c,d)=>(0,ye.jsx)(sk,{content:c,plugin:n,messageId:t.id,messageRole:t.role,terminalClient:r,onApprovePermission:i},d))},s):(0,ye.jsx)("div",{children:(0,ye.jsx)(sk,{content:a.item,plugin:n,messageId:t.id,messageRole:t.role,terminalClient:r,onApprovePermission:i})},s)),t.content.some(a=>(a.type==="text"||a.type==="text_with_context")&&a.text)&&(0,ye.jsx)("div",{className:"agent-client-message-actions",children:(0,ye.jsx)(oL,{contents:t.content})})]})});var Nr=G(Ce(),1),bk=G(ug(),1);function yo(e,t,n){var s;let r=(s=n.initialDeps)!=null?s:[],i,o=!0;function a(){var c,d,m;let l;n.key&&((c=n.debug)!=null&&c.call(n))&&(l=Date.now());let f=e();if(!(f.length!==r.length||f.some((y,x)=>r[x]!==y)))return i;r=f;let h;if(n.key&&((d=n.debug)!=null&&d.call(n))&&(h=Date.now()),i=t(...f),n.key&&((m=n.debug)!=null&&m.call(n))){let y=Math.round((Date.now()-l)*100)/100,x=Math.round((Date.now()-h)*100)/100,S=x/16,g=(b,v)=>{for(b=String(b);b.length<v;)b=" "+b;return b};console.info(`%c\u23F1 ${g(x,5)} /${g(y,5)} ms`,`
font-size: .6rem;
font-weight: bold;
color: hsl(${Math.max(0,Math.min(120-120*S,120))}deg 100% 31%);`,n==null?void 0:n.key)}return n!=null&&n.onChange&&!(o&&n.skipInitialOnChange)&&n.onChange(i),o=!1,i}return a.updateDeps=c=>{r=c},a}function _y(e,t){if(e===void 0)throw new Error(`Unexpected undefined${t?`: ${t}`:""}`);return e}var uk=(e,t)=>Math.abs(e-t)<1.01,dk=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};var fk=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},sL=e=>e,lL=e=>{let t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1),r=[];for(let i=t;i<=n;i++)r.push(i);return r},gk=(e,t)=>{let n=e.scrollElement;if(!n)return;let r=e.targetWindow;if(!r)return;let i=a=>{let{width:s,height:c}=a;t({width:Math.round(s),height:Math.round(c)})};if(i(fk(n)),!r.ResizeObserver)return()=>{};let o=new r.ResizeObserver(a=>{let s=()=>{let c=a[0];if(c!=null&&c.borderBoxSize){let d=c.borderBoxSize[0];if(d){i({width:d.inlineSize,height:d.blockSize});return}}i(fk(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(s):s()});return o.observe(n,{box:"border-box"}),()=>{o.unobserve(n)}},mk={passive:!0};var pk=typeof window=="undefined"?!0:"onscrollend"in window,hk=(e,t)=>{let n=e.scrollElement;if(!n)return;let r=e.targetWindow;if(!r)return;let i=0,o=e.options.useScrollendEvent&&pk?()=>{}:dk(r,()=>{t(i,!1)},e.options.isScrollingResetDelay),a=m=>()=>{let{horizontal:l,isRtl:f}=e.options;i=l?n.scrollLeft*(f&&-1||1):n.scrollTop,o(),t(i,m)},s=a(!0),c=a(!1);n.addEventListener("scroll",s,mk);let d=e.options.useScrollendEvent&&pk;return d&&n.addEventListener("scrollend",c,mk),()=>{n.removeEventListener("scroll",s),d&&n.removeEventListener("scrollend",c)}};var cL=(e,t,n)=>{if(t!=null&&t.borderBoxSize){let r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]};var vk=(e,{adjustments:t=0,behavior:n},r)=>{var i,o;let a=e+t;(o=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||o.call(i,{[r.options.horizontal?"left":"top"]:a,behavior:n})},rf=class{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var o;var n,r,i;return(o=(i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))!=null?o:Date.now()},this.observer=(()=>{let n=null,r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(o=>{let a=()=>{let s=o.target,c=this.indexFromElement(s);if(!s.isConnected){this.observer.unobserve(s);return}this.shouldMeasureDuringScroll(c)&&this.resizeItem(c,this.options.measureElement(s,o,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var o;return(o=r())==null?void 0:o.observe(i,{box:"border-box"})},unobserve:i=>{var o;return(o=r())==null?void 0:o.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{Object.entries(n).forEach(([r,i])=>{typeof i=="undefined"&&delete n[r]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:sL,rangeExtractor:lL,onChange:()=>{},measureElement:cL,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,...n}},this.notify=n=>{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=yo(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,th
$${m.cost.amount.toFixed(2)}`:`${sf(m.used)} / ${sf(m.size)} tokens`,children:[Math.round(m.used/m.size*100),"%"]}),c&&c.length>0?(0,qt.jsx)("div",{ref:y,className:"agent-client-config-options-container"}):(0,qt.jsxs)(qt.Fragment,{children:[i&&i.availableModes.length>1&&(0,qt.jsxs)("div",{className:"agent-client-mode-selector",title:(M=(T=i.availableModes.find(O=>O.id===i.currentModeId))==null?void 0:T.description)!=null?M:"Select mode",children:[(0,qt.jsx)("div",{ref:p}),(0,qt.jsx)("span",{className:"agent-client-mode-selector-icon",ref:O=>{O&&(0,Or.setIcon)(O,"chevron-down")}})]}),a&&a.availableModels.length>1&&(0,qt.jsxs)("div",{className:"agent-client-model-selector",title:(V=(P=a.availableModels.find(O=>O.modelId===a.currentModelId))==null?void 0:P.description)!=null?V:"Select model",children:[(0,qt.jsx)("div",{ref:h}),(0,qt.jsx)("span",{className:"agent-client-model-selector-icon",ref:O=>{O&&(0,Or.setIcon)(O,"chevron-down")}})]})]}),(0,qt.jsx)("button",{ref:f,onClick:r,disabled:t,className:`agent-client-chat-send-button ${e?"sending":""} ${t?"agent-client-disabled":""}`,title:l?e?"Stop generation":"Send message":"Connecting..."})]})}var vt=G(ve()),{useRef:cf,useState:Ey,useEffect:lf,useCallback:ct,useMemo:wL}=_L,Ik=5,$L=Ik*1024*1024,Ay=10,Tk=["image/png","image/jpeg","image/gif","image/webp"];function CL(e,t){let n=cf(-1),r=cf(null),i=wL(()=>e.filter(s=>s.role==="user").map(s=>{let c=s.content.find(d=>d.type==="text"||d.type==="text_with_context");return c&&"text"in c?c.text:""}).filter(s=>s.trim()!==""),[e]),o=ct((s,c)=>{if(!c||s.nativeEvent.isComposing||i.length===0)return!1;if(n.current!==-1&&(s.key==="ArrowLeft"||s.key==="ArrowRight"||r.current!==null&&c.value!==r.current))return n.current=-1,r.current=null,!1;if(s.key==="ArrowUp"){if(c.value.trim()!==""&&n.current===-1)return!1;s.preventDefault();let d=n.current+1;if(d>=i.length)return!0;n.current=d;let m=i[i.length-1-d];return r.current=m,t(m),window.setTimeout(()=>{c.selectionStart=m.length,c.selectionEnd=m.length},0),!0}if(s.key==="ArrowDown"){let d=n.current;if(d===-1)return!1;s.preventDefault();let m=d-1;if(n.current=m,m===-1)r.current=null,t("");else{let l=i[i.length-1-m];r.current=l,t(l),window.setTimeout(()=>{c.selectionStart=l.length,c.selectionEnd=l.length},0)}return!0}return!1},[i,t]),a=ct(()=>{n.current=-1,r.current=null},[]);return{handleHistoryKeyDown:o,resetHistory:a}}function kk({isSending:e,isSessionReady:t,isRestoringSession:n,agentLabel:r,availableCommands:i,autoMentionEnabled:o,restoredMessage:a,suggestions:s,plugin:c,view:d,onSendMessage:m,onStopGeneration:l,onRestoredMessageConsumed:f,modes:p,onModeChange:h,models:y,onModelChange:x,configOptions:S,onConfigOptionChange:g,usage:b,supportsImages:v=!1,agentId:_,inputValue:C,onInputChange:E,attachedFiles:A,onAttachedFilesChange:T,errorInfo:M,onClearError:P,agentUpdateNotification:V,onClearAgentUpdate:O,messages:L}){var $s;let{mentions:w,commands:k}=s,N=Ne(),j=Tr(c),F=c.settings.displaySettings.showEmojis,K=($s=c.app.vault.getConfig("spellcheck"))!=null?$s:!0,[ne,ue]=Ey(null),[Ue,ft]=Ey(""),[Wn,wt]=Ey(!1),{handleHistoryKeyDown:Qn,resetHistory:No}=CL(L,E),mt=cf(null),xi=cf(0);lf(()=>{T([])},[_,T]);let Oo=ct(q=>{if(q.length===0)return;let Q=Ay-A.length;if(Q<=0){new mi.Notice(`[Agent Client] Maximum ${Ay} attachments allowed`);return}let se=q.slice(0,Q);se.length<q.length&&new mi.Notice(`[Agent Client] Maximum ${Ay} attachments allowed`),T([...A,...se])},[A,T]),Cp=ct(q=>{T(A.filter(Q=>Q.id!==q))},[A,T]),Mc=ct(async q=>new Promise((Q,se)=>{let pe=new FileReader;pe.onload=()=>{let _n=pe.result.split(",")[1];Q(_n)},pe.onerror=se,pe.readAsDataURL(q)}),[]),Mo=ct(async q=>{let Q=[];for(let se of q){if(se.size>$L){new mi.Notice(`[Agent Client] Image too large (max ${Ik}MB)`);continue}try{let pe=await Mc(se);Q.push({id:crypto.randomUUID(),kind:"image",data:pe,mimeType:se.type})}catch(pe){console.error("Failed to convert image:",pe),new mi.Notice("[Agent Client] Failed to attach image")}}return Q},[Mc]),Ji=ct(q=>{let{webUtils:Q}=require("electron"),se=[];for(let pe of q){let St=Q.getPathForFile(pe);if(!St
--another=value`).setValue(this.formatArgs(r.args)).onChange(async c=>{this.plugin.settings.customAgents[i].args=this.parseArgs(c),await this.plugin.saveSettings()}),s.inputEl.rows=3}),new J.Setting(o).setName("Environment variables").setDesc("Enter KEY=VALUE pairs, one per line. (Stored as plain text)").addTextArea(s=>{s.setPlaceholder("TOKEN=...").setValue(this.formatEnv(r.env)).onChange(async c=>{this.plugin.settings.customAgents[i].env=this.parseEnv(c),await this.plugin.saveSettings()}),s.inputEl.rows=3})}generateCustomAgentDisplayName(){let n="Custom agent",r=new Set;r.add(this.plugin.settings.claude.displayName||this.plugin.settings.claude.id),r.add(this.plugin.settings.codex.displayName||this.plugin.settings.codex.id),r.add(this.plugin.settings.gemini.displayName||this.plugin.settings.gemini.id);for(let a of this.plugin.settings.customAgents)r.add(a.displayName||a.id);if(!r.has(n))return n;let i=2,o=`${n} ${i}`;for(;r.has(o);)i+=1,o=`${n} ${i}`;return o}generateCustomAgentId(){let n="custom-agent",r=new Set(this.plugin.settings.customAgents.map(a=>a.id));if(!r.has(n))return n;let i=2,o=`${n}-${i}`;for(;r.has(o);)i+=1,o=`${n}-${i}`;return o}addInstallHint(n,r){let i=`npm install -g ${r}@latest`,o=document.createDocumentFragment();o.append("Not installed? Run in terminal: "),o.appendChild(document.createElement("code")).textContent=i,new J.Setting(n).setDesc(o).addButton(a=>{a.setButtonText("Copy").onClick(()=>{navigator.clipboard.writeText(i).then(()=>{a.setButtonText("Copied!"),setTimeout(()=>{a.setButtonText("Copy")},1500)},()=>{})})})}addAutoDetectButton(n,r,i){n.addButton(o=>{let a=J.Platform.isWin&&this.plugin.settings.windowsWslMode,s=J.Platform.isWin&&!a?"where":"which";o.setButtonText("Auto-detect").setTooltip(`Run \`${s} ${r}\` to find the path`).onClick(async()=>{o.setButtonText("Detecting\u2026"),o.setDisabled(!0);try{let c=a?await aI(r,this.plugin.settings.windowsWslDistribution||void 0):await oI(r);c?(await i(c),this.display()):(o.setButtonText("Not found"),setTimeout(()=>{o.setButtonText("Auto-detect"),o.setDisabled(!1)},2e3))}catch(c){o.setButtonText("Error"),setTimeout(()=>{o.setButtonText("Auto-detect"),o.setDisabled(!1)},2e3)}})})}formatArgs(n){return n.join(`
`)}parseArgs(n){return n.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0)}formatEnv(n){return n.map(r=>{var i;return`${r.key}=${(i=r.value)!=null?i:""}`}).join(`
`)}parseEnv(n){let r=[];for(let i of n.split(/\r?\n/)){let o=i.trim();if(!o)continue;let a=o.indexOf("=");if(a===-1)continue;let s=o.slice(0,a).trim(),c=o.slice(a+1).trim();s&&r.push({key:s,value:c})}return ho(r)}};var a$=require("child_process");var u={};ei(u,{$brand:()=>_f,$input:()=>ex,$output:()=>Qb,NEVER:()=>Dy,TimePrecision:()=>rx,ZodAny:()=>X_,ZodArray:()=>W_,ZodBase64:()=>Ym,ZodBase64URL:()=>Jm,ZodBigInt:()=>gs,ZodBigIntFormat:()=>Qm,ZodBoolean:()=>ps,ZodCIDRv4:()=>Gm,ZodCIDRv6:()=>Xm,ZodCUID:()=>jm,ZodCUID2:()=>Zm,ZodCatch:()=>bw,ZodCodec:()=>sp,ZodCustom:()=>Ac,ZodCustomStringFormat:()=>fs,ZodDate:()=>_c,ZodDefault:()=>pw,ZodDiscriminatedUnion:()=>ew,ZodE164:()=>Km,ZodEmail:()=>Um,ZodEmoji:()=>Pm,ZodEnum:()=>us,ZodError:()=>dZ,ZodExactOptional:()=>dw,ZodFile:()=>cw,ZodFirstPartyTypeKind:()=>Nw,ZodFunction:()=>Tw,ZodGUID:()=>vc,ZodIPv4:()=>Hm,ZodIPv6:()=>Bm,ZodISODate:()=>km,ZodISODateTime:()=>Im,ZodISODuration:()=>Om,ZodISOTime:()=>Nm,ZodIntersection:()=>tw,ZodIssueCode:()=>mZ,ZodJWT:()=>Wm,ZodKSUID:()=>Fm,ZodLazy:()=>Ew,ZodLiteral:()=>lw,ZodMAC:()=>Z_,ZodMap:()=>aw,ZodNaN:()=>_w,ZodNanoID:()=>Lm,ZodNever:()=>J_,ZodNonOptional:()=>op,ZodNull:()=>B_,ZodNullable:()=>mw,ZodNumber:()=>ms,ZodNumberFormat:()=>To,ZodObject:()=>$c,ZodOptional:()=>rp,ZodPipe:()=>ap,ZodPrefault:()=>hw,ZodPromise:()=>zw,ZodReadonly:()=>ww,ZodRealError:()=>on,ZodRecord:()=>Ec,ZodSet:()=>sw,ZodString:()=>ds,ZodStringFormat:()=>Me,ZodSuccess:()=>Sw,ZodSymbol:()=>F_,ZodTemplateLiteral:()=>Cw,ZodTransform:()=>uw,ZodTuple:()=>iw,ZodType:()=>fe,ZodULID:()=>qm,ZodURL:()=>xc,ZodUUID:()=>Si,ZodUndefined:()=>H_,ZodUnion:()=>Cc,ZodUnknown:()=>Y_,ZodVoid:()=>K_,ZodXID:()=>Vm,ZodXor:()=>Q_,_ZodString:()=>Rm,_default:()=>gw,_function:()=>_O,any:()=>eO,array:()=>wc,base64:()=>UN,base64url:()=>PN,bigint:()=>YN,boolean:()=>V_,catch:()=>xw,check:()=>wO,cidrv4:()=>DN,cidrv6:()=>RN,clone:()=>Vt,codec:()=>SO,coerce:()=>lp,config:()=>We,core:()=>yi,cuid:()=>AN,cuid2:()=>zN,custom:()=>$O,date:()=>nO,decode:()=>M_,decodeAsync:()=>R_,describe:()=>CO,discriminatedUnion:()=>lO,e164:()=>LN,email:()=>vN,emoji:()=>CN,encode:()=>O_,encodeAsync:()=>D_,endsWith:()=>ts,enum:()=>np,exactOptional:()=>fw,file:()=>gO,flattenError:()=>oc,float32:()=>HN,float64:()=>BN,formatError:()=>ac,fromJSONSchema:()=>NO,function:()=>_O,getErrorMap:()=>gZ,globalRegistry:()=>It,gt:()=>hi,gte:()=>Ft,guid:()=>yN,hash:()=>FN,hex:()=>VN,hostname:()=>qN,httpUrl:()=>$N,includes:()=>Qa,instanceof:()=>AO,int:()=>Dm,int32:()=>GN,int64:()=>JN,intersection:()=>nw,ipv4:()=>NN,ipv6:()=>MN,iso:()=>Ao,json:()=>TO,jwt:()=>jN,keyof:()=>iO,ksuid:()=>kN,lazy:()=>Aw,length:()=>Eo,literal:()=>pO,locales:()=>wo,looseObject:()=>aO,looseRecord:()=>uO,lowercase:()=>Ka,lt:()=>gi,lte:()=>xn,mac:()=>ON,map:()=>dO,maxLength:()=>Co,maxSize:()=>jr,meta:()=>EO,mime:()=>ns,minLength:()=>Yi,minSize:()=>vi,multipleOf:()=>Lr,nan:()=>yO,nanoid:()=>EN,nativeEnum:()=>mO,negative:()=>bm,never:()=>ep,nonnegative:()=>_m,nonoptional:()=>yw,nonpositive:()=>xm,normalize:()=>is,null:()=>G_,nullable:()=>Sc,nullish:()=>hO,number:()=>q_,object:()=>rO,optional:()=>yc,overwrite:()=>Kn,parse:()=>T_,parseAsync:()=>I_,partialRecord:()=>cO,pipe:()=>bc,positive:()=>Sm,prefault:()=>vw,preprocess:()=>IO,prettifyError:()=>Gy,promise:()=>xO,property:()=>wm,readonly:()=>$w,record:()=>ow,refine:()=>Iw,regex:()=>Ja,regexes:()=>bn,registry:()=>Wf,safeDecode:()=>P_,safeDecodeAsync:()=>j_,safeEncode:()=>U_,safeEncodeAsync:()=>L_,safeParse:()=>k_,safeParseAsync:()=>N_,set:()=>fO,setErrorMap:()=>pZ,size:()=>$o,slugify:()=>ss,startsWith:()=>es,strictObject:()=>oO,string:()=>Mm,stringFormat:()=>ZN,stringbool:()=>zO,success:()=>vO,superRefine:()=>kw,symbol:()=>WN,templateLiteral:()=>bO,toJSONSchema:()=>Am,toLowerCase:()=>os,toUpperCase:()=>as,transform:()=>ip,treeifyError:()=>By,trim:()=>rs,tuple:()=>rw,uint32:()=>XN,uint64:()=>KN,ulid:()=>TN,undefined:()=>QN,union:()=>tp,unknown:()=>zo,uppercase:()=>Wa,url:()=>wN,util:()=>U,uuid:()=>SN,uuidv4:()=>bN,uuidv6:()=>xN,uuidv7:()=>_N,void:()=>tO,xid:()=>IN,xor:()=>sO});var yi={};ei(yi,{$ZodAny:()=>xb,$ZodArray:()=>Eb
`)}var Fa=e=>(t,n,r,i)=>{var s;let o=r?Object.assign(r,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},o);if(a instanceof Promise)throw new Jn;if(a.issues.length){let c=new((s=i==null?void 0:i.Err)!=null?s:e)(a.issues.map(d=>nn(d,o,We())));throw $f(c,i==null?void 0:i.callee),c}return a.value},Cf=Fa(rn),Ha=e=>async(t,n,r,i)=>{var s;let o=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},o);if(a instanceof Promise&&(a=await a),a.issues.length){let c=new((s=i==null?void 0:i.Err)!=null?s:e)(a.issues.map(d=>nn(d,o,We())));throw $f(c,i==null?void 0:i.callee),c}return a.value},Ef=Ha(rn),Ba=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new Jn;return o.issues.length?{success:!1,error:new(e!=null?e:rc)(o.issues.map(a=>nn(a,i,We())))}:{success:!0,data:o.value}},Xy=Ba(rn),Ga=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(a=>nn(a,i,We())))}:{success:!0,data:o.value}},Yy=Ga(rn),Af=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Fa(e)(t,n,i)},uj=Af(rn),zf=e=>(t,n,r)=>Fa(e)(t,n,r),dj=zf(rn),Tf=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Ha(e)(t,n,i)},fj=Tf(rn),If=e=>async(t,n,r)=>Ha(e)(t,n,r),mj=If(rn),kf=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Ba(e)(t,n,i)},pj=kf(rn),Nf=e=>(t,n,r)=>Ba(e)(t,n,r),gj=Nf(rn),Of=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Ga(e)(t,n,i)},hj=Of(rn),Mf=e=>async(t,n,r)=>Ga(e)(t,n,r),vj=Mf(rn);var bn={};ei(bn,{base64:()=>dS,base64url:()=>Df,bigint:()=>vS,boolean:()=>SS,browserEmail:()=>Cj,cidrv4:()=>cS,cidrv6:()=>uS,cuid:()=>Jy,cuid2:()=>Ky,date:()=>mS,datetime:()=>gS,domain:()=>zj,duration:()=>nS,e164:()=>fS,email:()=>rS,emoji:()=>oS,extendedDuration:()=>yj,guid:()=>iS,hex:()=>Tj,hostname:()=>Aj,html5Email:()=>_j,idnEmail:()=>$j,integer:()=>yS,ipv4:()=>aS,ipv6:()=>sS,ksuid:()=>eS,lowercase:()=>_S,mac:()=>lS,md5_base64:()=>kj,md5_base64url:()=>Nj,md5_hex:()=>Ij,nanoid:()=>tS,null:()=>bS,number:()=>Rf,rfc5322Email:()=>wj,sha1_base64:()=>Mj,sha1_base64url:()=>Dj,sha1_hex:()=>Oj,sha256_base64:()=>Uj,sha256_base64url:()=>Pj,sha256_hex:()=>Rj,sha384_base64:()=>jj,sha384_base64url:()=>Zj,sha384_hex:()=>Lj,sha512_base64:()=>Vj,sha512_base64url:()=>Fj,sha512_hex:()=>qj,string:()=>hS,time:()=>pS,ulid:()=>Wy,undefined:()=>xS,unicodeEmail:()=>Yk,uppercase:()=>wS,uuid:()=>xo,uuid4:()=>Sj,uuid6:()=>bj,uuid7:()=>xj,xid:()=>Qy});var Jy=/^[cC][^\s-]{8,}$/,Ky=/^[0-9a-z]+$/,Wy=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Qy=/^[0-9a-vA-V]{20}$/,eS=/^[A-Za-z0-9]{27}$/,tS=/^[a-zA-Z0-9_-]{21}$/,nS=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,yj=/^[-+]?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)?)??$/,iS=/^([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})$/,xo=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[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|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Sj=xo(4),bj=xo(6),xj=xo(7),rS=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_j=/^[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])?)*$/,wj=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,Yk=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,$j
`).filter(a=>a),i=Math.min(...r.map(a=>a.length-a.trimStart().length)),o=r.map(a=>a.slice(i)).map(a=>" ".repeat(this.indent*2)+a);for(let a of o)this.content.push(a)}compile(){var o;let t=Function,n=this==null?void 0:this.args,i=[...((o=this==null?void 0:this.content)!=null?o:[""]).map(a=>` ${a}`)];return new t(...n,i.join(`
`))}};var qS={major:4,minor:3,patch:6};var oe=$("$ZodType",(e,t)=>{var i,o,a;var n;e!=null||(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=qS;let r=[...(i=e._zod.def.checks)!=null?i:[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(let s of r)for(let c of s._zod.onattach)c(e);if(r.length===0)(o=(n=e._zod).deferred)!=null||(n.deferred=[]),(a=e._zod.deferred)==null||a.push(()=>{e._zod.run=e._zod.parse});else{let s=(d,m,l)=>{let f=Pr(d),p;for(let h of m){if(h._zod.def.when){if(!h._zod.def.when(d))continue}else if(f)continue;let y=d.issues.length,x=h._zod.check(d);if(x instanceof Promise&&(l==null?void 0:l.async)===!1)throw new Jn;if(p||x instanceof Promise)p=(p!=null?p:Promise.resolve()).then(async()=>{await x,d.issues.length!==y&&(f||(f=Pr(d,y)))});else{if(d.issues.length===y)continue;f||(f=Pr(d,y))}}return p?p.then(()=>d):d},c=(d,m,l)=>{if(Pr(d))return d.aborted=!0,d;let f=s(m,r,l);if(f instanceof Promise){if(l.async===!1)throw new Jn;return f.then(p=>e._zod.parse(p,l))}return e._zod.parse(f,l)};e._zod.run=(d,m)=>{if(m.skipChecks)return e._zod.parse(d,m);if(m.direction==="backward"){let f=e._zod.parse({value:d.value,issues:[]},{...m,skipChecks:!0});return f instanceof Promise?f.then(p=>c(p,d,m)):c(f,d,m)}let l=e._zod.parse(d,m);if(l instanceof Promise){if(m.async===!1)throw new Jn;return l.then(f=>s(f,r,m))}return s(l,r,m)}}me(e,"~standard",()=>({validate:s=>{var c;try{let d=Xy(e,s);return d.success?{value:d.data}:{issues:(c=d.error)==null?void 0:c.issues}}catch(d){return Yy(e,s).then(m=>{var l;return m.success?{value:m.data}:{issues:(l=m.error)==null?void 0:l.issues}})}},vendor:"zod",version:1}))}),_o=$("$ZodString",(e,t)=>{var n,r,i;oe.init(e,t),e._zod.pattern=(i=[...(r=(n=e==null?void 0:e._zod.bag)==null?void 0:n.patterns)!=null?r:[]].pop())!=null?i:hS(e._zod.bag),e._zod.parse=(o,a)=>{if(t.coerce)try{o.value=String(o.value)}catch(s){}return typeof o.value=="string"||o.issues.push({expected:"string",code:"invalid_type",input:o.value,inst:e}),o}}),Oe=$("$ZodStringFormat",(e,t)=>{Xa.init(e,t),_o.init(e,t)}),FS=$("$ZodGUID",(e,t)=>{var n;(n=t.pattern)!=null||(t.pattern=iS),Oe.init(e,t)}),HS=$("$ZodUUID",(e,t)=>{var n,r;if(t.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(o===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);(n=t.pattern)!=null||(t.pattern=xo(o))}else(r=t.pattern)!=null||(t.pattern=xo());Oe.init(e,t)}),BS=$("$ZodEmail",(e,t)=>{var n;(n=t.pattern)!=null||(t.pattern=rS),Oe.init(e,t)}),GS=$("$ZodURL",(e,t)=>{Oe.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),XS=$("$ZodEmoji",(e,t)=>{var n;(n=t.pattern)!=null||(t.pattern=oS()),Oe.init(e,t)}),YS=$("$ZodNanoID",(e,t)=>{var n;(n=t.pattern)!=null||(t.pattern=tS),Oe.init(e,t)}),JS=$("$ZodCUID",(e,t)=>{var n;(n=t.pattern)!=null||(t.pattern=Jy),Oe.init(e,t)}),KS=$("$ZodCUID2",(e,t)=>{var n;(n=t.pattern)!=null||(t.pattern=Ky),Oe.init(e,t)}),WS=$("$ZodULID",(e,t)=>{var n;(n=t.pattern)!=null||(t.pattern=Wy),Oe.init(e,t)}),QS=$("$ZodXID",(e,t)=>{var n;(n=t.pattern)!=null||(t.pattern=Qy),Oe.init(e,t)}),eb=$("$ZodKSUID",(e,t)=>{var n;(n=t.pattern)!=null||(t.pattern=eS),Oe.init(e,t)}),tb=$("$ZodISODateTime",(e,t)=>{var n;(n=t.pattern)!=null||(t.pattern=gS(t)),Oe.init(e,t)}),nb=$("$ZodISODate",(e,t)=>{var n;(n=t.pattern)!=null||(t.pattern=mS),Oe.init(e,t)}),ib=$("$ZodISOTime",(e,t)=>{var n;(n=t.pattern)!=null||(t.pattern=pS(t)),Oe.init(e,t)}),rb=$("$ZodISODuration",(e,t)=>{var n;(n=t.pattern)!=null||(t.patte
if (${_}.issues.length) {
if (${C} in input) {
payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
...iss,
path: iss.path ? [${C}, ...iss.path] : [${C}]
})));
}
}
if (${_}.value === undefined) {
if (${C} in input) {
newResult[${C}] = undefined;
}
} else {
newResult[${C}] = ${_}.value;
}
`):p.write(`
if (${_}.issues.length) {
payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
...iss,
path: iss.path ? [${C}, ...iss.path] : [${C}]
})));
}
if (${_}.value === undefined) {
if (${C} in input) {
newResult[${C}] = undefined;
}
} else {
newResult[${C}] = ${_}.value;
}
`)}p.write("payload.value = newResult;"),p.write("return payload;");let g=p.compile();return(v,_)=>g(f,v,_)},o,a=bo,s=!Kl.jitless,d=s&&jy.value,m=t.catchall,l;e._zod.parse=(f,p)=>{l!=null||(l=r.value);let h=f.value;return a(h)?s&&d&&(p==null?void 0:p.async)===!1&&p.jitless!==!0?(o||(o=i(t.shape)),f=o(f,p),m?g1([],h,f,p,l,e):f):n(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),f)}});function n1(e,t,n,r){for(let o of e)if(o.issues.length===0)return t.value=o.value,t;let i=e.filter(o=>!Pr(o));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(a=>nn(a,r,We())))}),t)}var dc=$("$ZodUnion",(e,t)=>{oe.init(e,t),me(e._zod,"optin",()=>t.options.some(i=>i._zod.optin==="optional")?"optional":void 0),me(e._zod,"optout",()=>t.options.some(i=>i._zod.optout==="optional")?"optional":void 0),me(e._zod,"values",()=>{if(t.options.every(i=>i._zod.values))return new Set(t.options.flatMap(i=>Array.from(i._zod.values)))}),me(e._zod,"pattern",()=>{if(t.options.every(i=>i._zod.pattern)){let i=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${i.map(o=>ec(o.source)).join("|")})$`)}});let n=t.options.length===1,r=t.options[0]._zod.run;e._zod.parse=(i,o)=>{if(n)return r(i,o);let a=!1,s=[];for(let c of t.options){let d=c._zod.run({value:i.value,issues:[]},o);if(d instanceof Promise)s.push(d),a=!0;else{if(d.issues.length===0)return d;s.push(d)}}return a?Promise.all(s).then(c=>n1(c,i,e,o)):n1(s,i,e,o)}});function i1(e,t,n,r){let i=e.filter(o=>o.issues.length===0);return i.length===1?(t.value=i[0].value,t):(i.length===0?t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(a=>nn(a,r,We())))}):t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:[],inclusive:!1}),t)}var zb=$("$ZodXor",(e,t)=>{dc.init(e,t),t.inclusive=!1;let n=t.options.length===1,r=t.options[0]._zod.run;e._zod.parse=(i,o)=>{if(n)return r(i,o);let a=!1,s=[];for(let c of t.options){let d=c._zod.run({value:i.value,issues:[]},o);d instanceof Promise?(s.push(d),a=!0):s.push(d)}return a?Promise.all(s).then(c=>i1(c,i,e,o)):i1(s,i,e,o)}}),Tb=$("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,dc.init(e,t);let n=e._zod.parse;me(e._zod,"propValues",()=>{let i={};for(let o of t.options){let a=o._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(let[s,c]of Object.entries(a)){i[s]||(i[s]=new Set);for(let d of c)i[s].add(d)}}return i});let r=qa(()=>{var a;let i=t.options,o=new Map;for(let s of i){let c=(a=s._zod.propValues)==null?void 0:a[t.discriminator];if(!c||c.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let d of c){if(o.has(d))throw new Error(`Duplicate discriminator value "${String(d)}"`);o.set(d,s)}}return o});e._zod.parse=(i,o)=>{let a=i.value;if(!bo(a))return i.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),i;let s=r.value.get(a==null?void 0:a[t.discriminator]);return s?s._zod.run(i,o):t.unionFallback?n(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:a,path:[t.discriminator],inst:e}),i)}}),Ib=$("$ZodIntersection",(e,t)=>{oe.init(e,t),e._zod.parse=(n,r)=>{let i=n.value,o=t.left._zod.run({value:i,issues:[]},r),a=t.right._zod.run({value:i,issues:[]},r);return o instanceof Promise||a instanceof Promise?Promise.all([o,a]).then(([c,d])=>r1(n,c,d)):r1(n,o,a)}});function VS(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Ur(e)&&Ur(t)){let n=Object.keys(t),r=Object.keys(e).filter(o=>n.indexOf(o)!==-1),i={...e,...t};for(let o of r){let a=VS(e[o],t[o]);if(!a.valid)return{valid:!1,mergeErrorPath:[o,...a.mergeErrorPath]};i[o]=a.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],o=t[r],a=VS(i,o);if(!a.valid)return{valid:!1,m
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let m of e.seen.entries()){let l=m[1];if(t===m[0]){o(m);continue}if(e.external){let p=(c=e.external.registry.get(m[0]))==null?void 0:c.id;if(t!==m[0]&&p){o(m);continue}}if((d=e.metadataRegistry.get(m[0]))==null?void 0:d.id){o(m);continue}if(l.cycle){o(m);continue}if(l.count>1&&e.reused==="ref"){o(m);continue}}}function Vr(e,t){var a,s,c,d,m;let n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=l=>{var S,g,b;let f=e.seen.get(l);if(f.ref===null)return;let p=(S=f.def)!=null?S:f.schema,h={...p},y=f.ref;if(f.ref=null,y){r(y);let v=e.seen.get(y),_=v.schema;if(_.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(p.allOf=(g=p.allOf)!=null?g:[],p.allOf.push(_)):Object.assign(p,_),Object.assign(p,h),l._zod.parent===y)for(let E in p)E==="$ref"||E==="allOf"||E in h||delete p[E];if(_.$ref&&v.def)for(let E in p)E==="$ref"||E==="allOf"||E in v.def&&JSON.stringify(p[E])===JSON.stringify(v.def[E])&&delete p[E]}let x=l._zod.parent;if(x&&x!==y){r(x);let v=e.seen.get(x);if(v!=null&&v.schema.$ref&&(p.$ref=v.schema.$ref,v.def))for(let _ in p)_==="$ref"||_==="allOf"||_ in v.def&&JSON.stringify(p[_])===JSON.stringify(v.def[_])&&delete p[_]}e.override({zodSchema:l,jsonSchema:p,path:(b=f.path)!=null?b:[]})};for(let l of[...e.seen.entries()].reverse())r(l[0]);let i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,(a=e.external)!=null&&a.uri){let l=(s=e.external.registry.get(t))==null?void 0:s.id;if(!l)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(l)}Object.assign(i,(c=n.def)!=null?c:n.schema);let o=(m=(d=e.external)==null?void 0:d.defs)!=null?m:{};for(let l of e.seen.entries()){let f=l[1];f.def&&f.defId&&(o[f.defId]=f.def)}e.external||Object.keys(o).length>0&&(e.target==="draft-2020-12"?i.$defs=o:i.definitions=o);try{let l=JSON.parse(JSON.stringify(i));return Object.defineProperty(l,"~standard",{value:{...t["~standard"],jsonSchema:{input:cs(t,"input",e.processors),output:cs(t,"output",e.processors)}},enumerable:!1,writable:!1}),l}catch(l){throw new Error("Error converting schema to JSON.")}}function Ht(e,t){let n=t!=null?t:{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Ht(r.element,n);if(r.type==="set")return Ht(r.valueType,n);if(r.type==="lazy")return Ht(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Ht(r.innerType,n);if(r.type==="intersection")return Ht(r.left,n)||Ht(r.right,n);if(r.type==="record"||r.type==="map")return Ht(r.keyType,n)||Ht(r.valueType,n);if(r.type==="pipe")return Ht(r.in,n)||Ht(r.out,n);if(r.type==="object"){for(let i in r.shape)if(Ht(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(let i of r.options)if(Ht(i,n))return!0;return!1}if(r.type==="tuple"){for(let i of r.items)if(Ht(i,n))return!0;return!!(r.rest&&Ht(r.rest,n))}return!1}var jx=(e,t={})=>n=>{let r=Zr({...n,processors:t});return $e(e,r),qr(r,e),Vr(r,e)},cs=(e,t,n={})=>r=>{let{libraryOptions:i,target:o}=r!=null?r:{},a=Zr({...i!=null?i:{},target:o,io:t,processors:n});return $e(e,a),qr(a,e),Vr(a,e)};var cZ={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Zx=(e,t,n,r)=>{var m;let i=n;i.type="string";let{minimum:o,maximum:a,format:s,patterns:c,contentEncoding:d}=e._zod.bag;if(typeof o=="number"&&(i.minLength=o),typeof a=="number"&&(i.maxLength=a),s&&(i.format=(m=cZ[s])!=null?m:s,i.format===""&&delete i.format,s==="time"&&delete i.format),d&&(i.contentEncoding=d),c&&c.size>0){let l=[...c];l.length===1?i.pattern=l[0].source:l.length>1&&(i.allOf=[...l.map(f=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern
`);s=l.pop()||"";for(let f of l){let p=f.trim();if(p)try{let h=JSON.parse(p);a.enqueue(h)}catch(h){console.error("Failed to parse JSON message:",p,h)}}}}finally{c.releaseLock(),a.close()}}}),o=new WritableStream({async write(a){let s=JSON.stringify(a)+`
`,c=e.getWriter();try{await c.write(n.encode(s))}finally{c.releaseLock()}}});return{readable:i,writable:o}}var an,WO=class{constructor(t,n){pt(this,an,void 0);let r=t(this),i=async(a,s)=>{switch(a){case Fe.initialize:{let c=Pw.parse(s);return r.initialize(c)}case Fe.session_new:{let c=Uw.parse(s);return r.newSession(c)}case Fe.session_load:{if(!r.loadSession)throw ze.methodNotFound(a);let c=Fw.parse(s);return r.loadSession(c)}case Fe.session_list:{if(!r.unstable_listSessions)throw ze.methodNotFound(a);let c=Dw.parse(s);return r.unstable_listSessions(c)}case Fe.session_fork:{if(!r.unstable_forkSession)throw ze.methodNotFound(a);let c=qw.parse(s);return r.unstable_forkSession(c)}case Fe.session_resume:{if(!r.unstable_resumeSession)throw ze.methodNotFound(a);let c=Gw.parse(s);return r.unstable_resumeSession(c)}case Fe.session_set_mode:{if(!r.setSessionMode)throw ze.methodNotFound(a);let c=Yw.parse(s),d=await r.setSessionMode(c);return d!=null?d:{}}case Fe.authenticate:{let c=Mw.parse(s),d=await r.authenticate(c);return d!=null?d:{}}case Fe.session_prompt:{let c=Qw.parse(s);return r.prompt(c)}case Fe.session_set_model:{if(!r.unstable_setSessionModel)throw ze.methodNotFound(a);let c=Jw.parse(s),d=await r.unstable_setSessionModel(c);return d!=null?d:{}}case Fe.session_set_config_option:{if(!r.setSessionConfigOption)throw ze.methodNotFound(a);let c=Xw.parse(s);return r.setSessionConfigOption(c)}default:if(r.extMethod)return r.extMethod(a,s);throw ze.methodNotFound(a)}},o=async(a,s)=>{switch(a){case Fe.session_cancel:{let c=jw.parse(s);return r.cancel(c)}default:if(r.extNotification)return r.extNotification(a,s);throw ze.methodNotFound(a)}};Fn(this,an,new pp(i,o,n))}async sessionUpdate(t){return await ie(this,an).sendNotification(yt.session_update,t)}async requestPermission(t){return await ie(this,an).sendRequest(yt.session_request_permission,t)}async readTextFile(t){return await ie(this,an).sendRequest(yt.fs_read_text_file,t)}async writeTextFile(t){var n;return(n=await ie(this,an).sendRequest(yt.fs_write_text_file,t))!=null?n:{}}async createTerminal(t){let n=await ie(this,an).sendRequest(yt.terminal_create,t);return new r$(n.terminalId,t.sessionId,ie(this,an))}async extMethod(t,n){return await ie(this,an).sendRequest(t,n)}async extNotification(t,n){return await ie(this,an).sendNotification(t,n)}get signal(){return ie(this,an).signal}get closed(){return ie(this,an).closed}};an=new WeakMap;var Fr,Hr,r$=class{constructor(t,n,r){qc(this,"id");pt(this,Fr,void 0);pt(this,Hr,void 0);this.id=t,Fn(this,Fr,n),Fn(this,Hr,r)}async currentOutput(){return await ie(this,Hr).sendRequest(yt.terminal_output,{sessionId:ie(this,Fr),terminalId:this.id})}async waitForExit(){return await ie(this,Hr).sendRequest(yt.terminal_wait_for_exit,{sessionId:ie(this,Fr),terminalId:this.id})}async kill(){var t;return(t=await ie(this,Hr).sendRequest(yt.terminal_kill,{sessionId:ie(this,Fr),terminalId:this.id}))!=null?t:{}}async release(){var t;return(t=await ie(this,Hr).sendRequest(yt.terminal_release,{sessionId:ie(this,Fr),terminalId:this.id}))!=null?t:{}}async[Symbol.asyncDispose](){await this.release()}};Fr=new WeakMap,Hr=new WeakMap;var dt,mp=class{constructor(t,n){pt(this,dt,void 0);let r=t(this),i=async(a,s)=>{var c,d,m,l,f,p,h;switch(a){case yt.fs_write_text_file:{let y=i$.parse(s);return(c=r.writeTextFile)==null?void 0:c.call(r,y)}case yt.fs_read_text_file:{let y=Hw.parse(s);return(d=r.readTextFile)==null?void 0:d.call(r,y)}case yt.session_request_permission:{let y=e$.parse(s);return r.requestPermission(y)}case yt.terminal_create:{let y=Zw.parse(s);return(m=r.createTerminal)==null?void 0:m.call(r,y)}case yt.terminal_output:{let y=Kw.parse(s);return(l=r.terminalOutput)==null?void 0:l.call(r,y)}case yt.terminal_release:{let y=Bw.parse(s),x=await((f=r.releaseTerminal)==null?void 0:f.call(r,y));return x!=null?x:{}}case yt.terminal_wait_for_exit:{let y=n$.parse(s);return(p=r.waitForTerminalExit)==null?void 0:p.call(r,y)}case yt.terminal_kill:{let y=Vw.parse(s),x=await((h=r.killTerminal)==null?void 0:h.call(r,y));return x!=null?x:{}}default:if(r.extMethod)retur
/*! Bundled license information:
react/cjs/react.production.js:
(**
* @license React
* react.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
scheduler/cjs/scheduler.production.js:
(**
* @license React
* scheduler.production.js
*
* Copyright (c) Meta Platforms, Inc. and 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.js:
(**
* @license React
* react-dom.production.js
*
* Copyright (c) Meta Platforms, Inc. and 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-client.production.js:
(**
* @license React
* react-dom-client.production.js
*
* Copyright (c) Meta Platforms, Inc. and 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.js:
(**
* @license React
* react-jsx-runtime.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
*/