lody 0.1.11 → 0.1.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +3 -3
- 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 vVe.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(wo))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"?wo[r].ansi16m(...n):e==="ansi256"?wo[r].ansi256(wo.rgbToAnsi256(...n)):wo[r].ansi(wo.rgbToAnsi(...n)):t==="hex"?V6("rgb",e,r,...wo.hexToRgb(...n)):wo[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),wo.color.close,this[wh]);return ub(this,i,this[Wm])}}};let e="bg"+t[0].toUpperCase()+t.slice(1);Sh[e]={get(){let{level:r}=this;return function(...n){let i=z6(V6(t,JL[r],"bgColor",...n),wo.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(),urt=Vm({level:KL?KL.level:0});var it=j0e;var ZL="0.1.
|
|
138
|
+
`);return s!==-1&&(e=YL(e,i,n,s)),n+e+i};Object.defineProperties(Vm.prototype,Sh);var j0e=Vm(),urt=Vm({level:KL?KL.level:0});var it=j0e;var ZL="0.1.12";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:grt,unload:_rt}=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 qs=qe(require("node:process"),1);function iI(){return qs.default.platform!=="win32"?qs.default.env.TERM!=="linux":!!qs.default.env.CI||!!qs.default.env.WT_SESSION||!!qs.default.env.TERMINUS_SUBLIME||qs.default.env.ConEmuTask==="{cmd::Cmder}"||qs.default.env.TERM_PROGRAM==="Terminus-Sublime"||qs.default.env.TERM_PROGRAM==="vscode"||qs.default.env.TERM==="xterm-256color"||qs.default.env.TERM==="alacritty"||qs.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var 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 So=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(){So.default.platform==="win32"||!So.default.stdin.isTTY||(So.default.stdin.setRawMode(!0),So.default.stdin.on("data",this.#o),So.default.stdin.resume())}#t(){So.default.stdin.isTTY&&(So.default.stdin.off("data",this.#o),So.default.stdin.pause(),So.default.stdin.setRawMode(!1))}#o(e){e[0]===ome&&So.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,8 +188,8 @@ 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 vl=qe(h0(),1);NF();var sZ=class{crdtType=On.Loro;doc;config;ctx;localUpdateUnsubscribe;destroyed=!1;initServerVersion;reachServerVersionPromise;hasReachedServerVersion=!1;constructor(t,e={}){this.doc=t||new vl.LoroDoc,this.config=e;{let r,n;this.reachServerVersionPromise={promise:new Promise((i,s)=>{r=i,n=s}),resolve:r,reject:n},this.reachServerVersionPromise.promise.then(()=>{this.hasReachedServerVersion=!0})}}waitForReachingServerVersion(){return this.reachServerVersionPromise.promise}cmpVersion(t){let e=vl.VersionVector.decode(t);return this.doc.version().compare(e)}handleJoinErr;getDoc(){return this.doc}setCtx(t){this.ctx=t,this.localUpdateUnsubscribe=this.doc.subscribeLocalUpdates(e=>{!this.destroyed&&this.ctx&&this.ctx.send([e])})}getVersion(){return this.doc.version().encode()}getAlternativeVersion(t){}async handleJoinOk(t){if(!this.destroyed)try{let e;if(t.version.length>0){try{e=vl.VersionVector.decode(t.version),this.initServerVersion=e}catch{throw new Error("Invalid version format received")}let r=this.doc.version().compare(e);if(r!=null&&r>=0&&this.reachServerVersionPromise.resolve(),r==null||r===1){let n=this.doc.export({mode:"update",from:e});this.ctx?.send([n])}}else{let r=this.doc.export({mode:"snapshot"});this.ctx?.send([r])}}catch(e){throw this.ctx.onJoinFailed(e instanceof Error?e.message:String(e)),e}}applyUpdate(t){if(!(this.destroyed||!t?.length)){try{this.doc.importBatch(t).pending==null}catch(e){this.ctx.onImportError(e instanceof Error?e:new Error(String(e)),t)}if(this.initServerVersion&&!this.hasReachedServerVersion){let e=this.doc.version().compare(this.initServerVersion);e!=null&&e>=0&&this.reachServerVersionPromise.resolve()}}}handleUpdateError(t){this.config.onUpdateError&&this.config.onUpdateError(t)}destroy(){this.destroyed||(this.destroyed=!0,this.localUpdateUnsubscribe&&(this.localUpdateUnsubscribe(),this.localUpdateUnsubscribe=void 0),this.ctx=void 0)}};var oZ=class{crdtType=On.LoroEphemeralStorePersisted;store;ctx;localUpdateUnsubscribe;destroyed=!1;constructor(t){this.store=t||new vl.EphemeralStore}waitForReachingServerVersion(){return Promise.resolve()}cmpVersion(t){return 0}handleJoinErr;getStore(){return this.store}setCtx(t){this.ctx=t,this.localUpdateUnsubscribe=this.store.subscribeLocalUpdates(e=>{!this.destroyed&&this.ctx&&this.ctx.send([e])})}getVersion(){return new Uint8Array}getAlternativeVersion(t){}async handleJoinOk(t){if(!this.destroyed&&this.ctx){let e=this.store.encodeAll();e.length>0&&this.ctx.send([e])}}applyUpdate(t){if(!(this.destroyed||!t?.length)){for(let e of t)if(e?.length>0)try{this.store.apply(e)}catch(r){this.ctx?.onImportError(r instanceof Error?r:new Error(String(r)),[e])}}}destroy(){this.destroyed||(this.destroyed=!0,this.localUpdateUnsubscribe&&(this.localUpdateUnsubscribe(),this.localUpdateUnsubscribe=void 0),this.store.destroy(),this.ctx=void 0)}};var nyt=new TextEncoder,iyt=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())}},syt=new qMe;var oyt=new TextEncoder,ayt=new TextDecoder;var Fu={Connecting:"connecting",Connected:"connected",Disconnected:"disconnected"},aZ=class{constructor(t){this.ops=t,this.status=Fu.Connecting,this.statusListeners=new Set,this.latencyListeners=new Set,this.pendingRooms=new Map,this.activeRooms=new Map,this.preJoinUpdates=new Map,this.fragmentBatches=new Map,this.roomAdaptors=new Map,this.roomIds=new Map,this.roomAuth=new Map,this.socketListeners=new WeakMap,this.pingWaiters=[],this.shouldReconnect=!0,this.reconnectAttempts=0,this.handleOnline=()=>{this.shouldReconnect&&this.status!==Fu.Connected&&(this.clearReconnectTimer(),this.scheduleReconnect(!0))},this.handleOffline=()=>{if(this.clearReconnectTimer(),this.shouldReconnect){this.setStatus(Fu.Disconnected);try{this.ws?.close(1001,"Offline")}catch{}}},this.attachNetworkListeners(),this.ensureConnectedPromise(),this.connect()}get socket(){return this.ws}ensureConnectedPromise(){this.resolveConnected||(this.connectedPromise=new Promise((t,e)=>{this.resolveConnected=()=>{this.resolveConnected=void 0,this.rejectConnected=void 0,t()},this.rejectConnected=r=>{this.resolveConnected=void 0,this.rejectConnected=void 0,e(r)}}))}attachNetworkListeners(){if(this.removeNetworkListeners?.(),this.removeNetworkListeners=void 0,typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("online",this.handleOnline),window.addEventListener("offline",this.handleOffline),this.removeNetworkListeners=()=>{window.removeEventListener("online",this.handleOnline),window.removeEventListener("offline",this.handleOffline)};return}let t=globalThis;if(typeof t.addEventListener=="function"){let r=this.handleOnline,n=this.handleOffline;t.addEventListener("online",r),t.addEventListener("offline",n),this.removeNetworkListeners=()=>{t.removeEventListener?.("online",r),t.removeEventListener?.("offline",n)};return}let e=t.process;if(e&&typeof e.on=="function"){let r=()=>{this.handleOnline()},n=()=>{this.handleOffline()};e.on("online",r),e.on("offline",n),this.removeNetworkListeners=()=>{typeof e.off=="function"?(e.off("online",r),e.off("offline",n)):typeof e.removeListener=="function"&&(e.removeListener("online",r),e.removeListener("offline",n))}}}getStatus(){return this.status}getLatency(){return this.lastLatencyMs}onStatusChange(t){this.statusListeners.add(t);try{t(this.status)}catch{}return()=>this.statusListeners.delete(t)}onLatency(t){if(this.latencyListeners.add(t),this.lastLatencyMs!=null)try{t(this.lastLatencyMs)}catch{}return()=>this.latencyListeners.delete(t)}setStatus(t){if(this.status===t)return;this.status=t;let e=Array.from(this.statusListeners);for(let r of e)try{r(t)}catch{}}async connect(){this.shouldReconnect=!0;let t=this.ws;if(t){let r=t.readyState;if(r===WebSocket.OPEN||r===WebSocket.CONNECTING)return this.connectedPromise}this.clearReconnectTimer(),this.ensureConnectedPromise(),this.setStatus(Fu.Connecting);let e=new WebSocket(this.ops.url);this.ws=e,t&&t!==e&&this.detachSocketListeners(t),this.attachSocketListeners(e);try{e.binaryType="arraybuffer"}catch{}return this.connectedPromise}attachSocketListeners(t){let e=()=>{this.onSocketOpen(t)},r=s=>{this.onSocketError(t,s)},n=s=>{this.onSocketClose(t,s)},i=s=>{this.onSocketMessage(t,s)};t.addEventListener("open",e),t.addEventListener("error",r),t.addEventListener("close",n),t.addEventListener("message",i),this.socketListeners.set(t,{open:e,error:r,close:n,message:i})}onSocketOpen(t){if(t!==this.ws){this.detachSocketListeners(t);try{t.close(1e3,"Superseded")}catch{}return}this.clearReconnectTimer(),this.reconnectAttempts=0,this.setStatus(Fu.Connected),this.startPingTimer(),this.resolveConnected?.(),this.rejoinActiveRooms()}onSocketError(t,e){t!==this.ws&&this.detachSocketListeners(t)}onSocketClose(t,e){let r=t===this.ws;if(this.detachSocketListeners(t),!r)return;let n=e?.code;n!=null&&n>=4400&&n<4500&&(this.shouldReconnect=!1);let i=e?.reason;if((i==="permission_changed"||i==="room_closed")&&(this.shouldReconnect=!1),this.clearPingTimer(),this.fragmentBatches.size){for(let[,s]of this.fragmentBatches)try{clearTimeout(s.timeoutId)}catch{}this.fragmentBatches.clear()}if(this.awaitingPongSince=void 0,this.ops.onWsClose?.(),this.rejectAllPingWaiters(new Error("WebSocket closed")),!this.shouldReconnect){this.setStatus(Fu.Disconnected),this.rejectConnected?.(new Error("Disconnected"));return}this.setStatus(Fu.Disconnected),this.scheduleReconnect()}async onSocketMessage(t,e){if(t!==this.ws)return;if(typeof e.data=="string"){if(e.data==="ping"){try{t.send("pong")}catch{}return}if(e.data==="pong"){this.handlePong();return}return}let r=VX(new Uint8Array(e.data));r!=null&&await this.handleMessage(r)}scheduleReconnect(t=!1){if(this.reconnectTimer)return;let e=++this.reconnectAttempts,r=t?0:Math.min(15e3,500*2**(e-1));this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},r)}clearReconnectTimer(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}rejoinActiveRooms(){for(let[t,e]of this.roomAdaptors){let r=this.roomIds.get(t);if(!r)continue;let n=this.activeRooms.get(t);if(!n)continue;let i={room:Promise.resolve(n.room),resolve:s=>{e.handleJoinOk(s).catch(o=>{console.error(o)}),this.pendingRooms.delete(t)},reject:s=>{console.error("Rejoin failed:",s)},adaptor:e,roomId:r,auth:this.roomAuth.get(t)};this.pendingRooms.set(t,i);try{this.ws.send(Xs({type:Rt.JoinRequest,crdt:e.crdtType,roomId:r,auth:i.auth??new Uint8Array,version:e.getVersion()}))}catch(s){console.error("Failed to send rejoin request:",s)}}}async handleMessage(t){let e=typeof t.roomId=="string"?t.roomId:new TextDecoder().decode(t.roomId),r=t.crdt+e;switch(t.type){case Rt.JoinRequest:throw new Error("JoinRequest should not be received by client");case Rt.JoinResponseOk:{let n=this.pendingRooms.get(r);n&&n.resolve(t);break}case Rt.JoinError:{let n=this.pendingRooms.get(r);n&&await this.handleJoinError(t,n,r);break}case Rt.DocUpdate:{let n=this.activeRooms.get(r);if(n)n.handler.handleDocUpdate(t.updates);else{let i=this.pendingRooms.get(r);if(i&&i.adaptor.crdtType===On.Elo){let s=this.preJoinUpdates.get(r)??[];s.push(...t.updates),this.preJoinUpdates.set(r,s)}}break}case Rt.DocUpdateFragmentHeader:this.handleFragmentHeader(t);break;case Rt.DocUpdateFragment:this.handleFragment(t);break;case Rt.UpdateError:{let n=this.activeRooms.get(r);if(n)n.handler.handleUpdateError(t);else{let i=typeof t.roomId=="string"?t.roomId:new TextDecoder().decode(t.roomId);console.error(`Update error for room ${i}: ${t.code} - ${t.message}`)}break}}}handleFragmentHeader(t){let e=typeof t.roomId=="string"?t.roomId:new TextDecoder().decode(t.roomId),r=`${t.crdt}-${e}-${t.batchId}`,n=this.fragmentBatches.get(r);n&&clearTimeout(n.timeoutId);let i=setTimeout(()=>{this.fragmentBatches.delete(r);try{this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(Xs({type:Rt.UpdateError,crdt:t.crdt,roomId:t.roomId,code:Ei.FragmentTimeout,message:`Fragment reassembly timeout for batch ${t.batchId}`}))}catch{}},1e4);this.fragmentBatches.set(r,{header:t,fragments:new Map,timeoutId:i})}handleFragment(t){let e=typeof t.roomId=="string"?t.roomId:new TextDecoder().decode(t.roomId),r=`${t.crdt}-${e}-${t.batchId}`,n=this.fragmentBatches.get(r);if(!n){console.error(`Received fragment for unknown batch ${t.batchId}`);return}if(n.fragments.set(t.index,t.fragment),n.fragments.size===n.header.fragmentCount){clearTimeout(n.timeoutId),this.fragmentBatches.delete(r);let i=new Uint8Array(n.header.totalSizeBytes),s=0;for(let u=0;u<n.header.fragmentCount;u++){let c=n.fragments.get(u);if(!c){console.error(`Missing fragment ${u} in batch ${t.batchId}`);return}i.set(c,s),s+=c.length}let o=t.crdt+e,a=this.activeRooms.get(o);if(a)a.handler.handleDocUpdate([i]);else{let u=this.pendingRooms.get(o);if(u&&u.adaptor.crdtType===On.Elo){let c=this.preJoinUpdates.get(o)??[];c.push(i),this.preJoinUpdates.set(o,c)}}}}registerActiveRoom(t,e,r,n,i){let s=e+t;this.activeRooms.set(s,{room:r,handler:n}),this.roomAdaptors.set(s,i),this.roomIds.set(s,t);let o=this.preJoinUpdates.get(s);if(o&&o.length)try{n.handleDocUpdate(o)}finally{this.preJoinUpdates.delete(s)}this.pendingRooms.delete(s)}async handleJoinError(t,e,r){if(await e.adaptor.handleJoinErr?.(t),t.code===Js.VersionUnknown){let n=e.adaptor.getVersion(),i=e.adaptor.getAlternativeVersion?.(n);if(i){this.ws.send(Xs({type:Rt.JoinRequest,crdt:e.adaptor.crdtType,roomId:e.roomId,auth:e.auth??new Uint8Array,version:i}));return}else{console.warn("Version unknown. Now join with an empty version"),this.ws.send(Xs({type:Rt.JoinRequest,crdt:e.adaptor.crdtType,roomId:e.roomId,auth:e.auth??new Uint8Array,version:new Uint8Array}));return}}e.reject(new Error(`Join failed: ${t.code} - ${t.message}`)),this.pendingRooms.delete(r)}cleanupRoom(t,e){let r=e+t;this.activeRooms.delete(r),this.pendingRooms.delete(r),this.roomAdaptors.delete(r),this.roomIds.delete(r),this.roomAuth.delete(r)}waitConnected(){return this.connectedPromise}async ping(t=5e3){if(await this.connectedPromise,!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not open");return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("Ping timeout"))},Math.max(1,t)),i={resolve:()=>{clearTimeout(n),e()},reject:s=>{clearTimeout(n),r(s)},timeoutId:n};this.pingWaiters.push(i);try{this.awaitingPongSince==null&&(this.awaitingPongSince=Date.now()),this.ws.send("ping")}catch(s){this.pingWaiters.pop(),clearTimeout(n),r(s instanceof Error?s:new Error(String(s)))}})}join({roomId:t,crdtAdaptor:e,auth:r}){let n=e.crdtType+t,i=this.pendingRooms.get(n);if(i)return i.room;let s=this.activeRooms.get(n);if(s)return Promise.resolve(s.room);let o,a,u=new Promise((c,l)=>{o=c,a=l}).then(c=>{e.setCtx({send:d=>{for(let p of d)this.sendUpdateOrFragments(e.crdtType,t,p)},onJoinFailed:d=>{console.error(`Join failed: ${d}`),this.ws.send(Xs({type:Rt.JoinError,crdt:e.crdtType,roomId:t,code:Js.AppError,message:d})),a(new Error(`Join failed: ${d}`))},onImportError:(d,p)=>{console.error(`Import error: ${d.message}`,p),this.ws.send(Xs({type:Rt.UpdateError,crdt:e.crdtType,roomId:t,code:Ei.AppError,message:d.message}))}});let{room:l,handler:f}=WMe({client:this,roomId:t,crdtType:e.crdtType,crdtAdaptor:e});return this.registerActiveRoom(t,e.crdtType,l,f,e),e.handleJoinOk(c).catch(d=>{console.error(d)}),l});return this.pendingRooms.set(n,{room:u,resolve:o,reject:a,adaptor:e,roomId:t,auth:r}),this.roomAuth.set(n,r),this.ws.send(Xs({type:Rt.JoinRequest,crdt:e.crdtType,roomId:t,auth:r??new Uint8Array,version:e.getVersion()})),u}close(){if(this.shouldReconnect=!1,this.clearReconnectTimer(),this.clearPingTimer(),this.reconnectAttempts=0,this.rejectConnected?.(new Error("Disconnected")),this.rejectConnected=void 0,this.resolveConnected=void 0,this.rejectAllPingWaiters(new Error("Disconnected")),this.fragmentBatches.size){for(let[,e]of this.fragmentBatches)try{clearTimeout(e.timeoutId)}catch{}this.fragmentBatches.clear()}this.awaitingPongSince=void 0;let t=this.ws;t&&this.socketListeners.has(t)&&this.ops.onWsClose?.(),this.detachSocketListeners(t),this.flushAndCloseWebSocket(t,{code:1e3,reason:"Client closed"}),this.setStatus(Fu.Disconnected)}sendUpdateOrFragments(t,e,r){let n=this.ws;if(!n||n.readyState!==WebSocket.OPEN)return;let i=Math.max(1,Math.min(240*1024,258048));if(r.length<=i){n.send(Xs({type:Rt.DocUpdate,crdt:t,roomId:e,updates:[r]}));return}let s=Math.ceil(r.length/i),o=new Uint8Array(8);crypto.getRandomValues(o);let a=C_(o),u={type:Rt.DocUpdateFragmentHeader,crdt:t,roomId:e,batchId:a,fragmentCount:s,totalSizeBytes:r.length};n.send(Xs(u));for(let c=0;c<s;c++){let l=c*i,f=Math.min(l+i,r.length),d=r.subarray(l,f),p={type:Rt.DocUpdateFragment,crdt:t,roomId:e,batchId:a,index:c,fragment:d};n.send(Xs(p))}}sendLeave(t,e){!this.ws||this.ws.readyState!==WebSocket.OPEN||this.ws.send(Xs({type:Rt.Leave,crdt:t,roomId:e}))}destroy(){if(this.shouldReconnect=!1,this.clearReconnectTimer(),this.clearPingTimer(),this.reconnectAttempts=0,this.rejectConnected?.(new Error("Destroyed")),this.rejectConnected=void 0,this.resolveConnected=void 0,this.rejectAllPingWaiters(new Error("Destroyed")),this.fragmentBatches.size){for(let[,e]of this.fragmentBatches)try{clearTimeout(e.timeoutId)}catch{}this.fragmentBatches.clear()}this.awaitingPongSince=void 0;let t=this.ws;t&&this.socketListeners.has(t)&&this.ops.onWsClose?.(),this.detachSocketListeners(t);try{this.removeNetworkListeners?.()}catch{}this.removeNetworkListeners=void 0;try{this.flushAndCloseWebSocket(t,{code:1e3,reason:"Client destroyed"})}catch{}this.setStatus(Fu.Disconnected)}flushAndCloseWebSocket(t,e){if(!t)return;let{code:r,reason:n,timeoutMs:i=2e3}=e??{},s=()=>{let c=Reflect.get(t,"bufferedAmount");return typeof c=="number"?c:void 0};if(s()==null){try{t.close(r,n)}catch{}return}let o=Date.now(),a=!1,u=()=>{if(a)return;let c=t.readyState;if(c===WebSocket.CLOSED||c===WebSocket.CLOSING){a=!0;try{t.close(r,n)}catch{}return}let l=s();if(l==null||l<=0||Date.now()-o>=i){a=!0;try{t.close(r,n)}catch{}return}setTimeout(u,25)};u()}detachSocketListeners(t){if(!t)return;let e=this.socketListeners.get(t);if(e){try{t.removeEventListener?.("open",e.open),t.removeEventListener?.("error",e.error),t.removeEventListener?.("close",e.close),t.removeEventListener?.("message",e.message)}catch{}this.socketListeners.delete(t)}}startPingTimer(){let t=HMe(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{}}}},jMe=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 $Me(t){return typeof t=="number"&&isFinite(t)&&t>0}function HMe(t){if(t.disablePing)return;let e=t.pingIntervalMs;return $Me(e)?e:3e4}function WMe(t){let e=new jMe(t);return{room:e,handler:e}}var zee=qe(h0());var iR={};nb(iR,{createValueFromSchema:()=>GMe,getDefaultValue:()=>P_,isContainerSchema:()=>Bu,isListLikeSchema:()=>rR,isLoroListSchema:()=>Pu,isLoroMapSchema:()=>Ru,isLoroMovableListSchema:()=>Nu,isLoroTextSchema:()=>nR,isLoroTreeSchema:()=>no,isRootSchemaType:()=>N_,schema:()=>Ee,validateSchema:()=>fd});var Mn="$cid";function ro(t,e){!Sn(t)||Object.prototype.hasOwnProperty.call(t,Mn)||Object.defineProperty(t,Mn,{value:e})}function Sn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date)&&!(t instanceof RegExp)&&typeof t!="function"}function Fa(t,e){if(t===e)return!0;if(t===null||e===null||typeof t!="object"&&typeof t!="function"||typeof e!="object"&&typeof e!="function")return!1;if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(!Fa(t[r],e[r]))return!1;return!0}if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(t instanceof RegExp&&e instanceof RegExp)return t.toString()===e.toString();if(!Array.isArray(t)&&!Array.isArray(e)){let r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(let i of r)if(!Object.prototype.hasOwnProperty.call(e,i)||!Fa(t[i],e[i]))return!1;return!0}return!1}function uZ(t){return t.split(":")[2]}function F_(t,e,r){if(r==="Text")return t.getText(e);if(r==="List")return t.getList(e);if(r==="MovableList")return t.getMovableList(e);if(r==="Map")return t.getMap(e);if(r==="Tree")return t.getTree(e);throw new Error}function ZF(t,e,r){return Sn(r)?{container:t,key:e,value:r,kind:"insert-container",childContainerType:"Map"}:Array.isArray(r)?{container:t,key:e,value:r,kind:"insert-container",childContainerType:"List"}:{container:t,key:e,value:r,kind:"insert"}}function bl(t,e,r){if(!e||t.kind!=="insert"&&t.kind!=="set")return t;let n=r?xl(r)??El(t.value):void 0;return n==null?t:t.kind==="insert"?{container:t.container,key:t.key,value:t.value,kind:"insert-container",childContainerType:n}:t.kind==="set"?{container:t.container,key:t.key,value:t.value,kind:"set-container",childContainerType:n}:t}function xl(t){let e=t.getContainerType();return e===null?void 0:e}function El(t,e){if(Sn(t))return"Map";if(Array.isArray(t))return e?.defaultMovableList?"MovableList":"List";if(typeof t=="string")return e?.defaultLoroText?"Text":void 0}function Ra(t,e){switch(t){case"MovableList":case"List":return typeof e=="object"&&Array.isArray(e);case"Map":return typeof e=="object"&&e!==null;case"Text":return typeof e=="string"&&e!==null;case"Tree":return typeof e=="object"&&Array.isArray(e);default:return!1}}function cZ(t,e){if(Sn(t))return"loro-map";if(Array.isArray(t))return e?.defaultMovableList?"loro-movable-list":"loro-list";if(typeof t=="string"){if(e?.defaultLoroText)return"loro-text"}else return}function 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 VMe(t,e){return fZ(e)?tR.get(e)?.has(t)??!1:!1}function zMe(t,e){if(!fZ(e))return;let r=tR.get(e);r||(r=new WeakSet,tR.set(e,r)),r.add(t)}function Ru(t){return t.type==="loro-map"}function Pu(t){return t.type==="loro-list"}function rR(t){return Pu(t)||Nu(t)}function Nu(t){return t.type==="loro-movable-list"}function N_(t){return t.type==="schema"}function nR(t){return t.type==="loro-text"}function no(t){return t.type==="loro-tree"}function Bu(t){return!!t&&(t.type==="loro-map"||t.type==="loro-list"||t.type==="loro-text"||t.type==="loro-movable-list"||t.type==="loro-tree")}function fd(t,e){let r=[];if(t.options.required&&e==null)return r.push("Value is required"),{valid:!1,errors:r};if(e==null)return{valid:!0};if(VMe(t,e))return{valid:!0};switch(t.type){case"string":typeof e!="string"&&r.push("Value must be a string");break;case"number":typeof e!="number"&&r.push("Value must be a number");break;case"boolean":typeof e!="boolean"&&r.push("Value must be a boolean");break;case"ignore":break;case"loro-text":typeof e!="string"&&r.push("Content must be a string");break;case"loro-map":if(!Sn(e))r.push("Value must be an object");else if(Ru(t)){for(let n in t.definition)if(Object.prototype.hasOwnProperty.call(t.definition,n)){let i=t.definition[n],s=e[n],o=fd(i,s);if(!o.valid&&o.errors){let a=o.errors.map(u=>`${n}: ${u}`);r.push(...a)}}}break;case"loro-movable-list":case"loro-list":if(!Array.isArray(e))r.push("Value must be an array");else if(Pu(t)||Nu(t)){let n=t.itemSchema;e.forEach((i,s)=>{let o=fd(n,i);if(!o.valid&&o.errors){let a=o.errors.map(u=>`Item ${s}: ${u}`);r.push(...a)}})}break;case"loro-tree":{if(!Array.isArray(e)){r.push("Value must be an array of tree nodes");break}if(!no(t)){r.push("Invalid tree schema");break}let n=(i,s)=>{if(!Sn(i)){r.push(`${s}: Node must be an object`);return}let o=i;o.id!=null&&typeof o.id!="string"&&r.push(`${s}: id must be a string if provided`);let a=fd(t.nodeSchema,o.data);!a.valid&&a.errors&&r.push(...a.errors.map(u=>`${s}.data: ${u}`)),Array.isArray(o.children)?o.children.forEach((u,c)=>{n(u,`${s}.children[${c}]`)}):r.push(`${s}: children must be an array`)};e.forEach((i,s)=>{n(i,`node[${s}]`)});break}case"schema":if(!Sn(e))r.push("Value must be an object");else if(N_(t))if(!Sn(e))r.push("Value must be an object");else{for(let n in t.definition)if(Object.prototype.hasOwnProperty.call(t.definition,n)){let i=t.definition[n],s=e[n],o=fd(i,s);if(!o.valid&&o.errors){let a=o.errors.map(u=>`${n}: ${u}`);r.push(...a)}}for(let n in e)Object.prototype.hasOwnProperty.call(t.definition,n)||r.push(`Unknown property: ${n}`)}else r.push(`Should be a schema, but got ${t.type}`);break;default:r.push(`Unknown schema type: ${t.type}`)}if(t.options.validate&&typeof t.options.validate=="function")try{let n=t.options.validate(e);if(n!==!0){let i=typeof n=="string"?n:"Value failed custom validation";r.push(i)}}catch(n){r.push(`Validation error: ${String(n)}`)}return r.length===0?(zMe(t,e),{valid:!0}):{valid:!1,errors:r}}function P_(t){if("defaultValue"in t.options)return t.options.defaultValue;switch(t.type){case"string":{let r=t.options.required?"":void 0;return r===void 0?void 0:r}case"number":{let r=t.options.required?0:void 0;return r===void 0?void 0:r}case"boolean":{let r=t.options.required?!1:void 0;return r===void 0?void 0:r}case"loro-text":{let r=t.options.required?"":void 0;return r===void 0?void 0:r}case"loro-map":{if(Ru(t)){let r={};for(let n in t.definition)if(Object.prototype.hasOwnProperty.call(t.definition,n)){let i=P_(t.definition[n]);i!==void 0&&(r[n]=i)}return r}return{}}case"loro-list":return[];case"loro-tree":{let r=t.options.required?[]:void 0;return r===void 0?void 0:r}case"schema":{if(N_(t)){let r={};for(let n in t.definition)if(Object.prototype.hasOwnProperty.call(t.definition,n)){let i=P_(t.definition[n]);i!==void 0&&(r[n]=i)}return r}return{}}default:return}}function GMe(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"),Cs=Symbol.for("immer-state"),YMe=process.env.NODE_ENV!=="production"?[function(t){return`The plugin for '${t}' has not been loaded into Immer. To enable the plugin, import and call \`enable${t}()\` when initializing your application.`},function(t){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${t}'`},"This object has been frozen and should not be mutated",function(t){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+t},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(t){return`'current' expects a draft, got: ${t}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(t){return`'original' expects a draft, got: ${t}`}]:[];function ts(t,...e){if(process.env.NODE_ENV!=="production"){let r=YMe[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[Cs]}function hd(t){return t?yZ(t)||Array.isArray(t)||!!t[dZ]||!!t.constructor?.[dZ]||L_(t)||r2(t):!1}var QMe=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)===QMe}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[Cs];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 KMe(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[Cs];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(){ts(2)}function n2(t){return Object.isFrozen(t)}var JMe={};function pd(t){let e=JMe[t];return e||ts(0,t),e}var B_;function bZ(){return B_}function XMe(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(ZMe),t.drafts_=null}function lR(t){t===B_&&(B_=t.parent_)}function pZ(t){return B_=XMe(B_,t)}function ZMe(t){let e=t[Cs];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[Cs].modified_&&(cR(e),ts(4)),hd(t)&&(t=ZS(e,t),e.parent_||e2(e,t)),e.patches_&&pd("Patches").generateReplacementPatches_(r[Cs].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[Cs];if(!n)return XS(e,(i,s)=>gZ(t,n,e,i,s,r)),e;if(n.scope_!==t)return e;if(!n.modified_)return e2(t,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let i=n.copy_,s=i,o=!1;n.type_===3&&(s=new Set(i),i.clear(),o=!0),XS(s,(a,u)=>gZ(t,n,i,a,u,r,o)),e2(t,i,!1),r&&t.patches_&&pd("Patches").generatePatches_(n,r,t.patches_,t.inversePatches_)}return n.copy_}function gZ(t,e,r,n,i,s,o){if(process.env.NODE_ENV!=="production"&&i===r&&ts(5),m0(i)){let a=s&&e&&e.type_!==3&&!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 eLe(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===Cs)return t;let r=dd(t);if(!aR(r,e))return tLe(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?.[Cs];if(s&&s.base_===r)return t.copy_[e]=r,t.assigned_[e]=!1,!0;if(KMe(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(){ts(11)},getPrototypeOf(t){return p0(t.base_)},setPrototypeOf(){ts(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))&&ts(13),M_.set.call(this,t,e,void 0)};M_.set=function(t,e,r){return process.env.NODE_ENV!=="production"&&e!=="length"&&isNaN(parseInt(e))&&ts(14),mR.set.call(this,t[0],e,r,t[0])};function sR(t,e){let r=t[Cs];return(r?dd(r):t)[e]}function tLe(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 rLe=class{constructor(t){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,r,n)=>{if(typeof e=="function"&&typeof r!="function"){let s=r;r=e;let o=this;return function(u=s,...c){return o.produce(u,l=>r.call(this,l,...c))}}typeof r!="function"&&ts(6),n!==void 0&&typeof n!="function"&&ts(7);let i;if(hd(e)){let s=pZ(this),o=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 ts(1,e)},this.produceWithPatches=(e,r)=>{if(typeof e=="function")return(o,...a)=>this.produceWithPatches(o,u=>e(u,...a));let n,i;return[this.produce(e,r,(o,a)=>{n=o,i=a}),n,i]},typeof t?.autoFreeze=="boolean"&&this.setAutoFreeze(t.autoFreeze),typeof t?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(t.useStrictShallowCopy)}createDraft(t){hd(t)||ts(8),m0(t)&&(t=nLe(t));let e=pZ(this),r=dR(t,void 0);return r[Cs].isManual_=!0,lR(e),r}finishDraft(t,e){let r=t&&t[Cs];(!r||!r.isManual_)&&ts(9);let{scope_:n}=r;return hZ(n,e),mZ(void 0,n)}setAutoFreeze(t){this.autoFreeze_=t}setUseStrictShallowCopy(t){this.useStrictShallowCopy_=t}applyPatches(t,e){let r;for(r=e.length-1;r>=0;r--){let i=e[r];if(i.path.length===0&&i.op==="replace"){t=i.value;break}}r>-1&&(e=e.slice(r+1));let n=pd("Patches").applyPatches_;return m0(t)?n(t,e):this.produce(t,i=>n(i,e))}};function dR(t,e){let r=L_(t)?pd("MapSet").proxyMap_(t,e):r2(t)?pd("MapSet").proxySet_(t,e):eLe(t,e);return(e?e.scope_:bZ()).drafts_.push(r),r}function nLe(t){return m0(t)||ts(10,t),EZ(t)}function EZ(t){if(!hd(t)||n2(t))return t;let e=t[Cs],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 rLe,q_=hR.produce;var wZ=hR.setAutoFreeze.bind(hR);var Ln=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)iLe(s,a,o,n.getContainerById,n.containerToJson,n.nodeDataWithCid,n.getNodeDataCid)})(t)}function iLe(t,e,r,n,i,s,o){if(hLe(e.target,r,n))return;let{parent:a,key:u,node:c}=sLe(t,e.path),l=c;if(l===void 0)if(e.diff.type==="map")a&&u!==void 0&&Pa(a,u,{}),l=a&&u!==void 0?wl(a,u):t;else if(e.diff.type==="list")a&&u!==void 0&&Pa(a,u,[]),l=a&&u!==void 0?wl(a,u):t;else if(e.diff.type==="text")a&&u!==void 0&&Pa(a,u,""),l=a&&u!==void 0?wl(a,u):t;else if(e.diff.type==="tree")a&&u!==void 0&&Pa(a,u,[]),l=a&&u!==void 0?wl(a,u):t;else if(e.diff.type==="counter")a&&u!==void 0&&Pa(a,u,0),l=a&&u!==void 0?wl(a,u):t;else{console.error("Unknown diff type:",e.diff);return}switch(e.diff.type){case"map":md(l)||(a&&u!==void 0&&Pa(a,u,{}),l=a&&u!==void 0?wl(a,u):t),md(l)&&uLe(l,e.diff.updated,r,i);break;case"list":U_(l)||(a&&u!==void 0&&Pa(a,u,[]),l=a&&u!==void 0?wl(a,u):[]),U_(l)&&cLe(l,e.diff.diff,r,i);break;case"text":{let d=dLe(typeof l=="string"?l:"",e.diff.diff);a&&u!==void 0&&Pa(a,u,d);break}case"tree":U_(l)||(a&&u!==void 0&&Pa(a,u,[]),l=a&&u!==void 0?wl(a,u):[]),U_(l)&&(lLe(l,e.diff.diff,e.target,s,o),s2.delete(l));break;case"counter":if(a&&u!==void 0){let d=(typeof l=="number"?l:0)+(e.diff.increment??0);Pa(a,u,d)}break}}function sLe(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=oLe(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 oLe(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 aLe(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 uLe(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 cLe(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 lLe(t,e,r,n,i){let s=o=>{if(!o)return t;let a=fLe(t,o);return a?a.node.children:t};for(let o of e)if(o.action==="create"){let a=s(o.parent),u={id:o.target,data:{},children:[]};if(r&&n?.(r)){let l=i?.(r,o.target);l&&ro(u.data,l)}let c=i2(o.index,a.length+1);a.splice(c,0,u)}else if(o.action==="delete"){let a=s(o.oldParent);if(!a)continue;let u=i2(o.oldIndex,a.length);if(u>=0&&u<a.length)a.splice(u,1);else{let c=a.findIndex(l=>l.id===o.target);c>=0&&a.splice(c,1)}}else if(o.action==="move"){let a=s(o.oldParent),u=i2(o.oldIndex,a.length),c;if(u>=0&&u<a.length)c=a.splice(u,1)[0];else{let d=a.findIndex(p=>p.id===o.target);d>=0&&(c=a.splice(d,1)[0])}if(!c)continue;let l=s(o.parent),f=i2(o.index,l.length+1);l.splice(f,0,c)}}function i2(t,e){return t<0?0:t>e?e:t}function fLe(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 dLe(t,e){if(e.length===0)return t;let r=t,n="",i=0;for(let s of e)s.retain!==void 0?(n+=r.slice(i,i+s.retain),i+=s.retain):s.delete!==void 0?i+=s.delete:s.insert!==void 0&&(n+=s.insert??"");return i<r.length&&(n+=r.slice(i)),n}function Pa(t,e,r){(Array.isArray(t)&&typeof e=="number"||!Array.isArray(t)&&typeof e=="string")&&(t[e]=r)}function wl(t,e){if(Array.isArray(t)&&typeof e=="number")return t[e];if(!Array.isArray(t)&&typeof e=="string")return t[e]}var s2=new WeakMap;function IZ(t){let e=t.kind();if(e==="Counter")return t.getShallowValue();if(e==="Tree"){let r=t.toJSON();return aLe(r)}return t.toJSON()}function hLe(t,e,r){if(e.has(t))return!0;if(!r)return!1;let i=r(t);for(;i;){let s=i.parent();if(!s)break;if(e.has(s.id))return!0;i=s}return!1}var j_=qe(h0(),1);function TZ(t,e){if(t){if(t.type==="schema")return t.definition[e];if(t.type==="loro-map"){if(Object.prototype.hasOwnProperty.call(t.definition,e))return t.definition[e];let r=t;if(r.catchallType)return r.catchallType}}}function Sl(t,e,r,n,i,s){let o={oldState:e,newState:r,schema:i};if(n===""){if(!ld(o,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,Ru))throw console.log("stateAndSchema:",o),new Error("Failed to diff container(map). Old and new state must be objects");u=kZ(t,o.oldState,o.newState,n,o.schema,s);break;case"List":if(!ld(o,KS,Pu))throw new Error("Failed to diff container(list). Old and new state must be arrays");c=o.schema?.idSelector,c?u=gLe(t,o.oldState,o.newState,n,o.schema,c,s):u=_Le(t,e,r,n,i,s);break;case"MovableList":if(!ld(o,KS,Nu))throw new Error("Failed to diff container(movable list). Old and new state must be arrays");if(c=o.schema?.idSelector,!c)throw new Error("Movable list schema must have an idSelector");u=mLe(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=pLe(o.oldState,o.newState,n);break;case"Tree":if(!ld(o,KS,no))throw new Error("Failed to diff container(tree). Old and new state must be arrays");u=_R(t,o.oldState,o.newState,n,o.schema,s);break;default:throw new Error(`Unsupported container type: ${a}`)}return u}function pLe(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"&&!(Mn in $)&&ro($,k.data.id);let O=Sl(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 mLe(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(!Fa(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(bl({container:n,key:m,value:_,kind:"insert"},!0,i?.itemSchema))}for(let m of l){if(Fa(m.oldItem,m.newItem))continue;let v=t.getMovableList(n).get(m.oldIndex);if((0,j_.isContainer)(v)){let w=Sl(t,m.oldItem,m.newItem,v.id,i?.itemSchema,o);a.push(...w)}else a.push(bl({container:n,key:m.newIndex,value:m.newItem,kind:"set"},!0,i?.itemSchema))}return a}function gLe(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(...Sl(t,_,v,F.id,i?.itemSchema,o)):Fa(_,v)||(a.push({container:n,key:m+p,value:void 0,kind:"delete"}),a.push(bl({container:n,key:m+p,value:v,kind:"insert"},u,i?.itemSchema))),m++,d++;continue}if(A&&!c.has(A)){a.push(bl({container:n,key:m+p,value:v,kind:"insert"},u,i?.itemSchema)),p++,d++;continue}a.push({container:n,key:m+p,value:void 0,kind:"delete"}),p--,m++}for(;d<r.length;d++){let _=r[d];a.push(bl({container:n,key:m+p,value:_,kind:"insert"},u,i?.itemSchema)),p++}return a}function _Le(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=Sl(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(bl({container:n,key:v,value:r[v],kind:"insert"},!0,i?.itemSchema))}for(let _=0;_<d-m;_++)o.push({container:n,key:l+m,value:void 0,kind:"delete"});for(let _=0;_<p-m;_++){let v=l+m+_;o.push(bl({container:n,key:v,value:r[v],kind:"insert"},!0,i?.itemSchema))}return o}function kZ(t,e,r,n,i,s){let o=[],a=e,u=r;for(let c in a){if(c===Mn)continue;let l=TZ(i,c);l&&l.type==="ignore"||c in u||o.push({container:n,key:c,value:void 0,kind:"delete"})}for(let c in u){if(c===Mn)continue;let l=a[c],f=u[c],d=TZ(i,c);if(d&&d.type==="ignore")continue;let p=d?.getContainerType()??El(f,s);if(d?.getContainerType()&&p&&!Ra(p,f)&&(console.warn(`Schema mismatch on key "${c}": expected ${d.getContainerType()} but got value ${JSON.stringify(f)}. Falling back to value-based inference to avoid divergence.`),p=El(f,s)),!(c in a)){p&&Ra(p,f)?o.push({container:n,key:c,value:f,kind:"insert-container",childContainerType:p}):o.push({container:n,key:c,value:f,kind:"insert"});continue}if(l!==f)if(p&&Ra(p,f)&&Ra(p,l)){if(n===""){let w=F_(t,c,p);p==="Map"&&f&&typeof f=="object"&&!(Mn in f)&&ro(f,w.id),o.push(...Sl(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"&&!(Mn in f)&&ro(f,v.id),o.push(...Sl(t,a[c],u[c],v.id,d,s)))}else o.push(ZF(n,c,u[c]))}return o}wZ(!1);function yLe(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&&no(c))},getNodeDataCid:(u,c)=>{try{let l=this.doc.getTree(u).getNodeByID(c);return l?l.data.id:void 0}catch{return}}}),this.notifySubscribers(gd.FROM_LORO)}finally{this.registerContainersFromLoroEvent(o),this.syncing=!1}}},this.doc=e.doc,this.schema=e.schema,this.options={doc:e.doc,schema:e.schema,initialState:e.initialState||{},validateUpdates:e.validateUpdates!==!1,throwOnValidationError:e.throwOnValidationError||!1,debug:e.debug||!1,checkStateConsistency:e.checkStateConsistency||!1,inferOptions:e.inferOptions||{}},this.ensureRootContainersFromInitialState();let r={},n=this.schema?P_(this.schema):void 0;n&&typeof n=="object"&&Object.assign(r,n);let i=this.buildRootStateSnapshot();i&&typeof i=="object"&&Object.assign(r,i);let s=this.options.initialState||{};if(this.schema&&this.schema.type==="schema")FZ(r,s,this.schema);else{let o=vLe(s);for(let[a,u]of Object.entries(o))a in r||(r[a]=u)}this.state=r,this.initializeContainers(),this.subscriptions.push(this.doc.subscribe(this.handleLoroEvent))}ensureRootContainersFromInitialState(){let e=this.options?.initialState||{};for(let[r,n]of Object.entries(e)){let i=null;Array.isArray(n)?i=this.doc.getList(r):typeof n=="string"?i=this.doc.getText(r):Sn(n)&&(i=this.doc.getMap(r)),i&&(this.rootPathById.set(i.id,[r]),this.registerContainerWithRegistry(i.id,void 0))}}initializeContainers(){if(this.schema&&this.schema.type!=="schema")throw new Error('Root schema must be of type "schema"');if(this.schema){for(let n in this.schema.definition)if(Object.prototype.hasOwnProperty.call(this.schema.definition,n)){let i=this.schema.definition[n];if(["loro-map","loro-list","loro-text","loro-movable-list","loro-tree"].includes(i.type)){let s=xl(i);if(!s)continue;let o=F_(this.doc,n,s);this.rootPathById.set(o.id,[n]),this.registerContainer(o.id,i)}}}let e=this.buildRootStateSnapshot(),r=q_(n=>{Object.assign(n,e)})(this.state);this.state=r}registerContainer(e,r){try{let n=this.doc.getContainerById(e);if(!n){this.options.debug&&console.warn(`registerContainer: container not found for id ${e}`);return}let i=n.id,s=this.containerRegistry.get(i);if(s){!s.schema&&r&&(s.schema=r);return}this.registerContainerWithRegistry(i,r),this.registerNestedContainers(n)}catch(n){this.options.debug&&console.error(`Error registering container: ${e}`,n)}}registerNestedContainers(e){if(!e.isAttached)return;let r=this.getContainerSchema(e.id);try{if(e.kind()==="Map"){let n=e;for(let i of n.keys()){let s=n.get(i);if((0,Ln.isContainer)(s)){let o;if(r&&Ru(r)){let a=this.getSchemaForMapKey(r,i);a&&Bu(a)&&(o=a)}this.registerContainer(s.id,o)}}}else if(e.kind()==="List"||e.kind()==="MovableList"){let n=e,i=n.length;for(let s=0;s<i;s++){let o=n.get(s);if((0,Ln.isContainer)(o)){let a;r&&(Pu(r)||Nu(r))&&(a=r.itemSchema),a&&this.registerContainer(o.id,a)}}}else if(e.kind()==="Tree"){let n=e,i;if(r&&no(r)&&(i=r.nodeSchema),i){let s=n.getNodes();for(let o of s)this.registerContainer(o.data.id,i)}}}catch(n){this.options.debug&&console.error(`Error registering nested containers for ${e.id}:`,n)}}registerContainersFromLoroEvent(e){for(let r of e.events)if(r.diff.type==="list"){let n=r.diff.diff,i=this.getContainerSchema(r.target);for(let s of n)if(s.insert){for(let o of s.insert)if((0,Ln.isContainer)(o)){let a=o,u;i&&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,Ln.isContainer)(s)){let a=Bu(o)?o:void 0;this.registerContainer(s.id,a),a||console.warn(`Container schema not found for key ${i} in map ${r.target}`)}}}else if(r.diff.type==="tree"){let n=this.doc.getTree(r.target),i=this.getContainerSchema(r.target),s;if(i&&no(i)&&(s=i.nodeSchema),!s)continue;for(let o of r.diff.diff)if(o.action==="create"){let a=n.getNodeByID(o.target);a&&this.registerContainer(a.data.id,s)}}}updateLoro(e,r){if(!this.syncing){this.syncing=!0;try{let n=this.state,i=Sl(this.doc,n,e,"",this.schema,this.options?.inferOptions);this.applyChangesToLoro(i,e,r)}finally{this.syncing=!1}}}applyChangesToLoro(e,r,n){let i=new Map;for(let s of e)i.has(s.container)||i.set(s.container,[]),i.get(s.container).push(s);for(let[s,o]of i.entries())if(s==="")this.applyRootChanges(o,r);else{let a=this.doc.getContainerById(s);if(a)this.applyContainerChanges(a,o,r);else throw new Error(`Container not found for ID: ${s}.
|
|
190
190
|
This is likely due to a stale reference or a synchronization issue.`)}if(e.length>0){let s;if(n){let o={};n.origin!==void 0&&(o.origin=n.origin),n.timestamp!==void 0&&(o.timestamp=n.timestamp),n.message!==void 0&&(o.message=n.message),(o.origin!==void 0||o.timestamp!==void 0||o.message!==void 0)&&(s=o)}this.doc.commit(s)}}applyRootChanges(e,r){for(let n of e){if(!yLe(n))continue;let{key:i,value:s}=n,o=i.toString(),a=this.schema?.definition?.[o],u=a?.type||cZ(s,this.options?.inferOptions),c=null;if(u==="loro-map")c=this.doc.getMap(o);else if(u==="loro-list")c=this.doc.getList(o);else if(u==="loro-text")c=this.doc.getText(o);else if(u==="loro-movable-list")c=this.doc.getMovableList(o);else if(u==="loro-tree")c=this.doc.getTree(o);else throw new Error;if(this.registerContainerWithRegistry(c.id,a),r&&c.kind()==="Map"){let f=r[o];this.stampCid(f,c.id)}this.updateTopLevelContainer(c,s)}}applyContainerChanges(e,r,n){switch(e.kind()){case"Map":{let i=e;for(let s of r){let{key:o,value:a,kind:u}=s;if(o==="")continue;let c=this.getSchemaForChild(e.id,o);if(!(c&&c.type==="ignore"))if(u==="insert")i.set(o,a);else if(u==="insert-container"){let l=this.getSchemaForChildContainer(e.id,o),f=this.insertContainerIntoMap(i,l,o,a);this.stampCid(a,f.id)}else if(u==="delete")i.delete(o);else throw new Error("Unsupported change kind for map")}break}case"List":{let i=e;for(let s of r){let{key:o,value:a,kind:u}=s;if(typeof o!="number")throw new Error(`Invalid list index: ${o}`);let c=o;if(c<0){console.warn(`Invalid list index: ${c}`);continue}if(u==="delete")i.delete(c,1);else if(u==="insert")i.insert(c,a);else if(u==="insert-container"){let l=this.getSchemaForChildContainer(e.id,o);this.insertContainerIntoList(i,l,c,a)}else throw new Error("Unsupported change kind for list")}break}case"MovableList":{let i=e;for(let s of r){let{key:o,value:a,kind:u}=s;if(typeof o!="number")throw new Error(`Invalid list index: ${o}`);let c=o;if(c<0){console.warn(`Invalid list index: ${c}`);continue}if(u==="delete")i.delete(c,1);else if(u==="insert")i.insert(c,a);else if(u==="insert-container"){let l=this.getSchemaForChildContainer(e.id,o);this.insertContainerIntoList(i,l,c,a)}else if(u==="move"){let l=s,f=l.fromIndex,d=l.toIndex;i.move(f,d)}else if(u==="set")i.set(c,a);else if(u==="set-container"){let l=this.getSchemaForChildContainer(e.id,o),[f,d]=this.createContainerFromSchema(l,a),p=i.setContainer(c,f);this.registerContainer(p.id,l),this.initializeContainer(p,l,a),this.stampCid(a,p.id)}else throw new Error}break}case"Text":{let i=e;for(let s of r){if(!("value"in s))continue;let o=s.value;typeof o=="string"&&i.update(o)}break}case"Tree":{let i=e,s,o=this.getContainerSchema(i.id);o&&no(o)&&(s=o.nodeSchema);for(let a of r)if(a.kind==="tree-create"){let u=i.createNode(a.parent,a.index);a.onCreate(u.id),s&&(this.registerContainer(u.data.id,s),this.initializeContainer(u.data,s,a.value),Ru(s)&&Sn(a.value)&&ro(a.value,u.data.id))}else a.kind==="tree-move"?i.move(a.target,a.parent,a.index):a.kind==="tree-delete"&&i.delete(a.target);break}default:console.warn(`Unsupported container type: ${e.kind()}`)}}updateTopLevelContainer(e,r){let n=e.kind();switch(n){case"Text":this.updateTextContainer(e,r);break;case"List":this.updateListContainer(e,r);break;case"Map":this.updateMapContainer(e,r);break;case"MovableList":this.updateListContainer(e,r);break;case"Tree":this.updateTreeContainer(e,r);break;default:throw new Error(`Unknown container kind for top-level update: ${n}.
|
|
191
|
-
This is likely a programming error or unsupported container type.`)}}updateTextContainer(e,r){if(typeof r!="string")throw new Error("Text value must be a string");e.update(r)}updateListContainer(e,r){if(Array.isArray(r)){let n=this.getContainerSchema(e.id);if(n&&!Pu(n)&&!Nu(n))throw new Error(`Invalid schema for list: ${n.type}. Expected LoroListSchema`);let i=n?.idSelector,s=n?.itemSchema;i?this.updateListWithIdSelector(e,r,i,s):this.updateListByIndex(e,r,s)}else throw new Error("List value must be an array")}updateListWithIdSelector(e,r,n,i){let s=new Map,o=e.length;for(let f=0;f<o;f++){let d=e.get(f);try{if(d){let p=n(d);p&&s.set(p,{item:d,index:f})}}catch(p){this.options.debug&&console.warn("Error getting ID for current list item:",p)}}let a=new Map,u=f=>{if(!f)return null;try{let d=n(f);if(d)return d}catch(d){this.options.debug&&console.warn("Error using ID selector directly:",d);let p=f.id;if(typeof p=="string")return p}return null};r.forEach((f,d)=>{try{let p=u(f);if(p)a.set(p,{item:f,index:d});else throw new Error(`Item at index ${d} has no ID`)}catch(p){this.options.debug&&console.warn(`Error getting ID for new list item at index ${d}:`,p)}});let c=[];for(let[f,{index:d}]of s.entries())a.has(f)||c.push(d);c.sort((f,d)=>d-f);for(let f of c)e.delete(f,1);let l=0;for(let f=0;f<r.length;f++){let d=r[f],p=null;try{p=u(d)}catch(_){console.warn(`Error getting ID for new item at index ${f}:`,_);continue}if(!p)continue;if(s.get(p)){let _=e.get(l);Fa(_,d)||(e.delete(l,1),this.insertItemIntoList(e,l,d,i))}else this.insertItemIntoList(e,l,d,i);l++}l<e.length&&e.delete(l,e.length-l)}updateListByIndex(e,r,n){let i=e.length,s=Math.max(i,r.length);for(let o=0;o<s;o++)if(o>=i)this.insertItemIntoList(e,o,r[o],n);else if(o>=r.length){e.delete(r.length,i-r.length);break}else{let a=e.get(o),u=r[o];Fa(a,u)||(e.delete(o,1),this.insertItemIntoList(e,o,u,n))}}insertItemIntoList(e,r,n,i){let s=!1,o;if(i&&Bu(i)?(s=!0,o=i):s=El(n,this.options?.inferOptions)!==void 0,s&&typeof n=="object"&&n!==null){this.insertContainerIntoList(e,o,r,n);return}e.insert(r,n)}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}notifySubscribers(e,r){let n={direction:e,tags:r};for(let i of this.subscribers)i(this.state,n)}dispose(){this.subscribers.clear(),this.subscriptions.forEach(e=>{e()}),this.subscriptions.length=0}insertContainerIntoMap(e,r,n,i){let[s,o]=this.createContainerFromSchema(r,i),a=e.setContainer(n,s);if(!a)throw new Error("Failed to insert container into map");return this.registerContainer(a.id,r),this.initializeContainer(a,r,i),a.kind()==="Map"&&this.stampCid(i,a.id),a}initializeContainer(e,r,n){let i=e.kind();if(i==="Map"){let s=e;if(!Sn(n))return;let o=r;for(let[a,u]of Object.entries(n)){if(a===Mn)continue;let c=this.getSchemaForMapKey(o,a);if(c&&Bu(c)){let l=xl(c);l&&Ra(l,u)?this.insertContainerIntoMap(s,c,a,u):s.set(a,u)}else s.set(a,u)}}else if(i==="List"||i==="MovableList"){let s=e;if(!Array.isArray(n))return;let o=r?.itemSchema,a=Bu(o);for(let u=0;u<n.length;u++){let c=n[u];if(a){let l=xl(o);l&&Ra(l,c)?this.insertContainerIntoList(s,o,u,c):s.insert(u,c)}else s.insert(u,c)}}else if(i==="Text")typeof n=="string"&&e.update(n);else if(i==="Tree"){let s=e;this.updateTreeContainer(s,n)}else throw new Error(`Unknown container kind: ${i}`)}createContainerFromSchema(e,r){let n=e?xl(e):El(r,this.options?.inferOptions);switch(n){case"Map":return[new Ln.LoroMap,"Map"];case"List":return[new Ln.LoroList,"List"];case"MovableList":return[new Ln.LoroMovableList,"MovableList"];case"Text":return[new Ln.LoroText,"Text"];case"Tree":return[new Ln.LoroTree,"Tree"];default:throw new Error(`Unknown schema type: ${n}`)}}insertContainerIntoList(e,r,n,i){let[s,o]=this.createContainerFromSchema(r,i),a;if(n===void 0?a=e.pushContainer(s):a=e.insertContainer(n,s),!a)throw new Error("Failed to insert container into list");return this.registerContainer(a.id,r),this.initializeContainer(a,r,i),a.kind()==="Map"&&this.stampCid(i,a.id),a}updateTreeContainer(e,r){if(!Array.isArray(r))throw new Error("Tree value must be an array of nodes");let n=vR(e.toJSON()),i=r,s=this.getContainerSchema(e.id),o=s&&no(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(!Sn(r))throw new Error("Map value must be an object");let n=this.getContainerSchema(e.id);n&&Sn(r)&&ro(r,e.id);let i=new Set(e.keys());for(let[s,o]of Object.entries(r))if(s!==Mn){if(n&&n.type==="loro-map")this.updateMapEntry(e,s,o,n);else{let a=El(o,this.options?.inferOptions);a&&Ra(a,o)?this.insertContainerIntoMap(e,void 0,s,o):e.set(s,o)}i.delete(s)}for(let s of i)e.delete(s)}updateMapEntry(e,r,n,i){if(r!==Mn){if(i&&i.type==="loro-map"){let s=i,o=this.getSchemaForMapKey(s,r);if(o&&o.type==="ignore")return;if(o&&Bu(o)){let a=xl(o);if(a&&Ra(a,n)){this.insertContainerIntoMap(e,o,r,n);return}}}e.set(r,n)}}getState(){return this.state}setState(e,r){if(this.syncing)return;let n=typeof e=="function"?q_(this.state,o=>{let a=e(o);if(a&&a!==o)return a}):Object.assign({},this.state,e);if(this.options.validateUpdates){let o=this.schema&&fd(this.schema,n);if(o&&!o.valid){let a=`State validation failed: ${o.errors?.join(", ")}`;throw new Error(a)}}let i=r?.tags?Array.isArray(r.tags)?r.tags:[r.tags]:void 0;this.updateLoro(n,r),this.state=n,this.options.checkStateConsistency&&this.checkStateConsistency(),this.notifySubscribers(gd.TO_LORO,i)}checkStateConsistency(){let e=this.state;if(!Fa(e,this.buildRootStateSnapshot()))throw console.error("State diverged",JSON.stringify(e,null,2),JSON.stringify(this.buildRootStateSnapshot(),null,2)),new Error("[InternalError] State diverged")}containerToStateJson(e){let r=e.kind();if(r==="Map"){let n=e,i={};ro(i,e.id);for(let s of n.keys()){let o=n.get(s);i[s]=(0,Ln.isContainer)(o)?this.containerToStateJson(o):o}return i}else if(r==="List"||r==="MovableList"){let n=[],i=e,s=i.length;for(let o=0;o<s;o++){let a=i.get(o);n.push((0,Ln.isContainer)(a)?this.containerToStateJson(a):a)}return n}else{if(r==="Text")return e.toJSON();if(r==="Tree"){let n=e,i=vR(n.toJSON()),s=this.getContainerSchema(n.id);if(s&&no(s)){let a=new Map,c=n.getNodes?.()??[];for(let f of c)try{let d=f,p=typeof d.id=="string"?d.id:void 0,m;if(d.data&&typeof d.data=="object"){let _=d.data;m=typeof _.id=="string"?_.id:void 0}p&&m&&a.set(p,m)}catch{}let l=f=>{for(let d of f){let p=d,m=typeof p.id=="string"?a.get(p.id):void 0;m&&((!p.data||typeof p.data!="object")&&(p.data={}),ro(p.data,m)),Array.isArray(p.children)&&l(p.children)}};l(i)}return i}}return e.toJSON()}buildRootStateSnapshot(){if(!this.schema||this.schema.type!=="schema")return o2(this.doc);let e={},r=this.schema;for(let n in r.definition){let i=r.definition[n],s=xl(i);if(!s)continue;let o=F_(this.doc,n,s);if(s==="Map")e[n]=this.containerToStateJson(o);else if(s==="List"||s==="MovableList")e[n]=this.containerToStateJson(o);else if(s==="Text")e[n]=this.containerToStateJson(o);else if(s==="Tree"){let a=this.containerToStateJson(o);if(!Array.isArray(a)||a.length===0)continue;e[n]=a}else e[n]=this.containerToStateJson(o)}return e}registerContainerWithRegistry(e,r){this.containerRegistry.set(e,{schema:r,registered:!0})}stampCid(e,r){Sn(e)&&ro(e,r)}getSchemaForMapKey(e,r){if(!e)return;if(Object.prototype.hasOwnProperty.call(e.definition,r))return e.definition[r];let n=e;if(n.catchallType)return n.catchallType}getContainerSchema(e){return this.containerRegistry.get(e)?.schema}getSchemaForChildContainer(e,r){let n=this.getSchemaForChild(e,r);if(!(!n||!Bu(n)))return n}getSchemaForChild(e,r){let n=this.getContainerSchema(e);if(n){if(Ru(n))return this.getSchemaForMapKey(n,String(r));if(Pu(n)||Nu(n))return n.itemSchema;if(no(n))return n.nodeSchema}}getContainerIds(){return Array.from(this.containerRegistry.keys())}};function o2(t){let e=t.toJsonWithReplacer((r,n)=>(0,Ln.isContainer)(n)&&n.kind()==="Tree"?vR(n.toJSON()):(0,Ln.isContainer)(n)&&n.kind()==="Map"?{...n.getShallowValue(),[Mn]: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(Sn(t)){let e=t;for(let r of Object.keys(e))e[r]=yR(e[r]);if(Object.prototype.hasOwnProperty.call(e,Mn)){let r=Object.getOwnPropertyDescriptor(e,Mn);if(!r||r.enumerable){let n=e[Mn];delete e[Mn],Object.defineProperty(e,Mn,{value:n})}}return e}return t}function vLe(t){let e={};for(let[r,n]of Object.entries(t))Array.isArray(n)?e[r]=[]:typeof n=="string"?e[r]="":Sn(n)?e[r]={}:e[r]=n;return e}function 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]="":Sn(i)&&(t[n]={}));continue}let o=s.type;if(o==="ignore"){t[n]=i;continue}if(o==="loro-map"){(!(n in t)||!Sn(t[n]))&&(t[n]={});let a=t[n],u=Sn(i)?i:{};FZ(a,u,{type:"schema",definition:s.definition,options:{},getContainerType(){return"Map"}});continue}if(o==="loro-list"||o==="loro-movable-list"){n in t||(t[n]=[]);continue}if(o==="loro-text"){n in t||(t[n]="");continue}if(o==="string"||o==="number"||o==="boolean"){n in t||(t[n]=i);continue}}}var jyt=Object.assign({},iR,bR);var Gyt=Ee.LoroMap({name:Ee.String(),color:Ee.String()}),Yyt=Ee.LoroMap({content:Ee.LoroText(),parentId:Ee.String({required:!1}),isDeleted:Ee.Boolean()}),bLe=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})}),xLe=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(bLe,t=>t.$cid),subIssues:Ee.LoroList(Ee.String()),parentIssueId:Ee.String({required:!1}),attachments:Ee.LoroList(Ee.String())}),RZ=Ee({issue:xLe}),ELe=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:ELe}),wLe=Ee.LoroMap({contents:Ee.String(),timestamp:Ee.String(),role:Ee.String(),read:Ee.Boolean({required:!1}),userId:Ee.String({required:!1})}),SLe=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(wLe,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:SLe}),DLe=Ee.LoroMap({userId:Ee.String(),avatar:Ee.String({required:!1}),name:Ee.String(),email:Ee.String(),role:Ee.String()}),CLe=Ee.LoroMap({id:Ee.String(),name:Ee.String(),githubRepos:Ee.LoroList(Ee.String()),members:Ee.LoroList(DLe,t=>t.userId)}),ALe=Ee.LoroMap({name:Ee.String(),color:Ee.String()}),BZ=Ee({meta:CLe,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(ALe,t=>t.$cid)}),MZ=t=>`issue-${t}`,LZ=t=>`session-${t}`,qZ=t=>`agent-${t}`;var ILe=5*60*1e3,UZ=t=>`ephemeral-${t}`,xR="machine-",Mu=t=>`${xR}${t}`,a2=class{constructor(e){this.store=e}aliveTimer=null;registerMachine(e,r){this.store.set(Mu(e),r),this.aliveTimer=setInterval(()=>{this.store.set(Mu(e),this.store.get(Mu(e)))},ILe/2)}unRegisterMachine(e){this.store.delete(Mu(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(Mu(e))}addMachineSession(e,r){let n=this.getMachine(e);if(n){let i=[...n.sessions,r];this.store.set(Mu(e),{...n,sessions:i})}}removeMachineSession(e,r){let n=this.getMachine(e);if(n){let i=n.sessions.filter(s=>s.sessionId!==r);this.store.set(Mu(e),{...n,sessions:i})}}updateMachineSession(e,r,n){let i=this.getMachine(e);if(i){let s=i.sessions.map(o=>o.sessionId===r?{...o,status:{...o.status,...n}}:o);this.store.set(Mu(e),{...i,sessions:s})}}updateMachine(e,r){let n=this.getMachine(e);n&&this.store.set(Mu(e),{...n,...r})}};var G7e=qe(Nee(),1),Y7e=qe(FR(),1),Q7e=qe(NR(),1),Vee=qe(v2(),1),K7e=qe(Wee(),1);var Al=Vee.default;globalThis.WebSocket=Al;var qo=M4(),x2=class{constructor(e,r){this.workspaceId=e;this.token=r;qo.debug(`[${this.workspaceId}] LoroWebsocketClient url: ${a0+`/ws/${this.workspaceId}`}`),this.client=new aZ({url:a0+`/ws/${this.workspaceId}`,onWsClose:()=>{qo.debug(`[${this.workspaceId}] LoroWebsocketClient ws closed`),this.client.connect()}}),this.docMirror=new 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){qo.error(`Error occurs when importing loro data ${i}`)},onUpdateError(i){qo.error(`Error occurs when updating loro ${i}`)}});qo.debug(`[${e}] waiting for client connected`),await this.client.waitConnected(),qo.debug(`[${e}] joining room`);let n=await this.client.join({roomId:e,crdtAdaptor:r});await n.waitForReachingServerVersion(),qo.debug(`[${e}] joined room frontiers: ${JSON.stringify(r.getDoc().frontiers())}`),this.rooms.set(e,n),this.adaptors.set(e,r)}return this.adaptors.get(e)}async getMirror(e,r,n){if(this.mirrors.has(e))return this.mirrors.get(e);let i=await this.getAdaptor(e),s=new _d({doc:i.getDoc(),schema:r,initialState:n});return this.mirrors.set(e,s),s}close(e){this.adaptors.get(e)&&this.adaptors.delete(e);let n=this.rooms.get(e);n&&(this.rooms.delete(e),n.leave());let i=this.mirrors.get(e);i&&(this.mirrors.delete(e),i.dispose())}closeAll(){for(let e of this.rooms.keys())this.close(e)}},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);qo.debug(`[${this.issueId}] doc frontiers: ${JSON.stringify(r.getDoc().frontiers())}`),this.mirror.setState(n=>(n.issue.status!==e?(qo.debug(`[${this.issueId}] setStatus ${e}`),n.issue.status=e,n.issue.actionHistory.push({type:"update",target:"status",value:JSON.stringify(e),by:"lody-cli",timestamp:new Date().toISOString()})):qo.debug(`[${this.issueId}] setStatus ${e} no change`),n))}destroy(){this.docMirror.close(this.roomId)}},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");qo.debug(`[${this.sessionId}] setChatId ${e}`),this.mirror.setState(r=>(r.session.chatId=e,r))}async setError(e){if(!this.mirror)throw new Error("Mirror not initialized");this.mirror.setState(r=>(r.session.error=e,r.session.status="error",r))}getStatus(){return this.mirror?this.mirror.getState().session.status:"terminated"}isChat(){return this.mirror?!!this.mirror.getState().session.chatId:!1}async getIssueId(){if(this.mirror)return this.mirror.getState().session.issueId}async setStatus(e){if(!this.mirror)throw new Error("Mirror not initialized");this.mirror.setState(r=>(r.session.status=e,r))}async getHistory(){return this.mirror?this.mirror.getState().session.history||[]:[]}async updateHistory(e){if(!this.mirror)throw new Error("Mirror not initialized");this.mirror.setState(r=>{let n=e(r.session.history||[]);return r.session.history=n,r})}destroy(){if(!this.mirror){this.docMirror.close(this.roomId);return}let e=this.getStatus();e==="running"||e==="requestPermission"?this.setStatus("error"):(e==="completed"||e==="terminated")&&this.setStatus("terminated"),this.docMirror.close(this.roomId)}},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,""),J7e=(t,e)=>{if(!e)return t;let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return t.replace(new RegExp(r,"g"),"***TOKEN***")},X7e=(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=J7e([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}=X7e(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 Z7e(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("execution_error"),await this.sessionManager.finishSession(r),this.workspaceDocument.ephemeral.removeMachineSession(this.machineId,r)}),this.sessionManager.on("exit",async e=>{let r=e.sessionId;(await this.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`),(await this.workspaceDocument.getOrCreateSessionDoc(r)).setError("session_not_found"),this.workspaceDocument.ephemeral.removeMachineSession(this.machineId,r))}async handleRegisterResponse(e){e.success?this.logger.info(`Registration successful, machine ID: ${this.machineId}`):this.logger.error(`Registration failed: ${e.error}`)}async handleSessionCreate(e){let{sessionId:r,config:n,workspaceId:i}=e;this.logger.info(`[${r}] Creating new session`);let s={sessionId:r,workspaceId:i,cliType:n.promptConfig.agentType,userId:this.userId,machineId:this.machineId,assumeDocExisting:!0,env:n.env};this.workspaceDocument.ephemeral.addMachineSession(this.machineId,{sessionId:r,status:{status:"establish"}});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,"execution_error"),this.workspaceDocument.ephemeral.removeMachineSession(this.machineId,r);return}}let a=n.promptConfig;this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"running",cliType:s.cliType});let u=await o.agentClient?.connection?.prompt({sessionId:o.acpSessionId,prompt:[{type:"text",text:a.prompt}]});(await this.workspaceDocument.getOrCreateSessionDoc(r)).setStatus("completed"),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{await this.sessionManager.setSessionError(r,"execution_error"),this.sendMessage({type:"session_create_response",sessionId:r,success:!1})}}async handleSessionTerminate(e){let{sessionId:r,force:n}=e;this.logger.info(`[${r}] Terminating session`);try{await this.sessionManager.terminateSession(r,n);let i={type:"session_terminated",sessionId:r,error:void 0,reason:"user_request"};this.sendMessage(i),this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"terminated"}),this.logger.info(`[${r}] Session terminated successfully`)}catch(i){let s={type:"session_terminated",sessionId:r,error:"execution_error",reason:"error"};this.sendMessage(s),this.logger.error(`[${r}] Failed to terminate: ${i instanceof Error?i.message:"Unknown error"}`)}}async 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 tqe(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 eqe(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()}},Z7e=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(),userId:void 0,read: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
|
-
`:"")+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",read:void 0,userId:void 0}),u;case"available_commands":return r.push({contents:JSON.stringify([e]),timestamp:new Date().toISOString(),role:"assistant",read:void 0,userId:void 0}),r
|
|
191
|
+
This is likely a programming error or unsupported container type.`)}}updateTextContainer(e,r){if(typeof r!="string")throw new Error("Text value must be a string");e.update(r)}updateListContainer(e,r){if(Array.isArray(r)){let n=this.getContainerSchema(e.id);if(n&&!Pu(n)&&!Nu(n))throw new Error(`Invalid schema for list: ${n.type}. Expected LoroListSchema`);let i=n?.idSelector,s=n?.itemSchema;i?this.updateListWithIdSelector(e,r,i,s):this.updateListByIndex(e,r,s)}else throw new Error("List value must be an array")}updateListWithIdSelector(e,r,n,i){let s=new Map,o=e.length;for(let f=0;f<o;f++){let d=e.get(f);try{if(d){let p=n(d);p&&s.set(p,{item:d,index:f})}}catch(p){this.options.debug&&console.warn("Error getting ID for current list item:",p)}}let a=new Map,u=f=>{if(!f)return null;try{let d=n(f);if(d)return d}catch(d){this.options.debug&&console.warn("Error using ID selector directly:",d);let p=f.id;if(typeof p=="string")return p}return null};r.forEach((f,d)=>{try{let p=u(f);if(p)a.set(p,{item:f,index:d});else throw new Error(`Item at index ${d} has no ID`)}catch(p){this.options.debug&&console.warn(`Error getting ID for new list item at index ${d}:`,p)}});let c=[];for(let[f,{index:d}]of s.entries())a.has(f)||c.push(d);c.sort((f,d)=>d-f);for(let f of c)e.delete(f,1);let l=0;for(let f=0;f<r.length;f++){let d=r[f],p=null;try{p=u(d)}catch(_){console.warn(`Error getting ID for new item at index ${f}:`,_);continue}if(!p)continue;if(s.get(p)){let _=e.get(l);Fa(_,d)||(e.delete(l,1),this.insertItemIntoList(e,l,d,i))}else this.insertItemIntoList(e,l,d,i);l++}l<e.length&&e.delete(l,e.length-l)}updateListByIndex(e,r,n){let i=e.length,s=Math.max(i,r.length);for(let o=0;o<s;o++)if(o>=i)this.insertItemIntoList(e,o,r[o],n);else if(o>=r.length){e.delete(r.length,i-r.length);break}else{let a=e.get(o),u=r[o];Fa(a,u)||(e.delete(o,1),this.insertItemIntoList(e,o,u,n))}}insertItemIntoList(e,r,n,i){let s=!1,o;if(i&&Bu(i)?(s=!0,o=i):s=El(n,this.options?.inferOptions)!==void 0,s&&typeof n=="object"&&n!==null){this.insertContainerIntoList(e,o,r,n);return}e.insert(r,n)}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}notifySubscribers(e,r){let n={direction:e,tags:r};for(let i of this.subscribers)i(this.state,n)}dispose(){this.subscribers.clear(),this.subscriptions.forEach(e=>{e()}),this.subscriptions.length=0}insertContainerIntoMap(e,r,n,i){let[s,o]=this.createContainerFromSchema(r,i),a=e.setContainer(n,s);if(!a)throw new Error("Failed to insert container into map");return this.registerContainer(a.id,r),this.initializeContainer(a,r,i),a.kind()==="Map"&&this.stampCid(i,a.id),a}initializeContainer(e,r,n){let i=e.kind();if(i==="Map"){let s=e;if(!Sn(n))return;let o=r;for(let[a,u]of Object.entries(n)){if(a===Mn)continue;let c=this.getSchemaForMapKey(o,a);if(c&&Bu(c)){let l=xl(c);l&&Ra(l,u)?this.insertContainerIntoMap(s,c,a,u):s.set(a,u)}else s.set(a,u)}}else if(i==="List"||i==="MovableList"){let s=e;if(!Array.isArray(n))return;let o=r?.itemSchema,a=Bu(o);for(let u=0;u<n.length;u++){let c=n[u];if(a){let l=xl(o);l&&Ra(l,c)?this.insertContainerIntoList(s,o,u,c):s.insert(u,c)}else s.insert(u,c)}}else if(i==="Text")typeof n=="string"&&e.update(n);else if(i==="Tree"){let s=e;this.updateTreeContainer(s,n)}else throw new Error(`Unknown container kind: ${i}`)}createContainerFromSchema(e,r){let n=e?xl(e):El(r,this.options?.inferOptions);switch(n){case"Map":return[new Ln.LoroMap,"Map"];case"List":return[new Ln.LoroList,"List"];case"MovableList":return[new Ln.LoroMovableList,"MovableList"];case"Text":return[new Ln.LoroText,"Text"];case"Tree":return[new Ln.LoroTree,"Tree"];default:throw new Error(`Unknown schema type: ${n}`)}}insertContainerIntoList(e,r,n,i){let[s,o]=this.createContainerFromSchema(r,i),a;if(n===void 0?a=e.pushContainer(s):a=e.insertContainer(n,s),!a)throw new Error("Failed to insert container into list");return this.registerContainer(a.id,r),this.initializeContainer(a,r,i),a.kind()==="Map"&&this.stampCid(i,a.id),a}updateTreeContainer(e,r){if(!Array.isArray(r))throw new Error("Tree value must be an array of nodes");let n=vR(e.toJSON()),i=r,s=this.getContainerSchema(e.id),o=s&&no(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(!Sn(r))throw new Error("Map value must be an object");let n=this.getContainerSchema(e.id);n&&Sn(r)&&ro(r,e.id);let i=new Set(e.keys());for(let[s,o]of Object.entries(r))if(s!==Mn){if(n&&n.type==="loro-map")this.updateMapEntry(e,s,o,n);else{let a=El(o,this.options?.inferOptions);a&&Ra(a,o)?this.insertContainerIntoMap(e,void 0,s,o):e.set(s,o)}i.delete(s)}for(let s of i)e.delete(s)}updateMapEntry(e,r,n,i){if(r!==Mn){if(i&&i.type==="loro-map"){let s=i,o=this.getSchemaForMapKey(s,r);if(o&&o.type==="ignore")return;if(o&&Bu(o)){let a=xl(o);if(a&&Ra(a,n)){this.insertContainerIntoMap(e,o,r,n);return}}}e.set(r,n)}}getState(){return this.state}setState(e,r){if(this.syncing)return;let n=typeof e=="function"?q_(this.state,o=>{let a=e(o);if(a&&a!==o)return a}):Object.assign({},this.state,e);if(this.options.validateUpdates){let o=this.schema&&fd(this.schema,n);if(o&&!o.valid){let a=`State validation failed: ${o.errors?.join(", ")}`;throw new Error(a)}}let i=r?.tags?Array.isArray(r.tags)?r.tags:[r.tags]:void 0;this.updateLoro(n,r),this.state=n,this.options.checkStateConsistency&&this.checkStateConsistency(),this.notifySubscribers(gd.TO_LORO,i)}checkStateConsistency(){let e=this.state;if(!Fa(e,this.buildRootStateSnapshot()))throw console.error("State diverged",JSON.stringify(e,null,2),JSON.stringify(this.buildRootStateSnapshot(),null,2)),new Error("[InternalError] State diverged")}containerToStateJson(e){let r=e.kind();if(r==="Map"){let n=e,i={};ro(i,e.id);for(let s of n.keys()){let o=n.get(s);i[s]=(0,Ln.isContainer)(o)?this.containerToStateJson(o):o}return i}else if(r==="List"||r==="MovableList"){let n=[],i=e,s=i.length;for(let o=0;o<s;o++){let a=i.get(o);n.push((0,Ln.isContainer)(a)?this.containerToStateJson(a):a)}return n}else{if(r==="Text")return e.toJSON();if(r==="Tree"){let n=e,i=vR(n.toJSON()),s=this.getContainerSchema(n.id);if(s&&no(s)){let a=new Map,c=n.getNodes?.()??[];for(let f of c)try{let d=f,p=typeof d.id=="string"?d.id:void 0,m;if(d.data&&typeof d.data=="object"){let _=d.data;m=typeof _.id=="string"?_.id:void 0}p&&m&&a.set(p,m)}catch{}let l=f=>{for(let d of f){let p=d,m=typeof p.id=="string"?a.get(p.id):void 0;m&&((!p.data||typeof p.data!="object")&&(p.data={}),ro(p.data,m)),Array.isArray(p.children)&&l(p.children)}};l(i)}return i}}return e.toJSON()}buildRootStateSnapshot(){if(!this.schema||this.schema.type!=="schema")return o2(this.doc);let e={},r=this.schema;for(let n in r.definition){let i=r.definition[n],s=xl(i);if(!s)continue;let o=F_(this.doc,n,s);if(s==="Map")e[n]=this.containerToStateJson(o);else if(s==="List"||s==="MovableList")e[n]=this.containerToStateJson(o);else if(s==="Text")e[n]=this.containerToStateJson(o);else if(s==="Tree"){let a=this.containerToStateJson(o);if(!Array.isArray(a)||a.length===0)continue;e[n]=a}else e[n]=this.containerToStateJson(o)}return e}registerContainerWithRegistry(e,r){this.containerRegistry.set(e,{schema:r,registered:!0})}stampCid(e,r){Sn(e)&&ro(e,r)}getSchemaForMapKey(e,r){if(!e)return;if(Object.prototype.hasOwnProperty.call(e.definition,r))return e.definition[r];let n=e;if(n.catchallType)return n.catchallType}getContainerSchema(e){return this.containerRegistry.get(e)?.schema}getSchemaForChildContainer(e,r){let n=this.getSchemaForChild(e,r);if(!(!n||!Bu(n)))return n}getSchemaForChild(e,r){let n=this.getContainerSchema(e);if(n){if(Ru(n))return this.getSchemaForMapKey(n,String(r));if(Pu(n)||Nu(n))return n.itemSchema;if(no(n))return n.nodeSchema}}getContainerIds(){return Array.from(this.containerRegistry.keys())}};function o2(t){let e=t.toJsonWithReplacer((r,n)=>(0,Ln.isContainer)(n)&&n.kind()==="Tree"?vR(n.toJSON()):(0,Ln.isContainer)(n)&&n.kind()==="Map"?{...n.getShallowValue(),[Mn]: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(Sn(t)){let e=t;for(let r of Object.keys(e))e[r]=yR(e[r]);if(Object.prototype.hasOwnProperty.call(e,Mn)){let r=Object.getOwnPropertyDescriptor(e,Mn);if(!r||r.enumerable){let n=e[Mn];delete e[Mn],Object.defineProperty(e,Mn,{value:n})}}return e}return t}function vLe(t){let e={};for(let[r,n]of Object.entries(t))Array.isArray(n)?e[r]=[]:typeof n=="string"?e[r]="":Sn(n)?e[r]={}:e[r]=n;return e}function 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]="":Sn(i)&&(t[n]={}));continue}let o=s.type;if(o==="ignore"){t[n]=i;continue}if(o==="loro-map"){(!(n in t)||!Sn(t[n]))&&(t[n]={});let a=t[n],u=Sn(i)?i:{};FZ(a,u,{type:"schema",definition:s.definition,options:{},getContainerType(){return"Map"}});continue}if(o==="loro-list"||o==="loro-movable-list"){n in t||(t[n]=[]);continue}if(o==="loro-text"){n in t||(t[n]="");continue}if(o==="string"||o==="number"||o==="boolean"){n in t||(t[n]=i);continue}}}var jyt=Object.assign({},iR,bR);var Gyt=Ee.LoroMap({name:Ee.String(),color:Ee.String()}),Yyt=Ee.LoroMap({content:Ee.LoroText(),parentId:Ee.String({required:!1}),isDeleted:Ee.Boolean()}),bLe=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})}),xLe=Ee.LoroMap({id:Ee.String(),title:Ee.String(),description:Ee.LoroText({required:!1}),status:Ee.String(),priority:Ee.String(),assigneeId:Ee.String({required:!1}),assigneeName:Ee.String({required:!1}),agent:Ee.String({required:!1}),githubRepo:Ee.String({required:!1}),labels:Ee.LoroList(Ee.String()),estimate:Ee.Number({required:!1}),dueDate:Ee.String({required:!1}),createdAt:Ee.String(),createdBy:Ee.String(),actionHistory:Ee.LoroList(bLe,t=>t.$cid),subIssues:Ee.LoroList(Ee.String()),parentIssueId:Ee.String({required:!1}),attachments:Ee.LoroList(Ee.String())}),RZ=Ee({issue:xLe}),ELe=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:ELe}),wLe=Ee.LoroMap({contents:Ee.String(),timestamp:Ee.String(),role:Ee.String(),read:Ee.Boolean({required:!1}),userId:Ee.String({required:!1})}),SLe=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(wLe,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:SLe}),DLe=Ee.LoroMap({userId:Ee.String(),avatar:Ee.String({required:!1}),name:Ee.String(),email:Ee.String(),role:Ee.String()}),CLe=Ee.LoroMap({id:Ee.String(),name:Ee.String(),githubRepos:Ee.LoroList(Ee.String()),members:Ee.LoroList(DLe,t=>t.userId)}),ALe=Ee.LoroMap({name:Ee.String(),color:Ee.String()}),BZ=Ee({meta:CLe,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(ALe,t=>t.$cid)}),MZ=t=>`issue-${t}`,LZ=t=>`session-${t}`,qZ=t=>`agent-${t}`;var ILe=5*60*1e3,UZ=t=>`ephemeral-${t}`,xR="machine-",Mu=t=>`${xR}${t}`,a2=class{constructor(e){this.store=e}aliveTimer=null;registerMachine(e,r){this.store.set(Mu(e),r),this.aliveTimer=setInterval(()=>{this.store.set(Mu(e),this.store.get(Mu(e)))},ILe/2)}unRegisterMachine(e){this.store.delete(Mu(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(Mu(e))}addMachineSession(e,r){let n=this.getMachine(e);if(n){let i=[...n.sessions,r];this.store.set(Mu(e),{...n,sessions:i})}}removeMachineSession(e,r){let n=this.getMachine(e);if(n){let i=n.sessions.filter(s=>s.sessionId!==r);this.store.set(Mu(e),{...n,sessions:i})}}updateMachineSession(e,r,n){let i=this.getMachine(e);if(i){let s=i.sessions.map(o=>o.sessionId===r?{...o,status:{...o.status,...n}}:o);this.store.set(Mu(e),{...i,sessions:s})}}updateMachine(e,r){let n=this.getMachine(e);n&&this.store.set(Mu(e),{...n,...r})}};var G7e=qe(Nee(),1),Y7e=qe(FR(),1),Q7e=qe(NR(),1),Vee=qe(v2(),1),K7e=qe(Wee(),1);var Al=Vee.default;globalThis.WebSocket=Al;var qo=M4(),x2=class{constructor(e,r){this.workspaceId=e;this.token=r;qo.debug(`[${this.workspaceId}] LoroWebsocketClient url: ${a0+`/ws/${this.workspaceId}`}`),this.client=new aZ({url:a0+`/ws/${this.workspaceId}`,onWsClose:()=>{qo.debug(`[${this.workspaceId}] LoroWebsocketClient ws closed`),this.client.connect()}}),this.docMirror=new 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){qo.error(`Error occurs when importing loro data ${i}`)},onUpdateError(i){qo.error(`Error occurs when updating loro ${i}`)}});qo.debug(`[${e}] waiting for client connected`),await this.client.waitConnected(),qo.debug(`[${e}] joining room`);let n=await this.client.join({roomId:e,crdtAdaptor:r});await n.waitForReachingServerVersion(),qo.debug(`[${e}] joined room frontiers: ${JSON.stringify(r.getDoc().frontiers())}`),this.rooms.set(e,n),this.adaptors.set(e,r)}return this.adaptors.get(e)}async getMirror(e,r,n){if(this.mirrors.has(e))return this.mirrors.get(e);let i=await this.getAdaptor(e),s=new _d({doc:i.getDoc(),schema:r,initialState:n});return this.mirrors.set(e,s),s}close(e){this.adaptors.get(e)&&this.adaptors.delete(e);let n=this.rooms.get(e);n&&(this.rooms.delete(e),n.leave());let i=this.mirrors.get(e);i&&(this.mirrors.delete(e),i.dispose())}closeAll(){for(let e of this.rooms.keys())this.close(e)}},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);qo.debug(`[${this.issueId}] doc frontiers: ${JSON.stringify(r.getDoc().frontiers())}`),this.mirror.setState(n=>(n.issue.status!==e?(qo.debug(`[${this.issueId}] setStatus ${e}`),n.issue.status=e,n.issue.actionHistory.push({type:"update",target:"status",value:JSON.stringify(e),by:"lody-cli",timestamp:new Date().toISOString()})):qo.debug(`[${this.issueId}] setStatus ${e} no change`),n))}destroy(){this.docMirror.close(this.roomId)}},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");qo.debug(`[${this.sessionId}] setChatId ${e}`),this.mirror.setState(r=>(r.session.chatId=e,r))}async setError(e){if(!this.mirror)throw new Error("Mirror not initialized");this.mirror.setState(r=>(r.session.error=e,r.session.status="error",r))}getStatus(){return this.mirror?this.mirror.getState().session.status:"terminated"}isChat(){return this.mirror?!!this.mirror.getState().session.chatId:!1}async getIssueId(){if(this.mirror)return this.mirror.getState().session.issueId}async setStatus(e){if(!this.mirror)throw new Error("Mirror not initialized");this.mirror.setState(r=>(r.session.status=e,r))}async getHistory(){return this.mirror?this.mirror.getState().session.history||[]:[]}async updateHistory(e){if(!this.mirror)throw new Error("Mirror not initialized");this.mirror.setState(r=>{let n=e(r.session.history||[]);return r.session.history=n,r})}destroy(){if(!this.mirror){this.docMirror.close(this.roomId);return}let e=this.getStatus();e==="running"||e==="requestPermission"?this.setStatus("error"):(e==="completed"||e==="terminated")&&this.setStatus("terminated"),this.docMirror.close(this.roomId)}},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,""),J7e=(t,e)=>{if(!e)return t;let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return t.replace(new RegExp(r,"g"),"***TOKEN***")},X7e=(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=J7e([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}=X7e(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 Z7e(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("execution_error"),await this.sessionManager.finishSession(r),this.workspaceDocument.ephemeral.removeMachineSession(this.machineId,r)}),this.sessionManager.on("exit",async e=>{let r=e.sessionId;(await this.workspaceDocument.getOrCreateSessionDoc(r)).setStatus("completed");let i=new Date().toISOString();this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"completed",completedAt:i})})}registerMachine(){let e={type:"register",role:"machine",id:this.machineId,token:this.token,workspaceId:this.workspaceId,userId:this.userId,machineInfo:{name:this.machineName,cliVersion:this.cliVersion,os:process.platform,enableDocker:this.enableDocker}};this.sendMessage(e),this.logger.info(`Machine registered with name: ${this.machineName}`)}async handleMessage(e){switch(this.logger.debug(`Received message: ${e.type}`),e.type){case"register_response":await this.handleRegisterResponse(e);break;case"session_create":await this.handleSessionCreate(e);break;case"session_terminate":await this.handleSessionTerminate(e);break;case"session_stop":await this.handleSessionStop(e);break;case"permission_response":await this.handlePermissionResponse(e);break;case"session_chat":await this.handleSessionChat(e);break;default:this.logger.debug(`Unknown message: ${e}`)}}async handleSessionChat(e){let{sessionId:r,promptConfig:n,historyCid:i}=e;if(this.logger.info(`[${r}] Received chat request`),i)try{await(await this.workspaceDocument.getOrCreateSessionDoc(r)).markHistoryAsRead(i),this.logger.debug(`[${r}] Marked history as read`)}catch(o){this.logger.warn(`[${r}] Failed to mark history as read: ${o instanceof Error?o.message:"Unknown error"}`)}this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"running",cliType:n.agentType,createdAt:new Date().toISOString()});let s=this.sessionManager.getSession(r);s?(await s.agentClient?.connection?.prompt({sessionId:s.acpSessionId,prompt:[{type:"text",text:n.prompt}]}),this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"completed",completedAt:new Date().toISOString()}),this.logger.info(`[${r}] Chat request processed successfully`)):(this.logger.warn(`[${r}] Session not found`),(await this.workspaceDocument.getOrCreateSessionDoc(r)).setError("session_not_found"),this.workspaceDocument.ephemeral.removeMachineSession(this.machineId,r))}async handleRegisterResponse(e){e.success?this.logger.info(`Registration successful, machine ID: ${this.machineId}`):this.logger.error(`Registration failed: ${e.error}`)}async handleSessionCreate(e){let{sessionId:r,config:n,workspaceId:i}=e;this.logger.info(`[${r}] Creating new session`);let s={sessionId:r,workspaceId:i,cliType:n.promptConfig.agentType,userId:this.userId,machineId:this.machineId,assumeDocExisting:!0,env:n.env};this.workspaceDocument.ephemeral.addMachineSession(this.machineId,{sessionId:r,status:{status:"establish",createdAt:new Date().toISOString()}});try{let o=await this.sessionManager.createSession(s);if(this.sendMessage({type:"session_create_response",sessionId:r,success:!0}),n.githubRepo&&n.githubToken){this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"git-clone",repo:n.githubRepo});try{await Kee(n.githubRepo,n.githubToken,o,this.logger)}catch(f){let d=f instanceof Error?f.message:"Failed to clone GitHub repository";this.logger.error(`[${r}] ${d}`),await this.sessionManager.setSessionError(r,"execution_error"),this.workspaceDocument.ephemeral.removeMachineSession(this.machineId,r);return}}let a=n.promptConfig;this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"running",cliType:s.cliType});let u=await o.agentClient?.connection?.prompt({sessionId:o.acpSessionId,prompt:[{type:"text",text:a.prompt}]});(await this.workspaceDocument.getOrCreateSessionDoc(r)).setStatus("completed");let l=new Date().toISOString();this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"completed",completedAt:l}),this.logger.debug(`[${r}] Prompt response: ${JSON.stringify(u)}`),this.logger.info(`[${r}] Session created successfully`)}catch{await this.sessionManager.setSessionError(r,"execution_error"),this.sendMessage({type:"session_create_response",sessionId:r,success:!1})}}async handleSessionTerminate(e){let{sessionId:r,force:n}=e;this.logger.info(`[${r}] Terminating session`);try{await this.sessionManager.terminateSession(r,n);let i={type:"session_terminated",sessionId:r,error:void 0,reason:"user_request"};this.sendMessage(i),this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"terminated"}),this.logger.info(`[${r}] Session terminated successfully`)}catch(i){let s={type:"session_terminated",sessionId:r,error:"execution_error",reason:"error"};this.sendMessage(s),this.logger.error(`[${r}] Failed to terminate: ${i instanceof Error?i.message:"Unknown error"}`)}}async handleSessionStop(e){let{sessionId:r}=e;this.logger.info(`[${r}] Received stop request`);let n=this.sessionManager.getSession(r);if(!n){this.logger.warn(`[${r}] Session not found for stop request`);return}if(!n.agentClient?.connection||!n.acpSessionId){this.logger.warn(`[${r}] Cannot stop session without active ACP connection`);return}try{await n.agentClient.connection.cancel({sessionId:n.acpSessionId}),(await this.workspaceDocument.getOrCreateSessionDoc(r)).setStatus("completed");let s=new Date().toISOString();this.workspaceDocument.ephemeral.updateMachineSession(this.machineId,r,{status:"completed",completedAt:s}),this.logger.info(`[${r}] Stop signal sent to agent`)}catch(i){this.logger.error(`[${r}] Failed to stop session: ${i instanceof Error?i.message:"Unknown error"}`)}}async handlePermissionResponse(e){this.logger.info(`[${e.sessionId}] Permission response received for ${e.requestId}: ${e.outcome.outcome}`);let r=this.pendingPermissionRequests.get(e.requestId);r?(r.resolve({outcome:e.outcome}),this.pendingPermissionRequests.delete(e.requestId)):this.logger.warn(`[${e.sessionId}] No pending permission request found for ${e.requestId}`);try{let n=await this.workspaceDocument.getOrCreateSessionDoc(e.sessionId);await tqe(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 eqe(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()}},Z7e=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(),userId:void 0,read: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
|
+
`:"")+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),n.contents=JSON.stringify(i),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",read:void 0,userId:void 0}),u;case"available_commands":return r.push({contents:JSON.stringify([e]),timestamp:new Date().toISOString(),role:"assistant",read:void 0,userId:void 0}),r}})},eqe=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([rqe(e,r)]),timestamp:new Date().toISOString(),read:void 0,userId:void 0}),i})},tqe=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}}},rqe=(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:()=>hZe,DIRTY:()=>rh,EMPTY_PATH:()=>VXe,INVALID:()=>gt,NEVER:()=>JZe,OK:()=>ki,ParseStatus:()=>gi,Schema:()=>zt,ZodAny:()=>pf,ZodArray:()=>fc,ZodBigInt:()=>ih,ZodBoolean:()=>sh,ZodBranded:()=>Uv,ZodCatch:()=>gh,ZodDate:()=>oh,ZodDefault:()=>mh,ZodDiscriminatedUnion:()=>YA,ZodEffects:()=>xo,ZodEnum:()=>hh,ZodError:()=>ps,ZodFirstPartyTypeKind:()=>bt,ZodFunction:()=>KA,ZodIntersection:()=>lh,ZodIssueCode:()=>Ie,ZodLazy:()=>fh,ZodLiteral:()=>dh,ZodMap:()=>Rm,ZodNaN:()=>Nm,ZodNativeEnum:()=>ph,ZodNever:()=>oa,ZodNull:()=>uh,ZodNullable:()=>ou,ZodNumber:()=>nh,ZodObject:()=>ms,ZodOptional:()=>vo,ZodParsedType:()=>He,ZodPipeline:()=>jv,ZodPromise:()=>mf,ZodReadonly:()=>_h,ZodRecord:()=>QA,ZodSchema:()=>zt,ZodSet:()=>Pm,ZodString:()=>hf,ZodSymbol:()=>Om,ZodTransformer:()=>xo,ZodTuple:()=>su,ZodType:()=>zt,ZodUndefined:()=>ah,ZodUnion:()=>ch,ZodUnknown:()=>lc,ZodVoid:()=>Fm,addIssueToContext:()=>Be,any:()=>EZe,array:()=>CZe,bigint:()=>_Ze,boolean:()=>yfe,coerce:()=>KZe,custom:()=>mfe,date:()=>yZe,datetimeRegex:()=>hfe,defaultErrorMap:()=>uc,discriminatedUnion:()=>kZe,effect:()=>$Ze,enum:()=>qZe,function:()=>BZe,getErrorMap:()=>Im,getParsedType:()=>iu,instanceof:()=>mZe,intersection:()=>OZe,isAborted:()=>zA,isAsync:()=>Tm,isDirty:()=>GA,isValid:()=>df,late:()=>pZe,lazy:()=>MZe,literal:()=>LZe,makeIssue:()=>qv,map:()=>PZe,nan:()=>gZe,nativeEnum:()=>UZe,never:()=>SZe,null:()=>xZe,nullable:()=>WZe,number:()=>_fe,object:()=>AZe,objectUtil:()=>DM,oboolean:()=>QZe,onumber:()=>YZe,optional:()=>HZe,ostring:()=>GZe,pipeline:()=>zZe,preprocess:()=>VZe,promise:()=>jZe,quotelessJson:()=>$Xe,record:()=>RZe,set:()=>NZe,setErrorMap:()=>WXe,strictObject:()=>IZe,string:()=>gfe,symbol:()=>vZe,transformer:()=>$Ze,tuple:()=>FZe,undefined:()=>bZe,union:()=>TZe,unknown:()=>wZe,util:()=>nr,void:()=>DZe});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"]),iu=t=>{switch(typeof t){case"undefined":return He.undefined;case"string":return He.string;case"number":return Number.isNaN(t)?He.nan:He.number;case"boolean":return He.boolean;case"function":return He.function;case"bigint":return He.bigint;case"symbol":return He.symbol;case"object":return Array.isArray(t)?He.array:t===null?He.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?He.promise:typeof Map<"u"&&t instanceof Map?He.map:typeof Set<"u"&&t instanceof Set?He.set:typeof Date<"u"&&t instanceof Date?He.date:He.object;default:return He.unknown}};var Ie=nr.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),$Xe=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),ps=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},i=s=>{for(let o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)n._errors.push(r(o));else{let a=n,u=0;for(;u<o.path.length;){let c=o.path[u];u===o.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(r(o))):a[c]=a[c]||{_errors:[]},a=a[c],u++}}};return i(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,nr.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];r[s]=r[s]||[],r[s].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};ps.create=t=>new ps(t);var HXe=(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=HXe;var ufe=uc;function WXe(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}},VXe=[];function Be(t,e){let r=Im(),n=qv({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===uc?void 0:uc].filter(i=>!!i)});t.common.issues.push(n)}var gi=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return gt;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let s=await i.key,o=await i.value;n.push({key:s,value:o})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:s,value:o}=i;if(s.status==="aborted"||o.status==="aborted")return gt;s.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(n[s.value]=o.value)}return{status:e.value,value:n}}},gt=Object.freeze({status:"aborted"}),rh=t=>({status:"dirty",value:t}),ki=t=>({status:"valid",value:t}),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 bo=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},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 ps(t.common.issues);return this._error=r,this._error}}};function jt(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(o,a)=>{let{message:u}=t;return o.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:u??r??a.defaultError}},description:i}}var zt=class{get description(){return this._def.description}_getType(e){return iu(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:iu(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new gi,ctx:{common:e.parent.common,data:e.data,parsedType:iu(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Tm(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:iu(e)},i=this._parseSync({data:e,path:n.path,parent:n});return cfe(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:iu(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return df(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>df(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:iu(e)},i=this._parse({data:e,path:n.path,parent:n}),s=await(Tm(i)?i:Promise.resolve(i));return 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 xo({schema:this,typeName:bt.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return vo.create(this,this._def)}nullable(){return ou.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return fc.create(this)}promise(){return mf.create(this,this._def)}or(e){return ch.create([this,e],this._def)}and(e){return lh.create(this,e,this._def)}transform(e){return new xo({...jt(this._def),schema:this,typeName:bt.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new mh({...jt(this._def),innerType:this,defaultValue:r,typeName:bt.ZodDefault})}brand(){return new Uv({typeName:bt.ZodBranded,type:this,...jt(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new gh({...jt(this._def),innerType:this,catchValue:r,typeName:bt.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return jv.create(this,e)}readonly(){return _h.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},zXe=/^c[^\s-]{8,}$/i,GXe=/^[0-9a-z]+$/,YXe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,QXe=/^[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,KXe=/^[a-z0-9_-]{21}$/i,JXe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,XXe=/^[-+]?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)?)??$/,ZXe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,eZe="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",CM,tZe=/^(?:(?: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])$/,rZe=/^(?:(?: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])$/,nZe=/^(([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]))$/,iZe=/^(([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])$/,sZe=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,oZe=/^([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])))",aZe=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 uZe(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 cZe(t,e){return!!((e==="v4"||!e)&&tZe.test(t)||(e==="v6"||!e)&&nZe.test(t))}function lZe(t,e){if(!JXe.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 fZe(t,e){return!!((e==="v4"||!e)&&rZe.test(t)||(e==="v6"||!e)&&iZe.test(t))}var hf=class t extends zt{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==He.string){let s=this._getOrReturnCtx(e);return Be(s,{code:Ie.invalid_type,expected:He.string,received:s.parsedType}),gt}let n=new gi,i;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(i=this._getOrReturnCtx(e,i),Be(i,{code:Ie.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(i=this._getOrReturnCtx(e,i),Be(i,{code:Ie.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let o=e.data.length>s.value,a=e.data.length<s.value;(o||a)&&(i=this._getOrReturnCtx(e,i),o?Be(i,{code:Ie.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&Be(i,{code:Ie.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")ZXe.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(eZe,"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")QXe.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")KXe.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")zXe.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")GXe.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")YXe.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"?aZe.test(e.data)||(i=this._getOrReturnCtx(e,i),Be(i,{code:Ie.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?uZe(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"?XXe.test(e.data)||(i=this._getOrReturnCtx(e,i),Be(i,{validation:"duration",code:Ie.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?cZe(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"?lZe(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"?fZe(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"?sZe.test(e.data)||(i=this._getOrReturnCtx(e,i),Be(i,{validation:"base64",code:Ie.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?oZe.test(e.data)||(i=this._getOrReturnCtx(e,i),Be(i,{validation:"base64url",code:Ie.invalid_string,message:s.message}),n.dirty()):nr.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:Ie.invalid_string,...tt.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...tt.errToObj(e)})}url(e){return this._addCheck({kind:"url",...tt.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...tt.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...tt.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...tt.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...tt.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...tt.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...tt.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...tt.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...tt.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...tt.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...tt.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...tt.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...tt.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...tt.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...tt.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...tt.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...tt.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...tt.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...tt.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...tt.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...tt.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...tt.errToObj(r)})}nonempty(e){return this.min(1,tt.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};hf.create=t=>new hf({checks:[],typeName:bt.ZodString,coerce:t?.coerce??!1,...jt(t)});function dZe(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,s=Number.parseInt(t.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return s%o/10**i}var nh=class t extends zt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==He.number){let s=this._getOrReturnCtx(e);return Be(s,{code:Ie.invalid_type,expected:He.number,received:s.parsedType}),gt}let n,i=new gi;for(let s of this._def.checks)s.kind==="int"?nr.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),Be(n,{code:Ie.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),Be(n,{code:Ie.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),Be(n,{code:Ie.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?dZe(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),Be(n,{code:Ie.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),Be(n,{code:Ie.not_finite,message:s.message}),i.dirty()):nr.assertNever(s);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,tt.toString(r))}gt(e,r){return this.setLimit("min",e,!1,tt.toString(r))}lte(e,r){return this.setLimit("max",e,!0,tt.toString(r))}lt(e,r){return this.setLimit("max",e,!1,tt.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:tt.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:tt.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:tt.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:tt.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:tt.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:tt.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:tt.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:tt.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:tt.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:tt.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&nr.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};nh.create=t=>new nh({checks:[],typeName:bt.ZodNumber,coerce:t?.coerce||!1,...jt(t)});var ih=class t extends zt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==He.bigint)return this._getInvalidInput(e);let n,i=new gi;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),Be(n,{code:Ie.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),Be(n,{code:Ie.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),Be(n,{code:Ie.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):nr.assertNever(s);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return Be(r,{code:Ie.invalid_type,expected:He.bigint,received:r.parsedType}),gt}gte(e,r){return this.setLimit("min",e,!0,tt.toString(r))}gt(e,r){return this.setLimit("min",e,!1,tt.toString(r))}lte(e,r){return this.setLimit("max",e,!0,tt.toString(r))}lt(e,r){return this.setLimit("max",e,!1,tt.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:tt.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:tt.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:tt.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:tt.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:tt.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:tt.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};ih.create=t=>new ih({checks:[],typeName:bt.ZodBigInt,coerce:t?.coerce??!1,...jt(t)});var sh=class extends zt{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==He.boolean){let n=this._getOrReturnCtx(e);return Be(n,{code:Ie.invalid_type,expected:He.boolean,received:n.parsedType}),gt}return ki(e.data)}};sh.create=t=>new sh({typeName:bt.ZodBoolean,coerce:t?.coerce||!1,...jt(t)});var oh=class t extends zt{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==He.date){let s=this._getOrReturnCtx(e);return Be(s,{code:Ie.invalid_type,expected:He.date,received:s.parsedType}),gt}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return Be(s,{code:Ie.invalid_date}),gt}let n=new gi,i;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(i=this._getOrReturnCtx(e,i),Be(i,{code:Ie.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(i=this._getOrReturnCtx(e,i),Be(i,{code:Ie.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):nr.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:tt.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:tt.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};oh.create=t=>new oh({checks:[],coerce:t?.coerce||!1,typeName:bt.ZodDate,...jt(t)});var Om=class extends zt{_parse(e){if(this._getType(e)!==He.symbol){let n=this._getOrReturnCtx(e);return Be(n,{code:Ie.invalid_type,expected:He.symbol,received:n.parsedType}),gt}return ki(e.data)}};Om.create=t=>new Om({typeName:bt.ZodSymbol,...jt(t)});var ah=class extends zt{_parse(e){if(this._getType(e)!==He.undefined){let n=this._getOrReturnCtx(e);return Be(n,{code:Ie.invalid_type,expected:He.undefined,received:n.parsedType}),gt}return ki(e.data)}};ah.create=t=>new ah({typeName:bt.ZodUndefined,...jt(t)});var uh=class extends zt{_parse(e){if(this._getType(e)!==He.null){let n=this._getOrReturnCtx(e);return Be(n,{code:Ie.invalid_type,expected:He.null,received:n.parsedType}),gt}return ki(e.data)}};uh.create=t=>new uh({typeName:bt.ZodNull,...jt(t)});var pf=class extends zt{constructor(){super(...arguments),this._any=!0}_parse(e){return ki(e.data)}};pf.create=t=>new pf({typeName:bt.ZodAny,...jt(t)});var lc=class extends zt{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ki(e.data)}};lc.create=t=>new lc({typeName:bt.ZodUnknown,...jt(t)});var oa=class extends zt{_parse(e){let r=this._getOrReturnCtx(e);return Be(r,{code:Ie.invalid_type,expected:He.never,received:r.parsedType}),gt}};oa.create=t=>new oa({typeName:bt.ZodNever,...jt(t)});var Fm=class extends zt{_parse(e){if(this._getType(e)!==He.undefined){let n=this._getOrReturnCtx(e);return Be(n,{code:Ie.invalid_type,expected:He.void,received:n.parsedType}),gt}return ki(e.data)}};Fm.create=t=>new Fm({typeName:bt.ZodVoid,...jt(t)});var fc=class t extends zt{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==He.array)return Be(r,{code:Ie.invalid_type,expected:He.array,received:r.parsedType}),gt;if(i.exactLength!==null){let o=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(o||a)&&(Be(r,{code:o?Ie.too_big:Ie.too_small,minimum:a?i.exactLength.value:void 0,maximum:o?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(Be(r,{code:Ie.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(Be(r,{code:Ie.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((o,a)=>i.type._parseAsync(new bo(r,o,r.path,a)))).then(o=>gi.mergeArray(n,o));let s=[...r.data].map((o,a)=>i.type._parseSync(new bo(r,o,r.path,a)));return gi.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:tt.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:tt.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:tt.toString(r)}})}nonempty(e){return this.min(1,e)}};fc.create=(t,e)=>new fc({type:t,minLength:null,maxLength:null,exactLength:null,typeName:bt.ZodArray,...jt(e)});function km(t){if(t instanceof ms){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=vo.create(km(n))}return new ms({...t._def,shape:()=>e})}else return t instanceof fc?new fc({...t._def,type:km(t.element)}):t instanceof vo?vo.create(km(t.unwrap())):t instanceof ou?ou.create(km(t.unwrap())):t instanceof su?su.create(t.items.map(e=>km(e))):t}var ms=class t extends zt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=nr.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==He.object){let c=this._getOrReturnCtx(e);return Be(c,{code:Ie.invalid_type,expected:He.object,received:c.parsedType}),gt}let{status:n,ctx:i}=this._processInputParams(e),{shape:s,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof oa&&this._def.unknownKeys==="strip"))for(let c in i.data)o.includes(c)||a.push(c);let u=[];for(let c of o){let l=s[c],f=i.data[c];u.push({key:{status:"valid",value:c},value:l._parse(new bo(i,f,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof oa){let c=this._def.unknownKeys;if(c==="passthrough")for(let l of a)u.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(c==="strict")a.length>0&&(Be(i,{code:Ie.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let l of a){let f=i.data[l];u.push({key:{status:"valid",value:l},value:c._parse(new bo(i,f,i.path,l)),alwaysSet:l in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let c=[];for(let l of u){let f=await l.key,d=await l.value;c.push({key:f,value:d,alwaysSet:l.alwaysSet})}return c}).then(c=>gi.mergeObjectSync(n,c)):gi.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return tt.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:tt.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:bt.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of nr.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of nr.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return km(this)}partial(e){let r={};for(let n of nr.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of nr.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof vo;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return pfe(nr.objectKeys(this.shape))}};ms.create=(t,e)=>new ms({shape:()=>t,unknownKeys:"strip",catchall:oa.create(),typeName:bt.ZodObject,...jt(e)});ms.strictCreate=(t,e)=>new ms({shape:()=>t,unknownKeys:"strict",catchall:oa.create(),typeName:bt.ZodObject,...jt(e)});ms.lazycreate=(t,e)=>new ms({shape:t,unknownKeys:"strip",catchall:oa.create(),typeName:bt.ZodObject,...jt(e)});var ch=class extends zt{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let o=s.map(a=>new ps(a.ctx.common.issues));return Be(r,{code:Ie.invalid_union,unionErrors:o}),gt}if(r.common.async)return Promise.all(n.map(async s=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(i);{let s,o=[];for(let u of n){let c={...r,common:{...r.common,issues:[]},parent:null},l=u._parseSync({data:r.data,path:r.path,parent:c});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=o.map(u=>new ps(u));return Be(r,{code:Ie.invalid_union,unionErrors:a}),gt}}get options(){return this._def.options}};ch.create=(t,e)=>new ch({options:t,typeName:bt.ZodUnion,...jt(e)});var cc=t=>t instanceof fh?cc(t.schema):t instanceof xo?cc(t.innerType()):t instanceof dh?[t.value]:t instanceof hh?t.options:t instanceof ph?nr.objectValues(t.enum):t instanceof mh?cc(t._def.innerType):t instanceof ah?[void 0]:t instanceof uh?[null]:t instanceof vo?[void 0,...cc(t.unwrap())]:t instanceof ou?[null,...cc(t.unwrap())]:t instanceof Uv||t instanceof _h?cc(t.unwrap()):t instanceof gh?cc(t._def.innerType):[],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}),gt;let n=this.discriminator,i=r.data[n],s=this.optionsMap.get(i);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(Be(r,{code:Ie.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),gt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let s of r){let o=cc(s.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,s)}}return new t({typeName:bt.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...jt(n)})}};function AM(t,e){let r=iu(t),n=iu(e);if(t===e)return{valid:!0,data:t};if(r===He.object&&n===He.object){let i=nr.objectKeys(e),s=nr.objectKeys(t).filter(a=>i.indexOf(a)!==-1),o={...t,...e};for(let a of s){let u=AM(t[a],e[a]);if(!u.valid)return{valid:!1};o[a]=u.data}return{valid:!0,data:o}}else if(r===He.array&&n===He.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let s=0;s<t.length;s++){let o=t[s],a=e[s],u=AM(o,a);if(!u.valid)return{valid:!1};i.push(u.data)}return{valid:!0,data:i}}else return r===He.date&&n===He.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var lh=class extends zt{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(s,o)=>{if(zA(s)||zA(o))return gt;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}),gt)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,o])=>i(s,o)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};lh.create=(t,e,r)=>new lh({left:t,right:e,typeName:bt.ZodIntersection,...jt(r)});var su=class t extends zt{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==He.array)return Be(n,{code:Ie.invalid_type,expected:He.array,received:n.parsedType}),gt;if(n.data.length<this._def.items.length)return Be(n,{code:Ie.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),gt;!this._def.rest&&n.data.length>this._def.items.length&&(Be(n,{code:Ie.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((o,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new bo(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(s).then(o=>gi.mergeArray(r,o)):gi.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};su.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new su({items:t,typeName:bt.ZodTuple,rest:null,...jt(e)})};var 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}),gt;let i=[],s=this._def.keyType,o=this._def.valueType;for(let a in n.data)i.push({key:s._parse(new bo(n,a,n.path,a)),value:o._parse(new bo(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?gi.mergeObjectAsync(r,i):gi.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof zt?new t({keyType:e,valueType:r,typeName:bt.ZodRecord,...jt(n)}):new t({keyType:hf.create(),valueType:e,typeName:bt.ZodRecord,...jt(r)})}},Rm=class extends zt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==He.map)return Be(n,{code:Ie.invalid_type,expected:He.map,received:n.parsedType}),gt;let i=this._def.keyType,s=this._def.valueType,o=[...n.data.entries()].map(([a,u],c)=>({key:i._parse(new bo(n,a,n.path,[c,"key"])),value:s._parse(new bo(n,u,n.path,[c,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let u of o){let c=await u.key,l=await u.value;if(c.status==="aborted"||l.status==="aborted")return gt;(c.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(c.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let u of o){let c=u.key,l=u.value;if(c.status==="aborted"||l.status==="aborted")return gt;(c.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(c.value,l.value)}return{status:r.value,value:a}}}};Rm.create=(t,e,r)=>new Rm({valueType:e,keyType:t,typeName:bt.ZodMap,...jt(r)});var Pm=class t extends zt{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==He.set)return Be(n,{code:Ie.invalid_type,expected:He.set,received:n.parsedType}),gt;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(Be(n,{code:Ie.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(Be(n,{code:Ie.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let s=this._def.valueType;function o(u){let c=new Set;for(let l of u){if(l.status==="aborted")return gt;l.status==="dirty"&&r.dirty(),c.add(l.value)}return{status:r.value,value:c}}let a=[...n.data.values()].map((u,c)=>s._parse(new bo(n,u,n.path,c)));return n.common.async?Promise.all(a).then(u=>o(u)):o(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:tt.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:tt.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Pm.create=(t,e)=>new Pm({valueType:t,minSize:null,maxSize:null,typeName:bt.ZodSet,...jt(e)});var 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}),gt;function n(a,u){return qv({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Im(),uc].filter(c=>!!c),issueData:{code:Ie.invalid_arguments,argumentsError:u}})}function i(a,u){return qv({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Im(),uc].filter(c=>!!c),issueData:{code:Ie.invalid_return_type,returnTypeError:u}})}let s={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof mf){let a=this;return ki(async function(...u){let c=new ps([]),l=await a._def.args.parseAsync(u,s).catch(p=>{throw c.addIssue(n(u,p)),c}),f=await Reflect.apply(o,this,l);return await a._def.returns._def.type.parseAsync(f,s).catch(p=>{throw c.addIssue(i(f,p)),c})})}else{let a=this;return ki(function(...u){let c=a._def.args.safeParse(u,s);if(!c.success)throw new ps([n(u,c.error)]);let l=Reflect.apply(o,this,c.data),f=a._def.returns.safeParse(l,s);if(!f.success)throw new ps([i(l,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:su.create(e).rest(lc.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||su.create([]).rest(lc.create()),returns:r||lc.create(),typeName:bt.ZodFunction,...jt(n)})}},fh=class extends zt{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};fh.create=(t,e)=>new fh({getter:t,typeName:bt.ZodLazy,...jt(e)});var dh=class extends zt{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return Be(r,{received:r.data,code:Ie.invalid_literal,expected:this._def.value}),gt}return{status:"valid",value:e.data}}get value(){return this._def.value}};dh.create=(t,e)=>new dh({value:t,typeName:bt.ZodLiteral,...jt(e)});function pfe(t,e){return new hh({values:t,typeName:bt.ZodEnum,...jt(e)})}var hh=class t extends zt{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return Be(r,{expected:nr.joinValues(n),received:r.parsedType,code:Ie.invalid_type}),gt}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return Be(r,{received:r.data,code:Ie.invalid_enum_value,options:n}),gt}return ki(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};hh.create=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}),gt}if(this._cache||(this._cache=new Set(nr.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=nr.objectValues(r);return Be(n,{received:n.data,code:Ie.invalid_enum_value,options:i}),gt}return ki(e.data)}get enum(){return this._def.values}};ph.create=(t,e)=>new ph({values:t,typeName:bt.ZodNativeEnum,...jt(e)});var mf=class extends zt{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==He.promise&&r.common.async===!1)return Be(r,{code:Ie.invalid_type,expected:He.promise,received:r.parsedType}),gt;let n=r.parsedType===He.promise?r.data:Promise.resolve(r.data);return ki(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};mf.create=(t,e)=>new mf({type:t,typeName:bt.ZodPromise,...jt(e)});var xo=class extends zt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===bt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,s={addIssue:o=>{Be(n,o),o.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let o=i.transform(n.data,s);if(n.common.async)return Promise.resolve(o).then(async a=>{if(r.value==="aborted")return gt;let u=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return u.status==="aborted"?gt:u.status==="dirty"?rh(u.value):r.value==="dirty"?rh(u.value):u});{if(r.value==="aborted")return gt;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?gt:a.status==="dirty"?rh(a.value):r.value==="dirty"?rh(a.value):a}}if(i.type==="refinement"){let o=a=>{let u=i.refinement(a,s);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?gt:(a.status==="dirty"&&r.dirty(),o(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?gt:(a.status==="dirty"&&r.dirty(),o(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!df(o))return gt;let a=i.transform(o.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>df(o)?Promise.resolve(i.transform(o.value,s)).then(a=>({status:r.value,value:a})):gt);nr.assertNever(i)}};xo.create=(t,e,r)=>new xo({schema:t,typeName:bt.ZodEffects,effect:e,...jt(r)});xo.createWithPreprocess=(t,e,r)=>new xo({schema:e,effect:{type:"preprocess",transform:t},typeName:bt.ZodEffects,...jt(r)});var vo=class extends zt{_parse(e){return this._getType(e)===He.undefined?ki(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};vo.create=(t,e)=>new vo({innerType:t,typeName:bt.ZodOptional,...jt(e)});var ou=class extends zt{_parse(e){return this._getType(e)===He.null?ki(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ou.create=(t,e)=>new ou({innerType:t,typeName:bt.ZodNullable,...jt(e)});var mh=class extends zt{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===He.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};mh.create=(t,e)=>new mh({innerType:t,typeName:bt.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...jt(e)});var gh=class extends zt{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Tm(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ps(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ps(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};gh.create=(t,e)=>new gh({innerType:t,typeName:bt.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...jt(e)});var Nm=class extends zt{_parse(e){if(this._getType(e)!==He.nan){let n=this._getOrReturnCtx(e);return Be(n,{code:Ie.invalid_type,expected:He.nan,received:n.parsedType}),gt}return{status:"valid",value:e.data}}};Nm.create=t=>new Nm({typeName:bt.ZodNaN,...jt(t)});var hZe=Symbol("zod_brand"),Uv=class extends zt{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},jv=class t extends zt{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?gt:s.status==="dirty"?(r.dirty(),rh(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?gt:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:bt.ZodPipeline})}},_h=class extends zt{_parse(e){let r=this._def.innerType._parse(e),n=i=>(df(i)&&(i.value=Object.freeze(i.value)),i);return Tm(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};_h.create=(t,e)=>new _h({innerType:t,typeName:bt.ZodReadonly,...jt(e)});function 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 pZe={object:ms.lazycreate},bt;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(bt||(bt={}));var mZe=(t,e={message:`Input not instance of ${t.name}`})=>mfe(r=>r instanceof t,e),gfe=hf.create,_fe=nh.create,gZe=Nm.create,_Ze=ih.create,yfe=sh.create,yZe=oh.create,vZe=Om.create,bZe=ah.create,xZe=uh.create,EZe=pf.create,wZe=lc.create,SZe=oa.create,DZe=Fm.create,CZe=fc.create,AZe=ms.create,IZe=ms.strictCreate,TZe=ch.create,kZe=YA.create,OZe=lh.create,FZe=su.create,RZe=QA.create,PZe=Rm.create,NZe=Pm.create,BZe=KA.create,MZe=fh.create,LZe=dh.create,qZe=hh.create,UZe=ph.create,jZe=mf.create,$Ze=xo.create,HZe=vo.create,WZe=ou.create,VZe=xo.createWithPreprocess,zZe=jv.create,GZe=()=>gfe().optional(),YZe=()=>_fe().optional(),QZe=()=>yfe().optional(),KZe={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 JZe=gt;var dc={authenticate:"authenticate",initialize:"initialize",session_cancel:"session/cancel",session_load:"session/load",session_new:"session/new",session_prompt:"session/prompt",session_set_mode:"session/set_mode",session_set_model:"session/set_model"},au={fs_read_text_file:"fs/read_text_file",fs_write_text_file:"fs/write_text_file",session_request_permission:"session/request_permission",session_update:"session/update",terminal_create:"terminal/create",terminal_kill:"terminal/kill",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit"},bfe=1,XZe=x.null(),ZZe=x.number(),eet=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()}),tet=x.record(x.unknown()),ret=x.union([x.literal("assistant"),x.literal("user")]),net=x.object({_meta:x.record(x.unknown()).optional(),mimeType:x.string().optional().nullable(),text:x.string(),uri:x.string()}),iet=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()}),set=x.object({_meta:x.record(x.unknown()).optional()}),oet=x.object({_meta:x.unknown().optional()}),aet=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")])}),uet=x.object({_meta:x.record(x.unknown()).optional()}),cet=x.record(x.unknown()),fet=x.string(),det=x.record(x.unknown()),het=x.object({hint:x.string()}),pet=x.null(),met=x.number(),get=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()}),_et=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(ret).optional().nullable(),lastModified:x.string().optional().nullable(),priority:x.number().optional().nullable()}),$v=x.union([net,iet]),yet=x.object({_meta:x.record(x.unknown()).optional()}),vet=x.object({_meta:x.record(x.unknown()).optional(),content:x.string()}),bet=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")})])}),xet=x.object({_meta:x.record(x.unknown()).optional(),terminalId:x.string()}),Eet=x.object({_meta:x.record(x.unknown()).optional()}),wet=x.object({_meta:x.record(x.unknown()).optional(),exitCode:x.number().optional().nullable(),signal:x.string().optional().nullable()}),Det=x.object({_meta:x.record(x.unknown()).optional()}),Cet=x.record(x.unknown()),Afe=x.object({_meta:x.record(x.unknown()).optional(),sessionId:x.string()}),Aet=x.record(x.unknown()),Iet=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()}),Tet=x.object({_meta:x.record(x.unknown()).optional(),description:x.string().optional().nullable(),id:x.string(),name:x.string()}),ket=x.object({_meta:x.record(x.unknown()).optional(),http:x.boolean().optional(),sse:x.boolean().optional()}),Oet=x.object({_meta:x.record(x.unknown()).optional(),audio:x.boolean().optional(),embeddedContext:x.boolean().optional(),image:x.boolean().optional()}),Fet=x.object({_meta:x.record(x.unknown()).optional(),description:x.string().optional().nullable(),modelId:x.string(),name:x.string()}),Ret=x.object({_meta:x.record(x.unknown()).optional(),description:x.string().optional().nullable(),id:fet,name:x.string()}),kfe=x.object({_meta:x.record(x.unknown()).optional(),availableModels:x.array(Fet),currentModelId:x.string()}),Ofe=x.object({_meta:x.record(x.unknown()).optional(),availableModes:x.array(Ret),currentModeId:x.string()}),Pet=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")])}),Net=het,Bet=x.object({_meta:x.record(x.unknown()).optional(),readTextFile:x.boolean().optional(),writeTextFile:x.boolean().optional()}),Met=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()}),Met]),Let=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")})]),qet=x.object({_meta:x.record(x.unknown()).optional(),exitCode:x.number().optional().nullable(),signal:x.string().optional().nullable()}),Uet=x.union([Afe,Aet]),BM=x.object({_meta:x.record(x.unknown()).optional(),options:x.array(Iet),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()}),jet=x.object({_meta:x.record(x.unknown()).optional(),models:kfe.optional().nullable(),modes:Ofe.optional().nullable(),sessionId:x.string()}),$et=x.object({_meta:x.record(x.unknown()).optional(),models:kfe.optional().nullable(),modes:Ofe.optional().nullable()}),Het=x.object({method:x.string(),params:Uet.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(Let),sessionId:x.string()}),Wet=x.object({_meta:x.record(x.unknown()).optional(),exitStatus:qet.optional().nullable(),output:x.string(),truncated:x.boolean()}),Vet=x.union([kM,OM,BM,MM,FM,RM,PM,NM,tet]),zet=x.object({_meta:x.record(x.unknown()).optional(),loadSession:x.boolean().optional(),mcpCapabilities:ket.optional(),promptCapabilities:Oet.optional()}),Get=x.object({_meta:x.record(x.unknown()).optional(),description:x.string(),input:Net.optional().nullable(),name:x.string()}),Yet=x.object({_meta:x.record(x.unknown()).optional(),fs:Bet.optional(),terminal:x.boolean().optional()}),Qet=x.object({id:x.union([XZe,ZZe,eet]),method:x.string(),params:Vet.optional().nullable()}),Ket=x.object({_meta:x.record(x.unknown()).optional(),agentCapabilities:zet.optional(),agentInfo:Tfe.optional().nullable(),authMethods:x.array(Tet).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(Pet),sessionUpdate:x.literal("plan")}),x.object({_meta:x.record(x.unknown()).optional(),availableCommands:x.array(Get),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:Yet.optional(),clientInfo:Tfe.optional().nullable(),protocolVersion:x.number()}),Jet=x.union([yet,vet,bet,xet,Wet,Eet,wet,Det,Cet]),Xet=x.union([LM,det]),Zet=x.union([Bfe,Sfe,Rfe,Pfe,Dfe,Nfe,Cfe,_et]),ett=x.object({method:x.string(),params:Xet.optional().nullable()}),ttt=x.union([Ket,set,jet,$et,oet,aet,uet,cet]),rtt=x.object({id:x.union([pet,met,get]),method:x.string(),params:Zet.optional().nullable()}),ntt=x.union([x.object({result:Jet}),x.object({error:wfe})]),itt=x.union([rtt,ntt,Het]),stt=x.union([x.object({result:ttt}),x.object({error:wfe})]),ott=x.union([Qet,stt,ett]),gSt=x.union([ott,itt]);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)+`
|
|
195
195
|
`,u=t.getWriter();try{await u.write(r.encode(a))}finally{u.releaseLock()}}});return{readable:i,writable:s}}var XA=class{#e;constructor(e,r){let n=e(this),i=async(o,a)=>{switch(o){case au.fs_write_text_file:{let u=kM.parse(a);return n.writeTextFile?.(u)}case au.fs_read_text_file:{let u=OM.parse(a);return n.readTextFile?.(u)}case au.session_request_permission:{let u=BM.parse(a);return n.requestPermission(u)}case au.terminal_create:{let u=MM.parse(a);return n.createTerminal?.(u)}case au.terminal_output:{let u=FM.parse(a);return n.terminalOutput?.(u)}case au.terminal_release:{let u=RM.parse(a);return await n.releaseTerminal?.(u)??{}}case au.terminal_wait_for_exit:{let u=PM.parse(a);return n.waitForTerminalExit?.(u)}case au.terminal_kill:{let u=NM.parse(a);return await n.killTerminal?.(u)??{}}default:if(o.startsWith("_")){let u=o.substring(1);if(!n.extMethod)throw Ns.methodNotFound(o);return n.extMethod(u,a)}throw Ns.methodNotFound(o)}},s=async(o,a)=>{switch(o){case au.session_update:{let u=LM.parse(a);return n.sessionUpdate(u)}default:if(o.startsWith("_")){let u=o.substring(1);return n.extNotification?n.extNotification(u,a):void 0}throw Ns.methodNotFound(o)}};this.#e=new qM(i,s,r)}async initialize(e){return await this.#e.sendRequest(dc.initialize,e)}async newSession(e){return await this.#e.sendRequest(dc.session_new,e)}async loadSession(e){return await this.#e.sendRequest(dc.session_load,e)??{}}async setSessionMode(e){return await this.#e.sendRequest(dc.session_set_mode,e)??{}}async setSessionModel(e){return await this.#e.sendRequest(dc.session_set_model,e)??{}}async authenticate(e){return await this.#e.sendRequest(dc.authenticate,e)??{}}async prompt(e){return await this.#e.sendRequest(dc.session_prompt,e)}async cancel(e){return await this.#e.sendNotification(dc.session_cancel,e)}async extMethod(e,r){return await this.#e.sendRequest(`_${e}`,r)}async extNotification(e,r){return await this.#e.sendNotification(`_${e}`,r)}get signal(){return this.#e.signal}get closed(){return this.#e.closed}},qM=class{#e=new Map;#n=0;#t;#o;#a;#r=Promise.resolve();#s=new AbortController;#i;constructor(e,r,n){this.#t=e,this.#o=r,this.#a=n,this.#i=new Promise(i=>{this.#s.signal.addEventListener("abort",()=>i())}),this.#f()}get signal(){return this.#s.signal}get closed(){return this.#i}async#f(){let e=this.#a.readable.getReader();try{for(;;){let{value:r,done:n}=await e.read();if(n)break;if(r)try{this.#m(r)}catch(i){console.error("Unexpected error during message processing:",r,i),"id"in r&&r.id!==void 0&&this.#d({jsonrpc:"2.0",id:r.id,error:{code:-32700,message:"Parse error"}})}}}finally{e.releaseLock(),this.#s.abort()}}async#m(e){if("method"in e&&"id"in e){let r=await this.#u(e.method,e.params);"error"in r&&console.error("Error handling request",e,r.error),await this.#d({jsonrpc:"2.0",id:e.id,...r})}else if("method"in e){let r=await this.#c(e.method,e.params);"error"in r&&console.error("Error handling notification",e,r.error)}else"id"in e?this.#l(e):console.error("Invalid message",{message:e})}async#u(e,r){try{return{result:await this.#t(e,r)??null}}catch(n){if(n instanceof Ns)return n.toResult();if(n instanceof x.ZodError)return Ns.invalidParams(n.format()).toResult();let i;(n instanceof Error||typeof n=="object"&&n!=null&&"message"in n&&typeof n.message=="string")&&(i=n.message);try{return Ns.internalError(i?JSON.parse(i):{}).toResult()}catch{return Ns.internalError({details:i}).toResult()}}}async#c(e,r){try{return await this.#o(e,r),{result:null}}catch(n){if(n instanceof Ns)return n.toResult();if(n instanceof x.ZodError)return Ns.invalidParams(n.format()).toResult();let i;(n instanceof Error||typeof n=="object"&&n!=null&&"message"in n&&typeof n.message=="string")&&(i=n.message);try{return Ns.internalError(i?JSON.parse(i):{}).toResult()}catch{return Ns.internalError({details:i}).toResult()}}}#l(e){let r=this.#e.get(e.id);r?("result"in e?r.resolve(e.result):"error"in e&&r.reject(e.error),this.#e.delete(e.id)):console.error("Got response to unknown request",e.id)}async sendRequest(e,r){let n=this.#n++,i=new Promise((s,o)=>{this.#e.set(n,{resolve:s,reject:o})});return await this.#d({jsonrpc:"2.0",id:n,method:e,params:r}),i}async sendNotification(e,r){await this.#d({jsonrpc:"2.0",method:e,params:r})}async#d(e){return this.#r=this.#r.then(async()=>{let r=this.#a.writable.getWriter();try{await r.write(e)}finally{r.releaseLock()}}).catch(r=>{console.error("ACP write error:",r)}),this.#r}},Ns=class t extends Error{code;data;constructor(e,r,n){super(r),this.code=e,this.name="RequestError",this.data=n}static parseError(e,r){return new t(-32700,`Parse error${r?`: ${r}`:""}`,e)}static invalidRequest(e,r){return new t(-32600,`Invalid request${r?`: ${r}`:""}`,e)}static methodNotFound(e){return new t(-32601,`"Method not found": ${e}`,{method:e})}static invalidParams(e,r){return new t(-32602,`Invalid params${r?`: ${r}`:""}`,e)}static internalError(e,r){return new t(-32603,`Internal error${r?`: ${r}`:""}`,e)}static authRequired(e,r){return new t(-32e3,`Authentication required${r?`: ${r}`:""}`,e)}static resourceNotFound(e){return new t(-32002,`Resource not found${e?`: ${e}`:""}`,e&&{uri:e})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}};var Mfe=require("crypto");var Bm=class{constructor(e){this.options=e;this.logger=e.logger,this.terminalManager=e.terminalManager,this.sandbox=e.sandbox}connection=null;logger;sandbox;terminalManager;acpSessionId=null;async requestPermission(e){if(this.sandbox)return{outcome:{outcome:"selected",optionId:(e.options.find(i=>i.kind==="allow_once"||i.kind==="allow_always"||!i.kind&&i.name.toLowerCase().includes("allow"))||e.options[0]).optionId}};this.ensureSessionMatch(e.sessionId);let r=(0,Mfe.randomUUID)();return this.logger.info(`[${this.options.sessionId}] Requesting permission for tool call ${e.toolCall.toolCallId}`),this.options.onRequestPermission(r,e)}async sessionUpdate(e){this.logger.debug(`ACP Session ${this.options.sessionId} update:`,e),this.options.onUpdateMessage(e)}async writeTextFile(e){throw new Error("Method not implemented.")}async readTextFile(e){throw new Error("Method not implemented.")}async createTerminal(e){this.ensureSessionMatch(e.sessionId);let r=e.env?.reduce((i,s)=>(i[s.name]=s.value,i),{})??void 0;return{terminalId:await this.terminalManager.createTerminal(e.sessionId,e.command,e.args??[],e.cwd??void 0,r,e.outputByteLimit??void 0)}}async terminalOutput(e){this.ensureSessionMatch(e.sessionId);let r=await this.terminalManager.terminalOutput(e.sessionId,e.terminalId);return{output:r.output,truncated:r.truncated,exitStatus:r.exitStatus??void 0}}async releaseTerminal(e){return this.ensureSessionMatch(e.sessionId),await this.terminalManager.releaseTerminal(e.sessionId,e.terminalId),{}}async waitForTerminalExit(e){return this.ensureSessionMatch(e.sessionId),await this.terminalManager.waitForTerminalExit(e.sessionId,e.terminalId)}async killTerminal(e){return this.ensureSessionMatch(e.sessionId),await this.terminalManager.killTerminal(e.sessionId,e.terminalId),{}}async extMethod(e,r){throw new Error("Method not implemented.")}async extNotification(e,r){throw new Error("Method not implemented.")}async startSession(e,r){let n=new XA(()=>this,e);this.connection=n,this.logger.info("Starting ACP Client...");let i=await n.initialize({protocolVersion:bfe,clientCapabilities:{terminal:!0}});this.logger.debug("ACP Client initialized:",i);let s=await n.newSession({cwd:r,mcpServers:[]});return this.logger.debug(`ACP Session started: ${s.sessionId}`),this.acpSessionId=s.sessionId,this.logger.debug(`ACP Session mode set to agent: ${s.sessionId}`),{sessionId:s.sessionId}}ensureSessionMatch(e){if(!this.acpSessionId)throw new Error("ACP session has not been initialized yet.");if(e!==this.acpSessionId)throw new Error(`Mismatched ACP session. Expected ${this.acpSessionId} but got ${e}`)}};var Lfe=require("child_process"),qfe=require("crypto"),UM=require("stream"),ctt=1024*1024,ZA=class{terminals=new Map;logger;sessionLabel;getActiveSessionId;defaultOutputByteLimit;constructor(e){this.logger=e.logger,this.sessionLabel=e.sessionLabel,this.getActiveSessionId=e.getActiveAcpSessionId,this.defaultOutputByteLimit=e.defaultOutputByteLimit??ctt}async createTerminal(e,r,n,i,s,o){this.ensureValidSession(e);let a=(0,qfe.randomUUID)(),u={id:a,handle:null,output:Buffer.alloc(0),outputByteLimit:o??this.defaultOutputByteLimit,truncated:!1,exitStatus:null,waiters:[]},c={onData:l=>this.appendOutput(u,l),onExit:(l,f)=>this.handleExit(u,l,f),onError:l=>{this.logger.error(`[${this.sessionLabel}] Terminal ${a} error: ${l.message}`)}};return u.handle=await this.startProcess({terminalId:a,command:r,args:n??[],cwd:i,env:s},c),this.terminals.set(a,u),this.logger.debug(`[${this.sessionLabel}] Terminal ${a} started: ${r}`),a}async terminalOutput(e,r){let n=this.getTerminal(e,r);return{output:n.output.toString("utf8"),truncated:n.truncated,exitStatus:n.exitStatus}}async releaseTerminal(e,r){let n=this.getTerminal(e,r);try{await this.killHandle(n)}catch(i){this.logger.warn(`[${this.sessionLabel}] Failed to kill terminal ${r} on release: ${i}`)}n.exitStatus||(n.exitStatus={exitCode:null,signal:"SIGTERM"},this.resolveWaiters(n)),await this.disposeHandle(n),this.terminals.delete(r),this.logger.debug(`[${this.sessionLabel}] Terminal ${r} released`)}async waitForTerminalExit(e,r){let n=this.getTerminal(e,r);return n.exitStatus?n.exitStatus:await new Promise(i=>{n.waiters.push(i)})}async killTerminal(e,r){let n=this.getTerminal(e,r);await this.killHandle(n)}resolveWaiters(e){let r=e.exitStatus??{exitCode:null,signal:null};for(;e.waiters.length;){let n=e.waiters.shift();n&&n(r)}}ensureValidSession(e){let r=this.getActiveSessionId();if(!r)throw new Error("ACP session is not active yet.");if(r!==e)throw new Error(`ACP session mismatch for terminal request: ${e}`)}getTerminal(e,r){this.ensureValidSession(e);let n=this.terminals.get(r);if(!n)throw new Error(`Terminal ${r} not found or already released`);return n}handleExit(e,r,n){this.terminals.has(e.id)&&(e.exitStatus={exitCode:typeof r=="number"?r:null,signal:n??void 0},this.resolveWaiters(e))}appendOutput(e,r){if(e.outputByteLimit===0){r.length&&(e.truncated=!0);return}let n=Buffer.isBuffer(r)?r:Buffer.from(r);e.output=Buffer.concat([e.output,n]),e.output.length>e.outputByteLimit&&(e.truncated=!0,e.output=ltt(e.output,e.outputByteLimit))}},e6=class extends ZA{resolveWorkdir;buildEnv;constructor(e){super(e),this.resolveWorkdir=e.resolveWorkdir,this.buildEnv=e.buildEnv}async startProcess(e,r){let n=this.resolveWorkdir(e.cwd),i=this.buildEnv(e.env),s=Ufe(e.command,e.args),o=(0,Lfe.spawn)("bash",["-lc",s],{cwd:n,env:i,stdio:["ignore","pipe","pipe"]}),a=f=>r.onData(f),u=f=>r.onData(f),c=(f,d)=>r.onExit(f,d),l=f=>r.onError?.(f);return o.stdout?.on("data",a),o.stderr?.on("data",u),o.on("close",c),o.on("error",l),{child:o,dispose:()=>{o.stdout?.off("data",a),o.stderr?.off("data",u),o.off("close",c),o.off("error",l)}}}async killHandle(e){!e.exitStatus&&!e.handle.child.killed&&e.handle.child.kill("SIGTERM")}async disposeHandle(e){e.handle.dispose()}},t6=class extends ZA{getContainer;resolveWorkdir;constructor(e){super(e),this.getContainer=e.getContainer,this.resolveWorkdir=e.resolveWorkdir}async startProcess(e,r){let n=this.getContainer();if(!n)throw new Error("Container is not ready for terminal execution");let i=Ufe(e.command,e.args),s=await n.exec({Cmd:["/bin/bash","-lc",i],WorkingDir:this.resolveWorkdir(e.cwd),AttachStdout:!0,AttachStderr:!0,AttachStdin:!0,Tty:!0,Env:e.env?Object.entries(e.env).map(([m,_])=>`${m}=${_}`):void 0}),o=await s.start({hijack:!0,stdin:!0}),a=new UM.PassThrough,u=new UM.PassThrough,c=m=>r.onData(m),l=m=>r.onData(m),f=m=>r.onError?.(m),d=async()=>{try{let m=await s.inspect();r.onExit(m.ExitCode??0,null)}catch(m){r.onError?.(m),r.onExit(null,null)}};a.on("data",c),u.on("data",l),n.modem.demuxStream(o,a,u),o.on("error",f),o.on("end",d);let p=await dtt(s);return{exec:s,stream:o,stdout:a,stderr:u,pid:p,removeListeners:()=>{a.off("data",c),u.off("data",l),o.off("error",f),o.off("end",d)}}}async killHandle(e){if(!e.exitStatus)try{if(e.handle.pid)try{process.kill(e.handle.pid,"SIGTERM")}catch(r){let n=r;if(n.code!=="ESRCH")throw n}e.handle.stream.destroyed||(e.handle.stream.write(""),e.handle.stream.end())}catch(r){this.logger.warn(`Failed to kill docker terminal: ${r}`)}}async disposeHandle(e){e.handle.removeListeners(),e.handle.stream.destroyed||e.handle.stream.destroy(),e.handle.stdout.destroyed||e.handle.stdout.destroy(),e.handle.stderr.destroyed||e.handle.stderr.destroy()}};function Ufe(t,e){if(!e.length)return t;let r=e.map(n=>`'${n.replace(/'/g,`'"'"'`)}'`).join(" ");return`${t} ${r}`}function ltt(t,e){if(t.length<=e)return t;let r=t.length-e;for(;r<t.length&&ftt(t[r]);)r+=1;return t.slice(r)}function ftt(t){return(t&192)===128}async function dtt(t,e=5,r=100){for(let n=0;n<e;n++){try{let i=await t.inspect();if(i.Pid&&i.Pid>0)return i.Pid}catch{return null}await new Promise(i=>setTimeout(i,r))}return null}var i6=class extends VA{isDocker=!0;docker;container=null;config;status;dockerExec=null;stream=null;healthCheckInterval;logger;lastInputWasAI=!1;sessionId;agentClient=null;acpSessionId=null;terminalManager;env={};constructor(e,r,n){super(),this.docker=e,this.config=r,this.logger=n,this.sessionId=r.sessionId,this.logger.debug("config",{config:r});let i=`lody-${r.sessionId.replaceAll(":","").replaceAll("@","")}-${Date.now()}`;this.status={sessionId:r.sessionId,containerId:"",containerName:i,status:"initializing"},this.terminalManager=new t6({logger:this.logger,sessionLabel:this.sessionId,getActiveAcpSessionId:()=>this.acpSessionId,getContainer:()=>this.container,resolveWorkdir:s=>s??this.getWorkdir()})}getWorkdir(){return D_}async create(){try{this.logger.info(`[${this.config.sessionId}] Creating devcontainer session`),this.status.status="building",await this.ensureDevcontainerImage();let e=await this.buildContainerConfig();this.status.status="starting",this.container=await this.docker.createContainer(e),this.status.containerId=this.container.id,this.logger.info(`[${this.config.sessionId}] Container created: ${this.status.containerName}`),await this.container.start(),this.startHealthCheck(),this.status.status="running",this.emit("created",this.status)}catch(e){throw this.status.status="error",this.status.error=e instanceof Error?e.message:"Unknown error",this.logger.error(`[${this.config.sessionId}] Failed to create container: ${this.status.error}`),this.emit("error",{sessionId:this.config.sessionId,error:e,status:{...this.status}}),e}}async exec(e,r,n,i){let s=this.formatCommand(e,r);return this.lastInputWasAI=i,await this.executeNonInteractiveCommand(s,n,i)}async ensureDevcontainerImage(){await jM({docker:this.docker,logger:this.logger,sessionPrefix:this.config.sessionId})}async buildContainerConfig(){let e={...this.config.env,LODY_SESSION_ID:this.config.sessionId,LODY_MACHINE_SERVER_URL:process.env.LODY_MACHINE_SERVER_URL,TERM:"xterm-256color",COLORTERM:"truecolor"};this.env=e,this.logger.debug(`[${this.config.sessionId}] Container config with env: ${JSON.stringify(e)}`);let r=[],n=Mm.default.join(r6.default.homedir(),".claude"),i=Mm.default.join(r6.default.homedir(),".codex");n6.default.existsSync(n)&&r.push(`${n}:/home/node/.claude:rw`),n6.default.existsSync(i)&&r.push(`${i}:/home/node/.codex:rw`);let s=Mm.default.join(r6.default.homedir(),".claude.json");return n6.default.existsSync(s)&&r.push(`${s}:/home/node/.claude.json:rw`),{name:this.status.containerName,Image:"lody/devcontainer:latest",Hostname:`lody-${this.config.sessionId.substring(0,8)}`,Env:Object.entries(e).map(([o,a])=>`${o}=${a}`),WorkingDir:this.config.workingDir||D_,User:"node",Tty:!0,OpenStdin:!0,StdinOnce:!1,AttachStdin:!0,AttachStdout:!0,AttachStderr:!0,HostConfig:{Init:!0,Binds:r,NetworkMode:"host",RestartPolicy:{Name:"unless-stopped"}},Labels:{"lody.managed":"true","lody.session.id":this.config.sessionId}}}handleOutput(e){e.trim()!==""&&this.emit("output",{sessionId:this.config.sessionId,data:e,timestamp:new Date,stream:"stdout",isFromAI:this.lastInputWasAI})}handleClose(e,r){this.logger.info(`[${this.config.sessionId}] process exited: code=${e}, signal=${r}`),this.status.exitCode=e||1,this.status.status="stopped",this.emit("exited",this.status)}handleError(e){this.logger.info(`[${this.config.sessionId}] docker process error: ${e}`),this.status.exitCode=1,this.status.status="error",this.emit("error",{sessionId:this.sessionId,error:e,status:{...this.status}})}formatCommand(e,r){if(!r.length)return e;let n=r.map(i=>`'${i.replace(/'/g,`'"'"'`)}'`).join(" ");return`${e} ${n}`}async createAgent(e){if(!this.container)throw new Error("Container not available");let n=await(await this.container.exec({Cmd:["/bin/bash","-c",`${e.command} ${e.args?.join(" ")}`],WorkingDir:this.getWorkdir(),Tty:!1,AttachStdin:!0,AttachStdout:!0,AttachStderr:!0,Env:Object.entries(this.env).map(([l,f])=>`${l}=${f}`)})).start({hijack:!0,stdin:!0}),i=new WritableStream({write:l=>{n.write(l)},close:()=>{n.end()}}),s=this.container,o=new ReadableStream({start(l){let f=new jfe.Writable({write(d,p,m){l.enqueue(new Uint8Array(d)),m()}});s.modem.demuxStream(n,f,null),n.on("end",()=>l.close()),n.on("error",d=>l.error(d))}}),a=JA(i,o),u=new Bm({logger:this.logger,sessionId:this.sessionId,terminalManager:this.terminalManager,onUpdateMessage:e.onUpdateMessage,onRequestPermission:e.onRequestPermission,sandbox:!0}),{sessionId:c}=await u.startSession(a,this.getWorkdir());return this.agentClient=u,this.acpSessionId=c,this.logger.debug(`[${this.sessionId}] ACP agent process started.`),c}async executeNonInteractiveCommand(e,r,n,i=!1,s=36e5){if(!this.container)throw new Error("Container not available");this.logger.info(`[${this.config.sessionId}] Executing non-interactive command: ${e}`);try{let a=await(await this.container.exec({Cmd:["/bin/bash","-c",e],WorkingDir:r,Tty:!1,AttachStdin:!1,AttachStdout:!0,AttachStderr:!1,Env:Object.entries(this.env).map(([c,l])=>`${c}=${l}`)})).start({hijack:!0,stdin:!1,Detach:i}),u=new Am;return new Promise((c,l)=>{let f="",d="",p=null;p=setTimeout(()=>{a.destroy(),this.handleClose(null,null),l(new Error(`Command timed out after ${s}ms: ${e}`))},s),a.on("data",m=>{if(m.length>=8){let _=m[0],v=m.slice(8).toString("utf8");_===1?(this.logger.debug(`[${this.config.sessionId}] Command stdout: ${v}`),u.write(v)):_===2&&(d+=v,this.handleError(new Error(d)),l(new Error(`Command failed: ${d}`)))}}),a.on("end",async()=>{p&&clearTimeout(p),n&&this.emit("exited",{sessionId:this.sessionId,exitCode:0,containerId:this.status.containerId,containerName:this.status.containerName,status:"stopped"}),c(f.trim())}),a.on("error",m=>{p&&clearTimeout(p),this.handleError(m),a.destroy(),l(m)}),u.on("data",m=>{let _=JSON.stringify(m);n&&this.handleOutput(_)})})}catch(o){throw this.logger.error(`[${this.config.sessionId}] Failed to create non-interactive exec: ${o}`),this.handleError(o instanceof Error?o:new Error("Unknown error")),o}}startHealthCheck(){this.healthCheckInterval=setInterval(async()=>{try{await this.updateStatus()}catch(e){this.logger.error(`[${this.config.sessionId}] Health check failed: ${e instanceof Error?e.message:"Unknown error"}`)}},3e4)}async updateStatus(){if(this.container)try{let e=await this.container.inspect();e.State.Running?this.status.status="running":(this.status.status="stopped",this.status.exitCode=e.State.ExitCode)}catch(e){this.logger.error(`[${this.config.sessionId}] Failed to update status: ${e instanceof Error?e.message:"Unknown error"}`),this.terminate(!0)}}async getStatus(){return this.container&&await this.updateStatus(),{...this.status}}getConfig(){return{...this.config}}async terminate(e=!1){if(this.logger.info(`[${this.config.sessionId}] Terminating container ${e?"(force)":""}`),this.status.status==="stopping"||this.status.status==="terminated"){this.logger.debug(`[${this.config.sessionId}] Container already ${this.status.status}`);return}try{if(this.logger.info(`[${this.config.sessionId}] Terminating container ${e?"(force)":""}`),this.status.status="stopping",this.healthCheckInterval&&(clearInterval(this.healthCheckInterval),this.healthCheckInterval=void 0),this.dockerExec)try{this.stream&&this.stream.destroy(),await new Promise(r=>setTimeout(r,1e3));try{(await this.dockerExec.inspect()).Running&&await this.container?.kill()}catch(r){this.logger.debug(`Exec inspect failed (likely already terminated): ${r.message}`)}}catch(r){this.logger.warn(`Failed to cleanup exec gracefully: ${r instanceof Error?r.message:"Unknown error"}`)}finally{this.dockerExec=null,this.stream=null}if(this.container){try{e?await this.container.kill():await this.container.stop({t:10})}catch(r){if(r.statusCode===409){this.logger.debug(`[${this.config.sessionId}] Container removal already in progress`);return}if(r.statusCode===304)this.logger.debug(`[${this.config.sessionId}] Container already stopped`);else throw r}await this.container.remove({force:!0}),this.container=null}this.status.status="terminated",this.emit("terminated",this.status)}catch(r){throw this.logger.error(`[${this.config.sessionId}] Failed to terminate container: ${r instanceof Error?r.message:"Unknown error"}`),r}}async cleanup(){await this.terminate(!0)}};async function htt({docker:t,sessionPrefix:e,logger:r,spinner:n}){let i="lody/devcontainer:latest",s=e?`[${e}] `:"";r.info(`${s}Building devcontainer image...`),n&&(n.text="Building development environment image (this may take several minutes)...");let o=Mm.default.join(__dirname,"devcontainer","Dockerfile"),a=await t.buildImage({context:Mm.default.dirname(o),src:["Dockerfile","devcontainer.json"]},{t:i,buildargs:{CLAUDE_CLI_VERSION:"latest"}}),u=0,c=0,l=Date.now();await new Promise((f,d)=>{t.modem.followProgress(a,(p,m)=>{p?d(p):(n&&n.succeed("Development environment image built successfully"),f(m))},p=>{if(p.stream){let m=p.stream.trim();r.info(`${s}Build: ${m}`);let _=m.match(/^Step (\d+)\/(\d+)\s*:\s*(.+)$/);if(_){u=parseInt(_[1]),c=parseInt(_[2]);let w=_[3];n&&(n.text=`Building image: Step ${u}/${c} - ${w}`)}let v=Date.now();if(n&&v-l>3e3){if(c>0){let w=Math.round(u/c*100);n.text=`Building image: ${w}% complete (Step ${u}/${c})`}else n.text="Building development environment image... (this may take several minutes)";l=v}n&&(m.includes("Downloading")||m.includes("Extracting"))&&m.length<100&&(n.text=`Building image: ${m}`)}p.error&&(r.error(`${s}Build error: ${p.error}`),n&&n.fail(`Build failed: ${p.error}`),d(new Error(p.error)))})})}async function jM({docker:t,sessionPrefix:e,logger:r,spinner:n}){let i="lody/devcontainer:latest",s=e?`[${e}] `:"";try{await t.getImage(i).inspect(),r.info(`${s}Using existing devcontainer image`),n&&(n.text="Development environment ready")}catch(o){r.error(`${s}Failed to get devcontainer image: ${o instanceof Error?o.message:"Unknown error"}`),await htt({docker:t,sessionPrefix:e,logger:r,spinner:n})}}var s6=class extends Cm{isDocker=!0;docker;sessions=new Map;cleanupInterval;pingInterval;constructor(e,r,n,i){super(e,r,n,i),this.docker=new $fe.default,this.startPeriodicCleanup()}async initialize(){await jM({docker:this.docker,logger:this.logger}),this.logger.info("Docker session manager initialized")}async createSessionInner(e){let r={sessionId:e.sessionId,env:{...e.env},workingDir:D_};try{return await this.createOrReuseSession(r)}catch(n){throw this.logger.error(`[${e.sessionId}] Failed to create Docker session: ${n instanceof Error?n.message:"Unknown error"}`),n}}async terminateSession(e,r=!1){let n=this.sessions.get(e);if(!n){this.logger.warn(`Session ${e} not found`);return}await n.terminate(r),this.logger.info(`[${e}] Docker session terminated`)}async cleanupInner(){this.logger.info("Cleaning up all Docker sessions..."),this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=void 0);try{await this.terminateAllSessions(!0),await this.cleanupOrphanedContainers()}catch(e){this.logger.error(`Failed to cleanup Docker sessions: ${e instanceof Error?e.message:"Unknown error"}`)}}hasSession(e){return this.sessions.has(e)}getSession(e){return this.sessions.get(e)||null}async createOrReuseSession(e){let r=this.sessions.get(e.sessionId);if(r){let i=await r.getStatus();if(i.status==="running"||i.status==="starting")return this.logger.info(`[${e.sessionId}] Reusing existing container session`),this.startPingInterval(),r;this.logger.warn(`[${e.sessionId}] Session exists but not running, terminating`),await this.terminateSession(e.sessionId,!0)}this.logger.debug(`[${e.sessionId}] Creating new devcontainer session config: ${JSON.stringify(e)}`);let n=new i6(this.docker,e,this.logger);this.registerSessionEvents(n),this.sessions.set(e.sessionId,n),this.startPingInterval();try{return await n.create(),this.logger.info(`[${e.sessionId}] Devcontainer session created successfully`),n}catch(i){throw this.sessions.delete(e.sessionId),this.tryStopPingInterval(),i}}registerSessionEvents(e){let r=e.getConfig().sessionId;e.on("output",n=>{let i={sessionId:n.sessionId,data:n.data,timestamp:n.timestamp};this.emit("output",i)}),e.on("error",n=>{let i=n.error instanceof Error?n.error:new Error(typeof n.error=="string"?n.error:"Unknown error"),s={sessionId:n.sessionId??r,error:i};this.emit("error",s)}),e.on("exited",n=>{let i={sessionId:n.sessionId,exitCode:n.exitCode||0};this.emit("exit",i)}),e.on("terminated",n=>{this.sessions.delete(r);let i={sessionId:n.sessionId,exitCode:n.exitCode,status:n};this.emit("terminated",i),this.tryStopPingInterval()})}async terminateAllSessions(e=!1){let r=Array.from(this.sessions.values()).map(n=>n.terminate(e).catch(i=>this.logger.error(`Failed to terminate session: ${i instanceof Error?i.message:"Unknown error"}`)));await Promise.allSettled(r),this.sessions.clear(),this.tryStopPingInterval()}async getAllSessionsStatus(){let e=[];for(let r of this.sessions.values())try{let n=await r.getStatus();e.push(n)}catch(n){this.logger.error(`Failed to get status for session: ${n instanceof Error?n.message:"Unknown error"}`)}return e}async cleanupOrphanedContainers(){try{let e=await this.docker.listContainers({all:!0,filters:{label:["lody.managed=true"]}}),r=new Set(this.sessions.keys());for(let n of e){let i=n.Labels["lody.session.id"];if(!i||!r.has(i))try{let s=this.docker.getContainer(n.Id);await s.stop(),await s.remove({force:!0}),this.logger.info(`Cleaned up orphaned container: ${n.Names[0]}`)}catch(s){this.logger.warn(`Failed to cleanup container: ${s instanceof Error?s.message:"Unknown error"}`)}}}catch(e){this.logger.error(`Failed to cleanup orphaned containers: ${e instanceof Error?e.message:"Unknown error"}`)}}startPeriodicCleanup(){this.cleanupInterval=setInterval(async()=>{try{await this.cleanupOrphanedContainers()}catch(e){this.logger.error(`Periodic cleanup failed: ${e instanceof Error?e.message:"Unknown error"}`)}},60*60*1e3)}startPingInterval(){this.sessions.size===0||this.pingInterval||(this.pingInterval=setInterval(()=>{this.emit("ping")},5e3))}tryStopPingInterval(){this.pingInterval&&this.sessions.size===0&&(clearInterval(this.pingInterval),this.pingInterval=void 0)}};var $M=require("child_process");var Hfe=qe(require("path"));var a6=qe(require("fs"));var o6=class extends VA{constructor(r,n,i){super();this.pwd=n;this.config=r,this.logger=i,this.sessionId=r.sessionId,this.terminalManager=new e6({logger:this.logger,sessionLabel:this.sessionId,getActiveAcpSessionId:()=>this.acpSessionId,resolveWorkdir:s=>s??this.getWorkdir(),buildEnv:s=>this.buildShellEnv(s)})}sessionId;isDocker=!1;config;logger;status="created";activeProcess=null;agentProcess=null;agentClient=null;acpSessionId=null;terminalManager;getWorkdir(){let r=Hfe.default.join(this.pwd,"LODY_WORKDIR",this.sessionId);return a6.existsSync(r)||a6.mkdirSync(r,{recursive:!0}),r}async exec(r,n,i,s){if(this.status==="failed"||this.status==="terminated")throw new Error(`Session ${this.sessionId} is not running`);let o=this.formatCommand(r,n);return await this.runCommand(o,i,s)}async terminate(r=!1){this.logger.info(`[${this.sessionId}] Terminating session${r?" (force)":""}`);let n=o=>{o&&!o.killed&&o.kill(r?"SIGKILL":"SIGTERM")},i=this.activeProcess;n(i),n(this.agentProcess),this.status="terminated";let s={sessionId:this.sessionId,exitCode:i?.exitCode??0};this.emit("terminated",s)}handleParserData=r=>{let n=JSON.stringify(r);this.emitOutput(n)};handleParserError=r=>{let n=r instanceof Error?r.message:String(r);this.logger.error(`[${this.sessionId}] Parser error: ${n}`)};formatCommand(r,n){if(!n.length)return r;let i=n.map(s=>`'${s.replace(/'/g,`'"'"'`)}'`).join(" ");return`${r} ${i}`}buildShellEnv(r){return{...process.env,...this.config.env,...r,FORCE_COLOR:"1",TERM:"xterm-256color",PS1:"",PROMPT_COMMAND:"",LODY_SESSION_ID:this.sessionId}}async createAgent(r){let n=this.buildShellEnv();console.log(`[${this.sessionId}] Starting ACP agent process...`,this.getWorkdir());let i=(0,$M.spawn)(r.command,r.args,{cwd:this.getWorkdir(),env:n,stdio:["pipe","pipe","pipe"]});this.agentProcess=i,i.on("error",l=>{this.logger.error(`[${this.sessionId}] Agent process error: ${l.message}`)}),i.once("exit",(l,f)=>{this.logger.debug(`[${this.sessionId}] ACP agent process exited with code ${l} signal ${f}`),this.agentProcess=null});let s=new WritableStream({write(l){i.stdin.write(l)},close(){i.stdin.end()}}),o=new ReadableStream({start(l){i.stdout.on("data",f=>{l.enqueue(f)}),i.stdout.on("end",()=>{l.close()})}}),a=JA(s,o),u=new Bm({logger:this.logger,sessionId:this.sessionId,terminalManager:this.terminalManager,onUpdateMessage:r.onUpdateMessage,onRequestPermission:r.onRequestPermission,sandbox:!0}),{sessionId:c}=await u.startSession(a,this.getWorkdir());return this.acpSessionId=c,this.agentClient=u,this.logger.debug(`[${this.sessionId}] ACP agent process started.`),c}runCommand(r,n,i){let s=this.buildShellEnv();return this.logger.info(`[${this.sessionId}] Executing command: ${r}`),new Promise((o,a)=>{let u=(0,$M.spawn)("bash",["-lc",r],{cwd:n,env:s,stdio:["ignore","pipe","pipe"]});this.logger.debug(`[${this.sessionId}] Spawned process PID: ${u.pid} with command: bash -lc ${r}`),this.activeProcess=u;let c="",l="",f=i?new Am:null;f&&(f.on("data",this.handleParserData),f.on("error",this.handleParserError)),u.stdout?.on("data",p=>{let m=p.toString();c+=m,f&&f.write(m)}),u.stderr?.on("data",p=>{let m=p.toString();l+=m,this.logger.warn(`[${this.sessionId}] Shell stderr: ${m}`)});let d=()=>{this.activeProcess=null,f&&(f.end(),f.removeListener("data",this.handleParserData),f.removeListener("error",this.handleParserError))};u.on("close",(p,m)=>{d();let _=p??0;!i&&c.trim()&&this.logger.info(`[${this.sessionId}] Command output: ${c.trim()}`),i&&this.emit("exit",{sessionId:this.sessionId,exitCode:_}),o(c.trimEnd())}),u.on("error",p=>{d(),this.emit("error",{sessionId:this.sessionId,error:p}),a(p)})})}emitOutput(r){if(r.trim()==="")return;let n={sessionId:this.sessionId,data:r,timestamp:new Date};this.emit("output",n)}};var u6=class extends Cm{constructor(r,n,i,s,o){super(r,n,i,s);this.pwd=o}isDocker=!1;sessions=new Map;async initialize(){this.logger.debug("Native session manager initialized")}async createSessionInner(r){let n=new o6(r,this.pwd||process.cwd(),this.logger);return this.registerSessionEvents(n),this.sessions.set(r.sessionId,n),n}async terminateSession(r,n=!1){let i=this.sessions.get(r);if(!i){this.logger.warn(`Session ${r} not found`);return}await i.terminate(n),this.logger.info(`[${r}] Native session terminated`)}async cleanupInner(){this.logger.info("Cleaning up all native sessions...");let r=Array.from(this.sessions.values()).map(n=>n.terminate(!0).catch(i=>this.logger.error(`[${n.sessionId}] Failed to terminate session: ${i instanceof Error?i.message:"Unknown error"}`)));await Promise.allSettled(r),this.sessions.clear()}hasSession(r){return this.sessions.has(r)}getSession(r){return this.sessions.get(r)||null}registerSessionEvents(r){r.on("output",n=>{this.emit("output",n)}),r.on("error",n=>{this.emit("error",n)}),r.on("exit",n=>{this.sessions.delete(n.sessionId),this.emit("exit",n)}),r.on("terminated",n=>{this.sessions.delete(n.sessionId);let i={sessionId:n.sessionId,issueId:n.issueId,exitCode:n.exitCode};this.emit("terminated",i)})}};var ptt=5e3,mtt=1/0,Hv=class{constructor(e){this.options=e;this.auth=new Mo(e.logger),this.logger=e.logger;let r=this.auth.getAuthInfo();r||(this.logger.error('Not logged in. Please run "lody login" to log in.'),process.exit(1)),this.userId=r.user.id,this.workspaceId=r.workspace.id,this.token=r.token,this.machineId=r.machine.machineId,this.machineName=r.machine.machineName,this.documentManager=new x2(this.workspaceId,this.token),this.client=new D2({managerOptions:{workspaceId:this.workspaceId,token:this.token,reconnectInterval:ptt,maxReconnectAttempts:mtt,logger:this.logger},sessionManagerFactory:n=>e.docker?new s6(this.logger,this.token,this.machineId,this.documentManager):new u6(this.logger,this.token,this.machineId,this.documentManager,process.cwd()),workspaceDocument:this.documentManager,handlerConfig:{token:this.token,workspaceId:this.workspaceId,userId:this.userId,machineId:this.machineId,machineName:this.machineName,enableDocker:e.docker||!1,cliVersion:G6.version},logger:this.logger})}auth;logger;userId;workspaceId;token;machineId;machineName;client;documentManager;async daemon(){await this.client.initialize(),this.documentManager.ephemeral.registerMachine(this.machineId,{id:this.machineId,name:this.machineName,cliVersion:G6.version,os:process.platform,isDocker:this.options.docker,sessions:[]})}async registerAgent(e){await this.client.initialize();let r=await this.documentManager.getOrCreateWorkspaceDoc(this.workspaceId,this.userId);for(let n of e)await r.hasAgentConfig(n,this.machineId)||await r.createAgentConfig(n,this.machineId)}async startNewAISession(e,r){let{sessionManager:n}=await this.client.initialize(),i=await n.createSession({workspaceId:this.workspaceId,userId:this.userId,machineId:this.machineId,cliType:e,title:r.slice(0,50),env:process.env});return await i.agentClient?.connection?.prompt({prompt:[{type:"text",text:r}],sessionId:i.acpSessionId}),i}async resumeAISession(e){}cleanup=async()=>await this.client.cleanup()},Wv=async(t,e,r)=>{let n=Po({level:r?"debug":"info",transports:"console",console:{colorize:!0,timestamp:!1,format:"simple"}});new Mo(n).getAuthInfo()||(n.warn("You have not logged in, `lody login` first"),process.exit(0)),await(await new Hv({logger:n,docker:!1}).startNewAISession(t,e)).terminate(),process.exit(0)};var c6=new Ms("start").description("Start agent service with or without Docker isolation").option("-f, --foreground","run in foreground (default is background)",!1).option("-d, --docker","Use Docker without prompting").option("--cli-types <types...>","Specify CLI types to register, `claude` or `codex`",(t,e)=>e?e.concat(t):[t]).option("-v, --verbose","verbose output").action(async t=>{let e={transports:"console",console:{colorize:!0,timestamp:!1,format:"simple"}};t.foreground||(e.transports="both",e.file={filename:"logs/start.log"}),t.verbose&&(e.level="debug");let r=Po(e),n=new Mo(r),i,s=n.getAuthInfo();s?(r.info("Found existing authentication, checking validity..."),(await n.validateToken(s.token)).valid?i=s.token:(r.warn("Existing authentication is invalid, please login again"),process.exit(1))):(r.warn("No existing authentication found, please login again"),process.exit(1));try{t.server=process.env.LODY_SERVER_URL||"http://localhost:8787";let o;if(!t.foreground?o=t.docker===!0:t.docker!==void 0?(o=t.docker,r.info(`Docker mode: ${o?"enabled":"disabled"} (via command line)`)):(r.info(it.cyan(`
|