lody 0.1.13 → 0.1.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +2 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -135,7 +135,7 @@ ${e}`;return Object.assign(new Error(r),t,{stack:i})}var z5=class extends EVe.Ev
|
|
|
135
135
|
`:`
|
|
136
136
|
`)+r,i=n+1,n=t.indexOf(`
|
|
137
137
|
`,i)}while(n!==-1);return s+=t.slice(i),s}var{stdout:QL,stderr:KL}=zL,H6=Symbol("GENERATOR"),wh=Symbol("STYLER"),Wm=Symbol("IS_EMPTY"),JL=["ansi","ansi","ansi256","ansi16m"],Sh=Object.create(null),M0e=(t,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let r=QL?QL.level:0;t.level=e.level===void 0?r:e.level};var L0e=t=>{let e=(...r)=>r.join(" ");return M0e(e,t),Object.setPrototypeOf(e,Vm.prototype),e};function Vm(t){return L0e(t)}Object.setPrototypeOf(Vm.prototype,Function.prototype);for(let[t,e]of Object.entries(wo))Sh[t]={get(){let r=ub(this,V6(e.open,e.close,this[wh]),this[Wm]);return Object.defineProperty(this,t,{value:r}),r}};Sh.visible={get(){let t=ub(this,this[wh],!0);return Object.defineProperty(this,"visible",{value:t}),t}};var W6=(t,e,r,...n)=>t==="rgb"?e==="ansi16m"?wo[r].ansi16m(...n):e==="ansi256"?wo[r].ansi256(wo.rgbToAnsi256(...n)):wo[r].ansi(wo.rgbToAnsi(...n)):t==="hex"?W6("rgb",e,r,...wo.hexToRgb(...n)):wo[r][t](...n),q0e=["rgb","hex","ansi256"];for(let t of q0e){Sh[t]={get(){let{level:r}=this;return function(...n){let i=V6(W6(t,JL[r],"color",...n),wo.color.close,this[wh]);return ub(this,i,this[Wm])}}};let e="bg"+t[0].toUpperCase()+t.slice(1);Sh[e]={get(){let{level:r}=this;return function(...n){let i=V6(W6(t,JL[r],"bgColor",...n),wo.bgColor.close,this[wh]);return ub(this,i,this[Wm])}}}}var U0e=Object.defineProperties(()=>{},{...Sh,level:{enumerable:!0,get(){return this[H6].level},set(t){this[H6].level=t}}}),V6=(t,e,r)=>{let n,i;return r===void 0?(n=t,i=e):(n=r.openAll+t,i=e+r.closeAll),{open:t,close:e,openAll:n,closeAll:i,parent:r}},ub=(t,e,r)=>{let n=(...i)=>j0e(n,i.length===1?""+i[0]:i.join(" "));return Object.setPrototypeOf(n,U0e),n[H6]=t,n[wh]=e,n[Wm]=r,n},j0e=(t,e)=>{if(t.level<=0||!e)return t[Wm]?"":e;let r=t[wh];if(r===void 0)return e;let{openAll:n,closeAll:i}=r;if(e.includes("\x1B"))for(;r!==void 0;)e=GL(e,r.close,r.open),r=r.parent;let s=e.indexOf(`
|
|
138
|
-
`);return s!==-1&&(e=YL(e,i,n,s)),n+e+i};Object.defineProperties(Vm.prototype,Sh);var $0e=Vm(),frt=Vm({level:KL?KL.level:0});var it=$0e;var ZL="0.1.
|
|
138
|
+
`);return s!==-1&&(e=YL(e,i,n,s)),n+e+i};Object.defineProperties(Vm.prototype,Sh);var $0e=Vm(),frt=Vm({level:KL?KL.level:0});var it=$0e;var ZL="0.1.14";var z6={name:"lody",version:ZL,description:"Lody Agent CLI tool for managing remote command execution",main:"dist/index.js",bin:{lody:"dist/index.js"},scripts:{dev:"tsx src/index.ts",build:"pnpm run clean && pnpm run typecheck && pnpm run build:bundle && pnpm run copy:wasm","build:watch":"pnpm run build:bundle -- --watch","build:bundle":"esbuild src/index.ts --bundle --platform=node --target=node18 --format=cjs --outfile=dist/index.js --minify --legal-comments=none --external:cpu-features --external:*.node","copy:wasm":"node scripts/copy-loro-wasm.js",clean:"rimraf dist",format:"prettier --write src/**/*.ts","format:check":"prettier --check src/**/*.ts",typecheck:"tsc --noEmit",test:"jest","test:watch":"jest --watch","test:coverage":"jest --coverage",prepublishOnly:"npm run clean && npm run build && node scripts/prepare-publish.js",postpublish:"node scripts/prepare-publish.js --restore","serve:dev":"NODE_ENV=development npm run dev serve","serve:prod":"NODE_ENV=production npm run dev serve"},keywords:["cli","typescript","command-line","agent","remote-execution"],author:"Leon Zhao",license:"MIT",engines:{node:">=18.0.0"},devDependencies:{"@agentclientprotocol/sdk":"^0.5.1","@lody/types":"workspace:*","@modelcontextprotocol/sdk":"^1.17.0","@types/dockerode":"^3.3.42","@types/express":"^5.0.0","@types/fs-extra":"^11.0.4","@types/inquirer":"^9.0.7","@types/jest":"^29.5.14","@types/js-yaml":"^4.0.9","@types/node":"catalog:","@types/throttle-debounce":"^5.0.2","@types/uuid":"^9.0.8","@types/ws":"^8.18.1",chalk:"^5.3.0",commander:"^12.1.0",convex:"1.25.4",dockerode:"^4.0.7",dotenv:"^16.6.1",esbuild:"^0.24.0",eventemitter3:"^5.0.1",express:"^4.21.2","fs-extra":"^11.2.0",inquirer:"^10.2.2",jest:"^29.7.0","js-yaml":"^4.1.0","loro-crdt":"catalog:","loro-mirror":"catalog:","loro-websocket":"workspace:*",ora:"^8.1.1",prettier:"^3.4.2",rimraf:"^6.0.1","ts-jest":"^29.2.5","ts-node":"^10.9.2",tsx:"^4.20.5",typescript:"catalog:",uuid:"^13.0.0",winston:"^3.11.0","winston-daily-rotate-file":"^5.0.0",ws:"^8.18.3"},files:["dist","README.md","LICENSE"],dependencies:{"throttle-debounce":"^5.0.2"}};var Qm=qe(require("node:process"),1);var eI=qe(require("node:process"),1);var zm=qe(require("node:process"),1);var H0e=(t,e,r,n)=>{if(r==="length"||r==="prototype"||r==="arguments"||r==="caller")return;let i=Object.getOwnPropertyDescriptor(t,r),s=Object.getOwnPropertyDescriptor(e,r);!W0e(i,s)&&n||Object.defineProperty(t,r,s)},W0e=function(t,e){return t===void 0||t.configurable||t.writable===e.writable&&t.enumerable===e.enumerable&&t.configurable===e.configurable&&(t.writable||t.value===e.value)},V0e=(t,e)=>{let r=Object.getPrototypeOf(e);r!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,r)},z0e=(t,e)=>`/* Wrapped ${t}*/
|
|
139
139
|
${e}`,G0e=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Y0e=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Q0e=(t,e,r)=>{let n=r===""?"":`with ${r.trim()}() `,i=z0e.bind(null,n,e.toString());Object.defineProperty(i,"name",Y0e);let{writable:s,enumerable:o,configurable:a}=G0e;Object.defineProperty(t,"toString",{value:i,writable:s,enumerable:o,configurable:a})};function G6(t,e,{ignoreNonConfigurable:r=!1}={}){let{name:n}=t;for(let i of Reflect.ownKeys(e))H0e(t,e,i,r);return V0e(t,e),Q0e(t,e,n),t}var cb=new WeakMap,e7=(t,e={})=>{if(typeof t!="function")throw new TypeError("Expected a function");let r,n=0,i=t.displayName||t.name||"<anonymous>",s=function(...o){if(cb.set(s,++n),n===1)r=t.apply(this,o),t=void 0;else if(e.throw===!0)throw new Error(`Function \`${i}\` can only be called once`);return r};return G6(s,t),cb.set(s,n),s};e7.callCount=t=>{if(!cb.has(t))throw new Error(`The given function \`${t.name}\` is not wrapped by the \`onetime\` package`);return cb.get(t)};var t7=e7;var yf=[];yf.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&yf.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&yf.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var lb=t=>!!t&&typeof t=="object"&&typeof t.removeListener=="function"&&typeof t.emit=="function"&&typeof t.reallyExit=="function"&&typeof t.listeners=="function"&&typeof t.kill=="function"&&typeof t.pid=="number"&&typeof t.on=="function",Y6=Symbol.for("signal-exit emitter"),Q6=globalThis,K0e=Object.defineProperty.bind(Object),K6=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Q6[Y6])return Q6[Y6];K0e(Q6,Y6,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,r){this.listeners[e].push(r)}removeListener(e,r){let n=this.listeners[e],i=n.indexOf(r);i!==-1&&(i===0&&n.length===1?n.length=0:n.splice(i,1))}emit(e,r,n){if(this.emitted[e])return!1;this.emitted[e]=!0;let i=!1;for(let s of this.listeners[e])i=s(r,n)===!0||i;return e==="exit"&&(i=this.emit("afterExit",r,n)||i),i}},fb=class{},J0e=t=>({onExit(e,r){return t.onExit(e,r)},load(){return t.load()},unload(){return t.unload()}}),J6=class extends fb{onExit(){return()=>{}}load(){}unload(){}},X6=class extends fb{#e=Z6.platform==="win32"?"SIGINT":"SIGHUP";#n=new K6;#t;#o;#a;#r={};#s=!1;constructor(e){super(),this.#t=e,this.#r={};for(let r of yf)this.#r[r]=()=>{let n=this.#t.listeners(r),{count:i}=this.#n,s=e;if(typeof s.__signal_exit_emitter__=="object"&&typeof s.__signal_exit_emitter__.count=="number"&&(i+=s.__signal_exit_emitter__.count),n.length===i){this.unload();let o=this.#n.emit("exit",null,r),a=r==="SIGHUP"?this.#e:r;o||e.kill(e.pid,a)}};this.#a=e.reallyExit,this.#o=e.emit}onExit(e,r){if(!lb(this.#t))return()=>{};this.#s===!1&&this.load();let n=r?.alwaysLast?"afterExit":"exit";return this.#n.on(n,e),()=>{this.#n.removeListener(n,e),this.#n.listeners.exit.length===0&&this.#n.listeners.afterExit.length===0&&this.unload()}}load(){if(!this.#s){this.#s=!0,this.#n.count+=1;for(let e of yf)try{let r=this.#r[e];r&&this.#t.on(e,r)}catch{}this.#t.emit=(e,...r)=>this.#f(e,...r),this.#t.reallyExit=e=>this.#i(e)}}unload(){this.#s&&(this.#s=!1,yf.forEach(e=>{let r=this.#r[e];if(!r)throw new Error("Listener not defined for signal: "+e);try{this.#t.removeListener(e,r)}catch{}}),this.#t.emit=this.#o,this.#t.reallyExit=this.#a,this.#n.count-=1)}#i(e){return lb(this.#t)?(this.#t.exitCode=e||0,this.#n.emit("exit",this.#t.exitCode,null),this.#a.call(this.#t,this.#t.exitCode)):0}#f(e,...r){let n=this.#o;if(e==="exit"&&lb(this.#t)){typeof r[0]=="number"&&(this.#t.exitCode=r[0]);let i=n.call(this.#t,e,...r);return this.#n.emit("exit",this.#t.exitCode,null),i}else return n.call(this.#t,e,...r)}},Z6=globalThis.process,{onExit:db,load:vrt,unload:brt}=J0e(lb(Z6)?new X6(Z6):new J6);var r7=zm.default.stderr.isTTY?zm.default.stderr:zm.default.stdout.isTTY?zm.default.stdout:void 0,X0e=r7?t7(()=>{db(()=>{r7.write("\x1B[?25h")},{alwaysLast:!0})}):()=>{},n7=X0e;var hb=!1,Ch={};Ch.show=(t=eI.default.stderr)=>{t.isTTY&&(hb=!1,t.write("\x1B[?25h"))};Ch.hide=(t=eI.default.stderr)=>{t.isTTY&&(n7(),hb=!0,t.write("\x1B[?25l"))};Ch.toggle=(t,e)=>{t!==void 0&&(hb=t),hb?Ch.show(e):Ch.hide(e)};var tI=Ch;var Km=qe(rI(),1);var qs=qe(require("node:process"),1);function nI(){return qs.default.platform!=="win32"?qs.default.env.TERM!=="linux":!!qs.default.env.CI||!!qs.default.env.WT_SESSION||!!qs.default.env.TERMINUS_SUBLIME||qs.default.env.ConEmuTask==="{cmd::Cmder}"||qs.default.env.TERM_PROGRAM==="Terminus-Sublime"||qs.default.env.TERM_PROGRAM==="vscode"||qs.default.env.TERM==="xterm-256color"||qs.default.env.TERM==="alacritty"||qs.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var eme={info:it.blue("\u2139"),success:it.green("\u2714"),warning:it.yellow("\u26A0"),error:it.red("\u2716")},tme={info:it.blue("i"),success:it.green("\u221A"),warning:it.yellow("\u203C"),error:it.red("\xD7")},rme=nI()?eme:tme,Gm=rme;function iI({onlyFirst:t=!1}={}){let i="(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";return new RegExp(i,t?void 0:"g")}var nme=iI();function Ym(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return t.replace(nme,"")}function a7(t){return t===161||t===164||t===167||t===168||t===170||t===173||t===174||t>=176&&t<=180||t>=182&&t<=186||t>=188&&t<=191||t===198||t===208||t===215||t===216||t>=222&&t<=225||t===230||t>=232&&t<=234||t===236||t===237||t===240||t===242||t===243||t>=247&&t<=250||t===252||t===254||t===257||t===273||t===275||t===283||t===294||t===295||t===299||t>=305&&t<=307||t===312||t>=319&&t<=322||t===324||t>=328&&t<=331||t===333||t===338||t===339||t===358||t===359||t===363||t===462||t===464||t===466||t===468||t===470||t===472||t===474||t===476||t===593||t===609||t===708||t===711||t>=713&&t<=715||t===717||t===720||t>=728&&t<=731||t===733||t===735||t>=768&&t<=879||t>=913&&t<=929||t>=931&&t<=937||t>=945&&t<=961||t>=963&&t<=969||t===1025||t>=1040&&t<=1103||t===1105||t===8208||t>=8211&&t<=8214||t===8216||t===8217||t===8220||t===8221||t>=8224&&t<=8226||t>=8228&&t<=8231||t===8240||t===8242||t===8243||t===8245||t===8251||t===8254||t===8308||t===8319||t>=8321&&t<=8324||t===8364||t===8451||t===8453||t===8457||t===8467||t===8470||t===8481||t===8482||t===8486||t===8491||t===8531||t===8532||t>=8539&&t<=8542||t>=8544&&t<=8555||t>=8560&&t<=8569||t===8585||t>=8592&&t<=8601||t===8632||t===8633||t===8658||t===8660||t===8679||t===8704||t===8706||t===8707||t===8711||t===8712||t===8715||t===8719||t===8721||t===8725||t===8730||t>=8733&&t<=8736||t===8739||t===8741||t>=8743&&t<=8748||t===8750||t>=8756&&t<=8759||t===8764||t===8765||t===8776||t===8780||t===8786||t===8800||t===8801||t>=8804&&t<=8807||t===8810||t===8811||t===8814||t===8815||t===8834||t===8835||t===8838||t===8839||t===8853||t===8857||t===8869||t===8895||t===8978||t>=9312&&t<=9449||t>=9451&&t<=9547||t>=9552&&t<=9587||t>=9600&&t<=9615||t>=9618&&t<=9621||t===9632||t===9633||t>=9635&&t<=9641||t===9650||t===9651||t===9654||t===9655||t===9660||t===9661||t===9664||t===9665||t>=9670&&t<=9672||t===9675||t>=9678&&t<=9681||t>=9698&&t<=9701||t===9711||t===9733||t===9734||t===9737||t===9742||t===9743||t===9756||t===9758||t===9792||t===9794||t===9824||t===9825||t>=9827&&t<=9829||t>=9831&&t<=9834||t===9836||t===9837||t===9839||t===9886||t===9887||t===9919||t>=9926&&t<=9933||t>=9935&&t<=9939||t>=9941&&t<=9953||t===9955||t===9960||t===9961||t>=9963&&t<=9969||t===9972||t>=9974&&t<=9977||t===9979||t===9980||t===9982||t===9983||t===10045||t>=10102&&t<=10111||t>=11094&&t<=11097||t>=12872&&t<=12879||t>=57344&&t<=63743||t>=65024&&t<=65039||t===65533||t>=127232&&t<=127242||t>=127248&&t<=127277||t>=127280&&t<=127337||t>=127344&&t<=127373||t===127375||t===127376||t>=127387&&t<=127404||t>=917760&&t<=917999||t>=983040&&t<=1048573||t>=1048576&&t<=1114109}function u7(t){return t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510}function c7(t){return t>=4352&&t<=4447||t===8986||t===8987||t===9001||t===9002||t>=9193&&t<=9196||t===9200||t===9203||t===9725||t===9726||t===9748||t===9749||t>=9776&&t<=9783||t>=9800&&t<=9811||t===9855||t>=9866&&t<=9871||t===9875||t===9889||t===9898||t===9899||t===9917||t===9918||t===9924||t===9925||t===9934||t===9940||t===9962||t===9970||t===9971||t===9973||t===9978||t===9981||t===9989||t===9994||t===9995||t===10024||t===10060||t===10062||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t===11035||t===11036||t===11088||t===11093||t>=11904&&t<=11929||t>=11931&&t<=12019||t>=12032&&t<=12245||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12353&&t<=12438||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12773||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=42124||t>=42128&&t<=42182||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=94176&&t<=94180||t===94192||t===94193||t>=94208&&t<=100343||t>=100352&&t<=101589||t>=101631&&t<=101640||t>=110576&&t<=110579||t>=110581&&t<=110587||t===110589||t===110590||t>=110592&&t<=110882||t===110898||t>=110928&&t<=110930||t===110933||t>=110948&&t<=110951||t>=110960&&t<=111355||t>=119552&&t<=119638||t>=119648&&t<=119670||t===126980||t===127183||t===127374||t>=127377&&t<=127386||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t===127568||t===127569||t>=127584&&t<=127589||t>=127744&&t<=127776||t>=127789&&t<=127797||t>=127799&&t<=127868||t>=127870&&t<=127891||t>=127904&&t<=127946||t>=127951&&t<=127955||t>=127968&&t<=127984||t===127988||t>=127992&&t<=128062||t===128064||t>=128066&&t<=128252||t>=128255&&t<=128317||t>=128331&&t<=128334||t>=128336&&t<=128359||t===128378||t===128405||t===128406||t===128420||t>=128507&&t<=128591||t>=128640&&t<=128709||t===128716||t>=128720&&t<=128722||t>=128725&&t<=128727||t>=128732&&t<=128735||t===128747||t===128748||t>=128756&&t<=128764||t>=128992&&t<=129003||t===129008||t>=129292&&t<=129338||t>=129340&&t<=129349||t>=129351&&t<=129535||t>=129648&&t<=129660||t>=129664&&t<=129673||t>=129679&&t<=129734||t>=129742&&t<=129756||t>=129759&&t<=129769||t>=129776&&t<=129784||t>=131072&&t<=196605||t>=196608&&t<=262141}function ime(t){if(!Number.isSafeInteger(t))throw new TypeError(`Expected a code point, got \`${typeof t}\`.`)}function l7(t,{ambiguousAsWide:e=!1}={}){return ime(t),u7(t)||c7(t)||e&&a7(t)?2:1}var h7=qe(d7(),1),sme=new Intl.Segmenter,ome=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function sI(t,e={}){if(typeof t!="string"||t.length===0)return 0;let{ambiguousIsNarrow:r=!0,countAnsiEscapeCodes:n=!1}=e;if(n||(t=Ym(t)),t.length===0)return 0;let i=0,s={ambiguousAsWide:!r};for(let{segment:o}of sme.segment(t)){let a=o.codePointAt(0);if(!(a<=31||a>=127&&a<=159)&&!(a>=8203&&a<=8207||a===65279)&&!(a>=768&&a<=879||a>=6832&&a<=6911||a>=7616&&a<=7679||a>=8400&&a<=8447||a>=65056&&a<=65071)&&!(a>=55296&&a<=57343)&&!(a>=65024&&a<=65039)&&!ome.test(o)){if((0,h7.default)().test(o)){i+=2;continue}i+=l7(a,s)}}return i}function oI({stream:t=process.stdout}={}){return!!(t&&t.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}var aI=qe(require("node:process"),1);function uI(){let{env:t}=aI.default,{TERM:e,TERM_PROGRAM:r}=t;return aI.default.platform!=="win32"?e!=="linux":!!t.WT_SESSION||!!t.TERMINUS_SUBLIME||t.ConEmuTask==="{cmd::Cmder}"||r==="Terminus-Sublime"||r==="vscode"||e==="xterm-256color"||e==="alacritty"||e==="rxvt-unicode"||e==="rxvt-unicode-256color"||t.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var So=qe(require("node:process"),1),ame=3,cI=class{#e=0;start(){this.#e++,this.#e===1&&this.#n()}stop(){if(this.#e<=0)throw new Error("`stop` called more times than `start`");this.#e--,this.#e===0&&this.#t()}#n(){So.default.platform==="win32"||!So.default.stdin.isTTY||(So.default.stdin.setRawMode(!0),So.default.stdin.on("data",this.#o),So.default.stdin.resume())}#t(){So.default.stdin.isTTY&&(So.default.stdin.off("data",this.#o),So.default.stdin.pause(),So.default.stdin.setRawMode(!1))}#o(e){e[0]===ame&&So.default.emit("SIGINT")}},ume=new cI,lI=ume;var cme=qe(rI(),1),fI=class{#e=0;#n=!1;#t=0;#o=-1;#a=0;#r;#s;#i;#f;#m;#u;#c;#l;#d;#h;#p;color;constructor(e){typeof e=="string"&&(e={text:e}),this.#r={color:"cyan",stream:Qm.default.stderr,discardStdin:!0,hideCursor:!0,...e},this.color=this.#r.color,this.spinner=this.#r.spinner,this.#m=this.#r.interval,this.#i=this.#r.stream,this.#u=typeof this.#r.isEnabled=="boolean"?this.#r.isEnabled:oI({stream:this.#i}),this.#c=typeof this.#r.isSilent=="boolean"?this.#r.isSilent:!1,this.text=this.#r.text,this.prefixText=this.#r.prefixText,this.suffixText=this.#r.suffixText,this.indent=this.#r.indent,Qm.default.env.NODE_ENV==="test"&&(this._stream=this.#i,this._isEnabled=this.#u,Object.defineProperty(this,"_linesToClear",{get(){return this.#e},set(r){this.#e=r}}),Object.defineProperty(this,"_frameIndex",{get(){return this.#o}}),Object.defineProperty(this,"_lineCount",{get(){return this.#t}}))}get indent(){return this.#l}set indent(e=0){if(!(e>=0&&Number.isInteger(e)))throw new Error("The `indent` option must be an integer from 0 and up");this.#l=e,this.#g()}get interval(){return this.#m??this.#s.interval??100}get spinner(){return this.#s}set spinner(e){if(this.#o=-1,this.#m=void 0,typeof e=="object"){if(e.frames===void 0)throw new Error("The given spinner must have a `frames` property");this.#s=e}else if(!uI())this.#s=Km.default.line;else if(e===void 0)this.#s=Km.default.dots;else if(e!=="default"&&Km.default[e])this.#s=Km.default[e];else throw new Error(`There is no built-in spinner named '${e}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`)}get text(){return this.#d}set text(e=""){this.#d=e,this.#g()}get prefixText(){return this.#h}set prefixText(e=""){this.#h=e,this.#g()}get suffixText(){return this.#p}set suffixText(e=""){this.#p=e,this.#g()}get isSpinning(){return this.#f!==void 0}#_(e=this.#h,r=" "){return typeof e=="string"&&e!==""?e+r:typeof e=="function"?e()+r:""}#y(e=this.#p,r=" "){return typeof e=="string"&&e!==""?r+e:typeof e=="function"?r+e():""}#g(){let e=this.#i.columns??80,r=this.#_(this.#h,"-"),n=this.#y(this.#p,"-"),i=" ".repeat(this.#l)+r+"--"+this.#d+"--"+n;this.#t=0;for(let s of Ym(i).split(`
|
|
140
140
|
`))this.#t+=Math.max(1,Math.ceil(sI(s,{countAnsiEscapeCodes:!0})/e))}get isEnabled(){return this.#u&&!this.#c}set isEnabled(e){if(typeof e!="boolean")throw new TypeError("The `isEnabled` option must be a boolean");this.#u=e}get isSilent(){return this.#c}set isSilent(e){if(typeof e!="boolean")throw new TypeError("The `isSilent` option must be a boolean");this.#c=e}frame(){let e=Date.now();(this.#o===-1||e-this.#a>=this.interval)&&(this.#o=++this.#o%this.#s.frames.length,this.#a=e);let{frames:r}=this.#s,n=r[this.#o];this.color&&(n=it[this.color](n));let i=typeof this.#h=="string"&&this.#h!==""?this.#h+" ":"",s=typeof this.text=="string"?" "+this.text:"",o=typeof this.#p=="string"&&this.#p!==""?" "+this.#p:"";return i+n+s+o}clear(){if(!this.#u||!this.#i.isTTY)return this;this.#i.cursorTo(0);for(let e=0;e<this.#e;e++)e>0&&this.#i.moveCursor(0,-1),this.#i.clearLine(1);return(this.#l||this.lastIndent!==this.#l)&&this.#i.cursorTo(this.#l),this.lastIndent=this.#l,this.#e=0,this}render(){return this.#c?this:(this.clear(),this.#i.write(this.frame()),this.#e=this.#t,this)}start(e){return e&&(this.text=e),this.#c?this:this.#u?this.isSpinning?this:(this.#r.hideCursor&&tI.hide(this.#i),this.#r.discardStdin&&Qm.default.stdin.isTTY&&(this.#n=!0,lI.start()),this.render(),this.#f=setInterval(this.render.bind(this),this.interval),this):(this.text&&this.#i.write(`- ${this.text}
|
|
141
141
|
`),this)}stop(){return this.#u?(clearInterval(this.#f),this.#f=void 0,this.#o=0,this.clear(),this.#r.hideCursor&&tI.show(this.#i),this.#r.discardStdin&&Qm.default.stdin.isTTY&&this.#n&&(lI.stop(),this.#n=!1),this):this}succeed(e){return this.stopAndPersist({symbol:Gm.success,text:e})}fail(e){return this.stopAndPersist({symbol:Gm.error,text:e})}warn(e){return this.stopAndPersist({symbol:Gm.warning,text:e})}info(e){return this.stopAndPersist({symbol:Gm.info,text:e})}stopAndPersist(e={}){if(this.#c)return this;let r=e.prefixText??this.#h,n=this.#_(r," "),i=e.symbol??" ",s=e.text??this.text,a=typeof s=="string"?(i?" ":"")+s:"",u=e.suffixText??this.#p,c=this.#y(u," "),l=n+i+a+c+`
|
|
@@ -188,7 +188,7 @@ Start Docker with: sudo systemctl start docker`}:e.includes("command not found")
|
|
|
188
188
|
Please visit: `+it.cyan(n.verification_uri_complete));try{this.logger.info("Attempting to open the URL in your default browser..."),await UX(n.verification_uri_complete)}catch(d){this.logger.warn(`Could not open the browser automatically: ${d instanceof Error?d.message:"Unknown error"}`),this.logger.info("Please open the URL manually if it did not open automatically.")}this.logger.info(it.yellow("=".repeat(50))+`
|
|
189
189
|
`);let i=Jm("Waiting for authorization...").start(),s=!1,o="",a=null,u={id:"",name:""},l=Date.now()+n.expires_in*1e3;for(;!s&&Date.now()<l;){await new Promise(d=>setTimeout(d,n.interval*1e3));try{let d=await this.client.query(s0.deviceAuth.checkDeviceAuthorization,{deviceCode:n.device_code});switch(d.status){case"authorized":s=!0,o=d.access_token,a=d.user,u=d.workspace,i.succeed("Authorization successful!");break;case"needs_token_generation":await this.client.mutation(s0.deviceAuth.generateCliToken,{deviceCode:n.device_code,userId:d.userId});let p=await this.client.query(s0.deviceAuth.checkDeviceAuthorization,{deviceCode:n.device_code});p.status==="authorized"&&(s=!0,o=p.access_token,a=p.user,u=p.workspace,i.succeed("Authorization successful!"));break;case"denied":return i.fail("Authorization was denied"),{success:!1,error:"Authorization denied"};case"expired":return i.fail("Authorization code expired"),{success:!1,error:"Authorization code expired"};case"error":return i.fail(`Error: ${d.error}`),{success:!1,error:d.error||"Unknown error"};case"pending":break}}catch{return{success:!1,error:"Network error or server error when logging in"}}}if(!s)return i.fail("Authorization timed out"),{success:!1,error:"Authorization timed out"};let f={token:o,user:a,workspace:{id:u.id,name:u.name},machine:{machineName:e,machineId:r}};return await FF(o,f.user,f.workspace,f.machine),{success:!0,...f}}logout(){let e=jX();if(!e)return this.logger.debug("No authentication found. You are not logged in."),{success:!0,user:void 0};let r=jS();return ml.unlinkSync(r),{success:!0,user:e.user}}async validateToken(e){return await gMe(e,this.client)}};async function FF(t,e,r,n){let i=jS(),s=$X.default.dirname(i);await ml.mkdir(s,{recursive:!0}),await ml.writeFile(i,JSON.stringify({token:t,user:e,workspace:r,machine:n},null,2))}function jX(){try{let t=jS(),e=ml.readFileSync(t,"utf-8");return JSON.parse(e)}catch{return null}}async function gMe(t,e){try{let r=await e.query(s0.deviceAuth.validateCliToken,{token:t});return r.valid&&r.user?{valid:!0,user:r.user,workspace:r.workspace}:{valid:!1}}catch{return{valid:!1}}}PF();var vl=qe(h0(),1);PF();var sZ=class{crdtType=On.Loro;doc;config;ctx;localUpdateUnsubscribe;destroyed=!1;initServerVersion;reachServerVersionPromise;hasReachedServerVersion=!1;constructor(t,e={}){this.doc=t||new vl.LoroDoc,this.config=e;{let r,n;this.reachServerVersionPromise={promise:new Promise((i,s)=>{r=i,n=s}),resolve:r,reject:n},this.reachServerVersionPromise.promise.then(()=>{this.hasReachedServerVersion=!0})}}waitForReachingServerVersion(){return this.reachServerVersionPromise.promise}cmpVersion(t){let e=vl.VersionVector.decode(t);return this.doc.version().compare(e)}handleJoinErr;getDoc(){return this.doc}setCtx(t){this.ctx=t,this.localUpdateUnsubscribe=this.doc.subscribeLocalUpdates(e=>{!this.destroyed&&this.ctx&&this.ctx.send([e])})}getVersion(){return this.doc.version().encode()}getAlternativeVersion(t){}async handleJoinOk(t){if(!this.destroyed)try{let e;if(t.version.length>0){try{e=vl.VersionVector.decode(t.version),this.initServerVersion=e}catch{throw new Error("Invalid version format received")}let r=this.doc.version().compare(e);if(r!=null&&r>=0&&this.reachServerVersionPromise.resolve(),r==null||r===1){let n=this.doc.export({mode:"update",from:e});this.ctx?.send([n])}}else{let r=this.doc.export({mode:"snapshot"});this.ctx?.send([r])}}catch(e){throw this.ctx.onJoinFailed(e instanceof Error?e.message:String(e)),e}}applyUpdate(t){if(!(this.destroyed||!t?.length)){try{this.doc.importBatch(t).pending==null}catch(e){this.ctx.onImportError(e instanceof Error?e:new Error(String(e)),t)}if(this.initServerVersion&&!this.hasReachedServerVersion){let e=this.doc.version().compare(this.initServerVersion);e!=null&&e>=0&&this.reachServerVersionPromise.resolve()}}}handleUpdateError(t){this.config.onUpdateError&&this.config.onUpdateError(t)}destroy(){this.destroyed||(this.destroyed=!0,this.localUpdateUnsubscribe&&(this.localUpdateUnsubscribe(),this.localUpdateUnsubscribe=void 0),this.ctx=void 0)}};var oZ=class{crdtType=On.LoroEphemeralStorePersisted;store;ctx;localUpdateUnsubscribe;destroyed=!1;constructor(t){this.store=t||new vl.EphemeralStore}waitForReachingServerVersion(){return Promise.resolve()}cmpVersion(t){return 0}handleJoinErr;getStore(){return this.store}setCtx(t){this.ctx=t,this.localUpdateUnsubscribe=this.store.subscribeLocalUpdates(e=>{!this.destroyed&&this.ctx&&this.ctx.send([e])})}getVersion(){return new Uint8Array}getAlternativeVersion(t){}async handleJoinOk(t){if(!this.destroyed&&this.ctx){let e=this.store.encodeAll();e.length>0&&this.ctx.send([e])}}applyUpdate(t){if(!(this.destroyed||!t?.length)){for(let e of t)if(e?.length>0)try{this.store.apply(e)}catch(r){this.ctx?.onImportError(r instanceof Error?r:new Error(String(r)),[e])}}}destroy(){this.destroyed||(this.destroyed=!0,this.localUpdateUnsubscribe&&(this.localUpdateUnsubscribe(),this.localUpdateUnsubscribe=void 0),this.store.destroy(),this.ctx=void 0)}};var oyt=new TextEncoder,ayt=new TextDecoder;var UMe=class{adaptors=new Map;register(t){this.adaptors.set(t.crdtType,t)}registerMany(t){for(let e of t)this.register(e)}get(t){return this.adaptors.get(t)}clear(){this.adaptors.clear()}list(){return Array.from(this.adaptors.values())}},uyt=new UMe;var cyt=new TextEncoder,lyt=new TextDecoder;var Fu={Connecting:"connecting",Connected:"connected",Disconnected:"disconnected"},aZ=class{constructor(t){this.ops=t,this.status=Fu.Connecting,this.statusListeners=new Set,this.latencyListeners=new Set,this.pendingRooms=new Map,this.activeRooms=new Map,this.preJoinUpdates=new Map,this.fragmentBatches=new Map,this.roomAdaptors=new Map,this.roomIds=new Map,this.roomAuth=new Map,this.socketListeners=new WeakMap,this.pingWaiters=[],this.shouldReconnect=!0,this.reconnectAttempts=0,this.handleOnline=()=>{this.shouldReconnect&&this.status!==Fu.Connected&&(this.clearReconnectTimer(),this.scheduleReconnect(!0))},this.handleOffline=()=>{if(this.clearReconnectTimer(),this.shouldReconnect){this.setStatus(Fu.Disconnected);try{this.ws?.close(1001,"Offline")}catch{}}},this.attachNetworkListeners(),this.ensureConnectedPromise(),this.connect()}get socket(){return this.ws}ensureConnectedPromise(){this.resolveConnected||(this.connectedPromise=new Promise((t,e)=>{this.resolveConnected=()=>{this.resolveConnected=void 0,this.rejectConnected=void 0,t()},this.rejectConnected=r=>{this.resolveConnected=void 0,this.rejectConnected=void 0,e(r)}}))}attachNetworkListeners(){if(this.removeNetworkListeners?.(),this.removeNetworkListeners=void 0,typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("online",this.handleOnline),window.addEventListener("offline",this.handleOffline),this.removeNetworkListeners=()=>{window.removeEventListener("online",this.handleOnline),window.removeEventListener("offline",this.handleOffline)};return}let t=globalThis;if(typeof t.addEventListener=="function"){let r=this.handleOnline,n=this.handleOffline;t.addEventListener("online",r),t.addEventListener("offline",n),this.removeNetworkListeners=()=>{t.removeEventListener?.("online",r),t.removeEventListener?.("offline",n)};return}let e=t.process;if(e&&typeof e.on=="function"){let r=()=>{this.handleOnline()},n=()=>{this.handleOffline()};e.on("online",r),e.on("offline",n),this.removeNetworkListeners=()=>{typeof e.off=="function"?(e.off("online",r),e.off("offline",n)):typeof e.removeListener=="function"&&(e.removeListener("online",r),e.removeListener("offline",n))}}}getStatus(){return this.status}getLatency(){return this.lastLatencyMs}onStatusChange(t){this.statusListeners.add(t);try{t(this.status)}catch{}return()=>this.statusListeners.delete(t)}onLatency(t){if(this.latencyListeners.add(t),this.lastLatencyMs!=null)try{t(this.lastLatencyMs)}catch{}return()=>this.latencyListeners.delete(t)}setStatus(t){if(this.status===t)return;this.status=t;let e=Array.from(this.statusListeners);for(let r of e)try{r(t)}catch{}}async connect(){this.shouldReconnect=!0;let t=this.ws;if(t){let r=t.readyState;if(r===WebSocket.OPEN||r===WebSocket.CONNECTING)return this.connectedPromise}this.clearReconnectTimer(),this.ensureConnectedPromise(),this.setStatus(Fu.Connecting);let e=new WebSocket(this.ops.url);this.ws=e,t&&t!==e&&this.detachSocketListeners(t),this.attachSocketListeners(e);try{e.binaryType="arraybuffer"}catch{}return this.connectedPromise}attachSocketListeners(t){let e=()=>{this.onSocketOpen(t)},r=s=>{this.onSocketError(t,s)},n=s=>{this.onSocketClose(t,s)},i=s=>{this.onSocketMessage(t,s)};t.addEventListener("open",e),t.addEventListener("error",r),t.addEventListener("close",n),t.addEventListener("message",i),this.socketListeners.set(t,{open:e,error:r,close:n,message:i})}onSocketOpen(t){if(t!==this.ws){this.detachSocketListeners(t);try{t.close(1e3,"Superseded")}catch{}return}this.clearReconnectTimer(),this.reconnectAttempts=0,this.setStatus(Fu.Connected),this.startPingTimer(),this.resolveConnected?.(),this.rejoinActiveRooms()}onSocketError(t,e){t!==this.ws&&this.detachSocketListeners(t)}onSocketClose(t,e){let r=t===this.ws;if(this.detachSocketListeners(t),!r)return;let n=e?.code;n!=null&&n>=4400&&n<4500&&(this.shouldReconnect=!1);let i=e?.reason;if((i==="permission_changed"||i==="room_closed")&&(this.shouldReconnect=!1),this.clearPingTimer(),this.fragmentBatches.size){for(let[,s]of this.fragmentBatches)try{clearTimeout(s.timeoutId)}catch{}this.fragmentBatches.clear()}if(this.awaitingPongSince=void 0,this.ops.onWsClose?.(),this.rejectAllPingWaiters(new Error("WebSocket closed")),!this.shouldReconnect){this.setStatus(Fu.Disconnected),this.rejectConnected?.(new Error("Disconnected"));return}this.setStatus(Fu.Disconnected),this.scheduleReconnect()}async onSocketMessage(t,e){if(t!==this.ws)return;if(typeof e.data=="string"){if(e.data==="ping"){try{t.send("pong")}catch{}return}if(e.data==="pong"){this.handlePong();return}return}let r=VX(new Uint8Array(e.data));r!=null&&await this.handleMessage(r)}scheduleReconnect(t=!1){if(this.reconnectTimer)return;let e=++this.reconnectAttempts,r=t?0:Math.min(15e3,500*2**(e-1));this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},r)}clearReconnectTimer(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}rejoinActiveRooms(){for(let[t,e]of this.roomAdaptors){let r=this.roomIds.get(t);if(!r)continue;let n=this.activeRooms.get(t);if(!n)continue;let i={room:Promise.resolve(n.room),resolve:s=>{e.handleJoinOk(s).catch(o=>{console.error(o)}),this.pendingRooms.delete(t)},reject:s=>{console.error("Rejoin failed:",s)},adaptor:e,roomId:r,auth:this.roomAuth.get(t)};this.pendingRooms.set(t,i);try{this.ws.send(Xs({type:Rt.JoinRequest,crdt:e.crdtType,roomId:r,auth:i.auth??new Uint8Array,version:e.getVersion()}))}catch(s){console.error("Failed to send rejoin request:",s)}}}async handleMessage(t){let e=typeof t.roomId=="string"?t.roomId:new TextDecoder().decode(t.roomId),r=t.crdt+e;switch(t.type){case Rt.JoinRequest:throw new Error("JoinRequest should not be received by client");case Rt.JoinResponseOk:{let n=this.pendingRooms.get(r);n&&n.resolve(t);break}case Rt.JoinError:{let n=this.pendingRooms.get(r);n&&await this.handleJoinError(t,n,r);break}case Rt.DocUpdate:{let n=this.activeRooms.get(r);if(n)n.handler.handleDocUpdate(t.updates);else{let i=this.pendingRooms.get(r);if(i&&i.adaptor.crdtType===On.Elo){let s=this.preJoinUpdates.get(r)??[];s.push(...t.updates),this.preJoinUpdates.set(r,s)}}break}case Rt.DocUpdateFragmentHeader:this.handleFragmentHeader(t);break;case Rt.DocUpdateFragment:this.handleFragment(t);break;case Rt.UpdateError:{let n=this.activeRooms.get(r);if(n)n.handler.handleUpdateError(t);else{let i=typeof t.roomId=="string"?t.roomId:new TextDecoder().decode(t.roomId);console.error(`Update error for room ${i}: ${t.code} - ${t.message}`)}break}}}handleFragmentHeader(t){let e=typeof t.roomId=="string"?t.roomId:new TextDecoder().decode(t.roomId),r=`${t.crdt}-${e}-${t.batchId}`,n=this.fragmentBatches.get(r);n&&clearTimeout(n.timeoutId);let i=setTimeout(()=>{this.fragmentBatches.delete(r);try{this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(Xs({type:Rt.UpdateError,crdt:t.crdt,roomId:t.roomId,code:Ei.FragmentTimeout,message:`Fragment reassembly timeout for batch ${t.batchId}`}))}catch{}},1e4);this.fragmentBatches.set(r,{header:t,fragments:new Map,timeoutId:i})}handleFragment(t){let e=typeof t.roomId=="string"?t.roomId:new TextDecoder().decode(t.roomId),r=`${t.crdt}-${e}-${t.batchId}`,n=this.fragmentBatches.get(r);if(!n){console.error(`Received fragment for unknown batch ${t.batchId}`);return}if(n.fragments.set(t.index,t.fragment),n.fragments.size===n.header.fragmentCount){clearTimeout(n.timeoutId),this.fragmentBatches.delete(r);let i=new Uint8Array(n.header.totalSizeBytes),s=0;for(let u=0;u<n.header.fragmentCount;u++){let c=n.fragments.get(u);if(!c){console.error(`Missing fragment ${u} in batch ${t.batchId}`);return}i.set(c,s),s+=c.length}let o=t.crdt+e,a=this.activeRooms.get(o);if(a)a.handler.handleDocUpdate([i]);else{let u=this.pendingRooms.get(o);if(u&&u.adaptor.crdtType===On.Elo){let c=this.preJoinUpdates.get(o)??[];c.push(i),this.preJoinUpdates.set(o,c)}}}}registerActiveRoom(t,e,r,n,i){let s=e+t;this.activeRooms.set(s,{room:r,handler:n}),this.roomAdaptors.set(s,i),this.roomIds.set(s,t);let o=this.preJoinUpdates.get(s);if(o&&o.length)try{n.handleDocUpdate(o)}finally{this.preJoinUpdates.delete(s)}this.pendingRooms.delete(s)}async handleJoinError(t,e,r){if(await e.adaptor.handleJoinErr?.(t),t.code===Js.VersionUnknown){let n=e.adaptor.getVersion(),i=e.adaptor.getAlternativeVersion?.(n);if(i){this.ws.send(Xs({type:Rt.JoinRequest,crdt:e.adaptor.crdtType,roomId:e.roomId,auth:e.auth??new Uint8Array,version:i}));return}else{console.warn("Version unknown. Now join with an empty version"),this.ws.send(Xs({type:Rt.JoinRequest,crdt:e.adaptor.crdtType,roomId:e.roomId,auth:e.auth??new Uint8Array,version:new Uint8Array}));return}}e.reject(new Error(`Join failed: ${t.code} - ${t.message}`)),this.pendingRooms.delete(r)}cleanupRoom(t,e){let r=e+t;this.activeRooms.delete(r),this.pendingRooms.delete(r),this.roomAdaptors.delete(r),this.roomIds.delete(r),this.roomAuth.delete(r)}waitConnected(){return this.connectedPromise}async ping(t=5e3){if(await this.connectedPromise,!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not open");return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("Ping timeout"))},Math.max(1,t)),i={resolve:()=>{clearTimeout(n),e()},reject:s=>{clearTimeout(n),r(s)},timeoutId:n};this.pingWaiters.push(i);try{this.awaitingPongSince==null&&(this.awaitingPongSince=Date.now()),this.ws.send("ping")}catch(s){this.pingWaiters.pop(),clearTimeout(n),r(s instanceof Error?s:new Error(String(s)))}})}join({roomId:t,crdtAdaptor:e,auth:r}){let n=e.crdtType+t,i=this.pendingRooms.get(n);if(i)return i.room;let s=this.activeRooms.get(n);if(s)return Promise.resolve(s.room);let o,a,u=new Promise((c,l)=>{o=c,a=l}).then(c=>{e.setCtx({send:d=>{for(let p of d)this.sendUpdateOrFragments(e.crdtType,t,p)},onJoinFailed:d=>{console.error(`Join failed: ${d}`),this.ws.send(Xs({type:Rt.JoinError,crdt:e.crdtType,roomId:t,code:Js.AppError,message:d})),a(new Error(`Join failed: ${d}`))},onImportError:(d,p)=>{console.error(`Import error: ${d.message}`,p),this.ws.send(Xs({type:Rt.UpdateError,crdt:e.crdtType,roomId:t,code:Ei.AppError,message:d.message}))}});let{room:l,handler:f}=VMe({client:this,roomId:t,crdtType:e.crdtType,crdtAdaptor:e});return this.registerActiveRoom(t,e.crdtType,l,f,e),e.handleJoinOk(c).catch(d=>{console.error(d)}),l});return this.pendingRooms.set(n,{room:u,resolve:o,reject:a,adaptor:e,roomId:t,auth:r}),this.roomAuth.set(n,r),this.ws.send(Xs({type:Rt.JoinRequest,crdt:e.crdtType,roomId:t,auth:r??new Uint8Array,version:e.getVersion()})),u}close(){if(this.shouldReconnect=!1,this.clearReconnectTimer(),this.clearPingTimer(),this.reconnectAttempts=0,this.rejectConnected?.(new Error("Disconnected")),this.rejectConnected=void 0,this.resolveConnected=void 0,this.rejectAllPingWaiters(new Error("Disconnected")),this.fragmentBatches.size){for(let[,e]of this.fragmentBatches)try{clearTimeout(e.timeoutId)}catch{}this.fragmentBatches.clear()}this.awaitingPongSince=void 0;let t=this.ws;t&&this.socketListeners.has(t)&&this.ops.onWsClose?.(),this.detachSocketListeners(t),this.flushAndCloseWebSocket(t,{code:1e3,reason:"Client closed"}),this.setStatus(Fu.Disconnected)}sendUpdateOrFragments(t,e,r){let n=this.ws;if(!n||n.readyState!==WebSocket.OPEN)return;let i=Math.max(1,Math.min(240*1024,258048));if(r.length<=i){n.send(Xs({type:Rt.DocUpdate,crdt:t,roomId:e,updates:[r]}));return}let s=Math.ceil(r.length/i),o=new Uint8Array(8);crypto.getRandomValues(o);let a=D_(o),u={type:Rt.DocUpdateFragmentHeader,crdt:t,roomId:e,batchId:a,fragmentCount:s,totalSizeBytes:r.length};n.send(Xs(u));for(let c=0;c<s;c++){let l=c*i,f=Math.min(l+i,r.length),d=r.subarray(l,f),p={type:Rt.DocUpdateFragment,crdt:t,roomId:e,batchId:a,index:c,fragment:d};n.send(Xs(p))}}sendLeave(t,e){!this.ws||this.ws.readyState!==WebSocket.OPEN||this.ws.send(Xs({type:Rt.Leave,crdt:t,roomId:e}))}destroy(){if(this.shouldReconnect=!1,this.clearReconnectTimer(),this.clearPingTimer(),this.reconnectAttempts=0,this.rejectConnected?.(new Error("Destroyed")),this.rejectConnected=void 0,this.resolveConnected=void 0,this.rejectAllPingWaiters(new Error("Destroyed")),this.fragmentBatches.size){for(let[,e]of this.fragmentBatches)try{clearTimeout(e.timeoutId)}catch{}this.fragmentBatches.clear()}this.awaitingPongSince=void 0;let t=this.ws;t&&this.socketListeners.has(t)&&this.ops.onWsClose?.(),this.detachSocketListeners(t);try{this.removeNetworkListeners?.()}catch{}this.removeNetworkListeners=void 0;try{this.flushAndCloseWebSocket(t,{code:1e3,reason:"Client destroyed"})}catch{}this.setStatus(Fu.Disconnected)}flushAndCloseWebSocket(t,e){if(!t)return;let{code:r,reason:n,timeoutMs:i=2e3}=e??{},s=()=>{let c=Reflect.get(t,"bufferedAmount");return typeof c=="number"?c:void 0};if(s()==null){try{t.close(r,n)}catch{}return}let o=Date.now(),a=!1,u=()=>{if(a)return;let c=t.readyState;if(c===WebSocket.CLOSED||c===WebSocket.CLOSING){a=!0;try{t.close(r,n)}catch{}return}let l=s();if(l==null||l<=0||Date.now()-o>=i){a=!0;try{t.close(r,n)}catch{}return}setTimeout(u,25)};u()}detachSocketListeners(t){if(!t)return;let e=this.socketListeners.get(t);if(e){try{t.removeEventListener?.("open",e.open),t.removeEventListener?.("error",e.error),t.removeEventListener?.("close",e.close),t.removeEventListener?.("message",e.message)}catch{}this.socketListeners.delete(t)}}startPingTimer(){let t=WMe(this.ops);t&&(this.clearPingTimer(),this.pingTimer=setInterval(()=>{try{this.ws&&this.ws.readyState===WebSocket.OPEN&&this.awaitingPongSince==null&&(this.awaitingPongSince=Date.now(),this.ws.send("ping"))}catch{}},t))}clearPingTimer(){this.pingTimer&&clearInterval(this.pingTimer),this.pingTimer=void 0}handlePong(){if(this.awaitingPongSince!=null){let t=Date.now()-this.awaitingPongSince;if(t>=0&&isFinite(t)){this.lastLatencyMs=t;let e=Array.from(this.latencyListeners);for(let r of e)try{r(t)}catch{}}this.awaitingPongSince=void 0}if(this.pingWaiters.length>0){let t=this.pingWaiters.splice(0,this.pingWaiters.length);for(let e of t)e.resolve()}}rejectAllPingWaiters(t){for(;this.pingWaiters.length;){let e=this.pingWaiters.shift();try{clearTimeout(e.timeoutId),e.reject(t)}catch{}}}},$Me=class{constructor(t){this.destroyed=!1,this.unsubscribe=[],this.client=t.client,this.roomId=t.roomId,this.crdtType=t.crdtType,this.crdtAdaptor=t.crdtAdaptor}async waitForReachingServerVersion(){return this.crdtAdaptor.waitForReachingServerVersion()}handleDocUpdate(t){this.crdtAdaptor.applyUpdate(t)}handleUpdateError(t){this.crdtAdaptor.handleUpdateError?.(t)}async leave(){this.destroyed||this.client.sendLeave(this.crdtType,this.roomId)}async destroy(){this.destroyed||(await this.leave(),this.destroyed=!0,this.crdtAdaptor.destroy(),this.unsubscribe.forEach(t=>{t()}),this.unsubscribe=[],this.client.cleanupRoom(this.roomId,this.crdtType))}};function HMe(t){return typeof t=="number"&&isFinite(t)&&t>0}function WMe(t){if(t.disablePing)return;let e=t.pingIntervalMs;return HMe(e)?e:3e4}function VMe(t){let e=new $Me(t);return{room:e,handler:e}}var zee=qe(h0());var nR={};nb(nR,{createValueFromSchema:()=>YMe,getDefaultValue:()=>P_,isContainerSchema:()=>Bu,isListLikeSchema:()=>tR,isLoroListSchema:()=>Pu,isLoroMapSchema:()=>Ru,isLoroMovableListSchema:()=>Nu,isLoroTextSchema:()=>rR,isLoroTreeSchema:()=>no,isRootSchemaType:()=>N_,schema:()=>Ee,validateSchema:()=>fd});var Mn="$cid";function ro(t,e){!Sn(t)||Object.prototype.hasOwnProperty.call(t,Mn)||Object.defineProperty(t,Mn,{value:e})}function Sn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date)&&!(t instanceof RegExp)&&typeof t!="function"}function Fa(t,e){if(t===e)return!0;if(t===null||e===null||typeof t!="object"&&typeof t!="function"||typeof e!="object"&&typeof e!="function")return!1;if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(!Fa(t[r],e[r]))return!1;return!0}if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(t instanceof RegExp&&e instanceof RegExp)return t.toString()===e.toString();if(!Array.isArray(t)&&!Array.isArray(e)){let r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(let i of r)if(!Object.prototype.hasOwnProperty.call(e,i)||!Fa(t[i],e[i]))return!1;return!0}return!1}function uZ(t){return t.split(":")[2]}function F_(t,e,r){if(r==="Text")return t.getText(e);if(r==="List")return t.getList(e);if(r==="MovableList")return t.getMovableList(e);if(r==="Map")return t.getMap(e);if(r==="Tree")return t.getTree(e);throw new Error}function XF(t,e,r){return Sn(r)?{container:t,key:e,value:r,kind:"insert-container",childContainerType:"Map"}:Array.isArray(r)?{container:t,key:e,value:r,kind:"insert-container",childContainerType:"List"}:{container:t,key:e,value:r,kind:"insert"}}function bl(t,e,r){if(!e||t.kind!=="insert"&&t.kind!=="set")return t;let n=r?xl(r)??El(t.value):void 0;return n==null?t:t.kind==="insert"?{container:t.container,key:t.key,value:t.value,kind:"insert-container",childContainerType:n}:t.kind==="set"?{container:t.container,key:t.key,value:t.value,kind:"set-container",childContainerType:n}:t}function xl(t){let e=t.getContainerType();return e===null?void 0:e}function El(t,e){if(Sn(t))return"Map";if(Array.isArray(t))return e?.defaultMovableList?"MovableList":"List";if(typeof t=="string")return e?.defaultLoroText?"Text":void 0}function Ra(t,e){switch(t){case"MovableList":case"List":return typeof e=="object"&&Array.isArray(e);case"Map":return typeof e=="object"&&e!==null;case"Text":return typeof e=="string"&&e!==null;case"Tree":return typeof e=="object"&&Array.isArray(e);default:return!1}}function cZ(t,e){if(Sn(t))return"loro-map";if(Array.isArray(t))return e?.defaultMovableList?"loro-movable-list":"loro-list";if(typeof t=="string"){if(e?.defaultLoroText)return"loro-text"}else return}function ZF(t){return typeof t=="object"}function KS(t){return Array.isArray(t)}function lZ(t){return typeof t=="string"}function ld(t,e,r){return e(t.oldState)&&e(t.newState)&&(!t.schema||r(t.schema))}function R_(t){if(typeof t!="string")return!1;let e=/[0-9]+@[0-9]+/;return!!t.match(e)}var eR=new WeakMap;function fZ(t){return typeof t=="object"&&t!==null}function zMe(t,e){return fZ(e)?eR.get(e)?.has(t)??!1:!1}function GMe(t,e){if(!fZ(e))return;let r=eR.get(e);r||(r=new WeakSet,eR.set(e,r)),r.add(t)}function Ru(t){return t.type==="loro-map"}function Pu(t){return t.type==="loro-list"}function tR(t){return Pu(t)||Nu(t)}function Nu(t){return t.type==="loro-movable-list"}function N_(t){return t.type==="schema"}function rR(t){return t.type==="loro-text"}function no(t){return t.type==="loro-tree"}function Bu(t){return!!t&&(t.type==="loro-map"||t.type==="loro-list"||t.type==="loro-text"||t.type==="loro-movable-list"||t.type==="loro-tree")}function fd(t,e){let r=[];if(t.options.required&&e==null)return r.push("Value is required"),{valid:!1,errors:r};if(e==null)return{valid:!0};if(zMe(t,e))return{valid:!0};switch(t.type){case"string":typeof e!="string"&&r.push("Value must be a string");break;case"number":typeof e!="number"&&r.push("Value must be a number");break;case"boolean":typeof e!="boolean"&&r.push("Value must be a boolean");break;case"ignore":break;case"loro-text":typeof e!="string"&&r.push("Content must be a string");break;case"loro-map":if(!Sn(e))r.push("Value must be an object");else if(Ru(t)){for(let n in t.definition)if(Object.prototype.hasOwnProperty.call(t.definition,n)){let i=t.definition[n],s=e[n],o=fd(i,s);if(!o.valid&&o.errors){let a=o.errors.map(u=>`${n}: ${u}`);r.push(...a)}}}break;case"loro-movable-list":case"loro-list":if(!Array.isArray(e))r.push("Value must be an array");else if(Pu(t)||Nu(t)){let n=t.itemSchema;e.forEach((i,s)=>{let o=fd(n,i);if(!o.valid&&o.errors){let a=o.errors.map(u=>`Item ${s}: ${u}`);r.push(...a)}})}break;case"loro-tree":{if(!Array.isArray(e)){r.push("Value must be an array of tree nodes");break}if(!no(t)){r.push("Invalid tree schema");break}let n=(i,s)=>{if(!Sn(i)){r.push(`${s}: Node must be an object`);return}let o=i;o.id!=null&&typeof o.id!="string"&&r.push(`${s}: id must be a string if provided`);let a=fd(t.nodeSchema,o.data);!a.valid&&a.errors&&r.push(...a.errors.map(u=>`${s}.data: ${u}`)),Array.isArray(o.children)?o.children.forEach((u,c)=>{n(u,`${s}.children[${c}]`)}):r.push(`${s}: children must be an array`)};e.forEach((i,s)=>{n(i,`node[${s}]`)});break}case"schema":if(!Sn(e))r.push("Value must be an object");else if(N_(t))if(!Sn(e))r.push("Value must be an object");else{for(let n in t.definition)if(Object.prototype.hasOwnProperty.call(t.definition,n)){let i=t.definition[n],s=e[n],o=fd(i,s);if(!o.valid&&o.errors){let a=o.errors.map(u=>`${n}: ${u}`);r.push(...a)}}for(let n in e)Object.prototype.hasOwnProperty.call(t.definition,n)||r.push(`Unknown property: ${n}`)}else r.push(`Should be a schema, but got ${t.type}`);break;default:r.push(`Unknown schema type: ${t.type}`)}if(t.options.validate&&typeof t.options.validate=="function")try{let n=t.options.validate(e);if(n!==!0){let i=typeof n=="string"?n:"Value failed custom validation";r.push(i)}}catch(n){r.push(`Validation error: ${String(n)}`)}return r.length===0?(GMe(t,e),{valid:!0}):{valid:!1,errors:r}}function P_(t){if("defaultValue"in t.options)return t.options.defaultValue;switch(t.type){case"string":{let r=t.options.required?"":void 0;return r===void 0?void 0:r}case"number":{let r=t.options.required?0:void 0;return r===void 0?void 0:r}case"boolean":{let r=t.options.required?!1:void 0;return r===void 0?void 0:r}case"loro-text":{let r=t.options.required?"":void 0;return r===void 0?void 0:r}case"loro-map":{if(Ru(t)){let r={};for(let n in t.definition)if(Object.prototype.hasOwnProperty.call(t.definition,n)){let i=P_(t.definition[n]);i!==void 0&&(r[n]=i)}return r}return{}}case"loro-list":return[];case"loro-tree":{let r=t.options.required?[]:void 0;return r===void 0?void 0:r}case"schema":{if(N_(t)){let r={};for(let n in t.definition)if(Object.prototype.hasOwnProperty.call(t.definition,n)){let i=P_(t.definition[n]);i!==void 0&&(r[n]=i)}return r}return{}}default:return}}function YMe(t,e){let r=t.type;return e}function Ee(t,e){return{type:"schema",definition:t,options:e||{},getContainerType(){return"Map"}}}Ee.String=function(t){return{type:"string",options:t||{},getContainerType:()=>null}};Ee.Number=function(t){return{type:"number",options:t||{},getContainerType:()=>null}};Ee.Boolean=function(t){return{type:"boolean",options:t||{},getContainerType:()=>null}};Ee.Ignore=function(t){return{type:"ignore",options:t||{},getContainerType:()=>null}};Ee.LoroMap=function(t,e){let r={type:"loro-map",definition:t,options:e||{},getContainerType:()=>"Map"},n={...r,catchall:i=>({...r,catchallType:i,catchall:s=>({...r,catchallType:s,catchall:n.catchall})})};return n};Ee.LoroMapRecord=function(t,e){return{type:"loro-map",definition:{},catchallType:t,options:e||{},getContainerType:()=>"Map",catchall:r=>Ee.LoroMapRecord(r,e)}};Ee.LoroList=function(t,e,r){return{type:"loro-list",itemSchema:t,idSelector:e,options:r||{},getContainerType:()=>"List"}};Ee.LoroMovableList=function(t,e,r){return{type:"loro-movable-list",itemSchema:t,idSelector:e,options:r||{},getContainerType:()=>"MovableList"}};Ee.LoroText=function(t){return{type:"loro-text",options:t||{},getContainerType:()=>"Text"}};Ee.LoroTree=function(t,e){return{type:"loro-tree",nodeSchema:t,options:e||{},getContainerType(){return"Tree"}}};var vR={};nb(vR,{Mirror:()=>_d,SyncDirection:()=>gd,toNormalizedJson:()=>o2});var _Z=Symbol.for("immer-nothing"),dZ=Symbol.for("immer-draftable"),Ds=Symbol.for("immer-state"),QMe=process.env.NODE_ENV!=="production"?[function(t){return`The plugin for '${t}' has not been loaded into Immer. To enable the plugin, import and call \`enable${t}()\` when initializing your application.`},function(t){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${t}'`},"This object has been frozen and should not be mutated",function(t){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+t},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(t){return`'current' expects a draft, got: ${t}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(t){return`'original' expects a draft, got: ${t}`}]:[];function ts(t,...e){if(process.env.NODE_ENV!=="production"){let r=QMe[t],n=typeof r=="function"?r.apply(null,e):r;throw new Error(`[Immer] ${n}`)}throw new Error(`[Immer] minified error nr: ${t}. Full error at: https://bit.ly/3cXEKWf`)}var p0=Object.getPrototypeOf;function m0(t){return!!t&&!!t[Ds]}function hd(t){return t?yZ(t)||Array.isArray(t)||!!t[dZ]||!!t.constructor?.[dZ]||L_(t)||r2(t):!1}var KMe=Object.prototype.constructor.toString();function yZ(t){if(!t||typeof t!="object")return!1;let e=p0(t);if(e===null)return!0;let r=Object.hasOwnProperty.call(e,"constructor")&&e.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===KMe}function XS(t,e){t2(t)===0?Reflect.ownKeys(t).forEach(r=>{e(r,t[r],t)}):t.forEach((r,n)=>e(n,r,t))}function t2(t){let e=t[Ds];return e?e.type_:Array.isArray(t)?1:L_(t)?2:r2(t)?3:0}function oR(t,e){return t2(t)===2?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function vZ(t,e,r){let n=t2(t);n===2?t.set(e,r):n===3?t.add(r):t[e]=r}function JMe(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}function L_(t){return t instanceof Map}function r2(t){return t instanceof Set}function dd(t){return t.copy_||t.base_}function aR(t,e){if(L_(t))return new Map(t);if(r2(t))return new Set(t);if(Array.isArray(t))return Array.prototype.slice.call(t);let r=yZ(t);if(e===!0||e==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(t);delete n[Ds];let i=Reflect.ownKeys(n);for(let s=0;s<i.length;s++){let o=i[s],a=n[o];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(n[o]={configurable:!0,writable:!0,enumerable:a.enumerable,value:t[o]})}return Object.create(p0(t),n)}else{let n=p0(t);if(n!==null&&r)return{...t};let i=Object.create(n);return Object.assign(i,t)}}function hR(t,e=!1){return n2(t)||m0(t)||!hd(t)||(t2(t)>1&&Object.defineProperties(t,{set:{value:JS},add:{value:JS},clear:{value:JS},delete:{value:JS}}),Object.freeze(t),e&&Object.values(t).forEach(r=>hR(r,!0))),t}function JS(){ts(2)}function n2(t){return Object.isFrozen(t)}var XMe={};function pd(t){let e=XMe[t];return e||ts(0,t),e}var B_;function bZ(){return B_}function ZMe(t,e){return{drafts_:[],parent_:t,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function hZ(t,e){e&&(pd("Patches"),t.patches_=[],t.inversePatches_=[],t.patchListener_=e)}function uR(t){cR(t),t.drafts_.forEach(eLe),t.drafts_=null}function cR(t){t===B_&&(B_=t.parent_)}function pZ(t){return B_=ZMe(B_,t)}function eLe(t){let e=t[Ds];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function mZ(t,e){e.unfinalizedDrafts_=e.drafts_.length;let r=e.drafts_[0];return t!==void 0&&t!==r?(r[Ds].modified_&&(uR(e),ts(4)),hd(t)&&(t=ZS(e,t),e.parent_||e2(e,t)),e.patches_&&pd("Patches").generateReplacementPatches_(r[Ds].base_,t,e.patches_,e.inversePatches_)):t=ZS(e,r,[]),uR(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),t!==_Z?t:void 0}function ZS(t,e,r){if(n2(e))return e;let n=e[Ds];if(!n)return XS(e,(i,s)=>gZ(t,n,e,i,s,r)),e;if(n.scope_!==t)return e;if(!n.modified_)return e2(t,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let i=n.copy_,s=i,o=!1;n.type_===3&&(s=new Set(i),i.clear(),o=!0),XS(s,(a,u)=>gZ(t,n,i,a,u,r,o)),e2(t,i,!1),r&&t.patches_&&pd("Patches").generatePatches_(n,r,t.patches_,t.inversePatches_)}return n.copy_}function gZ(t,e,r,n,i,s,o){if(process.env.NODE_ENV!=="production"&&i===r&&ts(5),m0(i)){let a=s&&e&&e.type_!==3&&!oR(e.assigned_,n)?s.concat(n):void 0,u=ZS(t,i,a);if(vZ(r,n,u),m0(u))t.canAutoFreeze_=!1;else return}else o&&r.add(i);if(hd(i)&&!n2(i)){if(!t.immer_.autoFreeze_&&t.unfinalizedDrafts_<1)return;ZS(t,i),(!e||!e.scope_.parent_)&&typeof n!="symbol"&&(L_(r)?r.has(n):Object.prototype.propertyIsEnumerable.call(r,n))&&e2(t,i)}}function e2(t,e,r=!1){!t.parent_&&t.immer_.autoFreeze_&&t.canAutoFreeze_&&hR(e,r)}function tLe(t,e){let r=Array.isArray(t),n={type_:r?1:0,scope_:e?e.scope_:bZ(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:t,draft_:null,copy_:null,revoke_:null,isManual_:!1},i=n,s=pR;r&&(i=[n],s=M_);let{revoke:o,proxy:a}=Proxy.revocable(i,s);return n.draft_=a,n.revoke_=o,a}var pR={get(t,e){if(e===Ds)return t;let r=dd(t);if(!oR(r,e))return rLe(t,r,e);let n=r[e];return t.finalized_||!hd(n)?n:n===iR(t.base_,e)?(sR(t),t.copy_[e]=fR(n,t)):n},has(t,e){return e in dd(t)},ownKeys(t){return Reflect.ownKeys(dd(t))},set(t,e,r){let n=xZ(dd(t),e);if(n?.set)return n.set.call(t.draft_,r),!0;if(!t.modified_){let i=iR(dd(t),e),s=i?.[Ds];if(s&&s.base_===r)return t.copy_[e]=r,t.assigned_[e]=!1,!0;if(JMe(r,i)&&(r!==void 0||oR(t.base_,e)))return!0;sR(t),lR(t)}return t.copy_[e]===r&&(r!==void 0||e in t.copy_)||Number.isNaN(r)&&Number.isNaN(t.copy_[e])||(t.copy_[e]=r,t.assigned_[e]=!0),!0},deleteProperty(t,e){return iR(t.base_,e)!==void 0||e in t.base_?(t.assigned_[e]=!1,sR(t),lR(t)):delete t.assigned_[e],t.copy_&&delete t.copy_[e],!0},getOwnPropertyDescriptor(t,e){let r=dd(t),n=Reflect.getOwnPropertyDescriptor(r,e);return n&&{writable:!0,configurable:t.type_!==1||e!=="length",enumerable:n.enumerable,value:r[e]}},defineProperty(){ts(11)},getPrototypeOf(t){return p0(t.base_)},setPrototypeOf(){ts(12)}},M_={};XS(pR,(t,e)=>{M_[t]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});M_.deleteProperty=function(t,e){return process.env.NODE_ENV!=="production"&&isNaN(parseInt(e))&&ts(13),M_.set.call(this,t,e,void 0)};M_.set=function(t,e,r){return process.env.NODE_ENV!=="production"&&e!=="length"&&isNaN(parseInt(e))&&ts(14),pR.set.call(this,t[0],e,r,t[0])};function iR(t,e){let r=t[Ds];return(r?dd(r):t)[e]}function rLe(t,e,r){let n=xZ(e,r);return n?"value"in n?n.value:n.get?.call(t.draft_):void 0}function xZ(t,e){if(!(e in t))return;let r=p0(t);for(;r;){let n=Object.getOwnPropertyDescriptor(r,e);if(n)return n;r=p0(r)}}function lR(t){t.modified_||(t.modified_=!0,t.parent_&&lR(t.parent_))}function sR(t){t.copy_||(t.copy_=aR(t.base_,t.scope_.immer_.useStrictShallowCopy_))}var nLe=class{constructor(t){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,r,n)=>{if(typeof e=="function"&&typeof r!="function"){let s=r;r=e;let o=this;return function(u=s,...c){return o.produce(u,l=>r.call(this,l,...c))}}typeof r!="function"&&ts(6),n!==void 0&&typeof n!="function"&&ts(7);let i;if(hd(e)){let s=pZ(this),o=fR(e,void 0),a=!0;try{i=r(o),a=!1}finally{a?uR(s):cR(s)}return hZ(s,n),mZ(i,s)}else if(!e||typeof e!="object"){if(i=r(e),i===void 0&&(i=e),i===_Z&&(i=void 0),this.autoFreeze_&&hR(i,!0),n){let s=[],o=[];pd("Patches").generateReplacementPatches_(e,i,s,o),n(s,o)}return i}else ts(1,e)},this.produceWithPatches=(e,r)=>{if(typeof e=="function")return(o,...a)=>this.produceWithPatches(o,u=>e(u,...a));let n,i;return[this.produce(e,r,(o,a)=>{n=o,i=a}),n,i]},typeof t?.autoFreeze=="boolean"&&this.setAutoFreeze(t.autoFreeze),typeof t?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(t.useStrictShallowCopy)}createDraft(t){hd(t)||ts(8),m0(t)&&(t=iLe(t));let e=pZ(this),r=fR(t,void 0);return r[Ds].isManual_=!0,cR(e),r}finishDraft(t,e){let r=t&&t[Ds];(!r||!r.isManual_)&&ts(9);let{scope_:n}=r;return hZ(n,e),mZ(void 0,n)}setAutoFreeze(t){this.autoFreeze_=t}setUseStrictShallowCopy(t){this.useStrictShallowCopy_=t}applyPatches(t,e){let r;for(r=e.length-1;r>=0;r--){let i=e[r];if(i.path.length===0&&i.op==="replace"){t=i.value;break}}r>-1&&(e=e.slice(r+1));let n=pd("Patches").applyPatches_;return m0(t)?n(t,e):this.produce(t,i=>n(i,e))}};function fR(t,e){let r=L_(t)?pd("MapSet").proxyMap_(t,e):r2(t)?pd("MapSet").proxySet_(t,e):tLe(t,e);return(e?e.scope_:bZ()).drafts_.push(r),r}function iLe(t){return m0(t)||ts(10,t),EZ(t)}function EZ(t){if(!hd(t)||n2(t))return t;let e=t[Ds],r;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,r=aR(t,e.scope_.immer_.useStrictShallowCopy_)}else r=aR(t,!0);return XS(r,(n,i)=>{vZ(r,n,EZ(i))}),e&&(e.finalized_=!1),r}var dR=new nLe,q_=dR.produce;var wZ=dR.setAutoFreeze.bind(dR);var Ln=qe(h0(),1);var mR=qe(h0(),1);function md(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function U_(t){return Array.isArray(t)}function DZ(t,e,r){let n=typeof r=="function"?{getContainerById:r}:r||{};return q_(s=>{let o=new Set;for(let a of e.events)sLe(s,a,o,n.getContainerById,n.containerToJson,n.nodeDataWithCid,n.getNodeDataCid)})(t)}function sLe(t,e,r,n,i,s,o){if(pLe(e.target,r,n))return;let{parent:a,key:u,node:c}=oLe(t,e.path),l=c;if(l===void 0)if(e.diff.type==="map")a&&u!==void 0&&Pa(a,u,{}),l=a&&u!==void 0?wl(a,u):t;else if(e.diff.type==="list")a&&u!==void 0&&Pa(a,u,[]),l=a&&u!==void 0?wl(a,u):t;else if(e.diff.type==="text")a&&u!==void 0&&Pa(a,u,""),l=a&&u!==void 0?wl(a,u):t;else if(e.diff.type==="tree")a&&u!==void 0&&Pa(a,u,[]),l=a&&u!==void 0?wl(a,u):t;else if(e.diff.type==="counter")a&&u!==void 0&&Pa(a,u,0),l=a&&u!==void 0?wl(a,u):t;else{console.error("Unknown diff type:",e.diff);return}switch(e.diff.type){case"map":md(l)||(a&&u!==void 0&&Pa(a,u,{}),l=a&&u!==void 0?wl(a,u):t),md(l)&&cLe(l,e.diff.updated,r,i);break;case"list":U_(l)||(a&&u!==void 0&&Pa(a,u,[]),l=a&&u!==void 0?wl(a,u):[]),U_(l)&&lLe(l,e.diff.diff,r,i);break;case"text":{let d=hLe(typeof l=="string"?l:"",e.diff.diff);a&&u!==void 0&&Pa(a,u,d);break}case"tree":U_(l)||(a&&u!==void 0&&Pa(a,u,[]),l=a&&u!==void 0?wl(a,u):[]),U_(l)&&(fLe(l,e.diff.diff,e.target,s,o),s2.delete(l));break;case"counter":if(a&&u!==void 0){let d=(typeof l=="number"?l:0)+(e.diff.increment??0);Pa(a,u,d)}break}}function oLe(t,e){if(!e||e.length===0)return{parent:void 0,key:void 0,node:t};let r,n=t,i;for(let s=0;s<e.length;s++){let o=e[s];if(r=U_(n)||md(n)?n:void 0,i=o,typeof o=="number")Array.isArray(r)?n=r[o]:n=void 0;else if(typeof o=="string"){let a=o;if(r&&Array.isArray(r)&&R_(o)){let c=aLe(r,o);c?(s===e.length-1&&(r=c.node,i="data"),n=CZ(c.node)):n=void 0}else r&&!Array.isArray(r)?n=r[a]:n=void 0}else throw new Error(`Unsupported path segment: ${String(o)}`)}return{parent:r,key:i,node:n}}function aLe(t,e){let r=s2.get(t);r||(r=SZ(t),s2.set(t,r));let n=r.get(e);return n||(r=SZ(t),s2.set(t,r),n=r.get(e)),n}function SZ(t){let e=new Map,r=[];for(let n=0;n<t.length;n++)r.push({list:t,index:n});for(;r.length;){let n=r.pop();if("list"in n){let i=n.list[n.index];if(!md(i))continue;let s=i,o=s.id;typeof o=="string"&&e.set(o,{list:n.list,index:n.index,node:s});let a=s.children;if(Array.isArray(a))for(let u=0;u<a.length;u++)r.push({list:a,index:u})}}return e}function CZ(t){let e=t.data;if(md(e))return e;let r={};return t.data=r,r}function uLe(t){return Array.isArray(t)?t.map(AZ):[]}function AZ(t){let e=t?.id,r=typeof e=="string"?e:"",n=t?.meta,i=md(n)?n:{},s=t?.children,o=Array.isArray(s)?s.map(AZ):[];return{id:r,data:i,children:o}}function cLe(t,e,r,n){if(md(t))for(let[i,s]of Object.entries(e)){if(s===void 0){delete t[i];continue}if((0,mR.isContainer)(s)){let o=s;r.add(o.id),t[i]=n?n(o):IZ(o);continue}t[i]=s}}function lLe(t,e,r,n){let i=0;for(let s of e)if(s.retain!==void 0)i+=s.retain;else if(s.delete!==void 0){let o=s.delete;o>0&&t.splice(i,o)}else if(s.insert!==void 0){let o=s.insert.map(a=>{if((0,mR.isContainer)(a)){let u=a;return r.add(u.id),n?n(u):IZ(u)}return a});t.splice(i,0,...o),i+=o.length}}function fLe(t,e,r,n,i){let s=o=>{if(!o)return t;let a=dLe(t,o);return a?a.node.children:t};for(let o of e)if(o.action==="create"){let a=s(o.parent),u={id:o.target,data:{},children:[]};if(r&&n?.(r)){let l=i?.(r,o.target);l&&ro(u.data,l)}let c=i2(o.index,a.length+1);a.splice(c,0,u)}else if(o.action==="delete"){let a=s(o.oldParent);if(!a)continue;let u=i2(o.oldIndex,a.length);if(u>=0&&u<a.length)a.splice(u,1);else{let c=a.findIndex(l=>l.id===o.target);c>=0&&a.splice(c,1)}}else if(o.action==="move"){let a=s(o.oldParent),u=i2(o.oldIndex,a.length),c;if(u>=0&&u<a.length)c=a.splice(u,1)[0];else{let d=a.findIndex(p=>p.id===o.target);d>=0&&(c=a.splice(d,1)[0])}if(!c)continue;let l=s(o.parent),f=i2(o.index,l.length+1);l.splice(f,0,c)}}function i2(t,e){return t<0?0:t>e?e:t}function dLe(t,e){let r=[{parent:void 0,list:t}];for(;r.length;){let{parent:n,list:i}=r.pop();for(let s=0;s<i.length;s++){let o=i[s];if(o&&o.id===e)return{parent:n,node:o};o&&Array.isArray(o.children)&&r.push({parent:o,list:o.children})}}}function hLe(t,e){if(e.length===0)return t;let r=t,n="",i=0;for(let s of e)s.retain!==void 0?(n+=r.slice(i,i+s.retain),i+=s.retain):s.delete!==void 0?i+=s.delete:s.insert!==void 0&&(n+=s.insert??"");return i<r.length&&(n+=r.slice(i)),n}function Pa(t,e,r){(Array.isArray(t)&&typeof e=="number"||!Array.isArray(t)&&typeof e=="string")&&(t[e]=r)}function wl(t,e){if(Array.isArray(t)&&typeof e=="number")return t[e];if(!Array.isArray(t)&&typeof e=="string")return t[e]}var s2=new WeakMap;function IZ(t){let e=t.kind();if(e==="Counter")return t.getShallowValue();if(e==="Tree"){let r=t.toJSON();return uLe(r)}return t.toJSON()}function pLe(t,e,r){if(e.has(t))return!0;if(!r)return!1;let i=r(t);for(;i;){let s=i.parent();if(!s)break;if(e.has(s.id))return!0;i=s}return!1}var j_=qe(h0(),1);function TZ(t,e){if(t){if(t.type==="schema")return t.definition[e];if(t.type==="loro-map"){if(Object.prototype.hasOwnProperty.call(t.definition,e))return t.definition[e];let r=t;if(r.catchallType)return r.catchallType}}}function Sl(t,e,r,n,i,s){let o={oldState:e,newState:r,schema:i};if(n===""){if(!ld(o,ZF,N_))throw console.log("stateAndSchema:",o),new Error("Failed to diff container. Old and new state must be objects");return kZ(t,o.oldState,o.newState,n,o.schema,s)}let a=uZ(n),u=[],c;switch(a){case"Map":if(!ld(o,ZF,Ru))throw console.log("stateAndSchema:",o),new Error("Failed to diff container(map). Old and new state must be objects");u=kZ(t,o.oldState,o.newState,n,o.schema,s);break;case"List":if(!ld(o,KS,Pu))throw new Error("Failed to diff container(list). Old and new state must be arrays");c=o.schema?.idSelector,c?u=_Le(t,o.oldState,o.newState,n,o.schema,c,s):u=yLe(t,e,r,n,i,s);break;case"MovableList":if(!ld(o,KS,Nu))throw new Error("Failed to diff container(movable list). Old and new state must be arrays");if(c=o.schema?.idSelector,!c)throw new Error("Movable list schema must have an idSelector");u=gLe(t,o.oldState,o.newState,n,o.schema,c,s);break;case"Text":if(!ld(o,lZ,rR))throw new Error("Failed to diff container(text). Old and new state must be strings");u=mLe(o.oldState,o.newState,n);break;case"Tree":if(!ld(o,KS,no))throw new Error("Failed to diff container(tree). Old and new state must be arrays");u=gR(t,o.oldState,o.newState,n,o.schema,s);break;default:throw new Error(`Unsupported container type: ${a}`)}return u}function mLe(t,e,r){return e===t?[]:[{container:r,key:"",value:e,kind:"insert"}]}function gR(t,e,r,n,i,s){let o=[];if(e===r)return o;let a=v=>v,u=a(e),c=a(r),l=new Map,f=new Map;function d(v,E,A){for(let F=0;F<v.length;F++){let D=v[F];D&&typeof D=="object"&&typeof D.id=="string"&&E.set(D.id,{id:D.id,parent:A,index:F,node:D}),D&&Array.isArray(D.children)&&d(D.children,E,typeof D.id=="string"?D.id:void 0)}}d(u,l),d(c,f);let p=[];for(let[v,E]of l)f.has(v)||p.push(E);let m=v=>{let E=0,A=v.parent?l.get(v.parent):void 0;for(;A;)E++,A=A.parent?l.get(A.parent):void 0;return E};p.sort((v,E)=>m(E)-m(v));for(let v of p)o.push({container:n,kind:"tree-delete",target:v.id});function _(v,E,A){for(let F=0;F<v.length;F++){let D=v[F],U=R_(D.id)?D.id:void 0,I=!U||!l.has(U),$=[];if(I){let O={container:n,kind:"tree-create",parent:E,index:F,value:D?.data,onCreate:k=>{D.id=k;for(let P of $)P.parent=k}};o.push(O),A?.push(O)}if(D&&Array.isArray(D.children)){let O=R_(D.id)?D.id:void 0;I?_(D.children,O,$):_(D.children,O)}}}_(c,void 0);for(let[v,E]of f){let A=l.get(v);if(!A)continue;let F=(A.parent??void 0)!==(E.parent??void 0),D=A.index!==E.index;(F||D)&&o.push({container:n,kind:"tree-move",target:v,parent:E.parent,index:E.index});try{let I=t.getTree(n).getNodeByID(v);if(I&&i){let $=E.node?.data;$&&typeof $=="object"&&!(Mn in $)&&ro($,I.data.id);let O=Sl(t,A.node?.data,E.node?.data,I.data.id,i.nodeSchema,s);o.push(...O)}}catch(U){console.error(`Failed to diff node.data for node ${v}:`,U)}}return o}function gLe(t,e,r,n,i,s,o){let a=[];if(e===r)return a;let u=new Map,c=new Map,l=[];for(let[m,_]of e.entries()){let v=s(_);v&&u.set(v,{index:m,item:_})}for(let[m,_]of r.entries()){let v=s(_);if(!v)continue;if(c.has(v))throw new Error("Duplicate item id in new state");c.set(v,{index:m,item:_});let E=u.get(v);E&&l.push({id:v,oldIndex:E.index,newIndex:m,oldItem:E.item,newItem:_})}let f=[];for(let[m,{index:_}]of u)c.has(m)||f.push({container:n,key:_,value:void 0,kind:"delete"});f.sort((m,_)=>_.key-m.key),a.push(...f);let d=[];for(let m of e){let _=s(m);_&&c.has(_)&&d.push(_)}let p=l.map(m=>m.id);if(!Fa(d,p)){let m=[...d],_=new Map;m.forEach((v,E)=>_.set(v,E));for(let v=0;v<p.length;v++){let E=p[v],A=_.get(E);if(A==null||A===v)continue;a.push({container:n,key:A,value:void 0,kind:"move",fromIndex:A,toIndex:v});let[F]=m.splice(A,1);m.splice(v,0,F);let D=Math.min(A,v),U=Math.max(A,v);for(let I=D;I<=U;I++)_.set(m[I],I)}}for(let[m,_]of r.entries()){let v=s(_);(!v||!u.has(v))&&a.push(bl({container:n,key:m,value:_,kind:"insert"},!0,i?.itemSchema))}for(let m of l){if(Fa(m.oldItem,m.newItem))continue;let v=t.getMovableList(n).get(m.oldIndex);if((0,j_.isContainer)(v)){let E=Sl(t,m.oldItem,m.newItem,v.id,i?.itemSchema,o);a.push(...E)}else a.push(bl({container:n,key:m.newIndex,value:m.newItem,kind:"set"},!0,i?.itemSchema))}return a}function _Le(t,e,r,n,i,s,o){let a=[];if(e===r)return a;let u=!!(i?.itemSchema.getContainerType()??!0),c=new Map,l=new Map;for(let[_,v]of e.entries()){let E=s(v);E&&c.set(E,{item:v,index:_})}for(let[_,v]of r.entries()){let E=s(v);E&&l.set(E,{item:v,newIndex:_})}let f=t.getList(n),d=0,p=0,m=0;for(;m<e.length;){if(d>=r.length){a.push({container:n,key:m+p,value:void 0,kind:"delete"}),p--,m++;continue}let _=e[m],v=r[d];if(_===v){d++,m++;continue}let E=s(_),A=s(v);if(E===A){let F=f.get(m);(0,j_.isContainer)(F)?a.push(...Sl(t,_,v,F.id,i?.itemSchema,o)):Fa(_,v)||(a.push({container:n,key:m+p,value:void 0,kind:"delete"}),a.push(bl({container:n,key:m+p,value:v,kind:"insert"},u,i?.itemSchema))),m++,d++;continue}if(A&&!c.has(A)){a.push(bl({container:n,key:m+p,value:v,kind:"insert"},u,i?.itemSchema)),p++,d++;continue}a.push({container:n,key:m+p,value:void 0,kind:"delete"}),p--,m++}for(;d<r.length;d++){let _=r[d];a.push(bl({container:n,key:m+p,value:_,kind:"insert"},u,i?.itemSchema)),p++}return a}function yLe(t,e,r,n,i,s){if(e===r)return[];let o=[],a=e.length,u=r.length,c=t.getList(n),l=0;for(;l<a&&l<u&&e[l]===r[l];)l++;let f=0;for(;f<a-l&&f<u-l&&e[a-1-f]===r[u-1-f];)f++;let d=a-l-f,p=u-l-f,m=Math.min(d,p);for(let _=0;_<m;_++){let v=l+_;if(e[v]===r[v])continue;let E=c.get(v);if((0,j_.isContainer)(E)){let A=Sl(t,e[v],r[v],E.id,i?.itemSchema,s);o.push(...A)}else o.push({container:n,key:v,value:void 0,kind:"delete"}),o.push(bl({container:n,key:v,value:r[v],kind:"insert"},!0,i?.itemSchema))}for(let _=0;_<d-m;_++)o.push({container:n,key:l+m,value:void 0,kind:"delete"});for(let _=0;_<p-m;_++){let v=l+m+_;o.push(bl({container:n,key:v,value:r[v],kind:"insert"},!0,i?.itemSchema))}return o}function kZ(t,e,r,n,i,s){let o=[],a=e,u=r;for(let c in a){if(c===Mn)continue;let l=TZ(i,c);l&&l.type==="ignore"||c in u||o.push({container:n,key:c,value:void 0,kind:"delete"})}for(let c in u){if(c===Mn)continue;let l=a[c],f=u[c],d=TZ(i,c);if(d&&d.type==="ignore")continue;let p=d?.getContainerType()??El(f,s);if(d?.getContainerType()&&p&&!Ra(p,f)&&(console.warn(`Schema mismatch on key "${c}": expected ${d.getContainerType()} but got value ${JSON.stringify(f)}. Falling back to value-based inference to avoid divergence.`),p=El(f,s)),!(c in a)){p&&Ra(p,f)?o.push({container:n,key:c,value:f,kind:"insert-container",childContainerType:p}):o.push({container:n,key:c,value:f,kind:"insert"});continue}if(l!==f)if(p&&Ra(p,f)&&Ra(p,l)){if(n===""){let E=F_(t,c,p);p==="Map"&&f&&typeof f=="object"&&!(Mn in f)&&ro(f,E.id),o.push(...Sl(t,a[c],u[c],E.id,d,s));continue}let m=t.getContainerById(n);if(m?.kind()!=="Map")throw new Error("Expected map container");let v=m.get(c);!v||!(0,j_.isContainer)(v)?o.push(XF(n,c,u[c])):(p==="Map"&&f&&typeof f=="object"&&!(Mn in f)&&ro(f,v.id),o.push(...Sl(t,a[c],u[c],v.id,d,s)))}else o.push(XF(n,c,u[c]))}return o}wZ(!1);function vLe(t){return t.key!==void 0}var gd;(function(t){t.FROM_LORO="FROM_LORO",t.TO_LORO="TO_LORO",t.BIDIRECTIONAL="BIDIRECTIONAL"})(gd||(gd={}));var _d=class{constructor(e){this.subscribers=new Set,this.syncing=!1,this.containerRegistry=new Map,this.subscriptions=[],this.rootPathById=new Map,this.handleLoroEvent=o=>{if(!this.syncing){this.syncing=!0;try{this.registerContainersFromLoroEvent(o);let a={...o,events:o.events.map(u=>{let c=this.rootPathById.get(u.target);return c&&(!Array.isArray(u.path)||u.path[0]!==c[0])?{...u,path:c}:u})};this.state=DZ(this.state,a,{getContainerById:u=>this.doc.getContainerById(u),containerToJson:u=>this.containerToStateJson(u),nodeDataWithCid:u=>{let c=this.getContainerSchema(u);return!!(c&&no(c))},getNodeDataCid:(u,c)=>{try{let l=this.doc.getTree(u).getNodeByID(c);return l?l.data.id:void 0}catch{return}}}),this.notifySubscribers(gd.FROM_LORO)}finally{this.registerContainersFromLoroEvent(o),this.syncing=!1}}},this.doc=e.doc,this.schema=e.schema,this.options={doc:e.doc,schema:e.schema,initialState:e.initialState||{},validateUpdates:e.validateUpdates!==!1,throwOnValidationError:e.throwOnValidationError||!1,debug:e.debug||!1,checkStateConsistency:e.checkStateConsistency||!1,inferOptions:e.inferOptions||{}},this.ensureRootContainersFromInitialState();let r={},n=this.schema?P_(this.schema):void 0;n&&typeof n=="object"&&Object.assign(r,n);let i=this.buildRootStateSnapshot();i&&typeof i=="object"&&Object.assign(r,i);let s=this.options.initialState||{};if(this.schema&&this.schema.type==="schema")FZ(r,s,this.schema);else{let o=bLe(s);for(let[a,u]of Object.entries(o))a in r||(r[a]=u)}this.state=r,this.initializeContainers(),this.subscriptions.push(this.doc.subscribe(this.handleLoroEvent))}ensureRootContainersFromInitialState(){let e=this.options?.initialState||{};for(let[r,n]of Object.entries(e)){let i=null;Array.isArray(n)?i=this.doc.getList(r):typeof n=="string"?i=this.doc.getText(r):Sn(n)&&(i=this.doc.getMap(r)),i&&(this.rootPathById.set(i.id,[r]),this.registerContainerWithRegistry(i.id,void 0))}}initializeContainers(){if(this.schema&&this.schema.type!=="schema")throw new Error('Root schema must be of type "schema"');if(this.schema){for(let n in this.schema.definition)if(Object.prototype.hasOwnProperty.call(this.schema.definition,n)){let i=this.schema.definition[n];if(["loro-map","loro-list","loro-text","loro-movable-list","loro-tree"].includes(i.type)){let s=xl(i);if(!s)continue;let o=F_(this.doc,n,s);this.rootPathById.set(o.id,[n]),this.registerContainer(o.id,i)}}}let e=this.buildRootStateSnapshot(),r=q_(n=>{Object.assign(n,e)})(this.state);this.state=r}registerContainer(e,r){try{let n=this.doc.getContainerById(e);if(!n){this.options.debug&&console.warn(`registerContainer: container not found for id ${e}`);return}let i=n.id,s=this.containerRegistry.get(i);if(s){!s.schema&&r&&(s.schema=r);return}this.registerContainerWithRegistry(i,r),this.registerNestedContainers(n)}catch(n){this.options.debug&&console.error(`Error registering container: ${e}`,n)}}registerNestedContainers(e){if(!e.isAttached)return;let r=this.getContainerSchema(e.id);try{if(e.kind()==="Map"){let n=e;for(let i of n.keys()){let s=n.get(i);if((0,Ln.isContainer)(s)){let o;if(r&&Ru(r)){let a=this.getSchemaForMapKey(r,i);a&&Bu(a)&&(o=a)}this.registerContainer(s.id,o)}}}else if(e.kind()==="List"||e.kind()==="MovableList"){let n=e,i=n.length;for(let s=0;s<i;s++){let o=n.get(s);if((0,Ln.isContainer)(o)){let a;r&&(Pu(r)||Nu(r))&&(a=r.itemSchema),a&&this.registerContainer(o.id,a)}}}else if(e.kind()==="Tree"){let n=e,i;if(r&&no(r)&&(i=r.nodeSchema),i){let s=n.getNodes();for(let o of s)this.registerContainer(o.data.id,i)}}}catch(n){this.options.debug&&console.error(`Error registering nested containers for ${e.id}:`,n)}}registerContainersFromLoroEvent(e){for(let r of e.events)if(r.diff.type==="list"){let n=r.diff.diff,i=this.getContainerSchema(r.target);for(let s of n)if(s.insert){for(let o of s.insert)if((0,Ln.isContainer)(o)){let a=o,u;i&&tR(i)&&(u=i.itemSchema),this.registerContainer(a.id,u),u||console.warn(`Container schema not found for key in list ${r.target}`)}}}else if(r.diff.type==="map"){let n=r.diff.updated;for(let[i,s]of Object.entries(n)){let o=this.getSchemaForChild(r.target,i);if((0,Ln.isContainer)(s)){let a=Bu(o)?o:void 0;this.registerContainer(s.id,a),a||console.warn(`Container schema not found for key ${i} in map ${r.target}`)}}}else if(r.diff.type==="tree"){let n=this.doc.getTree(r.target),i=this.getContainerSchema(r.target),s;if(i&&no(i)&&(s=i.nodeSchema),!s)continue;for(let o of r.diff.diff)if(o.action==="create"){let a=n.getNodeByID(o.target);a&&this.registerContainer(a.data.id,s)}}}updateLoro(e,r){if(!this.syncing){this.syncing=!0;try{let n=this.state,i=Sl(this.doc,n,e,"",this.schema,this.options?.inferOptions);this.applyChangesToLoro(i,e,r)}finally{this.syncing=!1}}}applyChangesToLoro(e,r,n){let i=new Map;for(let s of e)i.has(s.container)||i.set(s.container,[]),i.get(s.container).push(s);for(let[s,o]of i.entries())if(s==="")this.applyRootChanges(o,r);else{let a=this.doc.getContainerById(s);if(a)this.applyContainerChanges(a,o,r);else throw new Error(`Container not found for ID: ${s}.
|
|
190
190
|
This is likely due to a stale reference or a synchronization issue.`)}if(e.length>0){let s;if(n){let o={};n.origin!==void 0&&(o.origin=n.origin),n.timestamp!==void 0&&(o.timestamp=n.timestamp),n.message!==void 0&&(o.message=n.message),(o.origin!==void 0||o.timestamp!==void 0||o.message!==void 0)&&(s=o)}this.doc.commit(s)}}applyRootChanges(e,r){for(let n of e){if(!vLe(n))continue;let{key:i,value:s}=n,o=i.toString(),a=this.schema?.definition?.[o],u=a?.type||cZ(s,this.options?.inferOptions),c=null;if(u==="loro-map")c=this.doc.getMap(o);else if(u==="loro-list")c=this.doc.getList(o);else if(u==="loro-text")c=this.doc.getText(o);else if(u==="loro-movable-list")c=this.doc.getMovableList(o);else if(u==="loro-tree")c=this.doc.getTree(o);else throw new Error;if(this.registerContainerWithRegistry(c.id,a),r&&c.kind()==="Map"){let f=r[o];this.stampCid(f,c.id)}this.updateTopLevelContainer(c,s)}}applyContainerChanges(e,r,n){switch(e.kind()){case"Map":{let i=e;for(let s of r){let{key:o,value:a,kind:u}=s;if(o==="")continue;let c=this.getSchemaForChild(e.id,o);if(!(c&&c.type==="ignore"))if(u==="insert")i.set(o,a);else if(u==="insert-container"){let l=this.getSchemaForChildContainer(e.id,o),f=this.insertContainerIntoMap(i,l,o,a);this.stampCid(a,f.id)}else if(u==="delete")i.delete(o);else throw new Error("Unsupported change kind for map")}break}case"List":{let i=e;for(let s of r){let{key:o,value:a,kind:u}=s;if(typeof o!="number")throw new Error(`Invalid list index: ${o}`);let c=o;if(c<0){console.warn(`Invalid list index: ${c}`);continue}if(u==="delete")i.delete(c,1);else if(u==="insert")i.insert(c,a);else if(u==="insert-container"){let l=this.getSchemaForChildContainer(e.id,o);this.insertContainerIntoList(i,l,c,a)}else throw new Error("Unsupported change kind for list")}break}case"MovableList":{let i=e;for(let s of r){let{key:o,value:a,kind:u}=s;if(typeof o!="number")throw new Error(`Invalid list index: ${o}`);let c=o;if(c<0){console.warn(`Invalid list index: ${c}`);continue}if(u==="delete")i.delete(c,1);else if(u==="insert")i.insert(c,a);else if(u==="insert-container"){let l=this.getSchemaForChildContainer(e.id,o);this.insertContainerIntoList(i,l,c,a)}else if(u==="move"){let l=s,f=l.fromIndex,d=l.toIndex;i.move(f,d)}else if(u==="set")i.set(c,a);else if(u==="set-container"){let l=this.getSchemaForChildContainer(e.id,o),[f,d]=this.createContainerFromSchema(l,a),p=i.setContainer(c,f);this.registerContainer(p.id,l),this.initializeContainer(p,l,a),this.stampCid(a,p.id)}else throw new Error}break}case"Text":{let i=e;for(let s of r){if(!("value"in s))continue;let o=s.value;typeof o=="string"&&i.update(o)}break}case"Tree":{let i=e,s,o=this.getContainerSchema(i.id);o&&no(o)&&(s=o.nodeSchema);for(let a of r)if(a.kind==="tree-create"){let u=i.createNode(a.parent,a.index);a.onCreate(u.id),s&&(this.registerContainer(u.data.id,s),this.initializeContainer(u.data,s,a.value),Ru(s)&&Sn(a.value)&&ro(a.value,u.data.id))}else a.kind==="tree-move"?i.move(a.target,a.parent,a.index):a.kind==="tree-delete"&&i.delete(a.target);break}default:console.warn(`Unsupported container type: ${e.kind()}`)}}updateTopLevelContainer(e,r){let n=e.kind();switch(n){case"Text":this.updateTextContainer(e,r);break;case"List":this.updateListContainer(e,r);break;case"Map":this.updateMapContainer(e,r);break;case"MovableList":this.updateListContainer(e,r);break;case"Tree":this.updateTreeContainer(e,r);break;default:throw new Error(`Unknown container kind for top-level update: ${n}.
|
|
191
|
-
This is likely a programming error or unsupported container type.`)}}updateTextContainer(e,r){if(typeof r!="string")throw new Error("Text value must be a string");e.update(r)}updateListContainer(e,r){if(Array.isArray(r)){let n=this.getContainerSchema(e.id);if(n&&!Pu(n)&&!Nu(n))throw new Error(`Invalid schema for list: ${n.type}. Expected LoroListSchema`);let i=n?.idSelector,s=n?.itemSchema;i?this.updateListWithIdSelector(e,r,i,s):this.updateListByIndex(e,r,s)}else throw new Error("List value must be an array")}updateListWithIdSelector(e,r,n,i){let s=new Map,o=e.length;for(let f=0;f<o;f++){let d=e.get(f);try{if(d){let p=n(d);p&&s.set(p,{item:d,index:f})}}catch(p){this.options.debug&&console.warn("Error getting ID for current list item:",p)}}let a=new Map,u=f=>{if(!f)return null;try{let d=n(f);if(d)return d}catch(d){this.options.debug&&console.warn("Error using ID selector directly:",d);let p=f.id;if(typeof p=="string")return p}return null};r.forEach((f,d)=>{try{let p=u(f);if(p)a.set(p,{item:f,index:d});else throw new Error(`Item at index ${d} has no ID`)}catch(p){this.options.debug&&console.warn(`Error getting ID for new list item at index ${d}:`,p)}});let c=[];for(let[f,{index:d}]of s.entries())a.has(f)||c.push(d);c.sort((f,d)=>d-f);for(let f of c)e.delete(f,1);let l=0;for(let f=0;f<r.length;f++){let d=r[f],p=null;try{p=u(d)}catch(_){console.warn(`Error getting ID for new item at index ${f}:`,_);continue}if(!p)continue;if(s.get(p)){let _=e.get(l);Fa(_,d)||(e.delete(l,1),this.insertItemIntoList(e,l,d,i))}else this.insertItemIntoList(e,l,d,i);l++}l<e.length&&e.delete(l,e.length-l)}updateListByIndex(e,r,n){let i=e.length,s=Math.max(i,r.length);for(let o=0;o<s;o++)if(o>=i)this.insertItemIntoList(e,o,r[o],n);else if(o>=r.length){e.delete(r.length,i-r.length);break}else{let a=e.get(o),u=r[o];Fa(a,u)||(e.delete(o,1),this.insertItemIntoList(e,o,u,n))}}insertItemIntoList(e,r,n,i){let s=!1,o;if(i&&Bu(i)?(s=!0,o=i):s=El(n,this.options?.inferOptions)!==void 0,s&&typeof n=="object"&&n!==null){this.insertContainerIntoList(e,o,r,n);return}e.insert(r,n)}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}notifySubscribers(e,r){let n={direction:e,tags:r};for(let i of this.subscribers)i(this.state,n)}dispose(){this.subscribers.clear(),this.subscriptions.forEach(e=>{e()}),this.subscriptions.length=0}insertContainerIntoMap(e,r,n,i){let[s,o]=this.createContainerFromSchema(r,i),a=e.setContainer(n,s);if(!a)throw new Error("Failed to insert container into map");return this.registerContainer(a.id,r),this.initializeContainer(a,r,i),a.kind()==="Map"&&this.stampCid(i,a.id),a}initializeContainer(e,r,n){let i=e.kind();if(i==="Map"){let s=e;if(!Sn(n))return;let o=r;for(let[a,u]of Object.entries(n)){if(a===Mn)continue;let c=this.getSchemaForMapKey(o,a);if(c&&Bu(c)){let l=xl(c);l&&Ra(l,u)?this.insertContainerIntoMap(s,c,a,u):s.set(a,u)}else s.set(a,u)}}else if(i==="List"||i==="MovableList"){let s=e;if(!Array.isArray(n))return;let o=r?.itemSchema,a=Bu(o);for(let u=0;u<n.length;u++){let c=n[u];if(a){let l=xl(o);l&&Ra(l,c)?this.insertContainerIntoList(s,o,u,c):s.insert(u,c)}else s.insert(u,c)}}else if(i==="Text")typeof n=="string"&&e.update(n);else if(i==="Tree"){let s=e;this.updateTreeContainer(s,n)}else throw new Error(`Unknown container kind: ${i}`)}createContainerFromSchema(e,r){let n=e?xl(e):El(r,this.options?.inferOptions);switch(n){case"Map":return[new Ln.LoroMap,"Map"];case"List":return[new Ln.LoroList,"List"];case"MovableList":return[new Ln.LoroMovableList,"MovableList"];case"Text":return[new Ln.LoroText,"Text"];case"Tree":return[new Ln.LoroTree,"Tree"];default:throw new Error(`Unknown schema type: ${n}`)}}insertContainerIntoList(e,r,n,i){let[s,o]=this.createContainerFromSchema(r,i),a;if(n===void 0?a=e.pushContainer(s):a=e.insertContainer(n,s),!a)throw new Error("Failed to insert container into list");return this.registerContainer(a.id,r),this.initializeContainer(a,r,i),a.kind()==="Map"&&this.stampCid(i,a.id),a}updateTreeContainer(e,r){if(!Array.isArray(r))throw new Error("Tree value must be an array of nodes");let n=yR(e.toJSON()),i=r,s=this.getContainerSchema(e.id),o=s&&no(s)?s:void 0,a=gR(this.doc,n,i,e.id,o,this.options?.inferOptions);if(a.length===0)return;let u=new Map;for(let l of a){let f=l.container,d=u.get(f);d?d.push(l):u.set(f,[l])}let c=u.get(e.id);c&&c.length&&(this.applyContainerChanges(e,c),u.delete(e.id));for(let[l,f]of u){if(l==="")continue;let d=this.doc.getContainerById(l);!d||f.length===0||this.applyContainerChanges(d,f)}}updateMapContainer(e,r){if(!Sn(r))throw new Error("Map value must be an object");let n=this.getContainerSchema(e.id);n&&Sn(r)&&ro(r,e.id);let i=new Set(e.keys());for(let[s,o]of Object.entries(r))if(s!==Mn){if(n&&n.type==="loro-map")this.updateMapEntry(e,s,o,n);else{let a=El(o,this.options?.inferOptions);a&&Ra(a,o)?this.insertContainerIntoMap(e,void 0,s,o):e.set(s,o)}i.delete(s)}for(let s of i)e.delete(s)}updateMapEntry(e,r,n,i){if(r!==Mn){if(i&&i.type==="loro-map"){let s=i,o=this.getSchemaForMapKey(s,r);if(o&&o.type==="ignore")return;if(o&&Bu(o)){let a=xl(o);if(a&&Ra(a,n)){this.insertContainerIntoMap(e,o,r,n);return}}}e.set(r,n)}}getState(){return this.state}setState(e,r){if(this.syncing)return;let n=typeof e=="function"?q_(this.state,o=>{let a=e(o);if(a&&a!==o)return a}):Object.assign({},this.state,e);if(this.options.validateUpdates){let o=this.schema&&fd(this.schema,n);if(o&&!o.valid){let a=`State validation failed: ${o.errors?.join(", ")}`;throw new Error(a)}}let i=r?.tags?Array.isArray(r.tags)?r.tags:[r.tags]:void 0;this.updateLoro(n,r),this.state=n,this.options.checkStateConsistency&&this.checkStateConsistency(),this.notifySubscribers(gd.TO_LORO,i)}checkStateConsistency(){let e=this.state;if(!Fa(e,this.buildRootStateSnapshot()))throw console.error("State diverged",JSON.stringify(e,null,2),JSON.stringify(this.buildRootStateSnapshot(),null,2)),new Error("[InternalError] State diverged")}containerToStateJson(e){let r=e.kind();if(r==="Map"){let n=e,i={};ro(i,e.id);for(let s of n.keys()){let o=n.get(s);i[s]=(0,Ln.isContainer)(o)?this.containerToStateJson(o):o}return i}else if(r==="List"||r==="MovableList"){let n=[],i=e,s=i.length;for(let o=0;o<s;o++){let a=i.get(o);n.push((0,Ln.isContainer)(a)?this.containerToStateJson(a):a)}return n}else{if(r==="Text")return e.toJSON();if(r==="Tree"){let n=e,i=yR(n.toJSON()),s=this.getContainerSchema(n.id);if(s&&no(s)){let a=new Map,c=n.getNodes?.()??[];for(let f of c)try{let d=f,p=typeof d.id=="string"?d.id:void 0,m;if(d.data&&typeof d.data=="object"){let _=d.data;m=typeof _.id=="string"?_.id:void 0}p&&m&&a.set(p,m)}catch{}let l=f=>{for(let d of f){let p=d,m=typeof p.id=="string"?a.get(p.id):void 0;m&&((!p.data||typeof p.data!="object")&&(p.data={}),ro(p.data,m)),Array.isArray(p.children)&&l(p.children)}};l(i)}return i}}return e.toJSON()}buildRootStateSnapshot(){if(!this.schema||this.schema.type!=="schema")return o2(this.doc);let e={},r=this.schema;for(let n in r.definition){let i=r.definition[n],s=xl(i);if(!s)continue;let o=F_(this.doc,n,s);if(s==="Map")e[n]=this.containerToStateJson(o);else if(s==="List"||s==="MovableList")e[n]=this.containerToStateJson(o);else if(s==="Text")e[n]=this.containerToStateJson(o);else if(s==="Tree"){let a=this.containerToStateJson(o);if(!Array.isArray(a)||a.length===0)continue;e[n]=a}else e[n]=this.containerToStateJson(o)}return e}registerContainerWithRegistry(e,r){this.containerRegistry.set(e,{schema:r,registered:!0})}stampCid(e,r){Sn(e)&&ro(e,r)}getSchemaForMapKey(e,r){if(!e)return;if(Object.prototype.hasOwnProperty.call(e.definition,r))return e.definition[r];let n=e;if(n.catchallType)return n.catchallType}getContainerSchema(e){return this.containerRegistry.get(e)?.schema}getSchemaForChildContainer(e,r){let n=this.getSchemaForChild(e,r);if(!(!n||!Bu(n)))return n}getSchemaForChild(e,r){let n=this.getContainerSchema(e);if(n){if(Ru(n))return this.getSchemaForMapKey(n,String(r));if(Pu(n)||Nu(n))return n.itemSchema;if(no(n))return n.nodeSchema}}getContainerIds(){return Array.from(this.containerRegistry.keys())}};function o2(t){let e=t.toJsonWithReplacer((r,n)=>(0,Ln.isContainer)(n)&&n.kind()==="Tree"?yR(n.toJSON()):(0,Ln.isContainer)(n)&&n.kind()==="Map"?{...n.getShallowValue(),[Mn]:n.id}:n);return _R(e)}function _R(t){if(Array.isArray(t)){for(let e=0;e<t.length;e++)t[e]=_R(t[e]);return t}if(Sn(t)){let e=t;for(let r of Object.keys(e))e[r]=_R(e[r]);if(Object.prototype.hasOwnProperty.call(e,Mn)){let r=Object.getOwnPropertyDescriptor(e,Mn);if(!r||r.enumerable){let n=e[Mn];delete e[Mn],Object.defineProperty(e,Mn,{value:n})}}return e}return t}function bLe(t){let e={};for(let[r,n]of Object.entries(t))Array.isArray(n)?e[r]=[]:typeof n=="string"?e[r]="":Sn(n)?e[r]={}:e[r]=n;return e}function yR(t){return Array.isArray(t)?t.map(OZ):[]}function OZ(t){let e=t?.id,r=typeof e=="string"?e:"",n=t?.meta,i=typeof n=="object"&&n!=null&&!Array.isArray(n)?n:{},s=t?.children,o=Array.isArray(s)?s.map(OZ):[];return{id:r,data:i,children:o}}function FZ(t,e,r){for(let[n,i]of Object.entries(e)){let s=r.definition[n];if(!s){n in t||(Array.isArray(i)?t[n]=[]:typeof i=="string"?t[n]="":Sn(i)&&(t[n]={}));continue}let o=s.type;if(o==="ignore"){t[n]=i;continue}if(o==="loro-map"){(!(n in t)||!Sn(t[n]))&&(t[n]={});let a=t[n],u=Sn(i)?i:{};FZ(a,u,{type:"schema",definition:s.definition,options:{},getContainerType(){return"Map"}});continue}if(o==="loro-list"||o==="loro-movable-list"){n in t||(t[n]=[]);continue}if(o==="loro-text"){n in t||(t[n]="");continue}if(o==="string"||o==="number"||o==="boolean"){n in t||(t[n]=i);continue}}}var Wyt=Object.assign({},nR,vR);var Kyt=Ee.LoroMap({name:Ee.String(),color:Ee.String()}),Jyt=Ee.LoroMap({content:Ee.LoroText(),parentId:Ee.String({required:!1}),isDeleted:Ee.Boolean()}),xLe=Ee.LoroMap({type:Ee.String(),by:Ee.String(),timestamp:Ee.String(),target:Ee.String({required:!1}),value:Ee.String({required:!1}),commentId:Ee.String({required:!1}),sessionId:Ee.String({required:!1})}),ELe=Ee.LoroMap({id:Ee.String(),title:Ee.String(),description:Ee.LoroText({required:!1}),status:Ee.String(),priority:Ee.String(),assigneeId:Ee.String({required:!1}),assigneeName:Ee.String({required:!1}),agent:Ee.String({required:!1}),githubRepo:Ee.String({required:!1}),labels:Ee.LoroList(Ee.String()),estimate:Ee.Number({required:!1}),dueDate:Ee.String({required:!1}),createdAt:Ee.String(),createdBy:Ee.String(),actionHistory:Ee.LoroList(xLe,t=>t.$cid),subIssues:Ee.LoroList(Ee.String()),parentIssueId:Ee.String({required:!1}),attachments:Ee.LoroList(Ee.String())}),RZ=Ee({issue:ELe}),wLe=Ee.LoroMap({id:Ee.String(),name:Ee.String(),description:Ee.LoroText({required:!1}),cliType:Ee.String(),machineId:Ee.String({required:!1}),env:Ee.LoroMapRecord(Ee.String())}),PZ=Ee({config:wLe}),SLe=Ee.LoroMap({contents:Ee.String(),timestamp:Ee.String(),role:Ee.String(),read:Ee.Boolean({required:!1}),userId:Ee.String({required:!1})}),CLe=Ee.LoroMap({id:Ee.String(),machineId:Ee.String(),title:Ee.String({required:!1}),userId:Ee.String(),issueId:Ee.String({required:!1}),status:Ee.String(),history:Ee.LoroList(SLe,t=>t.timestamp),error:Ee.String({required:!1}),createdAt:Ee.String(),cliType:Ee.String(),agentConfigId:Ee.String({required:!1}),chatId:Ee.String({required:!1})}),NZ=Ee({session:CLe}),DLe=Ee.LoroMap({userId:Ee.String(),avatar:Ee.String({required:!1}),name:Ee.String(),email:Ee.String(),role:Ee.String()}),ALe=Ee.LoroMap({id:Ee.String(),name:Ee.String(),githubRepos:Ee.LoroList(Ee.String()),members:Ee.LoroList(DLe,t=>t.userId)}),ILe=Ee.LoroMap({name:Ee.String(),color:Ee.String()}),BZ=Ee({meta:ALe,issues:Ee.LoroList(Ee.LoroMap({id:Ee.String(),isDeleted:Ee.Boolean()}),t=>t.id),sessions:Ee.LoroList(Ee.LoroMap({id:Ee.String(),isDeleted:Ee.Boolean()}),t=>t.id),agentConfigs:Ee.LoroList(Ee.LoroMap({id:Ee.String(),isDeleted:Ee.Boolean()}),t=>t.id),labels:Ee.LoroList(ILe,t=>t.$cid)}),MZ=t=>`issue-${t}`,LZ=t=>`session-${t}`,qZ=t=>`agent-${t}`;var TLe=5*60*1e3,UZ=t=>`ephemeral-${t}`,bR="machine-",Mu=t=>`${bR}${t}`,a2=class{constructor(e){this.store=e}aliveTimer=null;registerMachine(e,r){this.store.set(Mu(e),r),this.aliveTimer=setInterval(()=>{this.store.set(Mu(e),this.store.get(Mu(e)))},TLe/2)}unRegisterMachine(e){this.store.delete(Mu(e)),this.aliveTimer&&clearInterval(this.aliveTimer)}getMachineIds(){return this.store.keys().filter(e=>e.startsWith(bR)).map(e=>e.replace(bR,""))}getMachine(e){return this.store.get(Mu(e))}addMachineSession(e,r){let n=this.getMachine(e);if(n){let i=[...n.sessions,r];this.store.set(Mu(e),{...n,sessions:i})}}removeMachineSession(e,r){let n=this.getMachine(e);if(n){let i=n.sessions.filter(s=>s.sessionId!==r);this.store.set(Mu(e),{...n,sessions:i})}}updateMachineSession(e,r,n){let i=this.getMachine(e);if(i){let s=i.sessions.map(o=>o.sessionId===r?{...o,status:{...o.status,...n}}:o);this.store.set(Mu(e),{...i,sessions:s})}}updateMachine(e,r){let n=this.getMachine(e);n&&this.store.set(Mu(e),{...n,...r})}};var Y7e=qe(Nee(),1),Q7e=qe(OR(),1),K7e=qe(PR(),1),Vee=qe(v2(),1),J7e=qe(Wee(),1);var Al=Vee.default;globalThis.WebSocket=Al;var qo=B4(),x2=class{constructor(e,r){this.workspaceId=e;this.token=r;qo.debug(`[${this.workspaceId}] LoroWebsocketClient url: ${a0+`/ws/${this.workspaceId}`}`),this.client=new aZ({url:a0+`/ws/${this.workspaceId}`,onWsClose:()=>{qo.debug(`[${this.workspaceId}] LoroWebsocketClient ws closed`),this.client.connect()}}),this.docMirror=new $R(this.client),this.ephemeral=new a2(this.ephemeralAdaptor.getStore())}client;docMirror;issues=new Map;sessions=new Map;workspaces=new Map;agents=new Map;ephemeral;ephemeralAdaptor=new oZ(new zee.EphemeralStore(24*60*60*1e3));async waitConnected(){await this.client.waitConnected(),await this.client.join({roomId:UZ(this.workspaceId),crdtAdaptor:this.ephemeralAdaptor})}disconnect(){this.client.close()}async getOrCreateAgentDoc(e){if(!this.agents.has(e)){let r=new zR(this.docMirror,e);await r.init(),this.agents.set(e,r)}return this.agents.get(e)}async getOrCreateIssueDoc(e){if(!this.issues.has(e)){let r=new HR(this.docMirror,e);await r.init(),this.issues.set(e,r)}return this.issues.get(e)}async getOrCreateSessionDoc(e){if(!this.sessions.has(e)){let r=new WR(this.docMirror,e);await r.init(),this.sessions.set(e,r)}return this.sessions.get(e)}async getOrCreateWorkspaceDoc(e,r){if(!this.workspaces.has(e)){let n=new VR(this.docMirror,r,e,this);await n.init(),this.workspaces.set(e,n)}return this.workspaces.get(e)}async cleanUp(){for(let e of this.sessions.values())e.destroy();for(let e of this.issues.values())e.destroy();for(let e of this.workspaces.values())e.destroy();this.issues.clear(),this.workspaces.clear(),this.sessions.clear()}async cleanSessionDoc(e){let r=this.sessions.get(e);r&&(r.destroy(),this.sessions.delete(e))}},$R=class{constructor(e){this.client=e}adaptors=new Map;rooms=new Map;mirrors=new Map;async getAdaptor(e){if(!this.adaptors.has(e)){let r=new sZ(void 0,{onImportError(i,s){qo.error(`Error occurs when importing loro data ${i}`)},onUpdateError(i){qo.error(`Error occurs when updating loro ${i}`)}});qo.debug(`[${e}] waiting for client connected`),await this.client.waitConnected(),qo.debug(`[${e}] joining room`);let n=await this.client.join({roomId:e,crdtAdaptor:r});await n.waitForReachingServerVersion(),qo.debug(`[${e}] joined room frontiers: ${JSON.stringify(r.getDoc().frontiers())}`),this.rooms.set(e,n),this.adaptors.set(e,r)}return this.adaptors.get(e)}async getMirror(e,r,n){if(this.mirrors.has(e))return this.mirrors.get(e);let i=await this.getAdaptor(e),s=new _d({doc:i.getDoc(),schema:r,initialState:n});return this.mirrors.set(e,s),s}close(e){this.adaptors.get(e)&&this.adaptors.delete(e);let n=this.rooms.get(e);n&&(this.rooms.delete(e),n.leave());let i=this.mirrors.get(e);i&&(this.mirrors.delete(e),i.dispose())}closeAll(){for(let e of this.rooms.keys())this.close(e)}},HR=class{constructor(e,r){this.docMirror=e;this.issueId=r;this.roomId=MZ(this.issueId)}mirror=null;roomId;async init(){this.mirror=await this.docMirror.getMirror(this.roomId,RZ)}getState(){if(!this.mirror)throw new Error("Mirror not initialized");return this.mirror.getState().issue}async setStatus(e){if(!this.mirror)throw new Error("Mirror not initialized");let r=await this.docMirror.getAdaptor(this.roomId);qo.debug(`[${this.issueId}] doc frontiers: ${JSON.stringify(r.getDoc().frontiers())}`),this.mirror.setState(n=>(n.issue.status!==e?(qo.debug(`[${this.issueId}] setStatus ${e}`),n.issue.status=e,n.issue.actionHistory.push({type:"update",target:"status",value:JSON.stringify(e),by:"lody-cli",timestamp:new Date().toISOString()})):qo.debug(`[${this.issueId}] setStatus ${e} no change`),n))}destroy(){this.docMirror.close(this.roomId)}},WR=class{constructor(e,r){this.docMirror=e;this.sessionId=r;this.roomId=LZ(this.sessionId)}mirror=null;roomId="";async init(){this.mirror=await this.docMirror.getMirror(this.roomId,NZ)}getState(){if(!this.mirror)throw new Error("Mirror not initialized");return this.mirror.getState().session}async markHistoryAsRead(e){if(!this.mirror)throw new Error("Mirror not initialized");this.mirror.setState(r=>{let n=r.session.history??[];for(let i of n)if(i.$cid===e){i.read=!0;break}return r})}async setChatId(e){if(!this.mirror)throw new Error("Mirror not initialized");qo.debug(`[${this.sessionId}] setChatId ${e}`),this.mirror.setState(r=>(r.session.chatId=e,r))}async setError(e){if(!this.mirror)throw new Error("Mirror not initialized");this.mirror.setState(r=>(r.session.error=e,r.session.status="error",r))}getStatus(){return this.mirror?this.mirror.getState().session.status:"terminated"}isChat(){return this.mirror?!!this.mirror.getState().session.chatId:!1}async getIssueId(){if(this.mirror)return this.mirror.getState().session.issueId}async setStatus(e){if(!this.mirror)throw new Error("Mirror not initialized");this.mirror.setState(r=>(r.session.status=e,r))}async getHistory(){return this.mirror?this.mirror.getState().session.history||[]:[]}async updateHistory(e){if(!this.mirror)throw new Error("Mirror not initialized");this.mirror.setState(r=>{let n=e(r.session.history||[]);return r.session.history=n,r})}destroy(){if(!this.mirror){this.docMirror.close(this.roomId);return}let e=this.getStatus();e==="running"||e==="requestPermission"?this.setStatus("error"):(e==="completed"||e==="terminated")&&this.setStatus("terminated"),this.docMirror.close(this.roomId)}},VR=class{constructor(e,r,n,i){this.docMirror=e;this.userId=r;this.workspaceId=n;this.manager=i;this.roomId=`workspace-${this.workspaceId}`}mirror=null;roomId;async init(){this.mirror=await this.docMirror.getMirror(this.roomId,BZ)}async createSession(e,r,n){if(!this.mirror)throw new Error("Mirror not initialized");let i=o0(),s=await this.manager.getOrCreateSessionDoc(i);return await s.init(),s.mirror?.setState(o=>({session:{...o.session,id:i,machineId:e,cliType:r,userId:this.userId,status:"running",history:[],title:n,createdAt:new Date().toISOString()}})),this.mirror.setState(o=>{o.sessions.push({id:i,isDeleted:!1})}),i}async hasAgentConfig(e,r){if(!this.mirror)throw new Error("Mirror not initialized");let n=this.mirror.getState().agentConfigs,i=!1;for(let s of n){if(s.isDeleted)continue;let a=(await this.manager.getOrCreateAgentDoc(s.id)).getState().config;if(i||=a.cliType===e&&a.machineId===r,i)break}return i}async createAgentConfig(e,r){if(!this.mirror)throw new Error("Mirror not initialized");let n=o0(),i=await this.manager.getOrCreateAgentDoc(n);return await i.init(),i.mirror?.setState(s=>({config:{id:n,name:e,description:"Default agent config created by Lody CLI",machineId:r,cliType:e,env:{},createdAt:new Date().toISOString()}})),this.mirror.setState(s=>{s.agentConfigs.push({id:n,isDeleted:!1})}),n}destroy(){this.docMirror.close(this.roomId)}getState(){if(!this.mirror)throw new Error("Mirror not initialized");return this.mirror.getState()}},zR=class{constructor(e,r){this.docMirror=e;this.agentId=r;this.roomId=qZ(this.agentId)}mirror=null;roomId;async init(){this.mirror=await this.docMirror.getMirror(this.roomId,PZ)}async destroy(){this.docMirror.close(this.roomId)}getState(){if(!this.mirror)throw new Error("Mirror not initialized");return this.mirror.getState()}};var Gee=require("events");var E2=class extends Gee.EventEmitter{ws=null;token;workspaceId;reconnectInterval;maxReconnectAttempts;reconnectAttempts=0;reconnectTimer=null;keepaliveTimer=null;isManualClose=!1;isConnected=!1;logger;constructor(e){super(),this.token=e.token,this.reconnectInterval=e.reconnectInterval||5e3,this.maxReconnectAttempts=e.maxReconnectAttempts||1/0,this.logger=e.logger,this.workspaceId=e.workspaceId}connect(){return new Promise((e,r)=>{try{let n=new URL(`${a0}/lody/${this.workspaceId}`);this.token&&n.searchParams.append("token",this.token),this.logger.debug(`Connecting to WebSocket: ${n}`),this.ws=new Al(n.toString(),{perMessageDeflate:!1,handshakeTimeout:15e3}),this.setupEventHandlers();let i=()=>{this.ws?.removeListener("error",s),e()},s=o=>{this.ws?.removeListener("open",i),r(o)};this.ws.once("open",i),this.ws.once("error",s),setTimeout(()=>{this.isConnected||(this.ws?.removeListener("open",i),this.ws?.removeListener("error",s),r(new Error("Connection timeout")))},3e4)}catch(n){r(n)}})}setupEventHandlers(){this.ws&&(this.ws.on("open",()=>{this.isConnected=!0,this.reconnectAttempts=0,this.logger.debug("WebSocket connected"),this.emit("open"),this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.keepaliveTimer=setInterval(()=>{this.ws?.readyState===Al.OPEN&&this.ws.send("ping")},3e4)}),this.ws.on("message",e=>{this.emit("message",e)}),this.ws.on("close",(e,r)=>{this.isConnected=!1,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.logger.warn(`WebSocket disconnected: code=${e}, reason=${r}`),this.emit("close",e,r),this.isManualClose||this.scheduleReconnect()}),this.ws.on("error",e=>{this.logger.error(`WebSocket error: ${e.message}`),e.message.includes("401")&&(this.logger.error("Authentication failed. Check your token."),this.close(),process.exit(1)),this.emit("error",e)}),this.ws.on("ping",e=>{this.ws?.readyState===Al.OPEN&&this.ws.pong(e)}))}scheduleReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){this.logger.error(`Max reconnection attempts (${this.maxReconnectAttempts}) reached`),this.emit("max_reconnect_exceeded");return}this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectAttempts++;let e=Math.min(this.reconnectInterval*Math.pow(1.5,this.reconnectAttempts-1),6e4);this.logger.info(`Reconnecting in ${e}ms... (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`),this.reconnectTimer=setTimeout(()=>{this.reconnect()},e)}async reconnect(){try{this.logger.info("Attempting to reconnect..."),await this.connect(),this.logger.info("Reconnected successfully"),this.emit("reconnected")}catch(e){this.logger.error(`Reconnection failed: ${e instanceof Error?e.message:"Unknown error"}`)}}send(e){if(this.ws?.readyState===Al.OPEN)this.ws.send(e);else throw this.logger.warn("Cannot send message: WebSocket is not connected"),new Error("WebSocket is not connected")}getSocket(){return this.ws}isReady(){return this.ws?.readyState===Al.OPEN}close(){this.isManualClose=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.ws&&(this.ws.close(),this.ws=null)}resetReconnectAttempts(){this.reconnectAttempts=0}};function Yee(t,e,r){var n=r||{},i=n.noTrailing,s=i===void 0?!1:i,o=n.noLeading,a=o===void 0?!1:o,u=n.debounceMode,c=u===void 0?void 0:u,l,f=!1,d=0;function p(){l&&clearTimeout(l)}function m(v){var E=v||{},A=E.upcomingOnly,F=A===void 0?!1:A;p(),f=!F}function _(){for(var v=arguments.length,E=new Array(v),A=0;A<v;A++)E[A]=arguments[A];var F=this,D=Date.now()-d;if(f)return;function U(){d=Date.now(),e.apply(F,E)}function I(){l=void 0}!a&&c&&!l&&U(),p(),c===void 0&&D>t?a?(d=Date.now(),s||(l=setTimeout(c?I:U,t))):U():s!==!0&&(l=setTimeout(c?I:U,c===void 0?t-D:t))}return _.cancel=m,_}var K_=t=>t&&t.replace(/^['"]+|['"]+$/g,""),X7e=(t,e)=>{if(!e)return t;let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return t.replace(new RegExp(r,"g"),"***TOKEN***")},Z7e=(t,e)=>{let r=K_(t)??t,n=K_(e?.trim());if(!n)return{cloneUrl:`https://github.com/${r}.git`};let i=encodeURIComponent(n);return n.startsWith("ghs_")?{cloneUrl:`https://x-access-token:${i}@github.com/${r}.git`,rewriteBase:`https://x-access-token:${i}@github.com/`}:{cloneUrl:`https://${i}@github.com/${r}.git`,rewriteBase:`https://${i}@github.com/`}},Qee=(t,e)=>{if(!e)return t;let r=["https://github.com/","git@github.com:","ssh://git@github.com/"],n=new Set;for(let s of r)n.add(s);let i=[];for(let s of n)i.push("-c",`url.${e}.insteadOf=${s}`);return[...i,...t]},Kee=async(t,e,r,n,i,s)=>{let o=X7e([r,...n].join(" "),s);return e.debug(`[${t.sessionId}] Executing (${i}): ${o}`),await t.exec(r,n,i,!1)},Jee=async(t,e,r,n)=>{let i=r.sessionId,s=r.getWorkdir();try{let o=K_(t?.trim())??t?.trim();if(!o){n.info(`[${i}] No GitHub repository specified, skipping clone`);return}if(n.info(`[${i}] Cloning GitHub repository: ${o}`),!o.match(/^[^/]+\/[^/]+$/))throw new Error(`Invalid GitHub repository format: ${o}. Expected format: owner/repo`);let{cloneUrl:a,rewriteBase:u}=Z7e(o,e),c=K_(a)??a,l=K_(u);e?e.startsWith("ghs_")?n.info(`[${i}] Using GitHub App token for authentication`):n.info(`[${i}] Using GitHub token for authentication`):n.info(`[${i}] Cloning public repository`),await Kee(r,n,"git",Qee(["clone","--depth","1","--recurse-submodules","--shallow-submodules",c,s],l),"/",e),await Kee(r,n,"git",Qee(["-C",s,"submodule","update","--init","--recursive","--depth","1"],l),"/",e),n.info(`[${i}] Successfully cloned repository: ${o}`)}catch(o){throw n.error(`[${r.sessionId}] Failed to clone GitHub repository: ${o instanceof Error?o.message:"Unknown error"}`),o}};var w2=class{constructor(e,r,n,i,s){this.workspaceDocument=n;this.socket=e,this.sessionManager=r,this.logger=i,this.token=s.token,this.userId=s.userId,this.workspaceId=s.workspaceId,this.machineName=s.machineName,this.enableDocker=s.enableDocker,this.cliVersion=s.cliVersion,this.machineId=s.machineId,this.sessionManager.setRequestPermissionHandler((o,a,u)=>this.handleAgentPermissionRequest(o,a,u)),this.setupSessionEventHandlers(),this.registerMachine()}socket;sessionManager;logger;machineId;token;userId;workspaceId;machineName;enableDocker;cliVersion;pendingPermissionRequests=new Map;acpUpdateBuffers=new Map;acpUpdateThrottlers=new Map;acpUpdateThrottleMs=200;setupSessionEventHandlers(){this.sessionManager.on("output",async e=>{this.logger.debug(`Output from session [${e.sessionId}]: ${e.data}`)}),this.sessionManager.on("onACPUpdateMessage",(e,r)=>{this.logger.debug(`[${e}] Received ACP update message ${r}`),this.enqueueACPUpdate(e,r)}),this.sessionManager.on("error",async e=>{this.logger.error(`[${e.sessionId}] error occur ${e}`);let r=e.sessionId;await this.finalizeACPState(r),(await this.workspaceDocument.getOrCreateSessionDoc(r)).setError("execution_error"),await this.sessionManager.finishSession(r),this.workspaceDocument.ephemeral.removeMachineSession(this.machineId,r)}),this.sessionManager.on("exit",async e=>{let r=e.sessionId;await this.finalizeACPState(r),(await this.workspaceDocument.getOrCreateSessionDoc(r)).setStatus("completed");let i=new Date().toISOString();this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"completed",completedAt:i})})}enqueueACPUpdate(e,r){let n=this.acpUpdateBuffers.get(e);n?n.push(r):this.acpUpdateBuffers.set(e,[r]),this.getOrCreateACPUpdateThrottler(e)()}getOrCreateACPUpdateThrottler(e){let r=this.acpUpdateThrottlers.get(e);return r||(r=Yee(this.acpUpdateThrottleMs,()=>this.flushACPUpdates(e).catch(n=>{this.logger.error(`[${e}] Failed to flush ACP updates: ${n instanceof Error?n.message:"Unknown error"}`)})),this.acpUpdateThrottlers.set(e,r),r)}async flushACPUpdates(e){this.acpUpdateThrottlers.get(e)?.cancel({upcomingOnly:!0});let r=this.acpUpdateBuffers.get(e);if(!r||r.length===0){this.acpUpdateBuffers.delete(e);return}this.acpUpdateBuffers.delete(e);let n=await this.workspaceDocument.getOrCreateSessionDoc(e);await eqe(n,r)}async flushAllACPUpdates(){let e=Array.from(new Set([...this.acpUpdateBuffers.keys(),...this.acpUpdateThrottlers.keys()]));for(let r of e)await this.finalizeACPState(r)}async finalizeACPState(e){try{await this.flushACPUpdates(e)}catch(r){this.logger.error(`[${e}] Failed to flush ACP updates during finalization: ${r instanceof Error?r.message:"Unknown error"}`)}finally{this.clearACPState(e)}}clearACPState(e){this.acpUpdateBuffers.delete(e),this.acpUpdateThrottlers.get(e)?.cancel(),this.acpUpdateThrottlers.delete(e)}registerMachine(){let e={type:"register",role:"machine",id:this.machineId,token:this.token,workspaceId:this.workspaceId,userId:this.userId,machineInfo:{name:this.machineName,cliVersion:this.cliVersion,os:process.platform,enableDocker:this.enableDocker}};this.sendMessage(e),this.logger.info(`Machine registered with name: ${this.machineName}`)}async handleMessage(e){switch(this.logger.debug(`Received message: ${e.type}`),e.type){case"register_response":await this.handleRegisterResponse(e);break;case"session_create":await this.handleSessionCreate(e);break;case"session_terminate":await this.handleSessionTerminate(e);break;case"session_stop":await this.handleSessionStop(e);break;case"permission_response":await this.handlePermissionResponse(e);break;case"session_chat":await this.handleSessionChat(e);break;default:this.logger.debug(`Unknown message: ${e}`)}}async handleSessionChat(e){let{sessionId:r,promptConfig:n,historyCid:i}=e;if(this.logger.info(`[${r}] Received chat request`),i)try{await(await this.workspaceDocument.getOrCreateSessionDoc(r)).markHistoryAsRead(i),this.logger.debug(`[${r}] Marked history as read`)}catch(o){this.logger.warn(`[${r}] Failed to mark history as read: ${o instanceof Error?o.message:"Unknown error"}`)}this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"running",cliType:n.agentType,createdAt:new Date().toISOString()});let s=this.sessionManager.getSession(r);s?(await s.agentClient?.connection?.prompt({sessionId:s.acpSessionId,prompt:[{type:"text",text:n.prompt}]}),this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"completed",completedAt:new Date().toISOString()}),await this.finalizeACPState(r),this.logger.info(`[${r}] Chat request processed successfully`)):(this.logger.warn(`[${r}] Session not found`),(await this.workspaceDocument.getOrCreateSessionDoc(r)).setError("session_not_found"),this.workspaceDocument.ephemeral.removeMachineSession(this.machineId,r))}async handleRegisterResponse(e){e.success?this.logger.info(`Registration successful, machine ID: ${this.machineId}`):this.logger.error(`Registration failed: ${e.error}`)}async handleSessionCreate(e){let{sessionId:r,config:n,workspaceId:i}=e;this.logger.info(`[${r}] Creating new session`);let s={sessionId:r,workspaceId:i,cliType:n.promptConfig.agentType,userId:this.userId,machineId:this.machineId,assumeDocExisting:!0,env:n.env};this.workspaceDocument.ephemeral.addMachineSession(this.machineId,{sessionId:r,status:{status:"establish",createdAt:new Date().toISOString()}});try{let o=await this.sessionManager.createSession(s);if(this.sendMessage({type:"session_create_response",sessionId:r,success:!0}),n.githubRepo&&n.githubToken){this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"git-clone",repo:n.githubRepo});try{await Jee(n.githubRepo,n.githubToken,o,this.logger)}catch(f){let d=f instanceof Error?f.message:"Failed to clone GitHub repository";this.logger.error(`[${r}] ${d}`),await this.sessionManager.setSessionError(r,"execution_error"),this.workspaceDocument.ephemeral.removeMachineSession(this.machineId,r),await this.finalizeACPState(r);return}}let a=n.promptConfig;this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"running",cliType:s.cliType});let u=await o.agentClient?.connection?.prompt({sessionId:o.acpSessionId,prompt:[{type:"text",text:a.prompt}]});(await this.workspaceDocument.getOrCreateSessionDoc(r)).setStatus("completed");let l=new Date().toISOString();this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"completed",completedAt:l}),this.logger.debug(`[${r}] Prompt response: ${JSON.stringify(u)}`),await this.finalizeACPState(r),this.logger.info(`[${r}] Session created successfully`)}catch{await this.finalizeACPState(r),await this.sessionManager.setSessionError(r,"execution_error"),this.sendMessage({type:"session_create_response",sessionId:r,success:!1})}}async handleSessionTerminate(e){let{sessionId:r,force:n}=e;this.logger.info(`[${r}] Terminating session`);try{await this.sessionManager.terminateSession(r,n),await this.finalizeACPState(r);let i={type:"session_terminated",sessionId:r,error:void 0,reason:"user_request"};this.sendMessage(i),this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"terminated"}),this.logger.info(`[${r}] Session terminated successfully`)}catch(i){let s={type:"session_terminated",sessionId:r,error:"execution_error",reason:"error"};this.sendMessage(s),this.logger.error(`[${r}] Failed to terminate: ${i instanceof Error?i.message:"Unknown error"}`)}}async handleSessionStop(e){let{sessionId:r}=e;this.logger.info(`[${r}] Received stop request`);let n=this.sessionManager.getSession(r);if(!n){this.logger.warn(`[${r}] Session not found for stop request`);return}if(!n.agentClient?.connection||!n.acpSessionId){this.logger.warn(`[${r}] Cannot stop session without active ACP connection`);return}try{await n.agentClient.connection.cancel({sessionId:n.acpSessionId}),await this.finalizeACPState(r),(await this.workspaceDocument.getOrCreateSessionDoc(r)).setStatus("completed");let s=new Date().toISOString();this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"completed",completedAt:s}),this.logger.info(`[${r}] Stop signal sent to agent`)}catch(i){this.logger.error(`[${r}] Failed to stop session: ${i instanceof Error?i.message:"Unknown error"}`)}}async handlePermissionResponse(e){this.logger.info(`[${e.sessionId}] Permission response received for ${e.requestId}: ${e.outcome.outcome}`);let r=this.pendingPermissionRequests.get(e.requestId);r?(r.resolve({outcome:e.outcome}),this.pendingPermissionRequests.delete(e.requestId)):this.logger.warn(`[${e.sessionId}] No pending permission request found for ${e.requestId}`);try{let n=await this.workspaceDocument.getOrCreateSessionDoc(e.sessionId);await iqe(n,e.requestId,e.outcome)}catch(n){this.logger.error(`[${e.sessionId}] Failed to update permission outcome: ${n instanceof Error?n.message:"Unknown error"}`)}}async handleAgentPermissionRequest(e,r,n){this.logger.info(`[${e}] Forwarding permission request ${r} for tool call ${n.toolCall.toolCallId}`);try{let s=await this.workspaceDocument.getOrCreateSessionDoc(e);await nqe(s,r,n)}catch(s){this.logger.error(`[${e}] Failed to append permission request to history: ${s instanceof Error?s.message:"Unknown error"}`)}let i={type:"request_permission",sessionId:e,requestId:r,request:n};return this.sendMessage(i),new Promise((s,o)=>{this.pendingPermissionRequests.has(r)&&this.logger.warn(`[${e}] Duplicate permission request ID detected: ${r}, overwriting existing handler`),this.pendingPermissionRequests.set(r,{resolve:s,reject:o,sessionId:e})})}sendMessage(e){try{this.socket.send(JSON.stringify(e))}catch(r){this.logger.error(`Failed to send message: ${r instanceof Error?r.message:"Unknown error"}`)}}updateSocket(e){this.socket=e,this.logger.debug("WebSocket instance updated")}async cleanup(){this.logger.info("Cleaning up message handler resources"),await this.flushAllACPUpdates(),this.acpUpdateThrottlers.forEach(e=>e.cancel()),this.acpUpdateThrottlers.clear(),await this.sessionManager.cleanUp()}},eqe=async(t,e)=>{let r=Array.isArray(e)?e:[e],n=[];for(let i of r)n.push(...tqe(i));n.length&&await t.updateHistory(i=>{let s=i;for(let o of n)s=rqe(s,o);return s})},tqe=t=>{let{update:e}=t;switch(e.sessionUpdate){case"user_message_chunk":return[];case"agent_message_chunk":case"agent_thought_chunk":switch(e.content.type){case"text":return[{type:"text",text:e.content.text}];case"image":case"audio":case"resource_link":case"resource":throw new Error(`Unsupported content type: ${e.content.type}`)}return[];case"tool_call":case"tool_call_update":return[{type:"tool_call",toolCallId:e.toolCallId,title:e.title,kind:e.kind||void 0,status:e.status||"pending",content:e.content?.map(r=>{switch(r.type){case"diff":return{type:r.type,path:r.path,newText:r.newText,oldText:r.oldText};case"terminal":case"content":return}}).filter(r=>r!==void 0)}];case"plan":return[{type:"plan",entries:e.entries}];case"available_commands_update":return[{type:"available_commands",commands:e.availableCommands}];case"current_mode_update":throw new Error(`Unsupported session update: ${e.sessionUpdate}`);default:return[]}},rqe=(t,e)=>{let r=t.length-1,n=r>=0?t[r]:null;if(!n||n.role!=="assistant")return GR(t,[e]);let i=s=>{let o=JSON.parse(n.contents),a=s(o),u={...n,contents:JSON.stringify(a)},c=[...t];return c[r]=u,c};switch(e.type){case"text":case"thought":return i(s=>{let o=[...s],a=o.findIndex(u=>u.type===e.type);if(a>=0){let u=o[a];(u.type==="text"||u.type==="thought")&&(o[a]={...u,text:u.text+(u.type==="thought"?`
|
|
191
|
+
This is likely a programming error or unsupported container type.`)}}updateTextContainer(e,r){if(typeof r!="string")throw new Error("Text value must be a string");e.update(r)}updateListContainer(e,r){if(Array.isArray(r)){let n=this.getContainerSchema(e.id);if(n&&!Pu(n)&&!Nu(n))throw new Error(`Invalid schema for list: ${n.type}. Expected LoroListSchema`);let i=n?.idSelector,s=n?.itemSchema;i?this.updateListWithIdSelector(e,r,i,s):this.updateListByIndex(e,r,s)}else throw new Error("List value must be an array")}updateListWithIdSelector(e,r,n,i){let s=new Map,o=e.length;for(let f=0;f<o;f++){let d=e.get(f);try{if(d){let p=n(d);p&&s.set(p,{item:d,index:f})}}catch(p){this.options.debug&&console.warn("Error getting ID for current list item:",p)}}let a=new Map,u=f=>{if(!f)return null;try{let d=n(f);if(d)return d}catch(d){this.options.debug&&console.warn("Error using ID selector directly:",d);let p=f.id;if(typeof p=="string")return p}return null};r.forEach((f,d)=>{try{let p=u(f);if(p)a.set(p,{item:f,index:d});else throw new Error(`Item at index ${d} has no ID`)}catch(p){this.options.debug&&console.warn(`Error getting ID for new list item at index ${d}:`,p)}});let c=[];for(let[f,{index:d}]of s.entries())a.has(f)||c.push(d);c.sort((f,d)=>d-f);for(let f of c)e.delete(f,1);let l=0;for(let f=0;f<r.length;f++){let d=r[f],p=null;try{p=u(d)}catch(_){console.warn(`Error getting ID for new item at index ${f}:`,_);continue}if(!p)continue;if(s.get(p)){let _=e.get(l);Fa(_,d)||(e.delete(l,1),this.insertItemIntoList(e,l,d,i))}else this.insertItemIntoList(e,l,d,i);l++}l<e.length&&e.delete(l,e.length-l)}updateListByIndex(e,r,n){let i=e.length,s=Math.max(i,r.length);for(let o=0;o<s;o++)if(o>=i)this.insertItemIntoList(e,o,r[o],n);else if(o>=r.length){e.delete(r.length,i-r.length);break}else{let a=e.get(o),u=r[o];Fa(a,u)||(e.delete(o,1),this.insertItemIntoList(e,o,u,n))}}insertItemIntoList(e,r,n,i){let s=!1,o;if(i&&Bu(i)?(s=!0,o=i):s=El(n,this.options?.inferOptions)!==void 0,s&&typeof n=="object"&&n!==null){this.insertContainerIntoList(e,o,r,n);return}e.insert(r,n)}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}notifySubscribers(e,r){let n={direction:e,tags:r};for(let i of this.subscribers)i(this.state,n)}dispose(){this.subscribers.clear(),this.subscriptions.forEach(e=>{e()}),this.subscriptions.length=0}insertContainerIntoMap(e,r,n,i){let[s,o]=this.createContainerFromSchema(r,i),a=e.setContainer(n,s);if(!a)throw new Error("Failed to insert container into map");return this.registerContainer(a.id,r),this.initializeContainer(a,r,i),a.kind()==="Map"&&this.stampCid(i,a.id),a}initializeContainer(e,r,n){let i=e.kind();if(i==="Map"){let s=e;if(!Sn(n))return;let o=r;for(let[a,u]of Object.entries(n)){if(a===Mn)continue;let c=this.getSchemaForMapKey(o,a);if(c&&Bu(c)){let l=xl(c);l&&Ra(l,u)?this.insertContainerIntoMap(s,c,a,u):s.set(a,u)}else s.set(a,u)}}else if(i==="List"||i==="MovableList"){let s=e;if(!Array.isArray(n))return;let o=r?.itemSchema,a=Bu(o);for(let u=0;u<n.length;u++){let c=n[u];if(a){let l=xl(o);l&&Ra(l,c)?this.insertContainerIntoList(s,o,u,c):s.insert(u,c)}else s.insert(u,c)}}else if(i==="Text")typeof n=="string"&&e.update(n);else if(i==="Tree"){let s=e;this.updateTreeContainer(s,n)}else throw new Error(`Unknown container kind: ${i}`)}createContainerFromSchema(e,r){let n=e?xl(e):El(r,this.options?.inferOptions);switch(n){case"Map":return[new Ln.LoroMap,"Map"];case"List":return[new Ln.LoroList,"List"];case"MovableList":return[new Ln.LoroMovableList,"MovableList"];case"Text":return[new Ln.LoroText,"Text"];case"Tree":return[new Ln.LoroTree,"Tree"];default:throw new Error(`Unknown schema type: ${n}`)}}insertContainerIntoList(e,r,n,i){let[s,o]=this.createContainerFromSchema(r,i),a;if(n===void 0?a=e.pushContainer(s):a=e.insertContainer(n,s),!a)throw new Error("Failed to insert container into list");return this.registerContainer(a.id,r),this.initializeContainer(a,r,i),a.kind()==="Map"&&this.stampCid(i,a.id),a}updateTreeContainer(e,r){if(!Array.isArray(r))throw new Error("Tree value must be an array of nodes");let n=yR(e.toJSON()),i=r,s=this.getContainerSchema(e.id),o=s&&no(s)?s:void 0,a=gR(this.doc,n,i,e.id,o,this.options?.inferOptions);if(a.length===0)return;let u=new Map;for(let l of a){let f=l.container,d=u.get(f);d?d.push(l):u.set(f,[l])}let c=u.get(e.id);c&&c.length&&(this.applyContainerChanges(e,c),u.delete(e.id));for(let[l,f]of u){if(l==="")continue;let d=this.doc.getContainerById(l);!d||f.length===0||this.applyContainerChanges(d,f)}}updateMapContainer(e,r){if(!Sn(r))throw new Error("Map value must be an object");let n=this.getContainerSchema(e.id);n&&Sn(r)&&ro(r,e.id);let i=new Set(e.keys());for(let[s,o]of Object.entries(r))if(s!==Mn){if(n&&n.type==="loro-map")this.updateMapEntry(e,s,o,n);else{let a=El(o,this.options?.inferOptions);a&&Ra(a,o)?this.insertContainerIntoMap(e,void 0,s,o):e.set(s,o)}i.delete(s)}for(let s of i)e.delete(s)}updateMapEntry(e,r,n,i){if(r!==Mn){if(i&&i.type==="loro-map"){let s=i,o=this.getSchemaForMapKey(s,r);if(o&&o.type==="ignore")return;if(o&&Bu(o)){let a=xl(o);if(a&&Ra(a,n)){this.insertContainerIntoMap(e,o,r,n);return}}}e.set(r,n)}}getState(){return this.state}setState(e,r){if(this.syncing)return;let n=typeof e=="function"?q_(this.state,o=>{let a=e(o);if(a&&a!==o)return a}):Object.assign({},this.state,e);if(this.options.validateUpdates){let o=this.schema&&fd(this.schema,n);if(o&&!o.valid){let a=`State validation failed: ${o.errors?.join(", ")}`;throw new Error(a)}}let i=r?.tags?Array.isArray(r.tags)?r.tags:[r.tags]:void 0;this.updateLoro(n,r),this.state=n,this.options.checkStateConsistency&&this.checkStateConsistency(),this.notifySubscribers(gd.TO_LORO,i)}checkStateConsistency(){let e=this.state;if(!Fa(e,this.buildRootStateSnapshot()))throw console.error("State diverged",JSON.stringify(e,null,2),JSON.stringify(this.buildRootStateSnapshot(),null,2)),new Error("[InternalError] State diverged")}containerToStateJson(e){let r=e.kind();if(r==="Map"){let n=e,i={};ro(i,e.id);for(let s of n.keys()){let o=n.get(s);i[s]=(0,Ln.isContainer)(o)?this.containerToStateJson(o):o}return i}else if(r==="List"||r==="MovableList"){let n=[],i=e,s=i.length;for(let o=0;o<s;o++){let a=i.get(o);n.push((0,Ln.isContainer)(a)?this.containerToStateJson(a):a)}return n}else{if(r==="Text")return e.toJSON();if(r==="Tree"){let n=e,i=yR(n.toJSON()),s=this.getContainerSchema(n.id);if(s&&no(s)){let a=new Map,c=n.getNodes?.()??[];for(let f of c)try{let d=f,p=typeof d.id=="string"?d.id:void 0,m;if(d.data&&typeof d.data=="object"){let _=d.data;m=typeof _.id=="string"?_.id:void 0}p&&m&&a.set(p,m)}catch{}let l=f=>{for(let d of f){let p=d,m=typeof p.id=="string"?a.get(p.id):void 0;m&&((!p.data||typeof p.data!="object")&&(p.data={}),ro(p.data,m)),Array.isArray(p.children)&&l(p.children)}};l(i)}return i}}return e.toJSON()}buildRootStateSnapshot(){if(!this.schema||this.schema.type!=="schema")return o2(this.doc);let e={},r=this.schema;for(let n in r.definition){let i=r.definition[n],s=xl(i);if(!s)continue;let o=F_(this.doc,n,s);if(s==="Map")e[n]=this.containerToStateJson(o);else if(s==="List"||s==="MovableList")e[n]=this.containerToStateJson(o);else if(s==="Text")e[n]=this.containerToStateJson(o);else if(s==="Tree"){let a=this.containerToStateJson(o);if(!Array.isArray(a)||a.length===0)continue;e[n]=a}else e[n]=this.containerToStateJson(o)}return e}registerContainerWithRegistry(e,r){this.containerRegistry.set(e,{schema:r,registered:!0})}stampCid(e,r){Sn(e)&&ro(e,r)}getSchemaForMapKey(e,r){if(!e)return;if(Object.prototype.hasOwnProperty.call(e.definition,r))return e.definition[r];let n=e;if(n.catchallType)return n.catchallType}getContainerSchema(e){return this.containerRegistry.get(e)?.schema}getSchemaForChildContainer(e,r){let n=this.getSchemaForChild(e,r);if(!(!n||!Bu(n)))return n}getSchemaForChild(e,r){let n=this.getContainerSchema(e);if(n){if(Ru(n))return this.getSchemaForMapKey(n,String(r));if(Pu(n)||Nu(n))return n.itemSchema;if(no(n))return n.nodeSchema}}getContainerIds(){return Array.from(this.containerRegistry.keys())}};function o2(t){let e=t.toJsonWithReplacer((r,n)=>(0,Ln.isContainer)(n)&&n.kind()==="Tree"?yR(n.toJSON()):(0,Ln.isContainer)(n)&&n.kind()==="Map"?{...n.getShallowValue(),[Mn]:n.id}:n);return _R(e)}function _R(t){if(Array.isArray(t)){for(let e=0;e<t.length;e++)t[e]=_R(t[e]);return t}if(Sn(t)){let e=t;for(let r of Object.keys(e))e[r]=_R(e[r]);if(Object.prototype.hasOwnProperty.call(e,Mn)){let r=Object.getOwnPropertyDescriptor(e,Mn);if(!r||r.enumerable){let n=e[Mn];delete e[Mn],Object.defineProperty(e,Mn,{value:n})}}return e}return t}function bLe(t){let e={};for(let[r,n]of Object.entries(t))Array.isArray(n)?e[r]=[]:typeof n=="string"?e[r]="":Sn(n)?e[r]={}:e[r]=n;return e}function yR(t){return Array.isArray(t)?t.map(OZ):[]}function OZ(t){let e=t?.id,r=typeof e=="string"?e:"",n=t?.meta,i=typeof n=="object"&&n!=null&&!Array.isArray(n)?n:{},s=t?.children,o=Array.isArray(s)?s.map(OZ):[];return{id:r,data:i,children:o}}function FZ(t,e,r){for(let[n,i]of Object.entries(e)){let s=r.definition[n];if(!s){n in t||(Array.isArray(i)?t[n]=[]:typeof i=="string"?t[n]="":Sn(i)&&(t[n]={}));continue}let o=s.type;if(o==="ignore"){t[n]=i;continue}if(o==="loro-map"){(!(n in t)||!Sn(t[n]))&&(t[n]={});let a=t[n],u=Sn(i)?i:{};FZ(a,u,{type:"schema",definition:s.definition,options:{},getContainerType(){return"Map"}});continue}if(o==="loro-list"||o==="loro-movable-list"){n in t||(t[n]=[]);continue}if(o==="loro-text"){n in t||(t[n]="");continue}if(o==="string"||o==="number"||o==="boolean"){n in t||(t[n]=i);continue}}}var Wyt=Object.assign({},nR,vR);var Kyt=Ee.LoroMap({name:Ee.String(),color:Ee.String()}),Jyt=Ee.LoroMap({content:Ee.LoroText(),parentId:Ee.String({required:!1}),isDeleted:Ee.Boolean()}),xLe=Ee.LoroMap({type:Ee.String(),by:Ee.String(),timestamp:Ee.String(),target:Ee.String({required:!1}),value:Ee.String({required:!1}),commentId:Ee.String({required:!1}),sessionId:Ee.String({required:!1})}),ELe=Ee.LoroMap({id:Ee.String(),title:Ee.String(),description:Ee.LoroText({required:!1}),status:Ee.String(),priority:Ee.String(),assigneeId:Ee.String({required:!1}),assigneeName:Ee.String({required:!1}),agent:Ee.String({required:!1}),githubRepo:Ee.String({required:!1}),labels:Ee.LoroList(Ee.String()),estimate:Ee.Number({required:!1}),dueDate:Ee.String({required:!1}),createdAt:Ee.String(),createdBy:Ee.String(),actionHistory:Ee.LoroList(xLe,t=>t.$cid),subIssues:Ee.LoroList(Ee.String()),parentIssueId:Ee.String({required:!1}),attachments:Ee.LoroList(Ee.String())}),RZ=Ee({issue:ELe}),wLe=Ee.LoroMap({id:Ee.String(),name:Ee.String(),description:Ee.LoroText({required:!1}),cliType:Ee.String(),machineId:Ee.String({required:!1}),env:Ee.LoroMapRecord(Ee.String())}),PZ=Ee({config:wLe}),SLe=Ee.LoroMap({contents:Ee.String(),timestamp:Ee.String(),role:Ee.String(),read:Ee.Boolean({required:!1}),userId:Ee.String({required:!1})}),CLe=Ee.LoroMap({id:Ee.String(),machineId:Ee.String(),title:Ee.String({required:!1}),userId:Ee.String(),issueId:Ee.String({required:!1}),status:Ee.String(),history:Ee.LoroList(SLe,t=>t.timestamp),error:Ee.String({required:!1}),createdAt:Ee.String(),cliType:Ee.String(),agentConfigId:Ee.String({required:!1}),chatId:Ee.String({required:!1})}),NZ=Ee({session:CLe}),DLe=Ee.LoroMap({userId:Ee.String(),avatar:Ee.String({required:!1}),name:Ee.String(),email:Ee.String(),role:Ee.String()}),ALe=Ee.LoroMap({id:Ee.String(),name:Ee.String(),githubRepos:Ee.LoroList(Ee.String()),members:Ee.LoroList(DLe,t=>t.userId)}),ILe=Ee.LoroMap({name:Ee.String(),color:Ee.String()}),BZ=Ee({meta:ALe,issues:Ee.LoroList(Ee.LoroMap({id:Ee.String(),isDeleted:Ee.Boolean()}),t=>t.id),sessions:Ee.LoroList(Ee.LoroMap({id:Ee.String(),isDeleted:Ee.Boolean()}),t=>t.id),agentConfigs:Ee.LoroList(Ee.LoroMap({id:Ee.String(),isDeleted:Ee.Boolean()}),t=>t.id),labels:Ee.LoroList(ILe,t=>t.$cid)}),MZ=t=>`issue-${t}`,LZ=t=>`session-${t}`,qZ=t=>`agent-${t}`;var TLe=5*60*1e3,UZ=t=>`ephemeral-${t}`,bR="machine-",Mu=t=>`${bR}${t}`,a2=class{constructor(e){this.store=e}aliveTimer=null;registerMachine(e,r){this.store.set(Mu(e),r),this.aliveTimer=setInterval(()=>{this.store.set(Mu(e),this.store.get(Mu(e)))},TLe/2)}unRegisterMachine(e){this.store.delete(Mu(e)),this.aliveTimer&&clearInterval(this.aliveTimer)}getMachineIds(){return this.store.keys().filter(e=>e.startsWith(bR)).map(e=>e.replace(bR,""))}getMachine(e){return this.store.get(Mu(e))}addMachineSession(e,r){let n=this.getMachine(e);if(n){let i=[...n.sessions,r];this.store.set(Mu(e),{...n,sessions:i})}}removeMachineSession(e,r){let n=this.getMachine(e);if(n){let i=n.sessions.filter(s=>s.sessionId!==r);this.store.set(Mu(e),{...n,sessions:i})}}updateMachineSession(e,r,n){let i=this.getMachine(e);if(i){let s=i.sessions.map(o=>o.sessionId===r?{...o,status:{...o.status,...n}}:o);this.store.set(Mu(e),{...i,sessions:s})}}updateMachine(e,r){let n=this.getMachine(e);n&&this.store.set(Mu(e),{...n,...r})}};var Y7e=qe(Nee(),1),Q7e=qe(OR(),1),K7e=qe(PR(),1),Vee=qe(v2(),1),J7e=qe(Wee(),1);var Al=Vee.default;globalThis.WebSocket=Al;var qo=B4(),x2=class{constructor(e,r){this.workspaceId=e;this.token=r;qo.debug(`[${this.workspaceId}] LoroWebsocketClient url: ${a0+`/ws/${this.workspaceId}`}`),this.client=new aZ({url:a0+`/ws/${this.workspaceId}`,onWsClose:()=>{qo.debug(`[${this.workspaceId}] LoroWebsocketClient ws closed`),this.client.connect()}}),this.docMirror=new $R(this.client),this.ephemeral=new a2(this.ephemeralAdaptor.getStore())}client;docMirror;issues=new Map;sessions=new Map;workspaces=new Map;agents=new Map;ephemeral;ephemeralAdaptor=new oZ(new zee.EphemeralStore(24*60*60*1e3));async waitConnected(){await this.client.waitConnected(),await this.client.join({roomId:UZ(this.workspaceId),crdtAdaptor:this.ephemeralAdaptor})}disconnect(){this.client.close()}async getOrCreateAgentDoc(e){if(!this.agents.has(e)){let r=new zR(this.docMirror,e);await r.init(),this.agents.set(e,r)}return this.agents.get(e)}async getOrCreateIssueDoc(e){if(!this.issues.has(e)){let r=new HR(this.docMirror,e);await r.init(),this.issues.set(e,r)}return this.issues.get(e)}async getOrCreateSessionDoc(e){if(!this.sessions.has(e)){let r=new WR(this.docMirror,e);await r.init(),this.sessions.set(e,r)}return this.sessions.get(e)}async getOrCreateWorkspaceDoc(e,r){if(!this.workspaces.has(e)){let n=new VR(this.docMirror,r,e,this);await n.init(),this.workspaces.set(e,n)}return this.workspaces.get(e)}async cleanUp(){for(let e of this.sessions.values())e.destroy();for(let e of this.issues.values())e.destroy();for(let e of this.workspaces.values())e.destroy();this.issues.clear(),this.workspaces.clear(),this.sessions.clear()}async cleanSessionDoc(e){let r=this.sessions.get(e);r&&(r.destroy(),this.sessions.delete(e))}},$R=class{constructor(e){this.client=e}adaptors=new Map;rooms=new Map;mirrors=new Map;async getAdaptor(e){if(!this.adaptors.has(e)){let r=new sZ(void 0,{onImportError(i,s){qo.error(`Error occurs when importing loro data ${i}`)},onUpdateError(i){qo.error(`Error occurs when updating loro ${i}`)}});qo.debug(`[${e}] waiting for client connected`),await this.client.waitConnected(),qo.debug(`[${e}] joining room`);let n=await this.client.join({roomId:e,crdtAdaptor:r});await n.waitForReachingServerVersion(),qo.debug(`[${e}] joined room frontiers: ${JSON.stringify(r.getDoc().frontiers())}`),this.rooms.set(e,n),this.adaptors.set(e,r)}return this.adaptors.get(e)}async getMirror(e,r,n){if(this.mirrors.has(e))return this.mirrors.get(e);let i=await this.getAdaptor(e),s=new _d({doc:i.getDoc(),schema:r,initialState:n});return this.mirrors.set(e,s),s}close(e){this.adaptors.get(e)&&this.adaptors.delete(e);let n=this.rooms.get(e);n&&(this.rooms.delete(e),n.leave());let i=this.mirrors.get(e);i&&(this.mirrors.delete(e),i.dispose())}closeAll(){for(let e of this.rooms.keys())this.close(e)}},HR=class{constructor(e,r){this.docMirror=e;this.issueId=r;this.roomId=MZ(this.issueId)}mirror=null;roomId;async init(){this.mirror=await this.docMirror.getMirror(this.roomId,RZ)}getState(){if(!this.mirror)throw new Error("Mirror not initialized");return this.mirror.getState().issue}async setStatus(e){if(!this.mirror)throw new Error("Mirror not initialized");let r=await this.docMirror.getAdaptor(this.roomId);qo.debug(`[${this.issueId}] doc frontiers: ${JSON.stringify(r.getDoc().frontiers())}`),this.mirror.setState(n=>(n.issue.status!==e?(qo.debug(`[${this.issueId}] setStatus ${e}`),n.issue.status=e,n.issue.actionHistory.push({type:"update",target:"status",value:JSON.stringify(e),by:"lody-cli",timestamp:new Date().toISOString()})):qo.debug(`[${this.issueId}] setStatus ${e} no change`),n))}destroy(){this.docMirror.close(this.roomId)}},WR=class{constructor(e,r){this.docMirror=e;this.sessionId=r;this.roomId=LZ(this.sessionId)}mirror=null;roomId="";async init(){this.mirror=await this.docMirror.getMirror(this.roomId,NZ)}getState(){if(!this.mirror)throw new Error("Mirror not initialized");return this.mirror.getState().session}async markHistoryAsRead(e){if(!this.mirror)throw new Error("Mirror not initialized");this.mirror.setState(r=>{let n=r.session.history??[];for(let i of n)if(i.$cid===e){i.read=!0;break}return r})}async setChatId(e){if(!this.mirror)throw new Error("Mirror not initialized");qo.debug(`[${this.sessionId}] setChatId ${e}`),this.mirror.setState(r=>(r.session.chatId=e,r))}async setError(e){if(!this.mirror)throw new Error("Mirror not initialized");this.mirror.setState(r=>(r.session.error=e,r.session.status="error",r))}getStatus(){return this.mirror?this.mirror.getState().session.status:"terminated"}isChat(){return this.mirror?!!this.mirror.getState().session.chatId:!1}async getIssueId(){if(this.mirror)return this.mirror.getState().session.issueId}async setStatus(e){if(!this.mirror)throw new Error("Mirror not initialized");this.mirror.setState(r=>(r.session.status=e,r))}async getHistory(){return this.mirror?this.mirror.getState().session.history||[]:[]}async updateHistory(e){if(!this.mirror)throw new Error("Mirror not initialized");this.mirror.setState(r=>{let n=e(r.session.history||[]);return r.session.history=n,r})}destroy(){if(!this.mirror){this.docMirror.close(this.roomId);return}let e=this.getStatus();e==="running"||e==="requestPermission"?this.setStatus("error"):(e==="completed"||e==="terminated")&&this.setStatus("terminated"),this.docMirror.close(this.roomId)}},VR=class{constructor(e,r,n,i){this.docMirror=e;this.userId=r;this.workspaceId=n;this.manager=i;this.roomId=`workspace-${this.workspaceId}`}mirror=null;roomId;async init(){this.mirror=await this.docMirror.getMirror(this.roomId,BZ)}async createSession(e,r,n){if(!this.mirror)throw new Error("Mirror not initialized");let i=o0(),s=await this.manager.getOrCreateSessionDoc(i);return await s.init(),s.mirror?.setState(o=>({session:{...o.session,id:i,machineId:e,cliType:r,userId:this.userId,status:"running",history:[],title:n,createdAt:new Date().toISOString()}})),this.mirror.setState(o=>{o.sessions.push({id:i,isDeleted:!1})}),i}async hasAgentConfig(e,r){if(!this.mirror)throw new Error("Mirror not initialized");let n=this.mirror.getState().agentConfigs,i=!1;for(let s of n){if(s.isDeleted)continue;let a=(await this.manager.getOrCreateAgentDoc(s.id)).getState().config;if(i||=a.cliType===e&&a.machineId===r,i)break}return i}async createAgentConfig(e,r){if(!this.mirror)throw new Error("Mirror not initialized");let n=o0(),i=await this.manager.getOrCreateAgentDoc(n);return await i.init(),i.mirror?.setState(s=>({config:{id:n,name:e,description:"Default agent config created by Lody CLI",machineId:r,cliType:e,env:{},createdAt:new Date().toISOString()}})),this.mirror.setState(s=>{s.agentConfigs.push({id:n,isDeleted:!1})}),n}destroy(){this.docMirror.close(this.roomId)}getState(){if(!this.mirror)throw new Error("Mirror not initialized");return this.mirror.getState()}},zR=class{constructor(e,r){this.docMirror=e;this.agentId=r;this.roomId=qZ(this.agentId)}mirror=null;roomId;async init(){this.mirror=await this.docMirror.getMirror(this.roomId,PZ)}async destroy(){this.docMirror.close(this.roomId)}getState(){if(!this.mirror)throw new Error("Mirror not initialized");return this.mirror.getState()}};var Gee=require("events");var E2=class extends Gee.EventEmitter{ws=null;token;workspaceId;reconnectInterval;maxReconnectAttempts;reconnectAttempts=0;reconnectTimer=null;keepaliveTimer=null;isManualClose=!1;isConnected=!1;logger;constructor(e){super(),this.token=e.token,this.reconnectInterval=e.reconnectInterval||5e3,this.maxReconnectAttempts=e.maxReconnectAttempts||5,this.logger=e.logger,this.workspaceId=e.workspaceId}connect(){return new Promise((e,r)=>{try{let n=new URL(`${a0}/lody/${this.workspaceId}`);this.token&&n.searchParams.append("token",this.token),this.logger.debug(`Connecting to WebSocket: ${n}`),this.ws=new Al(n.toString(),{perMessageDeflate:!1,handshakeTimeout:15e3}),this.setupEventHandlers();let i=()=>{this.ws?.removeListener("error",s),e()},s=o=>{this.ws?.removeListener("open",i),r(o)};this.ws.once("open",i),this.ws.once("error",s),setTimeout(()=>{this.isConnected||(this.ws?.removeListener("open",i),this.ws?.removeListener("error",s),r(new Error("Connection timeout")))},3e4)}catch(n){r(n)}})}setupEventHandlers(){this.ws&&(this.ws.on("open",()=>{this.isConnected=!0,this.reconnectAttempts=0,this.logger.debug("WebSocket connected"),this.emit("open"),this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.keepaliveTimer=setInterval(()=>{this.ws?.readyState===Al.OPEN&&this.ws.send("ping")},3e4)}),this.ws.on("message",e=>{this.emit("message",e)}),this.ws.on("close",(e,r)=>{this.isConnected=!1,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.logger.warn(`WebSocket disconnected: code=${e}, reason=${r}`),this.emit("close",e,r),this.isManualClose||this.scheduleReconnect()}),this.ws.on("error",e=>{this.logger.error(`WebSocket error: ${e.message}`),e.message.includes("401")&&(this.logger.error("Authentication failed. Check your token."),this.close(),process.exit(1)),this.emit("error",e)}),this.ws.on("ping",e=>{this.ws?.readyState===Al.OPEN&&this.ws.pong(e)}))}scheduleReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){this.logger.error(`Max reconnection attempts (${this.maxReconnectAttempts}) reached`),this.emit("max_reconnect_exceeded");return}this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectAttempts++;let e=Math.min(this.reconnectInterval*Math.pow(1.5,this.reconnectAttempts-1),6e4);this.logger.info(`Reconnecting in ${e}ms... (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`),this.reconnectTimer=setTimeout(()=>{this.reconnect()},e)}async reconnect(){try{this.logger.info("Attempting to reconnect..."),await this.connect(),this.logger.info("Reconnected successfully"),this.emit("reconnected")}catch(e){this.logger.error(`Reconnection failed: ${e instanceof Error?e.message:"Unknown error"}`)}}send(e){if(this.ws?.readyState===Al.OPEN)this.ws.send(e);else throw this.logger.warn("Cannot send message: WebSocket is not connected"),new Error("WebSocket is not connected")}getSocket(){return this.ws}isReady(){return this.ws?.readyState===Al.OPEN}close(){this.isManualClose=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.ws&&(this.ws.close(),this.ws=null)}resetReconnectAttempts(){this.reconnectAttempts=0}};function Yee(t,e,r){var n=r||{},i=n.noTrailing,s=i===void 0?!1:i,o=n.noLeading,a=o===void 0?!1:o,u=n.debounceMode,c=u===void 0?void 0:u,l,f=!1,d=0;function p(){l&&clearTimeout(l)}function m(v){var E=v||{},A=E.upcomingOnly,F=A===void 0?!1:A;p(),f=!F}function _(){for(var v=arguments.length,E=new Array(v),A=0;A<v;A++)E[A]=arguments[A];var F=this,D=Date.now()-d;if(f)return;function U(){d=Date.now(),e.apply(F,E)}function I(){l=void 0}!a&&c&&!l&&U(),p(),c===void 0&&D>t?a?(d=Date.now(),s||(l=setTimeout(c?I:U,t))):U():s!==!0&&(l=setTimeout(c?I:U,c===void 0?t-D:t))}return _.cancel=m,_}var K_=t=>t&&t.replace(/^['"]+|['"]+$/g,""),X7e=(t,e)=>{if(!e)return t;let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return t.replace(new RegExp(r,"g"),"***TOKEN***")},Z7e=(t,e)=>{let r=K_(t)??t,n=K_(e?.trim());if(!n)return{cloneUrl:`https://github.com/${r}.git`};let i=encodeURIComponent(n);return n.startsWith("ghs_")?{cloneUrl:`https://x-access-token:${i}@github.com/${r}.git`,rewriteBase:`https://x-access-token:${i}@github.com/`}:{cloneUrl:`https://${i}@github.com/${r}.git`,rewriteBase:`https://${i}@github.com/`}},Qee=(t,e)=>{if(!e)return t;let r=["https://github.com/","git@github.com:","ssh://git@github.com/"],n=new Set;for(let s of r)n.add(s);let i=[];for(let s of n)i.push("-c",`url.${e}.insteadOf=${s}`);return[...i,...t]},Kee=async(t,e,r,n,i,s)=>{let o=X7e([r,...n].join(" "),s);return e.debug(`[${t.sessionId}] Executing (${i}): ${o}`),await t.exec(r,n,i,!1)},Jee=async(t,e,r,n)=>{let i=r.sessionId,s=r.getWorkdir();try{let o=K_(t?.trim())??t?.trim();if(!o){n.info(`[${i}] No GitHub repository specified, skipping clone`);return}if(n.info(`[${i}] Cloning GitHub repository: ${o}`),!o.match(/^[^/]+\/[^/]+$/))throw new Error(`Invalid GitHub repository format: ${o}. Expected format: owner/repo`);let{cloneUrl:a,rewriteBase:u}=Z7e(o,e),c=K_(a)??a,l=K_(u);e?e.startsWith("ghs_")?n.info(`[${i}] Using GitHub App token for authentication`):n.info(`[${i}] Using GitHub token for authentication`):n.info(`[${i}] Cloning public repository`),await Kee(r,n,"git",Qee(["clone","--depth","1","--recurse-submodules","--shallow-submodules",c,s],l),"/",e),await Kee(r,n,"git",Qee(["-C",s,"submodule","update","--init","--recursive","--depth","1"],l),"/",e),n.info(`[${i}] Successfully cloned repository: ${o}`)}catch(o){throw n.error(`[${r.sessionId}] Failed to clone GitHub repository: ${o instanceof Error?o.message:"Unknown error"}`),o}};var w2=class{constructor(e,r,n,i,s){this.workspaceDocument=n;this.socket=e,this.sessionManager=r,this.logger=i,this.token=s.token,this.userId=s.userId,this.workspaceId=s.workspaceId,this.machineName=s.machineName,this.enableDocker=s.enableDocker,this.cliVersion=s.cliVersion,this.machineId=s.machineId,this.sessionManager.setRequestPermissionHandler((o,a,u)=>this.handleAgentPermissionRequest(o,a,u)),this.setupSessionEventHandlers(),this.registerMachine()}socket;sessionManager;logger;machineId;token;userId;workspaceId;machineName;enableDocker;cliVersion;pendingPermissionRequests=new Map;acpUpdateBuffers=new Map;acpUpdateThrottlers=new Map;acpUpdateThrottleMs=200;setupSessionEventHandlers(){this.sessionManager.on("output",async e=>{this.logger.debug(`Output from session [${e.sessionId}]: ${e.data}`)}),this.sessionManager.on("onACPUpdateMessage",(e,r)=>{this.logger.debug(`[${e}] Received ACP update message ${r}`),this.enqueueACPUpdate(e,r)}),this.sessionManager.on("error",async e=>{this.logger.error(`[${e.sessionId}] error occur ${e}`);let r=e.sessionId;await this.finalizeACPState(r),(await this.workspaceDocument.getOrCreateSessionDoc(r)).setError("execution_error"),await this.sessionManager.finishSession(r),this.workspaceDocument.ephemeral.removeMachineSession(this.machineId,r)}),this.sessionManager.on("exit",async e=>{let r=e.sessionId;await this.finalizeACPState(r),(await this.workspaceDocument.getOrCreateSessionDoc(r)).setStatus("completed");let i=new Date().toISOString();this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"completed",completedAt:i})})}enqueueACPUpdate(e,r){let n=this.acpUpdateBuffers.get(e);n?n.push(r):this.acpUpdateBuffers.set(e,[r]),this.getOrCreateACPUpdateThrottler(e)()}getOrCreateACPUpdateThrottler(e){let r=this.acpUpdateThrottlers.get(e);return r||(r=Yee(this.acpUpdateThrottleMs,()=>this.flushACPUpdates(e).catch(n=>{this.logger.error(`[${e}] Failed to flush ACP updates: ${n instanceof Error?n.message:"Unknown error"}`)})),this.acpUpdateThrottlers.set(e,r),r)}async flushACPUpdates(e){this.acpUpdateThrottlers.get(e)?.cancel({upcomingOnly:!0});let r=this.acpUpdateBuffers.get(e);if(!r||r.length===0){this.acpUpdateBuffers.delete(e);return}this.acpUpdateBuffers.delete(e);let n=await this.workspaceDocument.getOrCreateSessionDoc(e);await eqe(n,r)}async flushAllACPUpdates(){let e=Array.from(new Set([...this.acpUpdateBuffers.keys(),...this.acpUpdateThrottlers.keys()]));for(let r of e)await this.finalizeACPState(r)}async finalizeACPState(e){try{await this.flushACPUpdates(e)}catch(r){this.logger.error(`[${e}] Failed to flush ACP updates during finalization: ${r instanceof Error?r.message:"Unknown error"}`)}finally{this.clearACPState(e)}}clearACPState(e){this.acpUpdateBuffers.delete(e),this.acpUpdateThrottlers.get(e)?.cancel(),this.acpUpdateThrottlers.delete(e)}registerMachine(){let e={type:"register",role:"machine",id:this.machineId,token:this.token,workspaceId:this.workspaceId,userId:this.userId,machineInfo:{name:this.machineName,cliVersion:this.cliVersion,os:process.platform,enableDocker:this.enableDocker}};this.sendMessage(e),this.logger.info(`Machine registered with name: ${this.machineName}`)}async handleMessage(e){switch(this.logger.debug(`Received message: ${e.type}`),e.type){case"register_response":await this.handleRegisterResponse(e);break;case"session_create":await this.handleSessionCreate(e);break;case"session_terminate":await this.handleSessionTerminate(e);break;case"session_stop":await this.handleSessionStop(e);break;case"permission_response":await this.handlePermissionResponse(e);break;case"session_chat":await this.handleSessionChat(e);break;default:this.logger.debug(`Unknown message: ${e}`)}}async handleSessionChat(e){let{sessionId:r,promptConfig:n,historyCid:i}=e;if(this.logger.info(`[${r}] Received chat request`),i)try{await(await this.workspaceDocument.getOrCreateSessionDoc(r)).markHistoryAsRead(i),this.logger.debug(`[${r}] Marked history as read`)}catch(o){this.logger.warn(`[${r}] Failed to mark history as read: ${o instanceof Error?o.message:"Unknown error"}`)}this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"running",cliType:n.agentType,createdAt:new Date().toISOString()});let s=this.sessionManager.getSession(r);s?(await s.agentClient?.connection?.prompt({sessionId:s.acpSessionId,prompt:[{type:"text",text:n.prompt}]}),this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"completed",completedAt:new Date().toISOString()}),await this.finalizeACPState(r),this.logger.info(`[${r}] Chat request processed successfully`)):(this.logger.warn(`[${r}] Session not found`),(await this.workspaceDocument.getOrCreateSessionDoc(r)).setError("session_not_found"),this.workspaceDocument.ephemeral.removeMachineSession(this.machineId,r))}async handleRegisterResponse(e){e.success?this.logger.info(`Registration successful, machine ID: ${this.machineId}`):this.logger.error(`Registration failed: ${e.error}`)}async handleSessionCreate(e){let{sessionId:r,config:n,workspaceId:i}=e;this.logger.info(`[${r}] Creating new session`);let s={sessionId:r,workspaceId:i,cliType:n.promptConfig.agentType,userId:this.userId,machineId:this.machineId,assumeDocExisting:!0,env:n.env};this.workspaceDocument.ephemeral.addMachineSession(this.machineId,{sessionId:r,status:{status:"establish",createdAt:new Date().toISOString()}});try{let o=await this.sessionManager.createSession(s);if(this.sendMessage({type:"session_create_response",sessionId:r,success:!0}),n.githubRepo&&n.githubToken){this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"git-clone",repo:n.githubRepo});try{await Jee(n.githubRepo,n.githubToken,o,this.logger)}catch(f){let d=f instanceof Error?f.message:"Failed to clone GitHub repository";this.logger.error(`[${r}] ${d}`),await this.sessionManager.setSessionError(r,"execution_error"),this.workspaceDocument.ephemeral.removeMachineSession(this.machineId,r),await this.finalizeACPState(r);return}}let a=n.promptConfig;this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"running",cliType:s.cliType});let u=await o.agentClient?.connection?.prompt({sessionId:o.acpSessionId,prompt:[{type:"text",text:a.prompt}]});(await this.workspaceDocument.getOrCreateSessionDoc(r)).setStatus("completed");let l=new Date().toISOString();this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"completed",completedAt:l}),this.logger.debug(`[${r}] Prompt response: ${JSON.stringify(u)}`),await this.finalizeACPState(r),this.logger.info(`[${r}] Session created successfully`)}catch{await this.finalizeACPState(r),await this.sessionManager.setSessionError(r,"execution_error"),this.sendMessage({type:"session_create_response",sessionId:r,success:!1})}}async handleSessionTerminate(e){let{sessionId:r,force:n}=e;this.logger.info(`[${r}] Terminating session`);try{await this.sessionManager.terminateSession(r,n),await this.finalizeACPState(r);let i={type:"session_terminated",sessionId:r,error:void 0,reason:"user_request"};this.sendMessage(i),this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"terminated"}),this.logger.info(`[${r}] Session terminated successfully`)}catch(i){let s={type:"session_terminated",sessionId:r,error:"execution_error",reason:"error"};this.sendMessage(s),this.logger.error(`[${r}] Failed to terminate: ${i instanceof Error?i.message:"Unknown error"}`)}}async handleSessionStop(e){let{sessionId:r}=e;this.logger.info(`[${r}] Received stop request`);let n=this.sessionManager.getSession(r);if(!n){this.logger.warn(`[${r}] Session not found for stop request`);return}if(!n.agentClient?.connection||!n.acpSessionId){this.logger.warn(`[${r}] Cannot stop session without active ACP connection`);return}try{await n.agentClient.connection.cancel({sessionId:n.acpSessionId}),await this.finalizeACPState(r),(await this.workspaceDocument.getOrCreateSessionDoc(r)).setStatus("completed");let s=new Date().toISOString();this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"completed",completedAt:s}),this.logger.info(`[${r}] Stop signal sent to agent`)}catch(i){this.logger.error(`[${r}] Failed to stop session: ${i instanceof Error?i.message:"Unknown error"}`)}}async handlePermissionResponse(e){this.logger.info(`[${e.sessionId}] Permission response received for ${e.requestId}: ${e.outcome.outcome}`);let r=this.pendingPermissionRequests.get(e.requestId);r?(r.resolve({outcome:e.outcome}),this.pendingPermissionRequests.delete(e.requestId)):this.logger.warn(`[${e.sessionId}] No pending permission request found for ${e.requestId}`);try{let n=await this.workspaceDocument.getOrCreateSessionDoc(e.sessionId);await iqe(n,e.requestId,e.outcome)}catch(n){this.logger.error(`[${e.sessionId}] Failed to update permission outcome: ${n instanceof Error?n.message:"Unknown error"}`)}}async handleAgentPermissionRequest(e,r,n){this.logger.info(`[${e}] Forwarding permission request ${r} for tool call ${n.toolCall.toolCallId}`);try{let s=await this.workspaceDocument.getOrCreateSessionDoc(e);await nqe(s,r,n)}catch(s){this.logger.error(`[${e}] Failed to append permission request to history: ${s instanceof Error?s.message:"Unknown error"}`)}let i={type:"request_permission",sessionId:e,requestId:r,request:n};return this.sendMessage(i),new Promise((s,o)=>{this.pendingPermissionRequests.has(r)&&this.logger.warn(`[${e}] Duplicate permission request ID detected: ${r}, overwriting existing handler`),this.pendingPermissionRequests.set(r,{resolve:s,reject:o,sessionId:e})})}sendMessage(e){try{this.socket.send(JSON.stringify(e))}catch(r){this.logger.error(`Failed to send message: ${r instanceof Error?r.message:"Unknown error"}`)}}updateSocket(e){this.socket=e,this.logger.debug("WebSocket instance updated")}async cleanup(){this.logger.info("Cleaning up message handler resources"),await this.flushAllACPUpdates(),this.acpUpdateThrottlers.forEach(e=>e.cancel()),this.acpUpdateThrottlers.clear(),await this.sessionManager.cleanUp()}},eqe=async(t,e)=>{let r=Array.isArray(e)?e:[e],n=[];for(let i of r)n.push(...tqe(i));n.length&&await t.updateHistory(i=>{let s=i;for(let o of n)s=rqe(s,o);return s})},tqe=t=>{let{update:e}=t;switch(e.sessionUpdate){case"user_message_chunk":return[];case"agent_message_chunk":case"agent_thought_chunk":switch(e.content.type){case"text":return[{type:"text",text:e.content.text}];case"image":case"audio":case"resource_link":case"resource":throw new Error(`Unsupported content type: ${e.content.type}`)}return[];case"tool_call":case"tool_call_update":return[{type:"tool_call",toolCallId:e.toolCallId,title:e.title,kind:e.kind||void 0,status:e.status||"pending",content:e.content?.map(r=>{switch(r.type){case"diff":return{type:r.type,path:r.path,newText:r.newText,oldText:r.oldText};case"terminal":case"content":return}}).filter(r=>r!==void 0)}];case"plan":return[{type:"plan",entries:e.entries}];case"available_commands_update":return[{type:"available_commands",commands:e.availableCommands}];case"current_mode_update":throw new Error(`Unsupported session update: ${e.sessionUpdate}`);default:return[]}},rqe=(t,e)=>{let r=t.length-1,n=r>=0?t[r]:null;if(!n||n.role!=="assistant")return GR(t,[e]);let i=s=>{let o=JSON.parse(n.contents),a=s(o),u={...n,contents:JSON.stringify(a)},c=[...t];return c[r]=u,c};switch(e.type){case"text":case"thought":return i(s=>{let o=[...s],a=o.findIndex(u=>u.type===e.type);if(a>=0){let u=o[a];(u.type==="text"||u.type==="thought")&&(o[a]={...u,text:u.text+(u.type==="thought"?`
|
|
192
192
|
`:"")+e.text})}else o.push({...e});return o});case"plan":return i(s=>{let o=[...s],a=o.findIndex(u=>u.type==="plan");return a>=0?o[a]={...e}:o.push({...e}),o});case"tool_call":{let s=!1,o=t.map(a=>{let u=JSON.parse(a.contents),c=!1,l=u.map(f=>{if(f.type==="tool_call"&&f.toolCallId===e.toolCallId){c=!0,s=!0;let d=f.content||[];if(e.content!==void 0){let p=e.content;p.some(_=>_.type==="diff")&&(d=d.filter(_=>_.type!=="diff")),d=[...d,...p]}return{...f,toolCallId:e.toolCallId,title:e.title!==void 0?e.title:f.title,kind:e.kind!==void 0?e.kind:f.kind,status:e.status!==void 0?e.status:f.status,content:d}}return f});return c?{...a,contents:JSON.stringify(l)}:a});return s?o:GR(o,[e])}case"available_commands":return GR(t,[e]);default:return t}},GR=(t,e)=>[...t,{role:"assistant",contents:JSON.stringify(e),timestamp:new Date().toISOString(),userId:void 0,read:void 0}],nqe=async(t,e,r)=>{let n=r.toolCall.toolCallId;await t.updateHistory(i=>{let s=!1;return i.forEach(o=>{let a=JSON.parse(o.contents),u=!1,c=a.map(l=>l.type==="tool_call"&&l.toolCallId===n?(u=!0,s=!0,Xee(l,e,r)):l);u&&(o.contents=JSON.stringify(c))}),s||i.push({role:"assistant",contents:JSON.stringify([sqe(e,r)]),timestamp:new Date().toISOString(),read:void 0,userId:void 0}),i})},iqe=async(t,e,r)=>{await t.updateHistory(n=>(n.forEach(i=>{let s=JSON.parse(i.contents),o=!1,a=s.map(u=>u.type==="tool_call"&&u.permissionRequest?.requestId===e?(o=!0,{...u,permissionRequest:u.permissionRequest?{...u.permissionRequest,outcome:r}:u.permissionRequest}):u);o&&(i.contents=JSON.stringify(a))}),n))},Xee=(t,e,r)=>{let n=r.toolCall;return{...t,title:t.title??n.title??null,kind:t.kind??n.kind??void 0,status:t.status??n.status??"pending",content:t.content??n.content??void 0,locations:t.locations??n.locations??void 0,rawInput:t.rawInput??n.rawInput??void 0,rawOutput:t.rawOutput??n.rawOutput??void 0,permissionRequest:{requestId:e,options:r.options,outcome:t.permissionRequest?.outcome}}},sqe=(t,e)=>{let r={type:"tool_call",toolCallId:e.toolCall.toolCallId,title:e.toolCall.title??null,status:e.toolCall.status??"pending",kind:e.toolCall.kind??void 0,content:e.toolCall.content??void 0,locations:e.toolCall.locations??void 0,rawInput:e.toolCall.rawInput??void 0,rawOutput:e.toolCall.rawOutput??void 0};return Xee(r,t,e)};var S2=class{constructor(e){this.options=e;this.manager=new E2(e.managerOptions),this.logger=e.logger}manager;handler=null;sessionManager=null;initialized=!1;logger;async initialize(){if(this.initialized)return{socket:this.requireSocket(),sessionManager:this.requireSessionManager(),messageHandler:this.requireHandler()};await this.options.workspaceDocument.waitConnected(),await this.manager.connect();let e=this.requireSocket();return this.sessionManager=this.options.sessionManagerFactory(e),this.handler=new w2(e,this.sessionManager,this.options.workspaceDocument,this.options.logger,this.options.handlerConfig),this.attachBridges(),await this.sessionManager.initialize(),this.initialized=!0,{socket:e,sessionManager:this.sessionManager,messageHandler:this.handler}}getManager(){return this.manager}getMessageHandler(){return this.handler}getSessionManager(){return this.sessionManager}async cleanup(){this.detachBridges(),this.handler&&(await this.handler.cleanup(),this.handler=null),await this.sessionManager?.cleanUp().catch(e=>{this.options.logger.error(`Cleanup failed: ${e instanceof Error?e.message:"Unknown error"}`)}),this.sessionManager=null,this.initialized=!1,this.manager.close()}attachBridges(){this.manager.on("message",this.handleRawMessage),this.manager.on("reconnected",this.handleReconnect)}detachBridges(){this.manager.off("message",this.handleRawMessage),this.manager.off("reconnected",this.handleReconnect)}handleReconnect=()=>{let e=this.manager.getSocket();if(!e){this.options.logger.warn("Reconnected but no active socket found");return}this.handler&&(this.handler.updateSocket(e),this.handler.registerMachine()),this.options.logger.info("Reconnected and restored session state")};handleRawMessage=async e=>{let r=this.handler;if(!r)return;let n=e.toString();if(n!=="pong")try{let i=JSON.parse(n);await r.handleMessage(i)}catch(i){if(i instanceof SyntaxError){this.options.logger.debug(`Received non-JSON message: ${n}`);return}this.options.logger.error(`Failed to handle message: ${i instanceof Error?i.message:"Unknown error"}`)}};requireSocket(){let e=this.manager.getSocket();if(!e)throw new Error("WebSocket connection has not been established");return e}requireSessionManager(){if(!this.sessionManager)throw new Error("Session manager has not been initialized");return this.sessionManager}requireHandler(){if(!this.handler)throw new Error("Message handler has not been initialized");return this.handler}};var Hfe=qe(sfe());var HA=qe(afe(),1);var WA=HA.default;var SM={claude:{command:"npx",args:["-y","@zed-industries/claude-code-acp"]},codex:{command:"npx",args:["-y","@zed-industries/codex-acp"]}};var Dm=class extends HA.default{constructor(r,n,i,s){super();this.workspaceDocument=s;this.logger=r,this.token=n,this.machineId=i}logger;machineId;token;requestPermissionHandler;async createSession(r){if(!r.assumeDocExisting){let u=await(await this.workspaceDocument.getOrCreateWorkspaceDoc(r.workspaceId,r.userId)).createSession(r.machineId,r.cliType,r.title);r.sessionId=u}await this.workspaceDocument.getOrCreateSessionDoc(r.sessionId),this.logger.debug(`[${r.sessionId}] Session will enter create inner`);let n=await this.createSessionInner(r),i=r.sessionId,s;try{s=await n.createAgent({command:SM[r.cliType].command,args:SM[r.cliType].args,onUpdateMessage:a=>{this.emit("onACPUpdateMessage",i,a)},onRequestPermission:(a,u)=>this.requestPermissionHandler?this.requestPermissionHandler(i,a,u):(this.logger.warn(`[${i}] Permission handler not configured`),Promise.resolve({outcome:{outcome:"cancelled"}}))})}catch(a){throw this.logger.error(`[${r.sessionId}] Failed to create agent: ${a instanceof Error?a.message:"Unknown error"}`),a}return await(await this.workspaceDocument.getOrCreateSessionDoc(i)).setChatId(s),n}async cleanUp(){await this.workspaceDocument.cleanUp(),await this.cleanupInner()}async finishSession(r){await this.workspaceDocument.cleanSessionDoc(r)}setRequestPermissionHandler(r){this.requestPermissionHandler=r}async handleFinishCommand(r,n){let i=`${S_}/api/issues/${n}/review`;try{let o=await(await fetch(i,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`}})).json();o.success?this.logger.success(`Issue ${n} marked as completed`):this.logger.error(`Failed to mark issue as completed: ${o.error}`)}catch(s){this.logger.error(`Error calling issue complete API: ${s instanceof Error?s.message:"Unknown error"}`)}}async setSessionError(r,n){let i=await this.workspaceDocument.getOrCreateSessionDoc(r);i&&i.setError(n)}};var Mm=qe(require("path")),t6=qe(require("os")),r6=qe(require("fs"));var ufe=require("stream"),Am=class extends ufe.Transform{buffer="";constructor(){super({objectMode:!0})}_transform(e,r,n){this.buffer+=e.toString();let i=this.buffer.split(`
|
|
193
193
|
`);this.buffer=i.pop()||"";for(let s of i)if(s.trim())try{let o=JSON.parse(s);this.push(o)}catch{}n()}_flush(e){if(this.buffer.trim())try{let r=JSON.parse(this.buffer);this.push(r)}catch{this.emit("error",new Error(`Invalid JSON: ${this.buffer}`))}e()}reset(){this.buffer=""}getBuffer(){return this.buffer}};var $fe=require("stream");var x={};nb(x,{BRAND:()=>gZe,DIRTY:()=>rh,EMPTY_PATH:()=>YXe,INVALID:()=>gt,NEVER:()=>eet,OK:()=>ki,ParseStatus:()=>gi,Schema:()=>zt,ZodAny:()=>pf,ZodArray:()=>fc,ZodBigInt:()=>ih,ZodBoolean:()=>sh,ZodBranded:()=>Uv,ZodCatch:()=>gh,ZodDate:()=>oh,ZodDefault:()=>mh,ZodDiscriminatedUnion:()=>GA,ZodEffects:()=>xo,ZodEnum:()=>hh,ZodError:()=>ps,ZodFirstPartyTypeKind:()=>bt,ZodFunction:()=>QA,ZodIntersection:()=>lh,ZodIssueCode:()=>Ie,ZodLazy:()=>fh,ZodLiteral:()=>dh,ZodMap:()=>Rm,ZodNaN:()=>Nm,ZodNativeEnum:()=>ph,ZodNever:()=>oa,ZodNull:()=>uh,ZodNullable:()=>ou,ZodNumber:()=>nh,ZodObject:()=>ms,ZodOptional:()=>vo,ZodParsedType:()=>He,ZodPipeline:()=>jv,ZodPromise:()=>mf,ZodReadonly:()=>_h,ZodRecord:()=>YA,ZodSchema:()=>zt,ZodSet:()=>Pm,ZodString:()=>hf,ZodSymbol:()=>Om,ZodTransformer:()=>xo,ZodTuple:()=>su,ZodType:()=>zt,ZodUndefined:()=>ah,ZodUnion:()=>ch,ZodUnknown:()=>lc,ZodVoid:()=>Fm,addIssueToContext:()=>Be,any:()=>CZe,array:()=>TZe,bigint:()=>bZe,boolean:()=>vfe,coerce:()=>ZZe,custom:()=>gfe,date:()=>xZe,datetimeRegex:()=>pfe,defaultErrorMap:()=>uc,discriminatedUnion:()=>RZe,effect:()=>VZe,enum:()=>$Ze,function:()=>qZe,getErrorMap:()=>Im,getParsedType:()=>iu,instanceof:()=>yZe,intersection:()=>PZe,isAborted:()=>VA,isAsync:()=>Tm,isDirty:()=>zA,isValid:()=>df,late:()=>_Ze,lazy:()=>UZe,literal:()=>jZe,makeIssue:()=>qv,map:()=>MZe,nan:()=>vZe,nativeEnum:()=>HZe,never:()=>AZe,null:()=>SZe,nullable:()=>GZe,number:()=>yfe,object:()=>kZe,objectUtil:()=>CM,oboolean:()=>XZe,onumber:()=>JZe,optional:()=>zZe,ostring:()=>KZe,pipeline:()=>QZe,preprocess:()=>YZe,promise:()=>WZe,quotelessJson:()=>VXe,record:()=>BZe,set:()=>LZe,setErrorMap:()=>GXe,strictObject:()=>OZe,string:()=>_fe,symbol:()=>EZe,transformer:()=>VZe,tuple:()=>NZe,undefined:()=>wZe,union:()=>FZe,unknown:()=>DZe,util:()=>nr,void:()=>IZe});var nr;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let s={};for(let o of i)s[o]=o;return s},t.getValidEnumValues=i=>{let s=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),o={};for(let a of s)o[a]=i[a];return t.objectValues(o)},t.objectValues=i=>t.objectKeys(i).map(function(s){return i[s]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&s.push(o);return s},t.find=(i,s)=>{for(let o of i)if(s(o))return o},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,s=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(nr||(nr={}));var CM;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(CM||(CM={}));var He=nr.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),iu=t=>{switch(typeof t){case"undefined":return He.undefined;case"string":return He.string;case"number":return Number.isNaN(t)?He.nan:He.number;case"boolean":return He.boolean;case"function":return He.function;case"bigint":return He.bigint;case"symbol":return He.symbol;case"object":return Array.isArray(t)?He.array:t===null?He.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?He.promise:typeof Map<"u"&&t instanceof Map?He.map:typeof Set<"u"&&t instanceof Set?He.set:typeof Date<"u"&&t instanceof Date?He.date:He.object;default:return He.unknown}};var Ie=nr.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),VXe=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),ps=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},i=s=>{for(let o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)n._errors.push(r(o));else{let a=n,u=0;for(;u<o.path.length;){let c=o.path[u];u===o.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(r(o))):a[c]=a[c]||{_errors:[]},a=a[c],u++}}};return i(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,nr.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];r[s]=r[s]||[],r[s].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};ps.create=t=>new ps(t);var zXe=(t,e)=>{let r;switch(t.code){case Ie.invalid_type:t.received===He.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case Ie.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,nr.jsonStringifyReplacer)}`;break;case Ie.unrecognized_keys:r=`Unrecognized key(s) in object: ${nr.joinValues(t.keys,", ")}`;break;case Ie.invalid_union:r="Invalid input";break;case Ie.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${nr.joinValues(t.options)}`;break;case Ie.invalid_enum_value:r=`Invalid enum value. Expected ${nr.joinValues(t.options)}, received '${t.received}'`;break;case Ie.invalid_arguments:r="Invalid function arguments";break;case Ie.invalid_return_type:r="Invalid function return type";break;case Ie.invalid_date:r="Invalid date";break;case Ie.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:nr.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case Ie.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case Ie.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case Ie.custom:r="Invalid input";break;case Ie.invalid_intersection_types:r="Intersection results could not be merged";break;case Ie.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case Ie.not_finite:r="Number must be finite";break;default:r=e.defaultError,nr.assertNever(t)}return{message:r}},uc=zXe;var cfe=uc;function GXe(t){cfe=t}function Im(){return cfe}var qv=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,s=[...r,...i.path||[]],o={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let a="",u=n.filter(c=>!!c).slice().reverse();for(let c of u)a=c(o,{data:e,defaultError:a}).message;return{...i,path:s,message:a}},YXe=[];function Be(t,e){let r=Im(),n=qv({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===uc?void 0:uc].filter(i=>!!i)});t.common.issues.push(n)}var gi=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return gt;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let s=await i.key,o=await i.value;n.push({key:s,value:o})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:s,value:o}=i;if(s.status==="aborted"||o.status==="aborted")return gt;s.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(n[s.value]=o.value)}return{status:e.value,value:n}}},gt=Object.freeze({status:"aborted"}),rh=t=>({status:"dirty",value:t}),ki=t=>({status:"valid",value:t}),VA=t=>t.status==="aborted",zA=t=>t.status==="dirty",df=t=>t.status==="valid",Tm=t=>typeof Promise<"u"&&t instanceof Promise;var tt;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(tt||(tt={}));var bo=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},lfe=(t,e)=>{if(df(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new ps(t.common.issues);return this._error=r,this._error}}};function jt(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(o,a)=>{let{message:u}=t;return o.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:u??r??a.defaultError}},description:i}}var zt=class{get description(){return this._def.description}_getType(e){return iu(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:iu(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new gi,ctx:{common:e.parent.common,data:e.data,parsedType:iu(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Tm(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:iu(e)},i=this._parseSync({data:e,path:n.path,parent:n});return lfe(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:iu(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return df(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>df(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:iu(e)},i=this._parse({data:e,path:n.path,parent:n}),s=await(Tm(i)?i:Promise.resolve(i));return lfe(n,s)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,s)=>{let o=e(i),a=()=>s.addIssue({code:Ie.custom,...n(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(u=>u?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new xo({schema:this,typeName:bt.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return vo.create(this,this._def)}nullable(){return ou.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return fc.create(this)}promise(){return mf.create(this,this._def)}or(e){return ch.create([this,e],this._def)}and(e){return lh.create(this,e,this._def)}transform(e){return new xo({...jt(this._def),schema:this,typeName:bt.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new mh({...jt(this._def),innerType:this,defaultValue:r,typeName:bt.ZodDefault})}brand(){return new Uv({typeName:bt.ZodBranded,type:this,...jt(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new gh({...jt(this._def),innerType:this,catchValue:r,typeName:bt.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return jv.create(this,e)}readonly(){return _h.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},QXe=/^c[^\s-]{8,}$/i,KXe=/^[0-9a-z]+$/,JXe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,XXe=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ZXe=/^[a-z0-9_-]{21}$/i,eZe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,tZe=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,rZe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,nZe="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",DM,iZe=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,sZe=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,oZe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,aZe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,uZe=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,cZe=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dfe="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",lZe=new RegExp(`^${dfe}$`);function hfe(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function fZe(t){return new RegExp(`^${hfe(t)}$`)}function pfe(t){let e=`${dfe}T${hfe(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function dZe(t,e){return!!((e==="v4"||!e)&&iZe.test(t)||(e==="v6"||!e)&&oZe.test(t))}function hZe(t,e){if(!eZe.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function pZe(t,e){return!!((e==="v4"||!e)&&sZe.test(t)||(e==="v6"||!e)&&aZe.test(t))}var hf=class t extends zt{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==He.string){let s=this._getOrReturnCtx(e);return Be(s,{code:Ie.invalid_type,expected:He.string,received:s.parsedType}),gt}let n=new gi,i;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(i=this._getOrReturnCtx(e,i),Be(i,{code:Ie.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(i=this._getOrReturnCtx(e,i),Be(i,{code:Ie.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let o=e.data.length>s.value,a=e.data.length<s.value;(o||a)&&(i=this._getOrReturnCtx(e,i),o?Be(i,{code:Ie.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&Be(i,{code:Ie.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")rZe.test(e.data)||(i=this._getOrReturnCtx(e,i),Be(i,{validation:"email",code:Ie.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")DM||(DM=new RegExp(nZe,"u")),DM.test(e.data)||(i=this._getOrReturnCtx(e,i),Be(i,{validation:"emoji",code:Ie.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")XXe.test(e.data)||(i=this._getOrReturnCtx(e,i),Be(i,{validation:"uuid",code:Ie.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")ZXe.test(e.data)||(i=this._getOrReturnCtx(e,i),Be(i,{validation:"nanoid",code:Ie.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")QXe.test(e.data)||(i=this._getOrReturnCtx(e,i),Be(i,{validation:"cuid",code:Ie.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")KXe.test(e.data)||(i=this._getOrReturnCtx(e,i),Be(i,{validation:"cuid2",code:Ie.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")JXe.test(e.data)||(i=this._getOrReturnCtx(e,i),Be(i,{validation:"ulid",code:Ie.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),Be(i,{validation:"url",code:Ie.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),Be(i,{validation:"regex",code:Ie.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(e,i),Be(i,{code:Ie.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(i=this._getOrReturnCtx(e,i),Be(i,{code:Ie.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(i=this._getOrReturnCtx(e,i),Be(i,{code:Ie.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?pfe(s).test(e.data)||(i=this._getOrReturnCtx(e,i),Be(i,{code:Ie.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?lZe.test(e.data)||(i=this._getOrReturnCtx(e,i),Be(i,{code:Ie.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?fZe(s).test(e.data)||(i=this._getOrReturnCtx(e,i),Be(i,{code:Ie.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?tZe.test(e.data)||(i=this._getOrReturnCtx(e,i),Be(i,{validation:"duration",code:Ie.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?dZe(e.data,s.version)||(i=this._getOrReturnCtx(e,i),Be(i,{validation:"ip",code:Ie.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?hZe(e.data,s.alg)||(i=this._getOrReturnCtx(e,i),Be(i,{validation:"jwt",code:Ie.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?pZe(e.data,s.version)||(i=this._getOrReturnCtx(e,i),Be(i,{validation:"cidr",code:Ie.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?uZe.test(e.data)||(i=this._getOrReturnCtx(e,i),Be(i,{validation:"base64",code:Ie.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?cZe.test(e.data)||(i=this._getOrReturnCtx(e,i),Be(i,{validation:"base64url",code:Ie.invalid_string,message:s.message}),n.dirty()):nr.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:Ie.invalid_string,...tt.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...tt.errToObj(e)})}url(e){return this._addCheck({kind:"url",...tt.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...tt.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...tt.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...tt.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...tt.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...tt.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...tt.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...tt.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...tt.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...tt.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...tt.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...tt.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...tt.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...tt.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...tt.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...tt.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...tt.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...tt.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...tt.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...tt.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...tt.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...tt.errToObj(r)})}nonempty(e){return this.min(1,tt.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};hf.create=t=>new hf({checks:[],typeName:bt.ZodString,coerce:t?.coerce??!1,...jt(t)});function mZe(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,s=Number.parseInt(t.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return s%o/10**i}var nh=class t extends zt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==He.number){let s=this._getOrReturnCtx(e);return Be(s,{code:Ie.invalid_type,expected:He.number,received:s.parsedType}),gt}let n,i=new gi;for(let s of this._def.checks)s.kind==="int"?nr.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),Be(n,{code:Ie.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),Be(n,{code:Ie.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),Be(n,{code:Ie.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?mZe(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),Be(n,{code:Ie.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),Be(n,{code:Ie.not_finite,message:s.message}),i.dirty()):nr.assertNever(s);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,tt.toString(r))}gt(e,r){return this.setLimit("min",e,!1,tt.toString(r))}lte(e,r){return this.setLimit("max",e,!0,tt.toString(r))}lt(e,r){return this.setLimit("max",e,!1,tt.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:tt.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:tt.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:tt.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:tt.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:tt.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:tt.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:tt.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:tt.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:tt.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:tt.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&nr.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};nh.create=t=>new nh({checks:[],typeName:bt.ZodNumber,coerce:t?.coerce||!1,...jt(t)});var ih=class t extends zt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==He.bigint)return this._getInvalidInput(e);let n,i=new gi;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),Be(n,{code:Ie.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),Be(n,{code:Ie.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),Be(n,{code:Ie.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):nr.assertNever(s);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return Be(r,{code:Ie.invalid_type,expected:He.bigint,received:r.parsedType}),gt}gte(e,r){return this.setLimit("min",e,!0,tt.toString(r))}gt(e,r){return this.setLimit("min",e,!1,tt.toString(r))}lte(e,r){return this.setLimit("max",e,!0,tt.toString(r))}lt(e,r){return this.setLimit("max",e,!1,tt.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:tt.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:tt.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:tt.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:tt.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:tt.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:tt.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};ih.create=t=>new ih({checks:[],typeName:bt.ZodBigInt,coerce:t?.coerce??!1,...jt(t)});var sh=class extends zt{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==He.boolean){let n=this._getOrReturnCtx(e);return Be(n,{code:Ie.invalid_type,expected:He.boolean,received:n.parsedType}),gt}return ki(e.data)}};sh.create=t=>new sh({typeName:bt.ZodBoolean,coerce:t?.coerce||!1,...jt(t)});var oh=class t extends zt{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==He.date){let s=this._getOrReturnCtx(e);return Be(s,{code:Ie.invalid_type,expected:He.date,received:s.parsedType}),gt}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return Be(s,{code:Ie.invalid_date}),gt}let n=new gi,i;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(i=this._getOrReturnCtx(e,i),Be(i,{code:Ie.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(i=this._getOrReturnCtx(e,i),Be(i,{code:Ie.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):nr.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:tt.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:tt.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};oh.create=t=>new oh({checks:[],coerce:t?.coerce||!1,typeName:bt.ZodDate,...jt(t)});var Om=class extends zt{_parse(e){if(this._getType(e)!==He.symbol){let n=this._getOrReturnCtx(e);return Be(n,{code:Ie.invalid_type,expected:He.symbol,received:n.parsedType}),gt}return ki(e.data)}};Om.create=t=>new Om({typeName:bt.ZodSymbol,...jt(t)});var ah=class extends zt{_parse(e){if(this._getType(e)!==He.undefined){let n=this._getOrReturnCtx(e);return Be(n,{code:Ie.invalid_type,expected:He.undefined,received:n.parsedType}),gt}return ki(e.data)}};ah.create=t=>new ah({typeName:bt.ZodUndefined,...jt(t)});var uh=class extends zt{_parse(e){if(this._getType(e)!==He.null){let n=this._getOrReturnCtx(e);return Be(n,{code:Ie.invalid_type,expected:He.null,received:n.parsedType}),gt}return ki(e.data)}};uh.create=t=>new uh({typeName:bt.ZodNull,...jt(t)});var pf=class extends zt{constructor(){super(...arguments),this._any=!0}_parse(e){return ki(e.data)}};pf.create=t=>new pf({typeName:bt.ZodAny,...jt(t)});var lc=class extends zt{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ki(e.data)}};lc.create=t=>new lc({typeName:bt.ZodUnknown,...jt(t)});var oa=class extends zt{_parse(e){let r=this._getOrReturnCtx(e);return Be(r,{code:Ie.invalid_type,expected:He.never,received:r.parsedType}),gt}};oa.create=t=>new oa({typeName:bt.ZodNever,...jt(t)});var Fm=class extends zt{_parse(e){if(this._getType(e)!==He.undefined){let n=this._getOrReturnCtx(e);return Be(n,{code:Ie.invalid_type,expected:He.void,received:n.parsedType}),gt}return ki(e.data)}};Fm.create=t=>new Fm({typeName:bt.ZodVoid,...jt(t)});var fc=class t extends zt{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==He.array)return Be(r,{code:Ie.invalid_type,expected:He.array,received:r.parsedType}),gt;if(i.exactLength!==null){let o=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(o||a)&&(Be(r,{code:o?Ie.too_big:Ie.too_small,minimum:a?i.exactLength.value:void 0,maximum:o?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(Be(r,{code:Ie.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(Be(r,{code:Ie.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((o,a)=>i.type._parseAsync(new bo(r,o,r.path,a)))).then(o=>gi.mergeArray(n,o));let s=[...r.data].map((o,a)=>i.type._parseSync(new bo(r,o,r.path,a)));return gi.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:tt.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:tt.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:tt.toString(r)}})}nonempty(e){return this.min(1,e)}};fc.create=(t,e)=>new fc({type:t,minLength:null,maxLength:null,exactLength:null,typeName:bt.ZodArray,...jt(e)});function km(t){if(t instanceof ms){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=vo.create(km(n))}return new ms({...t._def,shape:()=>e})}else return t instanceof fc?new fc({...t._def,type:km(t.element)}):t instanceof vo?vo.create(km(t.unwrap())):t instanceof ou?ou.create(km(t.unwrap())):t instanceof su?su.create(t.items.map(e=>km(e))):t}var ms=class t extends zt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=nr.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==He.object){let c=this._getOrReturnCtx(e);return Be(c,{code:Ie.invalid_type,expected:He.object,received:c.parsedType}),gt}let{status:n,ctx:i}=this._processInputParams(e),{shape:s,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof oa&&this._def.unknownKeys==="strip"))for(let c in i.data)o.includes(c)||a.push(c);let u=[];for(let c of o){let l=s[c],f=i.data[c];u.push({key:{status:"valid",value:c},value:l._parse(new bo(i,f,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof oa){let c=this._def.unknownKeys;if(c==="passthrough")for(let l of a)u.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(c==="strict")a.length>0&&(Be(i,{code:Ie.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let l of a){let f=i.data[l];u.push({key:{status:"valid",value:l},value:c._parse(new bo(i,f,i.path,l)),alwaysSet:l in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let c=[];for(let l of u){let f=await l.key,d=await l.value;c.push({key:f,value:d,alwaysSet:l.alwaysSet})}return c}).then(c=>gi.mergeObjectSync(n,c)):gi.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return tt.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:tt.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:bt.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of nr.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of nr.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return km(this)}partial(e){let r={};for(let n of nr.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of nr.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof vo;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return mfe(nr.objectKeys(this.shape))}};ms.create=(t,e)=>new ms({shape:()=>t,unknownKeys:"strip",catchall:oa.create(),typeName:bt.ZodObject,...jt(e)});ms.strictCreate=(t,e)=>new ms({shape:()=>t,unknownKeys:"strict",catchall:oa.create(),typeName:bt.ZodObject,...jt(e)});ms.lazycreate=(t,e)=>new ms({shape:t,unknownKeys:"strip",catchall:oa.create(),typeName:bt.ZodObject,...jt(e)});var ch=class extends zt{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let o=s.map(a=>new ps(a.ctx.common.issues));return Be(r,{code:Ie.invalid_union,unionErrors:o}),gt}if(r.common.async)return Promise.all(n.map(async s=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(i);{let s,o=[];for(let u of n){let c={...r,common:{...r.common,issues:[]},parent:null},l=u._parseSync({data:r.data,path:r.path,parent:c});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=o.map(u=>new ps(u));return Be(r,{code:Ie.invalid_union,unionErrors:a}),gt}}get options(){return this._def.options}};ch.create=(t,e)=>new ch({options:t,typeName:bt.ZodUnion,...jt(e)});var cc=t=>t instanceof fh?cc(t.schema):t instanceof xo?cc(t.innerType()):t instanceof dh?[t.value]:t instanceof hh?t.options:t instanceof ph?nr.objectValues(t.enum):t instanceof mh?cc(t._def.innerType):t instanceof ah?[void 0]:t instanceof uh?[null]:t instanceof vo?[void 0,...cc(t.unwrap())]:t instanceof ou?[null,...cc(t.unwrap())]:t instanceof Uv||t instanceof _h?cc(t.unwrap()):t instanceof gh?cc(t._def.innerType):[],GA=class t extends zt{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==He.object)return Be(r,{code:Ie.invalid_type,expected:He.object,received:r.parsedType}),gt;let n=this.discriminator,i=r.data[n],s=this.optionsMap.get(i);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(Be(r,{code:Ie.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),gt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let s of r){let o=cc(s.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,s)}}return new t({typeName:bt.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...jt(n)})}};function AM(t,e){let r=iu(t),n=iu(e);if(t===e)return{valid:!0,data:t};if(r===He.object&&n===He.object){let i=nr.objectKeys(e),s=nr.objectKeys(t).filter(a=>i.indexOf(a)!==-1),o={...t,...e};for(let a of s){let u=AM(t[a],e[a]);if(!u.valid)return{valid:!1};o[a]=u.data}return{valid:!0,data:o}}else if(r===He.array&&n===He.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let s=0;s<t.length;s++){let o=t[s],a=e[s],u=AM(o,a);if(!u.valid)return{valid:!1};i.push(u.data)}return{valid:!0,data:i}}else return r===He.date&&n===He.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var lh=class extends zt{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(s,o)=>{if(VA(s)||VA(o))return gt;let a=AM(s.value,o.value);return a.valid?((zA(s)||zA(o))&&r.dirty(),{status:r.value,value:a.data}):(Be(n,{code:Ie.invalid_intersection_types}),gt)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,o])=>i(s,o)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};lh.create=(t,e,r)=>new lh({left:t,right:e,typeName:bt.ZodIntersection,...jt(r)});var su=class t extends zt{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==He.array)return Be(n,{code:Ie.invalid_type,expected:He.array,received:n.parsedType}),gt;if(n.data.length<this._def.items.length)return Be(n,{code:Ie.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),gt;!this._def.rest&&n.data.length>this._def.items.length&&(Be(n,{code:Ie.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((o,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new bo(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(s).then(o=>gi.mergeArray(r,o)):gi.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};su.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new su({items:t,typeName:bt.ZodTuple,rest:null,...jt(e)})};var YA=class t extends zt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==He.object)return Be(n,{code:Ie.invalid_type,expected:He.object,received:n.parsedType}),gt;let i=[],s=this._def.keyType,o=this._def.valueType;for(let a in n.data)i.push({key:s._parse(new bo(n,a,n.path,a)),value:o._parse(new bo(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?gi.mergeObjectAsync(r,i):gi.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof zt?new t({keyType:e,valueType:r,typeName:bt.ZodRecord,...jt(n)}):new t({keyType:hf.create(),valueType:e,typeName:bt.ZodRecord,...jt(r)})}},Rm=class extends zt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==He.map)return Be(n,{code:Ie.invalid_type,expected:He.map,received:n.parsedType}),gt;let i=this._def.keyType,s=this._def.valueType,o=[...n.data.entries()].map(([a,u],c)=>({key:i._parse(new bo(n,a,n.path,[c,"key"])),value:s._parse(new bo(n,u,n.path,[c,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let u of o){let c=await u.key,l=await u.value;if(c.status==="aborted"||l.status==="aborted")return gt;(c.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(c.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let u of o){let c=u.key,l=u.value;if(c.status==="aborted"||l.status==="aborted")return gt;(c.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(c.value,l.value)}return{status:r.value,value:a}}}};Rm.create=(t,e,r)=>new Rm({valueType:e,keyType:t,typeName:bt.ZodMap,...jt(r)});var Pm=class t extends zt{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==He.set)return Be(n,{code:Ie.invalid_type,expected:He.set,received:n.parsedType}),gt;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(Be(n,{code:Ie.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(Be(n,{code:Ie.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let s=this._def.valueType;function o(u){let c=new Set;for(let l of u){if(l.status==="aborted")return gt;l.status==="dirty"&&r.dirty(),c.add(l.value)}return{status:r.value,value:c}}let a=[...n.data.values()].map((u,c)=>s._parse(new bo(n,u,n.path,c)));return n.common.async?Promise.all(a).then(u=>o(u)):o(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:tt.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:tt.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Pm.create=(t,e)=>new Pm({valueType:t,minSize:null,maxSize:null,typeName:bt.ZodSet,...jt(e)});var QA=class t extends zt{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==He.function)return Be(r,{code:Ie.invalid_type,expected:He.function,received:r.parsedType}),gt;function n(a,u){return qv({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Im(),uc].filter(c=>!!c),issueData:{code:Ie.invalid_arguments,argumentsError:u}})}function i(a,u){return qv({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Im(),uc].filter(c=>!!c),issueData:{code:Ie.invalid_return_type,returnTypeError:u}})}let s={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof mf){let a=this;return ki(async function(...u){let c=new ps([]),l=await a._def.args.parseAsync(u,s).catch(p=>{throw c.addIssue(n(u,p)),c}),f=await Reflect.apply(o,this,l);return await a._def.returns._def.type.parseAsync(f,s).catch(p=>{throw c.addIssue(i(f,p)),c})})}else{let a=this;return ki(function(...u){let c=a._def.args.safeParse(u,s);if(!c.success)throw new ps([n(u,c.error)]);let l=Reflect.apply(o,this,c.data),f=a._def.returns.safeParse(l,s);if(!f.success)throw new ps([i(l,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:su.create(e).rest(lc.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||su.create([]).rest(lc.create()),returns:r||lc.create(),typeName:bt.ZodFunction,...jt(n)})}},fh=class extends zt{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};fh.create=(t,e)=>new fh({getter:t,typeName:bt.ZodLazy,...jt(e)});var dh=class extends zt{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return Be(r,{received:r.data,code:Ie.invalid_literal,expected:this._def.value}),gt}return{status:"valid",value:e.data}}get value(){return this._def.value}};dh.create=(t,e)=>new dh({value:t,typeName:bt.ZodLiteral,...jt(e)});function mfe(t,e){return new hh({values:t,typeName:bt.ZodEnum,...jt(e)})}var hh=class t extends zt{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return Be(r,{expected:nr.joinValues(n),received:r.parsedType,code:Ie.invalid_type}),gt}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return Be(r,{received:r.data,code:Ie.invalid_enum_value,options:n}),gt}return ki(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};hh.create=mfe;var ph=class extends zt{_parse(e){let r=nr.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==He.string&&n.parsedType!==He.number){let i=nr.objectValues(r);return Be(n,{expected:nr.joinValues(i),received:n.parsedType,code:Ie.invalid_type}),gt}if(this._cache||(this._cache=new Set(nr.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=nr.objectValues(r);return Be(n,{received:n.data,code:Ie.invalid_enum_value,options:i}),gt}return ki(e.data)}get enum(){return this._def.values}};ph.create=(t,e)=>new ph({values:t,typeName:bt.ZodNativeEnum,...jt(e)});var mf=class extends zt{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==He.promise&&r.common.async===!1)return Be(r,{code:Ie.invalid_type,expected:He.promise,received:r.parsedType}),gt;let n=r.parsedType===He.promise?r.data:Promise.resolve(r.data);return ki(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};mf.create=(t,e)=>new mf({type:t,typeName:bt.ZodPromise,...jt(e)});var xo=class extends zt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===bt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,s={addIssue:o=>{Be(n,o),o.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let o=i.transform(n.data,s);if(n.common.async)return Promise.resolve(o).then(async a=>{if(r.value==="aborted")return gt;let u=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return u.status==="aborted"?gt:u.status==="dirty"?rh(u.value):r.value==="dirty"?rh(u.value):u});{if(r.value==="aborted")return gt;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?gt:a.status==="dirty"?rh(a.value):r.value==="dirty"?rh(a.value):a}}if(i.type==="refinement"){let o=a=>{let u=i.refinement(a,s);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?gt:(a.status==="dirty"&&r.dirty(),o(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?gt:(a.status==="dirty"&&r.dirty(),o(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!df(o))return gt;let a=i.transform(o.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>df(o)?Promise.resolve(i.transform(o.value,s)).then(a=>({status:r.value,value:a})):gt);nr.assertNever(i)}};xo.create=(t,e,r)=>new xo({schema:t,typeName:bt.ZodEffects,effect:e,...jt(r)});xo.createWithPreprocess=(t,e,r)=>new xo({schema:e,effect:{type:"preprocess",transform:t},typeName:bt.ZodEffects,...jt(r)});var vo=class extends zt{_parse(e){return this._getType(e)===He.undefined?ki(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};vo.create=(t,e)=>new vo({innerType:t,typeName:bt.ZodOptional,...jt(e)});var ou=class extends zt{_parse(e){return this._getType(e)===He.null?ki(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ou.create=(t,e)=>new ou({innerType:t,typeName:bt.ZodNullable,...jt(e)});var mh=class extends zt{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===He.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};mh.create=(t,e)=>new mh({innerType:t,typeName:bt.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...jt(e)});var gh=class extends zt{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Tm(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ps(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ps(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};gh.create=(t,e)=>new gh({innerType:t,typeName:bt.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...jt(e)});var Nm=class extends zt{_parse(e){if(this._getType(e)!==He.nan){let n=this._getOrReturnCtx(e);return Be(n,{code:Ie.invalid_type,expected:He.nan,received:n.parsedType}),gt}return{status:"valid",value:e.data}}};Nm.create=t=>new Nm({typeName:bt.ZodNaN,...jt(t)});var gZe=Symbol("zod_brand"),Uv=class extends zt{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},jv=class t extends zt{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?gt:s.status==="dirty"?(r.dirty(),rh(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?gt:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:bt.ZodPipeline})}},_h=class extends zt{_parse(e){let r=this._def.innerType._parse(e),n=i=>(df(i)&&(i.value=Object.freeze(i.value)),i);return Tm(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};_h.create=(t,e)=>new _h({innerType:t,typeName:bt.ZodReadonly,...jt(e)});function ffe(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function gfe(t,e={},r){return t?pf.create().superRefine((n,i)=>{let s=t(n);if(s instanceof Promise)return s.then(o=>{if(!o){let a=ffe(e,n),u=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:u})}});if(!s){let o=ffe(e,n),a=o.fatal??r??!0;i.addIssue({code:"custom",...o,fatal:a})}}):pf.create()}var _Ze={object:ms.lazycreate},bt;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(bt||(bt={}));var yZe=(t,e={message:`Input not instance of ${t.name}`})=>gfe(r=>r instanceof t,e),_fe=hf.create,yfe=nh.create,vZe=Nm.create,bZe=ih.create,vfe=sh.create,xZe=oh.create,EZe=Om.create,wZe=ah.create,SZe=uh.create,CZe=pf.create,DZe=lc.create,AZe=oa.create,IZe=Fm.create,TZe=fc.create,kZe=ms.create,OZe=ms.strictCreate,FZe=ch.create,RZe=GA.create,PZe=lh.create,NZe=su.create,BZe=YA.create,MZe=Rm.create,LZe=Pm.create,qZe=QA.create,UZe=fh.create,jZe=dh.create,$Ze=hh.create,HZe=ph.create,WZe=mf.create,VZe=xo.create,zZe=vo.create,GZe=ou.create,YZe=xo.createWithPreprocess,QZe=jv.create,KZe=()=>_fe().optional(),JZe=()=>yfe().optional(),XZe=()=>vfe().optional(),ZZe={string:t=>hf.create({...t,coerce:!0}),number:t=>nh.create({...t,coerce:!0}),boolean:t=>sh.create({...t,coerce:!0}),bigint:t=>ih.create({...t,coerce:!0}),date:t=>oh.create({...t,coerce:!0})};var eet=gt;var dc={authenticate:"authenticate",initialize:"initialize",session_cancel:"session/cancel",session_load:"session/load",session_new:"session/new",session_prompt:"session/prompt",session_set_mode:"session/set_mode",session_set_model:"session/set_model"},au={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"},xfe=1,tet=x.null(),ret=x.number(),net=x.string(),kM=x.object({_meta:x.record(x.unknown()).optional(),content:x.string(),path:x.string(),sessionId:x.string()}),OM=x.object({_meta:x.record(x.unknown()).optional(),limit:x.number().optional().nullable(),line:x.number().optional().nullable(),path:x.string(),sessionId:x.string()}),FM=x.object({_meta:x.record(x.unknown()).optional(),sessionId:x.string(),terminalId:x.string()}),RM=x.object({_meta:x.record(x.unknown()).optional(),sessionId:x.string(),terminalId:x.string()}),PM=x.object({_meta:x.record(x.unknown()).optional(),sessionId:x.string(),terminalId:x.string()}),NM=x.object({_meta:x.record(x.unknown()).optional(),sessionId:x.string(),terminalId:x.string()}),iet=x.record(x.unknown()),set=x.union([x.literal("assistant"),x.literal("user")]),oet=x.object({_meta:x.record(x.unknown()).optional(),mimeType:x.string().optional().nullable(),text:x.string(),uri:x.string()}),aet=x.object({_meta:x.record(x.unknown()).optional(),blob:x.string(),mimeType:x.string().optional().nullable(),uri:x.string()}),Efe=x.union([x.literal("read"),x.literal("edit"),x.literal("delete"),x.literal("move"),x.literal("search"),x.literal("execute"),x.literal("think"),x.literal("fetch"),x.literal("switch_mode"),x.literal("other")]),wfe=x.union([x.literal("pending"),x.literal("in_progress"),x.literal("completed"),x.literal("failed")]),Sfe=x.object({code:x.number(),data:x.record(x.unknown()).optional(),message:x.string()}),uet=x.object({_meta:x.record(x.unknown()).optional()}),cet=x.object({_meta:x.unknown().optional()}),fet=x.object({_meta:x.record(x.unknown()).optional(),stopReason:x.union([x.literal("end_turn"),x.literal("max_tokens"),x.literal("max_turn_requests"),x.literal("refusal"),x.literal("cancelled")])}),det=x.object({_meta:x.record(x.unknown()).optional()}),het=x.record(x.unknown()),pet=x.string(),met=x.record(x.unknown()),get=x.object({hint:x.string()}),_et=x.null(),yet=x.number(),vet=x.string(),Cfe=x.object({_meta:x.record(x.unknown()).optional(),methodId:x.string()}),Dfe=x.object({_meta:x.record(x.unknown()).optional(),modeId:x.string(),sessionId:x.string()}),Afe=x.object({_meta:x.record(x.unknown()).optional(),modelId:x.string(),sessionId:x.string()}),bet=x.record(x.unknown()),bfe=x.object({_meta:x.record(x.unknown()).optional(),name:x.string(),value:x.string()}),zr=x.object({_meta:x.record(x.unknown()).optional(),audience:x.array(set).optional().nullable(),lastModified:x.string().optional().nullable(),priority:x.number().optional().nullable()}),$v=x.union([oet,aet]),xet=x.object({_meta:x.record(x.unknown()).optional()}),Eet=x.object({_meta:x.record(x.unknown()).optional(),content:x.string()}),wet=x.object({_meta:x.record(x.unknown()).optional(),outcome:x.union([x.object({outcome:x.literal("cancelled")}),x.object({optionId:x.string(),outcome:x.literal("selected")})])}),Cet=x.object({_meta:x.record(x.unknown()).optional(),terminalId:x.string()}),Det=x.object({_meta:x.record(x.unknown()).optional()}),Aet=x.object({_meta:x.record(x.unknown()).optional(),exitCode:x.number().optional().nullable(),signal:x.string().optional().nullable()}),Iet=x.object({_meta:x.record(x.unknown()).optional()}),Tet=x.record(x.unknown()),Ife=x.object({_meta:x.record(x.unknown()).optional(),sessionId:x.string()}),ket=x.record(x.unknown()),Oet=x.object({_meta:x.record(x.unknown()).optional(),kind:x.union([x.literal("allow_once"),x.literal("allow_always"),x.literal("reject_once"),x.literal("reject_always")]),name:x.string(),optionId:x.string()}),IM=x.union([x.object({content:x.union([x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),text:x.string(),type:x.literal("text")}),x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),data:x.string(),mimeType:x.string(),type:x.literal("image"),uri:x.string().optional().nullable()}),x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),data:x.string(),mimeType:x.string(),type:x.literal("audio")}),x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),description:x.string().optional().nullable(),mimeType:x.string().optional().nullable(),name:x.string(),size:x.number().optional().nullable(),title:x.string().optional().nullable(),type:x.literal("resource_link"),uri:x.string()}),x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),resource:$v,type:x.literal("resource")})]),type:x.literal("content")}),x.object({_meta:x.record(x.unknown()).optional(),newText:x.string(),oldText:x.string().optional().nullable(),path:x.string(),type:x.literal("diff")}),x.object({terminalId:x.string(),type:x.literal("terminal")})]),TM=x.object({_meta:x.record(x.unknown()).optional(),line:x.number().optional().nullable(),path:x.string()}),Tfe=x.object({_meta:x.record(x.unknown()).optional(),name:x.string(),value:x.string()}),kfe=x.object({name:x.string(),title:x.string().optional().nullable(),version:x.string()}),Fet=x.object({_meta:x.record(x.unknown()).optional(),description:x.string().optional().nullable(),id:x.string(),name:x.string()}),Ret=x.object({_meta:x.record(x.unknown()).optional(),http:x.boolean().optional(),sse:x.boolean().optional()}),Pet=x.object({_meta:x.record(x.unknown()).optional(),audio:x.boolean().optional(),embeddedContext:x.boolean().optional(),image:x.boolean().optional()}),Net=x.object({_meta:x.record(x.unknown()).optional(),description:x.string().optional().nullable(),modelId:x.string(),name:x.string()}),Bet=x.object({_meta:x.record(x.unknown()).optional(),description:x.string().optional().nullable(),id:pet,name:x.string()}),Ofe=x.object({_meta:x.record(x.unknown()).optional(),availableModels:x.array(Net),currentModelId:x.string()}),Ffe=x.object({_meta:x.record(x.unknown()).optional(),availableModes:x.array(Bet),currentModeId:x.string()}),Met=x.object({_meta:x.record(x.unknown()).optional(),content:x.string(),priority:x.union([x.literal("high"),x.literal("medium"),x.literal("low")]),status:x.union([x.literal("pending"),x.literal("in_progress"),x.literal("completed")])}),Let=get,qet=x.object({_meta:x.record(x.unknown()).optional(),readTextFile:x.boolean().optional(),writeTextFile:x.boolean().optional()}),Uet=x.object({args:x.array(x.string()),command:x.string(),env:x.array(Tfe),name:x.string()}),Rfe=x.union([x.object({headers:x.array(bfe),name:x.string(),type:x.literal("http"),url:x.string()}),x.object({headers:x.array(bfe),name:x.string(),type:x.literal("sse"),url:x.string()}),Uet]),jet=x.union([x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),text:x.string(),type:x.literal("text")}),x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),data:x.string(),mimeType:x.string(),type:x.literal("image"),uri:x.string().optional().nullable()}),x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),data:x.string(),mimeType:x.string(),type:x.literal("audio")}),x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),description:x.string().optional().nullable(),mimeType:x.string().optional().nullable(),name:x.string(),size:x.number().optional().nullable(),title:x.string().optional().nullable(),type:x.literal("resource_link"),uri:x.string()}),x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),resource:$v,type:x.literal("resource")})]),$et=x.object({_meta:x.record(x.unknown()).optional(),exitCode:x.number().optional().nullable(),signal:x.string().optional().nullable()}),Het=x.union([Ife,ket]),BM=x.object({_meta:x.record(x.unknown()).optional(),options:x.array(Oet),sessionId:x.string(),toolCall:x.object({_meta:x.record(x.unknown()).optional(),content:x.array(IM).optional().nullable(),kind:Efe.optional().nullable(),locations:x.array(TM).optional().nullable(),rawInput:x.record(x.unknown()).optional(),rawOutput:x.record(x.unknown()).optional(),status:wfe.optional().nullable(),title:x.string().optional().nullable(),toolCallId:x.string()})}),MM=x.object({_meta:x.record(x.unknown()).optional(),args:x.array(x.string()).optional(),command:x.string(),cwd:x.string().optional().nullable(),env:x.array(Tfe).optional(),outputByteLimit:x.number().optional().nullable(),sessionId:x.string()}),Wet=x.object({_meta:x.record(x.unknown()).optional(),models:Ofe.optional().nullable(),modes:Ffe.optional().nullable(),sessionId:x.string()}),Vet=x.object({_meta:x.record(x.unknown()).optional(),models:Ofe.optional().nullable(),modes:Ffe.optional().nullable()}),zet=x.object({method:x.string(),params:Het.optional().nullable()}),Pfe=x.object({_meta:x.record(x.unknown()).optional(),cwd:x.string(),mcpServers:x.array(Rfe)}),Nfe=x.object({_meta:x.record(x.unknown()).optional(),cwd:x.string(),mcpServers:x.array(Rfe),sessionId:x.string()}),Bfe=x.object({_meta:x.record(x.unknown()).optional(),prompt:x.array(jet),sessionId:x.string()}),Get=x.object({_meta:x.record(x.unknown()).optional(),exitStatus:$et.optional().nullable(),output:x.string(),truncated:x.boolean()}),Yet=x.union([kM,OM,BM,MM,FM,RM,PM,NM,iet]),Qet=x.object({_meta:x.record(x.unknown()).optional(),loadSession:x.boolean().optional(),mcpCapabilities:Ret.optional(),promptCapabilities:Pet.optional()}),Ket=x.object({_meta:x.record(x.unknown()).optional(),description:x.string(),input:Let.optional().nullable(),name:x.string()}),Jet=x.object({_meta:x.record(x.unknown()).optional(),fs:qet.optional(),terminal:x.boolean().optional()}),Xet=x.object({id:x.union([tet,ret,net]),method:x.string(),params:Yet.optional().nullable()}),Zet=x.object({_meta:x.record(x.unknown()).optional(),agentCapabilities:Qet.optional(),agentInfo:kfe.optional().nullable(),authMethods:x.array(Fet).optional(),protocolVersion:x.number()}),LM=x.object({_meta:x.record(x.unknown()).optional(),sessionId:x.string(),update:x.union([x.object({_meta:x.record(x.unknown()).optional(),content:x.union([x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),text:x.string(),type:x.literal("text")}),x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),data:x.string(),mimeType:x.string(),type:x.literal("image"),uri:x.string().optional().nullable()}),x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),data:x.string(),mimeType:x.string(),type:x.literal("audio")}),x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),description:x.string().optional().nullable(),mimeType:x.string().optional().nullable(),name:x.string(),size:x.number().optional().nullable(),title:x.string().optional().nullable(),type:x.literal("resource_link"),uri:x.string()}),x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),resource:$v,type:x.literal("resource")})]),sessionUpdate:x.literal("user_message_chunk")}),x.object({_meta:x.record(x.unknown()).optional(),content:x.union([x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),text:x.string(),type:x.literal("text")}),x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),data:x.string(),mimeType:x.string(),type:x.literal("image"),uri:x.string().optional().nullable()}),x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),data:x.string(),mimeType:x.string(),type:x.literal("audio")}),x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),description:x.string().optional().nullable(),mimeType:x.string().optional().nullable(),name:x.string(),size:x.number().optional().nullable(),title:x.string().optional().nullable(),type:x.literal("resource_link"),uri:x.string()}),x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),resource:$v,type:x.literal("resource")})]),sessionUpdate:x.literal("agent_message_chunk")}),x.object({_meta:x.record(x.unknown()).optional(),content:x.union([x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),text:x.string(),type:x.literal("text")}),x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),data:x.string(),mimeType:x.string(),type:x.literal("image"),uri:x.string().optional().nullable()}),x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),data:x.string(),mimeType:x.string(),type:x.literal("audio")}),x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),description:x.string().optional().nullable(),mimeType:x.string().optional().nullable(),name:x.string(),size:x.number().optional().nullable(),title:x.string().optional().nullable(),type:x.literal("resource_link"),uri:x.string()}),x.object({_meta:x.record(x.unknown()).optional(),annotations:zr.optional().nullable(),resource:$v,type:x.literal("resource")})]),sessionUpdate:x.literal("agent_thought_chunk")}),x.object({_meta:x.record(x.unknown()).optional(),content:x.array(IM).optional(),kind:x.union([x.literal("read"),x.literal("edit"),x.literal("delete"),x.literal("move"),x.literal("search"),x.literal("execute"),x.literal("think"),x.literal("fetch"),x.literal("switch_mode"),x.literal("other")]).optional(),locations:x.array(TM).optional(),rawInput:x.record(x.unknown()).optional(),rawOutput:x.record(x.unknown()).optional(),sessionUpdate:x.literal("tool_call"),status:x.union([x.literal("pending"),x.literal("in_progress"),x.literal("completed"),x.literal("failed")]).optional(),title:x.string(),toolCallId:x.string()}),x.object({_meta:x.record(x.unknown()).optional(),content:x.array(IM).optional().nullable(),kind:Efe.optional().nullable(),locations:x.array(TM).optional().nullable(),rawInput:x.record(x.unknown()).optional(),rawOutput:x.record(x.unknown()).optional(),sessionUpdate:x.literal("tool_call_update"),status:wfe.optional().nullable(),title:x.string().optional().nullable(),toolCallId:x.string()}),x.object({_meta:x.record(x.unknown()).optional(),entries:x.array(Met),sessionUpdate:x.literal("plan")}),x.object({_meta:x.record(x.unknown()).optional(),availableCommands:x.array(Ket),sessionUpdate:x.literal("available_commands_update")}),x.object({_meta:x.record(x.unknown()).optional(),currentModeId:x.string(),sessionUpdate:x.literal("current_mode_update")})])}),Mfe=x.object({_meta:x.record(x.unknown()).optional(),clientCapabilities:Jet.optional(),clientInfo:kfe.optional().nullable(),protocolVersion:x.number()}),ett=x.union([xet,Eet,wet,Cet,Get,Det,Aet,Iet,Tet]),ttt=x.union([LM,met]),rtt=x.union([Mfe,Cfe,Pfe,Nfe,Dfe,Bfe,Afe,bet]),ntt=x.object({method:x.string(),params:ttt.optional().nullable()}),itt=x.union([Zet,uet,Wet,Vet,cet,fet,det,het]),stt=x.object({id:x.union([_et,yet,vet]),method:x.string(),params:rtt.optional().nullable()}),ott=x.union([x.object({result:ett}),x.object({error:Sfe})]),att=x.union([stt,ott,zet]),utt=x.union([x.object({result:itt}),x.object({error:Sfe})]),ctt=x.union([Xet,utt,ntt]),xSt=x.union([ctt,att]);function KA(t,e){let r=new TextEncoder,n=new TextDecoder,i=new ReadableStream({async start(o){let a="",u=e.getReader();try{for(;;){let{value:c,done:l}=await u.read();if(l)break;if(!c)continue;a+=n.decode(c,{stream:!0});let f=a.split(`
|
|
194
194
|
`);a=f.pop()||"";for(let d of f){let p=d.trim();if(p)try{let m=JSON.parse(p);o.enqueue(m)}catch(m){console.error("Failed to parse JSON message:",p,m)}}}}finally{u.releaseLock(),o.close()}}}),s=new WritableStream({async write(o){let a=JSON.stringify(o)+`
|