From b74f7d9e33b10c2d0c6859f82fd3bad8ec038cf9 Mon Sep 17 00:00:00 2001 From: Johan Dahlin Date: Fri, 16 Jan 2026 00:12:59 +0100 Subject: [PATCH] vault backup: 2026-01-16 00:12:59 --- .../.obsidian/plugins/agent-client/main.js | 2 +- .../plugins/agent-client/manifest.json | 2 +- ...25_Scientific_articles_plan_20260106-1.pdf | 3 ++ ...Introduction to Scientifc Writing HT25.pdf | 3 ++ .../Methods & Main Results (TODO).md | 28 +++++++++++++++++++ 5 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 content/Vetenskaplig artikel/HT25_Scientific_articles_plan_20260106-1.pdf create mode 100644 content/Vetenskaplig artikel/Introduction to Scientifc Writing HT25.pdf create mode 100644 content/Vetenskaplig artikel/Methods & Main Results (TODO).md diff --git a/content/.obsidian/plugins/agent-client/main.js b/content/.obsidian/plugins/agent-client/main.js index 4d03aa4..4783ac6 100644 --- a/content/.obsidian/plugins/agent-client/main.js +++ b/content/.obsidian/plugins/agent-client/main.js @@ -152,7 +152,7 @@ This is what the user is currently focusing on. Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let m of e.seen.entries()){let l=m[1];if(t===m[0]){o(m);continue}if(e.external){let p=(u=e.external.registry.get(m[0]))==null?void 0:u.id;if(t!==m[0]&&p){o(m);continue}}if((d=e.metadataRegistry.get(m[0]))==null?void 0:d.id){o(m);continue}if(l.cycle){o(m);continue}if(l.count>1&&e.reused==="ref"){o(m);continue}}}function mr(e,t){var a,s,u,d,m;let n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=l=>{var y,g,b;let f=e.seen.get(l);if(f.ref===null)return;let p=(y=f.def)!=null?y:f.schema,h={...p},v=f.ref;if(f.ref=null,v){r(v);let S=e.seen.get(v),$=S.schema;if($.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(p.allOf=(g=p.allOf)!=null?g:[],p.allOf.push($)):Object.assign(p,$),Object.assign(p,h),l._zod.parent===v)for(let A in p)A==="$ref"||A==="allOf"||A in h||delete p[A];if($.$ref)for(let A in p)A==="$ref"||A==="allOf"||A in S.def&&JSON.stringify(p[A])===JSON.stringify(S.def[A])&&delete p[A]}let x=l._zod.parent;if(x&&x!==v){r(x);let S=e.seen.get(x);if(S!=null&&S.schema.$ref&&(p.$ref=S.schema.$ref,S.def))for(let $ in p)$==="$ref"||$==="allOf"||$ in S.def&&JSON.stringify(p[$])===JSON.stringify(S.def[$])&&delete p[$]}e.override({zodSchema:l,jsonSchema:p,path:(b=f.path)!=null?b:[]})};for(let l of[...e.seen.entries()].reverse())r(l[0]);let i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,(a=e.external)!=null&&a.uri){let l=(s=e.external.registry.get(t))==null?void 0:s.id;if(!l)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(l)}Object.assign(i,(u=n.def)!=null?u:n.schema);let o=(m=(d=e.external)==null?void 0:d.defs)!=null?m:{};for(let l of e.seen.entries()){let f=l[1];f.def&&f.defId&&(o[f.defId]=f.def)}e.external||Object.keys(o).length>0&&(e.target==="draft-2020-12"?i.$defs=o:i.definitions=o);try{let l=JSON.parse(JSON.stringify(i));return Object.defineProperty(l,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ua(t,"input",e.processors),output:Ua(t,"output",e.processors)}},enumerable:!1,writable:!1}),l}catch(l){throw new Error("Error converting schema to JSON.")}}function Rt(e,t){let n=t!=null?t:{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Rt(r.element,n);if(r.type==="set")return Rt(r.valueType,n);if(r.type==="lazy")return Rt(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Rt(r.innerType,n);if(r.type==="intersection")return Rt(r.left,n)||Rt(r.right,n);if(r.type==="record"||r.type==="map")return Rt(r.keyType,n)||Rt(r.valueType,n);if(r.type==="pipe")return Rt(r.in,n)||Rt(r.out,n);if(r.type==="object"){for(let i in r.shape)if(Rt(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(let i of r.options)if(Rt(i,n))return!0;return!1}if(r.type==="tuple"){for(let i of r.items)if(Rt(i,n))return!0;return!!(r.rest&&Rt(r.rest,n))}return!1}var eS=(e,t={})=>n=>{let r=dr({...n,processors:t});return xe(e,r),fr(r,e),mr(r,e)},Ua=(e,t,n={})=>r=>{let{libraryOptions:i,target:o}=r!=null?r:{},a=dr({...i!=null?i:{},target:o,io:t,processors:n});return xe(e,a),fr(a,e),mr(a,e)};var Jj={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},tS=(e,t,n,r)=>{var m;let i=n;i.type="string";let{minimum:o,maximum:a,format:s,patterns:u,contentEncoding:d}=e._zod.bag;if(typeof o=="number"&&(i.minLength=o),typeof a=="number"&&(i.maxLength=a),s&&(i.format=(m=Jj[s])!=null?m:s,i.format===""&&delete i.format,s==="time"&&delete i.format),d&&(i.contentEncoding=d),u&&u.size>0){let l=[...u];l.length===1?i.pattern=l[0].source:l.length>1&&(i.allOf=[...l.map(f=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},nS=(e,t,n,r)=>{let i=n,{minimum:o,maximum:a,format:s,multipleOf:u,exclusiveMaximum:d,exclusiveMinimum:m}=e._zod.bag;typeof s=="string"&&s.includes("int")?i.type="integer":i.type="number",typeof m=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(i.minimum=m,i.exclusiveMinimum=!0):i.exclusiveMinimum=m),typeof o=="number"&&(i.minimum=o,typeof m=="number"&&t.target!=="draft-04"&&(m>=o?delete i.minimum:delete i.exclusiveMinimum)),typeof d=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(i.maximum=d,i.exclusiveMaximum=!0):i.exclusiveMaximum=d),typeof a=="number"&&(i.maximum=a,typeof d=="number"&&t.target!=="draft-04"&&(d<=a?delete i.maximum:delete i.exclusiveMaximum)),typeof u=="number"&&(i.multipleOf=u)},iS=(e,t,n,r)=>{n.type="boolean"},rS=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},oS=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},aS=(e,t,n,r)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},sS=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},lS=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},uS=(e,t,n,r)=>{n.not={}},cS=(e,t,n,r)=>{},dS=(e,t,n,r)=>{},fS=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},mS=(e,t,n,r)=>{let i=e._zod.def,o=xl(i.entries);o.every(a=>typeof a=="number")&&(n.type="number"),o.every(a=>typeof a=="string")&&(n.type="string"),n.enum=o},pS=(e,t,n,r)=>{let i=e._zod.def,o=[];for(let a of i.values)if(a===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");o.push(Number(a))}else o.push(a);if(o.length!==0)if(o.length===1){let a=o[0];n.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[a]:n.const=a}else o.every(a=>typeof a=="number")&&(n.type="number"),o.every(a=>typeof a=="string")&&(n.type="string"),o.every(a=>typeof a=="boolean")&&(n.type="boolean"),o.every(a=>a===null)&&(n.type="null"),n.enum=o},gS=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},hS=(e,t,n,r)=>{let i=n,o=e._zod.pattern;if(!o)throw new Error("Pattern not found in template literal");i.type="string",i.pattern=o.source},vS=(e,t,n,r)=>{let i=n,o={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:s,mime:u}=e._zod.bag;a!==void 0&&(o.minLength=a),s!==void 0&&(o.maxLength=s),u?u.length===1?(o.contentMediaType=u[0],Object.assign(i,o)):(Object.assign(i,o),i.anyOf=u.map(d=>({contentMediaType:d}))):Object.assign(i,o)},yS=(e,t,n,r)=>{n.type="boolean"},bS=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},SS=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},xS=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},_S=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},$S=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},wS=(e,t,n,r)=>{let i=n,o=e._zod.def,{minimum:a,maximum:s}=e._zod.bag;typeof a=="number"&&(i.minItems=a),typeof s=="number"&&(i.maxItems=s),i.type="array",i.items=xe(o.element,t,{...r,path:[...r.path,"items"]})},zS=(e,t,n,r)=>{var d;let i=n,o=e._zod.def;i.type="object",i.properties={};let a=o.shape;for(let m in a)i.properties[m]=xe(a[m],t,{...r,path:[...r.path,"properties",m]});let s=new Set(Object.keys(a)),u=new Set([...s].filter(m=>{let l=o.shape[m]._zod;return t.io==="input"?l.optin===void 0:l.optout===void 0}));u.size>0&&(i.required=Array.from(u)),((d=o.catchall)==null?void 0:d._zod.def.type)==="never"?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=xe(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},xf=(e,t,n,r)=>{let i=e._zod.def,o=i.inclusive===!1,a=i.options.map((s,u)=>xe(s,t,{...r,path:[...r.path,o?"oneOf":"anyOf",u]}));o?n.oneOf=a:n.anyOf=a},AS=(e,t,n,r)=>{let i=e._zod.def,o=xe(i.left,t,{...r,path:[...r.path,"allOf",0]}),a=xe(i.right,t,{...r,path:[...r.path,"allOf",1]}),s=d=>"allOf"in d&&Object.keys(d).length===1,u=[...s(o)?o.allOf:[o],...s(a)?a.allOf:[a]];n.allOf=u},ES=(e,t,n,r)=>{let i=n,o=e._zod.def;i.type="array";let a=t.target==="draft-2020-12"?"prefixItems":"items",s=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",u=o.items.map((f,p)=>xe(f,t,{...r,path:[...r.path,a,p]})),d=o.rest?xe(o.rest,t,{...r,path:[...r.path,s,...t.target==="openapi-3.0"?[o.items.length]:[]]}):null;t.target==="draft-2020-12"?(i.prefixItems=u,d&&(i.items=d)):t.target==="openapi-3.0"?(i.items={anyOf:u},d&&i.items.anyOf.push(d),i.minItems=u.length,d||(i.maxItems=u.length)):(i.items=u,d&&(i.additionalItems=d));let{minimum:m,maximum:l}=e._zod.bag;typeof m=="number"&&(i.minItems=m),typeof l=="number"&&(i.maxItems=l)},TS=(e,t,n,r)=>{let i=n,o=e._zod.def;i.type="object";let a=o.keyType,s=a._zod.bag,u=s==null?void 0:s.patterns;if(o.mode==="loose"&&u&&u.size>0){let m=xe(o.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(let l of u)i.patternProperties[l.source]=m}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(i.propertyNames=xe(o.keyType,t,{...r,path:[...r.path,"propertyNames"]})),i.additionalProperties=xe(o.valueType,t,{...r,path:[...r.path,"additionalProperties"]});let d=a._zod.values;if(d){let m=[...d].filter(l=>typeof l=="string"||typeof l=="number");m.length>0&&(i.required=m)}},kS=(e,t,n,r)=>{let i=e._zod.def,o=xe(i.innerType,t,r),a=t.seen.get(e);t.target==="openapi-3.0"?(a.ref=i.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]},CS=(e,t,n,r)=>{let i=e._zod.def;xe(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},IS=(e,t,n,r)=>{let i=e._zod.def;xe(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},NS=(e,t,n,r)=>{let i=e._zod.def;xe(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},OS=(e,t,n,r)=>{let i=e._zod.def;xe(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType;let a;try{a=i.catchValue(void 0)}catch(s){throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=a},DS=(e,t,n,r)=>{let i=e._zod.def,o=t.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;xe(o,t,r);let a=t.seen.get(e);a.ref=o},MS=(e,t,n,r)=>{let i=e._zod.def;xe(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType,n.readOnly=!0},US=(e,t,n,r)=>{let i=e._zod.def;xe(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},_f=(e,t,n,r)=>{let i=e._zod.def;xe(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},RS=(e,t,n,r)=>{let i=e._zod.innerType;xe(i,t,r);let o=t.seen.get(e);o.ref=i},Sf={string:tS,number:nS,boolean:iS,bigint:rS,symbol:oS,null:aS,undefined:sS,void:lS,never:uS,any:cS,unknown:dS,date:fS,enum:mS,literal:pS,nan:gS,template_literal:hS,file:vS,success:yS,custom:bS,function:SS,transform:xS,map:_S,set:$S,array:wS,object:zS,union:xf,intersection:AS,tuple:ES,record:TS,nullable:kS,nonoptional:CS,default:IS,prefault:NS,catch:OS,pipe:DS,readonly:MS,promise:US,optional:_f,lazy:RS};function $f(e,t){if("_idmap"in e){let r=e,i=dr({...t,processors:Sf}),o={};for(let u of r._idmap.entries()){let[d,m]=u;xe(m,i)}let a={},s={registry:r,uri:t==null?void 0:t.uri,defs:o};i.external=s;for(let u of r._idmap.entries()){let[d,m]=u;fr(i,m),a[d]=mr(i,m)}if(Object.keys(o).length>0){let u=i.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[u]:o}}return{schemas:a}}let n=dr({...t,processors:Sf});return xe(e,n),fr(n,e),mr(n,e)}var wf=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){var r;let n=(r=t==null?void 0:t.target)!=null?r:"draft-2020-12";n==="draft-4"&&(n="draft-04"),n==="draft-7"&&(n="draft-07"),this.ctx=dr({processors:Sf,target:n,...(t==null?void 0:t.metadata)&&{metadata:t.metadata},...(t==null?void 0:t.unrepresentable)&&{unrepresentable:t.unrepresentable},...(t==null?void 0:t.override)&&{override:t.override},...(t==null?void 0:t.io)&&{io:t.io}})}process(t,n={path:[],schemaPath:[]}){return xe(t,this.ctx,n)}emit(t,n){n&&(n.cycles&&(this.ctx.cycles=n.cycles),n.reused&&(this.ctx.reused=n.reused),n.external&&(this.ctx.external=n.external)),fr(this.ctx,t);let r=mr(this.ctx,t),{"~standard":i,...o}=r;return o}};var jS={};var jl={};On(jl,{ZodAny:()=>lx,ZodArray:()=>fx,ZodBase64:()=>Bf,ZodBase64URL:()=>Gf,ZodBigInt:()=>qa,ZodBigIntFormat:()=>Jf,ZodBoolean:()=>Za,ZodCIDRv4:()=>Vf,ZodCIDRv6:()=>Hf,ZodCUID:()=>Uf,ZodCUID2:()=>Rf,ZodCatch:()=>Dx,ZodCodec:()=>im,ZodCustom:()=>Jl,ZodCustomStringFormat:()=>Pa,ZodDate:()=>Hl,ZodDefault:()=>Tx,ZodDiscriminatedUnion:()=>px,ZodE164:()=>Ff,ZodEmail:()=>Of,ZodEmoji:()=>Df,ZodEnum:()=>Ra,ZodExactOptional:()=>zx,ZodFile:()=>$x,ZodFunction:()=>Vx,ZodGUID:()=>Pl,ZodIPv4:()=>Zf,ZodIPv6:()=>qf,ZodIntersection:()=>gx,ZodJWT:()=>Xf,ZodKSUID:()=>Lf,ZodLazy:()=>Lx,ZodLiteral:()=>_x,ZodMAC:()=>tx,ZodMap:()=>Sx,ZodNaN:()=>Ux,ZodNanoID:()=>Mf,ZodNever:()=>cx,ZodNonOptional:()=>tm,ZodNull:()=>ax,ZodNullable:()=>Ex,ZodNumber:()=>La,ZodNumberFormat:()=>no,ZodObject:()=>Gl,ZodOptional:()=>em,ZodPipe:()=>nm,ZodPrefault:()=>Cx,ZodPromise:()=>qx,ZodReadonly:()=>Rx,ZodRecord:()=>Xl,ZodSet:()=>xx,ZodString:()=>ja,ZodStringFormat:()=>Te,ZodSuccess:()=>Ox,ZodSymbol:()=>rx,ZodTemplateLiteral:()=>Px,ZodTransform:()=>wx,ZodTuple:()=>vx,ZodType:()=>se,ZodULID:()=>jf,ZodURL:()=>Vl,ZodUUID:()=>Xn,ZodUndefined:()=>ox,ZodUnion:()=>Fl,ZodUnknown:()=>ux,ZodVoid:()=>dx,ZodXID:()=>Pf,ZodXor:()=>mx,_ZodString:()=>Nf,_default:()=>kx,_function:()=>FC,any:()=>zC,array:()=>Bl,base64:()=>lC,base64url:()=>uC,bigint:()=>SC,boolean:()=>ix,catch:()=>Mx,check:()=>XC,cidrv4:()=>aC,cidrv6:()=>sC,codec:()=>HC,cuid:()=>Qk,cuid2:()=>Wk,custom:()=>JC,date:()=>EC,describe:()=>YC,discriminatedUnion:()=>OC,e164:()=>cC,email:()=>qk,emoji:()=>Yk,enum:()=>Qf,exactOptional:()=>Ax,file:()=>LC,float32:()=>hC,float64:()=>vC,function:()=>FC,guid:()=>Vk,hash:()=>gC,hex:()=>pC,hostname:()=>mC,httpUrl:()=>Jk,instanceof:()=>QC,int:()=>If,int32:()=>yC,int64:()=>xC,intersection:()=>hx,ipv4:()=>iC,ipv6:()=>oC,json:()=>eI,jwt:()=>dC,keyof:()=>TC,ksuid:()=>nC,lazy:()=>Zx,literal:()=>PC,looseObject:()=>IC,looseRecord:()=>MC,mac:()=>rC,map:()=>UC,meta:()=>KC,nan:()=>VC,nanoid:()=>Kk,nativeEnum:()=>jC,never:()=>Yf,nonoptional:()=>Nx,null:()=>sx,nullable:()=>Zl,nullish:()=>ZC,number:()=>nx,object:()=>kC,optional:()=>Ll,partialRecord:()=>DC,pipe:()=>ql,prefault:()=>Ix,preprocess:()=>tI,promise:()=>GC,readonly:()=>jx,record:()=>bx,refine:()=>Hx,set:()=>RC,strictObject:()=>CC,string:()=>Cf,stringFormat:()=>fC,stringbool:()=>WC,success:()=>qC,superRefine:()=>Bx,symbol:()=>$C,templateLiteral:()=>BC,transform:()=>Wf,tuple:()=>yx,uint32:()=>bC,uint64:()=>_C,ulid:()=>eC,undefined:()=>wC,union:()=>Kf,unknown:()=>to,url:()=>Xk,uuid:()=>Hk,uuidv4:()=>Bk,uuidv6:()=>Gk,uuidv7:()=>Fk,void:()=>AC,xid:()=>tC,xor:()=>NC});var zf={};On(zf,{endsWith:()=>Ta,gt:()=>Bn,gte:()=>Ut,includes:()=>Aa,length:()=>Wr,lowercase:()=>wa,lt:()=>Hn,lte:()=>cn,maxLength:()=>Qr,maxSize:()=>cr,mime:()=>ka,minLength:()=>wi,minSize:()=>Gn,multipleOf:()=>ur,negative:()=>hf,nonnegative:()=>yf,nonpositive:()=>vf,normalize:()=>Ca,overwrite:()=>In,positive:()=>gf,property:()=>bf,regex:()=>$a,size:()=>Kr,slugify:()=>Da,startsWith:()=>Ea,toLowerCase:()=>Na,toUpperCase:()=>Oa,trim:()=>Ia,uppercase:()=>za});var eo={};On(eo,{ZodISODate:()=>Ef,ZodISODateTime:()=>Af,ZodISODuration:()=>kf,ZodISOTime:()=>Tf,date:()=>LS,datetime:()=>PS,duration:()=>qS,time:()=>ZS});var Af=_("ZodISODateTime",(e,t)=>{gy.init(e,t),Te.init(e,t)});function PS(e){return bb(Af,e)}var Ef=_("ZodISODate",(e,t)=>{hy.init(e,t),Te.init(e,t)});function LS(e){return Sb(Ef,e)}var Tf=_("ZodISOTime",(e,t)=>{vy.init(e,t),Te.init(e,t)});function ZS(e){return xb(Tf,e)}var kf=_("ZodISODuration",(e,t)=>{yy.init(e,t),Te.init(e,t)});function qS(e){return _b(kf,e)}var Zk=(e,t)=>{Al.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Tl(e,n)},flatten:{value:n=>El(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,pa,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,pa,2)}},isEmpty:{get(){return e.issues.length===0}}})},Kj=_("ZodError",Zk),Ft=_("ZodError",Zk,{Parent:Error});var VS=va(Ft),HS=ya(Ft),BS=ba(Ft),GS=Sa(Ft),FS=_d(Ft),XS=$d(Ft),JS=wd(Ft),YS=zd(Ft),KS=Ad(Ft),QS=Ed(Ft),WS=Td(Ft),ex=kd(Ft);var se=_("ZodType",(e,t)=>(ie.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Ua(e,"input"),output:Ua(e,"output")}}),e.toJSONSchema=eS(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>{var r;return e.clone(D.mergeDefs(t,{checks:[...(r=t.checks)!=null?r:[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},e.with=e.check,e.clone=(n,r)=>Mt(e,n,r),e.brand=()=>e,e.register=(n,r)=>(n.add(e,r),e),e.parse=(n,r)=>VS(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>BS(e,n,r),e.parseAsync=async(n,r)=>HS(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>GS(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>FS(e,n,r),e.decode=(n,r)=>XS(e,n,r),e.encodeAsync=async(n,r)=>JS(e,n,r),e.decodeAsync=async(n,r)=>YS(e,n,r),e.safeEncode=(n,r)=>KS(e,n,r),e.safeDecode=(n,r)=>QS(e,n,r),e.safeEncodeAsync=async(n,r)=>WS(e,n,r),e.safeDecodeAsync=async(n,r)=>ex(e,n,r),e.refine=(n,r)=>e.check(Hx(n,r)),e.superRefine=n=>e.check(Bx(n)),e.overwrite=n=>e.check(In(n)),e.optional=()=>Ll(e),e.exactOptional=()=>Ax(e),e.nullable=()=>Zl(e),e.nullish=()=>Ll(Zl(e)),e.nonoptional=n=>Nx(e,n),e.array=()=>Bl(e),e.or=n=>Kf([e,n]),e.and=n=>hx(e,n),e.transform=n=>ql(e,Wf(n)),e.default=n=>kx(e,n),e.prefault=n=>Ix(e,n),e.catch=n=>Mx(e,n),e.pipe=n=>ql(e,n),e.readonly=()=>jx(e),e.describe=n=>{let r=e.clone();return _t.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){var n;return(n=_t.get(e))==null?void 0:n.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return _t.get(e);let r=e.clone();return _t.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=n=>n(e),e)),Nf=_("_ZodString",(e,t)=>{var r,i,o;Jr.init(e,t),se.init(e,t),e._zod.processJSONSchema=(a,s,u)=>tS(e,a,s,u);let n=e._zod.bag;e.format=(r=n.format)!=null?r:null,e.minLength=(i=n.minimum)!=null?i:null,e.maxLength=(o=n.maximum)!=null?o:null,e.regex=(...a)=>e.check($a(...a)),e.includes=(...a)=>e.check(Aa(...a)),e.startsWith=(...a)=>e.check(Ea(...a)),e.endsWith=(...a)=>e.check(Ta(...a)),e.min=(...a)=>e.check(wi(...a)),e.max=(...a)=>e.check(Qr(...a)),e.length=(...a)=>e.check(Wr(...a)),e.nonempty=(...a)=>e.check(wi(1,...a)),e.lowercase=a=>e.check(wa(a)),e.uppercase=a=>e.check(za(a)),e.trim=()=>e.check(Ia()),e.normalize=(...a)=>e.check(Ca(...a)),e.toLowerCase=()=>e.check(Na()),e.toUpperCase=()=>e.check(Oa()),e.slugify=()=>e.check(Da())}),ja=_("ZodString",(e,t)=>{Jr.init(e,t),Nf.init(e,t),e.email=n=>e.check(Xd(Of,n)),e.url=n=>e.check(Rl(Vl,n)),e.jwt=n=>e.check(pf(Xf,n)),e.emoji=n=>e.check(Wd(Df,n)),e.guid=n=>e.check(Ul(Pl,n)),e.uuid=n=>e.check(Jd(Xn,n)),e.uuidv4=n=>e.check(Yd(Xn,n)),e.uuidv6=n=>e.check(Kd(Xn,n)),e.uuidv7=n=>e.check(Qd(Xn,n)),e.nanoid=n=>e.check(ef(Mf,n)),e.guid=n=>e.check(Ul(Pl,n)),e.cuid=n=>e.check(tf(Uf,n)),e.cuid2=n=>e.check(nf(Rf,n)),e.ulid=n=>e.check(rf(jf,n)),e.base64=n=>e.check(df(Bf,n)),e.base64url=n=>e.check(ff(Gf,n)),e.xid=n=>e.check(of(Pf,n)),e.ksuid=n=>e.check(af(Lf,n)),e.ipv4=n=>e.check(sf(Zf,n)),e.ipv6=n=>e.check(lf(qf,n)),e.cidrv4=n=>e.check(uf(Vf,n)),e.cidrv6=n=>e.check(cf(Hf,n)),e.e164=n=>e.check(mf(Ff,n)),e.datetime=n=>e.check(PS(n)),e.date=n=>e.check(LS(n)),e.time=n=>e.check(ZS(n)),e.duration=n=>e.check(qS(n))});function Cf(e){return gb(ja,e)}var Te=_("ZodStringFormat",(e,t)=>{Ee.init(e,t),Nf.init(e,t)}),Of=_("ZodEmail",(e,t)=>{ay.init(e,t),Te.init(e,t)});function qk(e){return Xd(Of,e)}var Pl=_("ZodGUID",(e,t)=>{ry.init(e,t),Te.init(e,t)});function Vk(e){return Ul(Pl,e)}var Xn=_("ZodUUID",(e,t)=>{oy.init(e,t),Te.init(e,t)});function Hk(e){return Jd(Xn,e)}function Bk(e){return Yd(Xn,e)}function Gk(e){return Kd(Xn,e)}function Fk(e){return Qd(Xn,e)}var Vl=_("ZodURL",(e,t)=>{sy.init(e,t),Te.init(e,t)});function Xk(e){return Rl(Vl,e)}function Jk(e){return Rl(Vl,{protocol:/^https?$/,hostname:un.domain,...D.normalizeParams(e)})}var Df=_("ZodEmoji",(e,t)=>{ly.init(e,t),Te.init(e,t)});function Yk(e){return Wd(Df,e)}var Mf=_("ZodNanoID",(e,t)=>{uy.init(e,t),Te.init(e,t)});function Kk(e){return ef(Mf,e)}var Uf=_("ZodCUID",(e,t)=>{cy.init(e,t),Te.init(e,t)});function Qk(e){return tf(Uf,e)}var Rf=_("ZodCUID2",(e,t)=>{dy.init(e,t),Te.init(e,t)});function Wk(e){return nf(Rf,e)}var jf=_("ZodULID",(e,t)=>{fy.init(e,t),Te.init(e,t)});function eC(e){return rf(jf,e)}var Pf=_("ZodXID",(e,t)=>{my.init(e,t),Te.init(e,t)});function tC(e){return of(Pf,e)}var Lf=_("ZodKSUID",(e,t)=>{py.init(e,t),Te.init(e,t)});function nC(e){return af(Lf,e)}var Zf=_("ZodIPv4",(e,t)=>{by.init(e,t),Te.init(e,t)});function iC(e){return sf(Zf,e)}var tx=_("ZodMAC",(e,t)=>{xy.init(e,t),Te.init(e,t)});function rC(e){return vb(tx,e)}var qf=_("ZodIPv6",(e,t)=>{Sy.init(e,t),Te.init(e,t)});function oC(e){return lf(qf,e)}var Vf=_("ZodCIDRv4",(e,t)=>{_y.init(e,t),Te.init(e,t)});function aC(e){return uf(Vf,e)}var Hf=_("ZodCIDRv6",(e,t)=>{$y.init(e,t),Te.init(e,t)});function sC(e){return cf(Hf,e)}var Bf=_("ZodBase64",(e,t)=>{zy.init(e,t),Te.init(e,t)});function lC(e){return df(Bf,e)}var Gf=_("ZodBase64URL",(e,t)=>{Ay.init(e,t),Te.init(e,t)});function uC(e){return ff(Gf,e)}var Ff=_("ZodE164",(e,t)=>{Ey.init(e,t),Te.init(e,t)});function cC(e){return mf(Ff,e)}var Xf=_("ZodJWT",(e,t)=>{Ty.init(e,t),Te.init(e,t)});function dC(e){return pf(Xf,e)}var Pa=_("ZodCustomStringFormat",(e,t)=>{ky.init(e,t),Te.init(e,t)});function fC(e,t,n={}){return Ma(Pa,e,t,n)}function mC(e){return Ma(Pa,"hostname",un.hostname,e)}function pC(e){return Ma(Pa,"hex",un.hex,e)}function gC(e,t){var o;let n=(o=t==null?void 0:t.enc)!=null?o:"hex",r=`${e}_${n}`,i=un[r];if(!i)throw new Error(`Unrecognized hash format: ${r}`);return Ma(Pa,r,i,t)}var La=_("ZodNumber",(e,t)=>{var r,i,o,a,s,u,d,m,l;Pd.init(e,t),se.init(e,t),e._zod.processJSONSchema=(f,p,h)=>nS(e,f,p,h),e.gt=(f,p)=>e.check(Bn(f,p)),e.gte=(f,p)=>e.check(Ut(f,p)),e.min=(f,p)=>e.check(Ut(f,p)),e.lt=(f,p)=>e.check(Hn(f,p)),e.lte=(f,p)=>e.check(cn(f,p)),e.max=(f,p)=>e.check(cn(f,p)),e.int=f=>e.check(If(f)),e.safe=f=>e.check(If(f)),e.positive=f=>e.check(Bn(0,f)),e.nonnegative=f=>e.check(Ut(0,f)),e.negative=f=>e.check(Hn(0,f)),e.nonpositive=f=>e.check(cn(0,f)),e.multipleOf=(f,p)=>e.check(ur(f,p)),e.step=(f,p)=>e.check(ur(f,p)),e.finite=()=>e;let n=e._zod.bag;e.minValue=(o=Math.max((r=n.minimum)!=null?r:Number.NEGATIVE_INFINITY,(i=n.exclusiveMinimum)!=null?i:Number.NEGATIVE_INFINITY))!=null?o:null,e.maxValue=(u=Math.min((a=n.maximum)!=null?a:Number.POSITIVE_INFINITY,(s=n.exclusiveMaximum)!=null?s:Number.POSITIVE_INFINITY))!=null?u:null,e.isInt=((d=n.format)!=null?d:"").includes("int")||Number.isSafeInteger((m=n.multipleOf)!=null?m:.5),e.isFinite=!0,e.format=(l=n.format)!=null?l:null});function nx(e){return $b(La,e)}var no=_("ZodNumberFormat",(e,t)=>{Cy.init(e,t),La.init(e,t)});function If(e){return zb(no,e)}function hC(e){return Ab(no,e)}function vC(e){return Eb(no,e)}function yC(e){return Tb(no,e)}function bC(e){return kb(no,e)}var Za=_("ZodBoolean",(e,t)=>{Nl.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>iS(e,n,r,i)});function ix(e){return Cb(Za,e)}var qa=_("ZodBigInt",(e,t)=>{var r,i,o;Ld.init(e,t),se.init(e,t),e._zod.processJSONSchema=(a,s,u)=>rS(e,a,s,u),e.gte=(a,s)=>e.check(Ut(a,s)),e.min=(a,s)=>e.check(Ut(a,s)),e.gt=(a,s)=>e.check(Bn(a,s)),e.gte=(a,s)=>e.check(Ut(a,s)),e.min=(a,s)=>e.check(Ut(a,s)),e.lt=(a,s)=>e.check(Hn(a,s)),e.lte=(a,s)=>e.check(cn(a,s)),e.max=(a,s)=>e.check(cn(a,s)),e.positive=a=>e.check(Bn(BigInt(0),a)),e.negative=a=>e.check(Hn(BigInt(0),a)),e.nonpositive=a=>e.check(cn(BigInt(0),a)),e.nonnegative=a=>e.check(Ut(BigInt(0),a)),e.multipleOf=(a,s)=>e.check(ur(a,s));let n=e._zod.bag;e.minValue=(r=n.minimum)!=null?r:null,e.maxValue=(i=n.maximum)!=null?i:null,e.format=(o=n.format)!=null?o:null});function SC(e){return Nb(qa,e)}var Jf=_("ZodBigIntFormat",(e,t)=>{Iy.init(e,t),qa.init(e,t)});function xC(e){return Db(Jf,e)}function _C(e){return Mb(Jf,e)}var rx=_("ZodSymbol",(e,t)=>{Ny.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>oS(e,n,r,i)});function $C(e){return Ub(rx,e)}var ox=_("ZodUndefined",(e,t)=>{Oy.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>sS(e,n,r,i)});function wC(e){return Rb(ox,e)}var ax=_("ZodNull",(e,t)=>{Dy.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>aS(e,n,r,i)});function sx(e){return jb(ax,e)}var lx=_("ZodAny",(e,t)=>{My.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>cS(e,n,r,i)});function zC(){return Pb(lx)}var ux=_("ZodUnknown",(e,t)=>{Uy.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>dS(e,n,r,i)});function to(){return Lb(ux)}var cx=_("ZodNever",(e,t)=>{Ry.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>uS(e,n,r,i)});function Yf(e){return Zb(cx,e)}var dx=_("ZodVoid",(e,t)=>{jy.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>lS(e,n,r,i)});function AC(e){return qb(dx,e)}var Hl=_("ZodDate",(e,t)=>{Py.init(e,t),se.init(e,t),e._zod.processJSONSchema=(r,i,o)=>fS(e,r,i,o),e.min=(r,i)=>e.check(Ut(r,i)),e.max=(r,i)=>e.check(cn(r,i));let n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null});function EC(e){return Vb(Hl,e)}var fx=_("ZodArray",(e,t)=>{Ly.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>wS(e,n,r,i),e.element=t.element,e.min=(n,r)=>e.check(wi(n,r)),e.nonempty=n=>e.check(wi(1,n)),e.max=(n,r)=>e.check(Qr(n,r)),e.length=(n,r)=>e.check(Wr(n,r)),e.unwrap=()=>e.element});function Bl(e,t){return Gb(fx,e,t)}function TC(e){let t=e._zod.def.shape;return Qf(Object.keys(t))}var Gl=_("ZodObject",(e,t)=>{Zy.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>zS(e,n,r,i),D.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>Qf(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:to()}),e.loose=()=>e.clone({...e._zod.def,catchall:to()}),e.strict=()=>e.clone({...e._zod.def,catchall:Yf()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>D.extend(e,n),e.safeExtend=n=>D.safeExtend(e,n),e.merge=n=>D.merge(e,n),e.pick=n=>D.pick(e,n),e.omit=n=>D.omit(e,n),e.partial=(...n)=>D.partial(em,e,n[0]),e.required=(...n)=>D.required(tm,e,n[0])});function kC(e,t){let n={type:"object",shape:e!=null?e:{},...D.normalizeParams(t)};return new Gl(n)}function CC(e,t){return new Gl({type:"object",shape:e,catchall:Yf(),...D.normalizeParams(t)})}function IC(e,t){return new Gl({type:"object",shape:e,catchall:to(),...D.normalizeParams(t)})}var Fl=_("ZodUnion",(e,t)=>{Ol.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>xf(e,n,r,i),e.options=t.options});function Kf(e,t){return new Fl({type:"union",options:e,...D.normalizeParams(t)})}var mx=_("ZodXor",(e,t)=>{Fl.init(e,t),qy.init(e,t),e._zod.processJSONSchema=(n,r,i)=>xf(e,n,r,i),e.options=t.options});function NC(e,t){return new mx({type:"union",options:e,inclusive:!1,...D.normalizeParams(t)})}var px=_("ZodDiscriminatedUnion",(e,t)=>{Fl.init(e,t),Vy.init(e,t)});function OC(e,t,n){return new px({type:"union",options:t,discriminator:e,...D.normalizeParams(n)})}var gx=_("ZodIntersection",(e,t)=>{Hy.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>AS(e,n,r,i)});function hx(e,t){return new gx({type:"intersection",left:e,right:t})}var vx=_("ZodTuple",(e,t)=>{Zd.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ES(e,n,r,i),e.rest=n=>e.clone({...e._zod.def,rest:n})});function yx(e,t,n){let r=t instanceof ie,i=r?n:t,o=r?t:null;return new vx({type:"tuple",items:e,rest:o,...D.normalizeParams(i)})}var Xl=_("ZodRecord",(e,t)=>{By.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>TS(e,n,r,i),e.keyType=t.keyType,e.valueType=t.valueType});function bx(e,t,n){return new Xl({type:"record",keyType:e,valueType:t,...D.normalizeParams(n)})}function DC(e,t,n){let r=Mt(e);return r._zod.values=void 0,new Xl({type:"record",keyType:r,valueType:t,...D.normalizeParams(n)})}function MC(e,t,n){return new Xl({type:"record",keyType:e,valueType:t,mode:"loose",...D.normalizeParams(n)})}var Sx=_("ZodMap",(e,t)=>{Gy.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_S(e,n,r,i),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...n)=>e.check(Gn(...n)),e.nonempty=n=>e.check(Gn(1,n)),e.max=(...n)=>e.check(cr(...n)),e.size=(...n)=>e.check(Kr(...n))});function UC(e,t,n){return new Sx({type:"map",keyType:e,valueType:t,...D.normalizeParams(n)})}var xx=_("ZodSet",(e,t)=>{Fy.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>$S(e,n,r,i),e.min=(...n)=>e.check(Gn(...n)),e.nonempty=n=>e.check(Gn(1,n)),e.max=(...n)=>e.check(cr(...n)),e.size=(...n)=>e.check(Kr(...n))});function RC(e,t){return new xx({type:"set",valueType:e,...D.normalizeParams(t)})}var Ra=_("ZodEnum",(e,t)=>{Xy.init(e,t),se.init(e,t),e._zod.processJSONSchema=(r,i,o)=>mS(e,r,i,o),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{let o={};for(let a of r)if(n.has(a))o[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new Ra({...t,checks:[],...D.normalizeParams(i),entries:o})},e.exclude=(r,i)=>{let o={...t.entries};for(let a of r)if(n.has(a))delete o[a];else throw new Error(`Key ${a} not found in enum`);return new Ra({...t,checks:[],...D.normalizeParams(i),entries:o})}});function Qf(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Ra({type:"enum",entries:n,...D.normalizeParams(t)})}function jC(e,t){return new Ra({type:"enum",entries:e,...D.normalizeParams(t)})}var _x=_("ZodLiteral",(e,t)=>{Jy.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>pS(e,n,r,i),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function PC(e,t){return new _x({type:"literal",values:Array.isArray(e)?e:[e],...D.normalizeParams(t)})}var $x=_("ZodFile",(e,t)=>{Yy.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>vS(e,n,r,i),e.min=(n,r)=>e.check(Gn(n,r)),e.max=(n,r)=>e.check(cr(n,r)),e.mime=(n,r)=>e.check(ka(Array.isArray(n)?n:[n],r))});function LC(e){return Fb($x,e)}var wx=_("ZodTransform",(e,t)=>{Ky.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>xS(e,n,r,i),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new rr(e.constructor.name);n.addIssue=o=>{var a,s,u;if(typeof o=="string")n.issues.push(D.issue(o,n.value,t));else{let d=o;d.fatal&&(d.continue=!1),(a=d.code)!=null||(d.code="custom"),(s=d.input)!=null||(d.input=n.value),(u=d.inst)!=null||(d.inst=e),n.issues.push(D.issue(d))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(o=>(n.value=o,n)):(n.value=i,n)}});function Wf(e){return new wx({type:"transform",transform:e})}var em=_("ZodOptional",(e,t)=>{qd.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_f(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Ll(e){return new em({type:"optional",innerType:e})}var zx=_("ZodExactOptional",(e,t)=>{Qy.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_f(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Ax(e){return new zx({type:"optional",innerType:e})}var Ex=_("ZodNullable",(e,t)=>{Wy.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kS(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Zl(e){return new Ex({type:"nullable",innerType:e})}function ZC(e){return Ll(Zl(e))}var Tx=_("ZodDefault",(e,t)=>{eb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>IS(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function kx(e,t){return new Tx({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():D.shallowClone(t)}})}var Cx=_("ZodPrefault",(e,t)=>{tb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>NS(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Ix(e,t){return new Cx({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():D.shallowClone(t)}})}var tm=_("ZodNonOptional",(e,t)=>{nb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>CS(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Nx(e,t){return new tm({type:"nonoptional",innerType:e,...D.normalizeParams(t)})}var Ox=_("ZodSuccess",(e,t)=>{ib.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>yS(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function qC(e){return new Ox({type:"success",innerType:e})}var Dx=_("ZodCatch",(e,t)=>{rb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>OS(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Mx(e,t){return new Dx({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Ux=_("ZodNaN",(e,t)=>{ob.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gS(e,n,r,i)});function VC(e){return Bb(Ux,e)}var nm=_("ZodPipe",(e,t)=>{ab.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>DS(e,n,r,i),e.in=t.in,e.out=t.out});function ql(e,t){return new nm({type:"pipe",in:e,out:t})}var im=_("ZodCodec",(e,t)=>{nm.init(e,t),Dl.init(e,t)});function HC(e,t,n){return new im({type:"pipe",in:e,out:t,transform:n.decode,reverseTransform:n.encode})}var Rx=_("ZodReadonly",(e,t)=>{sb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>MS(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function jx(e){return new Rx({type:"readonly",innerType:e})}var Px=_("ZodTemplateLiteral",(e,t)=>{lb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>hS(e,n,r,i)});function BC(e,t){return new Px({type:"template_literal",parts:e,...D.normalizeParams(t)})}var Lx=_("ZodLazy",(e,t)=>{db.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>RS(e,n,r,i),e.unwrap=()=>e._zod.def.getter()});function Zx(e){return new Lx({type:"lazy",getter:e})}var qx=_("ZodPromise",(e,t)=>{cb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>US(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function GC(e){return new qx({type:"promise",innerType:e})}var Vx=_("ZodFunction",(e,t)=>{ub.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>SS(e,n,r,i)});function FC(e){var t,n;return new Vx({type:"function",input:Array.isArray(e==null?void 0:e.input)?yx(e==null?void 0:e.input):(t=e==null?void 0:e.input)!=null?t:Bl(to()),output:(n=e==null?void 0:e.output)!=null?n:to()})}var Jl=_("ZodCustom",(e,t)=>{fb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bS(e,n,r,i)});function XC(e){let t=new Ce({check:"custom"});return t._zod.check=e,t}function JC(e,t){return Xb(Jl,e!=null?e:()=>!0,t)}function Hx(e,t={}){return Jb(Jl,e,t)}function Bx(e){return Yb(e)}var YC=Kb,KC=Qb;function QC(e,t={}){let n=new Jl({type:"custom",check:"custom",fn:r=>r instanceof e,abort:!0,...D.normalizeParams(t)});return n._zod.bag.Class=e,n._zod.check=r=>{var i;r.value instanceof e||r.issues.push({code:"invalid_type",expected:e.name,input:r.value,inst:n,path:[...(i=n._zod.def.path)!=null?i:[]]})},n}var WC=(...e)=>Wb({Codec:im,Boolean:Za,String:ja},...e);function eI(e){let t=Zx(()=>Kf([Cf(e),nx(),ix(),sx(),Bl(t),bx(Cf(),t)]));return t}function tI(e,t){return ql(Wf(e),t)}var Wj={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function eP(e){Je({customError:e})}function tP(){return Je().customError}var Gx;(function(e){})(Gx||(Gx={}));var Z={...jl,...zf,iso:eo},nP=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function iP(e,t){let n=e.$schema;return n==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":n==="http://json-schema.org/draft-07/schema#"?"draft-7":n==="http://json-schema.org/draft-04/schema#"?"draft-4":t!=null?t:"draft-2020-12"}function rP(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let n=e.slice(1).split("/").filter(Boolean);if(n.length===0)return t.rootSchema;let r=t.version==="draft-2020-12"?"$defs":"definitions";if(n[0]===r){let i=n[1];if(!i||!t.defs[i])throw new Error(`Reference not found: ${e}`);return t.defs[i]}throw new Error(`Reference not found: ${e}`)}function nI(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return Z.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let i=e.$ref;if(t.refs.has(i))return t.refs.get(i);if(t.processing.has(i))return Z.lazy(()=>{if(!t.refs.has(i))throw new Error(`Circular reference not resolved: ${i}`);return t.refs.get(i)});t.processing.add(i);let o=rP(i,t),a=Et(o,t);return t.refs.set(i,a),t.processing.delete(i),a}if(e.enum!==void 0){let i=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&i.length===1&&i[0]===null)return Z.null();if(i.length===0)return Z.never();if(i.length===1)return Z.literal(i[0]);if(i.every(a=>typeof a=="string"))return Z.enum(i);let o=i.map(a=>Z.literal(a));return o.length<2?o[0]:Z.union([o[0],o[1],...o.slice(2)])}if(e.const!==void 0)return Z.literal(e.const);let n=e.type;if(Array.isArray(n)){let i=n.map(o=>{let a={...e,type:o};return nI(a,t)});return i.length===0?Z.never():i.length===1?i[0]:Z.union(i)}if(!n)return Z.any();let r;switch(n){case"string":{let i=Z.string();if(e.format){let o=e.format;o==="email"?i=i.check(Z.email()):o==="uri"||o==="uri-reference"?i=i.check(Z.url()):o==="uuid"||o==="guid"?i=i.check(Z.uuid()):o==="date-time"?i=i.check(Z.iso.datetime()):o==="date"?i=i.check(Z.iso.date()):o==="time"?i=i.check(Z.iso.time()):o==="duration"?i=i.check(Z.iso.duration()):o==="ipv4"?i=i.check(Z.ipv4()):o==="ipv6"?i=i.check(Z.ipv6()):o==="mac"?i=i.check(Z.mac()):o==="cidr"?i=i.check(Z.cidrv4()):o==="cidr-v6"?i=i.check(Z.cidrv6()):o==="base64"?i=i.check(Z.base64()):o==="base64url"?i=i.check(Z.base64url()):o==="e164"?i=i.check(Z.e164()):o==="jwt"?i=i.check(Z.jwt()):o==="emoji"?i=i.check(Z.emoji()):o==="nanoid"?i=i.check(Z.nanoid()):o==="cuid"?i=i.check(Z.cuid()):o==="cuid2"?i=i.check(Z.cuid2()):o==="ulid"?i=i.check(Z.ulid()):o==="xid"?i=i.check(Z.xid()):o==="ksuid"&&(i=i.check(Z.ksuid()))}typeof e.minLength=="number"&&(i=i.min(e.minLength)),typeof e.maxLength=="number"&&(i=i.max(e.maxLength)),e.pattern&&(i=i.regex(new RegExp(e.pattern))),r=i;break}case"number":case"integer":{let i=n==="integer"?Z.number().int():Z.number();typeof e.minimum=="number"&&(i=i.min(e.minimum)),typeof e.maximum=="number"&&(i=i.max(e.maximum)),typeof e.exclusiveMinimum=="number"?i=i.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(i=i.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?i=i.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(i=i.lt(e.maximum)),typeof e.multipleOf=="number"&&(i=i.multipleOf(e.multipleOf)),r=i;break}case"boolean":{r=Z.boolean();break}case"null":{r=Z.null();break}case"object":{let i={},o=e.properties||{},a=new Set(e.required||[]);for(let[u,d]of Object.entries(o)){let m=Et(d,t);i[u]=a.has(u)?m:m.optional()}if(e.propertyNames){let u=Et(e.propertyNames,t),d=e.additionalProperties&&typeof e.additionalProperties=="object"?Et(e.additionalProperties,t):Z.any();if(Object.keys(i).length===0){r=Z.record(u,d);break}let m=Z.object(i).passthrough(),l=Z.looseRecord(u,d);r=Z.intersection(m,l);break}if(e.patternProperties){let u=e.patternProperties,d=Object.keys(u),m=[];for(let f of d){let p=Et(u[f],t),h=Z.string().regex(new RegExp(f));m.push(Z.looseRecord(h,p))}let l=[];if(Object.keys(i).length>0&&l.push(Z.object(i).passthrough()),l.push(...m),l.length===0)r=Z.object({}).passthrough();else if(l.length===1)r=l[0];else{let f=Z.intersection(l[0],l[1]);for(let p=2;pEt(u,t)),s=o&&typeof o=="object"&&!Array.isArray(o)?Et(o,t):void 0;s?r=Z.tuple(a).rest(s):r=Z.tuple(a),typeof e.minItems=="number"&&(r=r.check(Z.minLength(e.minItems))),typeof e.maxItems=="number"&&(r=r.check(Z.maxLength(e.maxItems)))}else if(Array.isArray(o)){let a=o.map(u=>Et(u,t)),s=e.additionalItems&&typeof e.additionalItems=="object"?Et(e.additionalItems,t):void 0;s?r=Z.tuple(a).rest(s):r=Z.tuple(a),typeof e.minItems=="number"&&(r=r.check(Z.minLength(e.minItems))),typeof e.maxItems=="number"&&(r=r.check(Z.maxLength(e.maxItems)))}else if(o!==void 0){let a=Et(o,t),s=Z.array(a);typeof e.minItems=="number"&&(s=s.min(e.minItems)),typeof e.maxItems=="number"&&(s=s.max(e.maxItems)),r=s}else r=Z.array(Z.any());break}default:throw new Error(`Unsupported type: ${n}`)}return e.description&&(r=r.describe(e.description)),e.default!==void 0&&(r=r.default(e.default)),r}function Et(e,t){if(typeof e=="boolean")return e?Z.any():Z.never();let n=nI(e,t),r=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let s=e.anyOf.map(d=>Et(d,t)),u=Z.union(s);n=r?Z.intersection(n,u):u}if(e.oneOf&&Array.isArray(e.oneOf)){let s=e.oneOf.map(d=>Et(d,t)),u=Z.xor(s);n=r?Z.intersection(n,u):u}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)n=r?n:Z.any();else{let s=r?n:Et(e.allOf[0],t),u=r?0:1;for(let d=u;d0&&t.registry.add(n,i),n}function iI(e,t){var o;if(typeof e=="boolean")return e?Z.any():Z.never();let n=iP(e,t==null?void 0:t.defaultTarget),r=e.$defs||e.definitions||{},i={version:n,defs:r,refs:new Map,processing:new Set,rootSchema:e,registry:(o=t==null?void 0:t.registry)!=null?o:_t};return Et(e,i)}var rm={};On(rm,{bigint:()=>lP,boolean:()=>sP,date:()=>uP,number:()=>aP,string:()=>oP});function oP(e){return hb(ja,e)}function aP(e){return wb(La,e)}function sP(e){return Ib(Za,e)}function lP(e){return Ob(qa,e)}function uP(e){return Hb(Hl,e)}Je(Vd());var Ge={authenticate:"authenticate",initialize:"initialize",session_cancel:"session/cancel",session_fork:"session/fork",session_list:"session/list",session_load:"session/load",session_new:"session/new",session_prompt:"session/prompt",session_resume:"session/resume",session_set_config_option:"session/set_config_option",session_set_mode:"session/set_mode",session_set_model:"session/set_model"},ut={fs_read_text_file:"fs/read_text_file",fs_write_text_file:"fs/write_text_file",session_request_permission:"session/request_permission",session_update:"session/update",terminal_create:"terminal/create",terminal_kill:"terminal/kill",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit"},rI=1;var dP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),description:c.union([c.string(),c.null()]).optional(),id:c.string(),name:c.string()}),Xx=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),methodId:c.string()}),fP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional()}),mP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),blob:c.string(),mimeType:c.union([c.string(),c.null()]).optional(),uri:c.string()}),pP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),terminalId:c.string()}),gP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),newText:c.string(),oldText:c.union([c.string(),c.null()]).optional(),path:c.string()}),oI=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),name:c.string(),value:c.string()}),hP=c.union([c.literal(-32700),c.literal(-32600),c.literal(-32601),c.literal(-32602),c.literal(-32603),c.literal(-32800),c.literal(-32e3),c.literal(-32002),c.number().int()]),aI=c.object({code:hP,data:c.unknown().optional(),message:c.string()}),sI=c.unknown(),lI=c.unknown(),uI=c.unknown(),vP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),readTextFile:c.boolean().optional().default(!1),writeTextFile:c.boolean().optional().default(!1)}),yP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),fs:vP.optional().default({readTextFile:!1,writeTextFile:!1}),terminal:c.boolean().optional().default(!1)}),cI=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),name:c.string(),value:c.string()}),dI=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),name:c.string(),title:c.union([c.string(),c.null()]).optional(),version:c.string()}),bP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional()}),Jx=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),cursor:c.union([c.string(),c.null()]).optional(),cwd:c.union([c.string(),c.null()]).optional()}),SP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),http:c.boolean().optional().default(!1),sse:c.boolean().optional().default(!1)}),xP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),headers:c.array(cI),name:c.string(),url:c.string()}),_P=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),headers:c.array(cI),name:c.string(),url:c.string()}),$P=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),args:c.array(c.string()),command:c.string(),env:c.array(oI),name:c.string()}),om=c.union([xP.and(c.object({type:c.literal("http")})),_P.and(c.object({type:c.literal("sse")})),$P]),Yx=c.string(),wP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),description:c.union([c.string(),c.null()]).optional(),modelId:Yx,name:c.string()}),Kx=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),cwd:c.string(),mcpServers:c.array(om)}),fI=c.string(),zP=c.union([c.literal("allow_once"),c.literal("allow_always"),c.literal("reject_once"),c.literal("reject_always")]),AP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),kind:zP,name:c.string(),optionId:fI}),EP=c.union([c.literal("high"),c.literal("medium"),c.literal("low")]),TP=c.union([c.literal("pending"),c.literal("in_progress"),c.literal("completed")]),kP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),content:c.string(),priority:EP,status:TP}),CP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),entries:c.array(kP)}),IP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),audio:c.boolean().optional().default(!1),embeddedContext:c.boolean().optional().default(!1),image:c.boolean().optional().default(!1)}),mI=c.number().int().gte(0).lte(65535),Qx=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),clientCapabilities:yP.optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:c.union([dI,c.null()]).optional(),protocolVersion:mI}),NP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),content:c.string()}),OP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional()}),io=c.union([c.null(),c.coerce.bigint(),c.string()]),D8=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),requestId:io}),DP=c.enum(["assistant","user"]),Yl=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),audience:c.union([c.array(DP),c.null()]).optional(),lastModified:c.union([c.string(),c.null()]).optional(),priority:c.union([c.number(),c.null()]).optional()}),MP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),annotations:c.union([Yl,c.null()]).optional(),data:c.string(),mimeType:c.string()}),UP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),annotations:c.union([Yl,c.null()]).optional(),data:c.string(),mimeType:c.string(),uri:c.union([c.string(),c.null()]).optional()}),RP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),annotations:c.union([Yl,c.null()]).optional(),description:c.union([c.string(),c.null()]).optional(),mimeType:c.union([c.string(),c.null()]).optional(),name:c.string(),size:c.union([c.coerce.bigint(),c.null()]).optional(),title:c.union([c.string(),c.null()]).optional(),uri:c.string()}),jP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),optionId:fI}),PP=c.union([c.object({outcome:c.literal("cancelled")}),jP.and(c.object({outcome:c.literal("selected")}))]),LP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),outcome:PP}),ZP=c.string(),pI=c.string(),Wx=c.string(),gI=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),description:c.union([c.string(),c.null()]).optional(),name:c.string(),value:Wx}),qP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),group:ZP,name:c.string(),options:c.array(gI)}),VP=c.union([c.array(gI),c.array(qP)]),HP=c.object({currentValue:Wx,options:VP}),Va=HP.and(c.object({type:c.literal("select")})).and(c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),description:c.union([c.string(),c.null()]).optional(),id:pI,name:c.string()})),BP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),configOptions:c.array(Va)}),GP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional()}),rt=c.string(),e_=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),sessionId:rt}),M8=c.object({method:c.string(),params:c.union([c.union([e_,sI]),c.null()]).optional()}),t_=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),args:c.array(c.string()).optional(),command:c.string(),cwd:c.union([c.string(),c.null()]).optional(),env:c.array(oI).optional(),outputByteLimit:c.union([c.number().int().gte(0),c.null()]).optional(),sessionId:rt}),n_=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),cwd:c.string(),mcpServers:c.array(om).optional(),sessionId:rt}),i_=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),sessionId:rt,terminalId:c.string()}),r_=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),cwd:c.string(),mcpServers:c.array(om),sessionId:rt}),o_=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),limit:c.union([c.number().int().gte(0),c.null()]).optional(),line:c.union([c.number().int().gte(0),c.null()]).optional(),path:c.string(),sessionId:rt}),a_=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),sessionId:rt,terminalId:c.string()}),s_=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),cwd:c.string(),mcpServers:c.array(om).optional(),sessionId:rt}),FP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),cwd:c.string(),sessionId:rt,title:c.union([c.string(),c.null()]).optional(),updatedAt:c.union([c.string(),c.null()]).optional()}),XP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),nextCursor:c.union([c.string(),c.null()]).optional(),sessions:c.array(FP)}),JP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),title:c.union([c.string(),c.null()]).optional(),updatedAt:c.union([c.string(),c.null()]).optional()}),YP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional()}),am=c.string(),KP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),currentModeId:am}),QP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),description:c.union([c.string(),c.null()]).optional(),id:am,name:c.string()}),sm=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),availableModes:c.array(QP),currentModeId:am}),lm=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),availableModels:c.array(wP),currentModelId:Yx}),WP=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),configOptions:c.union([c.array(Va),c.null()]).optional(),models:c.union([lm,c.null()]).optional(),modes:c.union([sm,c.null()]).optional(),sessionId:rt}),e2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),configOptions:c.union([c.array(Va),c.null()]).optional(),models:c.union([lm,c.null()]).optional(),modes:c.union([sm,c.null()]).optional()}),t2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),configOptions:c.union([c.array(Va),c.null()]).optional(),models:c.union([lm,c.null()]).optional(),modes:c.union([sm,c.null()]).optional(),sessionId:rt}),n2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),configOptions:c.union([c.array(Va),c.null()]).optional(),models:c.union([lm,c.null()]).optional(),modes:c.union([sm,c.null()]).optional()}),i2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional()}),r2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),fork:c.union([GP,c.null()]).optional(),list:c.union([YP,c.null()]).optional(),resume:c.union([i2,c.null()]).optional()}),o2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),loadSession:c.boolean().optional().default(!1),mcpCapabilities:SP.optional().default({http:!1,sse:!1}),promptCapabilities:IP.optional().default({audio:!1,embeddedContext:!1,image:!1}),sessionCapabilities:r2.optional().default({})}),a2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),agentCapabilities:o2.optional().default({loadSession:!1,mcpCapabilities:{http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:c.union([dI,c.null()]).optional(),authMethods:c.array(dP).optional().default([]),protocolVersion:mI}),s2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),configId:pI,sessionId:rt,value:Wx}),l2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),configOptions:c.array(Va)}),l_=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),modeId:am,sessionId:rt}),u2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional()}),u_=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),modelId:Yx,sessionId:rt}),c2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional()}),d2=c.union([c.literal("end_turn"),c.literal("max_tokens"),c.literal("max_turn_requests"),c.literal("refusal"),c.literal("cancelled")]),f2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),stopReason:d2}),U8=c.union([c.object({id:io,result:c.union([a2,fP,t2,e2,XP,WP,n2,u2,l2,f2,c2,uI])}),c.object({error:aI,id:io})]),m2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),terminalId:c.string()}),p2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),exitCode:c.union([c.number().int().gte(0),c.null()]).optional(),signal:c.union([c.string(),c.null()]).optional()}),c_=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),sessionId:rt,terminalId:c.string()}),g2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),exitStatus:c.union([p2,c.null()]).optional(),output:c.string(),truncated:c.boolean()}),h2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),annotations:c.union([Yl,c.null()]).optional(),text:c.string()}),v2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),mimeType:c.union([c.string(),c.null()]).optional(),text:c.string(),uri:c.string()}),y2=c.union([v2,mP]),b2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),annotations:c.union([Yl,c.null()]).optional(),resource:y2}),d_=c.union([h2.and(c.object({type:c.literal("text")})),UP.and(c.object({type:c.literal("image")})),MP.and(c.object({type:c.literal("audio")})),RP.and(c.object({type:c.literal("resource_link")})),b2.and(c.object({type:c.literal("resource")}))]),S2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),content:d_}),Fx=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),content:d_}),f_=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),prompt:c.array(d_),sessionId:rt}),R8=c.object({id:io,method:c.string(),params:c.union([c.union([Qx,Xx,Kx,r_,Jx,n_,s_,l_,s2,f_,u_,lI]),c.null()]).optional()}),hI=c.union([S2.and(c.object({type:c.literal("content")})),gP.and(c.object({type:c.literal("diff")})),m2.and(c.object({type:c.literal("terminal")}))]),vI=c.string(),yI=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),line:c.union([c.number().int().gte(0),c.null()]).optional(),path:c.string()}),bI=c.union([c.literal("pending"),c.literal("in_progress"),c.literal("completed"),c.literal("failed")]),SI=c.union([c.literal("read"),c.literal("edit"),c.literal("delete"),c.literal("move"),c.literal("search"),c.literal("execute"),c.literal("think"),c.literal("fetch"),c.literal("switch_mode"),c.literal("other")]),x2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),content:c.array(hI).optional(),kind:SI.optional(),locations:c.array(yI).optional(),rawInput:c.unknown().optional(),rawOutput:c.unknown().optional(),status:bI.optional(),title:c.string(),toolCallId:vI}),xI=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),content:c.union([c.array(hI),c.null()]).optional(),kind:c.union([SI,c.null()]).optional(),locations:c.union([c.array(yI),c.null()]).optional(),rawInput:c.unknown().optional(),rawOutput:c.unknown().optional(),status:c.union([bI,c.null()]).optional(),title:c.union([c.string(),c.null()]).optional(),toolCallId:vI}),m_=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),options:c.array(AP),sessionId:rt,toolCall:xI}),_2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),hint:c.string()}),$2=_2,w2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),description:c.string(),input:c.union([$2,c.null()]).optional(),name:c.string()}),z2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),availableCommands:c.array(w2)}),A2=c.union([Fx.and(c.object({sessionUpdate:c.literal("user_message_chunk")})),Fx.and(c.object({sessionUpdate:c.literal("agent_message_chunk")})),Fx.and(c.object({sessionUpdate:c.literal("agent_thought_chunk")})),x2.and(c.object({sessionUpdate:c.literal("tool_call")})),xI.and(c.object({sessionUpdate:c.literal("tool_call_update")})),CP.and(c.object({sessionUpdate:c.literal("plan")})),z2.and(c.object({sessionUpdate:c.literal("available_commands_update")})),KP.and(c.object({sessionUpdate:c.literal("current_mode_update")})),BP.and(c.object({sessionUpdate:c.literal("config_option_update")})),JP.and(c.object({sessionUpdate:c.literal("session_info_update")}))]),p_=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),sessionId:rt,update:A2}),j8=c.object({method:c.string(),params:c.union([c.union([p_,sI]),c.null()]).optional()}),g_=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),sessionId:rt,terminalId:c.string()}),E2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),exitCode:c.union([c.number().int().gte(0),c.null()]).optional(),signal:c.union([c.string(),c.null()]).optional()}),h_=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional(),content:c.string(),path:c.string(),sessionId:rt}),P8=c.object({id:io,method:c.string(),params:c.union([c.union([h_,o_,m_,t_,c_,a_,g_,i_,lI]),c.null()]).optional()}),T2=c.object({_meta:c.union([c.record(c.string(),c.unknown()),c.null()]).optional()}),L8=c.union([c.object({id:io,result:c.union([T2,NP,LP,pP,g2,OP,E2,bP,uI])}),c.object({error:aI,id:io})]);function _I(e,t){let n=new TextEncoder,r=new TextDecoder,i=new ReadableStream({async start(a){let s="",u=t.getReader();try{for(;;){let{value:d,done:m}=await u.read();if(m)break;if(!d)continue;s+=r.decode(d,{stream:!0});let l=s.split(` `);s=l.pop()||"";for(let f of l){let p=f.trim();if(p)try{let h=JSON.parse(p);a.enqueue(h)}catch(h){console.error("Failed to parse JSON message:",p,h)}}}}finally{u.releaseLock(),a.close()}}}),o=new WritableStream({async write(a){let s=JSON.stringify(a)+` `,u=e.getWriter();try{await u.write(n.encode(s))}finally{u.releaseLock()}}});return{readable:i,writable:o}}var Xt,$I=class{constructor(t,n){ot(this,Xt,void 0);let r=t(this),i=async(a,s)=>{switch(a){case Ge.initialize:{let u=Qx.parse(s);return r.initialize(u)}case Ge.session_new:{let u=Kx.parse(s);return r.newSession(u)}case Ge.session_load:{if(!r.loadSession)throw _e.methodNotFound(a);let u=r_.parse(s);return r.loadSession(u)}case Ge.session_list:{if(!r.unstable_listSessions)throw _e.methodNotFound(a);let u=Jx.parse(s);return r.unstable_listSessions(u)}case Ge.session_fork:{if(!r.unstable_forkSession)throw _e.methodNotFound(a);let u=n_.parse(s);return r.unstable_forkSession(u)}case Ge.session_resume:{if(!r.unstable_resumeSession)throw _e.methodNotFound(a);let u=s_.parse(s);return r.unstable_resumeSession(u)}case Ge.session_set_mode:{if(!r.setSessionMode)throw _e.methodNotFound(a);let u=l_.parse(s),d=await r.setSessionMode(u);return d!=null?d:{}}case Ge.authenticate:{let u=Xx.parse(s),d=await r.authenticate(u);return d!=null?d:{}}case Ge.session_prompt:{let u=f_.parse(s);return r.prompt(u)}case Ge.session_set_model:{if(!r.unstable_setSessionModel)throw _e.methodNotFound(a);let u=u_.parse(s),d=await r.unstable_setSessionModel(u);return d!=null?d:{}}default:if(a.startsWith("_")){if(!r.extMethod)throw _e.methodNotFound(a);return r.extMethod(a.substring(1),s)}throw _e.methodNotFound(a)}},o=async(a,s)=>{switch(a){case Ge.session_cancel:{let u=e_.parse(s);return r.cancel(u)}default:if(a.startsWith("_"))return r.extNotification?r.extNotification(a.substring(1),s):void 0;throw _e.methodNotFound(a)}};zn(this,Xt,new cm(i,o,n))}async sessionUpdate(t){return await te(this,Xt).sendNotification(ut.session_update,t)}async requestPermission(t){return await te(this,Xt).sendRequest(ut.session_request_permission,t)}async readTextFile(t){return await te(this,Xt).sendRequest(ut.fs_read_text_file,t)}async writeTextFile(t){var n;return(n=await te(this,Xt).sendRequest(ut.fs_write_text_file,t))!=null?n:{}}async createTerminal(t){let n=await te(this,Xt).sendRequest(ut.terminal_create,t);return new v_(n.terminalId,t.sessionId,te(this,Xt))}async extMethod(t,n){return await te(this,Xt).sendRequest(`_${t}`,n)}async extNotification(t,n){return await te(this,Xt).sendNotification(`_${t}`,n)}get signal(){return te(this,Xt).signal}get closed(){return te(this,Xt).closed}};Xt=new WeakMap;var pr,gr,v_=class{constructor(t,n,r){uu(this,"id");ot(this,pr,void 0);ot(this,gr,void 0);this.id=t,zn(this,pr,n),zn(this,gr,r)}async currentOutput(){return await te(this,gr).sendRequest(ut.terminal_output,{sessionId:te(this,pr),terminalId:this.id})}async waitForExit(){return await te(this,gr).sendRequest(ut.terminal_wait_for_exit,{sessionId:te(this,pr),terminalId:this.id})}async kill(){var t;return(t=await te(this,gr).sendRequest(ut.terminal_kill,{sessionId:te(this,pr),terminalId:this.id}))!=null?t:{}}async release(){var t;return(t=await te(this,gr).sendRequest(ut.terminal_release,{sessionId:te(this,pr),terminalId:this.id}))!=null?t:{}}async[Symbol.asyncDispose](){await this.release()}};pr=new WeakMap,gr=new WeakMap;var ct,um=class{constructor(t,n){ot(this,ct,void 0);let r=t(this),i=async(a,s)=>{var u,d,m,l,f,p,h;switch(a){case ut.fs_write_text_file:{let v=h_.parse(s);return(u=r.writeTextFile)==null?void 0:u.call(r,v)}case ut.fs_read_text_file:{let v=o_.parse(s);return(d=r.readTextFile)==null?void 0:d.call(r,v)}case ut.session_request_permission:{let v=m_.parse(s);return r.requestPermission(v)}case ut.terminal_create:{let v=t_.parse(s);return(m=r.createTerminal)==null?void 0:m.call(r,v)}case ut.terminal_output:{let v=c_.parse(s);return(l=r.terminalOutput)==null?void 0:l.call(r,v)}case ut.terminal_release:{let v=a_.parse(s),x=await((f=r.releaseTerminal)==null?void 0:f.call(r,v));return x!=null?x:{}}case ut.terminal_wait_for_exit:{let v=g_.parse(s);return(p=r.waitForTerminalExit)==null?void 0:p.call(r,v)}case ut.terminal_kill:{let v=i_.parse(s),x=await((h=r.killTerminal)==null?void 0:h.call(r,v));return x!=null?x:{}}default:if(a.startsWith("_")){let v=a.substring(1);if(!r.extMethod)throw _e.methodNotFound(a);return r.extMethod(v,s)}throw _e.methodNotFound(a)}},o=async(a,s)=>{switch(a){case ut.session_update:{let u=p_.parse(s);return r.sessionUpdate(u)}default:if(a.startsWith("_")){let u=a.substring(1);return r.extNotification?r.extNotification(u,s):void 0}throw _e.methodNotFound(a)}};zn(this,ct,new cm(i,o,n))}async initialize(t){return await te(this,ct).sendRequest(Ge.initialize,t)}async newSession(t){return await te(this,ct).sendRequest(Ge.session_new,t)}async loadSession(t){var n;return(n=await te(this,ct).sendRequest(Ge.session_load,t))!=null?n:{}}async unstable_forkSession(t){return await te(this,ct).sendRequest(Ge.session_fork,t)}async unstable_listSessions(t){return await te(this,ct).sendRequest(Ge.session_list,t)}async unstable_resumeSession(t){return await te(this,ct).sendRequest(Ge.session_resume,t)}async setSessionMode(t){var n;return(n=await te(this,ct).sendRequest(Ge.session_set_mode,t))!=null?n:{}}async unstable_setSessionModel(t){var n;return(n=await te(this,ct).sendRequest(Ge.session_set_model,t))!=null?n:{}}async authenticate(t){var n;return(n=await te(this,ct).sendRequest(Ge.authenticate,t))!=null?n:{}}async prompt(t){return await te(this,ct).sendRequest(Ge.session_prompt,t)}async cancel(t){return await te(this,ct).sendNotification(Ge.session_cancel,t)}async extMethod(t,n){return await te(this,ct).sendRequest(`_${t}`,n)}async extNotification(t,n){return await te(this,ct).sendNotification(`_${t}`,n)}get signal(){return te(this,ct).signal}get closed(){return te(this,ct).closed}};ct=new WeakMap;var Ha,dm,Ql,Wl,Ba,Ga,Fa,eu,fm,wI,mm,zI,pm,AI,gm,EI,hm,TI,ro,Kl,cm=class{constructor(t,n,r){ot(this,fm);ot(this,mm);ot(this,pm);ot(this,gm);ot(this,hm);ot(this,ro);ot(this,Ha,new Map);ot(this,dm,0);ot(this,Ql,void 0);ot(this,Wl,void 0);ot(this,Ba,void 0);ot(this,Ga,Promise.resolve());ot(this,Fa,new AbortController);ot(this,eu,void 0);zn(this,Ql,t),zn(this,Wl,n),zn(this,Ba,r),zn(this,eu,new Promise(i=>{te(this,Fa).signal.addEventListener("abort",()=>i())})),Dn(this,fm,wI).call(this)}get signal(){return te(this,Fa).signal}get closed(){return te(this,eu)}async sendRequest(t,n){let r=z_(this,dm)._++,i=new Promise((o,a)=>{te(this,Ha).set(r,{resolve:o,reject:a})});return await Dn(this,ro,Kl).call(this,{jsonrpc:"2.0",id:r,method:t,params:n}),i}async sendNotification(t,n){await Dn(this,ro,Kl).call(this,{jsonrpc:"2.0",method:t,params:n})}};Ha=new WeakMap,dm=new WeakMap,Ql=new WeakMap,Wl=new WeakMap,Ba=new WeakMap,Ga=new WeakMap,Fa=new WeakMap,eu=new WeakMap,fm=new WeakSet,wI=async function(){let t=te(this,Ba).readable.getReader();try{for(;;){let{value:n,done:r}=await t.read();if(r)break;if(n)try{Dn(this,mm,zI).call(this,n)}catch(i){console.error("Unexpected error during message processing:",n,i),"id"in n&&n.id!==void 0&&Dn(this,ro,Kl).call(this,{jsonrpc:"2.0",id:n.id,error:{code:-32700,message:"Parse error"}})}}}finally{t.releaseLock(),te(this,Fa).abort()}},mm=new WeakSet,zI=async function(t){if("method"in t&&"id"in t){let n=await Dn(this,pm,AI).call(this,t.method,t.params);"error"in n&&console.error("Error handling request",t,n.error),await Dn(this,ro,Kl).call(this,{jsonrpc:"2.0",id:t.id,...n})}else if("method"in t){let n=await Dn(this,gm,EI).call(this,t.method,t.params);"error"in n&&console.error("Error handling notification",t,n.error)}else"id"in t?Dn(this,hm,TI).call(this,t):console.error("Invalid message",{message:t})},pm=new WeakSet,AI=async function(t,n){try{let r=await te(this,Ql).call(this,t,n);return{result:r!=null?r:null}}catch(r){if(r instanceof _e)return r.toResult();if(r instanceof c.ZodError)return _e.invalidParams(r.format()).toResult();let i;(r instanceof Error||typeof r=="object"&&r!=null&&"message"in r&&typeof r.message=="string")&&(i=r.message);try{return _e.internalError(i?JSON.parse(i):{}).toResult()}catch(o){return _e.internalError({details:i}).toResult()}}},gm=new WeakSet,EI=async function(t,n){try{return await te(this,Wl).call(this,t,n),{result:null}}catch(r){if(r instanceof _e)return r.toResult();if(r instanceof c.ZodError)return _e.invalidParams(r.format()).toResult();let i;(r instanceof Error||typeof r=="object"&&r!=null&&"message"in r&&typeof r.message=="string")&&(i=r.message);try{return _e.internalError(i?JSON.parse(i):{}).toResult()}catch(o){return _e.internalError({details:i}).toResult()}}},hm=new WeakSet,TI=function(t){let n=te(this,Ha).get(t.id);n?("result"in t?n.resolve(t.result):"error"in t&&n.reject(t.error),te(this,Ha).delete(t.id)):console.error("Got response to unknown request",t.id)},ro=new WeakSet,Kl=async function(t){return zn(this,Ga,te(this,Ga).then(async()=>{let n=te(this,Ba).writable.getWriter();try{await n.write(t)}finally{n.releaseLock()}}).catch(n=>{console.error("ACP write error:",n)})),te(this,Ga)};var _e=class extends Error{constructor(n,r,i){super(r);uu(this,"code");uu(this,"data");this.code=n,this.name="RequestError",this.data=i}static parseError(n,r){return new _e(-32700,`Parse error${r?`: ${r}`:""}`,n)}static invalidRequest(n,r){return new _e(-32600,`Invalid request${r?`: ${r}`:""}`,n)}static methodNotFound(n){return new _e(-32601,`"Method not found": ${n}`,{method:n})}static invalidParams(n,r){return new _e(-32602,`Invalid params${r?`: ${r}`:""}`,n)}static internalError(n,r){return new _e(-32603,`Internal error${r?`: ${r}`:""}`,n)}static authRequired(n,r){return new _e(-32e3,`Authentication required${r?`: ${r}`:""}`,n)}static resourceNotFound(n){return new _e(-32002,`Resource not found${n?`: ${n}`:""}`,n&&{uri:n})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}};var Nn=require("obsidian");var Xa=class{static toToolCallContent(t){if(!t)return;let n=[];for(let r of t)r.type==="diff"?n.push({type:"diff",path:r.path,newText:r.newText,oldText:r.oldText}):r.type==="terminal"&&n.push({type:"terminal",terminalId:r.terminalId});return n.length>0?n:void 0}static toAcpContentBlock(t){switch(t.type){case"text":return{type:"text",text:t.text};case"image":return{type:"image",data:t.data,mimeType:t.mimeType};case"resource":return{type:"resource",resource:{uri:t.resource.uri,mimeType:t.resource.mimeType,text:t.resource.text},annotations:t.annotations}}}};var CI=require("child_process");var zi=require("obsidian");var y_=require("child_process"),b_=require("obsidian"),vm=null;function I2(){if(!b_.Platform.isWin)return null;if(vm!==null)return vm;try{let e=(0,y_.execSync)('reg query "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment" /v Path',{encoding:"utf8",windowsHide:!0}),t=(0,y_.execSync)('reg query "HKCU\\Environment" /v Path',{encoding:"utf8",windowsHide:!0}),n=kI(e),r=kI(t),i=[];return r&&i.push(r),n&&i.push(n),vm=i.join(";"),vm}catch(e){return null}}function kI(e){let t=e.split(` -`);for(let n of t){let r=n.trim();if(r.toLowerCase().startsWith("path")){let i=r.match(/Path\s+REG_(?:EXPAND_)?SZ\s+(.+)/i);if(i)return i[1].trim()}}return null}function ym(e){if(!b_.Platform.isWin)return e;let t=I2();if(!t)return e;let r=(e.PATH||"").split(";").filter(a=>a.length>0),i=t.split(";").filter(a=>a.length>0),o=[...r];for(let a of i)o.some(s=>s.toLowerCase()===a.toLowerCase())||o.push(a);return{...e,PATH:o.join(";")}}function Ja(e){let t=e.replace(/%/g,"%%").replace(/"/g,'""');return/[\s&()<>|^]/.test(e)?`"${t}"`:t}var bm=class{constructor(t){this.terminals=new Map;this.logger=new Le(t),this.plugin=t}createTerminal(t){var m,l,f;let n=crypto.randomUUID();if(!zi.Platform.isDesktopApp)throw new Error("Agent Client is only available on desktop");let r={...process.env};if(zi.Platform.isWin&&!this.plugin.settings.windowsWslMode&&(r=ym(r)),t.env)for(let p of t.env)r[p.name]=p.value;let i=t.command,o=t.args||[];if(zi.Platform.isWin&&this.plugin.settings.windowsWslMode){let p=this.plugin.settings.nodePath&&oa(this.plugin.settings.nodePath.trim())||void 0,h=md(i,o,t.cwd||process.cwd(),this.plugin.settings.windowsWslDistribution,p);i=h.command,o=h.args,this.logger.log(`[Terminal ${n}] Using WSL mode:`,this.plugin.settings.windowsWslDistribution||"default")}else if(zi.Platform.isMacOS||zi.Platform.isLinux){let p=zi.Platform.isMacOS?"/bin/zsh":"/bin/bash",h;o.length>0?h=[i,...o].map(v=>"'"+v.replace(/'/g,"'\\''")+"'").join(" "):h=i,i=p,o=["-l","-c",h]}else zi.Platform.isWin&&o.length>0&&(i=Ja(i),o=o.map(Ja));this.logger.log(`[Terminal ${n}] Creating terminal:`,{command:i,args:o,cwd:t.cwd});let a=zi.Platform.isWin&&!this.plugin.settings.windowsWslMode,s={cwd:t.cwd||void 0,env:r,stdio:["pipe","pipe","pipe"],shell:a},u=(0,CI.spawn)(i,o,s),d={id:n,process:u,output:"",exitStatus:null,outputByteLimit:(m=t.outputByteLimit)!=null?m:void 0,waitPromises:[]};return u.on("error",p=>{this.logger.log(`[Terminal ${n}] Process error:`,p.message);let h={exitCode:127,signal:null};d.exitStatus=h,d.waitPromises.forEach(v=>v(h)),d.waitPromises=[]}),(l=u.stdout)==null||l.on("data",p=>{let h=p.toString();this.logger.log(`[Terminal ${n}] stdout:`,h),this.appendOutput(d,h)}),(f=u.stderr)==null||f.on("data",p=>{let h=p.toString();this.logger.log(`[Terminal ${n}] stderr:`,h),this.appendOutput(d,h)}),u.on("exit",(p,h)=>{this.logger.log(`[Terminal ${n}] Process exited with code: ${p}, signal: ${h}`);let v={exitCode:p,signal:h};d.exitStatus=v,d.waitPromises.forEach(x=>x(v)),d.waitPromises=[]}),this.terminals.set(n,d),n}appendOutput(t,n){if(t.output+=n,t.outputByteLimit&&Buffer.byteLength(t.output,"utf8")>t.outputByteLimit){let r=Buffer.from(t.output,"utf8"),i=r.subarray(r.length-t.outputByteLimit);t.output=i.toString("utf8")}}getOutput(t){let n=this.terminals.get(t);return n?{output:n.output,truncated:n.outputByteLimit?Buffer.byteLength(n.output,"utf8")>=n.outputByteLimit:!1,exitStatus:n.exitStatus}:null}waitForExit(t){let n=this.terminals.get(t);return n?n.exitStatus?Promise.resolve(n.exitStatus):new Promise(r=>{n.waitPromises.push(r)}):Promise.reject(new Error(`Terminal ${t} not found`))}killTerminal(t){let n=this.terminals.get(t);return n?(n.exitStatus||n.process.kill("SIGTERM"),!0):!1}releaseTerminal(t){let n=this.terminals.get(t);return n?(this.logger.log(`[Terminal ${t}] Releasing terminal`),n.exitStatus||n.process.kill("SIGTERM"),n.cleanupTimeout=window.setTimeout(()=>{this.logger.log(`[Terminal ${t}] Cleaning up terminal after grace period`),this.terminals.delete(t)},3e4),!0):!1}killAllTerminals(){this.logger.log(`Killing ${this.terminals.size} running terminals...`),this.terminals.forEach((t,n)=>{t.cleanupTimeout&&window.clearTimeout(t.cleanupTimeout),t.exitStatus||(this.logger.log(`Killing terminal ${n}`),this.killTerminal(n))}),this.terminals.clear()}};var Sm=class{constructor(t){this.plugin=t;this.connection=null;this.agentProcess=null;this.sessionUpdateCallback=null;this.errorCallback=null;this.currentConfig=null;this.isInitializedFlag=!1;this.currentAgentId=null;this.autoAllowPermissions=!1;this.currentMessageId=null;this.pendingPermissionRequests=new Map;this.pendingPermissionQueue=[];this.logger=new Le(t),this.updateMessage=()=>{},this.terminalManager=new bm(t)}setUpdateMessageCallback(t){this.updateMessage=t}async initialize(t){var v,x,y,g,b,S,$,R,A,T,z,E,F,P,V,L,C,M,K,ce,be;if(this.logger.log("[AcpAdapter] Starting initialization with config:",t),this.logger.log(`[AcpAdapter] Current state - process: ${!!this.agentProcess}, PID: ${(v=this.agentProcess)==null?void 0:v.pid}`),this.agentProcess&&(this.logger.log(`[AcpAdapter] Killing existing process (PID: ${this.agentProcess.pid})`),this.agentProcess.kill(),this.agentProcess=null),this.connection&&(this.logger.log("[AcpAdapter] Cleaning up existing connection"),this.connection=null),this.currentConfig=t,this.autoAllowPermissions=this.plugin.settings.autoAllowPermissions,!t.command||t.command.trim().length===0)throw new Error(`Command not configured for agent "${t.displayName}" (${t.id}). Please configure the agent command in settings.`);let n=t.command.trim(),r=t.args.length>0?[...t.args]:[];this.logger.log(`[AcpAdapter] Active agent: ${t.displayName} (${t.id})`),this.logger.log("[AcpAdapter] Command:",n),this.logger.log("[AcpAdapter] Args:",r.length>0?r.join(" "):"(none)");let i={...process.env,...t.env||{}};if(Nn.Platform.isWin&&!this.plugin.settings.windowsWslMode&&(i=ym(i)),this.plugin.settings.nodePath&&this.plugin.settings.nodePath.trim().length>0){let q=oa(this.plugin.settings.nodePath.trim());if(q){let W=Nn.Platform.isWin?";":":";i.PATH=i.PATH?`${q}${W}${i.PATH}`:q}}this.logger.log("[AcpAdapter] Starting agent process in directory:",t.workingDirectory);let o=n,a=r;if(Nn.Platform.isWin&&this.plugin.settings.windowsWslMode){let q=this.plugin.settings.nodePath&&oa(this.plugin.settings.nodePath.trim())||void 0,W=md(n,r,t.workingDirectory,this.plugin.settings.windowsWslDistribution,q);o=W.command,a=W.args,this.logger.log("[AcpAdapter] Using WSL mode:",this.plugin.settings.windowsWslDistribution||"default","with command:",o,a)}else if(Nn.Platform.isMacOS||Nn.Platform.isLinux){let q=Nn.Platform.isMacOS?"/bin/zsh":"/bin/bash",W=[n,...r].map(Oe=>"'"+Oe.replace(/'/g,"'\\''")+"'").join(" "),Ye=W;if(this.plugin.settings.nodePath&&this.plugin.settings.nodePath.trim().length>0){let Oe=oa(this.plugin.settings.nodePath.trim());Oe&&(Ye=`export PATH='${Oe.replace(/'/g,"'\\''")}':"$PATH"; ${W}`)}o=q,a=["-l","-c",Ye],this.logger.log("[AcpAdapter] Using login shell:",q,"with command:",Ye)}else Nn.Platform.isWin&&(o=Ja(n),a=r.map(Ja),this.logger.log("[AcpAdapter] Using Windows shell with command:",o,a));let s=Nn.Platform.isWin&&!this.plugin.settings.windowsWslMode,u=(0,II.spawn)(o,a,{stdio:["pipe","pipe","pipe"],env:i,cwd:t.workingDirectory,shell:s});this.agentProcess=u;let d=`${t.displayName} (${t.id})`;if(u.on("spawn",()=>{this.logger.log(`[AcpAdapter] ${d} process spawned successfully, PID:`,u.pid)}),u.on("error",q=>{var Ye;this.logger.error(`[AcpAdapter] ${d} process error:`,q);let W={id:crypto.randomUUID(),category:"connection",severity:"error",occurredAt:new Date,agentId:t.id,originalError:q,...this.getErrorInfo(q,n,d)};(Ye=this.errorCallback)==null||Ye.call(this,W)}),u.on("exit",(q,W)=>{var Ye;if(this.logger.log(`[AcpAdapter] ${d} process exited with code:`,q,"signal:",W),q===127){this.logger.error(`[AcpAdapter] Command not found: ${n}`);let Oe={id:crypto.randomUUID(),category:"configuration",severity:"error",title:"Command Not Found",message:`The command "${n}" could not be found. Please check the path configuration for ${d}.`,suggestion:this.getCommandNotFoundSuggestion(n),occurredAt:new Date,agentId:t.id,code:q};(Ye=this.errorCallback)==null||Ye.call(this,Oe)}}),u.on("close",(q,W)=>{this.logger.log(`[AcpAdapter] ${d} process closed with code:`,q,"signal:",W)}),(x=u.stderr)==null||x.setEncoding("utf8"),(y=u.stderr)==null||y.on("data",q=>{this.logger.log(`[AcpAdapter] ${d} stderr:`,q)}),!u.stdin||!u.stdout)throw new Error("Agent process stdin/stdout not available");let m=u.stdin,l=u.stdout,f=new WritableStream({write(q){m.write(q)},close(){m.end()}}),p=new ReadableStream({start(q){l.on("data",W=>{q.enqueue(W)}),l.on("end",()=>{q.close()})}});this.logger.log("[AcpAdapter] Using working directory:",t.workingDirectory);let h=_I(f,p);this.connection=new um(()=>this,h);try{this.logger.log("[AcpAdapter] Starting ACP initialization...");let q=await this.connection.initialize({protocolVersion:rI,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!0},clientInfo:{name:"obsidian-agent-client",title:"Agent Client for Obsidian",version:this.plugin.manifest.version}});this.logger.log(`[AcpAdapter] \u2705 Connected to agent (protocol v${q.protocolVersion})`),this.logger.log("[AcpAdapter] Auth methods:",q.authMethods),this.logger.log("[AcpAdapter] Agent capabilities:",q.agentCapabilities),this.isInitializedFlag=!0,this.currentAgentId=t.id;let W=(g=q.agentCapabilities)==null?void 0:g.promptCapabilities,Ye=(b=q.agentCapabilities)==null?void 0:b.mcpCapabilities,Oe=(S=q.agentCapabilities)==null?void 0:S.sessionCapabilities;return{protocolVersion:q.protocolVersion,authMethods:q.authMethods||[],promptCapabilities:{image:($=W==null?void 0:W.image)!=null?$:!1,audio:(R=W==null?void 0:W.audio)!=null?R:!1,embeddedContext:(A=W==null?void 0:W.embeddedContext)!=null?A:!1},agentCapabilities:{loadSession:(z=(T=q.agentCapabilities)==null?void 0:T.loadSession)!=null?z:!1,sessionCapabilities:Oe?{resume:(E=Oe.resume)!=null?E:void 0,fork:(F=Oe.fork)!=null?F:void 0,list:(P=Oe.list)!=null?P:void 0}:void 0,mcpCapabilities:Ye?{http:(V=Ye.http)!=null?V:!1,sse:(L=Ye.sse)!=null?L:!1}:void 0,promptCapabilities:{image:(C=W==null?void 0:W.image)!=null?C:!1,audio:(M=W==null?void 0:W.audio)!=null?M:!1,embeddedContext:(K=W==null?void 0:W.embeddedContext)!=null?K:!1}},agentInfo:q.agentInfo?{name:q.agentInfo.name,title:(ce=q.agentInfo.title)!=null?ce:void 0,version:(be=q.agentInfo.version)!=null?be:void 0}:void 0}}catch(q){throw this.logger.error("[AcpAdapter] Initialization Error:",q),this.isInitializedFlag=!1,this.currentAgentId=null,q}}async newSession(t){if(!this.connection)throw new Error("Connection not initialized. Call initialize() first.");try{this.logger.log("[AcpAdapter] Creating new session...");let n=t;Nn.Platform.isWin&&this.plugin.settings.windowsWslMode&&(n=xi(t)),this.logger.log("[AcpAdapter] Using working directory:",n);let r=await this.connection.newSession({cwd:n,mcpServers:[]});this.logger.log(`[AcpAdapter] \u{1F4DD} Created session: ${r.sessionId}`),this.logger.log("[AcpAdapter] NewSessionResponse:",JSON.stringify(r,null,2));let i;r.modes&&(i={availableModes:r.modes.availableModes.map(a=>{var s;return{id:a.id,name:a.name,description:(s=a.description)!=null?s:void 0}}),currentModeId:r.modes.currentModeId},this.logger.log(`[AcpAdapter] Session modes: ${i.availableModes.map(a=>a.id).join(", ")} (current: ${i.currentModeId})`));let o;return r.models&&(o={availableModels:r.models.availableModels.map(a=>{var s;return{modelId:a.modelId,name:a.name,description:(s=a.description)!=null?s:void 0}}),currentModelId:r.models.currentModelId},this.logger.log(`[AcpAdapter] Session models: ${o.availableModels.map(a=>a.modelId).join(", ")} (current: ${o.currentModelId})`)),{sessionId:r.sessionId,modes:i,models:o}}catch(n){throw this.logger.error("[AcpAdapter] New Session Error:",n),n}}async authenticate(t){if(!this.connection)throw new Error("Connection not initialized. Call initialize() first.");try{return await this.connection.authenticate({methodId:t}),this.logger.log("[AcpAdapter] \u2705 authenticate ok:",t),!0}catch(n){return this.logger.error("[AcpAdapter] Authentication Error:",n),!1}}async sendPrompt(t,n){if(!this.connection)throw new Error("Connection not initialized. Call initialize() first.");this.resetCurrentMessage();try{let r=n.map(o=>Xa.toAcpContentBlock(o));this.logger.log(`[AcpAdapter] Sending prompt with ${n.length} content blocks`);let i=await this.connection.prompt({sessionId:t,prompt:r});this.logger.log(`[AcpAdapter] Agent completed with: ${i.stopReason}`)}catch(r){this.logger.error("[AcpAdapter] Prompt Error:",r);let i=r;if(i&&typeof i=="object"&&"code"in i&&i.code===-32603&&"data"in i){let o=i.data;if(o&&typeof o=="object"&&"details"in o&&typeof o.details=="string"){if(o.details.includes("empty response text")){this.logger.log("[AcpAdapter] Empty response text error - ignoring");return}if(o.details.includes("user aborted")){this.logger.log("[AcpAdapter] User aborted request - ignoring");return}}}throw r}}async cancel(t){if(!this.connection){this.logger.warn("[AcpAdapter] Cannot cancel: no connection");return}try{this.logger.log("[AcpAdapter] Sending session/cancel notification..."),await this.connection.cancel({sessionId:t}),this.logger.log("[AcpAdapter] Cancellation request sent successfully"),this.cancelAllOperations()}catch(n){this.logger.error("[AcpAdapter] Failed to send cancellation:",n),this.cancelAllOperations()}}disconnect(){return this.logger.log("[AcpAdapter] Disconnecting..."),this.cancelAllOperations(),this.agentProcess&&(this.logger.log(`[AcpAdapter] Killing agent process (PID: ${this.agentProcess.pid})`),this.agentProcess.kill(),this.agentProcess=null),this.connection=null,this.currentConfig=null,this.isInitializedFlag=!1,this.currentAgentId=null,this.logger.log("[AcpAdapter] Disconnected"),Promise.resolve()}isInitialized(){return this.isInitializedFlag&&this.connection!==null&&this.agentProcess!==null}getCurrentAgentId(){return this.currentAgentId}async setSessionMode(t,n){if(!this.connection)throw new Error("Connection not initialized. Call initialize() first.");this.logger.log(`[AcpAdapter] Setting session mode to: ${n} for session: ${t}`);try{await this.connection.setSessionMode({sessionId:t,modeId:n}),this.logger.log(`[AcpAdapter] Session mode set to: ${n}`)}catch(r){throw this.logger.error("[AcpAdapter] Failed to set session mode:",r),r}}async setSessionModel(t,n){if(!this.connection)throw new Error("Connection not initialized. Call initialize() first.");this.logger.log(`[AcpAdapter] Setting session model to: ${n} for session: ${t}`);try{await this.connection.unstable_setSessionModel({sessionId:t,modelId:n}),this.logger.log(`[AcpAdapter] Session model set to: ${n}`)}catch(r){throw this.logger.error("[AcpAdapter] Failed to set session model:",r),r}}onSessionUpdate(t){this.sessionUpdateCallback=t}onError(t){this.errorCallback=t}respondToPermission(t,n){if(!this.connection)throw new Error("ACP connection not initialized. Call initialize() first.");return this.logger.log("[AcpAdapter] Responding to permission request:",t,"with option:",n),this.handlePermissionResponse(t,n),Promise.resolve()}getErrorInfo(t,n,r){return t.code==="ENOENT"?{title:"Command Not Found",message:`The command "${n}" could not be found. Please check the path configuration for ${r}.`,suggestion:this.getCommandNotFoundSuggestion(n)}:{title:"Agent Startup Error",message:`Failed to start ${r}: ${t.message}`,suggestion:"Please check the agent configuration in settings."}}getCommandNotFoundSuggestion(t){var r;let n=((r=t.split("/").pop())==null?void 0:r.split("\\").pop())||"command";return Nn.Platform.isWin?`1. Verify the agent path: Use "where ${n}" in Command Prompt to find the correct path. 2. If the agent requires Node.js, also check that Node.js path is correctly set in General Settings (use "where node" to find it).`:`1. Verify the agent path: Use "which ${n}" in Terminal to find the correct path. 2. If the agent requires Node.js, also check that Node.js path is correctly set in General Settings (use "which node" to find it).`}sessionUpdate(t){var i,o,a,s,u,d,m,l,f,p;let n=t.update,r=t.sessionId;switch(this.logger.log("[AcpAdapter] sessionUpdate:",{sessionId:r,update:n}),n.sessionUpdate){case"agent_message_chunk":n.content.type==="text"&&((i=this.sessionUpdateCallback)==null||i.call(this,{type:"agent_message_chunk",sessionId:r,text:n.content.text}));break;case"agent_thought_chunk":n.content.type==="text"&&((o=this.sessionUpdateCallback)==null||o.call(this,{type:"agent_thought_chunk",sessionId:r,text:n.content.text}));break;case"user_message_chunk":n.content.type==="text"&&((a=this.sessionUpdateCallback)==null||a.call(this,{type:"user_message_chunk",sessionId:r,text:n.content.text}));break;case"tool_call":case"tool_call_update":{(m=this.sessionUpdateCallback)==null||m.call(this,{type:n.sessionUpdate,sessionId:r,toolCallId:n.toolCallId,title:(s=n.title)!=null?s:void 0,status:n.status||"pending",kind:(u=n.kind)!=null?u:void 0,content:Xa.toToolCallContent(n.content),locations:(d=n.locations)!=null?d:void 0});break}case"plan":(l=this.sessionUpdateCallback)==null||l.call(this,{type:"plan",sessionId:r,entries:n.entries});break;case"available_commands_update":{this.logger.log("[AcpAdapter] available_commands_update, commands:",n.availableCommands);let h=(n.availableCommands||[]).map(v=>{var x,y;return{name:v.name,description:v.description,hint:(y=(x=v.input)==null?void 0:x.hint)!=null?y:null}});(f=this.sessionUpdateCallback)==null||f.call(this,{type:"available_commands_update",sessionId:r,commands:h});break}case"current_mode_update":{this.logger.log(`[AcpAdapter] current_mode_update: ${n.currentModeId}`),(p=this.sessionUpdateCallback)==null||p.call(this,{type:"current_mode_update",sessionId:r,currentModeId:n.currentModeId});break}}return Promise.resolve()}resetCurrentMessage(){this.currentMessageId=null}handlePermissionResponse(t,n){let r=this.pendingPermissionRequests.get(t);if(!r)return;let{resolve:i,toolCallId:o,options:a}=r;this.updateMessage(o,{type:"tool_call",toolCallId:o,permissionRequest:{requestId:t,options:a,selectedOptionId:n,isActive:!1}}),i({outcome:{outcome:"selected",optionId:n}}),this.pendingPermissionRequests.delete(t),this.pendingPermissionQueue=this.pendingPermissionQueue.filter(s=>s.requestId!==t),this.activateNextPermission()}cancelAllOperations(){this.cancelPendingPermissionRequests(),this.terminalManager.killAllTerminals()}activateNextPermission(){if(this.pendingPermissionQueue.length===0)return;let t=this.pendingPermissionQueue[0],n=this.pendingPermissionRequests.get(t.requestId);n&&this.updateMessage(t.toolCallId,{type:"tool_call",toolCallId:t.toolCallId,permissionRequest:{requestId:t.requestId,options:n.options,isActive:!0}})}async requestPermission(t){var d,m,l,f;if(this.logger.log("[AcpAdapter] Permission request received:",t),this.autoAllowPermissions){let p=t.options.find(h=>h.kind==="allow_once"||h.kind==="allow_always"||!h.kind&&h.name.toLowerCase().includes("allow"))||t.options[0];return this.logger.log("[AcpAdapter] Auto-allowing permission request:",p),Promise.resolve({outcome:{outcome:"selected",optionId:p.optionId}})}let n=crypto.randomUUID(),r=((d=t.toolCall)==null?void 0:d.toolCallId)||crypto.randomUUID(),i=t.sessionId,o=t.options.map(p=>{let h=p.kind==="reject_always"?"reject_once":p.kind,v=h||(p.name.toLowerCase().includes("allow")?"allow_once":"reject_once");return{optionId:p.optionId,name:p.name,kind:v}}),a=this.pendingPermissionQueue.length===0,s={requestId:n,options:o,isActive:a};this.pendingPermissionQueue.push({requestId:n,toolCallId:r,options:o});let u=t.toolCall;return(f=this.sessionUpdateCallback)==null||f.call(this,{type:"tool_call",sessionId:i,toolCallId:r,title:(m=u==null?void 0:u.title)!=null?m:void 0,status:(u==null?void 0:u.status)||"pending",kind:(l=u==null?void 0:u.kind)!=null?l:void 0,content:Xa.toToolCallContent(u==null?void 0:u.content),permissionRequest:s}),new Promise(p=>{this.pendingPermissionRequests.set(n,{resolve:p,toolCallId:r,options:o})})}cancelPendingPermissionRequests(){this.logger.log(`[AcpAdapter] Cancelling ${this.pendingPermissionRequests.size} pending permission requests`),this.pendingPermissionRequests.forEach(({resolve:t,toolCallId:n,options:r},i)=>{this.updateMessage(n,{type:"tool_call",toolCallId:n,status:"completed",permissionRequest:{requestId:i,options:r,isCancelled:!0,isActive:!1}}),t({outcome:{outcome:"cancelled"}})}),this.pendingPermissionRequests.clear(),this.pendingPermissionQueue=[]}readTextFile(t){return Promise.resolve({content:""})}writeTextFile(t){return Promise.resolve({})}createTerminal(t){var i;this.logger.log("[AcpAdapter] createTerminal called with params:",t);let n={...t,cwd:t.cwd||((i=this.currentConfig)==null?void 0:i.workingDirectory)||""};this.logger.log("[AcpAdapter] Using modified params:",n);let r=this.terminalManager.createTerminal(n);return Promise.resolve({terminalId:r})}terminalOutput(t){let n=this.terminalManager.getOutput(t.terminalId);if(!n)throw new Error(`Terminal ${t.terminalId} not found`);return Promise.resolve(n)}async waitForTerminalExit(t){return await this.terminalManager.waitForExit(t.terminalId)}killTerminal(t){if(!this.terminalManager.killTerminal(t.terminalId))throw new Error(`Terminal ${t.terminalId} not found`);return Promise.resolve({})}releaseTerminal(t){return this.terminalManager.releaseTerminal(t.terminalId)||this.logger.log(`[AcpAdapter] releaseTerminal: Terminal ${t.terminalId} not found (may have been already cleaned up)`),Promise.resolve({})}async listSessions(t,n){var r;if(!this.connection)throw new Error("ACP connection not initialized. Call initialize() first.");try{this.logger.log("[AcpAdapter] Listing sessions...");let i=await this.connection.unstable_listSessions({cwd:t!=null?t:null,cursor:n!=null?n:null});return this.logger.log(`[AcpAdapter] Found ${i.sessions.length} sessions`),{sessions:i.sessions.map(o=>{var a,s;return{sessionId:o.sessionId,cwd:o.cwd,title:(a=o.title)!=null?a:void 0,updatedAt:(s=o.updatedAt)!=null?s:void 0}}),nextCursor:(r=i.nextCursor)!=null?r:void 0}}catch(i){throw this.logger.error("[AcpAdapter] List Sessions Error:",i),i}}async loadSession(t,n){if(!this.connection)throw new Error("ACP connection not initialized. Call initialize() first.");try{this.logger.log(`[AcpAdapter] Loading session: ${t}...`);let r=await this.connection.loadSession({sessionId:t,cwd:n,mcpServers:[]});this.logger.log(`[AcpAdapter] Session loaded: ${t}`);let i;r.modes&&(i={availableModes:r.modes.availableModes.map(a=>{var s;return{id:a.id,name:a.name,description:(s=a.description)!=null?s:void 0}}),currentModeId:r.modes.currentModeId});let o;return r.models&&(o={availableModels:r.models.availableModels.map(a=>{var s;return{modelId:a.modelId,name:a.name,description:(s=a.description)!=null?s:void 0}}),currentModelId:r.models.currentModelId}),{sessionId:t,modes:i,models:o}}catch(r){throw this.logger.error("[AcpAdapter] Load Session Error:",r),r}}async resumeSession(t,n){if(!this.connection)throw new Error("ACP connection not initialized. Call initialize() first.");try{this.logger.log(`[AcpAdapter] Resuming session: ${t}...`);let r=await this.connection.unstable_resumeSession({sessionId:t,cwd:n,mcpServers:[]});this.logger.log(`[AcpAdapter] Session resumed: ${t}`);let i;r.modes&&(i={availableModes:r.modes.availableModes.map(a=>{var s;return{id:a.id,name:a.name,description:(s=a.description)!=null?s:void 0}}),currentModeId:r.modes.currentModeId});let o;return r.models&&(o={availableModels:r.models.availableModels.map(a=>{var s;return{modelId:a.modelId,name:a.name,description:(s=a.description)!=null?s:void 0}}),currentModelId:r.models.currentModelId}),{sessionId:t,modes:i,models:o}}catch(r){throw this.logger.error("[AcpAdapter] Resume Session Error:",r),r}}async forkSession(t,n){if(!this.connection)throw new Error("ACP connection not initialized. Call initialize() first.");try{this.logger.log(`[AcpAdapter] Forking session: ${t}...`);let r=await this.connection.unstable_forkSession({sessionId:t,cwd:n,mcpServers:[]}),i=r.sessionId;this.logger.log(`[AcpAdapter] Session forked: ${t} -> ${i}`);let o;r.modes&&(o={availableModes:r.modes.availableModes.map(s=>{var u;return{id:s.id,name:s.name,description:(u=s.description)!=null?u:void 0}}),currentModeId:r.modes.currentModeId});let a;return r.models&&(a={availableModels:r.models.availableModels.map(s=>{var u;return{modelId:s.modelId,name:s.name,description:(u=s.description)!=null?u:void 0}}),currentModelId:r.models.currentModelId}),{sessionId:i,modes:o,models:a}}catch(r){throw this.logger.error("[AcpAdapter] Fork Session Error:",r),r}}};var ue={claude:{id:"claude-code-acp",displayName:"Claude Code",apiKey:"",command:"",args:[],env:[]},codex:{id:"codex-acp",displayName:"Codex",apiKey:"",command:"",args:[],env:[]},gemini:{id:"gemini-cli",displayName:"Gemini CLI",apiKey:"",command:"",args:["--experimental-acp"],env:[]},customAgents:[],activeAgentId:"claude-code-acp",autoAllowPermissions:!1,autoMentionActiveNote:!0,debugMode:!1,nodePath:"",exportSettings:{defaultFolder:"Agent Client",filenameTemplate:"agent_client_{date}_{time}",autoExportOnNewChat:!1,autoExportOnCloseChat:!1,openFileAfterExport:!0,includeImages:!0,imageLocation:"obsidian",imageCustomFolder:"Agent Client"},windowsWslMode:!1,windowsWslDistribution:void 0,sendMessageShortcut:"enter",displaySettings:{autoCollapseDiffs:!1,diffCollapseThreshold:10,maxNoteLength:1e4,maxSelectionLength:1e4},savedSessions:[]},tu=class extends hr.Plugin{constructor(){super(...arguments);this._acpAdapter=null}async onload(){await this.loadSettings(),this.settingsStore=pT(this.settings,this),this.registerView(yl,r=>new pd(r,this)),this.addRibbonIcon("bot-message-square","Open agent client",r=>{this.activateView()}).addClass("agent-client-ribbon-icon"),this.addCommand({id:"open-chat-view",name:"Open agent chat",callback:()=>{this.activateView()}}),this.registerAgentCommands(),this.registerPermissionCommands(),this.addSettingTab(new hd(this.app,this)),this.registerEvent(this.app.workspace.on("quit",()=>{this._acpAdapter&&this._acpAdapter.disconnect().catch(r=>{console.warn("[AgentClient] Quit cleanup error:",r)})}))}onunload(){}getOrCreateAdapter(){return this._acpAdapter||(this._acpAdapter=new Sm(this)),this._acpAdapter}async activateView(){var o;let{workspace:n}=this.app,r=null,i=n.getLeavesOfType(yl);if(i.length>0?r=i[0]:(r=n.getRightLeaf(!1),r&&await r.setViewState({type:yl,active:!0})),r){await n.revealLeaf(r);let a=(o=r.view)==null?void 0:o.containerEl;a&&window.setTimeout(()=>{let s=a.querySelector("textarea.chat-input-textarea");s instanceof HTMLTextAreaElement&&s.focus()},0)}}getAvailableAgents(){return[{id:this.settings.claude.id,displayName:this.settings.claude.displayName||this.settings.claude.id},{id:this.settings.codex.id,displayName:this.settings.codex.displayName||this.settings.codex.id},{id:this.settings.gemini.id,displayName:this.settings.gemini.displayName||this.settings.gemini.id},...this.settings.customAgents.map(n=>({id:n.id,displayName:n.displayName||n.id}))]}async openChatWithAgent(n){this.settings.activeAgentId!==n&&await this.settingsStore.updateSettings({activeAgentId:n}),await this.activateView(),this.app.workspace.trigger("agent-client:new-chat-requested",n)}registerAgentCommands(){let n=this.getAvailableAgents();for(let r of n)this.addCommand({id:`open-chat-with-${r.id}`,name:`New chat with ${r.displayName}`,callback:async()=>{await this.openChatWithAgent(r.id)}})}registerPermissionCommands(){this.addCommand({id:"approve-active-permission",name:"Approve active permission",callback:async()=>{await this.activateView(),this.app.workspace.trigger("agent-client:approve-active-permission")}}),this.addCommand({id:"reject-active-permission",name:"Reject active permission",callback:async()=>{await this.activateView(),this.app.workspace.trigger("agent-client:reject-active-permission")}}),this.addCommand({id:"toggle-auto-mention",name:"Toggle auto-mention",callback:async()=>{await this.activateView(),this.app.workspace.trigger("agent-client:toggle-auto-mention")}}),this.addCommand({id:"cancel-current-message",name:"Cancel current message",callback:()=>{this.app.workspace.trigger("agent-client:cancel-message")}})}async loadSettings(){var y;let n=(y=await this.loadData())!=null?y:{},r=typeof n.claude=="object"&&n.claude!==null?n.claude:{},i=typeof n.codex=="object"&&n.codex!==null?n.codex:{},o=typeof n.gemini=="object"&&n.gemini!==null?n.gemini:{},a=hl(r.args),s=Hr(r.env),u=hl(i.args),d=Hr(i.env),m=hl(o.args),l=Hr(o.env),f=Array.isArray(n.customAgents)?X1(n.customAgents.map(g=>F1(typeof g=="object"&&g!==null?g:{}))):[],p=[ue.claude.id,ue.codex.id,ue.gemini.id,...f.map(g=>g.id)],h=typeof n.activeAgentId=="string"?n.activeAgentId.trim():"",v=p.find(g=>g.length>0)||ue.claude.id,x=p.includes(h)&&h.length>0?h:v;this.settings={claude:{id:ue.claude.id,displayName:typeof r.displayName=="string"&&r.displayName.trim().length>0?r.displayName.trim():ue.claude.displayName,apiKey:typeof r.apiKey=="string"?r.apiKey:ue.claude.apiKey,command:typeof r.command=="string"&&r.command.trim().length>0?r.command.trim():typeof n.claudeCodeAcpCommandPath=="string"&&n.claudeCodeAcpCommandPath.trim().length>0?n.claudeCodeAcpCommandPath.trim():ue.claude.command,args:a.length>0?a:[],env:s.length>0?s:[]},codex:{id:ue.codex.id,displayName:typeof i.displayName=="string"&&i.displayName.trim().length>0?i.displayName.trim():ue.codex.displayName,apiKey:typeof i.apiKey=="string"?i.apiKey:ue.codex.apiKey,command:typeof i.command=="string"&&i.command.trim().length>0?i.command.trim():ue.codex.command,args:u.length>0?u:[],env:d.length>0?d:[]},gemini:{id:ue.gemini.id,displayName:typeof o.displayName=="string"&&o.displayName.trim().length>0?o.displayName.trim():ue.gemini.displayName,apiKey:typeof o.apiKey=="string"?o.apiKey:ue.gemini.apiKey,command:typeof o.command=="string"&&o.command.trim().length>0?o.command.trim():typeof n.geminiCommandPath=="string"&&n.geminiCommandPath.trim().length>0?n.geminiCommandPath.trim():ue.gemini.command,args:m.length>0?m:ue.gemini.args,env:l.length>0?l:[]},customAgents:f,activeAgentId:x,autoAllowPermissions:typeof n.autoAllowPermissions=="boolean"?n.autoAllowPermissions:ue.autoAllowPermissions,autoMentionActiveNote:typeof n.autoMentionActiveNote=="boolean"?n.autoMentionActiveNote:ue.autoMentionActiveNote,debugMode:typeof n.debugMode=="boolean"?n.debugMode:ue.debugMode,nodePath:typeof n.nodePath=="string"?n.nodePath.trim():ue.nodePath,exportSettings:(()=>{let g=n.exportSettings;return g&&typeof g=="object"?{defaultFolder:typeof g.defaultFolder=="string"?g.defaultFolder:ue.exportSettings.defaultFolder,filenameTemplate:typeof g.filenameTemplate=="string"?g.filenameTemplate:ue.exportSettings.filenameTemplate,autoExportOnNewChat:typeof g.autoExportOnNewChat=="boolean"?g.autoExportOnNewChat:ue.exportSettings.autoExportOnNewChat,autoExportOnCloseChat:typeof g.autoExportOnCloseChat=="boolean"?g.autoExportOnCloseChat:ue.exportSettings.autoExportOnCloseChat,openFileAfterExport:typeof g.openFileAfterExport=="boolean"?g.openFileAfterExport:ue.exportSettings.openFileAfterExport,includeImages:typeof g.includeImages=="boolean"?g.includeImages:ue.exportSettings.includeImages,imageLocation:g.imageLocation==="obsidian"||g.imageLocation==="custom"||g.imageLocation==="base64"?g.imageLocation:ue.exportSettings.imageLocation,imageCustomFolder:typeof g.imageCustomFolder=="string"?g.imageCustomFolder:ue.exportSettings.imageCustomFolder}:ue.exportSettings})(),windowsWslMode:typeof n.windowsWslMode=="boolean"?n.windowsWslMode:ue.windowsWslMode,windowsWslDistribution:typeof n.windowsWslDistribution=="string"?n.windowsWslDistribution:ue.windowsWslDistribution,sendMessageShortcut:n.sendMessageShortcut==="enter"||n.sendMessageShortcut==="cmd-enter"?n.sendMessageShortcut:ue.sendMessageShortcut,displaySettings:(()=>{let g=n.displaySettings;return g&&typeof g=="object"?{autoCollapseDiffs:typeof g.autoCollapseDiffs=="boolean"?g.autoCollapseDiffs:ue.displaySettings.autoCollapseDiffs,diffCollapseThreshold:typeof g.diffCollapseThreshold=="number"&&g.diffCollapseThreshold>0?g.diffCollapseThreshold:ue.displaySettings.diffCollapseThreshold,maxNoteLength:typeof g.maxNoteLength=="number"&&g.maxNoteLength>=1?g.maxNoteLength:ue.displaySettings.maxNoteLength,maxSelectionLength:typeof g.maxSelectionLength=="number"&&g.maxSelectionLength>=1?g.maxSelectionLength:ue.displaySettings.maxSelectionLength}:ue.displaySettings})(),savedSessions:Array.isArray(n.savedSessions)?n.savedSessions:ue.savedSessions},this.ensureActiveAgentId()}async saveSettings(){await this.saveData(this.settings)}async saveSettingsAndNotify(n){this.settings=n,await this.saveData(this.settings),this.settingsStore.set(this.settings)}async fetchLatestStable(){let r=(await(0,hr.requestUrl)({url:"https://api.github.com/repos/RAIT-09/obsidian-agent-client/releases/latest"})).json;return r.tag_name?Jn.clean(r.tag_name):null}async fetchLatestPrerelease(){let i=(await(0,hr.requestUrl)({url:"https://api.github.com/repos/RAIT-09/obsidian-agent-client/releases"})).json.find(o=>o.prerelease);return i?Jn.clean(i.tag_name):null}async checkForUpdates(){let n=Jn.clean(this.manifest.version)||this.manifest.version;if(Jn.prerelease(n)!==null){let[i,o]=await Promise.all([this.fetchLatestStable(),this.fetchLatestPrerelease()]),a=i&&Jn.gt(i,n),s=o&&Jn.gt(o,n);if(a||s){let u=a?i:o;return new hr.Notice(`[Agent Client] Update available: v${u}`),!0}}else{let i=await this.fetchLatestStable();if(i&&Jn.gt(i,n))return new hr.Notice(`[Agent Client] Update available: v${i}`),!0}return!1}ensureActiveAgentId(){let n=this.collectAvailableAgentIds();if(n.length===0){this.settings.activeAgentId=ue.claude.id;return}n.includes(this.settings.activeAgentId)||(this.settings.activeAgentId=n[0])}collectAvailableAgentIds(){let n=new Set;n.add(this.settings.claude.id),n.add(this.settings.codex.id),n.add(this.settings.gemini.id);for(let r of this.settings.customAgents)r.id&&r.id.length>0&&n.add(r.id);return Array.from(n)}}; +`);for(let n of t){let r=n.trim();if(r.toLowerCase().startsWith("path")){let i=r.match(/Path\s+REG_(?:EXPAND_)?SZ\s+(.+)/i);if(i)return i[1].trim()}}return null}function ym(e){if(!b_.Platform.isWin)return e;let t=I2();if(!t)return e;let r=(e.PATH||"").split(";").filter(a=>a.length>0),i=t.split(";").filter(a=>a.length>0),o=[...r];for(let a of i)o.some(s=>s.toLowerCase()===a.toLowerCase())||o.push(a);return{...e,PATH:o.join(";")}}function Ja(e){let t=e.replace(/%/g,"%%").replace(/"/g,'""');return/[\s&()<>|^]/.test(e)?`"${t}"`:t}var bm=class{constructor(t){this.terminals=new Map;this.logger=new Le(t),this.plugin=t}createTerminal(t){var m,l,f;let n=crypto.randomUUID();if(!zi.Platform.isDesktopApp)throw new Error("Agent Client is only available on desktop");let r={...process.env};if(zi.Platform.isWin&&!this.plugin.settings.windowsWslMode&&(r=ym(r)),t.env)for(let p of t.env)r[p.name]=p.value;let i=t.command,o=t.args||[];if(zi.Platform.isWin&&this.plugin.settings.windowsWslMode){let p=this.plugin.settings.nodePath&&oa(this.plugin.settings.nodePath.trim())||void 0,h=md(i,o,t.cwd||process.cwd(),this.plugin.settings.windowsWslDistribution,p);i=h.command,o=h.args,this.logger.log(`[Terminal ${n}] Using WSL mode:`,this.plugin.settings.windowsWslDistribution||"default")}else if(zi.Platform.isMacOS||zi.Platform.isLinux){let p=zi.Platform.isMacOS?"/bin/zsh":"/bin/bash",h;o.length>0?h=[i,...o].map(v=>"'"+v.replace(/'/g,"'\\''")+"'").join(" "):h=i,i=p,o=["-l","-c",h]}else zi.Platform.isWin&&o.length>0&&(i=Ja(i),o=o.map(Ja));this.logger.log(`[Terminal ${n}] Creating terminal:`,{command:i,args:o,cwd:t.cwd});let a=zi.Platform.isWin&&!this.plugin.settings.windowsWslMode,s={cwd:t.cwd||void 0,env:r,stdio:["pipe","pipe","pipe"],shell:a},u=(0,CI.spawn)(i,o,s),d={id:n,process:u,output:"",exitStatus:null,outputByteLimit:(m=t.outputByteLimit)!=null?m:void 0,waitPromises:[]};return u.on("error",p=>{this.logger.log(`[Terminal ${n}] Process error:`,p.message);let h={exitCode:127,signal:null};d.exitStatus=h,d.waitPromises.forEach(v=>v(h)),d.waitPromises=[]}),(l=u.stdout)==null||l.on("data",p=>{let h=p.toString();this.logger.log(`[Terminal ${n}] stdout:`,h),this.appendOutput(d,h)}),(f=u.stderr)==null||f.on("data",p=>{let h=p.toString();this.logger.log(`[Terminal ${n}] stderr:`,h),this.appendOutput(d,h)}),u.on("exit",(p,h)=>{this.logger.log(`[Terminal ${n}] Process exited with code: ${p}, signal: ${h}`);let v={exitCode:p,signal:h};d.exitStatus=v,d.waitPromises.forEach(x=>x(v)),d.waitPromises=[]}),this.terminals.set(n,d),n}appendOutput(t,n){if(t.output+=n,t.outputByteLimit&&Buffer.byteLength(t.output,"utf8")>t.outputByteLimit){let r=Buffer.from(t.output,"utf8"),i=r.subarray(r.length-t.outputByteLimit);t.output=i.toString("utf8")}}getOutput(t){let n=this.terminals.get(t);return n?{output:n.output,truncated:n.outputByteLimit?Buffer.byteLength(n.output,"utf8")>=n.outputByteLimit:!1,exitStatus:n.exitStatus}:null}waitForExit(t){let n=this.terminals.get(t);return n?n.exitStatus?Promise.resolve(n.exitStatus):new Promise(r=>{n.waitPromises.push(r)}):Promise.reject(new Error(`Terminal ${t} not found`))}killTerminal(t){let n=this.terminals.get(t);return n?(n.exitStatus||n.process.kill("SIGTERM"),!0):!1}releaseTerminal(t){let n=this.terminals.get(t);return n?(this.logger.log(`[Terminal ${t}] Releasing terminal`),n.exitStatus||n.process.kill("SIGTERM"),n.cleanupTimeout=window.setTimeout(()=>{this.logger.log(`[Terminal ${t}] Cleaning up terminal after grace period`),this.terminals.delete(t)},3e4),!0):!1}killAllTerminals(){this.logger.log(`Killing ${this.terminals.size} running terminals...`),this.terminals.forEach((t,n)=>{t.cleanupTimeout&&window.clearTimeout(t.cleanupTimeout),t.exitStatus||(this.logger.log(`Killing terminal ${n}`),this.killTerminal(n))}),this.terminals.clear()}};var Sm=class{constructor(t){this.plugin=t;this.connection=null;this.agentProcess=null;this.sessionUpdateCallback=null;this.errorCallback=null;this.currentConfig=null;this.isInitializedFlag=!1;this.currentAgentId=null;this.autoAllowPermissions=!1;this.currentMessageId=null;this.pendingPermissionRequests=new Map;this.pendingPermissionQueue=[];this.logger=new Le(t),this.updateMessage=()=>{},this.terminalManager=new bm(t)}setUpdateMessageCallback(t){this.updateMessage=t}async initialize(t){var v,x,y,g,b,S,$,R,A,T,z,E,F,P,V,L,C,M,K,ce,be;if(this.logger.log("[AcpAdapter] Starting initialization with config:",t),this.logger.log(`[AcpAdapter] Current state - process: ${!!this.agentProcess}, PID: ${(v=this.agentProcess)==null?void 0:v.pid}`),this.agentProcess&&(this.logger.log(`[AcpAdapter] Killing existing process (PID: ${this.agentProcess.pid})`),this.agentProcess.kill(),this.agentProcess=null),this.connection&&(this.logger.log("[AcpAdapter] Cleaning up existing connection"),this.connection=null),this.currentConfig=t,this.autoAllowPermissions=this.plugin.settings.autoAllowPermissions,!t.command||t.command.trim().length===0)throw new Error(`Command not configured for agent "${t.displayName}" (${t.id}). Please configure the agent command in settings.`);let n=t.command.trim(),r=t.args.length>0?[...t.args]:[];this.logger.log(`[AcpAdapter] Active agent: ${t.displayName} (${t.id})`),this.logger.log("[AcpAdapter] Command:",n),this.logger.log("[AcpAdapter] Args:",r.length>0?r.join(" "):"(none)");let i={...process.env,...t.env||{}};if(Nn.Platform.isWin&&!this.plugin.settings.windowsWslMode&&(i=ym(i)),this.plugin.settings.nodePath&&this.plugin.settings.nodePath.trim().length>0){let q=oa(this.plugin.settings.nodePath.trim());if(q){let W=Nn.Platform.isWin?";":":";i.PATH=i.PATH?`${q}${W}${i.PATH}`:q}}this.logger.log("[AcpAdapter] Starting agent process in directory:",t.workingDirectory);let o=n,a=r;if(Nn.Platform.isWin&&this.plugin.settings.windowsWslMode){let q=this.plugin.settings.nodePath&&oa(this.plugin.settings.nodePath.trim())||void 0,W=md(n,r,t.workingDirectory,this.plugin.settings.windowsWslDistribution,q);o=W.command,a=W.args,this.logger.log("[AcpAdapter] Using WSL mode:",this.plugin.settings.windowsWslDistribution||"default","with command:",o,a)}else if(Nn.Platform.isMacOS||Nn.Platform.isLinux){let q=Nn.Platform.isMacOS?"/bin/zsh":"/bin/bash",W=[n,...r].map(Oe=>"'"+Oe.replace(/'/g,"'\\''")+"'").join(" "),Ye=W;if(this.plugin.settings.nodePath&&this.plugin.settings.nodePath.trim().length>0){let Oe=oa(this.plugin.settings.nodePath.trim());Oe&&(Ye=`export PATH='${Oe.replace(/'/g,"'\\''")}':"$PATH"; ${W}`)}o=q,a=["-l","-c",Ye],this.logger.log("[AcpAdapter] Using login shell:",q,"with command:",Ye)}else Nn.Platform.isWin&&(o=Ja(n),a=r.map(Ja),this.logger.log("[AcpAdapter] Using Windows shell with command:",o,a));let s=Nn.Platform.isWin&&!this.plugin.settings.windowsWslMode,u=(0,II.spawn)(o,a,{stdio:["pipe","pipe","pipe"],env:i,cwd:t.workingDirectory,shell:s});this.agentProcess=u;let d=`${t.displayName} (${t.id})`;if(u.on("spawn",()=>{this.logger.log(`[AcpAdapter] ${d} process spawned successfully, PID:`,u.pid)}),u.on("error",q=>{var Ye;this.logger.error(`[AcpAdapter] ${d} process error:`,q);let W={id:crypto.randomUUID(),category:"connection",severity:"error",occurredAt:new Date,agentId:t.id,originalError:q,...this.getErrorInfo(q,n,d)};(Ye=this.errorCallback)==null||Ye.call(this,W)}),u.on("exit",(q,W)=>{var Ye;if(this.logger.log(`[AcpAdapter] ${d} process exited with code:`,q,"signal:",W),q===127){this.logger.error(`[AcpAdapter] Command not found: ${n}`);let Oe={id:crypto.randomUUID(),category:"configuration",severity:"error",title:"Command Not Found",message:`The command "${n}" could not be found. Please check the path configuration for ${d}.`,suggestion:this.getCommandNotFoundSuggestion(n),occurredAt:new Date,agentId:t.id,code:q};(Ye=this.errorCallback)==null||Ye.call(this,Oe)}}),u.on("close",(q,W)=>{this.logger.log(`[AcpAdapter] ${d} process closed with code:`,q,"signal:",W)}),(x=u.stderr)==null||x.setEncoding("utf8"),(y=u.stderr)==null||y.on("data",q=>{this.logger.log(`[AcpAdapter] ${d} stderr:`,q)}),!u.stdin||!u.stdout)throw new Error("Agent process stdin/stdout not available");let m=u.stdin,l=u.stdout,f=new WritableStream({write(q){m.write(q)},close(){m.end()}}),p=new ReadableStream({start(q){l.on("data",W=>{q.enqueue(W)}),l.on("end",()=>{q.close()})}});this.logger.log("[AcpAdapter] Using working directory:",t.workingDirectory);let h=_I(f,p);this.connection=new um(()=>this,h);try{this.logger.log("[AcpAdapter] Starting ACP initialization...");let q=await this.connection.initialize({protocolVersion:rI,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!0},clientInfo:{name:"obsidian-agent-client",title:"Agent Client for Obsidian",version:this.plugin.manifest.version}});this.logger.log(`[AcpAdapter] \u2705 Connected to agent (protocol v${q.protocolVersion})`),this.logger.log("[AcpAdapter] Auth methods:",q.authMethods),this.logger.log("[AcpAdapter] Agent capabilities:",q.agentCapabilities),this.isInitializedFlag=!0,this.currentAgentId=t.id;let W=(g=q.agentCapabilities)==null?void 0:g.promptCapabilities,Ye=(b=q.agentCapabilities)==null?void 0:b.mcpCapabilities,Oe=(S=q.agentCapabilities)==null?void 0:S.sessionCapabilities;return{protocolVersion:q.protocolVersion,authMethods:q.authMethods||[],promptCapabilities:{image:($=W==null?void 0:W.image)!=null?$:!1,audio:(R=W==null?void 0:W.audio)!=null?R:!1,embeddedContext:(A=W==null?void 0:W.embeddedContext)!=null?A:!1},agentCapabilities:{loadSession:(z=(T=q.agentCapabilities)==null?void 0:T.loadSession)!=null?z:!1,sessionCapabilities:Oe?{resume:(E=Oe.resume)!=null?E:void 0,fork:(F=Oe.fork)!=null?F:void 0,list:(P=Oe.list)!=null?P:void 0}:void 0,mcpCapabilities:Ye?{http:(V=Ye.http)!=null?V:!1,sse:(L=Ye.sse)!=null?L:!1}:void 0,promptCapabilities:{image:(C=W==null?void 0:W.image)!=null?C:!1,audio:(M=W==null?void 0:W.audio)!=null?M:!1,embeddedContext:(K=W==null?void 0:W.embeddedContext)!=null?K:!1}},agentInfo:q.agentInfo?{name:q.agentInfo.name,title:(ce=q.agentInfo.title)!=null?ce:void 0,version:(be=q.agentInfo.version)!=null?be:void 0}:void 0}}catch(q){throw this.logger.error("[AcpAdapter] Initialization Error:",q),this.isInitializedFlag=!1,this.currentAgentId=null,q}}async newSession(t){if(!this.connection)throw new Error("Connection not initialized. Call initialize() first.");try{this.logger.log("[AcpAdapter] Creating new session...");let n=t;Nn.Platform.isWin&&this.plugin.settings.windowsWslMode&&(n=xi(t)),this.logger.log("[AcpAdapter] Using working directory:",n);let r=await this.connection.newSession({cwd:n,mcpServers:[]});this.logger.log(`[AcpAdapter] \u{1F4DD} Created session: ${r.sessionId}`),this.logger.log("[AcpAdapter] NewSessionResponse:",JSON.stringify(r,null,2));let i;r.modes&&(i={availableModes:r.modes.availableModes.map(a=>{var s;return{id:a.id,name:a.name,description:(s=a.description)!=null?s:void 0}}),currentModeId:r.modes.currentModeId},this.logger.log(`[AcpAdapter] Session modes: ${i.availableModes.map(a=>a.id).join(", ")} (current: ${i.currentModeId})`));let o;return r.models&&(o={availableModels:r.models.availableModels.map(a=>{var s;return{modelId:a.modelId,name:a.name,description:(s=a.description)!=null?s:void 0}}),currentModelId:r.models.currentModelId},this.logger.log(`[AcpAdapter] Session models: ${o.availableModels.map(a=>a.modelId).join(", ")} (current: ${o.currentModelId})`)),{sessionId:r.sessionId,modes:i,models:o}}catch(n){throw this.logger.error("[AcpAdapter] New Session Error:",n),n}}async authenticate(t){if(!this.connection)throw new Error("Connection not initialized. Call initialize() first.");try{return await this.connection.authenticate({methodId:t}),this.logger.log("[AcpAdapter] \u2705 authenticate ok:",t),!0}catch(n){return this.logger.error("[AcpAdapter] Authentication Error:",n),!1}}async sendPrompt(t,n){if(!this.connection)throw new Error("Connection not initialized. Call initialize() first.");this.resetCurrentMessage();try{let r=n.map(o=>Xa.toAcpContentBlock(o));this.logger.log(`[AcpAdapter] Sending prompt with ${n.length} content blocks`);let i=await this.connection.prompt({sessionId:t,prompt:r});this.logger.log(`[AcpAdapter] Agent completed with: ${i.stopReason}`)}catch(r){this.logger.error("[AcpAdapter] Prompt Error:",r);let i=r;if(i&&typeof i=="object"&&"code"in i&&i.code===-32603&&"data"in i){let o=i.data;if(o&&typeof o=="object"&&"details"in o&&typeof o.details=="string"){if(o.details.includes("empty response text")){this.logger.log("[AcpAdapter] Empty response text error - ignoring");return}if(o.details.includes("user aborted")){this.logger.log("[AcpAdapter] User aborted request - ignoring");return}}}throw r}}async cancel(t){if(!this.connection){this.logger.warn("[AcpAdapter] Cannot cancel: no connection");return}try{this.logger.log("[AcpAdapter] Sending session/cancel notification..."),await this.connection.cancel({sessionId:t}),this.logger.log("[AcpAdapter] Cancellation request sent successfully"),this.cancelAllOperations()}catch(n){this.logger.error("[AcpAdapter] Failed to send cancellation:",n),this.cancelAllOperations()}}disconnect(){return this.logger.log("[AcpAdapter] Disconnecting..."),this.cancelAllOperations(),this.agentProcess&&(this.logger.log(`[AcpAdapter] Killing agent process (PID: ${this.agentProcess.pid})`),this.agentProcess.kill(),this.agentProcess=null),this.connection=null,this.currentConfig=null,this.isInitializedFlag=!1,this.currentAgentId=null,this.logger.log("[AcpAdapter] Disconnected"),Promise.resolve()}isInitialized(){return this.isInitializedFlag&&this.connection!==null&&this.agentProcess!==null}getCurrentAgentId(){return this.currentAgentId}async setSessionMode(t,n){if(!this.connection)throw new Error("Connection not initialized. Call initialize() first.");this.logger.log(`[AcpAdapter] Setting session mode to: ${n} for session: ${t}`);try{await this.connection.setSessionMode({sessionId:t,modeId:n}),this.logger.log(`[AcpAdapter] Session mode set to: ${n}`)}catch(r){throw this.logger.error("[AcpAdapter] Failed to set session mode:",r),r}}async setSessionModel(t,n){if(!this.connection)throw new Error("Connection not initialized. Call initialize() first.");this.logger.log(`[AcpAdapter] Setting session model to: ${n} for session: ${t}`);try{await this.connection.unstable_setSessionModel({sessionId:t,modelId:n}),this.logger.log(`[AcpAdapter] Session model set to: ${n}`)}catch(r){throw this.logger.error("[AcpAdapter] Failed to set session model:",r),r}}onSessionUpdate(t){this.sessionUpdateCallback=t}onError(t){this.errorCallback=t}respondToPermission(t,n){if(!this.connection)throw new Error("ACP connection not initialized. Call initialize() first.");return this.logger.log("[AcpAdapter] Responding to permission request:",t,"with option:",n),this.handlePermissionResponse(t,n),Promise.resolve()}getErrorInfo(t,n,r){return t.code==="ENOENT"?{title:"Command Not Found",message:`The command "${n}" could not be found. Please check the path configuration for ${r}.`,suggestion:this.getCommandNotFoundSuggestion(n)}:{title:"Agent Startup Error",message:`Failed to start ${r}: ${t.message}`,suggestion:"Please check the agent configuration in settings."}}getCommandNotFoundSuggestion(t){var r;let n=((r=t.split("/").pop())==null?void 0:r.split("\\").pop())||"command";return Nn.Platform.isWin?`1. Verify the agent path: Use "where ${n}" in Command Prompt to find the correct path. 2. If the agent requires Node.js, also check that Node.js path is correctly set in General Settings (use "where node" to find it).`:`1. Verify the agent path: Use "which ${n}" in Terminal to find the correct path. 2. If the agent requires Node.js, also check that Node.js path is correctly set in General Settings (use "which node" to find it).`}sessionUpdate(t){var i,o,a,s,u,d,m,l,f,p;let n=t.update,r=t.sessionId;switch(this.logger.log("[AcpAdapter] sessionUpdate:",{sessionId:r,update:n}),n.sessionUpdate){case"agent_message_chunk":n.content.type==="text"&&((i=this.sessionUpdateCallback)==null||i.call(this,{type:"agent_message_chunk",sessionId:r,text:n.content.text}));break;case"agent_thought_chunk":n.content.type==="text"&&((o=this.sessionUpdateCallback)==null||o.call(this,{type:"agent_thought_chunk",sessionId:r,text:n.content.text}));break;case"user_message_chunk":n.content.type==="text"&&((a=this.sessionUpdateCallback)==null||a.call(this,{type:"user_message_chunk",sessionId:r,text:n.content.text}));break;case"tool_call":case"tool_call_update":{(m=this.sessionUpdateCallback)==null||m.call(this,{type:n.sessionUpdate,sessionId:r,toolCallId:n.toolCallId,title:(s=n.title)!=null?s:void 0,status:n.status||"pending",kind:(u=n.kind)!=null?u:void 0,content:Xa.toToolCallContent(n.content),locations:(d=n.locations)!=null?d:void 0});break}case"plan":(l=this.sessionUpdateCallback)==null||l.call(this,{type:"plan",sessionId:r,entries:n.entries});break;case"available_commands_update":{this.logger.log("[AcpAdapter] available_commands_update, commands:",n.availableCommands);let h=(n.availableCommands||[]).map(v=>{var x,y;return{name:v.name,description:v.description,hint:(y=(x=v.input)==null?void 0:x.hint)!=null?y:null}});(f=this.sessionUpdateCallback)==null||f.call(this,{type:"available_commands_update",sessionId:r,commands:h});break}case"current_mode_update":{this.logger.log(`[AcpAdapter] current_mode_update: ${n.currentModeId}`),(p=this.sessionUpdateCallback)==null||p.call(this,{type:"current_mode_update",sessionId:r,currentModeId:n.currentModeId});break}}return Promise.resolve()}resetCurrentMessage(){this.currentMessageId=null}handlePermissionResponse(t,n){let r=this.pendingPermissionRequests.get(t);if(!r)return;let{resolve:i,toolCallId:o,options:a}=r;this.updateMessage(o,{type:"tool_call",toolCallId:o,permissionRequest:{requestId:t,options:a,selectedOptionId:n,isActive:!1}}),i({outcome:{outcome:"selected",optionId:n}}),this.pendingPermissionRequests.delete(t),this.pendingPermissionQueue=this.pendingPermissionQueue.filter(s=>s.requestId!==t),this.activateNextPermission()}cancelAllOperations(){this.cancelPendingPermissionRequests(),this.terminalManager.killAllTerminals()}activateNextPermission(){if(this.pendingPermissionQueue.length===0)return;let t=this.pendingPermissionQueue[0],n=this.pendingPermissionRequests.get(t.requestId);n&&this.updateMessage(t.toolCallId,{type:"tool_call",toolCallId:t.toolCallId,permissionRequest:{requestId:t.requestId,options:n.options,isActive:!0}})}async requestPermission(t){var d,m,l,f;if(this.logger.log("[AcpAdapter] Permission request received:",t),this.autoAllowPermissions){let p=t.options.find(h=>h.kind==="allow_once"||h.kind==="allow_always"||!h.kind&&h.name.toLowerCase().includes("allow"))||t.options[0];return this.logger.log("[AcpAdapter] Auto-allowing permission request:",p),Promise.resolve({outcome:{outcome:"selected",optionId:p.optionId}})}let n=crypto.randomUUID(),r=((d=t.toolCall)==null?void 0:d.toolCallId)||crypto.randomUUID(),i=t.sessionId,o=t.options.map(p=>{let h=p.kind==="reject_always"?"reject_once":p.kind,v=h||(p.name.toLowerCase().includes("allow")?"allow_once":"reject_once");return{optionId:p.optionId,name:p.name,kind:v}}),a=this.pendingPermissionQueue.length===0,s={requestId:n,options:o,isActive:a};this.pendingPermissionQueue.push({requestId:n,toolCallId:r,options:o});let u=t.toolCall;return(f=this.sessionUpdateCallback)==null||f.call(this,{type:"tool_call",sessionId:i,toolCallId:r,title:(m=u==null?void 0:u.title)!=null?m:void 0,status:(u==null?void 0:u.status)||"pending",kind:(l=u==null?void 0:u.kind)!=null?l:void 0,content:Xa.toToolCallContent(u==null?void 0:u.content),permissionRequest:s}),new Promise(p=>{this.pendingPermissionRequests.set(n,{resolve:p,toolCallId:r,options:o})})}cancelPendingPermissionRequests(){this.logger.log(`[AcpAdapter] Cancelling ${this.pendingPermissionRequests.size} pending permission requests`),this.pendingPermissionRequests.forEach(({resolve:t,toolCallId:n,options:r},i)=>{this.updateMessage(n,{type:"tool_call",toolCallId:n,status:"completed",permissionRequest:{requestId:i,options:r,isCancelled:!0,isActive:!1}}),t({outcome:{outcome:"cancelled"}})}),this.pendingPermissionRequests.clear(),this.pendingPermissionQueue=[]}readTextFile(t){return Promise.resolve({content:""})}writeTextFile(t){return Promise.resolve({})}createTerminal(t){var i;this.logger.log("[AcpAdapter] createTerminal called with params:",t);let n={...t,cwd:t.cwd||((i=this.currentConfig)==null?void 0:i.workingDirectory)||""};this.logger.log("[AcpAdapter] Using modified params:",n);let r=this.terminalManager.createTerminal(n);return Promise.resolve({terminalId:r})}terminalOutput(t){let n=this.terminalManager.getOutput(t.terminalId);if(!n)throw new Error(`Terminal ${t.terminalId} not found`);return Promise.resolve(n)}async waitForTerminalExit(t){return await this.terminalManager.waitForExit(t.terminalId)}killTerminal(t){if(!this.terminalManager.killTerminal(t.terminalId))throw new Error(`Terminal ${t.terminalId} not found`);return Promise.resolve({})}releaseTerminal(t){return this.terminalManager.releaseTerminal(t.terminalId)||this.logger.log(`[AcpAdapter] releaseTerminal: Terminal ${t.terminalId} not found (may have been already cleaned up)`),Promise.resolve({})}async listSessions(t,n){var r;if(!this.connection)throw new Error("ACP connection not initialized. Call initialize() first.");try{this.logger.log("[AcpAdapter] Listing sessions...");let i=await this.connection.unstable_listSessions({cwd:t!=null?t:null,cursor:n!=null?n:null});return this.logger.log(`[AcpAdapter] Found ${i.sessions.length} sessions`),{sessions:i.sessions.map(o=>{var a,s;return{sessionId:o.sessionId,cwd:o.cwd,title:(a=o.title)!=null?a:void 0,updatedAt:(s=o.updatedAt)!=null?s:void 0}}),nextCursor:(r=i.nextCursor)!=null?r:void 0}}catch(i){throw this.logger.error("[AcpAdapter] List Sessions Error:",i),i}}async loadSession(t,n){if(!this.connection)throw new Error("ACP connection not initialized. Call initialize() first.");try{this.logger.log(`[AcpAdapter] Loading session: ${t}...`);let r=await this.connection.loadSession({sessionId:t,cwd:n,mcpServers:[]});this.logger.log(`[AcpAdapter] Session loaded: ${t}`);let i;r.modes&&(i={availableModes:r.modes.availableModes.map(a=>{var s;return{id:a.id,name:a.name,description:(s=a.description)!=null?s:void 0}}),currentModeId:r.modes.currentModeId});let o;return r.models&&(o={availableModels:r.models.availableModels.map(a=>{var s;return{modelId:a.modelId,name:a.name,description:(s=a.description)!=null?s:void 0}}),currentModelId:r.models.currentModelId}),{sessionId:t,modes:i,models:o}}catch(r){throw this.logger.error("[AcpAdapter] Load Session Error:",r),r}}async resumeSession(t,n){if(!this.connection)throw new Error("ACP connection not initialized. Call initialize() first.");try{this.logger.log(`[AcpAdapter] Resuming session: ${t}...`);let r=await this.connection.unstable_resumeSession({sessionId:t,cwd:n,mcpServers:[]});this.logger.log(`[AcpAdapter] Session resumed: ${t}`);let i;r.modes&&(i={availableModes:r.modes.availableModes.map(a=>{var s;return{id:a.id,name:a.name,description:(s=a.description)!=null?s:void 0}}),currentModeId:r.modes.currentModeId});let o;return r.models&&(o={availableModels:r.models.availableModels.map(a=>{var s;return{modelId:a.modelId,name:a.name,description:(s=a.description)!=null?s:void 0}}),currentModelId:r.models.currentModelId}),{sessionId:t,modes:i,models:o}}catch(r){throw this.logger.error("[AcpAdapter] Resume Session Error:",r),r}}async forkSession(t,n){if(!this.connection)throw new Error("ACP connection not initialized. Call initialize() first.");try{this.logger.log(`[AcpAdapter] Forking session: ${t}...`);let r=await this.connection.unstable_forkSession({sessionId:t,cwd:n,mcpServers:[]}),i=r.sessionId;this.logger.log(`[AcpAdapter] Session forked: ${t} -> ${i}`);let o;r.modes&&(o={availableModes:r.modes.availableModes.map(s=>{var u;return{id:s.id,name:s.name,description:(u=s.description)!=null?u:void 0}}),currentModeId:r.modes.currentModeId});let a;return r.models&&(a={availableModels:r.models.availableModels.map(s=>{var u;return{modelId:s.modelId,name:s.name,description:(u=s.description)!=null?u:void 0}}),currentModelId:r.models.currentModelId}),{sessionId:i,modes:o,models:a}}catch(r){throw this.logger.error("[AcpAdapter] Fork Session Error:",r),r}}};var ue={claude:{id:"claude-code-acp",displayName:"Claude Code",apiKey:"",command:"",args:[],env:[]},codex:{id:"codex-acp",displayName:"Codex",apiKey:"",command:"",args:[],env:[]},gemini:{id:"gemini-cli",displayName:"Gemini CLI",apiKey:"",command:"",args:["--experimental-acp"],env:[]},customAgents:[],activeAgentId:"claude-code-acp",autoAllowPermissions:!1,autoMentionActiveNote:!0,debugMode:!1,nodePath:"",exportSettings:{defaultFolder:"Agent Client",filenameTemplate:"agent_client_{date}_{time}",autoExportOnNewChat:!1,autoExportOnCloseChat:!1,openFileAfterExport:!0,includeImages:!0,imageLocation:"obsidian",imageCustomFolder:"Agent Client"},windowsWslMode:!1,windowsWslDistribution:void 0,sendMessageShortcut:"enter",displaySettings:{autoCollapseDiffs:!1,diffCollapseThreshold:10,maxNoteLength:1e4,maxSelectionLength:1e4},savedSessions:[]},tu=class extends hr.Plugin{constructor(){super(...arguments);this._acpAdapter=null}async onload(){await this.loadSettings(),this.settingsStore=pT(this.settings,this),this.registerView(yl,r=>new pd(r,this)),this.addRibbonIcon("bot-message-square","Open agent client",r=>{this.activateView()}).addClass("agent-client-ribbon-icon"),this.addCommand({id:"open-chat-view",name:"Open agent chat",callback:()=>{this.activateView()}}),this.registerAgentCommands(),this.registerPermissionCommands(),this.addSettingTab(new hd(this.app,this)),this.registerEvent(this.app.workspace.on("quit",()=>{this._acpAdapter&&this._acpAdapter.disconnect().catch(r=>{console.warn("[AgentClient] Quit cleanup error:",r)})}))}onunload(){}getOrCreateAdapter(){return this._acpAdapter||(this._acpAdapter=new Sm(this)),this._acpAdapter}async activateView(){var o;let{workspace:n}=this.app,r=null,i=n.getLeavesOfType(yl);if(i.length>0?r=i[0]:(r=n.getRightLeaf(!1),r&&await r.setViewState({type:yl,active:!0})),r){await n.revealLeaf(r);let a=(o=r.view)==null?void 0:o.containerEl;a&&window.setTimeout(()=>{let s=a.querySelector("textarea.agent-client-chat-input-textarea");s instanceof HTMLTextAreaElement&&s.focus()},0)}}getAvailableAgents(){return[{id:this.settings.claude.id,displayName:this.settings.claude.displayName||this.settings.claude.id},{id:this.settings.codex.id,displayName:this.settings.codex.displayName||this.settings.codex.id},{id:this.settings.gemini.id,displayName:this.settings.gemini.displayName||this.settings.gemini.id},...this.settings.customAgents.map(n=>({id:n.id,displayName:n.displayName||n.id}))]}async openChatWithAgent(n){this.settings.activeAgentId!==n&&await this.settingsStore.updateSettings({activeAgentId:n}),await this.activateView(),this.app.workspace.trigger("agent-client:new-chat-requested",n)}registerAgentCommands(){let n=this.getAvailableAgents();for(let r of n)this.addCommand({id:`open-chat-with-${r.id}`,name:`New chat with ${r.displayName}`,callback:async()=>{await this.openChatWithAgent(r.id)}})}registerPermissionCommands(){this.addCommand({id:"approve-active-permission",name:"Approve active permission",callback:async()=>{await this.activateView(),this.app.workspace.trigger("agent-client:approve-active-permission")}}),this.addCommand({id:"reject-active-permission",name:"Reject active permission",callback:async()=>{await this.activateView(),this.app.workspace.trigger("agent-client:reject-active-permission")}}),this.addCommand({id:"toggle-auto-mention",name:"Toggle auto-mention",callback:async()=>{await this.activateView(),this.app.workspace.trigger("agent-client:toggle-auto-mention")}}),this.addCommand({id:"cancel-current-message",name:"Cancel current message",callback:()=>{this.app.workspace.trigger("agent-client:cancel-message")}})}async loadSettings(){var y;let n=(y=await this.loadData())!=null?y:{},r=typeof n.claude=="object"&&n.claude!==null?n.claude:{},i=typeof n.codex=="object"&&n.codex!==null?n.codex:{},o=typeof n.gemini=="object"&&n.gemini!==null?n.gemini:{},a=hl(r.args),s=Hr(r.env),u=hl(i.args),d=Hr(i.env),m=hl(o.args),l=Hr(o.env),f=Array.isArray(n.customAgents)?X1(n.customAgents.map(g=>F1(typeof g=="object"&&g!==null?g:{}))):[],p=[ue.claude.id,ue.codex.id,ue.gemini.id,...f.map(g=>g.id)],h=typeof n.activeAgentId=="string"?n.activeAgentId.trim():"",v=p.find(g=>g.length>0)||ue.claude.id,x=p.includes(h)&&h.length>0?h:v;this.settings={claude:{id:ue.claude.id,displayName:typeof r.displayName=="string"&&r.displayName.trim().length>0?r.displayName.trim():ue.claude.displayName,apiKey:typeof r.apiKey=="string"?r.apiKey:ue.claude.apiKey,command:typeof r.command=="string"&&r.command.trim().length>0?r.command.trim():typeof n.claudeCodeAcpCommandPath=="string"&&n.claudeCodeAcpCommandPath.trim().length>0?n.claudeCodeAcpCommandPath.trim():ue.claude.command,args:a.length>0?a:[],env:s.length>0?s:[]},codex:{id:ue.codex.id,displayName:typeof i.displayName=="string"&&i.displayName.trim().length>0?i.displayName.trim():ue.codex.displayName,apiKey:typeof i.apiKey=="string"?i.apiKey:ue.codex.apiKey,command:typeof i.command=="string"&&i.command.trim().length>0?i.command.trim():ue.codex.command,args:u.length>0?u:[],env:d.length>0?d:[]},gemini:{id:ue.gemini.id,displayName:typeof o.displayName=="string"&&o.displayName.trim().length>0?o.displayName.trim():ue.gemini.displayName,apiKey:typeof o.apiKey=="string"?o.apiKey:ue.gemini.apiKey,command:typeof o.command=="string"&&o.command.trim().length>0?o.command.trim():typeof n.geminiCommandPath=="string"&&n.geminiCommandPath.trim().length>0?n.geminiCommandPath.trim():ue.gemini.command,args:m.length>0?m:ue.gemini.args,env:l.length>0?l:[]},customAgents:f,activeAgentId:x,autoAllowPermissions:typeof n.autoAllowPermissions=="boolean"?n.autoAllowPermissions:ue.autoAllowPermissions,autoMentionActiveNote:typeof n.autoMentionActiveNote=="boolean"?n.autoMentionActiveNote:ue.autoMentionActiveNote,debugMode:typeof n.debugMode=="boolean"?n.debugMode:ue.debugMode,nodePath:typeof n.nodePath=="string"?n.nodePath.trim():ue.nodePath,exportSettings:(()=>{let g=n.exportSettings;return g&&typeof g=="object"?{defaultFolder:typeof g.defaultFolder=="string"?g.defaultFolder:ue.exportSettings.defaultFolder,filenameTemplate:typeof g.filenameTemplate=="string"?g.filenameTemplate:ue.exportSettings.filenameTemplate,autoExportOnNewChat:typeof g.autoExportOnNewChat=="boolean"?g.autoExportOnNewChat:ue.exportSettings.autoExportOnNewChat,autoExportOnCloseChat:typeof g.autoExportOnCloseChat=="boolean"?g.autoExportOnCloseChat:ue.exportSettings.autoExportOnCloseChat,openFileAfterExport:typeof g.openFileAfterExport=="boolean"?g.openFileAfterExport:ue.exportSettings.openFileAfterExport,includeImages:typeof g.includeImages=="boolean"?g.includeImages:ue.exportSettings.includeImages,imageLocation:g.imageLocation==="obsidian"||g.imageLocation==="custom"||g.imageLocation==="base64"?g.imageLocation:ue.exportSettings.imageLocation,imageCustomFolder:typeof g.imageCustomFolder=="string"?g.imageCustomFolder:ue.exportSettings.imageCustomFolder}:ue.exportSettings})(),windowsWslMode:typeof n.windowsWslMode=="boolean"?n.windowsWslMode:ue.windowsWslMode,windowsWslDistribution:typeof n.windowsWslDistribution=="string"?n.windowsWslDistribution:ue.windowsWslDistribution,sendMessageShortcut:n.sendMessageShortcut==="enter"||n.sendMessageShortcut==="cmd-enter"?n.sendMessageShortcut:ue.sendMessageShortcut,displaySettings:(()=>{let g=n.displaySettings;return g&&typeof g=="object"?{autoCollapseDiffs:typeof g.autoCollapseDiffs=="boolean"?g.autoCollapseDiffs:ue.displaySettings.autoCollapseDiffs,diffCollapseThreshold:typeof g.diffCollapseThreshold=="number"&&g.diffCollapseThreshold>0?g.diffCollapseThreshold:ue.displaySettings.diffCollapseThreshold,maxNoteLength:typeof g.maxNoteLength=="number"&&g.maxNoteLength>=1?g.maxNoteLength:ue.displaySettings.maxNoteLength,maxSelectionLength:typeof g.maxSelectionLength=="number"&&g.maxSelectionLength>=1?g.maxSelectionLength:ue.displaySettings.maxSelectionLength}:ue.displaySettings})(),savedSessions:Array.isArray(n.savedSessions)?n.savedSessions:ue.savedSessions},this.ensureActiveAgentId()}async saveSettings(){await this.saveData(this.settings)}async saveSettingsAndNotify(n){this.settings=n,await this.saveData(this.settings),this.settingsStore.set(this.settings)}async fetchLatestStable(){let r=(await(0,hr.requestUrl)({url:"https://api.github.com/repos/RAIT-09/obsidian-agent-client/releases/latest"})).json;return r.tag_name?Jn.clean(r.tag_name):null}async fetchLatestPrerelease(){let i=(await(0,hr.requestUrl)({url:"https://api.github.com/repos/RAIT-09/obsidian-agent-client/releases"})).json.find(o=>o.prerelease);return i?Jn.clean(i.tag_name):null}async checkForUpdates(){let n=Jn.clean(this.manifest.version)||this.manifest.version;if(Jn.prerelease(n)!==null){let[i,o]=await Promise.all([this.fetchLatestStable(),this.fetchLatestPrerelease()]),a=i&&Jn.gt(i,n),s=o&&Jn.gt(o,n);if(a||s){let u=a?i:o;return new hr.Notice(`[Agent Client] Update available: v${u}`),!0}}else{let i=await this.fetchLatestStable();if(i&&Jn.gt(i,n))return new hr.Notice(`[Agent Client] Update available: v${i}`),!0}return!1}ensureActiveAgentId(){let n=this.collectAvailableAgentIds();if(n.length===0){this.settings.activeAgentId=ue.claude.id;return}n.includes(this.settings.activeAgentId)||(this.settings.activeAgentId=n[0])}collectAvailableAgentIds(){let n=new Set;n.add(this.settings.claude.id),n.add(this.settings.codex.id),n.add(this.settings.gemini.id);for(let r of this.settings.customAgents)r.id&&r.id.length>0&&n.add(r.id);return Array.from(n)}}; /*! Bundled license information: react/cjs/react.production.js: diff --git a/content/.obsidian/plugins/agent-client/manifest.json b/content/.obsidian/plugins/agent-client/manifest.json index c412de1..f18f6f7 100644 --- a/content/.obsidian/plugins/agent-client/manifest.json +++ b/content/.obsidian/plugins/agent-client/manifest.json @@ -1 +1 @@ -{"id":"agent-client","name":"Agent Client","version":"0.6.0-preview.4","minAppVersion":"0.15.0","description":"Chat with AI agents via the Agent Client Protocol directly from your vault.","author":"RAIT-09","authorUrl":"https://github.com/RAIT-09","fundingUrl":"https://www.buymeacoffee.com/rait09","isDesktopOnly":true} \ No newline at end of file +{"id":"agent-client","name":"Agent Client","version":"0.6.0-preview.5","minAppVersion":"0.15.0","description":"Chat with AI agents via the Agent Client Protocol directly from your vault.","author":"RAIT-09","authorUrl":"https://github.com/RAIT-09","fundingUrl":"https://www.buymeacoffee.com/rait09","isDesktopOnly":true} \ No newline at end of file diff --git a/content/Vetenskaplig artikel/HT25_Scientific_articles_plan_20260106-1.pdf b/content/Vetenskaplig artikel/HT25_Scientific_articles_plan_20260106-1.pdf new file mode 100644 index 0000000..891324b --- /dev/null +++ b/content/Vetenskaplig artikel/HT25_Scientific_articles_plan_20260106-1.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2dac1f02cee7faeb0ee9378dea8a674a01ad2fb1399e9bf343143d45ca1d7f4a +size 96459 diff --git a/content/Vetenskaplig artikel/Introduction to Scientifc Writing HT25.pdf b/content/Vetenskaplig artikel/Introduction to Scientifc Writing HT25.pdf new file mode 100644 index 0000000..5ca8dc1 --- /dev/null +++ b/content/Vetenskaplig artikel/Introduction to Scientifc Writing HT25.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:83e8acadc840c383a3fca91cc7e040d80f730f5992164b07467b7a5dd5452de4 +size 5631411 diff --git a/content/Vetenskaplig artikel/Methods & Main Results (TODO).md b/content/Vetenskaplig artikel/Methods & Main Results (TODO).md new file mode 100644 index 0000000..1b88993 --- /dev/null +++ b/content/Vetenskaplig artikel/Methods & Main Results (TODO).md @@ -0,0 +1,28 @@ + +- [ ] Läs **Methods** och identifiera: + - [ ] Modell/material (celltyp, vävnad, patienter, djur, dataset) + - [ ] 2–3 huvudmetoder (endast övergripande nivå) + - [ ] Vad som jämförs/testas (grupper, kontroll vs behandling) + +- [ ] Identifiera **main results**: + - [ ] Lista 2–3 huvudfynd + - [ ] Koppla varje fynd till rätt metod + - [ ] Formulera resultaten i ord (ökade/minskade/skilde sig) + +- [ ] Välj **1–2 figurer**: + - [ ] Figur X: vilken metod, vad mäts, huvudbudskap + - [ ] Figur Y: vilken metod, vad mäts, huvudbudskap + +- [ ] Förbered muntlig förklaring (3–4 min): + - [ ] 30–45 s: Methods (översikt) + - [ ] 1–2 min: Resultat kopplat till figurer + - [ ] 30 s: Sammanfattning av huvudfynd + +- [ ] Kontrollera gränser: + - [ ] Ingen bakgrund/teori + - [ ] Ingen diskussion/tolkning + - [ ] Inga onödiga detaljer + +- [ ] Förbered stödanteckningar (papper/MD): + - [ ] Kort manus (bullet points) + - [ ] Nyckelord per figur \ No newline at end of file