lody 0.1.9 → 0.1.10

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.
Files changed (2) hide show
  1. package/dist/index.js +2 -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 wVe.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,W6=Symbol("GENERATOR"),wh=Symbol("STYLER"),Wm=Symbol("IS_EMPTY"),JL=["ansi","ansi","ansi256","ansi16m"],Sh=Object.create(null),B0e=(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 M0e=t=>{let e=(...r)=>r.join(" ");return B0e(e,t),Object.setPrototypeOf(e,Vm.prototype),e};function Vm(t){return M0e(t)}Object.setPrototypeOf(Vm.prototype,Function.prototype);for(let[t,e]of Object.entries(So))Sh[t]={get(){let r=ub(this,z6(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 V6=(t,e,r,...n)=>t==="rgb"?e==="ansi16m"?So[r].ansi16m(...n):e==="ansi256"?So[r].ansi256(So.rgbToAnsi256(...n)):So[r].ansi(So.rgbToAnsi(...n)):t==="hex"?V6("rgb",e,r,...So.hexToRgb(...n)):So[r][t](...n),L0e=["rgb","hex","ansi256"];for(let t of L0e){Sh[t]={get(){let{level:r}=this;return function(...n){let i=z6(V6(t,JL[r],"color",...n),So.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=z6(V6(t,JL[r],"bgColor",...n),So.bgColor.close,this[wh]);return ub(this,i,this[Wm])}}}}var q0e=Object.defineProperties(()=>{},{...Sh,level:{enumerable:!0,get(){return this[W6].level},set(t){this[W6].level=t}}}),z6=(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)=>U0e(n,i.length===1?""+i[0]:i.join(" "));return Object.setPrototypeOf(n,q0e),n[W6]=t,n[wh]=e,n[Wm]=r,n},U0e=(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 j0e=Vm(),drt=Vm({level:KL?KL.level:0});var it=j0e;var ZL="0.1.9";var G6={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:{"@lody/types":"workspace:*","@agentclientprotocol/sdk":"^0.5.1","@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/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"]};var Qm=qe(require("node:process"),1);var tI=qe(require("node:process"),1);var zm=qe(require("node:process"),1);var $0e=(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);!H0e(i,s)&&n||Object.defineProperty(t,r,s)},H0e=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)},W0e=(t,e)=>{let r=Object.getPrototypeOf(e);r!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,r)},V0e=(t,e)=>`/* Wrapped ${t}*/
138
+ `);return s!==-1&&(e=YL(e,i,n,s)),n+e+i};Object.defineProperties(Vm.prototype,Sh);var j0e=Vm(),drt=Vm({level:KL?KL.level:0});var it=j0e;var ZL="0.1.10";var G6={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:{"@lody/types":"workspace:*","@agentclientprotocol/sdk":"^0.5.1","@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/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"]};var Qm=qe(require("node:process"),1);var tI=qe(require("node:process"),1);var zm=qe(require("node:process"),1);var $0e=(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);!H0e(i,s)&&n||Object.defineProperty(t,r,s)},H0e=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)},W0e=(t,e)=>{let r=Object.getPrototypeOf(e);r!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,r)},V0e=(t,e)=>`/* Wrapped ${t}*/
139
139
  ${e}`,z0e=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),G0e=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Y0e=(t,e,r)=>{let n=r===""?"":`with ${r.trim()}() `,i=V0e.bind(null,n,e.toString());Object.defineProperty(i,"name",G0e);let{writable:s,enumerable:o,configurable:a}=z0e;Object.defineProperty(t,"toString",{value:i,writable:s,enumerable:o,configurable:a})};function Y6(t,e,{ignoreNonConfigurable:r=!1}={}){let{name:n}=t;for(let i of Reflect.ownKeys(e))$0e(t,e,i,r);return W0e(t,e),Y0e(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 Y6(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",Q6=Symbol.for("signal-exit emitter"),K6=globalThis,Q0e=Object.defineProperty.bind(Object),J6=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(K6[Q6])return K6[Q6];Q0e(K6,Q6,{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{},K0e=t=>({onExit(e,r){return t.onExit(e,r)},load(){return t.load()},unload(){return t.unload()}}),X6=class extends fb{onExit(){return()=>{}}load(){}unload(){}},Z6=class extends fb{#e=eI.platform==="win32"?"SIGINT":"SIGHUP";#n=new J6;#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)}},eI=globalThis.process,{onExit:db,load:brt,unload:xrt}=K0e(lb(eI)?new Z6(eI):new X6);var r7=zm.default.stderr.isTTY?zm.default.stderr:zm.default.stdout.isTTY?zm.default.stdout:void 0,J0e=r7?t7(()=>{db(()=>{r7.write("\x1B[?25h")},{alwaysLast:!0})}):()=>{},n7=J0e;var hb=!1,Dh={};Dh.show=(t=tI.default.stderr)=>{t.isTTY&&(hb=!1,t.write("\x1B[?25h"))};Dh.hide=(t=tI.default.stderr)=>{t.isTTY&&(n7(),hb=!0,t.write("\x1B[?25l"))};Dh.toggle=(t,e)=>{t!==void 0&&(hb=t),hb?Dh.show(e):Dh.hide(e)};var rI=Dh;var Km=qe(nI(),1);var Us=qe(require("node:process"),1);function iI(){return Us.default.platform!=="win32"?Us.default.env.TERM!=="linux":!!Us.default.env.CI||!!Us.default.env.WT_SESSION||!!Us.default.env.TERMINUS_SUBLIME||Us.default.env.ConEmuTask==="{cmd::Cmder}"||Us.default.env.TERM_PROGRAM==="Terminus-Sublime"||Us.default.env.TERM_PROGRAM==="vscode"||Us.default.env.TERM==="xterm-256color"||Us.default.env.TERM==="alacritty"||Us.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Z0e={info:it.blue("\u2139"),success:it.green("\u2714"),warning:it.yellow("\u26A0"),error:it.red("\u2716")},eme={info:it.blue("i"),success:it.green("\u221A"),warning:it.yellow("\u203C"),error:it.red("\xD7")},tme=iI()?Z0e:eme,Gm=tme;function sI({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 rme=sI();function Ym(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return t.replace(rme,"")}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 nme(t){if(!Number.isSafeInteger(t))throw new TypeError(`Expected a code point, got \`${typeof t}\`.`)}function l7(t,{ambiguousAsWide:e=!1}={}){return nme(t),u7(t)||c7(t)||e&&a7(t)?2:1}var h7=qe(d7(),1),ime=new Intl.Segmenter,sme=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function oI(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 ime.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)&&!sme.test(o)){if((0,h7.default)().test(o)){i+=2;continue}i+=l7(a,s)}}return i}function aI({stream:t=process.stdout}={}){return!!(t&&t.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}var uI=qe(require("node:process"),1);function cI(){let{env:t}=uI.default,{TERM:e,TERM_PROGRAM:r}=t;return uI.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 Do=qe(require("node:process"),1),ome=3,lI=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(){Do.default.platform==="win32"||!Do.default.stdin.isTTY||(Do.default.stdin.setRawMode(!0),Do.default.stdin.on("data",this.#o),Do.default.stdin.resume())}#t(){Do.default.stdin.isTTY&&(Do.default.stdin.off("data",this.#o),Do.default.stdin.pause(),Do.default.stdin.setRawMode(!1))}#o(e){e[0]===ome&&Do.default.emit("SIGINT")}},ame=new lI,fI=ame;var ume=qe(nI(),1),dI=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:aI({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(!cI())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(oI(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&&rI.hide(this.#i),this.#r.discardStdin&&Qm.default.stdin.isTTY&&(this.#n=!0,fI.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&&rI.show(this.#i),this.#r.discardStdin&&Qm.default.stdin.isTTY&&this.#n&&(fI.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 RF(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 mMe(e,this.client)}};async function RF(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 mMe(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}}}NF();var Rn=qe(h0(),1);NF();var sZ=class{crdtType=rn.Loro;doc;config;ctx;localUpdateUnsubscribe;destroyed=!1;initServerVersion;reachServerVersionPromise;hasReachedServerVersion=!1;constructor(t,e={}){this.doc=t||new Rn.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=Rn.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=Rn.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=rn.LoroEphemeralStorePersisted;store;ctx;localUpdateUnsubscribe;destroyed=!1;constructor(t){this.store=t||new Rn.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 ayt=new TextEncoder,uyt=new TextDecoder;var qMe=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())}},cyt=new qMe;var UMe=class{crdtType=rn.Loro;createEmpty(){let t=new Rn.LoroDoc,e=t.export({mode:"snapshot"});return t.free(),e}handleJoinRequest(t,e,r){let n=new Rn.LoroDoc,i;try{t.length>0&&n.import(t),i=n.version();let s;if(e.length>0){let o=Rn.VersionVector.decode(e);s=[n.export({mode:"update",from:o})]}else s=[t];return{response:{type:at.JoinResponseOk,crdt:this.crdtType,roomId:"",permission:r,version:i.encode()},updates:s}}finally{n.free(),i?.free()}}applyUpdates(t,e,r){if(r==="read")return{success:!1,error:{type:at.UpdateError,crdt:this.crdtType,roomId:"",code:nn.PermissionDenied,message:"Read-only permission, cannot apply updates"}};let n=new Rn.LoroDoc,i=[];try{t.length>0&&n.import(t);for(let s of e)s.length>0&&n.import(s).success&&i.push(s);return{success:!0,newDocumentData:n.export({mode:"snapshot"}),broadcastUpdates:i.length>0?i:void 0}}catch(s){return{success:!1,error:{type:at.UpdateError,crdt:this.crdtType,roomId:"",code:nn.InvalidUpdate,message:s instanceof Error?s.message:"Invalid update"}}}finally{n.free()}}getVersion(t){let e=new Rn.LoroDoc,r;try{return t.length>0&&e.import(t),r=e.version(),r.encode()}finally{e.free(),r?.free()}}merge(t){let e=new Rn.LoroDoc;try{for(let r of t)r.length>0&&e.import(r);return e.export({mode:"snapshot"})}finally{e.free()}}},lyt=new UMe,jMe=class{crdtType=rn.LoroEphemeralStore;timeout;constructor(t={}){this.timeout=t.timeout??1e4}createEmpty(){let t=new Rn.EphemeralStore(this.timeout);try{return t.encodeAll()}finally{t.inner.free()}}handleJoinRequest(t,e,r){return{response:{type:at.JoinResponseOk,crdt:this.crdtType,roomId:"",permission:r,version:new Uint8Array},updates:t.length>0?[t]:void 0}}applyUpdates(t,e,r){if(r==="read")return{success:!1,error:{type:at.UpdateError,crdt:this.crdtType,roomId:"",code:nn.PermissionDenied,message:"Read-only permission, cannot apply updates"}};let n=new Rn.EphemeralStore(this.timeout),i=[];try{t.length>0&&n.apply(t);for(let s of e)s.length>0&&(n.apply(s),i.push(s));return{success:!0,newDocumentData:n.encodeAll(),broadcastUpdates:i.length>0?i:void 0}}catch(s){return{success:!1,error:{type:at.UpdateError,crdt:this.crdtType,roomId:"",code:nn.InvalidUpdate,message:s instanceof Error?s.message:"Invalid update"}}}finally{n.destroy(),n.inner.free()}}getVersion(t){return new Uint8Array}merge(t){let e=new Rn.EphemeralStore(this.timeout);for(let r of t)r.length>0&&e.apply(r);try{return e.encodeAll()}finally{e.destroy(),e.inner.free()}}},fyt=new jMe,$Me=class{crdtType=rn.LoroEphemeralStorePersisted;timeout;constructor(t={}){this.timeout=t.timeout??1e4}createEmpty(){let t=new Rn.EphemeralStore(this.timeout);try{return t.encodeAll()}finally{t.inner.free()}}handleJoinRequest(t,e,r){return{response:{type:at.JoinResponseOk,crdt:this.crdtType,roomId:"",permission:r,version:new Uint8Array},updates:t.length>0?[t]:void 0}}applyUpdates(t,e,r){if(r==="read")return{success:!1,error:{type:at.UpdateError,crdt:this.crdtType,roomId:"",code:nn.PermissionDenied,message:"Read-only permission, cannot apply updates"}};let n=new Rn.EphemeralStore(this.timeout),i=[];try{t.length>0&&n.apply(t);for(let s of e)s.length>0&&(n.apply(s),i.push(s));return{success:!0,newDocumentData:n.encodeAll(),broadcastUpdates:i.length>0?i:void 0}}catch(s){return{success:!1,error:{type:at.UpdateError,crdt:this.crdtType,roomId:"",code:nn.InvalidUpdate,message:s instanceof Error?s.message:"Invalid update"}}}finally{n.destroy(),n.inner.free()}}getVersion(t){return new Uint8Array}merge(t){let e=new Rn.EphemeralStore(this.timeout);for(let r of t)r.length>0&&e.apply(r);try{return e.encodeAll()}finally{e.destroy(),e.inner.free()}}},dyt=new $Me,HMe=class{crdtType=rn.YjsAwareness;createEmpty(){return new Uint8Array}handleJoinRequest(t,e,r){let n=t.length>0?[t]:void 0;return{response:{type:at.JoinResponseOk,crdt:this.crdtType,roomId:"",permission:r,version:new Uint8Array},updates:n}}applyUpdates(t,e,r){if(r==="read")return{success:!1,error:{type:at.UpdateError,crdt:this.crdtType,roomId:"",code:nn.PermissionDenied,message:"Read-only permission, cannot apply updates"}};try{let n=t.length;for(let o of e)n+=o.length;let i=new Uint8Array(n),s=0;t.length&&(i.set(t,0),s+=t.length);for(let o of e)o.length&&(i.set(o,s),s+=o.length);return{success:!0,newDocumentData:i,broadcastUpdates:e.length>0?e:void 0}}catch(n){return{success:!1,error:{type:at.UpdateError,crdt:this.crdtType,roomId:"",code:nn.InvalidUpdate,message:n instanceof Error?n.message:"Invalid update"}}}}getVersion(t){return new Uint8Array}merge(t){let e=0;for(let i of t)e+=i.length;let r=new Uint8Array(e),n=0;for(let i of t)i.length&&(r.set(i,n),n+=i.length);return r}},hyt=new HMe;var Ru={Connecting:"connecting",Connected:"connected",Disconnected:"disconnected"},aZ=class{constructor(t){this.ops=t,this.status=Ru.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!==Ru.Connected&&(this.clearReconnectTimer(),this.scheduleReconnect(!0))},this.handleOffline=()=>{if(this.clearReconnectTimer(),this.shouldReconnect){this.setStatus(Ru.Disconnected);try{this.ws?.close(1001,"Offline")}catch{}}},this.attachNetworkListeners(),this.ensureConnectedPromise(),this.connect()}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(Ru.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(Ru.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(Ru.Disconnected),this.rejectConnected?.(new Error("Disconnected"));return}this.setStatus(Ru.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(Zs({type:at.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 at.JoinRequest:throw new Error("JoinRequest should not be received by client");case at.JoinResponseOk:{let n=this.pendingRooms.get(r);n&&n.resolve(t);break}case at.JoinError:{let n=this.pendingRooms.get(r);n&&await this.handleJoinError(t,n,r);break}case at.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===rn.Elo){let s=this.preJoinUpdates.get(r)??[];s.push(...t.updates),this.preJoinUpdates.set(r,s)}}break}case at.DocUpdateFragmentHeader:this.handleFragmentHeader(t);break;case at.DocUpdateFragment:this.handleFragment(t);break;case at.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(Zs({type:at.UpdateError,crdt:t.crdt,roomId:t.roomId,code:nn.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===rn.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===Xs.VersionUnknown){let n=e.adaptor.getVersion(),i=e.adaptor.getAlternativeVersion?.(n);if(i){this.ws.send(Zs({type:at.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(Zs({type:at.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(Zs({type:at.JoinError,crdt:e.crdtType,roomId:t,code:Xs.AppError,message:d})),a(new Error(`Join failed: ${d}`))},onImportError:(d,p)=>{console.error(`Import error: ${d.message}`,p),this.ws.send(Zs({type:at.UpdateError,crdt:e.crdtType,roomId:t,code:nn.AppError,message:d.message}))}});let{room:l,handler:f}=YMe({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(Zs({type:at.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(Ru.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(Zs({type:at.DocUpdate,crdt:t,roomId:e,updates:[r]}));return}let s=Math.ceil(r.length/i),o=new Uint8Array(8);crypto.getRandomValues(o);let a=C_(o),u={type:at.DocUpdateFragmentHeader,crdt:t,roomId:e,batchId:a,fragmentCount:s,totalSizeBytes:r.length};n.send(Zs(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:at.DocUpdateFragment,crdt:t,roomId:e,batchId:a,index:c,fragment:d};n.send(Zs(p))}}sendLeave(t,e){!this.ws||this.ws.readyState!==WebSocket.OPEN||this.ws.send(Zs({type:at.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(Ru.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=GMe(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{}}}},VMe=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 zMe(t){return typeof t=="number"&&isFinite(t)&&t>0}function GMe(t){if(t.disablePing)return;let e=t.pingIntervalMs;return zMe(e)?e:3e4}function YMe(t){let e=new VMe(t);return{room:e,handler:e}}var zee=qe(h0());var iR={};nb(iR,{createValueFromSchema:()=>JMe,getDefaultValue:()=>P_,isContainerSchema:()=>Mu,isListLikeSchema:()=>rR,isLoroListSchema:()=>Nu,isLoroMapSchema:()=>Pu,isLoroMovableListSchema:()=>Bu,isLoroTextSchema:()=>nR,isLoroTreeSchema:()=>io,isRootSchemaType:()=>N_,schema:()=>Ee,validateSchema:()=>fd});var qn="$cid";function no(t,e){!Cn(t)||Object.prototype.hasOwnProperty.call(t,qn)||Object.defineProperty(t,qn,{value:e})}function Cn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date)&&!(t instanceof RegExp)&&typeof t!="function"}function Ra(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(!Ra(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)||!Ra(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 ZF(t,e,r){return Cn(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 vl(t,e,r){if(!e||t.kind!=="insert"&&t.kind!=="set")return t;let n=r?bl(r)??xl(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 bl(t){let e=t.getContainerType();return e===null?void 0:e}function xl(t,e){if(Cn(t))return"Map";if(Array.isArray(t))return e?.defaultMovableList?"MovableList":"List";if(typeof t=="string")return e?.defaultLoroText?"Text":void 0}function Pa(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(Cn(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 eR(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 tR=new WeakMap;function fZ(t){return typeof t=="object"&&t!==null}function QMe(t,e){return fZ(e)?tR.get(e)?.has(t)??!1:!1}function KMe(t,e){if(!fZ(e))return;let r=tR.get(e);r||(r=new WeakSet,tR.set(e,r)),r.add(t)}function Pu(t){return t.type==="loro-map"}function Nu(t){return t.type==="loro-list"}function rR(t){return Nu(t)||Bu(t)}function Bu(t){return t.type==="loro-movable-list"}function N_(t){return t.type==="schema"}function nR(t){return t.type==="loro-text"}function io(t){return t.type==="loro-tree"}function Mu(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(QMe(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(!Cn(e))r.push("Value must be an object");else if(Pu(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(Nu(t)||Bu(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(!io(t)){r.push("Invalid tree schema");break}let n=(i,s)=>{if(!Cn(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(!Cn(e))r.push("Value must be an object");else if(N_(t))if(!Cn(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?(KMe(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(Pu(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 JMe(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 bR={};nb(bR,{Mirror:()=>_d,SyncDirection:()=>gd,toNormalizedJson:()=>o2});var _Z=Symbol.for("immer-nothing"),dZ=Symbol.for("immer-draftable"),As=Symbol.for("immer-state"),XMe=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 rs(t,...e){if(process.env.NODE_ENV!=="production"){let r=XMe[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[As]}function hd(t){return t?yZ(t)||Array.isArray(t)||!!t[dZ]||!!t.constructor?.[dZ]||L_(t)||r2(t):!1}var ZMe=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)===ZMe}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[As];return e?e.type_:Array.isArray(t)?1:L_(t)?2:r2(t)?3:0}function aR(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 eLe(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 uR(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[As];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 pR(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=>pR(r,!0))),t}function JS(){rs(2)}function n2(t){return Object.isFrozen(t)}var tLe={};function pd(t){let e=tLe[t];return e||rs(0,t),e}var B_;function bZ(){return B_}function rLe(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 cR(t){lR(t),t.drafts_.forEach(nLe),t.drafts_=null}function lR(t){t===B_&&(B_=t.parent_)}function pZ(t){return B_=rLe(B_,t)}function nLe(t){let e=t[As];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[As].modified_&&(cR(e),rs(4)),hd(t)&&(t=ZS(e,t),e.parent_||e2(e,t)),e.patches_&&pd("Patches").generateReplacementPatches_(r[As].base_,t,e.patches_,e.inversePatches_)):t=ZS(e,r,[]),cR(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[As];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&&rs(5),m0(i)){let a=s&&e&&e.type_!==3&&!aR(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_&&pR(e,r)}function iLe(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=mR;r&&(i=[n],s=M_);let{revoke:o,proxy:a}=Proxy.revocable(i,s);return n.draft_=a,n.revoke_=o,a}var mR={get(t,e){if(e===As)return t;let r=dd(t);if(!aR(r,e))return sLe(t,r,e);let n=r[e];return t.finalized_||!hd(n)?n:n===sR(t.base_,e)?(oR(t),t.copy_[e]=dR(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=sR(dd(t),e),s=i?.[As];if(s&&s.base_===r)return t.copy_[e]=r,t.assigned_[e]=!1,!0;if(eLe(r,i)&&(r!==void 0||aR(t.base_,e)))return!0;oR(t),fR(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 sR(t.base_,e)!==void 0||e in t.base_?(t.assigned_[e]=!1,oR(t),fR(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(){rs(11)},getPrototypeOf(t){return p0(t.base_)},setPrototypeOf(){rs(12)}},M_={};XS(mR,(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))&&rs(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))&&rs(14),mR.set.call(this,t[0],e,r,t[0])};function sR(t,e){let r=t[As];return(r?dd(r):t)[e]}function sLe(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 fR(t){t.modified_||(t.modified_=!0,t.parent_&&fR(t.parent_))}function oR(t){t.copy_||(t.copy_=uR(t.base_,t.scope_.immer_.useStrictShallowCopy_))}var oLe=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"&&rs(6),n!==void 0&&typeof n!="function"&&rs(7);let i;if(hd(e)){let s=pZ(this),o=dR(e,void 0),a=!0;try{i=r(o),a=!1}finally{a?cR(s):lR(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_&&pR(i,!0),n){let s=[],o=[];pd("Patches").generateReplacementPatches_(e,i,s,o),n(s,o)}return i}else rs(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)||rs(8),m0(t)&&(t=aLe(t));let e=pZ(this),r=dR(t,void 0);return r[As].isManual_=!0,lR(e),r}finishDraft(t,e){let r=t&&t[As];(!r||!r.isManual_)&&rs(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 dR(t,e){let r=L_(t)?pd("MapSet").proxyMap_(t,e):r2(t)?pd("MapSet").proxySet_(t,e):iLe(t,e);return(e?e.scope_:bZ()).drafts_.push(r),r}function aLe(t){return m0(t)||rs(10,t),EZ(t)}function EZ(t){if(!hd(t)||n2(t))return t;let e=t[As],r;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,r=uR(t,e.scope_.immer_.useStrictShallowCopy_)}else r=uR(t,!0);return XS(r,(n,i)=>{vZ(r,n,EZ(i))}),e&&(e.finalized_=!1),r}var hR=new oLe,q_=hR.produce;var wZ=hR.setAutoFreeze.bind(hR);var Un=qe(h0(),1);var gR=qe(h0(),1);function md(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function U_(t){return Array.isArray(t)}function CZ(t,e,r){let n=typeof r=="function"?{getContainerById:r}:r||{};return q_(s=>{let o=new Set;for(let a of e.events)uLe(s,a,o,n.getContainerById,n.containerToJson,n.nodeDataWithCid,n.getNodeDataCid)})(t)}function uLe(t,e,r,n,i,s,o){if(_Le(e.target,r,n))return;let{parent:a,key:u,node:c}=cLe(t,e.path),l=c;if(l===void 0)if(e.diff.type==="map")a&&u!==void 0&&Na(a,u,{}),l=a&&u!==void 0?El(a,u):t;else if(e.diff.type==="list")a&&u!==void 0&&Na(a,u,[]),l=a&&u!==void 0?El(a,u):t;else if(e.diff.type==="text")a&&u!==void 0&&Na(a,u,""),l=a&&u!==void 0?El(a,u):t;else if(e.diff.type==="tree")a&&u!==void 0&&Na(a,u,[]),l=a&&u!==void 0?El(a,u):t;else if(e.diff.type==="counter")a&&u!==void 0&&Na(a,u,0),l=a&&u!==void 0?El(a,u):t;else{console.error("Unknown diff type:",e.diff);return}switch(e.diff.type){case"map":md(l)||(a&&u!==void 0&&Na(a,u,{}),l=a&&u!==void 0?El(a,u):t),md(l)&&dLe(l,e.diff.updated,r,i);break;case"list":U_(l)||(a&&u!==void 0&&Na(a,u,[]),l=a&&u!==void 0?El(a,u):[]),U_(l)&&hLe(l,e.diff.diff,r,i);break;case"text":{let d=gLe(typeof l=="string"?l:"",e.diff.diff);a&&u!==void 0&&Na(a,u,d);break}case"tree":U_(l)||(a&&u!==void 0&&Na(a,u,[]),l=a&&u!==void 0?El(a,u):[]),U_(l)&&(pLe(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);Na(a,u,d)}break}}function cLe(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=lLe(r,o);c?(s===e.length-1&&(r=c.node,i="data"),n=DZ(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 lLe(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 DZ(t){let e=t.data;if(md(e))return e;let r={};return t.data=r,r}function fLe(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 dLe(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,gR.isContainer)(s)){let o=s;r.add(o.id),t[i]=n?n(o):IZ(o);continue}t[i]=s}}function hLe(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,gR.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 pLe(t,e,r,n,i){let s=o=>{if(!o)return t;let a=mLe(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&&no(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 mLe(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 gLe(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 Na(t,e,r){(Array.isArray(t)&&typeof e=="number"||!Array.isArray(t)&&typeof e=="string")&&(t[e]=r)}function El(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 fLe(r)}return t.toJSON()}function _Le(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 wl(t,e,r,n,i,s){let o={oldState:e,newState:r,schema:i};if(n===""){if(!ld(o,eR,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,eR,Pu))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,Nu))throw new Error("Failed to diff container(list). Old and new state must be arrays");c=o.schema?.idSelector,c?u=bLe(t,o.oldState,o.newState,n,o.schema,c,s):u=xLe(t,e,r,n,i,s);break;case"MovableList":if(!ld(o,KS,Bu))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=vLe(t,o.oldState,o.newState,n,o.schema,c,s);break;case"Text":if(!ld(o,lZ,nR))throw new Error("Failed to diff container(text). Old and new state must be strings");u=yLe(o.oldState,o.newState,n);break;case"Tree":if(!ld(o,KS,io))throw new Error("Failed to diff container(tree). Old and new state must be arrays");u=_R(t,o.oldState,o.newState,n,o.schema,s);break;default:throw new Error(`Unsupported container type: ${a}`)}return u}function yLe(t,e,r){return e===t?[]:[{container:r,key:"",value:e,kind:"insert"}]}function _R(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,w,A){for(let F=0;F<v.length;F++){let C=v[F];C&&typeof C=="object"&&typeof C.id=="string"&&w.set(C.id,{id:C.id,parent:A,index:F,node:C}),C&&Array.isArray(C.children)&&d(C.children,w,typeof C.id=="string"?C.id:void 0)}}d(u,l),d(c,f);let p=[];for(let[v,w]of l)f.has(v)||p.push(w);let m=v=>{let w=0,A=v.parent?l.get(v.parent):void 0;for(;A;)w++,A=A.parent?l.get(A.parent):void 0;return w};p.sort((v,w)=>m(w)-m(v));for(let v of p)o.push({container:n,kind:"tree-delete",target:v.id});function _(v,w,A){for(let F=0;F<v.length;F++){let C=v[F],U=R_(C.id)?C.id:void 0,k=!U||!l.has(U),$=[];if(k){let O={container:n,kind:"tree-create",parent:w,index:F,value:C?.data,onCreate:T=>{C.id=T;for(let P of $)P.parent=T}};o.push(O),A?.push(O)}if(C&&Array.isArray(C.children)){let O=R_(C.id)?C.id:void 0;k?_(C.children,O,$):_(C.children,O)}}}_(c,void 0);for(let[v,w]of f){let A=l.get(v);if(!A)continue;let F=(A.parent??void 0)!==(w.parent??void 0),C=A.index!==w.index;(F||C)&&o.push({container:n,kind:"tree-move",target:v,parent:w.parent,index:w.index});try{let k=t.getTree(n).getNodeByID(v);if(k&&i){let $=w.node?.data;$&&typeof $=="object"&&!(qn in $)&&no($,k.data.id);let O=wl(t,A.node?.data,w.node?.data,k.data.id,i.nodeSchema,s);o.push(...O)}}catch(U){console.error(`Failed to diff node.data for node ${v}:`,U)}}return o}function vLe(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 w=u.get(v);w&&l.push({id:v,oldIndex:w.index,newIndex:m,oldItem:w.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(!Ra(d,p)){let m=[...d],_=new Map;m.forEach((v,w)=>_.set(v,w));for(let v=0;v<p.length;v++){let w=p[v],A=_.get(w);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 C=Math.min(A,v),U=Math.max(A,v);for(let k=C;k<=U;k++)_.set(m[k],k)}}for(let[m,_]of r.entries()){let v=s(_);(!v||!u.has(v))&&a.push(vl({container:n,key:m,value:_,kind:"insert"},!0,i?.itemSchema))}for(let m of l){if(Ra(m.oldItem,m.newItem))continue;let v=t.getMovableList(n).get(m.oldIndex);if((0,j_.isContainer)(v)){let w=wl(t,m.oldItem,m.newItem,v.id,i?.itemSchema,o);a.push(...w)}else a.push(vl({container:n,key:m.newIndex,value:m.newItem,kind:"set"},!0,i?.itemSchema))}return a}function bLe(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 w=s(v);w&&c.set(w,{item:v,index:_})}for(let[_,v]of r.entries()){let w=s(v);w&&l.set(w,{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 w=s(_),A=s(v);if(w===A){let F=f.get(m);(0,j_.isContainer)(F)?a.push(...wl(t,_,v,F.id,i?.itemSchema,o)):Ra(_,v)||(a.push({container:n,key:m+p,value:void 0,kind:"delete"}),a.push(vl({container:n,key:m+p,value:v,kind:"insert"},u,i?.itemSchema))),m++,d++;continue}if(A&&!c.has(A)){a.push(vl({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(vl({container:n,key:m+p,value:_,kind:"insert"},u,i?.itemSchema)),p++}return a}function xLe(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 w=c.get(v);if((0,j_.isContainer)(w)){let A=wl(t,e[v],r[v],w.id,i?.itemSchema,s);o.push(...A)}else o.push({container:n,key:v,value:void 0,kind:"delete"}),o.push(vl({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(vl({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===qn)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===qn)continue;let l=a[c],f=u[c],d=TZ(i,c);if(d&&d.type==="ignore")continue;let p=d?.getContainerType()??xl(f,s);if(d?.getContainerType()&&p&&!Pa(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=xl(f,s)),!(c in a)){p&&Pa(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&&Pa(p,f)&&Pa(p,l)){if(n===""){let w=F_(t,c,p);p==="Map"&&f&&typeof f=="object"&&!(qn in f)&&no(f,w.id),o.push(...wl(t,a[c],u[c],w.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(ZF(n,c,u[c])):(p==="Map"&&f&&typeof f=="object"&&!(qn in f)&&no(f,v.id),o.push(...wl(t,a[c],u[c],v.id,d,s)))}else o.push(ZF(n,c,u[c]))}return o}wZ(!1);function ELe(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=CZ(this.state,a,{getContainerById:u=>this.doc.getContainerById(u),containerToJson:u=>this.containerToStateJson(u),nodeDataWithCid:u=>{let c=this.getContainerSchema(u);return!!(c&&io(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=wLe(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):Cn(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=bl(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,Un.isContainer)(s)){let o;if(r&&Pu(r)){let a=this.getSchemaForMapKey(r,i);a&&Mu(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,Un.isContainer)(o)){let a;r&&(Nu(r)||Bu(r))&&(a=r.itemSchema),a&&this.registerContainer(o.id,a)}}}else if(e.kind()==="Tree"){let n=e,i;if(r&&io(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,Un.isContainer)(o)){let a=o,u;i&&rR(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,Un.isContainer)(s)){let a=Mu(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&&io(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=wl(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(!ELe(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&&io(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),Pu(s)&&Cn(a.value)&&no(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&&!Nu(n)&&!Bu(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);Ra(_,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];Ra(a,u)||(e.delete(o,1),this.insertItemIntoList(e,o,u,n))}}insertItemIntoList(e,r,n,i){let s=!1,o;if(i&&Mu(i)?(s=!0,o=i):s=xl(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(!Cn(n))return;let o=r;for(let[a,u]of Object.entries(n)){if(a===qn)continue;let c=this.getSchemaForMapKey(o,a);if(c&&Mu(c)){let l=bl(c);l&&Pa(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=Mu(o);for(let u=0;u<n.length;u++){let c=n[u];if(a){let l=bl(o);l&&Pa(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?bl(e):xl(r,this.options?.inferOptions);switch(n){case"Map":return[new Un.LoroMap,"Map"];case"List":return[new Un.LoroList,"List"];case"MovableList":return[new Un.LoroMovableList,"MovableList"];case"Text":return[new Un.LoroText,"Text"];case"Tree":return[new Un.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=vR(e.toJSON()),i=r,s=this.getContainerSchema(e.id),o=s&&io(s)?s:void 0,a=_R(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(!Cn(r))throw new Error("Map value must be an object");let n=this.getContainerSchema(e.id);n&&Cn(r)&&no(r,e.id);let i=new Set(e.keys());for(let[s,o]of Object.entries(r))if(s!==qn){if(n&&n.type==="loro-map")this.updateMapEntry(e,s,o,n);else{let a=xl(o,this.options?.inferOptions);a&&Pa(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!==qn){if(i&&i.type==="loro-map"){let s=i,o=this.getSchemaForMapKey(s,r);if(o&&o.type==="ignore")return;if(o&&Mu(o)){let a=bl(o);if(a&&Pa(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(!Ra(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={};no(i,e.id);for(let s of n.keys()){let o=n.get(s);i[s]=(0,Un.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,Un.isContainer)(a)?this.containerToStateJson(a):a)}return n}else{if(r==="Text")return e.toJSON();if(r==="Tree"){let n=e,i=vR(n.toJSON()),s=this.getContainerSchema(n.id);if(s&&io(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={}),no(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=bl(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){Cn(e)&&no(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||!Mu(n)))return n}getSchemaForChild(e,r){let n=this.getContainerSchema(e);if(n){if(Pu(n))return this.getSchemaForMapKey(n,String(r));if(Nu(n)||Bu(n))return n.itemSchema;if(io(n))return n.nodeSchema}}getContainerIds(){return Array.from(this.containerRegistry.keys())}};function o2(t){let e=t.toJsonWithReplacer((r,n)=>(0,Un.isContainer)(n)&&n.kind()==="Tree"?vR(n.toJSON()):(0,Un.isContainer)(n)&&n.kind()==="Map"?{...n.getShallowValue(),[qn]:n.id}:n);return yR(e)}function yR(t){if(Array.isArray(t)){for(let e=0;e<t.length;e++)t[e]=yR(t[e]);return t}if(Cn(t)){let e=t;for(let r of Object.keys(e))e[r]=yR(e[r]);if(Object.prototype.hasOwnProperty.call(e,qn)){let r=Object.getOwnPropertyDescriptor(e,qn);if(!r||r.enumerable){let n=e[qn];delete e[qn],Object.defineProperty(e,qn,{value:n})}}return e}return t}function wLe(t){let e={};for(let[r,n]of Object.entries(t))Array.isArray(n)?e[r]=[]:typeof n=="string"?e[r]="":Cn(n)?e[r]={}:e[r]=n;return e}function vR(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]="":Cn(i)&&(t[n]={}));continue}let o=s.type;if(o==="ignore"){t[n]=i;continue}if(o==="loro-map"){(!(n in t)||!Cn(t[n]))&&(t[n]={});let a=t[n],u=Cn(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 Jyt=Object.assign({},iR,bR);var nvt=Ee.LoroMap({name:Ee.String(),color:Ee.String()}),ivt=Ee.LoroMap({content:Ee.LoroText(),parentId:Ee.String({required:!1}),isDeleted:Ee.Boolean()}),SLe=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})}),DLe=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}),githubRepos:Ee.LoroList(Ee.String()),labels:Ee.LoroList(Ee.String()),estimate:Ee.Number({required:!1}),dueDate:Ee.String({required:!1}),createdAt:Ee.String(),actionHistory:Ee.LoroList(SLe,t=>t.$cid),subIssues:Ee.LoroList(Ee.String()),parentIssueId:Ee.String({required:!1}),attachments:Ee.LoroList(Ee.String())}),RZ=Ee({issue:DLe}),CLe=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:CLe}),ALe=Ee.LoroMap({contents:Ee.String(),userInput:Ee.String({required:!1}),timestamp:Ee.String(),role:Ee.String(),read:Ee.Boolean({required:!1})}),ILe=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(ALe,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:ILe}),TLe=Ee.LoroMap({userId:Ee.String(),avatar:Ee.String({required:!1}),name:Ee.String(),email:Ee.String(),role:Ee.String()}),kLe=Ee.LoroMap({id:Ee.String(),name:Ee.String(),githubRepos:Ee.LoroList(Ee.String()),members:Ee.LoroList(TLe,t=>t.userId)}),OLe=Ee.LoroMap({name:Ee.String(),color:Ee.String()}),BZ=Ee({meta:kLe,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(OLe,t=>t.$cid)}),MZ=t=>`issue-${t}`,LZ=t=>`session-${t}`,qZ=t=>`agent-${t}`;var FLe=5*60*1e3,UZ=t=>`ephemeral-${t}`,xR="machine-",Sl=t=>`${xR}${t}`,a2=class{constructor(e){this.store=e}aliveTimer=null;registerMachine(e,r){this.store.set(Sl(e),r),this.aliveTimer=setInterval(()=>{this.store.set(Sl(e),this.store.get(Sl(e)))},FLe/2)}unRegisterMachine(e){this.store.delete(Sl(e)),this.aliveTimer&&clearInterval(this.aliveTimer)}getMachineIds(){return this.store.keys().filter(e=>e.startsWith(xR)).map(e=>e.replace(xR,""))}getMachine(e){return this.store.get(Sl(e))}addMachineSession(e,r){let n=this.getMachine(e);if(n){let i=[...n.sessions,r];this.store.set(Sl(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(Sl(e),{...i,sessions:s})}}updateMachine(e,r){let n=this.getMachine(e);n&&this.store.set(Sl(e),{...n,...r})}};var J7e=qe(Nee(),1),X7e=qe(FR(),1),Z7e=qe(NR(),1),Vee=qe(v2(),1),eqe=qe(Wee(),1);var Al=Vee.default;globalThis.WebSocket=Al;var Uo=M4(),x2=class{constructor(e,r){this.workspaceId=e;this.token=r;Uo.debug(`[${this.workspaceId}] LoroWebsocketClient url: ${a0+`/ws/${this.workspaceId}`}`),this.client=new aZ({url:a0+`/ws/${this.workspaceId}`,onWsClose:()=>{Uo.debug(`[${this.workspaceId}] LoroWebsocketClient ws closed`),this.client.connect()}}),this.docMirror=new HR(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 GR(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 WR(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 VR(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 zR(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))}},HR=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){Uo.error(`Error occurs when importing loro data ${i}`)},onUpdateError(i){Uo.error(`Error occurs when updating loro ${i}`)}});Uo.debug(`[${e}] waiting for client connected`),await this.client.waitConnected(),Uo.debug(`[${e}] joining room`);let n=await this.client.join({roomId:e,crdtAdaptor:r});await n.waitForReachingServerVersion(),Uo.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)}},WR=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);Uo.debug(`[${this.issueId}] doc frontiers: ${JSON.stringify(r.getDoc().frontiers())}`),this.mirror.setState(n=>(n.issue.status!==e?(Uo.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()})):Uo.debug(`[${this.issueId}] setStatus ${e} no change`),n))}destroy(){this.docMirror.close(this.roomId)}},VR=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");Uo.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)}},zR=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()}},GR=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}};var K_=t=>t&&t.replace(/^['"]+|['"]+$/g,""),tqe=(t,e)=>{if(!e)return t;let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return t.replace(new RegExp(r,"g"),"***TOKEN***")},rqe=(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/`}},Yee=(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]},Qee=async(t,e,r,n,i,s)=>{let o=tqe([r,...n].join(" "),s);return e.debug(`[${t.sessionId}] Executing (${i}): ${o}`),await t.exec(r,n,i,!1)},Kee=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}=rqe(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 Qee(r,n,"git",Yee(["clone","--depth","1","--recurse-submodules","--shallow-submodules",c,s],l),"/",e),await Qee(r,n,"git",Yee(["-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 S2=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;setupSessionEventHandlers(){this.sessionManager.on("output",async e=>{this.logger.debug(`Output from session [${e.sessionId}]: ${e.data}`)}),this.sessionManager.on("onACPUpdateMessage",async(e,r)=>{this.logger.debug(`[${e}] Received ACP update message ${r}`);let n=await this.workspaceDocument.getOrCreateSessionDoc(e);await nqe(n,r)}),this.sessionManager.on("error",async e=>{this.logger.error(`[${e.sessionId}] error occur ${e}`);let r=e.sessionId;(await this.workspaceDocument.getOrCreateSessionDoc(r)).setError(e.error.message),await this.sessionManager.finishSession(r),this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"error",error:e.error.message})}),this.sessionManager.on("exit",async e=>{let r=e.sessionId;(await this.workspaceDocument.getOrCreateSessionDoc(r)).setStatus("completed"),this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"completed"})})}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"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"}`)}let s=this.sessionManager.getSession(r);s?(await s.agentClient?.connection?.prompt({sessionId:s.acpSessionId,prompt:[{type:"text",text:n.prompt}]}),this.logger.info(`[${r}] Chat request processed successfully`)):(this.logger.warn(`[${r}] Session not found`),this.sendMessage({type:"session_error",sessionId:r,error:"Session does not exist. Please create a new session first."}))}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"}});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 Kee(n.githubRepo,n.githubToken,o,this.logger)}catch(c){let l=c instanceof Error?c.message:"Failed to clone GitHub repository";this.logger.error(`[${r}] ${l}`),await this.sessionManager.setSessionError(r,l),this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"error",error:l});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}]});this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"completed"}),this.logger.debug(`[${r}] Prompt response: ${JSON.stringify(u)}`),this.logger.info(`[${r}] Session created successfully`)}catch(o){this.sessionManager.setSessionError(r,o instanceof Error?o.message:"Unknown 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);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:i instanceof Error?i.message:"Unknown error",reason:"error"};this.sendMessage(s),this.logger.error(`[${r}] Failed to terminate: ${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 sqe(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 iqe(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.sessionManager.cleanUp()}},nqe=async(t,e)=>{let{update:r,sessionId:n}=e;switch(r.sessionUpdate){case"user_message_chunk":break;case"agent_message_chunk":case"agent_thought_chunk":switch(r.content.type){case"text":w2(t,{type:"text",text:r.content.text});break;case"image":case"audio":case"resource_link":case"resource":throw new Error(`Unsupported content type: ${r.content.type}`)}break;case"tool_call":case"tool_call_update":w2(t,{type:"tool_call",toolCallId:r.toolCallId,title:r.title,kind:r.kind||void 0,status:r.status||"pending",content:r.content?.map(i=>{switch(i.type){case"diff":return{type:i.type,path:i.path,newText:i.newText,oldText:i.oldText};case"terminal":case"content":return}}).filter(i=>i!==void 0)});break;case"plan":w2(t,{type:"plan",entries:r.entries});break;case"available_commands_update":w2(t,{type:"available_commands",commands:r.availableCommands});break;case"current_mode_update":throw new Error(`Unsupported session update: ${r.sessionUpdate}`)}},w2=async(t,e)=>{await t.updateHistory(r=>{let n=null;if(r.length>0&&(n=r[r.length-1]),!n||n.role!=="assistant")return r.push({role:"assistant",contents:JSON.stringify([e]),timestamp:new Date().toISOString(),read:void 0,userInput:void 0}),r;let i=JSON.parse(n.contents);switch(e.type){case"text":case"thought":let s=i.findIndex(c=>c.type===e.type);if(s>=0){let c=i[s];(c.type==="text"||c.type==="thought")&&(c.text+=(c.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&&!Nu(n)&&!Bu(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);Ra(_,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];Ra(a,u)||(e.delete(o,1),this.insertItemIntoList(e,o,u,n))}}insertItemIntoList(e,r,n,i){let s=!1,o;if(i&&Mu(i)?(s=!0,o=i):s=xl(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(!Cn(n))return;let o=r;for(let[a,u]of Object.entries(n)){if(a===qn)continue;let c=this.getSchemaForMapKey(o,a);if(c&&Mu(c)){let l=bl(c);l&&Pa(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=Mu(o);for(let u=0;u<n.length;u++){let c=n[u];if(a){let l=bl(o);l&&Pa(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?bl(e):xl(r,this.options?.inferOptions);switch(n){case"Map":return[new Un.LoroMap,"Map"];case"List":return[new Un.LoroList,"List"];case"MovableList":return[new Un.LoroMovableList,"MovableList"];case"Text":return[new Un.LoroText,"Text"];case"Tree":return[new Un.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=vR(e.toJSON()),i=r,s=this.getContainerSchema(e.id),o=s&&io(s)?s:void 0,a=_R(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(!Cn(r))throw new Error("Map value must be an object");let n=this.getContainerSchema(e.id);n&&Cn(r)&&no(r,e.id);let i=new Set(e.keys());for(let[s,o]of Object.entries(r))if(s!==qn){if(n&&n.type==="loro-map")this.updateMapEntry(e,s,o,n);else{let a=xl(o,this.options?.inferOptions);a&&Pa(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!==qn){if(i&&i.type==="loro-map"){let s=i,o=this.getSchemaForMapKey(s,r);if(o&&o.type==="ignore")return;if(o&&Mu(o)){let a=bl(o);if(a&&Pa(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(!Ra(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={};no(i,e.id);for(let s of n.keys()){let o=n.get(s);i[s]=(0,Un.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,Un.isContainer)(a)?this.containerToStateJson(a):a)}return n}else{if(r==="Text")return e.toJSON();if(r==="Tree"){let n=e,i=vR(n.toJSON()),s=this.getContainerSchema(n.id);if(s&&io(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={}),no(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=bl(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){Cn(e)&&no(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||!Mu(n)))return n}getSchemaForChild(e,r){let n=this.getContainerSchema(e);if(n){if(Pu(n))return this.getSchemaForMapKey(n,String(r));if(Nu(n)||Bu(n))return n.itemSchema;if(io(n))return n.nodeSchema}}getContainerIds(){return Array.from(this.containerRegistry.keys())}};function o2(t){let e=t.toJsonWithReplacer((r,n)=>(0,Un.isContainer)(n)&&n.kind()==="Tree"?vR(n.toJSON()):(0,Un.isContainer)(n)&&n.kind()==="Map"?{...n.getShallowValue(),[qn]:n.id}:n);return yR(e)}function yR(t){if(Array.isArray(t)){for(let e=0;e<t.length;e++)t[e]=yR(t[e]);return t}if(Cn(t)){let e=t;for(let r of Object.keys(e))e[r]=yR(e[r]);if(Object.prototype.hasOwnProperty.call(e,qn)){let r=Object.getOwnPropertyDescriptor(e,qn);if(!r||r.enumerable){let n=e[qn];delete e[qn],Object.defineProperty(e,qn,{value:n})}}return e}return t}function wLe(t){let e={};for(let[r,n]of Object.entries(t))Array.isArray(n)?e[r]=[]:typeof n=="string"?e[r]="":Cn(n)?e[r]={}:e[r]=n;return e}function vR(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]="":Cn(i)&&(t[n]={}));continue}let o=s.type;if(o==="ignore"){t[n]=i;continue}if(o==="loro-map"){(!(n in t)||!Cn(t[n]))&&(t[n]={});let a=t[n],u=Cn(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 Jyt=Object.assign({},iR,bR);var nvt=Ee.LoroMap({name:Ee.String(),color:Ee.String()}),ivt=Ee.LoroMap({content:Ee.LoroText(),parentId:Ee.String({required:!1}),isDeleted:Ee.Boolean()}),SLe=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})}),DLe=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}),githubRepos:Ee.LoroList(Ee.String()),labels:Ee.LoroList(Ee.String()),estimate:Ee.Number({required:!1}),dueDate:Ee.String({required:!1}),createdAt:Ee.String(),actionHistory:Ee.LoroList(SLe,t=>t.$cid),subIssues:Ee.LoroList(Ee.String()),parentIssueId:Ee.String({required:!1}),attachments:Ee.LoroList(Ee.String())}),RZ=Ee({issue:DLe}),CLe=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:CLe}),ALe=Ee.LoroMap({contents:Ee.String(),userInput:Ee.String({required:!1}),timestamp:Ee.String(),role:Ee.String(),read:Ee.Boolean({required:!1})}),ILe=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(ALe,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:ILe}),TLe=Ee.LoroMap({userId:Ee.String(),avatar:Ee.String({required:!1}),name:Ee.String(),email:Ee.String(),role:Ee.String()}),kLe=Ee.LoroMap({id:Ee.String(),name:Ee.String(),githubRepos:Ee.LoroList(Ee.String()),members:Ee.LoroList(TLe,t=>t.userId)}),OLe=Ee.LoroMap({name:Ee.String(),color:Ee.String()}),BZ=Ee({meta:kLe,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(OLe,t=>t.$cid)}),MZ=t=>`issue-${t}`,LZ=t=>`session-${t}`,qZ=t=>`agent-${t}`;var FLe=5*60*1e3,UZ=t=>`ephemeral-${t}`,xR="machine-",Sl=t=>`${xR}${t}`,a2=class{constructor(e){this.store=e}aliveTimer=null;registerMachine(e,r){this.store.set(Sl(e),r),this.aliveTimer=setInterval(()=>{this.store.set(Sl(e),this.store.get(Sl(e)))},FLe/2)}unRegisterMachine(e){this.store.delete(Sl(e)),this.aliveTimer&&clearInterval(this.aliveTimer)}getMachineIds(){return this.store.keys().filter(e=>e.startsWith(xR)).map(e=>e.replace(xR,""))}getMachine(e){return this.store.get(Sl(e))}addMachineSession(e,r){let n=this.getMachine(e);if(n){let i=[...n.sessions,r];this.store.set(Sl(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(Sl(e),{...i,sessions:s})}}updateMachine(e,r){let n=this.getMachine(e);n&&this.store.set(Sl(e),{...n,...r})}};var J7e=qe(Nee(),1),X7e=qe(FR(),1),Z7e=qe(NR(),1),Vee=qe(v2(),1),eqe=qe(Wee(),1);var Al=Vee.default;globalThis.WebSocket=Al;var Uo=M4(),x2=class{constructor(e,r){this.workspaceId=e;this.token=r;Uo.debug(`[${this.workspaceId}] LoroWebsocketClient url: ${a0+`/ws/${this.workspaceId}`}`),this.client=new aZ({url:a0+`/ws/${this.workspaceId}`,onWsClose:()=>{Uo.debug(`[${this.workspaceId}] LoroWebsocketClient ws closed`),this.client.connect()}}),this.docMirror=new HR(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 GR(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 WR(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 VR(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 zR(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))}},HR=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){Uo.error(`Error occurs when importing loro data ${i}`)},onUpdateError(i){Uo.error(`Error occurs when updating loro ${i}`)}});Uo.debug(`[${e}] waiting for client connected`),await this.client.waitConnected(),Uo.debug(`[${e}] joining room`);let n=await this.client.join({roomId:e,crdtAdaptor:r});await n.waitForReachingServerVersion(),Uo.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)}},WR=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);Uo.debug(`[${this.issueId}] doc frontiers: ${JSON.stringify(r.getDoc().frontiers())}`),this.mirror.setState(n=>(n.issue.status!==e?(Uo.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()})):Uo.debug(`[${this.issueId}] setStatus ${e} no change`),n))}destroy(){this.docMirror.close(this.roomId)}},VR=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");Uo.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)}},zR=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()}},GR=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}};var K_=t=>t&&t.replace(/^['"]+|['"]+$/g,""),tqe=(t,e)=>{if(!e)return t;let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return t.replace(new RegExp(r,"g"),"***TOKEN***")},rqe=(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/`}},Yee=(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]},Qee=async(t,e,r,n,i,s)=>{let o=tqe([r,...n].join(" "),s);return e.debug(`[${t.sessionId}] Executing (${i}): ${o}`),await t.exec(r,n,i,!1)},Kee=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}=rqe(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 Qee(r,n,"git",Yee(["clone","--depth","1","--recurse-submodules","--shallow-submodules",c,s],l),"/",e),await Qee(r,n,"git",Yee(["-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 S2=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;setupSessionEventHandlers(){this.sessionManager.on("output",async e=>{this.logger.debug(`Output from session [${e.sessionId}]: ${e.data}`)}),this.sessionManager.on("onACPUpdateMessage",async(e,r)=>{this.logger.debug(`[${e}] Received ACP update message ${r}`);let n=await this.workspaceDocument.getOrCreateSessionDoc(e);await nqe(n,r)}),this.sessionManager.on("error",async e=>{this.logger.error(`[${e.sessionId}] error occur ${e}`);let r=e.sessionId;(await this.workspaceDocument.getOrCreateSessionDoc(r)).setError(e.error.message),await this.sessionManager.finishSession(r),this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"error",error:e.error.message})}),this.sessionManager.on("exit",async e=>{let r=e.sessionId;(await this.workspaceDocument.getOrCreateSessionDoc(r)).setStatus("completed"),this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"completed"})})}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"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"}`)}let s=this.sessionManager.getSession(r);s?(await s.agentClient?.connection?.prompt({sessionId:s.acpSessionId,prompt:[{type:"text",text:n.prompt}]}),this.logger.info(`[${r}] Chat request processed successfully`)):(this.logger.warn(`[${r}] Session not found`),this.sendMessage({type:"session_error",sessionId:r,error:"Session does not exist. Please create a new session first."}))}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"}});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 Kee(n.githubRepo,n.githubToken,o,this.logger)}catch(l){let f=l instanceof Error?l.message:"Failed to clone GitHub repository";this.logger.error(`[${r}] ${f}`),await this.sessionManager.setSessionError(r,f),this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"error",error:f});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"),this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"completed"}),this.logger.debug(`[${r}] Prompt response: ${JSON.stringify(u)}`),this.logger.info(`[${r}] Session created successfully`)}catch(o){this.sessionManager.setSessionError(r,o instanceof Error?o.message:"Unknown 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);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:i instanceof Error?i.message:"Unknown error",reason:"error"};this.sendMessage(s),this.logger.error(`[${r}] Failed to terminate: ${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 sqe(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 iqe(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.sessionManager.cleanUp()}},nqe=async(t,e)=>{let{update:r,sessionId:n}=e;switch(r.sessionUpdate){case"user_message_chunk":break;case"agent_message_chunk":case"agent_thought_chunk":switch(r.content.type){case"text":w2(t,{type:"text",text:r.content.text});break;case"image":case"audio":case"resource_link":case"resource":throw new Error(`Unsupported content type: ${r.content.type}`)}break;case"tool_call":case"tool_call_update":w2(t,{type:"tool_call",toolCallId:r.toolCallId,title:r.title,kind:r.kind||void 0,status:r.status||"pending",content:r.content?.map(i=>{switch(i.type){case"diff":return{type:i.type,path:i.path,newText:i.newText,oldText:i.oldText};case"terminal":case"content":return}}).filter(i=>i!==void 0)});break;case"plan":w2(t,{type:"plan",entries:r.entries});break;case"available_commands_update":w2(t,{type:"available_commands",commands:r.availableCommands});break;case"current_mode_update":throw new Error(`Unsupported session update: ${r.sessionUpdate}`)}},w2=async(t,e)=>{await t.updateHistory(r=>{let n=null;if(r.length>0&&(n=r[r.length-1]),!n||n.role!=="assistant")return r.push({role:"assistant",contents:JSON.stringify([e]),timestamp:new Date().toISOString(),read:void 0,userInput:void 0}),r;let i=JSON.parse(n.contents);switch(e.type){case"text":case"thought":let s=i.findIndex(c=>c.type===e.type);if(s>=0){let c=i[s];(c.type==="text"||c.type==="thought")&&(c.text+=(c.type==="thought"?`
192
192
  `:"")+e.text)}else i.push(e);return n.contents=JSON.stringify(i),r;case"plan":let o=i.findIndex(c=>c.type==="plan");return o>=0?i[o]=e:i.push(e),r;case"tool_call":let a=!1,u=r.map(c=>({...c,contents:JSON.stringify(JSON.parse(c.contents).map(l=>{if(l.type==="tool_call"&&l.toolCallId===e.toolCallId&&e.type==="tool_call"){a=!0;let f=l.content||[];if(e.content!==void 0){let d=e.content;d.some(m=>m.type==="diff")&&(f=f.filter(m=>m.type!=="diff")),f=[...f,...d]}return{...l,toolCallId:e.toolCallId,title:e.title!==void 0?e.title:l.title,kind:e.kind!==void 0?e.kind:l.kind,status:e.status!==void 0?e.status:l.status,content:f}}return l}))}));return a||u.push({contents:JSON.stringify([e]),timestamp:new Date().toISOString(),role:"assistant",userInput:void 0,read:void 0}),u;case"available_commands":return r.push({contents:JSON.stringify([e]),timestamp:new Date().toISOString(),role:"assistant",userInput:void 0,read:void 0}),r;default:return r}})},iqe=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,Jee(l,e,r)):l);u&&(o.contents=JSON.stringify(c))}),s||i.push({role:"assistant",contents:JSON.stringify([oqe(e,r)]),timestamp:new Date().toISOString(),userInput:void 0,read:void 0}),i})},sqe=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))},Jee=(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}}},oqe=(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 Jee(r,t,e)};var D2=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 S2(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 $fe=qe(ife());var WA=qe(ofe(),1);var VA=WA.default;var SM={claude:{command:"npx",args:["-y","@zed-industries/claude-code-acp"]},codex:{command:"npx",args:["-y","@zed-industries/codex-acp"]}};var Cm=class extends WA.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")),r6=qe(require("os")),n6=qe(require("fs"));var afe=require("stream"),Am=class extends afe.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 jfe=require("stream");var x={};nb(x,{BRAND:()=>_Ze,DIRTY:()=>rh,EMPTY_PATH:()=>QXe,INVALID:()=>_t,NEVER:()=>tet,OK:()=>Oi,ParseStatus:()=>yi,Schema:()=>zt,ZodAny:()=>pf,ZodArray:()=>fc,ZodBigInt:()=>ih,ZodBoolean:()=>sh,ZodBranded:()=>Uv,ZodCatch:()=>gh,ZodDate:()=>oh,ZodDefault:()=>mh,ZodDiscriminatedUnion:()=>YA,ZodEffects:()=>Eo,ZodEnum:()=>hh,ZodError:()=>ms,ZodFirstPartyTypeKind:()=>xt,ZodFunction:()=>KA,ZodIntersection:()=>lh,ZodIssueCode:()=>Ie,ZodLazy:()=>fh,ZodLiteral:()=>dh,ZodMap:()=>Rm,ZodNaN:()=>Nm,ZodNativeEnum:()=>ph,ZodNever:()=>aa,ZodNull:()=>uh,ZodNullable:()=>au,ZodNumber:()=>nh,ZodObject:()=>gs,ZodOptional:()=>bo,ZodParsedType:()=>He,ZodPipeline:()=>jv,ZodPromise:()=>mf,ZodReadonly:()=>_h,ZodRecord:()=>QA,ZodSchema:()=>zt,ZodSet:()=>Pm,ZodString:()=>hf,ZodSymbol:()=>Om,ZodTransformer:()=>Eo,ZodTuple:()=>ou,ZodType:()=>zt,ZodUndefined:()=>ah,ZodUnion:()=>ch,ZodUnknown:()=>lc,ZodVoid:()=>Fm,addIssueToContext:()=>Be,any:()=>CZe,array:()=>kZe,bigint:()=>xZe,boolean:()=>yfe,coerce:()=>eet,custom:()=>mfe,date:()=>EZe,datetimeRegex:()=>hfe,defaultErrorMap:()=>uc,discriminatedUnion:()=>PZe,effect:()=>zZe,enum:()=>HZe,function:()=>UZe,getErrorMap:()=>Im,getParsedType:()=>su,instanceof:()=>vZe,intersection:()=>NZe,isAborted:()=>zA,isAsync:()=>Tm,isDirty:()=>GA,isValid:()=>df,late:()=>yZe,lazy:()=>jZe,literal:()=>$Ze,makeIssue:()=>qv,map:()=>LZe,nan:()=>bZe,nativeEnum:()=>WZe,never:()=>IZe,null:()=>DZe,nullable:()=>YZe,number:()=>_fe,object:()=>OZe,objectUtil:()=>DM,oboolean:()=>ZZe,onumber:()=>XZe,optional:()=>GZe,ostring:()=>JZe,pipeline:()=>KZe,preprocess:()=>QZe,promise:()=>VZe,quotelessJson:()=>zXe,record:()=>MZe,set:()=>qZe,setErrorMap:()=>YXe,strictObject:()=>FZe,string:()=>gfe,symbol:()=>wZe,transformer:()=>zZe,tuple:()=>BZe,undefined:()=>SZe,union:()=>RZe,unknown:()=>AZe,util:()=>nr,void:()=>TZe});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 DM;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(DM||(DM={}));var He=nr.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),su=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"]),zXe=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),ms=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()}};ms.create=t=>new ms(t);var GXe=(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=GXe;var ufe=uc;function YXe(t){ufe=t}function Im(){return ufe}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}},QXe=[];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 yi=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 _t;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 _t;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}}},_t=Object.freeze({status:"aborted"}),rh=t=>({status:"dirty",value:t}),Oi=t=>({status:"valid",value:t}),zA=t=>t.status==="aborted",GA=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 xo=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}},cfe=(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 ms(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 su(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:su(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new yi,ctx:{common:e.parent.common,data:e.data,parsedType:su(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:su(e)},i=this._parseSync({data:e,path:n.path,parent:n});return cfe(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:su(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:su(e)},i=this._parse({data:e,path:n.path,parent:n}),s=await(Tm(i)?i:Promise.resolve(i));return cfe(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 Eo({schema:this,typeName:xt.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 bo.create(this,this._def)}nullable(){return au.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 Eo({...jt(this._def),schema:this,typeName:xt.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:xt.ZodDefault})}brand(){return new Uv({typeName:xt.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:xt.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}},KXe=/^c[^\s-]{8,}$/i,JXe=/^[0-9a-z]+$/,XXe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ZXe=/^[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,eZe=/^[a-z0-9_-]{21}$/i,tZe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,rZe=/^[-+]?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)?)??$/,nZe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,iZe="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",CM,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])$/,oZe=/^(?:(?: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])$/,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]))$/,uZe=/^(([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])$/,cZe=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,lZe=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ffe="((\\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])))",fZe=new RegExp(`^${ffe}$`);function dfe(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 dZe(t){return new RegExp(`^${dfe(t)}$`)}function hfe(t){let e=`${ffe}T${dfe(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 hZe(t,e){return!!((e==="v4"||!e)&&sZe.test(t)||(e==="v6"||!e)&&aZe.test(t))}function pZe(t,e){if(!tZe.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 mZe(t,e){return!!((e==="v4"||!e)&&oZe.test(t)||(e==="v6"||!e)&&uZe.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}),_t}let n=new yi,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")nZe.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")CM||(CM=new RegExp(iZe,"u")),CM.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")ZXe.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")eZe.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")KXe.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")JXe.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")XXe.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"?hfe(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"?fZe.test(e.data)||(i=this._getOrReturnCtx(e,i),Be(i,{code:Ie.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?dZe(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"?rZe.test(e.data)||(i=this._getOrReturnCtx(e,i),Be(i,{validation:"duration",code:Ie.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?hZe(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"?pZe(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"?mZe(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"?cZe.test(e.data)||(i=this._getOrReturnCtx(e,i),Be(i,{validation:"base64",code:Ie.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?lZe.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:xt.ZodString,coerce:t?.coerce??!1,...jt(t)});function gZe(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}),_t}let n,i=new yi;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"?gZe(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:xt.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 yi;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}),_t}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:xt.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}),_t}return Oi(e.data)}};sh.create=t=>new sh({typeName:xt.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}),_t}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return Be(s,{code:Ie.invalid_date}),_t}let n=new yi,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:xt.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}),_t}return Oi(e.data)}};Om.create=t=>new Om({typeName:xt.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}),_t}return Oi(e.data)}};ah.create=t=>new ah({typeName:xt.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}),_t}return Oi(e.data)}};uh.create=t=>new uh({typeName:xt.ZodNull,...jt(t)});var pf=class extends zt{constructor(){super(...arguments),this._any=!0}_parse(e){return Oi(e.data)}};pf.create=t=>new pf({typeName:xt.ZodAny,...jt(t)});var lc=class extends zt{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Oi(e.data)}};lc.create=t=>new lc({typeName:xt.ZodUnknown,...jt(t)});var aa=class extends zt{_parse(e){let r=this._getOrReturnCtx(e);return Be(r,{code:Ie.invalid_type,expected:He.never,received:r.parsedType}),_t}};aa.create=t=>new aa({typeName:xt.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}),_t}return Oi(e.data)}};Fm.create=t=>new Fm({typeName:xt.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}),_t;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 xo(r,o,r.path,a)))).then(o=>yi.mergeArray(n,o));let s=[...r.data].map((o,a)=>i.type._parseSync(new xo(r,o,r.path,a)));return yi.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:xt.ZodArray,...jt(e)});function km(t){if(t instanceof gs){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=bo.create(km(n))}return new gs({...t._def,shape:()=>e})}else return t instanceof fc?new fc({...t._def,type:km(t.element)}):t instanceof bo?bo.create(km(t.unwrap())):t instanceof au?au.create(km(t.unwrap())):t instanceof ou?ou.create(t.items.map(e=>km(e))):t}var gs=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}),_t}let{status:n,ctx:i}=this._processInputParams(e),{shape:s,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof aa&&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 xo(i,f,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof aa){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 xo(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=>yi.mergeObjectSync(n,c)):yi.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:xt.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 bo;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return pfe(nr.objectKeys(this.shape))}};gs.create=(t,e)=>new gs({shape:()=>t,unknownKeys:"strip",catchall:aa.create(),typeName:xt.ZodObject,...jt(e)});gs.strictCreate=(t,e)=>new gs({shape:()=>t,unknownKeys:"strict",catchall:aa.create(),typeName:xt.ZodObject,...jt(e)});gs.lazycreate=(t,e)=>new gs({shape:t,unknownKeys:"strip",catchall:aa.create(),typeName:xt.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 ms(a.ctx.common.issues));return Be(r,{code:Ie.invalid_union,unionErrors:o}),_t}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 ms(u));return Be(r,{code:Ie.invalid_union,unionErrors:a}),_t}}get options(){return this._def.options}};ch.create=(t,e)=>new ch({options:t,typeName:xt.ZodUnion,...jt(e)});var cc=t=>t instanceof fh?cc(t.schema):t instanceof Eo?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 bo?[void 0,...cc(t.unwrap())]:t instanceof au?[null,...cc(t.unwrap())]:t instanceof Uv||t instanceof _h?cc(t.unwrap()):t instanceof gh?cc(t._def.innerType):[],YA=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}),_t;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]}),_t)}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:xt.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...jt(n)})}};function AM(t,e){let r=su(t),n=su(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(zA(s)||zA(o))return _t;let a=AM(s.value,o.value);return a.valid?((GA(s)||GA(o))&&r.dirty(),{status:r.value,value:a.data}):(Be(n,{code:Ie.invalid_intersection_types}),_t)};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:xt.ZodIntersection,...jt(r)});var ou=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}),_t;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"}),_t;!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 xo(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(s).then(o=>yi.mergeArray(r,o)):yi.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};ou.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ou({items:t,typeName:xt.ZodTuple,rest:null,...jt(e)})};var QA=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}),_t;let i=[],s=this._def.keyType,o=this._def.valueType;for(let a in n.data)i.push({key:s._parse(new xo(n,a,n.path,a)),value:o._parse(new xo(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?yi.mergeObjectAsync(r,i):yi.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:xt.ZodRecord,...jt(n)}):new t({keyType:hf.create(),valueType:e,typeName:xt.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}),_t;let i=this._def.keyType,s=this._def.valueType,o=[...n.data.entries()].map(([a,u],c)=>({key:i._parse(new xo(n,a,n.path,[c,"key"])),value:s._parse(new xo(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 _t;(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 _t;(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:xt.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}),_t;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 _t;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 xo(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:xt.ZodSet,...jt(e)});var KA=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}),_t;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 Oi(async function(...u){let c=new ms([]),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 Oi(function(...u){let c=a._def.args.safeParse(u,s);if(!c.success)throw new ms([n(u,c.error)]);let l=Reflect.apply(o,this,c.data),f=a._def.returns.safeParse(l,s);if(!f.success)throw new ms([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:ou.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||ou.create([]).rest(lc.create()),returns:r||lc.create(),typeName:xt.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:xt.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}),_t}return{status:"valid",value:e.data}}get value(){return this._def.value}};dh.create=(t,e)=>new dh({value:t,typeName:xt.ZodLiteral,...jt(e)});function pfe(t,e){return new hh({values:t,typeName:xt.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}),_t}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}),_t}return Oi(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=pfe;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}),_t}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}),_t}return Oi(e.data)}get enum(){return this._def.values}};ph.create=(t,e)=>new ph({values:t,typeName:xt.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}),_t;let n=r.parsedType===He.promise?r.data:Promise.resolve(r.data);return Oi(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};mf.create=(t,e)=>new mf({type:t,typeName:xt.ZodPromise,...jt(e)});var Eo=class extends zt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===xt.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 _t;let u=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return u.status==="aborted"?_t:u.status==="dirty"?rh(u.value):r.value==="dirty"?rh(u.value):u});{if(r.value==="aborted")return _t;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?_t: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"?_t:(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"?_t:(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 _t;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})):_t);nr.assertNever(i)}};Eo.create=(t,e,r)=>new Eo({schema:t,typeName:xt.ZodEffects,effect:e,...jt(r)});Eo.createWithPreprocess=(t,e,r)=>new Eo({schema:e,effect:{type:"preprocess",transform:t},typeName:xt.ZodEffects,...jt(r)});var bo=class extends zt{_parse(e){return this._getType(e)===He.undefined?Oi(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};bo.create=(t,e)=>new bo({innerType:t,typeName:xt.ZodOptional,...jt(e)});var au=class extends zt{_parse(e){return this._getType(e)===He.null?Oi(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};au.create=(t,e)=>new au({innerType:t,typeName:xt.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:xt.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 ms(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ms(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};gh.create=(t,e)=>new gh({innerType:t,typeName:xt.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}),_t}return{status:"valid",value:e.data}}};Nm.create=t=>new Nm({typeName:xt.ZodNaN,...jt(t)});var _Ze=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"?_t: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"?_t: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:xt.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:xt.ZodReadonly,...jt(e)});function lfe(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function mfe(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=lfe(e,n),u=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:u})}});if(!s){let o=lfe(e,n),a=o.fatal??r??!0;i.addIssue({code:"custom",...o,fatal:a})}}):pf.create()}var yZe={object:gs.lazycreate},xt;(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"})(xt||(xt={}));var vZe=(t,e={message:`Input not instance of ${t.name}`})=>mfe(r=>r instanceof t,e),gfe=hf.create,_fe=nh.create,bZe=Nm.create,xZe=ih.create,yfe=sh.create,EZe=oh.create,wZe=Om.create,SZe=ah.create,DZe=uh.create,CZe=pf.create,AZe=lc.create,IZe=aa.create,TZe=Fm.create,kZe=fc.create,OZe=gs.create,FZe=gs.strictCreate,RZe=ch.create,PZe=YA.create,NZe=lh.create,BZe=ou.create,MZe=QA.create,LZe=Rm.create,qZe=Pm.create,UZe=KA.create,jZe=fh.create,$Ze=dh.create,HZe=hh.create,WZe=ph.create,VZe=mf.create,zZe=Eo.create,GZe=bo.create,YZe=au.create,QZe=Eo.createWithPreprocess,KZe=jv.create,JZe=()=>gfe().optional(),XZe=()=>_fe().optional(),ZZe=()=>yfe().optional(),eet={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 tet=_t;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"},uu={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"},bfe=1,ret=x.null(),net=x.number(),iet=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()}),set=x.record(x.unknown()),oet=x.union([x.literal("assistant"),x.literal("user")]),aet=x.object({_meta:x.record(x.unknown()).optional(),mimeType:x.string().optional().nullable(),text:x.string(),uri:x.string()}),uet=x.object({_meta:x.record(x.unknown()).optional(),blob:x.string(),mimeType:x.string().optional().nullable(),uri:x.string()}),xfe=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")]),Efe=x.union([x.literal("pending"),x.literal("in_progress"),x.literal("completed"),x.literal("failed")]),wfe=x.object({code:x.number(),data:x.record(x.unknown()).optional(),message:x.string()}),cet=x.object({_meta:x.record(x.unknown()).optional()}),fet=x.object({_meta:x.unknown().optional()}),det=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")])}),het=x.object({_meta:x.record(x.unknown()).optional()}),pet=x.record(x.unknown()),met=x.string(),get=x.record(x.unknown()),_et=x.object({hint:x.string()}),yet=x.null(),vet=x.number(),bet=x.string(),Sfe=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()}),Cfe=x.object({_meta:x.record(x.unknown()).optional(),modelId:x.string(),sessionId:x.string()}),xet=x.record(x.unknown()),vfe=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(oet).optional().nullable(),lastModified:x.string().optional().nullable(),priority:x.number().optional().nullable()}),$v=x.union([aet,uet]),Eet=x.object({_meta:x.record(x.unknown()).optional()}),wet=x.object({_meta:x.record(x.unknown()).optional(),content:x.string()}),Det=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()}),Aet=x.object({_meta:x.record(x.unknown()).optional()}),Iet=x.object({_meta:x.record(x.unknown()).optional(),exitCode:x.number().optional().nullable(),signal:x.string().optional().nullable()}),Tet=x.object({_meta:x.record(x.unknown()).optional()}),ket=x.record(x.unknown()),Afe=x.object({_meta:x.record(x.unknown()).optional(),sessionId:x.string()}),Oet=x.record(x.unknown()),Fet=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()}),Ife=x.object({_meta:x.record(x.unknown()).optional(),name:x.string(),value:x.string()}),Tfe=x.object({name:x.string(),title:x.string().optional().nullable(),version:x.string()}),Ret=x.object({_meta:x.record(x.unknown()).optional(),description:x.string().optional().nullable(),id:x.string(),name:x.string()}),Pet=x.object({_meta:x.record(x.unknown()).optional(),http:x.boolean().optional(),sse:x.boolean().optional()}),Net=x.object({_meta:x.record(x.unknown()).optional(),audio:x.boolean().optional(),embeddedContext:x.boolean().optional(),image:x.boolean().optional()}),Bet=x.object({_meta:x.record(x.unknown()).optional(),description:x.string().optional().nullable(),modelId:x.string(),name:x.string()}),Met=x.object({_meta:x.record(x.unknown()).optional(),description:x.string().optional().nullable(),id:met,name:x.string()}),kfe=x.object({_meta:x.record(x.unknown()).optional(),availableModels:x.array(Bet),currentModelId:x.string()}),Ofe=x.object({_meta:x.record(x.unknown()).optional(),availableModes:x.array(Met),currentModeId:x.string()}),Let=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")])}),qet=_et,Uet=x.object({_meta:x.record(x.unknown()).optional(),readTextFile:x.boolean().optional(),writeTextFile:x.boolean().optional()}),jet=x.object({args:x.array(x.string()),command:x.string(),env:x.array(Ife),name:x.string()}),Ffe=x.union([x.object({headers:x.array(vfe),name:x.string(),type:x.literal("http"),url:x.string()}),x.object({headers:x.array(vfe),name:x.string(),type:x.literal("sse"),url:x.string()}),jet]),$et=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")})]),Het=x.object({_meta:x.record(x.unknown()).optional(),exitCode:x.number().optional().nullable(),signal:x.string().optional().nullable()}),Wet=x.union([Afe,Oet]),BM=x.object({_meta:x.record(x.unknown()).optional(),options:x.array(Fet),sessionId:x.string(),toolCall:x.object({_meta:x.record(x.unknown()).optional(),content:x.array(IM).optional().nullable(),kind:xfe.optional().nullable(),locations:x.array(TM).optional().nullable(),rawInput:x.record(x.unknown()).optional(),rawOutput:x.record(x.unknown()).optional(),status:Efe.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(Ife).optional(),outputByteLimit:x.number().optional().nullable(),sessionId:x.string()}),Vet=x.object({_meta:x.record(x.unknown()).optional(),models:kfe.optional().nullable(),modes:Ofe.optional().nullable(),sessionId:x.string()}),zet=x.object({_meta:x.record(x.unknown()).optional(),models:kfe.optional().nullable(),modes:Ofe.optional().nullable()}),Get=x.object({method:x.string(),params:Wet.optional().nullable()}),Rfe=x.object({_meta:x.record(x.unknown()).optional(),cwd:x.string(),mcpServers:x.array(Ffe)}),Pfe=x.object({_meta:x.record(x.unknown()).optional(),cwd:x.string(),mcpServers:x.array(Ffe),sessionId:x.string()}),Nfe=x.object({_meta:x.record(x.unknown()).optional(),prompt:x.array($et),sessionId:x.string()}),Yet=x.object({_meta:x.record(x.unknown()).optional(),exitStatus:Het.optional().nullable(),output:x.string(),truncated:x.boolean()}),Qet=x.union([kM,OM,BM,MM,FM,RM,PM,NM,set]),Ket=x.object({_meta:x.record(x.unknown()).optional(),loadSession:x.boolean().optional(),mcpCapabilities:Pet.optional(),promptCapabilities:Net.optional()}),Jet=x.object({_meta:x.record(x.unknown()).optional(),description:x.string(),input:qet.optional().nullable(),name:x.string()}),Xet=x.object({_meta:x.record(x.unknown()).optional(),fs:Uet.optional(),terminal:x.boolean().optional()}),Zet=x.object({id:x.union([ret,net,iet]),method:x.string(),params:Qet.optional().nullable()}),ett=x.object({_meta:x.record(x.unknown()).optional(),agentCapabilities:Ket.optional(),agentInfo:Tfe.optional().nullable(),authMethods:x.array(Ret).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:xfe.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:Efe.optional().nullable(),title:x.string().optional().nullable(),toolCallId:x.string()}),x.object({_meta:x.record(x.unknown()).optional(),entries:x.array(Let),sessionUpdate:x.literal("plan")}),x.object({_meta:x.record(x.unknown()).optional(),availableCommands:x.array(Jet),sessionUpdate:x.literal("available_commands_update")}),x.object({_meta:x.record(x.unknown()).optional(),currentModeId:x.string(),sessionUpdate:x.literal("current_mode_update")})])}),Bfe=x.object({_meta:x.record(x.unknown()).optional(),clientCapabilities:Xet.optional(),clientInfo:Tfe.optional().nullable(),protocolVersion:x.number()}),ttt=x.union([Eet,wet,Det,Cet,Yet,Aet,Iet,Tet,ket]),rtt=x.union([LM,get]),ntt=x.union([Bfe,Sfe,Rfe,Pfe,Dfe,Nfe,Cfe,xet]),itt=x.object({method:x.string(),params:rtt.optional().nullable()}),stt=x.union([ett,cet,Vet,zet,fet,det,het,pet]),ott=x.object({id:x.union([yet,vet,bet]),method:x.string(),params:ntt.optional().nullable()}),att=x.union([x.object({result:ttt}),x.object({error:wfe})]),utt=x.union([ott,att,Get]),ctt=x.union([x.object({result:stt}),x.object({error:wfe})]),ltt=x.union([Zet,ctt,itt]),DSt=x.union([ltt,utt]);function JA(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)+`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lody",
3
- "version": "0.1.9",
3
+ "version": "0.1.10",
4
4
  "description": "Lody Agent CLI tool for managing remote command execution",
5
5
  "main": "dist/index.js",
6
6
  "bin": {