Files
my-vault/.obsidian/plugins/opencode-obsidian/main.js
T

100 lines
555 KiB
JavaScript
Raw Normal View History

2026-01-21 08:46:13 +08:00
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var tr=Object.defineProperty;var Ig=Object.getOwnPropertyDescriptor;var Pg=Object.getOwnPropertyNames;var Tg=Object.prototype.hasOwnProperty;var yd=r=>{throw TypeError(r)};var zg=(r,e,n)=>e in r?tr(r,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):r[e]=n;var Y=(r,e)=>()=>(r&&(e=r(r=0)),e);var $e=(r,e)=>{for(var n in e)tr(r,n,{get:e[n],enumerable:!0})},Og=(r,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of Pg(e))!Tg.call(r,t)&&t!==n&&tr(r,t,{get:()=>e[t],enumerable:!(i=Ig(e,t))||i.enumerable});return r};var Dg=r=>Og(tr({},"__esModule",{value:!0}),r);var D=(r,e,n)=>zg(r,typeof e!="symbol"?e+"":e,n),Oo=(r,e,n)=>e.has(r)||yd("Cannot "+n);var I=(r,e,n)=>(Oo(r,e,"read from private field"),n?n.call(r):e.get(r)),fe=(r,e,n)=>e.has(r)?yd("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,n),ee=(r,e,n,i)=>(Oo(r,e,"write to private field"),i?i.call(r,n):e.set(r,n),n),Ve=(r,e,n)=>(Oo(r,e,"access private method"),n);var nr,se=Y(()=>{nr=class{constructor(e={}){this.collectedErrors=[];var n,i,t,o;this.config={showUserNotifications:(n=e.showUserNotifications)!=null?n:!0,logToConsole:(i=e.logToConsole)!=null?i:!0,collectErrors:(t=e.collectErrors)!=null?t:!1,maxCollectedErrors:(o=e.maxCollectedErrors)!=null?o:100,notificationCallback:e.notificationCallback}}handleError(e,n={},i="error"){let t=e instanceof Error?e:new Error(String(e));this.config.collectErrors&&this.collectError(t,i,n),this.config.logToConsole&&this.logError(t,i,n),this.config.showUserNotifications&&(i==="critical"||i==="error")&&this.notifyUser(t,i,n)}logError(e,n,i){let o=`${`[${i.module||"Unknown"}]${i.function?`.${i.function}`:""}`} ${n.toUpperCase()}: ${e.message}`;switch(n){case"critical":case"error":console.error(o,{error:e,stack:e.stack,context:i.metadata});break;case"warning":console.warn(o,{error:e,context:i.metadata});break;case"info":console.debug(o,{error:e,context:i.metadata});break}}notifyUser(e,n,i){let t=e.message;if(e.message.includes("Unable to connect")||e.message.includes("Please ensure")||e.message.startsWith("Failed to")||(i.operation?t=`${i.operation}: ${t}`:i.module&&(t=`${i.module}: ${t}`)),t.length>200&&(t=t.substring(0,197)+"..."),this.config.notificationCallback)try{this.config.notificationCallback(t,n)}catch(s){console.error("[ErrorHandler] Failed to show notification:",s)}else console.error(`[User Notification - ${n}] ${t}`)}collectError(e,n,i){this.collectedErrors.length>=this.config.maxCollectedErrors&&this.collectedErrors.shift(),this.collectedErrors.push({error:e,severity:n,context:i,timestamp:Date.now()})}getCollectedErrors(){return[...this.collectedErrors]}clearCollectedErrors(){this.collectedErrors=[]}wrapAsync(e,n){return async(...i)=>{try{return await e(...i)}catch(t){throw this.handleError(t,n),t}}}wrapSync(e,n){return(...i)=>{try{return e(...i)}catch(t){throw this.handleError(t,n),t}}}}});function Sd(r){return new Date(r).toLocaleTimeString()}function $d(r){return new Date(r).toISOString()}function xd(){return new Date().toISOString().replace(/[:.]/g,"-")}function wd(r,e=50){return r.replace(/[<>:"/\\|?*]/g,"_").substring(0,e)}function _d(r){let e=r.trim();if(!e.startsWith("/"))return null;let n=e.slice(1).trim();if(!n)return null;let i=n.indexOf(" ");if(i===-1)return{command:n,args:""};let t=n.slice(0,i);return t?{command:t,args:n.slice(i+1)}:null}function kd(r,e){try{return JSON.parse(r)}catch(n){return e}}function Cd(r,e=""){try{return JSON.stringify(r)}catch(n){return e}}var Ct=Y(()=>{});function Mg(r={}){let{serverUrl:e,operation:n}=r;return e?`Unable to connect to OpenCode Server at ${e}. Please ensure the server is running and accessible.`:n?`Network error during ${n}. Please check your connection and try again.`:"Network error. Please check your connection and try again."}function Ag(r={}){let{operation:e,sessionId:n}=r;return n?"Session not found. It may have been deleted.":e?`Resource not found during ${e}.`:"Resource not found."}function Lg(r={}){let{operation:e}=r;return e?`Server error during ${e}. Please try again later.`:"Server error. Please try agai
`);M=($=st.pop())!=null?$:"";for(let kt of st){let at=kt.split(`
`),O=[],V;for(let F of at)if(F.startsWith("data:"))O.push(F.replace(/^data:\s*/,""));else if(F.startsWith("event:"))V=F.replace(/^event:\s*/,"");else if(F.startsWith("id:"))d=F.replace(/^id:\s*/,"");else if(F.startsWith("retry:")){let te=Number.parseInt(F.replace(/^retry:\s*/,""),10);Number.isNaN(te)||(h=te)}let T,j=!1;if(O.length){let F=O.join(`
`);try{T=JSON.parse(F),j=!0}catch(te){T=F}}j&&(i&&await i(T),n&&(T=await n(T))),e==null||e({data:T,event:V,id:d,retry:h}),O.length&&(yield T)}}}finally{y.removeEventListener("abort",G),x.releaseLock()}break}catch(S){if(r==null||r(S),o!==void 0&&g>=o)break;let x=Math.min(h*2**(g-1),s!=null?s:3e4);await a(x)}}}()}}});var Ud,Nd=Y(()=>{Ud=async(r,e)=>{let n=typeof e=="function"?await e(r):e;if(n)return r.scheme==="bearer"?`Bearer ${n}`:r.scheme==="basic"?`Basic ${btoa(n)}`:n}});var Lo,Uo=Y(()=>{Lo={bodySerializer:r=>JSON.stringify(r,(e,n)=>typeof n=="bigint"?n.toString():n)}});var jg,Rg,Zg,br,Pt,Sr,No=Y(()=>{jg=r=>{switch(r){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Rg=r=>{switch(r){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},Zg=r=>{switch(r){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},br=({allowReserved:r,explode:e,name:n,style:i,value:t})=>{if(!e){let c=(r?t:t.map(l=>encodeURIComponent(l))).join(Rg(i));switch(i){case"label":return`.${c}`;case"matrix":return`;${n}=${c}`;case"simple":return c;default:return`${n}=${c}`}}let o=jg(i),s=t.map(c=>i==="label"||i==="simple"?r?c:encodeURIComponent(c):Pt({allowReserved:r,name:n,value:c})).join(o);return i==="label"||i==="matrix"?o+s:s},Pt=({allowReserved:r,name:e,value:n})=>{if(n==null)return"";if(typeof n=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${e}=${r?n:encodeURIComponent(n)}`},Sr=({allowReserved:r,explode:e,name:n,style:i,value:t,valueOnly:o})=>{if(t instanceof Date)return o?t.toISOString():`${n}=${t.toISOString()}`;if(i!=="deepObject"&&!e){let l=[];Object.entries(t).forEach(([d,a])=>{l=[...l,d,r?a:encodeURIComponent(a)]});let u=l.join(",");switch(i){case"form":return`${n}=${u}`;case"label":return`.${u}`;case"matrix":return`;${n}=${u}`;default:return u}}let s=Zg(i),c=Object.entries(t).map(([l,u])=>Pt({allowReserved:r,name:i==="deepObject"?`${n}[${l}]`:l,value:u})).join(s);return i==="label"||i==="matrix"?s+c:c}});var Fg,Hg,jd,Rd=Y(()=>{No();Fg=/\{[^{}]+\}/g,Hg=({path:r,url:e})=>{let n=e,i=e.match(Fg);if(i)for(let t of i){let o=!1,s=t.substring(1,t.length-1),c="simple";s.endsWith("*")&&(o=!0,s=s.substring(0,s.length-1)),s.startsWith(".")?(s=s.substring(1),c="label"):s.startsWith(";")&&(s=s.substring(1),c="matrix");let l=r[s];if(l==null)continue;if(Array.isArray(l)){n=n.replace(t,br({explode:o,name:s,style:c,value:l}));continue}if(typeof l=="object"){n=n.replace(t,Sr({explode:o,name:s,style:c,value:l,valueOnly:!0}));continue}if(c==="matrix"){n=n.replace(t,`;${Pt({name:s,value:l})}`);continue}let u=encodeURIComponent(c==="label"?`.${l}`:l);n=n.replace(t,u)}return n},jd=({baseUrl:r,path:e,query:n,querySerializer:i,url:t})=>{let o=t.startsWith("/")?t:`/${t}`,s=(r!=null?r:"")+o;e&&(s=Hg({path:e,url:s}));let c=n?i(n):"";return c.startsWith("?")&&(c=c.substring(1)),c&&(s+=`?${c}`),s}});var Zd,Fd,Vg,Hd,jo,Ro,$r,hn,Vd,qg,Wg,gn,Zo=Y(()=>{Nd();Uo();No();Rd();Zd=({allowReserved:r,array:e,object:n}={})=>t=>{let o=[];if(t&&typeof t=="object")for(let s in t){let c=t[s];if(c!=null)if(Array.isArray(c)){let l=br({allowReserved:r,explode:!0,name:s,style:"form",value:c,...e});l&&o.push(l)}else if(typeof c=="object"){let l=Sr({allowReserved:r,explode:!0,name:s,style:"deepObject",value:c,...n});l&&o.push(l)}else{let l=Pt({allowReserved:r,name:s,value:c});l&&o.push(l)}}return o.join("&")},Fd=r=>{var n;if(!r)return"stream";let e=(n=r.split(";")[0])==null?void 0:n.trim();if(e){if(e.startsWith("application/json")||e.endsWith("+json"))return"json";if(e==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some(i=>e.startsWith(i)))return"blob";if(e.startsWith("text/"))return"text"}},Vg=(r,e)=>{var n,i;return e?!!(r.headers.has(e)||(n=r.query)!=null&&n[e]||(i=r.headers.get("Cookie"))!=null&&i.includes(`${e}=`)):!1},Hd=async({security:r,...e})=>{var n;for(let i of r){if(Vg(e,i.name))continue;let t=await Ud(i,e.auth);if(!t)contin
`);u=(d=p.pop())!=null?d:"";for(let m of p){let h=m.split(`
`),g=[];for(let $ of h){let P=$.replace(/\r$/,"");P.startsWith("data:")?g.push(P.replace(/^data:\s*/,"")):P.startsWith("id:")&&(this.lastEventId=P.replace(/^id:\s*/,""))}if(!g.length)continue;let y=g.join(`
`);yield kd(y,y)}}}async processEventStream(e){try{for await(let n of e)this.handleSDKEvent(n)}catch(n){throw this.errorHandler.handleError(n,{module:"StreamHandler",function:"processEventStream",operation:"Processing event stream"},"warning"),this.handleSDKError(n),n}}extractSessionIdFromEvent(e){var n,i,t,o,s,c;return((i=(n=e.properties)==null?void 0:n.part)==null?void 0:i.sessionID)||((o=(t=e.properties)==null?void 0:t.part)==null?void 0:o.sessionId)||((s=e.properties)==null?void 0:s.sessionID)||((c=e.properties)==null?void 0:c.sessionId)||e.sessionId||e.sessionID||e.id||null}handleSDKEvent(e){try{let n=this.extractSessionIdFromEvent(e)||"";if(e.type)switch(e.type){case"message.part.updated":case"message.updated":this.handleMessagePartUpdated(e,n);return;case"session.idle":case"session.completed":this.handleSessionIdle(n);return;case"session.progress":this.handleSessionProgress(e,n);return;case"session.ended":case"session.aborted":this.handleSessionEnded(e,n);return;case"permission.request":this.handlePermissionRequest(e,n);return;default:console.debug("[StreamHandler] Unhandled event type:",e.type);return}e.role==="assistant"&&e.parts&&this.handleAssistantMessage(e,n)}catch(n){this.errorHandler.handleError(n,{module:"StreamHandler",function:"handleSDKEvent",operation:"Processing SDK event",metadata:{eventType:e.type}},"warning")}}invokeCallbacks(e,n,i){e.forEach(t=>{try{t(...n)}catch(o){console.warn(`[StreamHandler] Error in ${i} callback:`,o)}})}handleMessagePartUpdated(e,n){var s,c,l,u;let i=((s=e.properties)==null?void 0:s.part)||((c=e.data)==null?void 0:c.part)||e.part,t=((l=e.properties)==null?void 0:l.delta)||((u=e.data)==null?void 0:u.delta)||e.delta;if(!i&&!t)return;let o=t||(i==null?void 0:i.text)||"";(i==null?void 0:i.type)==="text"||!(i!=null&&i.type)&&o?this.invokeCallbacks(this.streamTokenCallbacks,[n,o,!1],"stream token"):((i==null?void 0:i.type)==="reasoning"||(i==null?void 0:i.type)==="thinking")&&this.invokeCallbacks(this.streamThinkingCallbacks,[n,o],"stream thinking")}handleAssistantMessage(e,n){if(e.parts&&Array.isArray(e.parts))for(let i of e.parts)i.type==="text"&&i.text?this.invokeCallbacks(this.streamTokenCallbacks,[n,i.text,!1],"stream token"):i.type==="reasoning"&&i.text&&this.invokeCallbacks(this.streamThinkingCallbacks,[n,i.text],"stream thinking")}handleSessionIdle(e){this.sessionState.promptInFlightSessionId===e&&(this.sessionState.promptInFlightSessionId=null),this.invokeCallbacks(this.streamTokenCallbacks,[e,"",!0],"stream token completion")}handleSessionProgress(e,n){var t;let i=((t=e.data)==null?void 0:t.progress)||e.progress;i&&this.invokeCallbacks(this.progressUpdateCallbacks,[n,i],"progress update")}handleSessionEnded(e,n){var t;let i=((t=e.data)==null?void 0:t.reason)||e.reason||"completed";this.sessionState.sessions.delete(n),this.sessionState.currentSessionId===n&&(this.sessionState.currentSessionId=null),this.sessionState.promptInFlightSessionId===n&&(this.sessionState.promptInFlightSessionId=null),this.invokeCallbacks(this.sessionEndCallbacks,[n,i],"session end")}handlePermissionRequest(e,n){let i=e.properties||e.data||e,{requestId:t,operation:o,resourcePath:s,context:c}=i;if(!t||!o||!s){console.warn("[StreamHandler] Malformed permission.request event - missing required fields:",{requestId:t,operation:o,resourcePath:s,event:e});return}this.invokeCallbacks(this.permissionRequestCallbacks,[n,t,o,s,c],"permission request")}handleSDKError(e){this.errorHandler.handleError(e,{module:"StreamHandler",function:"handleSDKError",operation:"SDK event error"},"error"),this.invokeCallbacks(this.errorCallbacks,[e],"error")}}});var Cr,tp=Y(()=>{se();Ct();mr();Cr=class{constructor(e,n,i){this.currentSessionId=null;this.sessions=new Map;this.promptInFlightSessionId=null;this.sdkClient=e,this.errorHandler=n,this.serverUrl=i}getCurrentSessionId(){return this.currentSessionId}setCurrentSessionId(e){this.currentSessionId=e}getPromptInFlightSessionId(){return this.promptInFlightSessionId}setPromptInFlightSessionId(e){this.promptInFlightSessionId=e}getSessions(){return this.sessions}clearSessionSta
`);return{id:i.info.id,role:i.info.role,content:o,timestamp:i.info.time.created}})}catch(n){this.handleSdkError(n,"getSessionMessages","getting session messages",e)}}async updateSessionTitle(e,n){try{let i=await this.sdkClient.session.update({path:{id:e},body:{title:n}});if(i.error)throw new Error(`Failed to update session title: ${i.error}`);let t=this.sessions.get(e);t&&(t.title=n)}catch(i){this.handleSdkError(i,"updateSessionTitle","updating session title",e)}}async deleteSession(e){try{let n=await this.sdkClient.session.delete({path:{id:e}});if(n.error)throw new Error(`Failed to delete session: ${n.error}`);this.sessions.delete(e),this.currentSessionId===e&&(this.currentSessionId=null),this.promptInFlightSessionId===e&&(this.promptInFlightSessionId=null)}catch(n){le(n)===404&&(this.sessions.delete(e),this.currentSessionId===e&&(this.currentSessionId=null),this.promptInFlightSessionId===e&&(this.promptInFlightSessionId=null)),this.handleSdkError(n,"deleteSession","deleting session",e)}}async revertSession(e,n){try{let i=await this.sdkClient.session.revert({path:{id:e},body:{messageID:n}});if(i.error)throw new Error(`Failed to revert session: ${i.error}`)}catch(i){this.handleSdkError(i,"revertSession","reverting session",e)}}async unrevertSession(e){try{let n=await this.sdkClient.session.unrevert({path:{id:e}});if(n.error)throw new Error(`Failed to unrevert session: ${n.error}`)}catch(n){this.handleSdkError(n,"unrevertSession","unreverting session",e)}}async forkSession(e,n,i){try{let t=await this.sdkClient.session.fork({path:{id:e},body:{...n?{messageID:n}:{},...i?{title:i}:{}}});if(t.error)throw new Error(`Failed to fork session: ${t.error}`);if(!t.data)throw new Error("OpenCode Server session.fork returned no data.");let o=this.extractSessionId(t.data);if(!o)throw new Error("OpenCode Server fork response did not include a session id.");return this.sessions.set(o,t.data),o}catch(t){this.handleSdkError(t,"forkSession","forking session",e)}}async getSessionDiff(e){try{let n=await this.sdkClient.session.diff({path:{id:e}});if(n.error)throw new Error(`Failed to get session diff: ${n.error}`);if(!n.data)throw new Error("OpenCode Server session.diff returned no data.");let t=(n.data.files||[]).map(o=>({path:o.path||"",added:o.added||[],removed:o.removed||[],language:o.language}));return{sessionId:e,files:t}}catch(n){this.handleSdkError(n,"getSessionDiff","getting session diff",e)}}buildSystemMessage(e,n,i){var o,s;let t=[];if(n&&t.push(`Agent: ${n}`),i!=null&&i.length&&t.push(`Instructions: ${i.join(", ")}`),e){let c=[];e.currentNote&&c.push(`Current note: ${e.currentNote}`),e.selection&&c.push(`Selection: ${e.selection}`),(o=e.links)!=null&&o.length&&c.push(`Links: ${e.links.join(", ")}`),(s=e.tags)!=null&&s.length&&c.push(`Tags: ${e.tags.join(", ")}`),c.length&&t.push(`Context: ${c.join("; ")}`)}return t.length>0?t.join(`
`):null}async searchText(e){try{let n=await this.sdkClient.find.text({query:{pattern:e.pattern,...e.path?{directory:e.path}:{}},...e.language?{language:e.language}:{},...e.limit?{limit:e.limit}:{},...e.caseSensitive?{caseSensitive:e.caseSensitive}:{},...e.regex?{regex:e.regex}:{}});if(n.error)throw new Error(`Failed to search text: ${n.error}`);return n.data?n.data.map(i=>({path:i.path||"",line:i.line||0,content:i.content||"",language:i.language})):[]}catch(n){this.handleSdkError(n,"searchText","searching text")}}async searchFiles(e,n){try{let i=await this.sdkClient.find.files({query:{query:e},...n?{limit:n}:{}});if(i.error)throw new Error(`Failed to search files: ${i.error}`);return i.data?i.data.map(t=>({path:t.path||"",size:t.size||0,lastModified:t.lastModified||Date.now(),language:t.language})):[]}catch(i){this.handleSdkError(i,"searchFiles","searching files")}}async searchSymbols(e,n){try{let i=await this.sdkClient.find.symbols({query:{query:e},...n?{limit:n}:{}});if(i.error)throw new Error(`Failed to search symbols: ${i.error}`);return i.data?i.data.map(t=>({name:t.name||"",type:t.type||"",path:t.path||"",line:t.line||0,column:t.column||0,parent:t.parent})):[]}catch(i){this.handleSdkError(i,"searchSymbols","searching symbols")}}}});var rp={};$e(rp,{OpenCodeServerClient:()=>vn});function Jg(r,e){return Kd({baseUrl:r,fetch:e})}var np,vn,us=Y(()=>{Xd();np=require("obsidian");se();mr();Ct();Qd();ep();tp();vn=class{constructor(e,n){this.commandListCache=null;this.featureCache=null;var t;let i=this.normalizeServerUrl(e.url);this.config={...e,url:i,requestTimeoutMs:(t=e.requestTimeoutMs)!=null?t:1e4},this.errorHandler=n,this.connectionHandler=new _r(this.config,this.errorHandler),this.sdkClient=Jg(i,this.createObsidianFetch()),this.sessionOps=new Cr(this.sdkClient,this.errorHandler,i),this.streamHandler=new kr(this.config,this.errorHandler,this.sdkClient,{promptInFlightSessionId:this.sessionOps.getPromptInFlightSessionId(),sessions:this.sessionOps.getSessions(),currentSessionId:this.sessionOps.getCurrentSessionId()})}get currentSessionId(){return this.sessionOps.getCurrentSessionId()}set currentSessionId(e){this.sessionOps.setCurrentSessionId(e)}get sessions(){return this.sessionOps.getSessions()}get promptInFlightSessionId(){return this.sessionOps.getPromptInFlightSessionId()}set promptInFlightSessionId(e){this.sessionOps.setPromptInFlightSessionId(e)}createObsidianFetch(){return async(e,n)=>{var u;let{resolvedUrl:i,method:t,headers:o,contentType:s,body:c,bodyLength:l}=await this.buildRequestOptions(e,n);try{let d=(u=this.config.requestTimeoutMs)!=null?u:1e4,a=i.includes("/message"),p=i.includes("/prompt"),m=a||p?Math.max(d,6e4):d,h=null,g;try{let b=(0,np.requestUrl)({url:i,method:t,headers:o,contentType:s,body:c});try{g=m>0?await Promise.race([b.then($=>$),new Promise(($,P)=>{h=setTimeout(()=>{P(new Error(`HTTP request timed out after ${m}ms`))},m)})]):await b}catch($){throw $}}finally{h&&clearTimeout(h)}let y;return g.text?y=g.text:g.json!==void 0&&g.json!==null?y=Cd(g.json,""):y="",new Response(y,{status:g.status,statusText:g.status.toString(),headers:new Headers(g.headers||{})})}catch(d){let a=d instanceof Error?d.message:"Unknown error",p=a.includes("timed out");if(a.includes("not valid JSON")||a.includes("Unexpected token"))throw d;if(p){let h=this.config.url,g=new Error(`Unable to connect to OpenCode Server at ${h}. Please ensure the server is running and accessible.`);try{g.cause=d}catch(y){}throw this.errorHandler.handleError(g,{module:"OpenCodeClient",function:"createObsidianFetch",metadata:{url:i,method:t,suggestedFix:"Check if OpenCode Server is running at "+h}},"error"),g}throw this.errorHandler.handleError(d,{module:"OpenCodeClient",function:"createObsidianFetch",operation:"HTTP request",metadata:{url:i,method:t}},"error"),d}}}async buildRequestOptions(e,n){var u,d,a,p,m;let i=this.resolveRequestUrl(e),t=(n==null?void 0:n.method)||"GET",o=new Headers((u=n==null?void 0:n.headers)!=null?u:{}),s=n!=null&&n.body?String(n.body):void 0;typeof Request!="undefined"&&e instanceof Request&&(t=(a=(d=n==null?void 0:n.
${p} message${p!==1?"s":""} \u2022 Last updated ${m}`;ae(l,"title",h);let g=!1;d.ondblclick=b=>{if(b.stopPropagation(),g)return;g=!0;let $=document.createElement("input");$.type="text",$.value=c.title,$.className="opencode-obsidian-tab-title-edit",N($,{width:`${d.offsetWidth}px`,minWidth:"120px",maxWidth:"300px"}),N(d,{display:"none"}),u.insertBefore($,d),$.focus(),$.select();let P=async()=>{let x=$.value.trim();x&&x!==c.title&&await this.renameConversation(c.id,x),$.remove(),N(d,{display:""}),g=!1},S=()=>{$.remove(),N(d,{display:""}),g=!1};$.onblur=()=>{setTimeout(P,200)},$.onkeydown=x=>{x.key==="Enter"?(x.preventDefault(),x.stopPropagation(),P()):x.key==="Escape"&&(x.preventDefault(),x.stopPropagation(),S())}};let y=l.createSpan("opencode-obsidian-tab-close");y.textContent="\xD7",ae(y,"title","Delete conversation"),y.onclick=async b=>{if(b.stopPropagation(),n)return;let P=!!c.sessionId?`Are you sure you want to delete "${c.title}"? This will also delete the session from the server.`:`Are you sure you want to delete "${c.title}"?`;new ct(this.app,"Delete conversation",P,async()=>{await this.deleteConversation(c.id)}).open()},l.oncontextmenu=b=>{n||(b.preventDefault(),b.stopPropagation(),this.showConversationContextMenu(l,c.id,b))},l.onclick=async()=>{!g&&!n&&await this.switchConversation(c.id)}});let t=i.createDiv("opencode-obsidian-tab opencode-obsidian-tab-new");if(n){let c=t.createSpan("opencode-obsidian-spinner");t.addClass("opencode-obsidian-tab-disabled")}else t.textContent="+";if(ae(t,"title",n?"Loading...":"New conversation"),t.onclick=async()=>{n||await this.createNewConversation()},this.syncFromServer){let c=i.createDiv("opencode-obsidian-tab opencode-obsidian-tab-sync");if(n){let l=c.createSpan("opencode-obsidian-spinner");c.addClass("opencode-obsidian-tab-disabled")}else c.innerHTML="\u21BB";ae(c,"title",n?"Syncing...":"Sync from server"),c.onclick=async()=>{!n&&this.syncFromServer&&await this.syncFromServer()}}}showConversationContextMenu(e,n,i){let t=document.querySelector(".opencode-obsidian-context-menu");t&&t.remove();let o=this.conversations.find(a=>a.id===n);if(!o)return;let s=document.createElement("div");s.className="opencode-obsidian-context-menu",N(s,{position:"fixed",left:`${i.clientX}px`,top:`${i.clientY}px`,zIndex:"10000"});let c=s.createDiv("opencode-obsidian-context-menu-item");c.textContent="Rename",c.onclick=async()=>{s.remove();let a=e.querySelector(".opencode-obsidian-tab-title");a&&a.dispatchEvent(new MouseEvent("dblclick",{bubbles:!0}))};let l=s.createDiv("opencode-obsidian-context-menu-item");if(l.textContent="Export",l.onclick=()=>{s.remove(),this.exportConversation(n)},o.sessionId&&this.viewSessionDiff){let a=s.createDiv("opencode-obsidian-context-menu-item");a.textContent="View changes",a.onclick=()=>{s.remove(),o.sessionId&&this.viewSessionDiff&&this.viewSessionDiff(o.sessionId)}}if(o.sessionId&&this.forkConversation){let a=s.createDiv("opencode-obsidian-context-menu-item");a.textContent="Fork session",a.onclick=()=>{s.remove(),this.forkConversation&&this.forkConversation(n)}}let u=s.createDiv("opencode-obsidian-context-menu-item");u.textContent="Delete",u.addClass("opencode-obsidian-context-menu-item-danger"),u.onclick=()=>{s.remove();let p=!!o.sessionId?`Are you sure you want to delete "${o.title}"? This will also delete the session from the server.`:`Are you sure you want to delete "${o.title}"?`;new ct(this.app,"Delete conversation",p,async()=>{await this.deleteConversation(n)}).open()},document.body.appendChild(s);let d=a=>{s.contains(a.target)||(s.remove(),document.removeEventListener("click",d))};setTimeout(()=>{document.addEventListener("click",d)},0)}};Ct();var sr=class{constructor(e,n,i,t,o,s,c,l){this.getActiveConversation=n;this.onRegenerate=i;this.getScrollPosition=t;this.getIsLoading=o;this.onRevert=s;this.onUnrevert=c;this.onFork=l;this.messageRenderer=e}render(e){var s,c,l;if(q(e),(c=(s=this.getIsLoading)==null?void 0:s.call(this))!=null?c:!1){let d=e.createDiv("opencode-obsidian-loading-overlay").createDiv("opencode-obsidian-loading-message");d.createSpan("opencod
`),t=!1,o="",s=[],c="";for(let l=0;l<i.length;l++){let u=i[l];if(u)if(u.startsWith("```"))if(t){if(t=!1,c.trim()){let p=e.createDiv("opencode-obsidian-markdown-text");lt.MarkdownRenderer.render(this.plugin.app,c.trim(),p,"",this.view),c=""}let d=e.createEl("pre");d.addClass("opencode-obsidian-code-block");let a=d.createEl("code");o&&a.addClass(`language-${o}`),a.textContent=s.join(`
`),this.addCodeBlockActions(d,s.join(`
`)),s=[],o=""}else t=!0,o=u.slice(3).trim();else t?s.push(u):c+=(c?`
`:"")+u}if(t&&s.length>0){let l=e.createEl("pre");l.addClass("opencode-obsidian-code-block");let u=l.createEl("code");o&&u.addClass(`language-${o}`),u.textContent=s.join(`
`),this.addCodeBlockActions(l,s.join(`
`))}if(c.trim()){let l=e.createDiv("opencode-obsidian-markdown-text");lt.MarkdownRenderer.render(this.plugin.app,c.trim(),l,"",this.view)}}addCodeBlockActions(e,n){let t=e.createDiv("opencode-obsidian-code-actions").createEl("button",{text:"Copy",cls:"opencode-obsidian-code-copy"});t.onclick=async()=>{try{await navigator.clipboard.writeText(n),t.textContent="Copied!",setTimeout(()=>{t.textContent="Copy"},2e3)}catch(o){this.plugin.errorHandler.handleError(o,{module:"OpenCodeObsidianView",function:"addCodeActions",operation:"Copying code to clipboard"},"warning"),new lt.Notice("Failed to copy code")}}}addMessageActions(e,n,i,t,o,s){let c=e.createDiv("opencode-obsidian-message-actions"),l=c.createEl("button",{text:"\u{1F4CB}",cls:"opencode-obsidian-message-action",attr:{title:"Copy message"}});if(l.onclick=async()=>{try{await navigator.clipboard.writeText(n.content),new lt.Notice("Message copied to clipboard")}catch(u){this.plugin.errorHandler.handleError(u,{module:"OpenCodeObsidianView",function:"addMessageActions",operation:"Copying message to clipboard"},"warning"),new lt.Notice("Failed to copy message")}},n.role==="assistant"&&i){let u=c.createEl("button",{text:"\u{1F504}",cls:"opencode-obsidian-message-action",attr:{title:"Regenerate response"}});u.onclick=()=>{i(n)}}if(t){let u=c.createEl("button",{text:"\u21A9\uFE0F",cls:"opencode-obsidian-message-action",attr:{title:"Revert to here"}});u.onclick=()=>{t(n)}}if(o&&s){let u=c.createEl("button",{text:"\u{1F374}",cls:"opencode-obsidian-message-action",attr:{title:"Fork from here"}});u.onclick=async()=>{try{u.disabled=!0,u.textContent="\u23F3",await o(n)}catch(d){}finally{u.disabled=!1,u.textContent="\u{1F374}"}}}}};var cr=class{constructor(e,n,i,t,o,s,c,l){this.plugin=e;this.app=n;this.sendMessage=i;this.stopStreaming=t;this.showAttachmentModal=o;this.ensureCommandSuggestions=s;this.parseSlashCommand=c;this.setIsStreaming=l;this.commandSuggestions=[];this.commandSuggestionsLoading=!1;this.isStreaming=!1}render(e){var at;q(e);let n=e.createDiv("opencode-obsidian-input-container"),t=n.createDiv("opencode-obsidian-input-toolbar").createEl("select",{cls:"opencode-obsidian-agent-select"}),o=[{id:"assistant",name:"Assistant"},{id:"bootstrap",name:"Bootstrap"},{id:"thinking-partner",name:"Thinking Partner"},{id:"research-assistant",name:"Research Assistant"},{id:"read-only",name:"Read Only"}],s=((at=this.plugin.settings.agents)==null?void 0:at.filter(O=>!O.hidden))||[],c=s.length>0?s:o;c.forEach(O=>{let V=t.createEl("option",{value:O.id,text:O.name});"color"in O&&typeof O.color=="string"&&(V.style.color=O.color)});let l=this.plugin.settings.agent;c.some(O=>O.id===l)?t.value=l:c.length>0&&c[0]&&(t.value=c[0].id,this.plugin.settings.agent=c[0].id,this.plugin.saveSettings()),t.onchange=async()=>{this.plugin.settings.agent=t.value,await this.plugin.debouncedSaveSettings()};let u=n.createEl("textarea",{cls:"opencode-obsidian-input-textarea",attr:{placeholder:"Type your message... (Shift+Enter for new line, Enter to send)"}}),d=n.createDiv("opencode-obsidian-command-suggestions"),a=d.createDiv("opencode-obsidian-command-suggestions-list"),p=n.createDiv("opencode-obsidian-input-status"),m=p.createSpan("opencode-obsidian-char-count"),h=p.createSpan("opencode-obsidian-streaming-status"),g=()=>{let O=u.value.length;m.textContent=`${O} characters`,O>8e3?m.addClass("opencode-obsidian-char-warning"):m.removeClass("opencode-obsidian-char-warning")},y=[],b=-1,$=()=>{d.removeClass("is-visible"),y=[],b=-1},P=O=>{let V=u.value,T=V.startsWith("/")?V.slice(1):V,j=T.search(/\s/),F=j===-1?"":T.slice(j);u.value=`/${O.name}${F||" "}`,$(),u.focus(),g(),N(u,{height:"auto"}),N(u,{height:`${Math.min(u.scrollHeight,200)}px`})},S=O=>{if(q(a),y=O,b=O.length>0?0:-1,O.length===0){$();return}d.addClass("is-visible"),O.forEach((V,T)=>{let j=a.createDiv("opencode-obsidian-command-suggestion");T===b&&j.addClass("is-selected");let F=j.createSpan("opencode-obsidian-command-suggestion-name");if(F.textContent=`/${V.name}`,V.description){let te=j.createSpan("opencode-obsidian-command-suggestion-description");te.textCo
`),n.language,"removed")}if(n.added&&n.added.length>0){let s=o.createDiv("opencode-diff-section");s.createEl("div",{text:`+ ${n.added.length} line${n.added.length===1?"":"s"} added`,cls:"opencode-diff-section-header added"}),this.renderCodeBlock(s,n.added.join(`
`),n.language,"added")}}renderCodeBlock(e,n,i,t){let o=e.createEl("pre",{cls:`opencode-diff-code ${t}`}),s=o.createEl("code");i&&s.addClass(`language-${i}`),s.textContent=n,this.addCopyButton(o,n)}addCopyButton(e,n){let t=e.createDiv("opencode-diff-code-actions").createEl("button",{text:"Copy",cls:"opencode-diff-code-copy"});t.onclick=async()=>{try{await navigator.clipboard.writeText(n),t.textContent="Copied!",setTimeout(()=>{t.textContent="Copy"},2e3)}catch(o){console.error("Failed to copy code:",o)}}}};var dr=require("obsidian");var ln=class{constructor(e,n){this.currentMode="text";this.searchTimeout=null;this.plugin=e,this.container=n,this.app=e.app,this.render(),this.bindEvents()}render(){q(this.container),N(this.container,{display:"flex",flexDirection:"column",height:"100%",backgroundColor:"var(--background-primary)",border:"1px solid var(--background-modifier-border)",borderRadius:"var(--radius-s)"});let e=this.container.createEl("div",{cls:"search-header"});N(e,{display:"flex",flexDirection:"column",padding:"8px",borderBottom:"1px solid var(--background-modifier-border)"}),this.modeTabs=e.createEl("div",{cls:"search-mode-tabs"}),N(this.modeTabs,{display:"flex",marginBottom:"8px",gap:"4px"}),this.createModeTab("text","Text"),this.createModeTab("files","Files"),this.createModeTab("symbols","Symbols");let n=e.createEl("div",{cls:"search-input-container"});N(n,{display:"flex",gap:"8px"}),this.searchInput=n.createEl("input",{type:"text",placeholder:"Search...",cls:"search-input"}),N(this.searchInput,{flex:"1",padding:"8px 12px",border:"1px solid var(--background-modifier-border)",borderRadius:"var(--radius-s)",backgroundColor:"var(--background-secondary)",color:"var(--text-normal)"}),this.searchButton=n.createEl("button",{text:"Search",cls:"search-button"}),N(this.searchButton,{padding:"8px 16px",backgroundColor:"var(--interactive-accent)",color:"var(--text-on-accent)",border:"none",borderRadius:"var(--radius-s)",cursor:"pointer"}),this.resultsContainer=this.container.createEl("div",{cls:"search-results"}),N(this.resultsContainer,{flex:"1",overflow:"auto",padding:"8px"}),this.statusMessage=this.container.createEl("div",{cls:"search-status"}),N(this.statusMessage,{padding:"8px",fontSize:"var(--font-size-smaller)",color:"var(--text-muted)",borderTop:"1px solid var(--background-modifier-border)"}),this.loadingIndicator=this.container.createEl("div",{cls:"search-loading",text:"Searching..."}),N(this.loadingIndicator,{display:"none",padding:"16px",textAlign:"center",color:"var(--text-muted)"})}createModeTab(e,n){let i=this.modeTabs.createEl("button",{text:n,cls:"search-mode-tab"});N(i,{padding:"4px 8px",backgroundColor:e===this.currentMode?"var(--interactive-accent)":"var(--background-secondary)",color:e===this.currentMode?"var(--text-on-accent)":"var(--text-normal)",border:"1px solid var(--background-modifier-border)",borderRadius:"var(--radius-xs)",cursor:"pointer",fontSize:"var(--font-size-smaller)"}),i.addEventListener("click",()=>{this.setMode(e)})}setMode(e){this.currentMode=e,this.modeTabs.querySelectorAll(".search-mode-tab").forEach((n,i)=>{let o=["text","files","symbols"][i];N(n,{backgroundColor:o===e?"var(--interactive-accent)":"var(--background-secondary)",color:o===e?"var(--text-on-accent)":"var(--text-normal)"})}),this.clearResults(),this.updatePlaceholder()}updatePlaceholder(){let e={text:"Search text across files...",files:"Search files by name...",symbols:"Search symbols (functions, classes, etc.)..."};this.searchInput.placeholder=e[this.currentMode]}bindEvents(){this.searchInput.addEventListener("input",()=>{this.searchTimeout&&clearTimeout(this.searchTimeout),this.searchInput.value.trim().length>0?this.searchTimeout=window.setTimeout(()=>{this.performSearch()},300):this.clearResults()}),this.searchButton.addEventListener("click",()=>{this.performSearch()}),this.searchInput.addEventListener("keydown",e=>{e.key==="Enter"&&this.performSearch()}),this.searchInput.addEventListener("keydown",e=>{e.key==="Escape"&&this.hide()}),this.searchInput.focus()}async performSearch(){var n,i,t;let e=this.searchInput.value
`)[0])!=null?o:"").substring(0,50).trim();t&&(e.title=t.length>50?`${t.substring(0,47)}...`:t,this.saveConversations(),this.updateConversationSelector())}findConversationBySessionId(e){return this.conversations.find(n=>n.sessionId===e)||null}async loadSessionMessages(e){var i;let n=this.conversations.find(t=>t.id===e);if(!n)throw new Error(`Conversation not found: ${e}`);if(!n.sessionId)throw new Error(`Conversation has no sessionId: ${e}`);if(!this.sessionManager)throw new Error("SessionManager not available");if(!((i=this.plugin.opencodeClient)!=null&&i.isConnected()))throw new Error("OpenCode client not connected");try{let t=await this.sessionManager.loadSessionMessagesWithRetry(n.sessionId);n.messages=t,n.updatedAt=Date.now(),await this.saveConversations(),this.updateMessages()}catch(t){throw this.plugin.errorHandler.handleError(t,{module:"ConversationManager",function:"loadSessionMessages",operation:"Loading session messages from server",metadata:{conversationId:e,sessionId:n.sessionId}},"error"),t}}async handleSessionNotFound(e){let n=this.conversations.find(i=>i.sessionId===e);n&&(console.debug(`[ConversationManager] Removing sessionId ${e} from conversation ${n.id} due to 404 error`),n.sessionId=void 0,n.updatedAt=Date.now(),await this.saveConversations(),this.updateConversationSelector(),new ve.Notice(`Session "${n.title}" was not found on server. Converted to local-only conversation.`))}};var Et=require("obsidian");se();var dn=class{constructor(e,n,i,t,o,s,c,l,u,d,a,p,m,h,g,y,b){this.plugin=e;this.app=n;this.getActiveConversation=i;this.createNewConversation=t;this.parseSlashCommand=o;this.setIsStreaming=s;this.setCurrentAbortController=c;this.updateMessages=l;this.updateStreamingStatus=u;this.saveConversations=d;this.generateConversationTitle=a;this.showThinkingIndicator=p;this.showBlockedIndicator=m;this.showUsageInfo=h;this.showToolUse=g;this.showToolResult=y;this.sessionManager=b;this.isStreaming=!1;this.currentAbortController=null}async sendMessage(e){var s;console.info("[OpenCodeObsidianView] sendMessage invoked:",{contentLength:e.length});let n=this.getActiveConversation();if(!n){await this.createNewConversation(),await this.sendMessage(e);return}if(e.trim().startsWith("/")&&!this.parseSlashCommand(e)){new Et.Notice("Enter a command after /.");return}let i={id:`msg-${Date.now()}-user`,role:"user",content:e,timestamp:Date.now()};n.messages.push(i);let t={id:`msg-${Date.now()}-assistant`,role:"assistant",content:"",timestamp:Date.now()};n.messages.push(t);let o=this.parseSlashCommand(e);this.currentAbortController=new AbortController,this.setCurrentAbortController(this.currentAbortController),this.setStreamingState(!0),this.updateMessages();try{if(!this.plugin.opencodeClient)throw new Error("OpenCode Server client not initialized. Please check settings.");this.plugin.connectionManager?await this.plugin.connectionManager.ensureConnected(1e4):this.plugin.opencodeClient.isConnected()||await this.plugin.opencodeClient.connect();let c=n.pendingImagePath,l;if(c&&o)new Et.Notice("Attachments are not supported for commands."),n.pendingImagePath=void 0;else if(c){try{let a=this.app.vault.getAbstractFileByPath(c);if(a instanceof Et.TFile){let p=a,m=await this.app.vault.readBinary(p),h=btoa(String.fromCharCode(...new Uint8Array(m))),y={jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp"}[p.extension.toLowerCase()]||"image/png";l=[{data:h,mimeType:y,name:p.name}]}}catch(a){this.plugin.errorHandler.handleError(a,{module:"OpenCodeObsidianView",function:"handleFileInput",operation:"Attaching image"},"warning")}n.pendingImagePath=void 0}let u=n.sessionId||((s=this.plugin.opencodeClient)==null?void 0:s.getCurrentSessionId())||null;if(u=await this.ensureSession(n,u),!this.plugin.opencodeClient)throw new Error("OpenCode Server client not initialized");let d=async a=>{if(this.plugin.opencodeClient)if(o){let p=await this.plugin.opencodeClient.sendSessionCommand(a,o.command,o.args,this.plugin.settings.agent);t.content=p!=null?p:"Command executed.",this.setStreamingState(!1),this.updateMessages()}else await thi
`),s=wd(i.title),c=xd(),u=`Exports/${`${s}-${c}.md`}`;await this.app.vault.createFolder("Exports").catch(()=>{}),await this.app.vault.create(u,o),new Z.Notice(`Conversation exported to ${u}`)}catch(t){this.plugin.errorHandler.handleError(t,{module:"OpenCodeObsidianView",function:"exportConversation",operation:"Exporting conversation"},"warning");let o=t instanceof Error?t.message:"Unknown error";new Z.Notice(`Failed to export conversation: ${o}`)}}async viewSessionDiff(n){var i;try{let t=new Z.Notice("Loading session changes...",0),o=await((i=this.plugin.opencodeClient)==null?void 0:i.getSessionDiff(n));if(t.hide(),!o){new Z.Notice("Failed to load session changes: Client not available");return}new ur(this.app,o).open()}catch(t){this.plugin.errorHandler.handleError(t,{module:"OpenCodeObsidianView",function:"viewSessionDiff",operation:"Viewing session diff",metadata:{sessionId:n}},"warning");let o=t instanceof Error?t.message:"Unknown error";new Z.Notice(`Failed to load session changes: ${o}`)}}showAttachmentModal(){new lr(this.app,n=>{(async()=>{try{this.conversationManager.getActiveConversation()||await this.conversationManager.createNewConversation();let t="05_Attachments",s=`${Date.now()}-${n.name}`,c=`${t}/${s}`;await this.app.vault.adapter.exists(t)||await this.app.vault.createFolder(t);let u=await n.arrayBuffer();await this.app.vault.createBinary(c,u);let d=this.app.vault.adapter.basePath,a=d?`${d}/${c}`:c,p=this.conversationManager.getActiveConversation();p&&(p.pendingImagePath=a),new Z.Notice(`Image attached: ${n.name}`)}catch(i){this.plugin.errorHandler.handleError(i,{module:"OpenCodeObsidianView",function:"handleFileInput",operation:"Saving image"},"warning");let t=i instanceof Error?i.message:"Unknown error";new Z.Notice(`Failed to save image: ${t}`)}})()}).open()}getOrCreateIndicator(n,i){let t=this.containerEl.querySelector(n);if(!t){let o=this.containerEl.querySelector(i);o&&(t=o.createDiv(n.replace(".","")))}return t}showThinkingIndicator(n){console.debug("AI is thinking:",n);let i=this.getOrCreateIndicator(".opencode-obsidian-thinking-indicator",".opencode-obsidian-messages");i&&(i.textContent=`\u{1F4AD} ${n||"Thinking..."}`,N(i,{display:"block"}),setTimeout(()=>{N(i,{display:"none"})},3e3))}showBlockedIndicator(n){let i=this.getOrCreateIndicator(".opencode-obsidian-blocked-indicator",".opencode-obsidian-header");i&&(i.textContent=`\u{1F512} ${n}`,N(i,{display:"block"}))}showUsageInfo(n){let i=`${n.model}: ${n.inputTokens} tokens`;console.debug("Usage:",i)}showToolUse(n){console.debug("Tool use:",n),new Z.Notice(`Using tool: ${n.name}`)}showToolResult(n){console.debug("Tool result:",n),n.isError&&new Z.Notice(`Tool error: ${n.content}`)}async loadScrollPositions(){try{let n=await this.plugin.loadData();this.scrollPositions=(n==null?void 0:n.scrollPositions)||{}}catch(n){this.plugin.errorHandler.handleError(n,{module:"OpenCodeObsidianView",function:"loadScrollPositions",operation:"Loading scroll positions"},"warning")}}async saveScrollPosition(n,i){try{this.scrollPositions[n]=i;let o={...await this.plugin.loadData()||{},scrollPositions:this.scrollPositions};await this.plugin.saveData(o)}catch(t){this.plugin.errorHandler.handleError(t,{module:"OpenCodeObsidianView",function:"saveScrollPosition",operation:"Saving scroll position"},"warning")}}attachScrollListener(){let n=this.containerEl.querySelector(".opencode-obsidian-messages");n&&n.addEventListener("scroll",()=>{this.activeConversationId&&this.debouncedSaveScrollPosition(this.activeConversationId,n.scrollTop)})}async createNewConversation(){await this.conversationManager.createNewConversation()}};var R=require("obsidian");function Pd(r,e){let n=null,i=null,t=null,o=null;return function(...c){return n!==null&&(clearTimeout(n),n=null),i||(i=new Promise((l,u)=>{t=l,o=u})),n=setTimeout(async()=>{try{let l=await r(...c);t&&t(l)}catch(l){o&&o(l)}finally{n=null,i=null,t=null,o=null}},e),i}}function Do(r){return r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"")}function vr(r,e,n){let i=r.trim(),t=i==="0"?0:parseInt(i,10);return isNaN(t)||n!==void 0&&t<
`).map(e=>e.trim()).filter(e=>e.length>0)}function Td(r){return r.split(",").map(e=>e.trim()).filter(e=>e.length>0)}function zd(r){return r.startsWith(".")?r:`.${r}`}function Od(r,e){return r.classList.contains(e)}function Ao(r){let e=document.createElement("textarea");return r!=null&&r.className&&(e.className=r.className),r!=null&&r.placeholder&&(e.placeholder=r.placeholder),r!=null&&r.rows&&(e.rows=r.rows),r!=null&&r.value&&(e.value=r.value),r!=null&&r.onChange&&(e.onchange=()=>{var n;return(n=r.onChange)==null?void 0:n.call(r,e.value)}),e}var Er=class extends R.PluginSettingTab{constructor(e,n){super(e,n),this.plugin=n}ensureServerConfig(){return this.plugin.settings.opencodeServer||(this.plugin.settings.opencodeServer={url:"",requestTimeoutMs:1e4,autoReconnect:!0,reconnectDelay:3e3,reconnectMaxAttempts:10,useEmbeddedServer:!1,opencodePath:"opencode",embeddedServerPort:4096}),this.plugin.settings.opencodeServer}display(){let{containerEl:e}=this;e.empty(),e.createEl("p",{text:"Configure your OpenCode Obsidian plugin settings. Changes are saved automatically.",cls:"setting-item-description"}),this.renderServerConfiguration(e),this.renderAgentConfiguration(e),this.renderToolPermissions(e),this.renderAdvancedSettings(e)}renderServerConfiguration(e){var t;new R.Setting(e).setName("OpenCode Server").setHeading(),e.createEl("p",{text:"Configure connection to OpenCode Server. Providers and API keys are managed on the server side.",cls:"setting-item-description"});let n=this.ensureServerConfig(),i=(t=n.useEmbeddedServer)!=null?t:!1;if(new R.Setting(e).setName("Use embedded server").setDesc("Run OpenCode Server directly within Obsidian (experimental)").addToggle(o=>{o.setValue(i).onChange(async s=>{n.useEmbeddedServer=s,await this.plugin.saveSettings(),this.display()})}),i){let o=new R.Setting(e);o.setName("Server Status");let s=o.controlEl.createDiv("opencode-server-status"),c=()=>{if(s.empty(),this.plugin.serverManager){let l=this.plugin.serverManager.getState(),u=s.createEl("span",{text:l.charAt(0).toUpperCase()+l.slice(1),cls:`opencode-server-status-${l}`});if(l==="error"){let a=this.plugin.serverManager.getLastError();a&&s.createEl("span",{text:` - ${a.message}`,cls:"opencode-server-status-error-message"})}let d=s.createDiv("opencode-server-control-buttons");if(l==="running"){let a=d.createEl("button",{text:"Stop",cls:"mod-danger"});a.onclick=async()=>{var p;a.disabled=!0,a.textContent="Stopping...",(p=this.plugin.serverManager)==null||p.stop(),await this.plugin.saveSettings(),this.display()}}else if(l==="stopped"||l==="error"){let a=d.createEl("button",{text:"Start",cls:"mod-cta"});a.onclick=async()=>{a.disabled=!0,a.textContent="Starting...",this.plugin.serverManager?await this.plugin.serverManager.start():this.plugin.serverManager=await Promise.resolve().then(()=>(mn(),yr)).then(p=>p.ServerManager.initializeFromConfig(n,this.plugin.errorHandler,m=>this.plugin.handleServerStateChange(m),async m=>{n.url=m,await this.plugin.saveSettings()})),await this.plugin.saveSettings(),this.display()}}}else{s.createEl("span",{text:"Not initialized",cls:"opencode-server-status-stopped"});let l=s.createEl("button",{text:"Initialize",cls:"mod-cta"});l.onclick=async()=>{l.disabled=!0,l.textContent="Initializing...",this.plugin.serverManager=await Promise.resolve().then(()=>(mn(),yr)).then(u=>u.ServerManager.initializeFromConfig(n,this.plugin.errorHandler,d=>this.plugin.handleServerStateChange(d),async d=>{n.url=d,await this.plugin.saveSettings()})),await this.plugin.saveSettings(),this.display()}}};c(),o.addExtraButton(l=>{l.setIcon("refresh-cw").setTooltip("Refresh server status").onClick(()=>{c()})}),new R.Setting(e).setName("OpenCode executable path").setDesc("Path to the opencode executable (e.g., /usr/local/bin/opencode or C:\\Program Files\\OpenCode\\opencode.exe)").addText(l=>{l.setPlaceholder("opencode").setValue(n.opencodePath||"opencode"),l.onChange(async u=>{n.opencodePath=u.trim()||"opencode",await this.plugin.debouncedSaveSettings()})}),new R.Setting(e).setName("Embedded server port").setDesc("Port to run the embedded OpenCo
docs/*.md`,rows:3,value:((d=n.allowedPaths)==null?void 0:d.join(`
`))||"",onChange:async p=>{this.plugin.settings.permissionScope||(this.plugin.settings.permissionScope={});let m=Mo(p);this.plugin.settings.permissionScope.allowedPaths=m.length>0?m:void 0,await this.plugin.debouncedSaveSettings()}});i.controlEl.appendChild(t);let o=new R.Setting(e).setName("Denied paths"),s=this.app.vault.configDir;o.setDesc(`Glob patterns for denied paths (checked first, always denied). Example: **/${s}/**, **/.git/**. One pattern per line.`);let c=Ao({className:"opencode-setting-textarea",placeholder:`**/${s}/**
**/.git/**
**/node_modules/**`,rows:3,value:((a=n.deniedPaths)==null?void 0:a.join(`
`))||"",onChange:async p=>{this.plugin.settings.permissionScope||(this.plugin.settings.permissionScope={});let m=Mo(p);this.plugin.settings.permissionScope.deniedPaths=m.length>0?m:void 0,await this.plugin.debouncedSaveSettings()}});o.controlEl.appendChild(c);let l=new R.Setting(e);l.setName("Maximum file size"),l.setDesc("Maximum file size in bytes (e.g., 10485760 for 10MB). Leave empty for no limit."),l.addText(p=>{let m=n.maxFileSize;p.setPlaceholder("10485760 (10MB)").setValue(m?m.toString():""),p.inputEl.type="number",p.inputEl.min="1",p.onChange(async h=>{this.plugin.settings.permissionScope||(this.plugin.settings.permissionScope={});let g=parseInt(h.trim(),10);this.plugin.settings.permissionScope.maxFileSize=h.trim()&&!isNaN(g)&&g>0?g:void 0,await this.plugin.debouncedSaveSettings()})}),l.addExtraButton(p=>{p.setIcon("help").setTooltip("Common sizes: 1024 (1KB), 1048576 (1MB), 10485760 (10MB), 104857600 (100MB)").onClick(()=>{new R.Notice("1KB=1024, 1MB=1048576, 10MB=10485760, 100MB=104857600")})});let u=new R.Setting(e);u.setName("Allowed file extensions"),u.setDesc("Comma-separated list of allowed file extensions (e.g., .md, .txt, .json). Leave empty to allow all extensions."),u.addText(p=>{var m;p.setPlaceholder(".md, .txt, .json, .yaml").setValue(((m=n.allowedExtensions)==null?void 0:m.join(", "))||""),p.onChange(async h=>{this.plugin.settings.permissionScope||(this.plugin.settings.permissionScope={});let g=Td(h).map(zd);this.plugin.settings.permissionScope.allowedExtensions=g.length>0?g:void 0,await this.plugin.debouncedSaveSettings()})}),u.addExtraButton(p=>{p.setIcon("reset").setTooltip("Reset to default").onClick(()=>{this.plugin.settings.permissionScope&&(this.plugin.settings.permissionScope.allowedExtensions=void 0,this.display(),this.plugin.saveSettings())})})}renderAdvancedSettings(e){let n=e.createDiv("opencode-settings-advanced"),i=n.createDiv("opencode-settings-advanced-header");new R.Setting(i).setName("Advanced").setHeading();let t=i.createEl("button",{text:"Show",cls:"mod-cta"}),o=n.createDiv("opencode-settings-advanced-content");o.addClass("hidden"),t.onclick=()=>{let s=!Od(o,"hidden");s?o.addClass("hidden"):o.removeClass("hidden"),t.textContent=s?"Show":"Hide"},this.renderReconnectionSettings(o),new R.Setting(o).setName("Reset to defaults").setDesc("Reset all settings to default values. This cannot be undone.").addButton(s=>{s.setButtonText("Reset").setWarning().onClick(()=>{new R.Notice("Reset functionality coming soon")})})}renderReconnectionSettings(e){new R.Setting(e).setName("Reconnection").setHeading(),e.createEl("p",{text:"Configure automatic reconnection behavior when connection to OpenCode Server is lost.",cls:"setting-item-description"}),new R.Setting(e).setName("Auto reconnect").setDesc("Automatically attempt to reconnect when connection is lost").addToggle(n=>{var i,t;n.setValue((t=(i=this.plugin.settings.opencodeServer)==null?void 0:i.autoReconnect)!=null?t:!0).onChange(async o=>{let s=this.ensureServerConfig();s.autoReconnect=o,await this.plugin.saveSettings()})}),new R.Setting(e).setName("Reconnect delay").setDesc("Delay between reconnection attempts in milliseconds (default: 3000ms, with exponential backoff)").addText(n=>{var t,o;let i=(o=(t=this.plugin.settings.opencodeServer)==null?void 0:t.reconnectDelay)!=null?o:3e3;n.setPlaceholder("3000").setValue(i.toString()),n.inputEl.type="number",n.inputEl.min="1000",n.onChange(async s=>{let c=this.ensureServerConfig();c.reconnectDelay=vr(s,3e3,1e3),await this.plugin.debouncedSaveSettings()})}),new R.Setting(e).setName("Max reconnect attempts").setDesc("Maximum number of reconnection attempts (0 = unlimited, default: 10)").addText(n=>{var t,o;let i=(o=(t=this.plugin.settings.opencodeServer)==null?void 0:t.reconnectMaxAttempts)!=null?o:10;n.setPlaceholder("10").setValue(i===0?"0":i.toString()),n.inputEl.type="number",n.inputEl.min="0",n.onChange(async s=>{let c=this.ensureServerConfig();c.reconnectMaxAttempts=vr(s,10,0),await this.plugin.debouncedSaveSettings()})}),new R.Setting(e).setName("Request timeout").setDesc("Maximum time to w
`),s=-1;if(i.insertAt!==void 0?s=Math.max(0,Math.min(o.length,i.insertAt-1)):i.insertMarker&&(s=o.findIndex(l=>l.includes(i.insertMarker)),s>=0&&(s+=1)),s>=0){let l=n.createDiv("opencode-obsidian-permission-before");l.createEl("h4",{text:"Before insertion point"}),l.createEl("pre",{cls:"opencode-obsidian-code-preview"}).createEl("code",{text:o.slice(0,s).join(`
`)||"(start of file)"});let d=n.createDiv("opencode-obsidian-permission-insert");d.createEl("h4",{text:`Content to insert at line ${s+1}`}),d.createEl("pre",{cls:"opencode-obsidian-code-preview opencode-obsidian-code-added"}).createEl("code",{text:i.content});let p=n.createDiv("opencode-obsidian-permission-after");p.createEl("h4",{text:"After insertion point"}),p.createEl("pre",{cls:"opencode-obsidian-code-preview"}).createEl("code",{text:o.slice(s).join(`
`)||"(end of file)"})}else n.createEl("p",{text:"Insertion point not found. Content to insert:",cls:"mod-warning"}),n.createEl("pre",{cls:"opencode-obsidian-code-preview"}).createEl("code",{text:i.content})}renderGenericPreview(n){if(!this.request.preview){n.createEl("p",{text:"No preview available",cls:"mod-warning"});return}if(this.request.preview.originalContent){let o=n.createDiv("opencode-obsidian-permission-original");o.createEl("h4",{text:"Original"}),o.createEl("pre",{cls:"opencode-obsidian-code-preview"}).createEl("code",{text:this.request.preview.originalContent})}let i=n.createDiv("opencode-obsidian-permission-new");i.createEl("h4",{text:"Modified"}),i.createEl("pre",{cls:"opencode-obsidian-code-preview"}).createEl("code",{text:this.request.preview.newContent})}onClose(){this.stopCountdown(),this.responseHandled||this.onResponse(!1,"Modal closed without response");let{contentEl:n}=this;n.empty()}};var op=6e4,Tr=class{constructor(e,n,i,t,o){this.client=e;this.eventBus=n;this.permissionManager=i;this.auditLogger=t;this.errorHandler=o;this.app=null;this.pendingRequests=new Map;this.currentModal=null;this.requestQueue=[];this.setupListeners()}setApp(e){this.app=e}setupListeners(){this.eventBus.onPermissionRequest(e=>{this.handleRequest(e)}),this.eventBus.onSessionEnd(e=>{this.cleanupSession(e.sessionId)})}async handleRequest(e){let{sessionId:n,requestId:i,operation:t,resourcePath:o,context:s}=e;try{await this.auditLogger.log({id:`perm_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,timestamp:Date.now(),toolName:(s==null?void 0:s.toolName)||"server.operation",sessionId:n,callId:i,input:{operation:t,resourcePath:o,context:s},permissionLevel:this.permissionManager.getPermissionLevel(),requiredApproval:!0,dryRun:!1,isError:!1});let c=this.mapOperation(t),l=await this.permissionManager.validatePath(o,c);if(!l.allowed){await this.denyRequest(n,i,`Plugin denied: ${l.reason}`);return}await this.showModal(n,i,t,o,s)}catch(c){this.errorHandler.handleError(c,{module:"PermissionCoordinator",function:"handleRequest",metadata:{sessionId:n,requestId:i,operation:t,resourcePath:o}},"error"),await this.denyRequest(n,i,"Internal error")}}mapOperation(e){let n=e.toLowerCase();return n.includes("read")||n.includes("get")?"read":n.includes("create")?"create":n.includes("update")||n.includes("modify")?"modify":n.includes("delete")?"delete":"write"}async denyRequest(e,n,i){try{await this.client.respondToPermission(e,n,!1,i),await this.auditLogger.log({id:`perm_deny_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,timestamp:Date.now(),toolName:"server.operation",sessionId:e,callId:n,input:{reason:i},output:{approved:!1,reason:i},permissionLevel:this.permissionManager.getPermissionLevel(),requiredApproval:!0,approved:!1,dryRun:!1,isError:!1})}catch(t){this.errorHandler.handleError(t,{module:"PermissionCoordinator",function:"denyRequest",metadata:{sessionId:e,requestId:n,reason:i}},"warning")}}async showModal(e,n,i,t,o){if(!this.app)throw new Error("App required for modal");if(this.currentModal){let l=setTimeout(()=>void this.handleTimeout(n),op);this.requestQueue.push({sessionId:e,requestId:n,operation:i,resourcePath:t,context:o,timeoutId:l});return}let s=setTimeout(()=>void this.handleTimeout(n),op);this.pendingRequests.set(n,{sessionId:e,requestId:n,operation:i,resourcePath:t,context:o,timeoutId:s});let c={sessionId:e,callId:n,toolName:(o==null?void 0:o.toolName)||i,args:{path:t,...o==null?void 0:o.args},preview:o==null?void 0:o.preview};this.currentModal=new Tt(this.app,c,async(l,u)=>{await this.handleUserResponse(n,l,u)}),this.currentModal.open()}async handleUserResponse(e,n,i){var o;let t=this.pendingRequests.get(e);if(t){clearTimeout(t.timeoutId),this.pendingRequests.delete(e),this.currentModal=null;try{await this.client.respondToPermission(t.sessionId,e,n,i),await this.auditLogger.log({id:`perm_resp_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,timestamp:Date.now(),toolName:((o=t.context)==null?void 0:o.toolName)||"server.operation",sessionId:t.sessionId,callId:e,input:{operation:t.operation,resourcePath
`)}var Mt=r=>(e,n,i,t)=>{var c;let o=i?Object.assign(i,{async:!1}):{async:!1},s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new ze;if(s.issues.length){let l=new((c=t==null?void 0:t.Err)!=null?c:r)(s.issues.map(u=>ye(u,o,Q())));throw Dr(l,t==null?void 0:t.callee),l}return s.value},Mr=Mt(be),At=r=>async(e,n,i,t)=>{var c;let o=i?Object.assign(i,{async:!0}):{async:!0},s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let l=new((c=t==null?void 0:t.Err)!=null?c:r)(s.issues.map(u=>ye(u,o,Q())));throw Dr(l,t==null?void 0:t.callee),l}return s.value},Ar=At(be),Lt=r=>(e,n,i)=>{let t=i?{...i,async:!1}:{async:!1},o=e._zod.run({value:n,issues:[]},t);if(o instanceof Promise)throw new ze;return o.issues.length?{success:!1,error:new(r!=null?r:kn)(o.issues.map(s=>ye(s,t,Q())))}:{success:!0,data:o.value}},ks=Lt(be),Ut=r=>async(e,n,i)=>{let t=i?Object.assign(i,{async:!0}):{async:!0},o=e._zod.run({value:n,issues:[]},t);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new r(o.issues.map(s=>ye(s,t,Q())))}:{success:!0,data:o.value}},Cs=Ut(be),Lr=r=>(e,n,i)=>{let t=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return Mt(r)(e,n,t)},_f=Lr(be),Ur=r=>(e,n,i)=>Mt(r)(e,n,i),kf=Ur(be),Nr=r=>async(e,n,i)=>{let t=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return At(r)(e,n,t)},Cf=Nr(be),jr=r=>async(e,n,i)=>At(r)(e,n,i),Ef=jr(be),Rr=r=>(e,n,i)=>{let t=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return Lt(r)(e,n,t)},If=Rr(be),Zr=r=>(e,n,i)=>Lt(r)(e,n,i),Pf=Zr(be),Fr=r=>async(e,n,i)=>{let t=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return Ut(r)(e,n,t)},Tf=Fr(be),Hr=r=>async(e,n,i)=>Ut(r)(e,n,i),zf=Hr(be);var we={};$e(we,{base64:()=>Fs,base64url:()=>Vr,bigint:()=>Js,boolean:()=>Ks,browserEmail:()=>jf,cidrv4:()=>Rs,cidrv6:()=>Zs,cuid:()=>Es,cuid2:()=>Is,date:()=>Vs,datetime:()=>Ws,domain:()=>Ff,duration:()=>Ds,e164:()=>Hs,email:()=>As,emoji:()=>Ls,extendedDuration:()=>Of,guid:()=>Ms,hex:()=>Hf,hostname:()=>Zf,html5Email:()=>Lf,idnEmail:()=>Nf,integer:()=>Gs,ipv4:()=>Us,ipv6:()=>Ns,ksuid:()=>zs,lowercase:()=>Qs,mac:()=>js,md5_base64:()=>qf,md5_base64url:()=>Wf,md5_hex:()=>Vf,nanoid:()=>Os,null:()=>Xs,number:()=>qr,rfc5322Email:()=>Uf,sha1_base64:()=>Jf,sha1_base64url:()=>Gf,sha1_hex:()=>Bf,sha256_base64:()=>Xf,sha256_base64url:()=>Yf,sha256_hex:()=>Kf,sha384_base64:()=>ev,sha384_base64url:()=>tv,sha384_hex:()=>Qf,sha512_base64:()=>rv,sha512_base64url:()=>iv,sha512_hex:()=>nv,string:()=>Bs,time:()=>qs,ulid:()=>Ps,undefined:()=>Ys,unicodeEmail:()=>pp,uppercase:()=>ea,uuid:()=>pt,uuid4:()=>Df,uuid6:()=>Mf,uuid7:()=>Af,xid:()=>Ts});var Es=/^[cC][^\s-]{8,}$/,Is=/^[0-9a-z]+$/,Ps=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ts=/^[0-9a-vA-V]{20}$/,zs=/^[A-Za-z0-9]{27}$/,Os=/^[a-zA-Z0-9_-]{21}$/,Ds=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Of=/^[-+]?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)?)??$/,Ms=/^([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})$/,pt=r=>r?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${r}[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)$/,Df=pt(4),Mf=pt(6),Af=pt(7),As=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Lf=/^[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])?)*$/,Uf=/^(([^<>()\[\]\\.,;:\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,}))$/,pp=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,Nf=pp,
`).filter(s=>s),t=Math.min(...i.map(s=>s.length-s.trimStart().length)),o=i.map(s=>s.slice(t)).map(s=>" ".repeat(this.indent*2)+s);for(let s of o)this.content.push(s)}compile(){var o;let e=Function,n=this==null?void 0:this.args,t=[...((o=this==null?void 0:this.content)!=null?o:[""]).map(s=>` ${s}`)];return new e(...n,t.join(`
`))}};var ba={major:4,minor:3,patch:5};var A=f("$ZodType",(r,e)=>{var t,o,s;var n;r!=null||(r={}),r._zod.def=e,r._zod.bag=r._zod.bag||{},r._zod.version=ba;let i=[...(t=r._zod.def.checks)!=null?t:[]];r._zod.traits.has("$ZodCheck")&&i.unshift(r);for(let c of i)for(let l of c._zod.onattach)l(r);if(i.length===0)(o=(n=r._zod).deferred)!=null||(n.deferred=[]),(s=r._zod.deferred)==null||s.push(()=>{r._zod.run=r._zod.parse});else{let c=(u,d,a)=>{let p=Ge(u),m;for(let h of d){if(h._zod.def.when){if(!h._zod.def.when(u))continue}else if(p)continue;let g=u.issues.length,y=h._zod.check(u);if(y instanceof Promise&&(a==null?void 0:a.async)===!1)throw new ze;if(m||y instanceof Promise)m=(m!=null?m:Promise.resolve()).then(async()=>{await y,u.issues.length!==g&&(p||(p=Ge(u,g)))});else{if(u.issues.length===g)continue;p||(p=Ge(u,g))}}return m?m.then(()=>u):u},l=(u,d,a)=>{if(Ge(u))return u.aborted=!0,u;let p=c(d,i,a);if(p instanceof Promise){if(a.async===!1)throw new ze;return p.then(m=>r._zod.parse(m,a))}return r._zod.parse(p,a)};r._zod.run=(u,d)=>{if(d.skipChecks)return r._zod.parse(u,d);if(d.direction==="backward"){let p=r._zod.parse({value:u.value,issues:[]},{...d,skipChecks:!0});return p instanceof Promise?p.then(m=>l(m,u,d)):l(p,u,d)}let a=r._zod.parse(u,d);if(a instanceof Promise){if(d.async===!1)throw new ze;return a.then(p=>c(p,i,d))}return c(a,i,d)}}U(r,"~standard",()=>({validate:c=>{var l;try{let u=ks(r,c);return u.success?{value:u.data}:{issues:(l=u.error)==null?void 0:l.issues}}catch(u){return Cs(r,c).then(d=>{var a;return d.success?{value:d.data}:{issues:(a=d.error)==null?void 0:a.issues}})}},vendor:"zod",version:1}))}),mt=f("$ZodString",(r,e)=>{var n,i,t;A.init(r,e),r._zod.pattern=(t=[...(i=(n=r==null?void 0:r._zod.bag)==null?void 0:n.patterns)!=null?i:[]].pop())!=null?t:Bs(r._zod.bag),r._zod.parse=(o,s)=>{if(e.coerce)try{o.value=String(o.value)}catch(c){}return typeof o.value=="string"||o.issues.push({expected:"string",code:"invalid_type",input:o.value,inst:r}),o}}),W=f("$ZodStringFormat",(r,e)=>{Nt.init(r,e),mt.init(r,e)}),$a=f("$ZodGUID",(r,e)=>{var n;(n=e.pattern)!=null||(e.pattern=Ms),W.init(r,e)}),xa=f("$ZodUUID",(r,e)=>{var n,i;if(e.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(o===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);(n=e.pattern)!=null||(e.pattern=pt(o))}else(i=e.pattern)!=null||(e.pattern=pt());W.init(r,e)}),wa=f("$ZodEmail",(r,e)=>{var n;(n=e.pattern)!=null||(e.pattern=As),W.init(r,e)}),_a=f("$ZodURL",(r,e)=>{W.init(r,e),r._zod.check=n=>{try{let i=n.value.trim(),t=new URL(i);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(t.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:n.value,inst:r,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(t.protocol.endsWith(":")?t.protocol.slice(0,-1):t.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:r,continue:!e.abort})),e.normalize?n.value=t.href:n.value=i;return}catch(i){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:r,continue:!e.abort})}}}),ka=f("$ZodEmoji",(r,e)=>{var n;(n=e.pattern)!=null||(e.pattern=Ls()),W.init(r,e)}),Ca=f("$ZodNanoID",(r,e)=>{var n;(n=e.pattern)!=null||(e.pattern=Os),W.init(r,e)}),Ea=f("$ZodCUID",(r,e)=>{var n;(n=e.pattern)!=null||(e.pattern=Es),W.init(r,e)}),Ia=f("$ZodCUID2",(r,e)=>{var n;(n=e.pattern)!=null||(e.pattern=Is),W.init(r,e)}),Pa=f("$ZodULID",(r,e)=>{var n;(n=e.pattern)!=null||(e.pattern=Ps),W.init(r,e)}),Ta=f("$ZodXID",(r,e)=>{var n;(n=e.pattern)!=null||(e.pattern=Ts),W.init(r,e)}),za=f("$ZodKSUID",(r,e)=>{var n;(n=e.pattern)!=null||(e.pattern=zs),W.init(r,e)}),Oa=f("$ZodISODateTime",(r,e)=>{var n;(n=e.pattern)!=null||(e.pattern=Ws(e)),W.init(r,e)}),Da=f("$ZodISODate",(r,e)=>{var n;(n=e.pattern)!=null||(e.pattern=Vs),W.init(r,e)}),Ma=f("$ZodISOTime",(r,e)=>{var n;(n=e.pattern)!=null||(e.pattern=qs(e)),W.init(r,e)}),Aa=f("$ZodISODuration",(r,e)=>{var n;(n=e.pattern)!=null||(e.pattern=Ds),W.init(r,e)
if (${x}.issues.length) {
if (${M} in input) {
payload.issues = payload.issues.concat(${x}.issues.map(iss => ({
...iss,
path: iss.path ? [${M}, ...iss.path] : [${M}]
})));
}
}
if (${x}.value === undefined) {
if (${M} in input) {
newResult[${M}] = undefined;
}
} else {
newResult[${M}] = ${x}.value;
}
`):m.write(`
if (${x}.issues.length) {
payload.issues = payload.issues.concat(${x}.issues.map(iss => ({
...iss,
path: iss.path ? [${M}, ...iss.path] : [${M}]
})));
}
if (${x}.value === undefined) {
if (${M} in input) {
newResult[${M}] = undefined;
}
} else {
newResult[${M}] = ${x}.value;
}
`)}m.write("payload.value = newResult;"),m.write("return payload;");let $=m.compile();return(S,x)=>$(p,S,x)},o,s=dt,c=!yn.jitless,u=c&&vs.value,d=e.catchall,a;r._zod.parse=(p,m)=>{a!=null||(a=i.value);let h=p.value;return s(h)?c&&u&&(m==null?void 0:m.async)===!1&&m.jitless!==!0?(o||(o=t(e.shape)),p=o(p,m),d?Op([],h,p,m,a,r):p):n(p,m):(p.issues.push({expected:"object",code:"invalid_type",input:h,inst:r}),p)}});function bp(r,e,n,i){for(let o of r)if(o.issues.length===0)return e.value=o.value,e;let t=r.filter(o=>!Ge(o));return t.length===1?(e.value=t[0].value,t[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:r.map(o=>o.issues.map(s=>ye(s,i,Q())))}),e)}var On=f("$ZodUnion",(r,e)=>{A.init(r,e),U(r._zod,"optin",()=>e.options.some(t=>t._zod.optin==="optional")?"optional":void 0),U(r._zod,"optout",()=>e.options.some(t=>t._zod.optout==="optional")?"optional":void 0),U(r._zod,"values",()=>{if(e.options.every(t=>t._zod.values))return new Set(e.options.flatMap(t=>Array.from(t._zod.values)))}),U(r._zod,"pattern",()=>{if(e.options.every(t=>t._zod.pattern)){let t=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${t.map(o=>$n(o.source)).join("|")})$`)}});let n=e.options.length===1,i=e.options[0]._zod.run;r._zod.parse=(t,o)=>{if(n)return i(t,o);let s=!1,c=[];for(let l of e.options){let u=l._zod.run({value:t.value,issues:[]},o);if(u instanceof Promise)c.push(u),s=!0;else{if(u.issues.length===0)return u;c.push(u)}}return s?Promise.all(c).then(l=>bp(l,t,r,o)):bp(c,t,r,o)}});function Sp(r,e,n,i){let t=r.filter(o=>o.issues.length===0);return t.length===1?(e.value=t[0].value,e):(t.length===0?e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:r.map(o=>o.issues.map(s=>ye(s,i,Q())))}):e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:[],inclusive:!1}),e)}var oc=f("$ZodXor",(r,e)=>{On.init(r,e),e.inclusive=!1;let n=e.options.length===1,i=e.options[0]._zod.run;r._zod.parse=(t,o)=>{if(n)return i(t,o);let s=!1,c=[];for(let l of e.options){let u=l._zod.run({value:t.value,issues:[]},o);u instanceof Promise?(c.push(u),s=!0):c.push(u)}return s?Promise.all(c).then(l=>Sp(l,t,r,o)):Sp(c,t,r,o)}}),sc=f("$ZodDiscriminatedUnion",(r,e)=>{e.inclusive=!1,On.init(r,e);let n=r._zod.parse;U(r._zod,"propValues",()=>{let t={};for(let o of e.options){let s=o._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(let[c,l]of Object.entries(s)){t[c]||(t[c]=new Set);for(let u of l)t[c].add(u)}}return t});let i=Ot(()=>{var s;let t=e.options,o=new Map;for(let c of t){let l=(s=c._zod.propValues)==null?void 0:s[e.discriminator];if(!l||l.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(c)}"`);for(let u of l){if(o.has(u))throw new Error(`Duplicate discriminator value "${String(u)}"`);o.set(u,c)}}return o});r._zod.parse=(t,o)=>{let s=t.value;if(!dt(s))return t.issues.push({code:"invalid_type",expected:"object",input:s,inst:r}),t;let c=i.value.get(s==null?void 0:s[e.discriminator]);return c?c._zod.run(t,o):e.unionFallback?n(t,o):(t.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,input:s,path:[e.discriminator],inst:r}),t)}}),ac=f("$ZodIntersection",(r,e)=>{A.init(r,e),r._zod.parse=(n,i)=>{let t=n.value,o=e.left._zod.run({value:t,issues:[]},i),s=e.right._zod.run({value:t,issues:[]},i);return o instanceof Promise||s instanceof Promise?Promise.all([o,s]).then(([l,u])=>$p(n,l,u)):$p(n,o,s)}});function Sa(r,e){if(r===e)return{valid:!0,data:r};if(r instanceof Date&&e instanceof Date&&+r==+e)return{valid:!0,data:r};if(Je(r)&&Je(e)){let n=Object.keys(e),i=Object.keys(r).filter(o=>n.indexOf(o)!==-1),t={...r,...e};for(let o of i){let s=Sa(r[o],e[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};t[o]=s.data}return{valid:!0,data:t}}if(Array.isArray(r)&&Array.isArray(e)){if(r.length!==e.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let i=0;i<r.length;i++){let t=r[i],o=e[i],s=Sa(t,o);if(!s.valid)return{valid:!1,mergeError
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let d of r.seen.entries()){let a=d[1];if(e===d[0]){o(d);continue}if(r.external){let m=(l=r.external.registry.get(d[0]))==null?void 0:l.id;if(e!==d[0]&&m){o(d);continue}}if((u=r.metadataRegistry.get(d[0]))==null?void 0:u.id){o(d);continue}if(a.cycle){o(d);continue}if(a.count>1&&r.reused==="ref"){o(d);continue}}}function et(r,e){var s,c,l,u,d;let n=r.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let i=a=>{var b,$,P;let p=r.seen.get(a);if(p.ref===null)return;let m=(b=p.def)!=null?b:p.schema,h={...m},g=p.ref;if(p.ref=null,g){i(g);let S=r.seen.get(g),x=S.schema;if(x.$ref&&(r.target==="draft-07"||r.target==="draft-04"||r.target==="openapi-3.0")?(m.allOf=($=m.allOf)!=null?$:[],m.allOf.push(x)):Object.assign(m,x),Object.assign(m,h),a._zod.parent===g)for(let G in m)G==="$ref"||G==="allOf"||G in h||delete m[G];if(x.$ref)for(let G in m)G==="$ref"||G==="allOf"||G in S.def&&JSON.stringify(m[G])===JSON.stringify(S.def[G])&&delete m[G]}let y=a._zod.parent;if(y&&y!==g){i(y);let S=r.seen.get(y);if(S!=null&&S.schema.$ref&&(m.$ref=S.schema.$ref,S.def))for(let x in m)x==="$ref"||x==="allOf"||x in S.def&&JSON.stringify(m[x])===JSON.stringify(S.def[x])&&delete m[x]}r.override({zodSchema:a,jsonSchema:m,path:(P=p.path)!=null?P:[]})};for(let a of[...r.seen.entries()].reverse())i(a[0]);let t={};if(r.target==="draft-2020-12"?t.$schema="https://json-schema.org/draft/2020-12/schema":r.target==="draft-07"?t.$schema="http://json-schema.org/draft-07/schema#":r.target==="draft-04"?t.$schema="http://json-schema.org/draft-04/schema#":r.target,(s=r.external)!=null&&s.uri){let a=(c=r.external.registry.get(e))==null?void 0:c.id;if(!a)throw new Error("Schema is missing an `id` property");t.$id=r.external.uri(a)}Object.assign(t,(l=n.def)!=null?l:n.schema);let o=(d=(u=r.external)==null?void 0:u.defs)!=null?d:{};for(let a of r.seen.entries()){let p=a[1];p.def&&p.defId&&(o[p.defId]=p.def)}r.external||Object.keys(o).length>0&&(r.target==="draft-2020-12"?t.$defs=o:t.definitions=o);try{let a=JSON.parse(JSON.stringify(t));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:Qt(e,"input",r.processors),output:Qt(e,"output",r.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw new Error("Error converting schema to JSON.")}}function he(r,e){let n=e!=null?e:{seen:new Set};if(n.seen.has(r))return!1;n.seen.add(r);let i=r._zod.def;if(i.type==="transform")return!0;if(i.type==="array")return he(i.element,n);if(i.type==="set")return he(i.valueType,n);if(i.type==="lazy")return he(i.getter(),n);if(i.type==="promise"||i.type==="optional"||i.type==="nonoptional"||i.type==="nullable"||i.type==="readonly"||i.type==="default"||i.type==="prefault")return he(i.innerType,n);if(i.type==="intersection")return he(i.left,n)||he(i.right,n);if(i.type==="record"||i.type==="map")return he(i.keyType,n)||he(i.valueType,n);if(i.type==="pipe")return he(i.in,n)||he(i.out,n);if(i.type==="object"){for(let t in i.shape)if(he(i.shape[t],n))return!0;return!1}if(i.type==="union"){for(let t of i.options)if(he(t,n))return!0;return!1}if(i.type==="tuple"){for(let t of i.items)if(he(t,n))return!0;return!!(i.rest&&he(i.rest,n))}return!1}var vl=(r,e={})=>n=>{let i=Ye({...n,processors:e});return H(r,i),Qe(i,r),et(i,r)},Qt=(r,e,n={})=>i=>{let{libraryOptions:t,target:o}=i!=null?i:{},s=Ye({...t!=null?t:{},target:o,io:e,processors:n});return H(r,s),Qe(s,r),et(s,r)};var wy={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},yl=(r,e,n,i)=>{var d;let t=n;t.type="string";let{minimum:o,maximum:s,format:c,patterns:l,contentEncoding:u}=r._zod.bag;if(typeof o=="number"&&(t.minLength=o),typeof s=="number"&&(t.maxLength=s),c&&(t.format=(d=wy[c])!=null?d:c,t.format===""&&delete t.format,c==="time"&&delete t.format),u&&(t.contentEncoding=u),l&&l.size>0){let a=[...l];a.length===1?t.pattern=a[0].source:a.length>1&&(t.allOf=[...a.map(p=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source
`).length,characterCount:c.length},p;if(l!=null&&l.title&&typeof l.title=="string")p=l.title;else{let h=c.match(/^#+\s+(.+)$/m);p=((m=h==null?void 0:h[1])==null?void 0:m.trim())||o.basename}return{path:e.path,exists:!0,title:p,frontmatter:e.includeProperties?l:void 0,tags:u,links:d,stats:a}})}async generatePreview(e,n,i,t){let o=Date.now(),s=t||`preview_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;if(e==="obsidian.read_note"){let c=n;try{let l=await this.permissionManager.canRead(c.path);if(!l.allowed)throw await this.createAuditLog(e,i,s,n,o,"read",void 0,new Error(`Permission denied for preview: ${l.reason}`),c.path),new Error(`Permission denied: ${l.reason}`)}catch(l){throw await this.createAuditLog(e,i,s,n,o,"read",void 0,l instanceof Error?l:new Error(String(l)),c.path),l}try{let l,u=this.vault.getAbstractFileByPath(c.path);return bo(u)&&(l=await this.vault.read(u)),await this.createAuditLog(e,i,s,n,o,"read",{preview:{originalContent:l,path:c.path}},void 0,c.path),{originalContent:l,path:c.path}}catch(l){return await this.createAuditLog(e,i,s,n,o,"read",void 0,l instanceof Error?l:new Error(String(l)),c.path),console.warn("[VaultReader] Failed to generate preview:",l),{originalContent:void 0,path:c.path}}}}};function Gn(r){return r!==null&&r instanceof Yh.TFile}function Xh(r){return r!==null&&!("extension"in r)&&"children"in r}var $t=class extends Error{constructor(e){super(e),this.name="PermissionPendingError"}},xo=class{constructor(e,n,i,t,o){this.vault=e,this.app=n,this.metadataCache=i,this.permissionManager=t,this.auditLogger=o,this.reader=new $o(e,n,i,t,o)}generateLogId(){return`log_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}async createAuditLog(e,n,i,t,o,s,c,l,u,d,a){let p=Date.now()-o,m=this.permissionManager.getPermissionLevel(),h=s!=="read"&&this.permissionManager.requiresApproval(e,s),g={id:this.generateLogId(),timestamp:o,toolName:e,sessionId:n,callId:i,input:t,output:c!==void 0?c:void 0,isError:!!l,error:l==null?void 0:l.message,permissionLevel:m,requiredApproval:h,approved:h?d:void 0,dryRun:a||!1,affectedPath:u,duration:p};await this.auditLogger.log(g)}async executeWithAuditLog(e,n,i,t,o,s,c=!1,l=!1,u){let d=Date.now();try{let a=await u();return await this.createAuditLog(e,n,i,t,d,o,a,void 0,s,c,l),a}catch(a){throw await this.createAuditLog(e,n,i,t,d,o,void 0,a instanceof Error?a:new Error(String(a)),s,c,l),a}}async searchVault(e,n,i){return this.reader.searchVault(e,n,i)}async readNote(e,n,i){return this.reader.readNote(e,n,i)}async listNotes(e,n,i){return this.reader.listNotes(e,n,i)}async getNoteMetadata(e,n,i){return this.reader.getNoteMetadata(e,n,i)}async createNote(e,n,i,t=!1){let o=i||`call_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;return this.executeWithAuditLog("obsidian.create_note",n,o,e,"create",e.path,t,!1,async()=>{let s=await this.permissionManager.canCreate(e.path);if(!s.allowed)throw new Error(`Permission denied: ${s.reason}`);if(this.permissionManager.requiresApproval("obsidian.create_note","create")&&!t)throw new $t("User approval required for create operation");let c=this.vault.getAbstractFileByPath(e.path),l=Gn(c);if(l&&!e.overwrite)throw new Error(`File already exists: ${e.path}. Use overwrite=true to replace it.`);if(l&&Gn(c))await this.vault.modify(c,e.content);else{let u=e.path.split("/");if(u.length>1){let d=u.slice(0,-1).join("/"),a=this.vault.getAbstractFileByPath(d);Xh(a)||await this.vault.createFolder(d)}await this.vault.create(e.path,e.content)}return{path:e.path,created:!0,existed:l}})}async updateNote(e,n,i,t=!1){var c,l,u;let o=Date.now(),s=i||`call_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;try{let d=await this.permissionManager.canModify(e.path);if(!d.allowed){let $=new Error(`Permission denied: ${d.reason}`);throw await this.createAuditLog("obsidian.update_note",n,s,e,o,"modify",void 0,$,e.path,!1,(c=e.dryRun)!=null?c:!0),$}let a=this.vault.getAbstractFileByPath(e.path),p=Gn(a)?await this.vault.read(a):"",m,h=0,g=0;switch(e.mode){case"replace":m=e.content,p&&(g=p.split(`
`).length),h=m.split(`
`).length;break;case"append":m=p+(p&&!p.endsWith(`
`)?`
`:"")+e.content,h=e.content.split(`
`).length;break;case"prepend":m=e.content+(e.content&&!e.content.endsWith(`
`)?`
`:"")+p,h=e.content.split(`
`).length;break;case"insert":{if(!e.insertAt&&!e.insertMarker)throw new Error("insertAt or insertMarker is required for insert mode");let $=p.split(`
`),P;if(e.insertAt!==void 0)P=Math.max(0,Math.min($.length,e.insertAt-1));else if(e.insertMarker){let x=$.findIndex(M=>M.includes(e.insertMarker));if(x===-1)throw new Error(`Marker "${e.insertMarker}" not found in file`);P=x+1}else throw new Error("insertAt or insertMarker is required for insert mode");let S=e.content.split(`
`);$.splice(P,0,...S),m=$.join(`
`),h=S.length;break}default:throw new Error(`Unknown update mode: ${String(e.mode)}`)}if(p){let $=p.split(`
`).length,P=m.split(`
`).length;e.mode==="replace"?(g=$,h=P):h=P-$}else h=m.split(`
`).length;let y={originalContent:p||void 0,newContent:m,addedLines:h,removedLines:e.mode==="replace"&&p?g:void 0};if((l=e.dryRun)==null||l){let $={path:e.path,updated:!1,mode:e.mode,preview:y};return await this.createAuditLog("obsidian.update_note",n,s,e,o,"modify",$,void 0,e.path,!1,!0),$}if(this.permissionManager.requiresApproval("obsidian.update_note","modify")&&!t)throw new $t("User approval required for update note operation");if(Gn(a))await this.vault.modify(a,m);else{let $=e.path.split("/");if($.length>1){let P=$.slice(0,-1).join("/"),S=this.vault.getAbstractFileByPath(P);Xh(S)||await this.vault.createFolder(P)}await this.vault.create(e.path,m)}let b={path:e.path,updated:!0,mode:e.mode,preview:y};return await this.createAuditLog("obsidian.update_note",n,s,e,o,"modify",b,void 0,e.path,t,!1),b}catch(d){throw d instanceof $t||await this.createAuditLog("obsidian.update_note",n,s,e,o,"modify",void 0,d instanceof Error?d:new Error(String(d)),e.path,t,(u=e.dryRun)!=null?u:!0),d}}async generatePreview(e,n,i,t){if(e==="obsidian.read_note"){let c=await this.reader.generatePreview(e,n,i,t);return c?{originalContent:c.originalContent,newContent:c.originalContent||"",mode:"read"}:void 0}let o=Date.now(),s=t||`preview_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;if(e==="obsidian.update_note"){let c=n;try{let l=await this.permissionManager.canRead(c.path);if(!l.allowed)throw await this.createAuditLog(e,i,s,n,o,"read",void 0,new Error(`Permission denied for preview: ${l.reason}`),c.path,!1,!0),new Error(`Permission denied: ${l.reason}`)}catch(l){throw await this.createAuditLog(e,i,s,n,o,"read",void 0,l instanceof Error?l:new Error(String(l)),c.path,!1,!0),l}try{let l,u=this.vault.getAbstractFileByPath(c.path);Gn(u)&&(l=await this.vault.read(u));let d=c.content;l!==void 0&&(c.mode==="append"?d=l+(l&&!l.endsWith(`
`)?`
`:"")+c.content:c.mode==="prepend"?d=c.content+(c.content&&!c.content.endsWith(`
`)?`
`:"")+l:(c.mode==="replace"||c.mode==="insert")&&(d=c.content));let a=l?l.split(`
`).length:0,p=d.split(`
`).length,m=p>a?p-a:0,h=p<a?a-p:0;return await this.createAuditLog(e,i,s,n,o,"read",{preview:{originalContent:l,newContent:d,mode:c.mode,addedLines:m,removedLines:h}},void 0,c.path,void 0,!0),{originalContent:l,newContent:d,mode:c.mode,addedLines:m,removedLines:h}}catch(l){return await this.createAuditLog(e,i,s,n,o,"read",void 0,l instanceof Error?l:new Error(String(l)),c.path,!1,!0),console.warn("[ObsidianToolExecutor] Failed to generate preview:",l),{originalContent:void 0,newContent:c.content,mode:c.mode}}}}};var Ny=E.object({query:E.string().describe("Search query string"),limit:E.number().int().positive().optional().default(20).describe("Maximum number of results to return"),includeContent:E.boolean().optional().default(!1).describe("Whether to include content snippets in results")}),jy=E.object({results:E.array(E.object({path:E.string().describe("File path"),title:E.string().optional().describe("File title or name"),content:E.string().optional().describe("Content snippet if includeContent is true"),matchCount:E.number().optional().describe("Number of matches found in this file")})),totalMatches:E.number().describe("Total number of matching files found")}),Ry=E.object({path:E.string().describe("Path to the note file (relative to vault root)")}),Zy=E.object({path:E.string().describe("File path"),content:E.string().describe("File content"),exists:E.boolean().describe("Whether the file exists")}),Fy=E.object({folder:E.string().optional().default("").describe("Folder path to list (empty string for vault root)"),recursive:E.boolean().optional().default(!0).describe("Whether to list files recursively"),includeFolders:E.boolean().optional().default(!1).describe("Whether to include folder paths in results")}),Hy=E.object({files:E.array(E.object({path:E.string().describe("File or folder path"),isFolder:E.boolean().optional().describe("Whether this is a folder (only if includeFolders is true)"),size:E.number().optional().describe("File size in bytes"),modified:E.number().optional().describe("Last modification timestamp (milliseconds since epoch)")})),totalCount:E.number().describe("Total number of items found")}),Vy=E.object({path:E.string().describe("Path where the note should be created (relative to vault root)"),content:E.string().describe("Content to write to the note"),overwrite:E.boolean().optional().default(!1).describe("Whether to overwrite if file already exists")}),qy=E.object({path:E.string().describe("File path that was created"),created:E.boolean().describe("Whether the file was actually created (false if dryRun or permission denied)"),existed:E.boolean().optional().describe("Whether the file already existed before this operation")}),Wy=E.object({path:E.string().describe("Path to the note file"),content:E.string().describe("Content to update with"),mode:E.enum(["replace","append","prepend","insert"]).describe("Update mode"),insertAt:E.number().optional().describe("Line number to insert at (required for insert mode)"),insertMarker:E.string().optional().describe("Marker string to insert after (alternative to insertAt)"),dryRun:E.boolean().optional().default(!0).describe("Whether to preview changes without applying them")}),By=E.object({path:E.string().describe("File path that was updated"),updated:E.boolean().describe("Whether the file was actually updated (false if dryRun or permission denied)"),mode:E.string().describe("Update mode that was used"),preview:E.object({originalContent:E.string().optional().describe("Original file content"),newContent:E.string().describe("Content after update"),addedLines:E.number().optional().describe("Number of lines added"),removedLines:E.number().optional().describe("Number of lines removed")}).optional().describe("Preview of changes (always included if dryRun=true)")}),Jy=E.object({path:E.string().describe("Path to the note file"),includeLinks:E.boolean().optional().default(!0).describe("Whether to include link relationships"),includeTags:E.boolean().optional().default(!0).describe("Whether to include tags"),includeProperties:E.boolean().optional().default(!0).describe("Whether
globstar while`,e,p,n,m,h),this.matchOne(e.slice(p),n.slice(m),i))return this.debug("globstar found match!",p,l,h),!0;if(h==="."||h===".."||!t.dot&&h.charAt(0)==="."){this.debug("dot detected!",e,p,n,m);break}this.debug("globstar swallow a segment, and continue"),p++}return!!(i&&(this.debug(`
>>> no match, partial?`,e,p,n,m),p===l))}let g;if(typeof d=="string"?(g=a===d,this.debug("string match",d,a,g)):(g=d.test(a),this.debug("pattern match",d,a,g)),!g)return!1}if(s===l&&c===u)return!0;if(s===l)return i;if(c===u)return s===l-1&&e[s]==="";throw new Error("wtf?")}braceExpand(){return Sg(this.pattern,this.options)}parse(e){Xn(e);let n=this.options;if(e==="**")return Ie;if(e==="")return"";let i,t=null;(i=e.match(zb))?t=n.dot?Db:Ob:(i=e.match($b))?t=(n.nocase?n.dot?kb:_b:n.dot?wb:xb)(i[1]):(i=e.match(Mb))?t=(n.nocase?n.dot?Lb:Ab:n.dot?Ub:Nb)(i):(i=e.match(Cb))?t=n.dot?Ib:Eb:(i=e.match(Pb))&&(t=Tb);let o=an.fromGlob(e,this.options).toMMPattern();return t&&typeof o=="object"&&Reflect.defineProperty(o,"test",{value:t}),o}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let n=this.options,i=n.noglobstar?Zb:n.dot?Fb:Hb,t=new Set(n.nocase?["i"]:[]),o=e.map(l=>{let u=l.map(a=>{if(a instanceof RegExp)for(let p of a.flags.split(""))t.add(p);return typeof a=="string"?Jb(a):a===Ie?Ie:a._src});u.forEach((a,p)=>{let m=u[p+1],h=u[p-1];a!==Ie||h===Ie||(h===void 0?m!==void 0&&m!==Ie?u[p+1]="(?:\\/|"+i+"\\/)?"+m:u[p]=i:m===void 0?u[p-1]=h+"(?:\\/|\\/"+i+")?":m!==Ie&&(u[p-1]=h+"(?:\\/|\\/"+i+"\\/)"+m,u[p+1]=Ie))});let d=u.filter(a=>a!==Ie);if(this.partial&&d.length>=1){let a=[];for(let p=1;p<=d.length;p++)a.push(d.slice(0,p).join("/"));return"(?:"+a.join("|")+")"}return d.join("/")}).join("|"),[s,c]=e.length>1?["(?:",")"]:["",""];o="^"+s+o+c+"$",this.partial&&(o="^(?:\\/|"+s+o.slice(1,-1)+c+")$"),this.negate&&(o="^(?!"+o+").+$");try{this.regexp=new RegExp(o,[...t].join(""))}catch(l){this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,n=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&n)return!0;let i=this.options;this.isWindows&&(e=e.split("\\").join("/"));let t=this.slashSplit(e);this.debug(this.pattern,"split",t);let o=this.set;this.debug(this.pattern,"set",o);let s=t[t.length-1];if(!s)for(let c=t.length-2;!s&&c>=0;c--)s=t[c];for(let c=0;c<o.length;c++){let l=o[c],u=t;if(i.matchBase&&l.length===1&&(u=[s]),this.matchOne(u,l,n))return i.flipNegate?!0:!this.negate}return i.flipNegate?!1:this.negate}static defaults(e){return re.defaults(e).Minimatch}};re.AST=an;re.Minimatch=cn;re.escape=gd;re.unescape=tt;var xg={"read-only":{allowedPaths:void 0,deniedPaths:void 0,maxFileSize:void 0,allowedExtensions:void 0},"scoped-write":{allowedPaths:void 0,deniedPaths:["**/.obsidian/**","**/.git/**","**/node_modules/**","**/.opencode/**"],maxFileSize:10485760,allowedExtensions:[".md",".txt",".json",".yaml",".yml",".toml"]},"full-write":{allowedPaths:void 0,deniedPaths:["**/.obsidian/workspace.json","**/.obsidian/hotkeys.json","**/.obsidian/appearance.json"],maxFileSize:void 0,allowedExtensions:void 0}};var Co=class{constructor(e,n="read-only",i){this.vault=e,this.permissionLevel=n,this.scope=this.mergeScopeWithDefaults(i||{},n)}mergeScopeWithDefaults(e,n){var o,s,c,l,u,d;let i=xg[n];return{allowedPaths:(s=(o=e.allowedPaths)!=null?o:i.allowedPaths)!=null?s:void 0,deniedPaths:[...i.deniedPaths||[],...e.deniedPaths||[]],maxFileSize:(l=(c=e.maxFileSize)!=null?c:i.maxFileSize)!=null?l:void 0,allowedExtensions:(d=(u=e.allowedExtensions)!=null?u:i.allowedExtensions)!=null?d:void 0}}setPermissionLevel(e){this.permissionLevel=e,this.scope=this.mergeScopeWithDefaults(this.scope,e)}setScope(e){this.scope=this.mergeScopeWithDefaults(e,this.permissionLevel)}async canRead(e){return this.validatePath(e,"read")}async canWrite(e){return this.permissionLevel==="read-only"?{allowed:!1,reason:"Permission level is read-only. Write operations are not allowed.",secrets:!1}:this.validatePath(e,"write")}async canCreate(e){return this.permissionLevel==="read-only"?{allowed:!1,reason:"Permission level is read-only. Create operations are not allowed.",secrets:!1}:this.validatePath(e,"create")}async canModify(e)
`,s=this.vault.getAbstractFileByPath(t);if(s&&s instanceof fd.TFile){let c=await this.vault.read(s);await this.vault.modify(s,c+o)}else await this.vault.create(t,o)}catch(o){throw console.error(`[AuditLogger] Failed to persist log to ${t}:`,o),o}}async ensureAuditDir(){try{this.vault.getAbstractFileByPath(this.auditDir)||await this.vault.createFolder(this.auditDir)}catch(e){console.warn(`[AuditLogger] Could not ensure audit directory exists: ${String(e)}`)}}formatDate(e){let n=e.getFullYear(),i=String(e.getMonth()+1).padStart(2,"0"),t=String(e.getDate()).padStart(2,"0");return`${n}-${i}-${t}`}async getLogs(e){try{let n=[...this.inMemoryLogs];if((e!=null&&e.startTime||e!=null&&e.endTime||e!=null&&e.offset||e!=null&&e.limit)&&(n=[...await this.loadLogsFromFiles(e),...this.inMemoryLogs],n.sort((t,o)=>o.timestamp-t.timestamp)),n=this.applyFilters(n,e),e!=null&&e.offset||e!=null&&e.limit){let i=e.offset||0,t=e.limit||100;n=n.slice(i,i+t)}return n}catch(n){return console.error("[AuditLogger] Failed to query logs:",n),[]}}async loadLogsFromFiles(e){let n=[],i,t;if(e!=null&&e.startTime&&(i=new Date(e.startTime)),e!=null&&e.endTime&&(t=new Date(e.endTime)),!i&&!t){let l=new Date,u=this.formatDate(l),d=`${this.auditDir}/${u}.jsonl`,a=await this.loadLogsFromFile(d);return n.push(...a),n}let o=i||new Date(Date.now()-30*24*60*60*1e3),s=t||new Date,c=new Date(o);for(;c<=s;){let l=this.formatDate(c),u=`${this.auditDir}/${l}.jsonl`,d=await this.loadLogsFromFile(u);n.push(...d),c.setDate(c.getDate()+1)}return n}async loadLogsFromFile(e){try{let n=this.vault.getAbstractFileByPath(e);if(!n||!(n instanceof fd.TFile))return[];let t=(await this.vault.read(n)).split(`
`).filter(s=>s.trim()),o=[];for(let s of t)try{let c=JSON.parse(s);o.push(c)}catch(c){console.warn(`[AuditLogger] Skipping malformed log line in ${e}:`,c)}return o}catch(n){return[]}}applyFilters(e,n){return n?e.filter(i=>!(n.toolName&&i.toolName!==n.toolName||n.sessionId&&i.sessionId!==n.sessionId||n.callId&&i.callId!==n.callId||n.startTime&&i.timestamp<n.startTime||n.endTime&&i.timestamp>n.endTime||n.pathPattern&&i.affectedPath&&!re(i.affectedPath,n.pathPattern)||n.permissionLevel&&i.permissionLevel!==n.permissionLevel||n.isError!==void 0&&i.isError!==n.isError||n.approved!==void 0&&i.approved!==n.approved||n.dryRun!==void 0&&i.dryRun!==n.dryRun)):e}async cleanupOldLogs(){try{let e=new Date;if(e.setDate(e.getDate()-this.retentionDays),!this.vault.getAbstractFileByPath(this.auditDir))return;console.debug("[AuditLogger] Cleanup not implemented - requires file system access to list files"),console.debug(`[AuditLogger] Retention policy: keep last ${this.retentionDays} days`)}catch(e){console.error("[AuditLogger] Failed to cleanup old logs:",e)}}async getStats(e){let n=await this.getLogs(e),i={total:n.length,byTool:{},byError:{errors:0,successes:0},byApproval:{approved:0,rejected:0,notRequired:0}};for(let t of n)i.byTool[t.toolName]=(i.byTool[t.toolName]||0)+1,t.isError?i.byError.errors++:i.byError.successes++,t.requiredApproval?t.approved===!0?i.byApproval.approved++:t.approved===!1&&i.byApproval.rejected++:i.byApproval.notRequired++;return i}setRetentionDays(e){this.retentionDays=e}getRetentionDays(){return this.retentionDays}async queryBySession(e){try{return(await this.getLogs()).filter(i=>i.sessionId===e)}catch(n){return console.error("[AuditLogger] Failed to query logs by session:",n),[]}}async queryByRequestId(e){try{return(await this.getLogs()).filter(i=>i.callId===e)}catch(n){return console.error("[AuditLogger] Failed to query logs by request ID:",n),[]}}};var Eo=class{constructor(){this.streamTokenListeners=[];this.streamThinkingListeners=[];this.errorListeners=[];this.progressUpdateListeners=[];this.sessionEndListeners=[];this.permissionRequestListeners=[]}onStreamToken(e){return this.streamTokenListeners.push(e),()=>{this.streamTokenListeners=this.streamTokenListeners.filter(n=>n!==e)}}onStreamThinking(e){return this.streamThinkingListeners.push(e),()=>{this.streamThinkingListeners=this.streamThinkingListeners.filter(n=>n!==e)}}onProgressUpdate(e){return this.progressUpdateListeners.push(e),()=>{this.progressUpdateListeners=this.progressUpdateListeners.filter(n=>n!==e)}}onSessionEnd(e){return this.sessionEndListeners.push(e),()=>{this.sessionEndListeners=this.sessionEndListeners.filter(n=>n!==e)}}onPermissionRequest(e){return this.permissionRequestListeners.push(e),()=>{this.permissionRequestListeners=this.permissionRequestListeners.filter(n=>n!==e)}}onError(e){return this.errorListeners.push(e),()=>{this.errorListeners=this.errorListeners.filter(n=>n!==e)}}emitStreamToken(e){for(let n of this.streamTokenListeners)n(e)}emitStreamThinking(e){for(let n of this.streamThinkingListeners)n(e)}emitProgressUpdate(e){for(let n of this.progressUpdateListeners)n(e)}emitSessionEnd(e){for(let n of this.sessionEndListeners)n(e)}emitPermissionRequest(e){for(let n of this.permissionRequestListeners)n(e)}emitError(e){for(let n of this.errorListeners)n(e)}};mn();se();var Io=class{constructor(e={},n){this.items=[];this.categories=[];this.state="idle";this.itemListeners=[];this.stateListeners=[];this.config={autoSave:!0,defaultPriority:"medium",defaultStatus:"pending",showCompleted:!0,...e},this.errorHandler=n,this.errorHandler.handleError(new Error(`TodoManager initialized with config: ${JSON.stringify(this.config)}`),{module:"TodoManager",function:"constructor"},"info")}setState(e,n){let i=this.state;this.state=e,i!==e&&this.notifyStateChange({state:e,error:n,timestamp:Date.now()})}notifyItemChange(e){this.errorHandler.handleError(new Error(`Todo state changed: ${e.type} - ${e.item.id}`),{module:"TodoManager",function:"notifyItemChange"},"info");for(let n of this.itemListeners)try{n(e)}catch(i){this.errorHandler.handleError(i,{m
module.exports = To;